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 |
|---|---|---|---|---|---|---|
osgi/osgi.enroute.examples | osgi.enroute.examples.plugin.application/src/osgi/enroute/examples/plugin/application/OrderApplication.java | // Path: osgi.enroute.examples.plugin.application/src/osgi/enroute/examples/plugin/api/Product.java
// public class Product extends DTO {
// public String supplier;
// public String id;
// public String name;
// public String description;
// public long price;
// public int inStock;
// public int deliveryTimeInDays;
// }
//
// Path: osgi.enroute.examples.plugin.application/src/osgi/enroute/examples/plugin/api/SupplierPlugin.java
// public interface SupplierPlugin {
// Set<Product> findProducts( String query );
// boolean buy( String id);
// String getSupplierId();
// }
| import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import osgi.enroute.configurer.api.RequireConfigurerExtender;
import osgi.enroute.examples.plugin.api.Product;
import osgi.enroute.examples.plugin.api.SupplierPlugin;
import osgi.enroute.google.angular.capabilities.RequireAngularWebResource;
import osgi.enroute.rest.api.REST;
import osgi.enroute.twitter.bootstrap.capabilities.RequireBootstrapWebResource;
import osgi.enroute.webserver.capabilities.RequireWebServerExtender; | package osgi.enroute.examples.plugin.application;
@RequireAngularWebResource(resource = { "angular.js", "angular-resource.js", "angular-route.js" }, priority = 1000)
@RequireBootstrapWebResource(resource = "css/bootstrap.css")
@RequireWebServerExtender
@RequireConfigurerExtender
@Component(name = "osgi.enroute.examples.plugin")
public class OrderApplication implements REST {
@Reference
volatile List<SupplierPlugin> suppliers;
| // Path: osgi.enroute.examples.plugin.application/src/osgi/enroute/examples/plugin/api/Product.java
// public class Product extends DTO {
// public String supplier;
// public String id;
// public String name;
// public String description;
// public long price;
// public int inStock;
// public int deliveryTimeInDays;
// }
//
// Path: osgi.enroute.examples.plugin.application/src/osgi/enroute/examples/plugin/api/SupplierPlugin.java
// public interface SupplierPlugin {
// Set<Product> findProducts( String query );
// boolean buy( String id);
// String getSupplierId();
// }
// Path: osgi.enroute.examples.plugin.application/src/osgi/enroute/examples/plugin/application/OrderApplication.java
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import osgi.enroute.configurer.api.RequireConfigurerExtender;
import osgi.enroute.examples.plugin.api.Product;
import osgi.enroute.examples.plugin.api.SupplierPlugin;
import osgi.enroute.google.angular.capabilities.RequireAngularWebResource;
import osgi.enroute.rest.api.REST;
import osgi.enroute.twitter.bootstrap.capabilities.RequireBootstrapWebResource;
import osgi.enroute.webserver.capabilities.RequireWebServerExtender;
package osgi.enroute.examples.plugin.application;
@RequireAngularWebResource(resource = { "angular.js", "angular-resource.js", "angular-route.js" }, priority = 1000)
@RequireBootstrapWebResource(resource = "css/bootstrap.css")
@RequireWebServerExtender
@RequireConfigurerExtender
@Component(name = "osgi.enroute.examples.plugin")
public class OrderApplication implements REST {
@Reference
volatile List<SupplierPlugin> suppliers;
| public List<Product> getFind(String query) { |
osgi/osgi.enroute.examples | osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/application/BackendApplication.java | // Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/Backend.java
// public interface Backend {
// String TYPE = "type";
//
// /**
// * Save a blob
// *
// * @param name
// * The name of the blob
// * @param data
// * The actual data
// * @return the meta data describing the details of the store
// */
// MetaData save(String name, byte[] data) throws Exception;
//
// /**
// * Read the blob with the given name.
// *
// * @param name
// * The name of the resource
// * @return the data
// */
// byte[] read(String name) throws Exception;
//
// /**
// * Return a list of the meta data of what the store has.
// *
// * @return The list
// */
// Collection<? extends MetaData> list() throws Exception;
//
// /**
// * Delete a blob
// *
// * @param name
// * The name of the blob
// * @return true if deleted, false if could not be deleted (might not exist)
// */
// boolean delete(String name) throws Exception;
// }
| import java.io.FileNotFoundException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import osgi.enroute.configurer.api.RequireConfigurerExtender;
import osgi.enroute.examples.backend.api.Backend;
import osgi.enroute.google.angular.capabilities.RequireAngularWebResource;
import osgi.enroute.stackexchange.pagedown.capabilities.RequirePagedownWebResource;
import osgi.enroute.twitter.bootstrap.capabilities.RequireBootstrapWebResource;
import osgi.enroute.webserver.capabilities.RequireWebServerExtender; | package osgi.enroute.examples.backend.application;
/**
* The Backend Application is the application core. It maintains a lost of
* backends by name and provides access to it.
*
*/
@RequireAngularWebResource(resource = { "angular.js", "angular-route.js",
"angular-resource.js" }, priority = 1000)
@RequirePagedownWebResource(resource = "enmarkdown.js")
@RequireBootstrapWebResource(resource = { "css/bootstrap.css" })
@RequireWebServerExtender
@RequireConfigurerExtender
@Component(name = "osgi.enroute.examples.backends", service = BackendApplication.class)
public class BackendApplication { | // Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/Backend.java
// public interface Backend {
// String TYPE = "type";
//
// /**
// * Save a blob
// *
// * @param name
// * The name of the blob
// * @param data
// * The actual data
// * @return the meta data describing the details of the store
// */
// MetaData save(String name, byte[] data) throws Exception;
//
// /**
// * Read the blob with the given name.
// *
// * @param name
// * The name of the resource
// * @return the data
// */
// byte[] read(String name) throws Exception;
//
// /**
// * Return a list of the meta data of what the store has.
// *
// * @return The list
// */
// Collection<? extends MetaData> list() throws Exception;
//
// /**
// * Delete a blob
// *
// * @param name
// * The name of the blob
// * @return true if deleted, false if could not be deleted (might not exist)
// */
// boolean delete(String name) throws Exception;
// }
// Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/application/BackendApplication.java
import java.io.FileNotFoundException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import osgi.enroute.configurer.api.RequireConfigurerExtender;
import osgi.enroute.examples.backend.api.Backend;
import osgi.enroute.google.angular.capabilities.RequireAngularWebResource;
import osgi.enroute.stackexchange.pagedown.capabilities.RequirePagedownWebResource;
import osgi.enroute.twitter.bootstrap.capabilities.RequireBootstrapWebResource;
import osgi.enroute.webserver.capabilities.RequireWebServerExtender;
package osgi.enroute.examples.backend.application;
/**
* The Backend Application is the application core. It maintains a lost of
* backends by name and provides access to it.
*
*/
@RequireAngularWebResource(resource = { "angular.js", "angular-route.js",
"angular-resource.js" }, priority = 1000)
@RequirePagedownWebResource(resource = "enmarkdown.js")
@RequireBootstrapWebResource(resource = { "css/bootstrap.css" })
@RequireWebServerExtender
@RequireConfigurerExtender
@Component(name = "osgi.enroute.examples.backends", service = BackendApplication.class)
public class BackendApplication { | private ConcurrentMap<String, Backend> backends = new ConcurrentHashMap<>(); |
osgi/osgi.enroute.examples | osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/file/provider/FileBackend.java | // Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/Backend.java
// public interface Backend {
// String TYPE = "type";
//
// /**
// * Save a blob
// *
// * @param name
// * The name of the blob
// * @param data
// * The actual data
// * @return the meta data describing the details of the store
// */
// MetaData save(String name, byte[] data) throws Exception;
//
// /**
// * Read the blob with the given name.
// *
// * @param name
// * The name of the resource
// * @return the data
// */
// byte[] read(String name) throws Exception;
//
// /**
// * Return a list of the meta data of what the store has.
// *
// * @return The list
// */
// Collection<? extends MetaData> list() throws Exception;
//
// /**
// * Delete a blob
// *
// * @param name
// * The name of the blob
// * @return true if deleted, false if could not be deleted (might not exist)
// */
// boolean delete(String name) throws Exception;
// }
//
// Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/MetaData.java
// public class MetaData extends DTO {
// /**
// * The name of the blob
// */
// public String name;
//
// /**
// * The size of the blob
// */
// public long size;
//
// /**
// * The epoch time when it was last modified.
// */
// public long modified;
// }
| import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import osgi.enroute.examples.backend.api.Backend;
import osgi.enroute.examples.backend.api.MetaData; | package osgi.enroute.examples.backend.file.provider;
/**
* Implementation of the {@link Backend} API for a file system
*/
@Component(property = Backend.TYPE + "=file")
public class FileBackend implements Backend {
File root;
@Activate
void activate(BundleContext context) {
root = context.getDataFile("backend-file");
root.mkdirs();
}
/*
* Save a blob
*/
@Override | // Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/Backend.java
// public interface Backend {
// String TYPE = "type";
//
// /**
// * Save a blob
// *
// * @param name
// * The name of the blob
// * @param data
// * The actual data
// * @return the meta data describing the details of the store
// */
// MetaData save(String name, byte[] data) throws Exception;
//
// /**
// * Read the blob with the given name.
// *
// * @param name
// * The name of the resource
// * @return the data
// */
// byte[] read(String name) throws Exception;
//
// /**
// * Return a list of the meta data of what the store has.
// *
// * @return The list
// */
// Collection<? extends MetaData> list() throws Exception;
//
// /**
// * Delete a blob
// *
// * @param name
// * The name of the blob
// * @return true if deleted, false if could not be deleted (might not exist)
// */
// boolean delete(String name) throws Exception;
// }
//
// Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/MetaData.java
// public class MetaData extends DTO {
// /**
// * The name of the blob
// */
// public String name;
//
// /**
// * The size of the blob
// */
// public long size;
//
// /**
// * The epoch time when it was last modified.
// */
// public long modified;
// }
// Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/file/provider/FileBackend.java
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import osgi.enroute.examples.backend.api.Backend;
import osgi.enroute.examples.backend.api.MetaData;
package osgi.enroute.examples.backend.file.provider;
/**
* Implementation of the {@link Backend} API for a file system
*/
@Component(property = Backend.TYPE + "=file")
public class FileBackend implements Backend {
File root;
@Activate
void activate(BundleContext context) {
root = context.getDataFile("backend-file");
root.mkdirs();
}
/*
* Save a blob
*/
@Override | public MetaData save(String name, byte[] data) throws Exception { |
osgi/osgi.enroute.examples | osgi.enroute.examples.plugin.application/src/osgi/enroute/examples/plugin/test/provider/TestSupplier.java | // Path: osgi.enroute.examples.plugin.application/src/osgi/enroute/examples/plugin/api/Product.java
// public class Product extends DTO {
// public String supplier;
// public String id;
// public String name;
// public String description;
// public long price;
// public int inStock;
// public int deliveryTimeInDays;
// }
//
// Path: osgi.enroute.examples.plugin.application/src/osgi/enroute/examples/plugin/api/SupplierPlugin.java
// public interface SupplierPlugin {
// Set<Product> findProducts( String query );
// boolean buy( String id);
// String getSupplierId();
// }
| import java.io.InputStream;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import osgi.enroute.dto.api.DTOs;
import osgi.enroute.examples.plugin.api.Product;
import osgi.enroute.examples.plugin.api.SupplierPlugin; | package osgi.enroute.examples.plugin.test.provider;
@Component
public class TestSupplier implements SupplierPlugin {
@Reference
DTOs dtos;
| // Path: osgi.enroute.examples.plugin.application/src/osgi/enroute/examples/plugin/api/Product.java
// public class Product extends DTO {
// public String supplier;
// public String id;
// public String name;
// public String description;
// public long price;
// public int inStock;
// public int deliveryTimeInDays;
// }
//
// Path: osgi.enroute.examples.plugin.application/src/osgi/enroute/examples/plugin/api/SupplierPlugin.java
// public interface SupplierPlugin {
// Set<Product> findProducts( String query );
// boolean buy( String id);
// String getSupplierId();
// }
// Path: osgi.enroute.examples.plugin.application/src/osgi/enroute/examples/plugin/test/provider/TestSupplier.java
import java.io.InputStream;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import osgi.enroute.dto.api.DTOs;
import osgi.enroute.examples.plugin.api.Product;
import osgi.enroute.examples.plugin.api.SupplierPlugin;
package osgi.enroute.examples.plugin.test.provider;
@Component
public class TestSupplier implements SupplierPlugin {
@Reference
DTOs dtos;
| Product[] products; |
osgi/osgi.enroute.examples | osgi.enroute.examples.scheduler.application/src/osgi/enroute/examples/scheduler/application/SchedulerRESTFacade.java | // Path: osgi.enroute.examples.scheduler.application/src/osgi/enroute/examples/scheduler/application/SchedulerApplication.java
// public static class ExampleInfo extends DTO {
// public String description;
// public String type;
// public String deflt;
// }
//
// Path: osgi.enroute.examples.scheduler.application/src/osgi/enroute/examples/scheduler/application/SchedulerApplication.java
// public static class Tracker extends DTO {
// public int id;
// public long created = System.currentTimeMillis();
// public long modified;
// public List<Integer> ticks = new ArrayList<>();
// public String tooltip;
// public long ended;
// public String method;
// public String parameter;
// public Object value;
// public String failure;
// public TrackerEvent lastEvent;
//
// CancellablePromise<?> promise;
// }
| import java.util.Map;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import osgi.enroute.examples.scheduler.application.SchedulerApplication.ExampleInfo;
import osgi.enroute.examples.scheduler.application.SchedulerApplication.Tracker;
import osgi.enroute.rest.api.REST;
import osgi.enroute.rest.api.RESTRequest; | package osgi.enroute.examples.scheduler.application;
/**
* This component is the facade for the REST interface. We accept a uri like
*
* <pre>
* PUT /rest/scheduler/:method-name?parameter= start a tracker
* DELETE /rest/scheduler/:id delete a tracker
* GET /rest/scheduler/:id get the tracker
* GET /rest/scheduler get example info
* </pre>
* <p>
* This example should, but does not do it, implement authorization checking.
*/
@Component()
public class SchedulerRESTFacade implements REST {
@Reference private SchedulerApplication app;
interface PutRequest extends RESTRequest {
String parameter();
}
/*
* Start a command and create a tracker.
*/ | // Path: osgi.enroute.examples.scheduler.application/src/osgi/enroute/examples/scheduler/application/SchedulerApplication.java
// public static class ExampleInfo extends DTO {
// public String description;
// public String type;
// public String deflt;
// }
//
// Path: osgi.enroute.examples.scheduler.application/src/osgi/enroute/examples/scheduler/application/SchedulerApplication.java
// public static class Tracker extends DTO {
// public int id;
// public long created = System.currentTimeMillis();
// public long modified;
// public List<Integer> ticks = new ArrayList<>();
// public String tooltip;
// public long ended;
// public String method;
// public String parameter;
// public Object value;
// public String failure;
// public TrackerEvent lastEvent;
//
// CancellablePromise<?> promise;
// }
// Path: osgi.enroute.examples.scheduler.application/src/osgi/enroute/examples/scheduler/application/SchedulerRESTFacade.java
import java.util.Map;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import osgi.enroute.examples.scheduler.application.SchedulerApplication.ExampleInfo;
import osgi.enroute.examples.scheduler.application.SchedulerApplication.Tracker;
import osgi.enroute.rest.api.REST;
import osgi.enroute.rest.api.RESTRequest;
package osgi.enroute.examples.scheduler.application;
/**
* This component is the facade for the REST interface. We accept a uri like
*
* <pre>
* PUT /rest/scheduler/:method-name?parameter= start a tracker
* DELETE /rest/scheduler/:id delete a tracker
* GET /rest/scheduler/:id get the tracker
* GET /rest/scheduler get example info
* </pre>
* <p>
* This example should, but does not do it, implement authorization checking.
*/
@Component()
public class SchedulerRESTFacade implements REST {
@Reference private SchedulerApplication app;
interface PutRequest extends RESTRequest {
String parameter();
}
/*
* Start a command and create a tracker.
*/ | public Tracker putScheduler(PutRequest rq, Object payload, String method) throws Exception { |
osgi/osgi.enroute.examples | osgi.enroute.examples.scheduler.application/src/osgi/enroute/examples/scheduler/application/SchedulerRESTFacade.java | // Path: osgi.enroute.examples.scheduler.application/src/osgi/enroute/examples/scheduler/application/SchedulerApplication.java
// public static class ExampleInfo extends DTO {
// public String description;
// public String type;
// public String deflt;
// }
//
// Path: osgi.enroute.examples.scheduler.application/src/osgi/enroute/examples/scheduler/application/SchedulerApplication.java
// public static class Tracker extends DTO {
// public int id;
// public long created = System.currentTimeMillis();
// public long modified;
// public List<Integer> ticks = new ArrayList<>();
// public String tooltip;
// public long ended;
// public String method;
// public String parameter;
// public Object value;
// public String failure;
// public TrackerEvent lastEvent;
//
// CancellablePromise<?> promise;
// }
| import java.util.Map;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import osgi.enroute.examples.scheduler.application.SchedulerApplication.ExampleInfo;
import osgi.enroute.examples.scheduler.application.SchedulerApplication.Tracker;
import osgi.enroute.rest.api.REST;
import osgi.enroute.rest.api.RESTRequest; | package osgi.enroute.examples.scheduler.application;
/**
* This component is the facade for the REST interface. We accept a uri like
*
* <pre>
* PUT /rest/scheduler/:method-name?parameter= start a tracker
* DELETE /rest/scheduler/:id delete a tracker
* GET /rest/scheduler/:id get the tracker
* GET /rest/scheduler get example info
* </pre>
* <p>
* This example should, but does not do it, implement authorization checking.
*/
@Component()
public class SchedulerRESTFacade implements REST {
@Reference private SchedulerApplication app;
interface PutRequest extends RESTRequest {
String parameter();
}
/*
* Start a command and create a tracker.
*/
public Tracker putScheduler(PutRequest rq, Object payload, String method) throws Exception {
return app.createTracker(method, rq.parameter());
}
public Tracker deleteScheduler(RESTRequest rq, int id) throws Exception {
return app.removeTracker(id);
}
public Tracker getScheduler(RESTRequest rq, int id) {
return app.getTracker(id);
}
| // Path: osgi.enroute.examples.scheduler.application/src/osgi/enroute/examples/scheduler/application/SchedulerApplication.java
// public static class ExampleInfo extends DTO {
// public String description;
// public String type;
// public String deflt;
// }
//
// Path: osgi.enroute.examples.scheduler.application/src/osgi/enroute/examples/scheduler/application/SchedulerApplication.java
// public static class Tracker extends DTO {
// public int id;
// public long created = System.currentTimeMillis();
// public long modified;
// public List<Integer> ticks = new ArrayList<>();
// public String tooltip;
// public long ended;
// public String method;
// public String parameter;
// public Object value;
// public String failure;
// public TrackerEvent lastEvent;
//
// CancellablePromise<?> promise;
// }
// Path: osgi.enroute.examples.scheduler.application/src/osgi/enroute/examples/scheduler/application/SchedulerRESTFacade.java
import java.util.Map;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import osgi.enroute.examples.scheduler.application.SchedulerApplication.ExampleInfo;
import osgi.enroute.examples.scheduler.application.SchedulerApplication.Tracker;
import osgi.enroute.rest.api.REST;
import osgi.enroute.rest.api.RESTRequest;
package osgi.enroute.examples.scheduler.application;
/**
* This component is the facade for the REST interface. We accept a uri like
*
* <pre>
* PUT /rest/scheduler/:method-name?parameter= start a tracker
* DELETE /rest/scheduler/:id delete a tracker
* GET /rest/scheduler/:id get the tracker
* GET /rest/scheduler get example info
* </pre>
* <p>
* This example should, but does not do it, implement authorization checking.
*/
@Component()
public class SchedulerRESTFacade implements REST {
@Reference private SchedulerApplication app;
interface PutRequest extends RESTRequest {
String parameter();
}
/*
* Start a command and create a tracker.
*/
public Tracker putScheduler(PutRequest rq, Object payload, String method) throws Exception {
return app.createTracker(method, rq.parameter());
}
public Tracker deleteScheduler(RESTRequest rq, int id) throws Exception {
return app.removeTracker(id);
}
public Tracker getScheduler(RESTRequest rq, int id) {
return app.getTracker(id);
}
| public Map<String, ExampleInfo> getScheduler(RESTRequest rq) { |
osgi/osgi.enroute.examples | osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/application/BackendREST.java | // Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/Backend.java
// public interface Backend {
// String TYPE = "type";
//
// /**
// * Save a blob
// *
// * @param name
// * The name of the blob
// * @param data
// * The actual data
// * @return the meta data describing the details of the store
// */
// MetaData save(String name, byte[] data) throws Exception;
//
// /**
// * Read the blob with the given name.
// *
// * @param name
// * The name of the resource
// * @return the data
// */
// byte[] read(String name) throws Exception;
//
// /**
// * Return a list of the meta data of what the store has.
// *
// * @return The list
// */
// Collection<? extends MetaData> list() throws Exception;
//
// /**
// * Delete a blob
// *
// * @param name
// * The name of the blob
// * @return true if deleted, false if could not be deleted (might not exist)
// */
// boolean delete(String name) throws Exception;
// }
//
// Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/MetaData.java
// public class MetaData extends DTO {
// /**
// * The name of the blob
// */
// public String name;
//
// /**
// * The size of the blob
// */
// public long size;
//
// /**
// * The epoch time when it was last modified.
// */
// public long modified;
// }
| import java.io.FileNotFoundException;
import java.util.Collection;
import org.osgi.dto.DTO;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import osgi.enroute.examples.backend.api.Backend;
import osgi.enroute.examples.backend.api.MetaData;
import osgi.enroute.rest.api.REST;
import osgi.enroute.rest.api.RESTRequest; | package osgi.enroute.examples.backend.application;
/**
* The Backend REST API provides a REST interface into the Backend Application.
* It provides the REST CRUD operations. The URI for this REST API has the
* following syntax:
*
* <pre>
* /rest/backend GET Return an array of types
* /rest/backend/<type> GET Return a list of MetaData
* for the entries in the <type>
* backend
* /rest/backend/<type>/<name> GET Get the blob
* PUT Put the blob
* DELETE Delete the blob
* </pre>
*
*/
@Component
public class BackendREST implements REST {
@Reference
BackendApplication model;
/*
* Defines how the body looks like
*/
interface PutRequest extends RESTRequest {
String _body();
}
/**
* Used to return data with some of its metadata.
*/
public static class Data extends DTO {
public String name;
public String type;
public String data;
}
/*
* This is the {@code PUT /rest/backend/<type>/<name>}. Get the backend and
* save the blob
*/ | // Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/Backend.java
// public interface Backend {
// String TYPE = "type";
//
// /**
// * Save a blob
// *
// * @param name
// * The name of the blob
// * @param data
// * The actual data
// * @return the meta data describing the details of the store
// */
// MetaData save(String name, byte[] data) throws Exception;
//
// /**
// * Read the blob with the given name.
// *
// * @param name
// * The name of the resource
// * @return the data
// */
// byte[] read(String name) throws Exception;
//
// /**
// * Return a list of the meta data of what the store has.
// *
// * @return The list
// */
// Collection<? extends MetaData> list() throws Exception;
//
// /**
// * Delete a blob
// *
// * @param name
// * The name of the blob
// * @return true if deleted, false if could not be deleted (might not exist)
// */
// boolean delete(String name) throws Exception;
// }
//
// Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/MetaData.java
// public class MetaData extends DTO {
// /**
// * The name of the blob
// */
// public String name;
//
// /**
// * The size of the blob
// */
// public long size;
//
// /**
// * The epoch time when it was last modified.
// */
// public long modified;
// }
// Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/application/BackendREST.java
import java.io.FileNotFoundException;
import java.util.Collection;
import org.osgi.dto.DTO;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import osgi.enroute.examples.backend.api.Backend;
import osgi.enroute.examples.backend.api.MetaData;
import osgi.enroute.rest.api.REST;
import osgi.enroute.rest.api.RESTRequest;
package osgi.enroute.examples.backend.application;
/**
* The Backend REST API provides a REST interface into the Backend Application.
* It provides the REST CRUD operations. The URI for this REST API has the
* following syntax:
*
* <pre>
* /rest/backend GET Return an array of types
* /rest/backend/<type> GET Return a list of MetaData
* for the entries in the <type>
* backend
* /rest/backend/<type>/<name> GET Get the blob
* PUT Put the blob
* DELETE Delete the blob
* </pre>
*
*/
@Component
public class BackendREST implements REST {
@Reference
BackendApplication model;
/*
* Defines how the body looks like
*/
interface PutRequest extends RESTRequest {
String _body();
}
/**
* Used to return data with some of its metadata.
*/
public static class Data extends DTO {
public String name;
public String type;
public String data;
}
/*
* This is the {@code PUT /rest/backend/<type>/<name>}. Get the backend and
* save the blob
*/ | public MetaData putBackend(PutRequest pr, String type, String name) |
osgi/osgi.enroute.examples | osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/application/BackendREST.java | // Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/Backend.java
// public interface Backend {
// String TYPE = "type";
//
// /**
// * Save a blob
// *
// * @param name
// * The name of the blob
// * @param data
// * The actual data
// * @return the meta data describing the details of the store
// */
// MetaData save(String name, byte[] data) throws Exception;
//
// /**
// * Read the blob with the given name.
// *
// * @param name
// * The name of the resource
// * @return the data
// */
// byte[] read(String name) throws Exception;
//
// /**
// * Return a list of the meta data of what the store has.
// *
// * @return The list
// */
// Collection<? extends MetaData> list() throws Exception;
//
// /**
// * Delete a blob
// *
// * @param name
// * The name of the blob
// * @return true if deleted, false if could not be deleted (might not exist)
// */
// boolean delete(String name) throws Exception;
// }
//
// Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/MetaData.java
// public class MetaData extends DTO {
// /**
// * The name of the blob
// */
// public String name;
//
// /**
// * The size of the blob
// */
// public long size;
//
// /**
// * The epoch time when it was last modified.
// */
// public long modified;
// }
| import java.io.FileNotFoundException;
import java.util.Collection;
import org.osgi.dto.DTO;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import osgi.enroute.examples.backend.api.Backend;
import osgi.enroute.examples.backend.api.MetaData;
import osgi.enroute.rest.api.REST;
import osgi.enroute.rest.api.RESTRequest; | package osgi.enroute.examples.backend.application;
/**
* The Backend REST API provides a REST interface into the Backend Application.
* It provides the REST CRUD operations. The URI for this REST API has the
* following syntax:
*
* <pre>
* /rest/backend GET Return an array of types
* /rest/backend/<type> GET Return a list of MetaData
* for the entries in the <type>
* backend
* /rest/backend/<type>/<name> GET Get the blob
* PUT Put the blob
* DELETE Delete the blob
* </pre>
*
*/
@Component
public class BackendREST implements REST {
@Reference
BackendApplication model;
/*
* Defines how the body looks like
*/
interface PutRequest extends RESTRequest {
String _body();
}
/**
* Used to return data with some of its metadata.
*/
public static class Data extends DTO {
public String name;
public String type;
public String data;
}
/*
* This is the {@code PUT /rest/backend/<type>/<name>}. Get the backend and
* save the blob
*/
public MetaData putBackend(PutRequest pr, String type, String name)
throws Exception {
return getBackend(type).save(name, pr._body().getBytes("UTF-8"));
}
/*
* This is the {@code GET /rest/backend}. Get the list of type names.
*/
public Collection<String> getBackend(RESTRequest rq) {
return model.getBackends();
}
/*
* This is the {@code GET /rest/backend/<type>}. Get the list of blob meta
* data for the given type.
*/
public Collection<? extends MetaData> getBackend(RESTRequest pr, String type)
throws Exception {
return getBackend(type).list();
}
/*
* This is the {@code GET /rest/backend<type>/<name>}. Get the blob data for
* the given type.
*/
public Data getBackend(RESTRequest pr, String type, String name)
throws Exception { | // Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/Backend.java
// public interface Backend {
// String TYPE = "type";
//
// /**
// * Save a blob
// *
// * @param name
// * The name of the blob
// * @param data
// * The actual data
// * @return the meta data describing the details of the store
// */
// MetaData save(String name, byte[] data) throws Exception;
//
// /**
// * Read the blob with the given name.
// *
// * @param name
// * The name of the resource
// * @return the data
// */
// byte[] read(String name) throws Exception;
//
// /**
// * Return a list of the meta data of what the store has.
// *
// * @return The list
// */
// Collection<? extends MetaData> list() throws Exception;
//
// /**
// * Delete a blob
// *
// * @param name
// * The name of the blob
// * @return true if deleted, false if could not be deleted (might not exist)
// */
// boolean delete(String name) throws Exception;
// }
//
// Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/api/MetaData.java
// public class MetaData extends DTO {
// /**
// * The name of the blob
// */
// public String name;
//
// /**
// * The size of the blob
// */
// public long size;
//
// /**
// * The epoch time when it was last modified.
// */
// public long modified;
// }
// Path: osgi.enroute.examples.backend.application/src/osgi/enroute/examples/backend/application/BackendREST.java
import java.io.FileNotFoundException;
import java.util.Collection;
import org.osgi.dto.DTO;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import osgi.enroute.examples.backend.api.Backend;
import osgi.enroute.examples.backend.api.MetaData;
import osgi.enroute.rest.api.REST;
import osgi.enroute.rest.api.RESTRequest;
package osgi.enroute.examples.backend.application;
/**
* The Backend REST API provides a REST interface into the Backend Application.
* It provides the REST CRUD operations. The URI for this REST API has the
* following syntax:
*
* <pre>
* /rest/backend GET Return an array of types
* /rest/backend/<type> GET Return a list of MetaData
* for the entries in the <type>
* backend
* /rest/backend/<type>/<name> GET Get the blob
* PUT Put the blob
* DELETE Delete the blob
* </pre>
*
*/
@Component
public class BackendREST implements REST {
@Reference
BackendApplication model;
/*
* Defines how the body looks like
*/
interface PutRequest extends RESTRequest {
String _body();
}
/**
* Used to return data with some of its metadata.
*/
public static class Data extends DTO {
public String name;
public String type;
public String data;
}
/*
* This is the {@code PUT /rest/backend/<type>/<name>}. Get the backend and
* save the blob
*/
public MetaData putBackend(PutRequest pr, String type, String name)
throws Exception {
return getBackend(type).save(name, pr._body().getBytes("UTF-8"));
}
/*
* This is the {@code GET /rest/backend}. Get the list of type names.
*/
public Collection<String> getBackend(RESTRequest rq) {
return model.getBackends();
}
/*
* This is the {@code GET /rest/backend/<type>}. Get the list of blob meta
* data for the given type.
*/
public Collection<? extends MetaData> getBackend(RESTRequest pr, String type)
throws Exception {
return getBackend(type).list();
}
/*
* This is the {@code GET /rest/backend<type>/<name>}. Get the blob data for
* the given type.
*/
public Data getBackend(RESTRequest pr, String type, String name)
throws Exception { | Backend backend = getBackend(type); |
ThinkBigAnalytics/colossal-pipe | src/sample/java/colossal/pipe/sample/SamplePipe.java | // Path: src/main/java/colossal/util/TimeShard.java
// public interface TimeShard {
// public String makePath(DateTime ts);
//
// public String makeTimestamp(DateTime start, DateTime end);
// }
| import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import colossal.pipe.*;
import colossal.util.TimeShard; | /**
* Copyright (C) 2010-2014 Think Big Analytics, Inc. All Rights Reserved.
*
* 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. See accompanying LICENSE file.
*/
package colossal.pipe.sample;
public class SamplePipe extends Configured implements Tool {
@SuppressWarnings({ "unchecked", "unused" })
@Override
public int run(String[] args) throws Exception {
ColPipe pipe = new ColPipe(getClass());
/* Parse options - just use the standard options - input and output location, time window, etc. */
BaseOptions o = new BaseOptions();
int result = o.parse(pipe, args);
if (result != 0)
return result;
| // Path: src/main/java/colossal/util/TimeShard.java
// public interface TimeShard {
// public String makePath(DateTime ts);
//
// public String makeTimestamp(DateTime start, DateTime end);
// }
// Path: src/sample/java/colossal/pipe/sample/SamplePipe.java
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import colossal.pipe.*;
import colossal.util.TimeShard;
/**
* Copyright (C) 2010-2014 Think Big Analytics, Inc. All Rights Reserved.
*
* 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. See accompanying LICENSE file.
*/
package colossal.pipe.sample;
public class SamplePipe extends Configured implements Tool {
@SuppressWarnings({ "unchecked", "unused" })
@Override
public int run(String[] args) throws Exception {
ColPipe pipe = new ColPipe(getClass());
/* Parse options - just use the standard options - input and output location, time window, etc. */
BaseOptions o = new BaseOptions();
int result = o.parse(pipe, args);
if (result != 0)
return result;
| String hrPath = TimeShard.makePath(o.getStart()); |
ThinkBigAnalytics/colossal-pipe | src/sample/java/colossal/pipe/sample/LogClean.java | // Path: src/main/java/colossal/pipe/BaseMapper.java
// public class BaseMapper<IN,OUT> extends Configured implements ColMapper<IN,OUT> {
//
// /** Override this method for a mapper */
// @SuppressWarnings("unchecked")
// public void map(IN in, OUT out, ColContext<OUT> context) {
// context.write((OUT)in);
// }
//
// @Override
// public void close(OUT out, ColContext<OUT> context) {
// // no op by default
// }
//
// }
//
// Path: src/main/java/colossal/pipe/ColContext.java
// public class ColContext<OUT> {
//
// private Reporter reporter;
// private AvroCollector<OUT> collector;
//
// public<IN, K, V, KO, VO> ColContext(AvroCollector<OUT> collector, Reporter reporter) {
// this.reporter = reporter;
// this.collector = collector;
// }
//
// public void write(OUT out) {
// try {
// collector.collect(out);
// }
// catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public Counter getCounter(Enum<?> name) {
// return reporter.getCounter(name);
// }
//
// public Counter getCounter(String group, String name) {
// return reporter.getCounter(group, name);
// }
//
// public void incrCounter(Enum<?> key, long amount) {
// reporter.incrCounter(key, amount);
// }
//
// public void incrCounter(String group, String counter, long amount) {
// reporter.incrCounter(group, counter, amount);
// }
//
// public InputSplit getInputSplit() throws UnsupportedOperationException {
// return reporter.getInputSplit();
// }
//
// public void progress() {
// reporter.progress();
// }
//
// public void setStatus(String status) {
// reporter.setStatus(status);
// }
//
// public void incrCounter(Enum counter) {
// reporter.incrCounter(counter, 1L);
// }
//
// public void incrCounter(String group, String counter) {
// reporter.incrCounter(group, counter, 1L);
// }
//
// }
| import org.apache.hadoop.conf.Configuration;
import colossal.pipe.BaseMapper;
import colossal.pipe.ColContext; | /**
* Copyright (C) 2010-2014 Think Big Analytics, Inc. All Rights Reserved.
*
* 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. See accompanying LICENSE file.
*/
package colossal.pipe.sample;
public class LogClean extends BaseMapper<LogRec,LogRec> {
@Override
public void setConf(Configuration conf) {
super.setConf(conf);
if (conf != null) {
//use conf.get
}
}
@Override | // Path: src/main/java/colossal/pipe/BaseMapper.java
// public class BaseMapper<IN,OUT> extends Configured implements ColMapper<IN,OUT> {
//
// /** Override this method for a mapper */
// @SuppressWarnings("unchecked")
// public void map(IN in, OUT out, ColContext<OUT> context) {
// context.write((OUT)in);
// }
//
// @Override
// public void close(OUT out, ColContext<OUT> context) {
// // no op by default
// }
//
// }
//
// Path: src/main/java/colossal/pipe/ColContext.java
// public class ColContext<OUT> {
//
// private Reporter reporter;
// private AvroCollector<OUT> collector;
//
// public<IN, K, V, KO, VO> ColContext(AvroCollector<OUT> collector, Reporter reporter) {
// this.reporter = reporter;
// this.collector = collector;
// }
//
// public void write(OUT out) {
// try {
// collector.collect(out);
// }
// catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public Counter getCounter(Enum<?> name) {
// return reporter.getCounter(name);
// }
//
// public Counter getCounter(String group, String name) {
// return reporter.getCounter(group, name);
// }
//
// public void incrCounter(Enum<?> key, long amount) {
// reporter.incrCounter(key, amount);
// }
//
// public void incrCounter(String group, String counter, long amount) {
// reporter.incrCounter(group, counter, amount);
// }
//
// public InputSplit getInputSplit() throws UnsupportedOperationException {
// return reporter.getInputSplit();
// }
//
// public void progress() {
// reporter.progress();
// }
//
// public void setStatus(String status) {
// reporter.setStatus(status);
// }
//
// public void incrCounter(Enum counter) {
// reporter.incrCounter(counter, 1L);
// }
//
// public void incrCounter(String group, String counter) {
// reporter.incrCounter(group, counter, 1L);
// }
//
// }
// Path: src/sample/java/colossal/pipe/sample/LogClean.java
import org.apache.hadoop.conf.Configuration;
import colossal.pipe.BaseMapper;
import colossal.pipe.ColContext;
/**
* Copyright (C) 2010-2014 Think Big Analytics, Inc. All Rights Reserved.
*
* 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. See accompanying LICENSE file.
*/
package colossal.pipe.sample;
public class LogClean extends BaseMapper<LogRec,LogRec> {
@Override
public void setConf(Configuration conf) {
super.setConf(conf);
if (conf != null) {
//use conf.get
}
}
@Override | public void map(LogRec in, LogRec out, ColContext<LogRec> context) { |
ThinkBigAnalytics/colossal-pipe | src/sample/java/colossal/pipe/sample/BotFilter.java | // Path: src/main/java/colossal/pipe/BaseReducer.java
// public class BaseReducer<IN,OUT> extends Configured implements ColReducer<IN,OUT> {
// /** Override this method for a mapper */
// @SuppressWarnings("unchecked")
// public void reduce(Iterable<IN> in, OUT out, ColContext<OUT> context) {
// for (IN i : in) {
// context.write((OUT)i);
// }
// }
//
// @Override
// public void close(OUT out, ColContext<OUT> context) {
// // no op by default
// }
//
// }
//
// Path: src/main/java/colossal/pipe/ColContext.java
// public class ColContext<OUT> {
//
// private Reporter reporter;
// private AvroCollector<OUT> collector;
//
// public<IN, K, V, KO, VO> ColContext(AvroCollector<OUT> collector, Reporter reporter) {
// this.reporter = reporter;
// this.collector = collector;
// }
//
// public void write(OUT out) {
// try {
// collector.collect(out);
// }
// catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public Counter getCounter(Enum<?> name) {
// return reporter.getCounter(name);
// }
//
// public Counter getCounter(String group, String name) {
// return reporter.getCounter(group, name);
// }
//
// public void incrCounter(Enum<?> key, long amount) {
// reporter.incrCounter(key, amount);
// }
//
// public void incrCounter(String group, String counter, long amount) {
// reporter.incrCounter(group, counter, amount);
// }
//
// public InputSplit getInputSplit() throws UnsupportedOperationException {
// return reporter.getInputSplit();
// }
//
// public void progress() {
// reporter.progress();
// }
//
// public void setStatus(String status) {
// reporter.setStatus(status);
// }
//
// public void incrCounter(Enum counter) {
// reporter.incrCounter(counter, 1L);
// }
//
// public void incrCounter(String group, String counter) {
// reporter.incrCounter(group, counter, 1L);
// }
//
// }
| import colossal.pipe.BaseReducer;
import colossal.pipe.ColContext; | /**
* Copyright (C) 2010-2014 Think Big Analytics, Inc. All Rights Reserved.
*
* 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. See accompanying LICENSE file.
*/
package colossal.pipe.sample;
public class BotFilter extends BaseReducer<LogRec,LogRec> {
@Override | // Path: src/main/java/colossal/pipe/BaseReducer.java
// public class BaseReducer<IN,OUT> extends Configured implements ColReducer<IN,OUT> {
// /** Override this method for a mapper */
// @SuppressWarnings("unchecked")
// public void reduce(Iterable<IN> in, OUT out, ColContext<OUT> context) {
// for (IN i : in) {
// context.write((OUT)i);
// }
// }
//
// @Override
// public void close(OUT out, ColContext<OUT> context) {
// // no op by default
// }
//
// }
//
// Path: src/main/java/colossal/pipe/ColContext.java
// public class ColContext<OUT> {
//
// private Reporter reporter;
// private AvroCollector<OUT> collector;
//
// public<IN, K, V, KO, VO> ColContext(AvroCollector<OUT> collector, Reporter reporter) {
// this.reporter = reporter;
// this.collector = collector;
// }
//
// public void write(OUT out) {
// try {
// collector.collect(out);
// }
// catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public Counter getCounter(Enum<?> name) {
// return reporter.getCounter(name);
// }
//
// public Counter getCounter(String group, String name) {
// return reporter.getCounter(group, name);
// }
//
// public void incrCounter(Enum<?> key, long amount) {
// reporter.incrCounter(key, amount);
// }
//
// public void incrCounter(String group, String counter, long amount) {
// reporter.incrCounter(group, counter, amount);
// }
//
// public InputSplit getInputSplit() throws UnsupportedOperationException {
// return reporter.getInputSplit();
// }
//
// public void progress() {
// reporter.progress();
// }
//
// public void setStatus(String status) {
// reporter.setStatus(status);
// }
//
// public void incrCounter(Enum counter) {
// reporter.incrCounter(counter, 1L);
// }
//
// public void incrCounter(String group, String counter) {
// reporter.incrCounter(group, counter, 1L);
// }
//
// }
// Path: src/sample/java/colossal/pipe/sample/BotFilter.java
import colossal.pipe.BaseReducer;
import colossal.pipe.ColContext;
/**
* Copyright (C) 2010-2014 Think Big Analytics, Inc. All Rights Reserved.
*
* 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. See accompanying LICENSE file.
*/
package colossal.pipe.sample;
public class BotFilter extends BaseReducer<LogRec,LogRec> {
@Override | public void reduce(Iterable<LogRec> in, LogRec out, ColContext<LogRec> context) { |
ThinkBigAnalytics/colossal-pipe | src/main/java/colossal/util/EmailAlerter.java | // Path: src/main/java/colossal/pipe/PhaseError.java
// public class PhaseError {
// private String message;
// private Throwable exception;
//
// public PhaseError(String message) {
// this.message = message;
// this.exception = null;
// }
// public PhaseError(Throwable t, String processName) {
// this.message = "Failure running "+processName;
// this.exception = t;
// }
// public String getMessage() {
// return message;
// }
// public Throwable getException() {
// return exception;
// }
// }
| import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import colossal.pipe.PhaseError; | SimpleEmail email = makeFailureEmail();
StringBuilder msg = new StringBuilder(summary);
msg.append("Exception:\n");
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
exception.printStackTrace(printWriter);
msg.append(writer.toString());
email.setMsg(msg.toString());
email.send();
} catch (EmailException e) {
System.err.println("Can't send email!");
e.printStackTrace();
}
}
private SimpleEmail makeFailureEmail() throws EmailException {
return makeEmail("Job Failure");
}
private SimpleEmail makeEmail(String title) throws EmailException {
SimpleEmail email = new SimpleEmail();
for (String targetAddress : targetAddresses)
email.addTo(targetAddress);
email.setSubject(title);
email.setFrom(from);
email.setHostName(host);
return email;
}
@Override | // Path: src/main/java/colossal/pipe/PhaseError.java
// public class PhaseError {
// private String message;
// private Throwable exception;
//
// public PhaseError(String message) {
// this.message = message;
// this.exception = null;
// }
// public PhaseError(Throwable t, String processName) {
// this.message = "Failure running "+processName;
// this.exception = t;
// }
// public String getMessage() {
// return message;
// }
// public Throwable getException() {
// return exception;
// }
// }
// Path: src/main/java/colossal/util/EmailAlerter.java
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import colossal.pipe.PhaseError;
SimpleEmail email = makeFailureEmail();
StringBuilder msg = new StringBuilder(summary);
msg.append("Exception:\n");
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
exception.printStackTrace(printWriter);
msg.append(writer.toString());
email.setMsg(msg.toString());
email.send();
} catch (EmailException e) {
System.err.println("Can't send email!");
e.printStackTrace();
}
}
private SimpleEmail makeFailureEmail() throws EmailException {
return makeEmail("Job Failure");
}
private SimpleEmail makeEmail(String title) throws EmailException {
SimpleEmail email = new SimpleEmail();
for (String targetAddress : targetAddresses)
email.addTo(targetAddress);
email.setSubject(title);
email.setFrom(from);
email.setHostName(host);
return email;
}
@Override | public void alert(List<PhaseError> errors) { |
ThinkBigAnalytics/colossal-pipe | src/main/java/colossal/pipe/ColPipe.java | // Path: src/main/java/colossal/util/Alerter.java
// public interface Alerter {
//
// public void alert(Exception exception, String summary);
//
// public void alert(List<PhaseError> result);
//
// public void alert(String problem);
//
// public void pipeCompletion(String pipeName, String summary);
//
// }
//
// Path: src/main/java/colossal/util/EmailAlerter.java
// public class EmailAlerter implements Alerter {
//
// private String[] targetAddresses;
// private String from = System.getProperty("colossal.util.email.alerts.from");
// private String host = System.getProperty("colossal.util.email.alerts.host", "localhost");
// private boolean emailEnabled;
// {
// String defaultAddrs = System.getProperty("colossal.util.email.alerts.to");
// if (defaultAddrs != null) {
// targetAddresses = defaultAddrs.split(",");
// for (int i=0; i<targetAddresses.length; i++)
// targetAddresses[i] = targetAddresses[i].trim();
// emailEnabled = (from != null);
// } else {
// emailEnabled = false;
// }
// }
//
// @Override
// public void alert(Exception exception, String summary) {
//
// if (!emailEnabled) {
// System.err.println("Alert: "+summary);
// exception.printStackTrace();
// System.err.println("Can't email - not configured");
// return;
// }
//
// System.err.println("Emailing Alert: "+summary);
// exception.printStackTrace();
//
// try {
// SimpleEmail email = makeFailureEmail();
// StringBuilder msg = new StringBuilder(summary);
// msg.append("Exception:\n");
// StringWriter writer = new StringWriter();
// PrintWriter printWriter = new PrintWriter(writer);
// exception.printStackTrace(printWriter);
// msg.append(writer.toString());
// email.setMsg(msg.toString());
// email.send();
// } catch (EmailException e) {
// System.err.println("Can't send email!");
// e.printStackTrace();
// }
// }
//
// private SimpleEmail makeFailureEmail() throws EmailException {
// return makeEmail("Job Failure");
// }
//
// private SimpleEmail makeEmail(String title) throws EmailException {
// SimpleEmail email = new SimpleEmail();
// for (String targetAddress : targetAddresses)
// email.addTo(targetAddress);
// email.setSubject(title);
// email.setFrom(from);
// email.setHostName(host);
// return email;
// }
//
// @Override
// public void alert(List<PhaseError> errors) {
// System.err.format("%sAlert: can't run pipeline\n", emailEnabled ? "Emailing " : "");
// for (PhaseError e : errors) {
// System.err.println(e.getMessage());
// }
// if (!emailEnabled) {
// System.err.println("Can't email - not configured");
// return;
// }
//
// try {
// SimpleEmail email = makeFailureEmail();
// StringBuilder msg = new StringBuilder();
// for (PhaseError e : errors) {
// msg.append(e.getMessage()).append('\n');
// }
// email.setMsg(msg.toString());
// email.send();
// } catch (EmailException e) {
// System.err.println("Can't send email!");
// e.printStackTrace();
// }
// }
//
// @Override
// public void pipeCompletion(String pipeName, String summary) {
// System.out.println("Pipe completion: "+pipeName);
// System.out.println(summary);
// if (!emailEnabled) return;
//
// try {
// SimpleEmail email = makeEmail("Pipe completion: "+pipeName);
// email.setMsg(summary);
// email.send();
// }
// catch (EmailException e) {
// System.err.println("Can't send email!");
// e.printStackTrace();
// }
// }
//
// @Override
// public void alert(String problem) {
// PhaseError err = new PhaseError(problem);
// ArrayList<PhaseError> list = new ArrayList<PhaseError>(1);
// list.add(err);
// alert(list);
// }
//
// }
| import java.net.URI;
import java.util.*;
import java.util.concurrent.*;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.mapred.JobConf;
import colossal.util.Alerter;
import colossal.util.EmailAlerter; | /*
* Licensed to Think Big Analytics, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Think Big Analytics, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2010 Think Big Analytics. All Rights Reserved.
*/
package colossal.pipe;
@SuppressWarnings("deprecation")
public class ColPipe {
private List<ColFile> writes;
private int parallelPhases = 2; // default to 2 phases at once - use concurrency (also speeds up local running)
private JobConf baseConf = new JobConf(); | // Path: src/main/java/colossal/util/Alerter.java
// public interface Alerter {
//
// public void alert(Exception exception, String summary);
//
// public void alert(List<PhaseError> result);
//
// public void alert(String problem);
//
// public void pipeCompletion(String pipeName, String summary);
//
// }
//
// Path: src/main/java/colossal/util/EmailAlerter.java
// public class EmailAlerter implements Alerter {
//
// private String[] targetAddresses;
// private String from = System.getProperty("colossal.util.email.alerts.from");
// private String host = System.getProperty("colossal.util.email.alerts.host", "localhost");
// private boolean emailEnabled;
// {
// String defaultAddrs = System.getProperty("colossal.util.email.alerts.to");
// if (defaultAddrs != null) {
// targetAddresses = defaultAddrs.split(",");
// for (int i=0; i<targetAddresses.length; i++)
// targetAddresses[i] = targetAddresses[i].trim();
// emailEnabled = (from != null);
// } else {
// emailEnabled = false;
// }
// }
//
// @Override
// public void alert(Exception exception, String summary) {
//
// if (!emailEnabled) {
// System.err.println("Alert: "+summary);
// exception.printStackTrace();
// System.err.println("Can't email - not configured");
// return;
// }
//
// System.err.println("Emailing Alert: "+summary);
// exception.printStackTrace();
//
// try {
// SimpleEmail email = makeFailureEmail();
// StringBuilder msg = new StringBuilder(summary);
// msg.append("Exception:\n");
// StringWriter writer = new StringWriter();
// PrintWriter printWriter = new PrintWriter(writer);
// exception.printStackTrace(printWriter);
// msg.append(writer.toString());
// email.setMsg(msg.toString());
// email.send();
// } catch (EmailException e) {
// System.err.println("Can't send email!");
// e.printStackTrace();
// }
// }
//
// private SimpleEmail makeFailureEmail() throws EmailException {
// return makeEmail("Job Failure");
// }
//
// private SimpleEmail makeEmail(String title) throws EmailException {
// SimpleEmail email = new SimpleEmail();
// for (String targetAddress : targetAddresses)
// email.addTo(targetAddress);
// email.setSubject(title);
// email.setFrom(from);
// email.setHostName(host);
// return email;
// }
//
// @Override
// public void alert(List<PhaseError> errors) {
// System.err.format("%sAlert: can't run pipeline\n", emailEnabled ? "Emailing " : "");
// for (PhaseError e : errors) {
// System.err.println(e.getMessage());
// }
// if (!emailEnabled) {
// System.err.println("Can't email - not configured");
// return;
// }
//
// try {
// SimpleEmail email = makeFailureEmail();
// StringBuilder msg = new StringBuilder();
// for (PhaseError e : errors) {
// msg.append(e.getMessage()).append('\n');
// }
// email.setMsg(msg.toString());
// email.send();
// } catch (EmailException e) {
// System.err.println("Can't send email!");
// e.printStackTrace();
// }
// }
//
// @Override
// public void pipeCompletion(String pipeName, String summary) {
// System.out.println("Pipe completion: "+pipeName);
// System.out.println(summary);
// if (!emailEnabled) return;
//
// try {
// SimpleEmail email = makeEmail("Pipe completion: "+pipeName);
// email.setMsg(summary);
// email.send();
// }
// catch (EmailException e) {
// System.err.println("Can't send email!");
// e.printStackTrace();
// }
// }
//
// @Override
// public void alert(String problem) {
// PhaseError err = new PhaseError(problem);
// ArrayList<PhaseError> list = new ArrayList<PhaseError>(1);
// list.add(err);
// alert(list);
// }
//
// }
// Path: src/main/java/colossal/pipe/ColPipe.java
import java.net.URI;
import java.util.*;
import java.util.concurrent.*;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.mapred.JobConf;
import colossal.util.Alerter;
import colossal.util.EmailAlerter;
/*
* Licensed to Think Big Analytics, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Think Big Analytics, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2010 Think Big Analytics. All Rights Reserved.
*/
package colossal.pipe;
@SuppressWarnings("deprecation")
public class ColPipe {
private List<ColFile> writes;
private int parallelPhases = 2; // default to 2 phases at once - use concurrency (also speeds up local running)
private JobConf baseConf = new JobConf(); | private Alerter alerter = new EmailAlerter(); |
ThinkBigAnalytics/colossal-pipe | src/main/java/colossal/pipe/ColPipe.java | // Path: src/main/java/colossal/util/Alerter.java
// public interface Alerter {
//
// public void alert(Exception exception, String summary);
//
// public void alert(List<PhaseError> result);
//
// public void alert(String problem);
//
// public void pipeCompletion(String pipeName, String summary);
//
// }
//
// Path: src/main/java/colossal/util/EmailAlerter.java
// public class EmailAlerter implements Alerter {
//
// private String[] targetAddresses;
// private String from = System.getProperty("colossal.util.email.alerts.from");
// private String host = System.getProperty("colossal.util.email.alerts.host", "localhost");
// private boolean emailEnabled;
// {
// String defaultAddrs = System.getProperty("colossal.util.email.alerts.to");
// if (defaultAddrs != null) {
// targetAddresses = defaultAddrs.split(",");
// for (int i=0; i<targetAddresses.length; i++)
// targetAddresses[i] = targetAddresses[i].trim();
// emailEnabled = (from != null);
// } else {
// emailEnabled = false;
// }
// }
//
// @Override
// public void alert(Exception exception, String summary) {
//
// if (!emailEnabled) {
// System.err.println("Alert: "+summary);
// exception.printStackTrace();
// System.err.println("Can't email - not configured");
// return;
// }
//
// System.err.println("Emailing Alert: "+summary);
// exception.printStackTrace();
//
// try {
// SimpleEmail email = makeFailureEmail();
// StringBuilder msg = new StringBuilder(summary);
// msg.append("Exception:\n");
// StringWriter writer = new StringWriter();
// PrintWriter printWriter = new PrintWriter(writer);
// exception.printStackTrace(printWriter);
// msg.append(writer.toString());
// email.setMsg(msg.toString());
// email.send();
// } catch (EmailException e) {
// System.err.println("Can't send email!");
// e.printStackTrace();
// }
// }
//
// private SimpleEmail makeFailureEmail() throws EmailException {
// return makeEmail("Job Failure");
// }
//
// private SimpleEmail makeEmail(String title) throws EmailException {
// SimpleEmail email = new SimpleEmail();
// for (String targetAddress : targetAddresses)
// email.addTo(targetAddress);
// email.setSubject(title);
// email.setFrom(from);
// email.setHostName(host);
// return email;
// }
//
// @Override
// public void alert(List<PhaseError> errors) {
// System.err.format("%sAlert: can't run pipeline\n", emailEnabled ? "Emailing " : "");
// for (PhaseError e : errors) {
// System.err.println(e.getMessage());
// }
// if (!emailEnabled) {
// System.err.println("Can't email - not configured");
// return;
// }
//
// try {
// SimpleEmail email = makeFailureEmail();
// StringBuilder msg = new StringBuilder();
// for (PhaseError e : errors) {
// msg.append(e.getMessage()).append('\n');
// }
// email.setMsg(msg.toString());
// email.send();
// } catch (EmailException e) {
// System.err.println("Can't send email!");
// e.printStackTrace();
// }
// }
//
// @Override
// public void pipeCompletion(String pipeName, String summary) {
// System.out.println("Pipe completion: "+pipeName);
// System.out.println(summary);
// if (!emailEnabled) return;
//
// try {
// SimpleEmail email = makeEmail("Pipe completion: "+pipeName);
// email.setMsg(summary);
// email.send();
// }
// catch (EmailException e) {
// System.err.println("Can't send email!");
// e.printStackTrace();
// }
// }
//
// @Override
// public void alert(String problem) {
// PhaseError err = new PhaseError(problem);
// ArrayList<PhaseError> list = new ArrayList<PhaseError>(1);
// list.add(err);
// alert(list);
// }
//
// }
| import java.net.URI;
import java.util.*;
import java.util.concurrent.*;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.mapred.JobConf;
import colossal.util.Alerter;
import colossal.util.EmailAlerter; | /*
* Licensed to Think Big Analytics, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Think Big Analytics, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2010 Think Big Analytics. All Rights Reserved.
*/
package colossal.pipe;
@SuppressWarnings("deprecation")
public class ColPipe {
private List<ColFile> writes;
private int parallelPhases = 2; // default to 2 phases at once - use concurrency (also speeds up local running)
private JobConf baseConf = new JobConf(); | // Path: src/main/java/colossal/util/Alerter.java
// public interface Alerter {
//
// public void alert(Exception exception, String summary);
//
// public void alert(List<PhaseError> result);
//
// public void alert(String problem);
//
// public void pipeCompletion(String pipeName, String summary);
//
// }
//
// Path: src/main/java/colossal/util/EmailAlerter.java
// public class EmailAlerter implements Alerter {
//
// private String[] targetAddresses;
// private String from = System.getProperty("colossal.util.email.alerts.from");
// private String host = System.getProperty("colossal.util.email.alerts.host", "localhost");
// private boolean emailEnabled;
// {
// String defaultAddrs = System.getProperty("colossal.util.email.alerts.to");
// if (defaultAddrs != null) {
// targetAddresses = defaultAddrs.split(",");
// for (int i=0; i<targetAddresses.length; i++)
// targetAddresses[i] = targetAddresses[i].trim();
// emailEnabled = (from != null);
// } else {
// emailEnabled = false;
// }
// }
//
// @Override
// public void alert(Exception exception, String summary) {
//
// if (!emailEnabled) {
// System.err.println("Alert: "+summary);
// exception.printStackTrace();
// System.err.println("Can't email - not configured");
// return;
// }
//
// System.err.println("Emailing Alert: "+summary);
// exception.printStackTrace();
//
// try {
// SimpleEmail email = makeFailureEmail();
// StringBuilder msg = new StringBuilder(summary);
// msg.append("Exception:\n");
// StringWriter writer = new StringWriter();
// PrintWriter printWriter = new PrintWriter(writer);
// exception.printStackTrace(printWriter);
// msg.append(writer.toString());
// email.setMsg(msg.toString());
// email.send();
// } catch (EmailException e) {
// System.err.println("Can't send email!");
// e.printStackTrace();
// }
// }
//
// private SimpleEmail makeFailureEmail() throws EmailException {
// return makeEmail("Job Failure");
// }
//
// private SimpleEmail makeEmail(String title) throws EmailException {
// SimpleEmail email = new SimpleEmail();
// for (String targetAddress : targetAddresses)
// email.addTo(targetAddress);
// email.setSubject(title);
// email.setFrom(from);
// email.setHostName(host);
// return email;
// }
//
// @Override
// public void alert(List<PhaseError> errors) {
// System.err.format("%sAlert: can't run pipeline\n", emailEnabled ? "Emailing " : "");
// for (PhaseError e : errors) {
// System.err.println(e.getMessage());
// }
// if (!emailEnabled) {
// System.err.println("Can't email - not configured");
// return;
// }
//
// try {
// SimpleEmail email = makeFailureEmail();
// StringBuilder msg = new StringBuilder();
// for (PhaseError e : errors) {
// msg.append(e.getMessage()).append('\n');
// }
// email.setMsg(msg.toString());
// email.send();
// } catch (EmailException e) {
// System.err.println("Can't send email!");
// e.printStackTrace();
// }
// }
//
// @Override
// public void pipeCompletion(String pipeName, String summary) {
// System.out.println("Pipe completion: "+pipeName);
// System.out.println(summary);
// if (!emailEnabled) return;
//
// try {
// SimpleEmail email = makeEmail("Pipe completion: "+pipeName);
// email.setMsg(summary);
// email.send();
// }
// catch (EmailException e) {
// System.err.println("Can't send email!");
// e.printStackTrace();
// }
// }
//
// @Override
// public void alert(String problem) {
// PhaseError err = new PhaseError(problem);
// ArrayList<PhaseError> list = new ArrayList<PhaseError>(1);
// list.add(err);
// alert(list);
// }
//
// }
// Path: src/main/java/colossal/pipe/ColPipe.java
import java.net.URI;
import java.util.*;
import java.util.concurrent.*;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.mapred.JobConf;
import colossal.util.Alerter;
import colossal.util.EmailAlerter;
/*
* Licensed to Think Big Analytics, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Think Big Analytics, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2010 Think Big Analytics. All Rights Reserved.
*/
package colossal.pipe;
@SuppressWarnings("deprecation")
public class ColPipe {
private List<ColFile> writes;
private int parallelPhases = 2; // default to 2 phases at once - use concurrency (also speeds up local running)
private JobConf baseConf = new JobConf(); | private Alerter alerter = new EmailAlerter(); |
ThinkBigAnalytics/colossal-pipe | src/main/java/colossal/util/Alerter.java | // Path: src/main/java/colossal/pipe/PhaseError.java
// public class PhaseError {
// private String message;
// private Throwable exception;
//
// public PhaseError(String message) {
// this.message = message;
// this.exception = null;
// }
// public PhaseError(Throwable t, String processName) {
// this.message = "Failure running "+processName;
// this.exception = t;
// }
// public String getMessage() {
// return message;
// }
// public Throwable getException() {
// return exception;
// }
// }
| import java.util.List;
import colossal.pipe.PhaseError; | /*
* Licensed to Think Big Analytics, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Think Big Analytics, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2010 Think Big Analytics. All Rights Reserved.
*/
package colossal.util;
/**
* Interface used to generate job alerts.
*
* @author rbodkin
*
*/
public interface Alerter {
public void alert(Exception exception, String summary);
| // Path: src/main/java/colossal/pipe/PhaseError.java
// public class PhaseError {
// private String message;
// private Throwable exception;
//
// public PhaseError(String message) {
// this.message = message;
// this.exception = null;
// }
// public PhaseError(Throwable t, String processName) {
// this.message = "Failure running "+processName;
// this.exception = t;
// }
// public String getMessage() {
// return message;
// }
// public Throwable getException() {
// return exception;
// }
// }
// Path: src/main/java/colossal/util/Alerter.java
import java.util.List;
import colossal.pipe.PhaseError;
/*
* Licensed to Think Big Analytics, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Think Big Analytics, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2010 Think Big Analytics. All Rights Reserved.
*/
package colossal.util;
/**
* Interface used to generate job alerts.
*
* @author rbodkin
*
*/
public interface Alerter {
public void alert(Exception exception, String summary);
| public void alert(List<PhaseError> result); |
LucaScorpion/JavaRant | src/main/java/com/scorpiac/javarant/MinimalUser.java | // Path: src/main/java/com/scorpiac/javarant/services/RequestHandler.java
// @Singleton
// public class RequestHandler {
// public static final URI BASE_URI = URI.create("https://www.devrant.io");
// public static final URI AVATARS_URI = URI.create("https://avatars.devrant.io");
//
// private static final String APP_ID = "3";
// private static final String PLAT_ID = "3";
//
// private final ObjectMapperResponseHandlerFactory responseHandlerFactory;
//
// private int timeout = 15000;
//
// @Inject
// RequestHandler(ObjectMapperResponseHandlerFactory responseHandlerFactory) {
// this.responseHandlerFactory = responseHandlerFactory;
// }
//
// public <T, R extends Response<T>> R get(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) {
// return get(endpoint.toString(), clazz, params);
// }
//
// public <T, R extends Response<T>> R get(String endpoint, Class<R> clazz, NameValuePair... params) {
// return handleRequest(
// buildRequest(endpoint, Request::Get, getParameters(params)),
// clazz
// );
// }
//
// public <T, R extends Response<T>> R post(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) {
// return post(endpoint.toString(), clazz, params);
// }
//
// public <T, R extends Response<T>> R post(String endpoint, Class<R> clazz, NameValuePair... params) {
// return handleRequest(
// buildRequest(endpoint, Request::Post, Collections.emptyList()).bodyForm(getParameters(params)),
// clazz
// );
// }
//
// /**
// * Build a request.
// *
// * @param endpoint The endpoint to make the request to.
// * @param requestFunction The function to create a new request from a URI.
// * @param params The request parameters.
// * @return A request.
// */
// private Request buildRequest(String endpoint, Function<URI, Request> requestFunction, List<NameValuePair> params) {
// URI uri;
//
// try {
// // Build the URI.
// uri = new URIBuilder(resolve(endpoint))
// .addParameters(params)
// .build();
// } catch (URISyntaxException e) {
// // This never happens.
// throw new IllegalArgumentException("Could not build URI.", e);
// }
//
// return requestFunction.apply(uri)
// .connectTimeout(timeout)
// .socketTimeout(timeout);
// }
//
// /**
// * Resolve an endpoint to a URI.
// * This method's main purpose is to be overridden for the tests.
// *
// * @param endpoint The endpoint to resolve.
// * @return A complete URI.
// */
// URI resolve(String endpoint) {
// return BASE_URI.resolve(endpoint);
// }
//
// /**
// * Handle a request.
// *
// * @param request The request to handle.
// * @param clazz The class to map the response to.
// * @param <T> The type of the class to use in the result.
// * @param <R> The type of the class to map the internal response to.
// * @return The mapped response.
// */
// // This is because of the last line, which cannot be checked. Just make sure it is tested properly.
// @SuppressWarnings("unchecked")
// private <T, R extends Response<T>> R handleRequest(Request request, Class<R> clazz) {
// R response;
// try {
// response = request.execute().handleResponse(responseHandlerFactory.getResponseHandler(clazz));
// } catch (IOException e) {
// throw new DevRantException("Failed to execute request.", e);
// }
//
// return response;
// }
//
// /**
// * Get a list with all the parameters, including default and auth parameters.
// * This also filters out any parameters that are {@code null}.
// *
// * @param params The parameters to use.
// * @return A list containing the given and default parameters.
// */
// private List<NameValuePair> getParameters(NameValuePair... params) {
// List<NameValuePair> paramList = new ArrayList<>();
//
// // Add all non-null parameters.
// paramList.addAll(
// Arrays.stream(params)
// .filter(Objects::nonNull)
// .collect(Collectors.toList())
// );
//
// // Add the parameters which always need to be present.
// paramList.add(new BasicNameValuePair("app", APP_ID));
// paramList.add(new BasicNameValuePair("plat", PLAT_ID));
//
// return paramList;
// }
//
// /**
// * Set the request timeout.
// * This timeout will be used for the socket and connection timeout.
// *
// * @param timeout The timeout in milliseconds to set, or -1 to set no timeout.
// */
// public void setRequestTimeout(int timeout) {
// this.timeout = timeout;
// }
//
// /**
// * Get the current request timeout in milliseconds, or -1 if there is no timeout.
// *
// * @return The request timeout.
// */
// public int getRequestTimeout() {
// return timeout;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.scorpiac.javarant.services.RequestHandler;
import java.net.URI; | * @return The user id.
*/
public int getId() {
return id;
}
/**
* Get the username.
*
* @return The username.
*/
public String getUsername() {
return username;
}
/**
* Get the user's overall score.
*
* @return The score.
*/
public int getScore() {
return score;
}
/**
* Get the link to the user's profile.
*
* @return The link to the user's profile.
*/
public URI getLink() { | // Path: src/main/java/com/scorpiac/javarant/services/RequestHandler.java
// @Singleton
// public class RequestHandler {
// public static final URI BASE_URI = URI.create("https://www.devrant.io");
// public static final URI AVATARS_URI = URI.create("https://avatars.devrant.io");
//
// private static final String APP_ID = "3";
// private static final String PLAT_ID = "3";
//
// private final ObjectMapperResponseHandlerFactory responseHandlerFactory;
//
// private int timeout = 15000;
//
// @Inject
// RequestHandler(ObjectMapperResponseHandlerFactory responseHandlerFactory) {
// this.responseHandlerFactory = responseHandlerFactory;
// }
//
// public <T, R extends Response<T>> R get(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) {
// return get(endpoint.toString(), clazz, params);
// }
//
// public <T, R extends Response<T>> R get(String endpoint, Class<R> clazz, NameValuePair... params) {
// return handleRequest(
// buildRequest(endpoint, Request::Get, getParameters(params)),
// clazz
// );
// }
//
// public <T, R extends Response<T>> R post(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) {
// return post(endpoint.toString(), clazz, params);
// }
//
// public <T, R extends Response<T>> R post(String endpoint, Class<R> clazz, NameValuePair... params) {
// return handleRequest(
// buildRequest(endpoint, Request::Post, Collections.emptyList()).bodyForm(getParameters(params)),
// clazz
// );
// }
//
// /**
// * Build a request.
// *
// * @param endpoint The endpoint to make the request to.
// * @param requestFunction The function to create a new request from a URI.
// * @param params The request parameters.
// * @return A request.
// */
// private Request buildRequest(String endpoint, Function<URI, Request> requestFunction, List<NameValuePair> params) {
// URI uri;
//
// try {
// // Build the URI.
// uri = new URIBuilder(resolve(endpoint))
// .addParameters(params)
// .build();
// } catch (URISyntaxException e) {
// // This never happens.
// throw new IllegalArgumentException("Could not build URI.", e);
// }
//
// return requestFunction.apply(uri)
// .connectTimeout(timeout)
// .socketTimeout(timeout);
// }
//
// /**
// * Resolve an endpoint to a URI.
// * This method's main purpose is to be overridden for the tests.
// *
// * @param endpoint The endpoint to resolve.
// * @return A complete URI.
// */
// URI resolve(String endpoint) {
// return BASE_URI.resolve(endpoint);
// }
//
// /**
// * Handle a request.
// *
// * @param request The request to handle.
// * @param clazz The class to map the response to.
// * @param <T> The type of the class to use in the result.
// * @param <R> The type of the class to map the internal response to.
// * @return The mapped response.
// */
// // This is because of the last line, which cannot be checked. Just make sure it is tested properly.
// @SuppressWarnings("unchecked")
// private <T, R extends Response<T>> R handleRequest(Request request, Class<R> clazz) {
// R response;
// try {
// response = request.execute().handleResponse(responseHandlerFactory.getResponseHandler(clazz));
// } catch (IOException e) {
// throw new DevRantException("Failed to execute request.", e);
// }
//
// return response;
// }
//
// /**
// * Get a list with all the parameters, including default and auth parameters.
// * This also filters out any parameters that are {@code null}.
// *
// * @param params The parameters to use.
// * @return A list containing the given and default parameters.
// */
// private List<NameValuePair> getParameters(NameValuePair... params) {
// List<NameValuePair> paramList = new ArrayList<>();
//
// // Add all non-null parameters.
// paramList.addAll(
// Arrays.stream(params)
// .filter(Objects::nonNull)
// .collect(Collectors.toList())
// );
//
// // Add the parameters which always need to be present.
// paramList.add(new BasicNameValuePair("app", APP_ID));
// paramList.add(new BasicNameValuePair("plat", PLAT_ID));
//
// return paramList;
// }
//
// /**
// * Set the request timeout.
// * This timeout will be used for the socket and connection timeout.
// *
// * @param timeout The timeout in milliseconds to set, or -1 to set no timeout.
// */
// public void setRequestTimeout(int timeout) {
// this.timeout = timeout;
// }
//
// /**
// * Get the current request timeout in milliseconds, or -1 if there is no timeout.
// *
// * @return The request timeout.
// */
// public int getRequestTimeout() {
// return timeout;
// }
// }
// Path: src/main/java/com/scorpiac/javarant/MinimalUser.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.scorpiac.javarant.services.RequestHandler;
import java.net.URI;
* @return The user id.
*/
public int getId() {
return id;
}
/**
* Get the username.
*
* @return The username.
*/
public String getUsername() {
return username;
}
/**
* Get the user's overall score.
*
* @return The score.
*/
public int getScore() {
return score;
}
/**
* Get the link to the user's profile.
*
* @return The link to the user's profile.
*/
public URI getLink() { | return RequestHandler.BASE_URI.resolve("/users").resolve(username); |
LucaScorpion/JavaRant | src/main/java/com/scorpiac/javarant/services/RequestHandler.java | // Path: src/main/java/com/scorpiac/javarant/ApiEndpoint.java
// public enum ApiEndpoint {
// API("/api"),
// API_DEVRANT(API, "devrant"),
// COMMENTS(API, "comments"),
// VOTE("vote"),
// // Rants.
// RANTS(API_DEVRANT, "rants"),
// SURPRISE(RANTS, "surprise"),
// SEARCH(API_DEVRANT, "search"),
// WEEKLY(API_DEVRANT, "weekly-rants"),
// STORIES(API_DEVRANT, "story-rants"),
// COLLABS(API_DEVRANT, "collabs"),
// // Users.
// USER_ID(API, "get-user-id"),
// USERS(API, "users"),
// AUTH_TOKEN(USERS, "auth-token");
//
// private final String endpoint;
//
// ApiEndpoint(String endpoint) {
// this.endpoint = endpoint;
// }
//
// ApiEndpoint(ApiEndpoint base, String endpoint) {
// this(base.toString() + '/' + endpoint);
// }
//
// @Override
// public String toString() {
// return endpoint;
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/DevRantException.java
// public class DevRantException extends RuntimeException {
// public DevRantException(String message) {
// super(message);
// }
//
// public DevRantException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/Response.java
// public abstract class Response<T> {
// @JsonProperty
// private boolean success;
// @JsonProperty
// private String error;
//
// // The actual result value.
// T value;
//
// /**
// * Get the error message.
// *
// * @return The error message.
// */
// public String getError() {
// return error != null ? error : "An unknown error occurred.";
// }
//
// /**
// * Get the result value.
// *
// * @return An optional containing the result value.
// */
// public Optional<T> getValue() {
// return Optional.ofNullable(value);
// }
//
// public T getValueOrError() {
// if (!success) {
// throw new DevRantApiException(error);
// }
// return value;
// }
// }
| import com.scorpiac.javarant.ApiEndpoint;
import com.scorpiac.javarant.DevRantException;
import com.scorpiac.javarant.responses.Response;
import org.apache.http.NameValuePair;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors; | package com.scorpiac.javarant.services;
@Singleton
public class RequestHandler {
public static final URI BASE_URI = URI.create("https://www.devrant.io");
public static final URI AVATARS_URI = URI.create("https://avatars.devrant.io");
private static final String APP_ID = "3";
private static final String PLAT_ID = "3";
private final ObjectMapperResponseHandlerFactory responseHandlerFactory;
private int timeout = 15000;
@Inject
RequestHandler(ObjectMapperResponseHandlerFactory responseHandlerFactory) {
this.responseHandlerFactory = responseHandlerFactory;
}
| // Path: src/main/java/com/scorpiac/javarant/ApiEndpoint.java
// public enum ApiEndpoint {
// API("/api"),
// API_DEVRANT(API, "devrant"),
// COMMENTS(API, "comments"),
// VOTE("vote"),
// // Rants.
// RANTS(API_DEVRANT, "rants"),
// SURPRISE(RANTS, "surprise"),
// SEARCH(API_DEVRANT, "search"),
// WEEKLY(API_DEVRANT, "weekly-rants"),
// STORIES(API_DEVRANT, "story-rants"),
// COLLABS(API_DEVRANT, "collabs"),
// // Users.
// USER_ID(API, "get-user-id"),
// USERS(API, "users"),
// AUTH_TOKEN(USERS, "auth-token");
//
// private final String endpoint;
//
// ApiEndpoint(String endpoint) {
// this.endpoint = endpoint;
// }
//
// ApiEndpoint(ApiEndpoint base, String endpoint) {
// this(base.toString() + '/' + endpoint);
// }
//
// @Override
// public String toString() {
// return endpoint;
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/DevRantException.java
// public class DevRantException extends RuntimeException {
// public DevRantException(String message) {
// super(message);
// }
//
// public DevRantException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/Response.java
// public abstract class Response<T> {
// @JsonProperty
// private boolean success;
// @JsonProperty
// private String error;
//
// // The actual result value.
// T value;
//
// /**
// * Get the error message.
// *
// * @return The error message.
// */
// public String getError() {
// return error != null ? error : "An unknown error occurred.";
// }
//
// /**
// * Get the result value.
// *
// * @return An optional containing the result value.
// */
// public Optional<T> getValue() {
// return Optional.ofNullable(value);
// }
//
// public T getValueOrError() {
// if (!success) {
// throw new DevRantApiException(error);
// }
// return value;
// }
// }
// Path: src/main/java/com/scorpiac/javarant/services/RequestHandler.java
import com.scorpiac.javarant.ApiEndpoint;
import com.scorpiac.javarant.DevRantException;
import com.scorpiac.javarant.responses.Response;
import org.apache.http.NameValuePair;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
package com.scorpiac.javarant.services;
@Singleton
public class RequestHandler {
public static final URI BASE_URI = URI.create("https://www.devrant.io");
public static final URI AVATARS_URI = URI.create("https://avatars.devrant.io");
private static final String APP_ID = "3";
private static final String PLAT_ID = "3";
private final ObjectMapperResponseHandlerFactory responseHandlerFactory;
private int timeout = 15000;
@Inject
RequestHandler(ObjectMapperResponseHandlerFactory responseHandlerFactory) {
this.responseHandlerFactory = responseHandlerFactory;
}
| public <T, R extends Response<T>> R get(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) { |
LucaScorpion/JavaRant | src/main/java/com/scorpiac/javarant/services/RequestHandler.java | // Path: src/main/java/com/scorpiac/javarant/ApiEndpoint.java
// public enum ApiEndpoint {
// API("/api"),
// API_DEVRANT(API, "devrant"),
// COMMENTS(API, "comments"),
// VOTE("vote"),
// // Rants.
// RANTS(API_DEVRANT, "rants"),
// SURPRISE(RANTS, "surprise"),
// SEARCH(API_DEVRANT, "search"),
// WEEKLY(API_DEVRANT, "weekly-rants"),
// STORIES(API_DEVRANT, "story-rants"),
// COLLABS(API_DEVRANT, "collabs"),
// // Users.
// USER_ID(API, "get-user-id"),
// USERS(API, "users"),
// AUTH_TOKEN(USERS, "auth-token");
//
// private final String endpoint;
//
// ApiEndpoint(String endpoint) {
// this.endpoint = endpoint;
// }
//
// ApiEndpoint(ApiEndpoint base, String endpoint) {
// this(base.toString() + '/' + endpoint);
// }
//
// @Override
// public String toString() {
// return endpoint;
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/DevRantException.java
// public class DevRantException extends RuntimeException {
// public DevRantException(String message) {
// super(message);
// }
//
// public DevRantException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/Response.java
// public abstract class Response<T> {
// @JsonProperty
// private boolean success;
// @JsonProperty
// private String error;
//
// // The actual result value.
// T value;
//
// /**
// * Get the error message.
// *
// * @return The error message.
// */
// public String getError() {
// return error != null ? error : "An unknown error occurred.";
// }
//
// /**
// * Get the result value.
// *
// * @return An optional containing the result value.
// */
// public Optional<T> getValue() {
// return Optional.ofNullable(value);
// }
//
// public T getValueOrError() {
// if (!success) {
// throw new DevRantApiException(error);
// }
// return value;
// }
// }
| import com.scorpiac.javarant.ApiEndpoint;
import com.scorpiac.javarant.DevRantException;
import com.scorpiac.javarant.responses.Response;
import org.apache.http.NameValuePair;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors; | package com.scorpiac.javarant.services;
@Singleton
public class RequestHandler {
public static final URI BASE_URI = URI.create("https://www.devrant.io");
public static final URI AVATARS_URI = URI.create("https://avatars.devrant.io");
private static final String APP_ID = "3";
private static final String PLAT_ID = "3";
private final ObjectMapperResponseHandlerFactory responseHandlerFactory;
private int timeout = 15000;
@Inject
RequestHandler(ObjectMapperResponseHandlerFactory responseHandlerFactory) {
this.responseHandlerFactory = responseHandlerFactory;
}
| // Path: src/main/java/com/scorpiac/javarant/ApiEndpoint.java
// public enum ApiEndpoint {
// API("/api"),
// API_DEVRANT(API, "devrant"),
// COMMENTS(API, "comments"),
// VOTE("vote"),
// // Rants.
// RANTS(API_DEVRANT, "rants"),
// SURPRISE(RANTS, "surprise"),
// SEARCH(API_DEVRANT, "search"),
// WEEKLY(API_DEVRANT, "weekly-rants"),
// STORIES(API_DEVRANT, "story-rants"),
// COLLABS(API_DEVRANT, "collabs"),
// // Users.
// USER_ID(API, "get-user-id"),
// USERS(API, "users"),
// AUTH_TOKEN(USERS, "auth-token");
//
// private final String endpoint;
//
// ApiEndpoint(String endpoint) {
// this.endpoint = endpoint;
// }
//
// ApiEndpoint(ApiEndpoint base, String endpoint) {
// this(base.toString() + '/' + endpoint);
// }
//
// @Override
// public String toString() {
// return endpoint;
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/DevRantException.java
// public class DevRantException extends RuntimeException {
// public DevRantException(String message) {
// super(message);
// }
//
// public DevRantException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/Response.java
// public abstract class Response<T> {
// @JsonProperty
// private boolean success;
// @JsonProperty
// private String error;
//
// // The actual result value.
// T value;
//
// /**
// * Get the error message.
// *
// * @return The error message.
// */
// public String getError() {
// return error != null ? error : "An unknown error occurred.";
// }
//
// /**
// * Get the result value.
// *
// * @return An optional containing the result value.
// */
// public Optional<T> getValue() {
// return Optional.ofNullable(value);
// }
//
// public T getValueOrError() {
// if (!success) {
// throw new DevRantApiException(error);
// }
// return value;
// }
// }
// Path: src/main/java/com/scorpiac/javarant/services/RequestHandler.java
import com.scorpiac.javarant.ApiEndpoint;
import com.scorpiac.javarant.DevRantException;
import com.scorpiac.javarant.responses.Response;
import org.apache.http.NameValuePair;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
package com.scorpiac.javarant.services;
@Singleton
public class RequestHandler {
public static final URI BASE_URI = URI.create("https://www.devrant.io");
public static final URI AVATARS_URI = URI.create("https://avatars.devrant.io");
private static final String APP_ID = "3";
private static final String PLAT_ID = "3";
private final ObjectMapperResponseHandlerFactory responseHandlerFactory;
private int timeout = 15000;
@Inject
RequestHandler(ObjectMapperResponseHandlerFactory responseHandlerFactory) {
this.responseHandlerFactory = responseHandlerFactory;
}
| public <T, R extends Response<T>> R get(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) { |
LucaScorpion/JavaRant | src/main/java/com/scorpiac/javarant/services/RequestHandler.java | // Path: src/main/java/com/scorpiac/javarant/ApiEndpoint.java
// public enum ApiEndpoint {
// API("/api"),
// API_DEVRANT(API, "devrant"),
// COMMENTS(API, "comments"),
// VOTE("vote"),
// // Rants.
// RANTS(API_DEVRANT, "rants"),
// SURPRISE(RANTS, "surprise"),
// SEARCH(API_DEVRANT, "search"),
// WEEKLY(API_DEVRANT, "weekly-rants"),
// STORIES(API_DEVRANT, "story-rants"),
// COLLABS(API_DEVRANT, "collabs"),
// // Users.
// USER_ID(API, "get-user-id"),
// USERS(API, "users"),
// AUTH_TOKEN(USERS, "auth-token");
//
// private final String endpoint;
//
// ApiEndpoint(String endpoint) {
// this.endpoint = endpoint;
// }
//
// ApiEndpoint(ApiEndpoint base, String endpoint) {
// this(base.toString() + '/' + endpoint);
// }
//
// @Override
// public String toString() {
// return endpoint;
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/DevRantException.java
// public class DevRantException extends RuntimeException {
// public DevRantException(String message) {
// super(message);
// }
//
// public DevRantException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/Response.java
// public abstract class Response<T> {
// @JsonProperty
// private boolean success;
// @JsonProperty
// private String error;
//
// // The actual result value.
// T value;
//
// /**
// * Get the error message.
// *
// * @return The error message.
// */
// public String getError() {
// return error != null ? error : "An unknown error occurred.";
// }
//
// /**
// * Get the result value.
// *
// * @return An optional containing the result value.
// */
// public Optional<T> getValue() {
// return Optional.ofNullable(value);
// }
//
// public T getValueOrError() {
// if (!success) {
// throw new DevRantApiException(error);
// }
// return value;
// }
// }
| import com.scorpiac.javarant.ApiEndpoint;
import com.scorpiac.javarant.DevRantException;
import com.scorpiac.javarant.responses.Response;
import org.apache.http.NameValuePair;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors; | .socketTimeout(timeout);
}
/**
* Resolve an endpoint to a URI.
* This method's main purpose is to be overridden for the tests.
*
* @param endpoint The endpoint to resolve.
* @return A complete URI.
*/
URI resolve(String endpoint) {
return BASE_URI.resolve(endpoint);
}
/**
* Handle a request.
*
* @param request The request to handle.
* @param clazz The class to map the response to.
* @param <T> The type of the class to use in the result.
* @param <R> The type of the class to map the internal response to.
* @return The mapped response.
*/
// This is because of the last line, which cannot be checked. Just make sure it is tested properly.
@SuppressWarnings("unchecked")
private <T, R extends Response<T>> R handleRequest(Request request, Class<R> clazz) {
R response;
try {
response = request.execute().handleResponse(responseHandlerFactory.getResponseHandler(clazz));
} catch (IOException e) { | // Path: src/main/java/com/scorpiac/javarant/ApiEndpoint.java
// public enum ApiEndpoint {
// API("/api"),
// API_DEVRANT(API, "devrant"),
// COMMENTS(API, "comments"),
// VOTE("vote"),
// // Rants.
// RANTS(API_DEVRANT, "rants"),
// SURPRISE(RANTS, "surprise"),
// SEARCH(API_DEVRANT, "search"),
// WEEKLY(API_DEVRANT, "weekly-rants"),
// STORIES(API_DEVRANT, "story-rants"),
// COLLABS(API_DEVRANT, "collabs"),
// // Users.
// USER_ID(API, "get-user-id"),
// USERS(API, "users"),
// AUTH_TOKEN(USERS, "auth-token");
//
// private final String endpoint;
//
// ApiEndpoint(String endpoint) {
// this.endpoint = endpoint;
// }
//
// ApiEndpoint(ApiEndpoint base, String endpoint) {
// this(base.toString() + '/' + endpoint);
// }
//
// @Override
// public String toString() {
// return endpoint;
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/DevRantException.java
// public class DevRantException extends RuntimeException {
// public DevRantException(String message) {
// super(message);
// }
//
// public DevRantException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/Response.java
// public abstract class Response<T> {
// @JsonProperty
// private boolean success;
// @JsonProperty
// private String error;
//
// // The actual result value.
// T value;
//
// /**
// * Get the error message.
// *
// * @return The error message.
// */
// public String getError() {
// return error != null ? error : "An unknown error occurred.";
// }
//
// /**
// * Get the result value.
// *
// * @return An optional containing the result value.
// */
// public Optional<T> getValue() {
// return Optional.ofNullable(value);
// }
//
// public T getValueOrError() {
// if (!success) {
// throw new DevRantApiException(error);
// }
// return value;
// }
// }
// Path: src/main/java/com/scorpiac/javarant/services/RequestHandler.java
import com.scorpiac.javarant.ApiEndpoint;
import com.scorpiac.javarant.DevRantException;
import com.scorpiac.javarant.responses.Response;
import org.apache.http.NameValuePair;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
.socketTimeout(timeout);
}
/**
* Resolve an endpoint to a URI.
* This method's main purpose is to be overridden for the tests.
*
* @param endpoint The endpoint to resolve.
* @return A complete URI.
*/
URI resolve(String endpoint) {
return BASE_URI.resolve(endpoint);
}
/**
* Handle a request.
*
* @param request The request to handle.
* @param clazz The class to map the response to.
* @param <T> The type of the class to use in the result.
* @param <R> The type of the class to map the internal response to.
* @return The mapped response.
*/
// This is because of the last line, which cannot be checked. Just make sure it is tested properly.
@SuppressWarnings("unchecked")
private <T, R extends Response<T>> R handleRequest(Request request, Class<R> clazz) {
R response;
try {
response = request.execute().handleResponse(responseHandlerFactory.getResponseHandler(clazz));
} catch (IOException e) { | throw new DevRantException("Failed to execute request.", e); |
LucaScorpion/JavaRant | src/main/java/com/scorpiac/javarant/Rant.java | // Path: src/main/java/com/scorpiac/javarant/services/RequestHandler.java
// @Singleton
// public class RequestHandler {
// public static final URI BASE_URI = URI.create("https://www.devrant.io");
// public static final URI AVATARS_URI = URI.create("https://avatars.devrant.io");
//
// private static final String APP_ID = "3";
// private static final String PLAT_ID = "3";
//
// private final ObjectMapperResponseHandlerFactory responseHandlerFactory;
//
// private int timeout = 15000;
//
// @Inject
// RequestHandler(ObjectMapperResponseHandlerFactory responseHandlerFactory) {
// this.responseHandlerFactory = responseHandlerFactory;
// }
//
// public <T, R extends Response<T>> R get(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) {
// return get(endpoint.toString(), clazz, params);
// }
//
// public <T, R extends Response<T>> R get(String endpoint, Class<R> clazz, NameValuePair... params) {
// return handleRequest(
// buildRequest(endpoint, Request::Get, getParameters(params)),
// clazz
// );
// }
//
// public <T, R extends Response<T>> R post(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) {
// return post(endpoint.toString(), clazz, params);
// }
//
// public <T, R extends Response<T>> R post(String endpoint, Class<R> clazz, NameValuePair... params) {
// return handleRequest(
// buildRequest(endpoint, Request::Post, Collections.emptyList()).bodyForm(getParameters(params)),
// clazz
// );
// }
//
// /**
// * Build a request.
// *
// * @param endpoint The endpoint to make the request to.
// * @param requestFunction The function to create a new request from a URI.
// * @param params The request parameters.
// * @return A request.
// */
// private Request buildRequest(String endpoint, Function<URI, Request> requestFunction, List<NameValuePair> params) {
// URI uri;
//
// try {
// // Build the URI.
// uri = new URIBuilder(resolve(endpoint))
// .addParameters(params)
// .build();
// } catch (URISyntaxException e) {
// // This never happens.
// throw new IllegalArgumentException("Could not build URI.", e);
// }
//
// return requestFunction.apply(uri)
// .connectTimeout(timeout)
// .socketTimeout(timeout);
// }
//
// /**
// * Resolve an endpoint to a URI.
// * This method's main purpose is to be overridden for the tests.
// *
// * @param endpoint The endpoint to resolve.
// * @return A complete URI.
// */
// URI resolve(String endpoint) {
// return BASE_URI.resolve(endpoint);
// }
//
// /**
// * Handle a request.
// *
// * @param request The request to handle.
// * @param clazz The class to map the response to.
// * @param <T> The type of the class to use in the result.
// * @param <R> The type of the class to map the internal response to.
// * @return The mapped response.
// */
// // This is because of the last line, which cannot be checked. Just make sure it is tested properly.
// @SuppressWarnings("unchecked")
// private <T, R extends Response<T>> R handleRequest(Request request, Class<R> clazz) {
// R response;
// try {
// response = request.execute().handleResponse(responseHandlerFactory.getResponseHandler(clazz));
// } catch (IOException e) {
// throw new DevRantException("Failed to execute request.", e);
// }
//
// return response;
// }
//
// /**
// * Get a list with all the parameters, including default and auth parameters.
// * This also filters out any parameters that are {@code null}.
// *
// * @param params The parameters to use.
// * @return A list containing the given and default parameters.
// */
// private List<NameValuePair> getParameters(NameValuePair... params) {
// List<NameValuePair> paramList = new ArrayList<>();
//
// // Add all non-null parameters.
// paramList.addAll(
// Arrays.stream(params)
// .filter(Objects::nonNull)
// .collect(Collectors.toList())
// );
//
// // Add the parameters which always need to be present.
// paramList.add(new BasicNameValuePair("app", APP_ID));
// paramList.add(new BasicNameValuePair("plat", PLAT_ID));
//
// return paramList;
// }
//
// /**
// * Set the request timeout.
// * This timeout will be used for the socket and connection timeout.
// *
// * @param timeout The timeout in milliseconds to set, or -1 to set no timeout.
// */
// public void setRequestTimeout(int timeout) {
// this.timeout = timeout;
// }
//
// /**
// * Get the current request timeout in milliseconds, or -1 if there is no timeout.
// *
// * @return The request timeout.
// */
// public int getRequestTimeout() {
// return timeout;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.scorpiac.javarant.services.RequestHandler;
import java.net.URI;
import java.util.Collections;
import java.util.List; | package com.scorpiac.javarant;
public class Rant extends RantContent {
@JsonProperty
private List<String> tags;
@JsonProperty("num_comments")
private int commentCount;
@Override
public boolean equals(Object obj) {
return super.equals(obj) && obj instanceof Rant;
}
/**
* Get the link to the rant.
*
* @return The link to the rant.
*/
public URI getLink() { | // Path: src/main/java/com/scorpiac/javarant/services/RequestHandler.java
// @Singleton
// public class RequestHandler {
// public static final URI BASE_URI = URI.create("https://www.devrant.io");
// public static final URI AVATARS_URI = URI.create("https://avatars.devrant.io");
//
// private static final String APP_ID = "3";
// private static final String PLAT_ID = "3";
//
// private final ObjectMapperResponseHandlerFactory responseHandlerFactory;
//
// private int timeout = 15000;
//
// @Inject
// RequestHandler(ObjectMapperResponseHandlerFactory responseHandlerFactory) {
// this.responseHandlerFactory = responseHandlerFactory;
// }
//
// public <T, R extends Response<T>> R get(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) {
// return get(endpoint.toString(), clazz, params);
// }
//
// public <T, R extends Response<T>> R get(String endpoint, Class<R> clazz, NameValuePair... params) {
// return handleRequest(
// buildRequest(endpoint, Request::Get, getParameters(params)),
// clazz
// );
// }
//
// public <T, R extends Response<T>> R post(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) {
// return post(endpoint.toString(), clazz, params);
// }
//
// public <T, R extends Response<T>> R post(String endpoint, Class<R> clazz, NameValuePair... params) {
// return handleRequest(
// buildRequest(endpoint, Request::Post, Collections.emptyList()).bodyForm(getParameters(params)),
// clazz
// );
// }
//
// /**
// * Build a request.
// *
// * @param endpoint The endpoint to make the request to.
// * @param requestFunction The function to create a new request from a URI.
// * @param params The request parameters.
// * @return A request.
// */
// private Request buildRequest(String endpoint, Function<URI, Request> requestFunction, List<NameValuePair> params) {
// URI uri;
//
// try {
// // Build the URI.
// uri = new URIBuilder(resolve(endpoint))
// .addParameters(params)
// .build();
// } catch (URISyntaxException e) {
// // This never happens.
// throw new IllegalArgumentException("Could not build URI.", e);
// }
//
// return requestFunction.apply(uri)
// .connectTimeout(timeout)
// .socketTimeout(timeout);
// }
//
// /**
// * Resolve an endpoint to a URI.
// * This method's main purpose is to be overridden for the tests.
// *
// * @param endpoint The endpoint to resolve.
// * @return A complete URI.
// */
// URI resolve(String endpoint) {
// return BASE_URI.resolve(endpoint);
// }
//
// /**
// * Handle a request.
// *
// * @param request The request to handle.
// * @param clazz The class to map the response to.
// * @param <T> The type of the class to use in the result.
// * @param <R> The type of the class to map the internal response to.
// * @return The mapped response.
// */
// // This is because of the last line, which cannot be checked. Just make sure it is tested properly.
// @SuppressWarnings("unchecked")
// private <T, R extends Response<T>> R handleRequest(Request request, Class<R> clazz) {
// R response;
// try {
// response = request.execute().handleResponse(responseHandlerFactory.getResponseHandler(clazz));
// } catch (IOException e) {
// throw new DevRantException("Failed to execute request.", e);
// }
//
// return response;
// }
//
// /**
// * Get a list with all the parameters, including default and auth parameters.
// * This also filters out any parameters that are {@code null}.
// *
// * @param params The parameters to use.
// * @return A list containing the given and default parameters.
// */
// private List<NameValuePair> getParameters(NameValuePair... params) {
// List<NameValuePair> paramList = new ArrayList<>();
//
// // Add all non-null parameters.
// paramList.addAll(
// Arrays.stream(params)
// .filter(Objects::nonNull)
// .collect(Collectors.toList())
// );
//
// // Add the parameters which always need to be present.
// paramList.add(new BasicNameValuePair("app", APP_ID));
// paramList.add(new BasicNameValuePair("plat", PLAT_ID));
//
// return paramList;
// }
//
// /**
// * Set the request timeout.
// * This timeout will be used for the socket and connection timeout.
// *
// * @param timeout The timeout in milliseconds to set, or -1 to set no timeout.
// */
// public void setRequestTimeout(int timeout) {
// this.timeout = timeout;
// }
//
// /**
// * Get the current request timeout in milliseconds, or -1 if there is no timeout.
// *
// * @return The request timeout.
// */
// public int getRequestTimeout() {
// return timeout;
// }
// }
// Path: src/main/java/com/scorpiac/javarant/Rant.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.scorpiac.javarant.services.RequestHandler;
import java.net.URI;
import java.util.Collections;
import java.util.List;
package com.scorpiac.javarant;
public class Rant extends RantContent {
@JsonProperty
private List<String> tags;
@JsonProperty("num_comments")
private int commentCount;
@Override
public boolean equals(Object obj) {
return super.equals(obj) && obj instanceof Rant;
}
/**
* Get the link to the rant.
*
* @return The link to the rant.
*/
public URI getLink() { | return RequestHandler.BASE_URI.resolve("/rants/" + getId()); |
LucaScorpion/JavaRant | src/test/java/com/scorpiac/javarant/ITHelper.java | // Path: src/test/java/com/scorpiac/javarant/services/MockRequestHandler.java
// public class MockRequestHandler extends RequestHandler {
// private final URI local;
//
// public MockRequestHandler(int port) {
// super(new ObjectMapperResponseHandlerFactory(new ObjectMapperService()));
// local = URI.create("http://localhost:" + port);
// }
//
// @Override
// URI resolve(String endpoint) {
// return local.resolve(endpoint);
// }
// }
| import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.MappingBuilder;
import com.scorpiac.javarant.services.MockRequestHandler;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import java.io.IOException;
import java.util.Scanner;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; | package com.scorpiac.javarant;
public abstract class ITHelper extends TestHelper {
protected WireMockServer server;
protected DevRant devRant;
@BeforeClass
public void beforeClass() {
server = new WireMockServer(
options()
.dynamicPort()
);
server.start();
devRant = new DevRant(); | // Path: src/test/java/com/scorpiac/javarant/services/MockRequestHandler.java
// public class MockRequestHandler extends RequestHandler {
// private final URI local;
//
// public MockRequestHandler(int port) {
// super(new ObjectMapperResponseHandlerFactory(new ObjectMapperService()));
// local = URI.create("http://localhost:" + port);
// }
//
// @Override
// URI resolve(String endpoint) {
// return local.resolve(endpoint);
// }
// }
// Path: src/test/java/com/scorpiac/javarant/ITHelper.java
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.MappingBuilder;
import com.scorpiac.javarant.services.MockRequestHandler;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import java.io.IOException;
import java.util.Scanner;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
package com.scorpiac.javarant;
public abstract class ITHelper extends TestHelper {
protected WireMockServer server;
protected DevRant devRant;
@BeforeClass
public void beforeClass() {
server = new WireMockServer(
options()
.dynamicPort()
);
server.start();
devRant = new DevRant(); | devRant.setRequestHandler(new MockRequestHandler(server.port())); |
LucaScorpion/JavaRant | src/main/java/com/scorpiac/javarant/responses/AbstractRantsFeedResponse.java | // Path: src/main/java/com/scorpiac/javarant/News.java
// public class News {
// @JsonProperty
// private int id;
// @JsonProperty
// private String headline;
// @JsonProperty
// private String body;
// @JsonProperty
// private String footer;
//
// @Override
// public String toString() {
// return headline + '\n' + body + '\n' + footer;
// }
//
// @Override
// public int hashCode() {
// return id;
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj instanceof News && ((News) obj).id == id;
// }
//
// /**
// * Get the id.
// *
// * @return The id.
// */
// public int getId() {
// return id;
// }
//
// /**
// * Get the headline.
// *
// * @return The headline.
// */
// public String getHeadline() {
// return headline;
// }
//
// /**
// * Get the body text.
// *
// * @return The body.
// */
// public String getBody() {
// return body;
// }
//
// /**
// * Get the footer.
// *
// * @return The footer.
// */
// public String getFooter() {
// return footer;
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/Rant.java
// public class Rant extends RantContent {
// @JsonProperty
// private List<String> tags;
// @JsonProperty("num_comments")
// private int commentCount;
//
// @Override
// public boolean equals(Object obj) {
// return super.equals(obj) && obj instanceof Rant;
// }
//
// /**
// * Get the link to the rant.
// *
// * @return The link to the rant.
// */
// public URI getLink() {
// return RequestHandler.BASE_URI.resolve("/rants/" + getId());
// }
//
// /**
// * Get the tags.
// *
// * @return The tags.
// */
// public List<String> getTags() {
// return Collections.unmodifiableList(tags);
// }
//
// /**
// * Get the amount of comments.
// *
// * @return The amount of comments.
// */
// public int getCommentCount() {
// return commentCount;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.scorpiac.javarant.News;
import com.scorpiac.javarant.Rant;
import java.util.List; | package com.scorpiac.javarant.responses;
abstract class AbstractRantsFeedResponse<T extends Rant> extends Response<List<T>> {
@JsonProperty | // Path: src/main/java/com/scorpiac/javarant/News.java
// public class News {
// @JsonProperty
// private int id;
// @JsonProperty
// private String headline;
// @JsonProperty
// private String body;
// @JsonProperty
// private String footer;
//
// @Override
// public String toString() {
// return headline + '\n' + body + '\n' + footer;
// }
//
// @Override
// public int hashCode() {
// return id;
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj instanceof News && ((News) obj).id == id;
// }
//
// /**
// * Get the id.
// *
// * @return The id.
// */
// public int getId() {
// return id;
// }
//
// /**
// * Get the headline.
// *
// * @return The headline.
// */
// public String getHeadline() {
// return headline;
// }
//
// /**
// * Get the body text.
// *
// * @return The body.
// */
// public String getBody() {
// return body;
// }
//
// /**
// * Get the footer.
// *
// * @return The footer.
// */
// public String getFooter() {
// return footer;
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/Rant.java
// public class Rant extends RantContent {
// @JsonProperty
// private List<String> tags;
// @JsonProperty("num_comments")
// private int commentCount;
//
// @Override
// public boolean equals(Object obj) {
// return super.equals(obj) && obj instanceof Rant;
// }
//
// /**
// * Get the link to the rant.
// *
// * @return The link to the rant.
// */
// public URI getLink() {
// return RequestHandler.BASE_URI.resolve("/rants/" + getId());
// }
//
// /**
// * Get the tags.
// *
// * @return The tags.
// */
// public List<String> getTags() {
// return Collections.unmodifiableList(tags);
// }
//
// /**
// * Get the amount of comments.
// *
// * @return The amount of comments.
// */
// public int getCommentCount() {
// return commentCount;
// }
// }
// Path: src/main/java/com/scorpiac/javarant/responses/AbstractRantsFeedResponse.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.scorpiac.javarant.News;
import com.scorpiac.javarant.Rant;
import java.util.List;
package com.scorpiac.javarant.responses;
abstract class AbstractRantsFeedResponse<T extends Rant> extends Response<List<T>> {
@JsonProperty | private News news; // TODO: use this. |
LucaScorpion/JavaRant | src/main/java/com/scorpiac/javarant/DevRantAuth.java | // Path: src/main/java/com/scorpiac/javarant/responses/CommentResponse.java
// public class CommentResponse extends Response<Comment> {
// @JsonProperty
// void setComment(Comment comment) {
// value = comment;
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/RantResponse.java
// public class RantResponse extends Response<Rant> {
// @JsonProperty
// void setRant(Rant rant) {
// value = rant;
// }
// }
| import com.scorpiac.javarant.responses.CommentResponse;
import com.scorpiac.javarant.responses.RantResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.List; | package com.scorpiac.javarant;
public class DevRantAuth {
private final DevRant devRant;
DevRantAuth(DevRant devRant) {
this.devRant = devRant;
}
/**
* Vote on a rant.
*
* @param id The rant to vote on.
* @param vote The vote to cast.
* @return The rant.
*/
public Rant voteRant(int id, Vote vote) {
return devRant.getRequestHandler().post(
ApiEndpoint.RANTS.toString() + '/' + id + '/' + ApiEndpoint.VOTE.toString(), | // Path: src/main/java/com/scorpiac/javarant/responses/CommentResponse.java
// public class CommentResponse extends Response<Comment> {
// @JsonProperty
// void setComment(Comment comment) {
// value = comment;
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/RantResponse.java
// public class RantResponse extends Response<Rant> {
// @JsonProperty
// void setRant(Rant rant) {
// value = rant;
// }
// }
// Path: src/main/java/com/scorpiac/javarant/DevRantAuth.java
import com.scorpiac.javarant.responses.CommentResponse;
import com.scorpiac.javarant.responses.RantResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.List;
package com.scorpiac.javarant;
public class DevRantAuth {
private final DevRant devRant;
DevRantAuth(DevRant devRant) {
this.devRant = devRant;
}
/**
* Vote on a rant.
*
* @param id The rant to vote on.
* @param vote The vote to cast.
* @return The rant.
*/
public Rant voteRant(int id, Vote vote) {
return devRant.getRequestHandler().post(
ApiEndpoint.RANTS.toString() + '/' + id + '/' + ApiEndpoint.VOTE.toString(), | RantResponse.class, |
LucaScorpion/JavaRant | src/main/java/com/scorpiac/javarant/DevRantAuth.java | // Path: src/main/java/com/scorpiac/javarant/responses/CommentResponse.java
// public class CommentResponse extends Response<Comment> {
// @JsonProperty
// void setComment(Comment comment) {
// value = comment;
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/RantResponse.java
// public class RantResponse extends Response<Rant> {
// @JsonProperty
// void setRant(Rant rant) {
// value = rant;
// }
// }
| import com.scorpiac.javarant.responses.CommentResponse;
import com.scorpiac.javarant.responses.RantResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.List; | package com.scorpiac.javarant;
public class DevRantAuth {
private final DevRant devRant;
DevRantAuth(DevRant devRant) {
this.devRant = devRant;
}
/**
* Vote on a rant.
*
* @param id The rant to vote on.
* @param vote The vote to cast.
* @return The rant.
*/
public Rant voteRant(int id, Vote vote) {
return devRant.getRequestHandler().post(
ApiEndpoint.RANTS.toString() + '/' + id + '/' + ApiEndpoint.VOTE.toString(),
RantResponse.class,
getParameters(vote.getOptions())
).getValueOrError();
}
/**
* Vote on a comment.
*
* @param id The comment to vote on.
* @param vote The vote to cast.
* @return The comment.
*/
public Comment voteComment(int id, Vote vote) {
return devRant.getRequestHandler().post(
ApiEndpoint.COMMENTS.toString() + '/' + id + '/' + ApiEndpoint.VOTE.toString(), | // Path: src/main/java/com/scorpiac/javarant/responses/CommentResponse.java
// public class CommentResponse extends Response<Comment> {
// @JsonProperty
// void setComment(Comment comment) {
// value = comment;
// }
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/RantResponse.java
// public class RantResponse extends Response<Rant> {
// @JsonProperty
// void setRant(Rant rant) {
// value = rant;
// }
// }
// Path: src/main/java/com/scorpiac/javarant/DevRantAuth.java
import com.scorpiac.javarant.responses.CommentResponse;
import com.scorpiac.javarant.responses.RantResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.List;
package com.scorpiac.javarant;
public class DevRantAuth {
private final DevRant devRant;
DevRantAuth(DevRant devRant) {
this.devRant = devRant;
}
/**
* Vote on a rant.
*
* @param id The rant to vote on.
* @param vote The vote to cast.
* @return The rant.
*/
public Rant voteRant(int id, Vote vote) {
return devRant.getRequestHandler().post(
ApiEndpoint.RANTS.toString() + '/' + id + '/' + ApiEndpoint.VOTE.toString(),
RantResponse.class,
getParameters(vote.getOptions())
).getValueOrError();
}
/**
* Vote on a comment.
*
* @param id The comment to vote on.
* @param vote The vote to cast.
* @return The comment.
*/
public Comment voteComment(int id, Vote vote) {
return devRant.getRequestHandler().post(
ApiEndpoint.COMMENTS.toString() + '/' + id + '/' + ApiEndpoint.VOTE.toString(), | CommentResponse.class, |
LucaScorpion/JavaRant | src/main/java/com/scorpiac/javarant/responses/Response.java | // Path: src/main/java/com/scorpiac/javarant/DevRantApiException.java
// public class DevRantApiException extends RuntimeException {
// public DevRantApiException(String message) {
// super("A devRant API exception occurred: " + message);
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.scorpiac.javarant.DevRantApiException;
import java.util.Optional; | package com.scorpiac.javarant.responses;
/**
* This class is used internally to create a pojo from a response.
* It contains whether the request was successful, an error message and the actual result value.
*
* @param <T> The type of the value the response contains.
*/
public abstract class Response<T> {
@JsonProperty
private boolean success;
@JsonProperty
private String error;
// The actual result value.
T value;
/**
* Get the error message.
*
* @return The error message.
*/
public String getError() {
return error != null ? error : "An unknown error occurred.";
}
/**
* Get the result value.
*
* @return An optional containing the result value.
*/
public Optional<T> getValue() {
return Optional.ofNullable(value);
}
public T getValueOrError() {
if (!success) { | // Path: src/main/java/com/scorpiac/javarant/DevRantApiException.java
// public class DevRantApiException extends RuntimeException {
// public DevRantApiException(String message) {
// super("A devRant API exception occurred: " + message);
// }
// }
// Path: src/main/java/com/scorpiac/javarant/responses/Response.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.scorpiac.javarant.DevRantApiException;
import java.util.Optional;
package com.scorpiac.javarant.responses;
/**
* This class is used internally to create a pojo from a response.
* It contains whether the request was successful, an error message and the actual result value.
*
* @param <T> The type of the value the response contains.
*/
public abstract class Response<T> {
@JsonProperty
private boolean success;
@JsonProperty
private String error;
// The actual result value.
T value;
/**
* Get the error message.
*
* @return The error message.
*/
public String getError() {
return error != null ? error : "An unknown error occurred.";
}
/**
* Get the result value.
*
* @return An optional containing the result value.
*/
public Optional<T> getValue() {
return Optional.ofNullable(value);
}
public T getValueOrError() {
if (!success) { | throw new DevRantApiException(error); |
LucaScorpion/JavaRant | src/main/java/com/scorpiac/javarant/DevRantFeed.java | // Path: src/main/java/com/scorpiac/javarant/responses/CollabsFeedResponse.java
// public class CollabsFeedResponse extends AbstractRantsFeedResponse<Collab> {
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/RantsFeedResponse.java
// public class RantsFeedResponse extends AbstractRantsFeedResponse<Rant> {
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/ResultsFeedResponse.java
// public class ResultsFeedResponse extends Response<List<Rant>> {
// @JsonProperty
// void setResults(List<Rant> results) {
// value = results;
// }
// }
| import com.scorpiac.javarant.responses.CollabsFeedResponse;
import com.scorpiac.javarant.responses.RantsFeedResponse;
import com.scorpiac.javarant.responses.ResultsFeedResponse;
import org.apache.http.message.BasicNameValuePair;
import java.util.List; | package com.scorpiac.javarant;
public class DevRantFeed {
private final DevRant devRant;
DevRantFeed(DevRant devRant) {
this.devRant = devRant;
}
/**
* Get rants from the feed.
*
* @param sort How to sort the feed.
* @param limit How many rants to get.
* @param skip How many rants to skip.
* @return Rants from the feed.
*/
public List<Rant> getRants(Sort sort, int limit, int skip) { | // Path: src/main/java/com/scorpiac/javarant/responses/CollabsFeedResponse.java
// public class CollabsFeedResponse extends AbstractRantsFeedResponse<Collab> {
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/RantsFeedResponse.java
// public class RantsFeedResponse extends AbstractRantsFeedResponse<Rant> {
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/ResultsFeedResponse.java
// public class ResultsFeedResponse extends Response<List<Rant>> {
// @JsonProperty
// void setResults(List<Rant> results) {
// value = results;
// }
// }
// Path: src/main/java/com/scorpiac/javarant/DevRantFeed.java
import com.scorpiac.javarant.responses.CollabsFeedResponse;
import com.scorpiac.javarant.responses.RantsFeedResponse;
import com.scorpiac.javarant.responses.ResultsFeedResponse;
import org.apache.http.message.BasicNameValuePair;
import java.util.List;
package com.scorpiac.javarant;
public class DevRantFeed {
private final DevRant devRant;
DevRantFeed(DevRant devRant) {
this.devRant = devRant;
}
/**
* Get rants from the feed.
*
* @param sort How to sort the feed.
* @param limit How many rants to get.
* @param skip How many rants to skip.
* @return Rants from the feed.
*/
public List<Rant> getRants(Sort sort, int limit, int skip) { | return devRant.getRequestHandler().get(ApiEndpoint.RANTS, RantsFeedResponse.class, |
LucaScorpion/JavaRant | src/main/java/com/scorpiac/javarant/DevRantFeed.java | // Path: src/main/java/com/scorpiac/javarant/responses/CollabsFeedResponse.java
// public class CollabsFeedResponse extends AbstractRantsFeedResponse<Collab> {
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/RantsFeedResponse.java
// public class RantsFeedResponse extends AbstractRantsFeedResponse<Rant> {
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/ResultsFeedResponse.java
// public class ResultsFeedResponse extends Response<List<Rant>> {
// @JsonProperty
// void setResults(List<Rant> results) {
// value = results;
// }
// }
| import com.scorpiac.javarant.responses.CollabsFeedResponse;
import com.scorpiac.javarant.responses.RantsFeedResponse;
import com.scorpiac.javarant.responses.ResultsFeedResponse;
import org.apache.http.message.BasicNameValuePair;
import java.util.List; | package com.scorpiac.javarant;
public class DevRantFeed {
private final DevRant devRant;
DevRantFeed(DevRant devRant) {
this.devRant = devRant;
}
/**
* Get rants from the feed.
*
* @param sort How to sort the feed.
* @param limit How many rants to get.
* @param skip How many rants to skip.
* @return Rants from the feed.
*/
public List<Rant> getRants(Sort sort, int limit, int skip) {
return devRant.getRequestHandler().get(ApiEndpoint.RANTS, RantsFeedResponse.class,
new BasicNameValuePair("sort", sort.toString()),
new BasicNameValuePair("limit", String.valueOf(limit)),
new BasicNameValuePair("skip", String.valueOf(skip))
).getValueOrError();
}
/**
* Search for rants.
*
* @param term The term to search for.
* @return The search results.
*/
public List<Rant> search(String term) { | // Path: src/main/java/com/scorpiac/javarant/responses/CollabsFeedResponse.java
// public class CollabsFeedResponse extends AbstractRantsFeedResponse<Collab> {
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/RantsFeedResponse.java
// public class RantsFeedResponse extends AbstractRantsFeedResponse<Rant> {
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/ResultsFeedResponse.java
// public class ResultsFeedResponse extends Response<List<Rant>> {
// @JsonProperty
// void setResults(List<Rant> results) {
// value = results;
// }
// }
// Path: src/main/java/com/scorpiac/javarant/DevRantFeed.java
import com.scorpiac.javarant.responses.CollabsFeedResponse;
import com.scorpiac.javarant.responses.RantsFeedResponse;
import com.scorpiac.javarant.responses.ResultsFeedResponse;
import org.apache.http.message.BasicNameValuePair;
import java.util.List;
package com.scorpiac.javarant;
public class DevRantFeed {
private final DevRant devRant;
DevRantFeed(DevRant devRant) {
this.devRant = devRant;
}
/**
* Get rants from the feed.
*
* @param sort How to sort the feed.
* @param limit How many rants to get.
* @param skip How many rants to skip.
* @return Rants from the feed.
*/
public List<Rant> getRants(Sort sort, int limit, int skip) {
return devRant.getRequestHandler().get(ApiEndpoint.RANTS, RantsFeedResponse.class,
new BasicNameValuePair("sort", sort.toString()),
new BasicNameValuePair("limit", String.valueOf(limit)),
new BasicNameValuePair("skip", String.valueOf(skip))
).getValueOrError();
}
/**
* Search for rants.
*
* @param term The term to search for.
* @return The search results.
*/
public List<Rant> search(String term) { | return devRant.getRequestHandler().get(ApiEndpoint.SEARCH, ResultsFeedResponse.class, |
LucaScorpion/JavaRant | src/main/java/com/scorpiac/javarant/DevRantFeed.java | // Path: src/main/java/com/scorpiac/javarant/responses/CollabsFeedResponse.java
// public class CollabsFeedResponse extends AbstractRantsFeedResponse<Collab> {
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/RantsFeedResponse.java
// public class RantsFeedResponse extends AbstractRantsFeedResponse<Rant> {
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/ResultsFeedResponse.java
// public class ResultsFeedResponse extends Response<List<Rant>> {
// @JsonProperty
// void setResults(List<Rant> results) {
// value = results;
// }
// }
| import com.scorpiac.javarant.responses.CollabsFeedResponse;
import com.scorpiac.javarant.responses.RantsFeedResponse;
import com.scorpiac.javarant.responses.ResultsFeedResponse;
import org.apache.http.message.BasicNameValuePair;
import java.util.List; | * @return Weekly rants from the feed.
*/
public List<Rant> getWeekly(Sort sort, int skip) {
return devRant.getRequestHandler().get(ApiEndpoint.WEEKLY, RantsFeedResponse.class,
new BasicNameValuePair("sort", sort.toString()),
new BasicNameValuePair("skip", String.valueOf(skip))
).getValueOrError();
}
/**
* Get stories from the feed.
*
* @param sort How to sort the feed.
* @param skip How many rants to skip.
* @return Stories from the feed.
*/
public List<Rant> getStories(Sort sort, int skip) {
return devRant.getRequestHandler().get(ApiEndpoint.STORIES, RantsFeedResponse.class,
new BasicNameValuePair("sort", sort.toString()),
new BasicNameValuePair("skip", String.valueOf(skip))
).getValueOrError();
}
/**
* Get collabs from the feed.
*
* @param limit How many rants to get.
* @return Collabs from the feed.
*/
public List<Collab> getCollabs(int limit) { | // Path: src/main/java/com/scorpiac/javarant/responses/CollabsFeedResponse.java
// public class CollabsFeedResponse extends AbstractRantsFeedResponse<Collab> {
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/RantsFeedResponse.java
// public class RantsFeedResponse extends AbstractRantsFeedResponse<Rant> {
// }
//
// Path: src/main/java/com/scorpiac/javarant/responses/ResultsFeedResponse.java
// public class ResultsFeedResponse extends Response<List<Rant>> {
// @JsonProperty
// void setResults(List<Rant> results) {
// value = results;
// }
// }
// Path: src/main/java/com/scorpiac/javarant/DevRantFeed.java
import com.scorpiac.javarant.responses.CollabsFeedResponse;
import com.scorpiac.javarant.responses.RantsFeedResponse;
import com.scorpiac.javarant.responses.ResultsFeedResponse;
import org.apache.http.message.BasicNameValuePair;
import java.util.List;
* @return Weekly rants from the feed.
*/
public List<Rant> getWeekly(Sort sort, int skip) {
return devRant.getRequestHandler().get(ApiEndpoint.WEEKLY, RantsFeedResponse.class,
new BasicNameValuePair("sort", sort.toString()),
new BasicNameValuePair("skip", String.valueOf(skip))
).getValueOrError();
}
/**
* Get stories from the feed.
*
* @param sort How to sort the feed.
* @param skip How many rants to skip.
* @return Stories from the feed.
*/
public List<Rant> getStories(Sort sort, int skip) {
return devRant.getRequestHandler().get(ApiEndpoint.STORIES, RantsFeedResponse.class,
new BasicNameValuePair("sort", sort.toString()),
new BasicNameValuePair("skip", String.valueOf(skip))
).getValueOrError();
}
/**
* Get collabs from the feed.
*
* @param limit How many rants to get.
* @return Collabs from the feed.
*/
public List<Collab> getCollabs(int limit) { | return devRant.getRequestHandler().get(ApiEndpoint.COLLABS, CollabsFeedResponse.class, |
LucaScorpion/JavaRant | src/main/java/com/scorpiac/javarant/DevRant.java | // Path: src/main/java/com/scorpiac/javarant/services/RequestHandler.java
// @Singleton
// public class RequestHandler {
// public static final URI BASE_URI = URI.create("https://www.devrant.io");
// public static final URI AVATARS_URI = URI.create("https://avatars.devrant.io");
//
// private static final String APP_ID = "3";
// private static final String PLAT_ID = "3";
//
// private final ObjectMapperResponseHandlerFactory responseHandlerFactory;
//
// private int timeout = 15000;
//
// @Inject
// RequestHandler(ObjectMapperResponseHandlerFactory responseHandlerFactory) {
// this.responseHandlerFactory = responseHandlerFactory;
// }
//
// public <T, R extends Response<T>> R get(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) {
// return get(endpoint.toString(), clazz, params);
// }
//
// public <T, R extends Response<T>> R get(String endpoint, Class<R> clazz, NameValuePair... params) {
// return handleRequest(
// buildRequest(endpoint, Request::Get, getParameters(params)),
// clazz
// );
// }
//
// public <T, R extends Response<T>> R post(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) {
// return post(endpoint.toString(), clazz, params);
// }
//
// public <T, R extends Response<T>> R post(String endpoint, Class<R> clazz, NameValuePair... params) {
// return handleRequest(
// buildRequest(endpoint, Request::Post, Collections.emptyList()).bodyForm(getParameters(params)),
// clazz
// );
// }
//
// /**
// * Build a request.
// *
// * @param endpoint The endpoint to make the request to.
// * @param requestFunction The function to create a new request from a URI.
// * @param params The request parameters.
// * @return A request.
// */
// private Request buildRequest(String endpoint, Function<URI, Request> requestFunction, List<NameValuePair> params) {
// URI uri;
//
// try {
// // Build the URI.
// uri = new URIBuilder(resolve(endpoint))
// .addParameters(params)
// .build();
// } catch (URISyntaxException e) {
// // This never happens.
// throw new IllegalArgumentException("Could not build URI.", e);
// }
//
// return requestFunction.apply(uri)
// .connectTimeout(timeout)
// .socketTimeout(timeout);
// }
//
// /**
// * Resolve an endpoint to a URI.
// * This method's main purpose is to be overridden for the tests.
// *
// * @param endpoint The endpoint to resolve.
// * @return A complete URI.
// */
// URI resolve(String endpoint) {
// return BASE_URI.resolve(endpoint);
// }
//
// /**
// * Handle a request.
// *
// * @param request The request to handle.
// * @param clazz The class to map the response to.
// * @param <T> The type of the class to use in the result.
// * @param <R> The type of the class to map the internal response to.
// * @return The mapped response.
// */
// // This is because of the last line, which cannot be checked. Just make sure it is tested properly.
// @SuppressWarnings("unchecked")
// private <T, R extends Response<T>> R handleRequest(Request request, Class<R> clazz) {
// R response;
// try {
// response = request.execute().handleResponse(responseHandlerFactory.getResponseHandler(clazz));
// } catch (IOException e) {
// throw new DevRantException("Failed to execute request.", e);
// }
//
// return response;
// }
//
// /**
// * Get a list with all the parameters, including default and auth parameters.
// * This also filters out any parameters that are {@code null}.
// *
// * @param params The parameters to use.
// * @return A list containing the given and default parameters.
// */
// private List<NameValuePair> getParameters(NameValuePair... params) {
// List<NameValuePair> paramList = new ArrayList<>();
//
// // Add all non-null parameters.
// paramList.addAll(
// Arrays.stream(params)
// .filter(Objects::nonNull)
// .collect(Collectors.toList())
// );
//
// // Add the parameters which always need to be present.
// paramList.add(new BasicNameValuePair("app", APP_ID));
// paramList.add(new BasicNameValuePair("plat", PLAT_ID));
//
// return paramList;
// }
//
// /**
// * Set the request timeout.
// * This timeout will be used for the socket and connection timeout.
// *
// * @param timeout The timeout in milliseconds to set, or -1 to set no timeout.
// */
// public void setRequestTimeout(int timeout) {
// this.timeout = timeout;
// }
//
// /**
// * Get the current request timeout in milliseconds, or -1 if there is no timeout.
// *
// * @return The request timeout.
// */
// public int getRequestTimeout() {
// return timeout;
// }
// }
| import com.google.inject.Guice;
import com.google.inject.Injector;
import com.scorpiac.javarant.responses.*;
import com.scorpiac.javarant.services.RequestHandler;
import org.apache.http.message.BasicNameValuePair;
import javax.inject.Inject; | package com.scorpiac.javarant;
public class DevRant {
private static final Injector INJECTOR;
private final DevRantFeed devRantFeed;
private final DevRantAuth devRantAuth;
| // Path: src/main/java/com/scorpiac/javarant/services/RequestHandler.java
// @Singleton
// public class RequestHandler {
// public static final URI BASE_URI = URI.create("https://www.devrant.io");
// public static final URI AVATARS_URI = URI.create("https://avatars.devrant.io");
//
// private static final String APP_ID = "3";
// private static final String PLAT_ID = "3";
//
// private final ObjectMapperResponseHandlerFactory responseHandlerFactory;
//
// private int timeout = 15000;
//
// @Inject
// RequestHandler(ObjectMapperResponseHandlerFactory responseHandlerFactory) {
// this.responseHandlerFactory = responseHandlerFactory;
// }
//
// public <T, R extends Response<T>> R get(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) {
// return get(endpoint.toString(), clazz, params);
// }
//
// public <T, R extends Response<T>> R get(String endpoint, Class<R> clazz, NameValuePair... params) {
// return handleRequest(
// buildRequest(endpoint, Request::Get, getParameters(params)),
// clazz
// );
// }
//
// public <T, R extends Response<T>> R post(ApiEndpoint endpoint, Class<R> clazz, NameValuePair... params) {
// return post(endpoint.toString(), clazz, params);
// }
//
// public <T, R extends Response<T>> R post(String endpoint, Class<R> clazz, NameValuePair... params) {
// return handleRequest(
// buildRequest(endpoint, Request::Post, Collections.emptyList()).bodyForm(getParameters(params)),
// clazz
// );
// }
//
// /**
// * Build a request.
// *
// * @param endpoint The endpoint to make the request to.
// * @param requestFunction The function to create a new request from a URI.
// * @param params The request parameters.
// * @return A request.
// */
// private Request buildRequest(String endpoint, Function<URI, Request> requestFunction, List<NameValuePair> params) {
// URI uri;
//
// try {
// // Build the URI.
// uri = new URIBuilder(resolve(endpoint))
// .addParameters(params)
// .build();
// } catch (URISyntaxException e) {
// // This never happens.
// throw new IllegalArgumentException("Could not build URI.", e);
// }
//
// return requestFunction.apply(uri)
// .connectTimeout(timeout)
// .socketTimeout(timeout);
// }
//
// /**
// * Resolve an endpoint to a URI.
// * This method's main purpose is to be overridden for the tests.
// *
// * @param endpoint The endpoint to resolve.
// * @return A complete URI.
// */
// URI resolve(String endpoint) {
// return BASE_URI.resolve(endpoint);
// }
//
// /**
// * Handle a request.
// *
// * @param request The request to handle.
// * @param clazz The class to map the response to.
// * @param <T> The type of the class to use in the result.
// * @param <R> The type of the class to map the internal response to.
// * @return The mapped response.
// */
// // This is because of the last line, which cannot be checked. Just make sure it is tested properly.
// @SuppressWarnings("unchecked")
// private <T, R extends Response<T>> R handleRequest(Request request, Class<R> clazz) {
// R response;
// try {
// response = request.execute().handleResponse(responseHandlerFactory.getResponseHandler(clazz));
// } catch (IOException e) {
// throw new DevRantException("Failed to execute request.", e);
// }
//
// return response;
// }
//
// /**
// * Get a list with all the parameters, including default and auth parameters.
// * This also filters out any parameters that are {@code null}.
// *
// * @param params The parameters to use.
// * @return A list containing the given and default parameters.
// */
// private List<NameValuePair> getParameters(NameValuePair... params) {
// List<NameValuePair> paramList = new ArrayList<>();
//
// // Add all non-null parameters.
// paramList.addAll(
// Arrays.stream(params)
// .filter(Objects::nonNull)
// .collect(Collectors.toList())
// );
//
// // Add the parameters which always need to be present.
// paramList.add(new BasicNameValuePair("app", APP_ID));
// paramList.add(new BasicNameValuePair("plat", PLAT_ID));
//
// return paramList;
// }
//
// /**
// * Set the request timeout.
// * This timeout will be used for the socket and connection timeout.
// *
// * @param timeout The timeout in milliseconds to set, or -1 to set no timeout.
// */
// public void setRequestTimeout(int timeout) {
// this.timeout = timeout;
// }
//
// /**
// * Get the current request timeout in milliseconds, or -1 if there is no timeout.
// *
// * @return The request timeout.
// */
// public int getRequestTimeout() {
// return timeout;
// }
// }
// Path: src/main/java/com/scorpiac/javarant/DevRant.java
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.scorpiac.javarant.responses.*;
import com.scorpiac.javarant.services.RequestHandler;
import org.apache.http.message.BasicNameValuePair;
import javax.inject.Inject;
package com.scorpiac.javarant;
public class DevRant {
private static final Injector INJECTOR;
private final DevRantFeed devRantFeed;
private final DevRantAuth devRantAuth;
| private RequestHandler requestHandler; |
baoyongzhang/AirData | core/src/main/java/com/baoyz/airdata/crud/Delete.java | // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
| import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Delete {
private Class<?> table;
private String where;
private String[] whereArgs;
| // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
// Path: core/src/main/java/com/baoyz/airdata/crud/Delete.java
import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Delete {
private Class<?> table;
private String where;
private String[] whereArgs;
| private AbstractDatabase database; |
baoyongzhang/AirData | core/src/main/java/com/baoyz/airdata/crud/Delete.java | // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
| import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Delete {
private Class<?> table;
private String where;
private String[] whereArgs;
private AbstractDatabase database; | // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
// Path: core/src/main/java/com/baoyz/airdata/crud/Delete.java
import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Delete {
private Class<?> table;
private String where;
private String[] whereArgs;
private AbstractDatabase database; | private AirDatabaseHelper helper; |
baoyongzhang/AirData | core/src/main/java/com/baoyz/airdata/crud/Select.java | // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
| import android.database.Cursor;
import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Select<T> {
/*
boolean distinct, String table, String[] columns,
String selection, String[] selectionArgs, String groupBy,
String having, String orderBy, String limit
*/
private boolean distinct;
private Class<T> table;
private String[] columns;
private String selection;
private String[] selectionArgs;
private String groupBy;
private String having;
private String orderBy;
private String limit;
| // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
// Path: core/src/main/java/com/baoyz/airdata/crud/Select.java
import android.database.Cursor;
import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Select<T> {
/*
boolean distinct, String table, String[] columns,
String selection, String[] selectionArgs, String groupBy,
String having, String orderBy, String limit
*/
private boolean distinct;
private Class<T> table;
private String[] columns;
private String selection;
private String[] selectionArgs;
private String groupBy;
private String having;
private String orderBy;
private String limit;
| private AbstractDatabase database; |
baoyongzhang/AirData | core/src/main/java/com/baoyz/airdata/crud/Select.java | // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
| import android.database.Cursor;
import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Select<T> {
/*
boolean distinct, String table, String[] columns,
String selection, String[] selectionArgs, String groupBy,
String having, String orderBy, String limit
*/
private boolean distinct;
private Class<T> table;
private String[] columns;
private String selection;
private String[] selectionArgs;
private String groupBy;
private String having;
private String orderBy;
private String limit;
private AbstractDatabase database; | // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
// Path: core/src/main/java/com/baoyz/airdata/crud/Select.java
import android.database.Cursor;
import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Select<T> {
/*
boolean distinct, String table, String[] columns,
String selection, String[] selectionArgs, String groupBy,
String having, String orderBy, String limit
*/
private boolean distinct;
private Class<T> table;
private String[] columns;
private String selection;
private String[] selectionArgs;
private String groupBy;
private String having;
private String orderBy;
private String limit;
private AbstractDatabase database; | private AirDatabaseHelper helper; |
baoyongzhang/AirData | app/src/androidTest/java/com/baoyz/airdata/BasicTest.java | // Path: core/src/main/java/com/baoyz/airdata/crud/Select.java
// public class Select<T> {
//
// /*
// boolean distinct, String table, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit
// */
//
// private boolean distinct;
// private Class<T> table;
// private String[] columns;
// private String selection;
// private String[] selectionArgs;
// private String groupBy;
// private String having;
// private String orderBy;
// private String limit;
//
// private AbstractDatabase database;
// private AirDatabaseHelper helper;
//
// public Select(AbstractDatabase database) {
// this.database = database;
// this.helper = database.getDatabaseHelper();
// }
//
// public Select<T> columns(String... columns) {
// this.columns = columns;
// return this;
// }
//
// public Select<T> from(Class<T> table) {
// this.table = table;
// return this;
// }
//
// public Select<T> distinct(boolean distinct) {
// this.distinct = distinct;
// return this;
// }
//
// public Select<T> where(String selection, String... selectionArgs) {
// this.selection = selection;
// this.selectionArgs = selectionArgs;
// return this;
// }
//
// public Select<T> groupBy(String groupBy) {
// this.groupBy = groupBy;
// return this;
// }
//
// public Select having(String having) {
// this.having = having;
// return this;
// }
//
// public Select<T> orderBy(String orderBy) {
// this.orderBy = orderBy;
// return this;
// }
//
// public Select<T> limit(String limit) {
// this.limit = limit;
// return this;
// }
//
// public int count() {
// columns = new String[]{"COUNT(*)"};
//
// Cursor cursor = helper.rawQuery(table, distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
// if (cursor.moveToFirst()) {
// return cursor.getInt(0);
// }
// return 0;
// }
//
// public T single() {
// List<T> list = list();
// if (list != null && list.size() > 0) {
// T result = list.get(0);
// return result;
// }
// return null;
// }
//
// public List<T> list() {
// List<T> result = helper.query(table, distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
// return result;
// }
//
// }
//
// Path: app/src/main/java/com/baoyz/airdata/model/Student.java
// @Table
// public class Student {
//
// @PrimaryKey
// private int id;
// private String name;
// private int score;
// private char mark;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
//
// public char getMark() {
// return mark;
// }
//
// public void setMark(char mark) {
// this.mark = mark;
// }
//
// @Override
// public String toString() {
// return "Student{" +
// "id=" + id +
// ", name='" + name + '\'' +
// ", score=" + score +
// ", mark=" + mark +
// '}';
// }
// }
| import android.app.Application;
import android.test.ApplicationTestCase;
import com.baoyz.airdata.crud.Select;
import com.baoyz.airdata.model.Student;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata;
/**
* AirData
* Created by baoyz on 15/7/20.
*/
public class BasicTest extends ApplicationTestCase<Application> {
public BasicTest() {
super(Application.class);
}
public void testAll(){
testInsert();
testUpdate();
testDelete();
testSelect();
}
public void testInsert() { | // Path: core/src/main/java/com/baoyz/airdata/crud/Select.java
// public class Select<T> {
//
// /*
// boolean distinct, String table, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit
// */
//
// private boolean distinct;
// private Class<T> table;
// private String[] columns;
// private String selection;
// private String[] selectionArgs;
// private String groupBy;
// private String having;
// private String orderBy;
// private String limit;
//
// private AbstractDatabase database;
// private AirDatabaseHelper helper;
//
// public Select(AbstractDatabase database) {
// this.database = database;
// this.helper = database.getDatabaseHelper();
// }
//
// public Select<T> columns(String... columns) {
// this.columns = columns;
// return this;
// }
//
// public Select<T> from(Class<T> table) {
// this.table = table;
// return this;
// }
//
// public Select<T> distinct(boolean distinct) {
// this.distinct = distinct;
// return this;
// }
//
// public Select<T> where(String selection, String... selectionArgs) {
// this.selection = selection;
// this.selectionArgs = selectionArgs;
// return this;
// }
//
// public Select<T> groupBy(String groupBy) {
// this.groupBy = groupBy;
// return this;
// }
//
// public Select having(String having) {
// this.having = having;
// return this;
// }
//
// public Select<T> orderBy(String orderBy) {
// this.orderBy = orderBy;
// return this;
// }
//
// public Select<T> limit(String limit) {
// this.limit = limit;
// return this;
// }
//
// public int count() {
// columns = new String[]{"COUNT(*)"};
//
// Cursor cursor = helper.rawQuery(table, distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
// if (cursor.moveToFirst()) {
// return cursor.getInt(0);
// }
// return 0;
// }
//
// public T single() {
// List<T> list = list();
// if (list != null && list.size() > 0) {
// T result = list.get(0);
// return result;
// }
// return null;
// }
//
// public List<T> list() {
// List<T> result = helper.query(table, distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
// return result;
// }
//
// }
//
// Path: app/src/main/java/com/baoyz/airdata/model/Student.java
// @Table
// public class Student {
//
// @PrimaryKey
// private int id;
// private String name;
// private int score;
// private char mark;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
//
// public char getMark() {
// return mark;
// }
//
// public void setMark(char mark) {
// this.mark = mark;
// }
//
// @Override
// public String toString() {
// return "Student{" +
// "id=" + id +
// ", name='" + name + '\'' +
// ", score=" + score +
// ", mark=" + mark +
// '}';
// }
// }
// Path: app/src/androidTest/java/com/baoyz/airdata/BasicTest.java
import android.app.Application;
import android.test.ApplicationTestCase;
import com.baoyz.airdata.crud.Select;
import com.baoyz.airdata.model.Student;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata;
/**
* AirData
* Created by baoyz on 15/7/20.
*/
public class BasicTest extends ApplicationTestCase<Application> {
public BasicTest() {
super(Application.class);
}
public void testAll(){
testInsert();
testUpdate();
testDelete();
testSelect();
}
public void testInsert() { | Student stu = new Student(); |
baoyongzhang/AirData | app/src/androidTest/java/com/baoyz/airdata/BasicTest.java | // Path: core/src/main/java/com/baoyz/airdata/crud/Select.java
// public class Select<T> {
//
// /*
// boolean distinct, String table, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit
// */
//
// private boolean distinct;
// private Class<T> table;
// private String[] columns;
// private String selection;
// private String[] selectionArgs;
// private String groupBy;
// private String having;
// private String orderBy;
// private String limit;
//
// private AbstractDatabase database;
// private AirDatabaseHelper helper;
//
// public Select(AbstractDatabase database) {
// this.database = database;
// this.helper = database.getDatabaseHelper();
// }
//
// public Select<T> columns(String... columns) {
// this.columns = columns;
// return this;
// }
//
// public Select<T> from(Class<T> table) {
// this.table = table;
// return this;
// }
//
// public Select<T> distinct(boolean distinct) {
// this.distinct = distinct;
// return this;
// }
//
// public Select<T> where(String selection, String... selectionArgs) {
// this.selection = selection;
// this.selectionArgs = selectionArgs;
// return this;
// }
//
// public Select<T> groupBy(String groupBy) {
// this.groupBy = groupBy;
// return this;
// }
//
// public Select having(String having) {
// this.having = having;
// return this;
// }
//
// public Select<T> orderBy(String orderBy) {
// this.orderBy = orderBy;
// return this;
// }
//
// public Select<T> limit(String limit) {
// this.limit = limit;
// return this;
// }
//
// public int count() {
// columns = new String[]{"COUNT(*)"};
//
// Cursor cursor = helper.rawQuery(table, distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
// if (cursor.moveToFirst()) {
// return cursor.getInt(0);
// }
// return 0;
// }
//
// public T single() {
// List<T> list = list();
// if (list != null && list.size() > 0) {
// T result = list.get(0);
// return result;
// }
// return null;
// }
//
// public List<T> list() {
// List<T> result = helper.query(table, distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
// return result;
// }
//
// }
//
// Path: app/src/main/java/com/baoyz/airdata/model/Student.java
// @Table
// public class Student {
//
// @PrimaryKey
// private int id;
// private String name;
// private int score;
// private char mark;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
//
// public char getMark() {
// return mark;
// }
//
// public void setMark(char mark) {
// this.mark = mark;
// }
//
// @Override
// public String toString() {
// return "Student{" +
// "id=" + id +
// ", name='" + name + '\'' +
// ", score=" + score +
// ", mark=" + mark +
// '}';
// }
// }
| import android.app.Application;
import android.test.ApplicationTestCase;
import com.baoyz.airdata.crud.Select;
import com.baoyz.airdata.model.Student;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata;
/**
* AirData
* Created by baoyz on 15/7/20.
*/
public class BasicTest extends ApplicationTestCase<Application> {
public BasicTest() {
super(Application.class);
}
public void testAll(){
testInsert();
testUpdate();
testDelete();
testSelect();
}
public void testInsert() {
Student stu = new Student();
stu.setName("Jack");
stu.setMark('a');
stu.setScore(60);
MyDatabase database = new MyDatabase(getContext());
long save = database.save(stu);
assertFalse(save == -1);
}
public void testUpdate() {
MyDatabase database = new MyDatabase(getContext()); | // Path: core/src/main/java/com/baoyz/airdata/crud/Select.java
// public class Select<T> {
//
// /*
// boolean distinct, String table, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit
// */
//
// private boolean distinct;
// private Class<T> table;
// private String[] columns;
// private String selection;
// private String[] selectionArgs;
// private String groupBy;
// private String having;
// private String orderBy;
// private String limit;
//
// private AbstractDatabase database;
// private AirDatabaseHelper helper;
//
// public Select(AbstractDatabase database) {
// this.database = database;
// this.helper = database.getDatabaseHelper();
// }
//
// public Select<T> columns(String... columns) {
// this.columns = columns;
// return this;
// }
//
// public Select<T> from(Class<T> table) {
// this.table = table;
// return this;
// }
//
// public Select<T> distinct(boolean distinct) {
// this.distinct = distinct;
// return this;
// }
//
// public Select<T> where(String selection, String... selectionArgs) {
// this.selection = selection;
// this.selectionArgs = selectionArgs;
// return this;
// }
//
// public Select<T> groupBy(String groupBy) {
// this.groupBy = groupBy;
// return this;
// }
//
// public Select having(String having) {
// this.having = having;
// return this;
// }
//
// public Select<T> orderBy(String orderBy) {
// this.orderBy = orderBy;
// return this;
// }
//
// public Select<T> limit(String limit) {
// this.limit = limit;
// return this;
// }
//
// public int count() {
// columns = new String[]{"COUNT(*)"};
//
// Cursor cursor = helper.rawQuery(table, distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
// if (cursor.moveToFirst()) {
// return cursor.getInt(0);
// }
// return 0;
// }
//
// public T single() {
// List<T> list = list();
// if (list != null && list.size() > 0) {
// T result = list.get(0);
// return result;
// }
// return null;
// }
//
// public List<T> list() {
// List<T> result = helper.query(table, distinct, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
// return result;
// }
//
// }
//
// Path: app/src/main/java/com/baoyz/airdata/model/Student.java
// @Table
// public class Student {
//
// @PrimaryKey
// private int id;
// private String name;
// private int score;
// private char mark;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
//
// public char getMark() {
// return mark;
// }
//
// public void setMark(char mark) {
// this.mark = mark;
// }
//
// @Override
// public String toString() {
// return "Student{" +
// "id=" + id +
// ", name='" + name + '\'' +
// ", score=" + score +
// ", mark=" + mark +
// '}';
// }
// }
// Path: app/src/androidTest/java/com/baoyz/airdata/BasicTest.java
import android.app.Application;
import android.test.ApplicationTestCase;
import com.baoyz.airdata.crud.Select;
import com.baoyz.airdata.model.Student;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata;
/**
* AirData
* Created by baoyz on 15/7/20.
*/
public class BasicTest extends ApplicationTestCase<Application> {
public BasicTest() {
super(Application.class);
}
public void testAll(){
testInsert();
testUpdate();
testDelete();
testSelect();
}
public void testInsert() {
Student stu = new Student();
stu.setName("Jack");
stu.setMark('a');
stu.setScore(60);
MyDatabase database = new MyDatabase(getContext());
long save = database.save(stu);
assertFalse(save == -1);
}
public void testUpdate() {
MyDatabase database = new MyDatabase(getContext()); | Student single = new Select<Student>(database).from(Student.class).single(); |
baoyongzhang/AirData | compiler/src/main/java/com/baoyz/airdata/TableInfo.java | // Path: compiler/src/main/java/com/baoyz/airdata/utils/TextUtils.java
// public class TextUtils {
//
// public static String join(CharSequence delimiter, Iterable tokens) {
// StringBuilder sb = new StringBuilder();
// boolean firstTime = true;
// for (Object token: tokens) {
// if (firstTime) {
// firstTime = false;
// } else {
// sb.append(delimiter);
// }
// sb.append(token);
// }
// return sb.toString();
// }
// }
| import com.baoyz.airdata.annotation.Table;
import com.baoyz.airdata.utils.TextUtils;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.element.TypeElement; | } else {
name = table.name();
}
qualifiedName = tableElement.getQualifiedName().toString();
}
public void addColumn(ColumnInfo column) {
if (columns == null)
columns = new ArrayList<>();
columns.add(column);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ColumnInfo> getColumns() {
return columns;
}
public void setColumns(List<ColumnInfo> columns) {
this.columns = columns;
}
public String getColumnDefinitions() { | // Path: compiler/src/main/java/com/baoyz/airdata/utils/TextUtils.java
// public class TextUtils {
//
// public static String join(CharSequence delimiter, Iterable tokens) {
// StringBuilder sb = new StringBuilder();
// boolean firstTime = true;
// for (Object token: tokens) {
// if (firstTime) {
// firstTime = false;
// } else {
// sb.append(delimiter);
// }
// sb.append(token);
// }
// return sb.toString();
// }
// }
// Path: compiler/src/main/java/com/baoyz/airdata/TableInfo.java
import com.baoyz.airdata.annotation.Table;
import com.baoyz.airdata.utils.TextUtils;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.element.TypeElement;
} else {
name = table.name();
}
qualifiedName = tableElement.getQualifiedName().toString();
}
public void addColumn(ColumnInfo column) {
if (columns == null)
columns = new ArrayList<>();
columns.add(column);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ColumnInfo> getColumns() {
return columns;
}
public void setColumns(List<ColumnInfo> columns) {
this.columns = columns;
}
public String getColumnDefinitions() { | return TextUtils.join(",", getColumns()); |
baoyongzhang/AirData | core/src/main/java/com/baoyz/airdata/crud/Update.java | // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
//
// Path: core/src/main/java/com/baoyz/airdata/ContentValuesWrapper.java
// public class ContentValuesWrapper {
//
// private ContentValues values;
//
// public static ContentValuesWrapper wrap(ContentValues values) {
// ContentValuesWrapper wrapper = new ContentValuesWrapper();
// wrapper.values = values;
// return wrapper;
// }
//
// public void put(String key, Boolean value) {
// values.put(key, value);
// }
//
// public void put(String key, Byte value) {
// values.put(key, value);
// }
//
// public void put(String key, Short value) {
// values.put(key, value);
// }
//
// public void put(String key, Integer value) {
// values.put(key, value);
// }
//
// public void put(String key, Long value) {
// values.put(key, value);
// }
//
// public void put(String key, Double value) {
// values.put(key, value);
// }
//
// public void put(String key, Float value) {
// values.put(key, value);
// }
//
// public void put(String key, String value) {
// values.put(key, value);
// }
//
// public void put(String key, byte[] value) {
// values.put(key, value);
// }
//
// public void put(String key, Byte[] value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// byte[] bytes = new byte[value.length];
// System.arraycopy(value, 0, bytes, 0, bytes.length);
// put(key, bytes);
// }
//
// public void put(String key, char value) {
// values.put(key, (int) value);
// }
//
// public void put(String key, Character value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// put(key, (char) value);
// }
//
// public void put(String key, Date value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// values.put(key, value.getTime());
// }
//
// public ContentValues getValues() {
// return values;
// }
// }
| import android.content.ContentValues;
import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper;
import com.baoyz.airdata.ContentValuesWrapper; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Update {
private Class table;
private String where;
private String[] whereArgs; | // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
//
// Path: core/src/main/java/com/baoyz/airdata/ContentValuesWrapper.java
// public class ContentValuesWrapper {
//
// private ContentValues values;
//
// public static ContentValuesWrapper wrap(ContentValues values) {
// ContentValuesWrapper wrapper = new ContentValuesWrapper();
// wrapper.values = values;
// return wrapper;
// }
//
// public void put(String key, Boolean value) {
// values.put(key, value);
// }
//
// public void put(String key, Byte value) {
// values.put(key, value);
// }
//
// public void put(String key, Short value) {
// values.put(key, value);
// }
//
// public void put(String key, Integer value) {
// values.put(key, value);
// }
//
// public void put(String key, Long value) {
// values.put(key, value);
// }
//
// public void put(String key, Double value) {
// values.put(key, value);
// }
//
// public void put(String key, Float value) {
// values.put(key, value);
// }
//
// public void put(String key, String value) {
// values.put(key, value);
// }
//
// public void put(String key, byte[] value) {
// values.put(key, value);
// }
//
// public void put(String key, Byte[] value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// byte[] bytes = new byte[value.length];
// System.arraycopy(value, 0, bytes, 0, bytes.length);
// put(key, bytes);
// }
//
// public void put(String key, char value) {
// values.put(key, (int) value);
// }
//
// public void put(String key, Character value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// put(key, (char) value);
// }
//
// public void put(String key, Date value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// values.put(key, value.getTime());
// }
//
// public ContentValues getValues() {
// return values;
// }
// }
// Path: core/src/main/java/com/baoyz/airdata/crud/Update.java
import android.content.ContentValues;
import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper;
import com.baoyz.airdata.ContentValuesWrapper;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Update {
private Class table;
private String where;
private String[] whereArgs; | private ContentValuesWrapper values; |
baoyongzhang/AirData | core/src/main/java/com/baoyz/airdata/crud/Update.java | // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
//
// Path: core/src/main/java/com/baoyz/airdata/ContentValuesWrapper.java
// public class ContentValuesWrapper {
//
// private ContentValues values;
//
// public static ContentValuesWrapper wrap(ContentValues values) {
// ContentValuesWrapper wrapper = new ContentValuesWrapper();
// wrapper.values = values;
// return wrapper;
// }
//
// public void put(String key, Boolean value) {
// values.put(key, value);
// }
//
// public void put(String key, Byte value) {
// values.put(key, value);
// }
//
// public void put(String key, Short value) {
// values.put(key, value);
// }
//
// public void put(String key, Integer value) {
// values.put(key, value);
// }
//
// public void put(String key, Long value) {
// values.put(key, value);
// }
//
// public void put(String key, Double value) {
// values.put(key, value);
// }
//
// public void put(String key, Float value) {
// values.put(key, value);
// }
//
// public void put(String key, String value) {
// values.put(key, value);
// }
//
// public void put(String key, byte[] value) {
// values.put(key, value);
// }
//
// public void put(String key, Byte[] value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// byte[] bytes = new byte[value.length];
// System.arraycopy(value, 0, bytes, 0, bytes.length);
// put(key, bytes);
// }
//
// public void put(String key, char value) {
// values.put(key, (int) value);
// }
//
// public void put(String key, Character value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// put(key, (char) value);
// }
//
// public void put(String key, Date value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// values.put(key, value.getTime());
// }
//
// public ContentValues getValues() {
// return values;
// }
// }
| import android.content.ContentValues;
import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper;
import com.baoyz.airdata.ContentValuesWrapper; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Update {
private Class table;
private String where;
private String[] whereArgs;
private ContentValuesWrapper values;
| // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
//
// Path: core/src/main/java/com/baoyz/airdata/ContentValuesWrapper.java
// public class ContentValuesWrapper {
//
// private ContentValues values;
//
// public static ContentValuesWrapper wrap(ContentValues values) {
// ContentValuesWrapper wrapper = new ContentValuesWrapper();
// wrapper.values = values;
// return wrapper;
// }
//
// public void put(String key, Boolean value) {
// values.put(key, value);
// }
//
// public void put(String key, Byte value) {
// values.put(key, value);
// }
//
// public void put(String key, Short value) {
// values.put(key, value);
// }
//
// public void put(String key, Integer value) {
// values.put(key, value);
// }
//
// public void put(String key, Long value) {
// values.put(key, value);
// }
//
// public void put(String key, Double value) {
// values.put(key, value);
// }
//
// public void put(String key, Float value) {
// values.put(key, value);
// }
//
// public void put(String key, String value) {
// values.put(key, value);
// }
//
// public void put(String key, byte[] value) {
// values.put(key, value);
// }
//
// public void put(String key, Byte[] value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// byte[] bytes = new byte[value.length];
// System.arraycopy(value, 0, bytes, 0, bytes.length);
// put(key, bytes);
// }
//
// public void put(String key, char value) {
// values.put(key, (int) value);
// }
//
// public void put(String key, Character value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// put(key, (char) value);
// }
//
// public void put(String key, Date value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// values.put(key, value.getTime());
// }
//
// public ContentValues getValues() {
// return values;
// }
// }
// Path: core/src/main/java/com/baoyz/airdata/crud/Update.java
import android.content.ContentValues;
import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper;
import com.baoyz.airdata.ContentValuesWrapper;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Update {
private Class table;
private String where;
private String[] whereArgs;
private ContentValuesWrapper values;
| private AbstractDatabase database; |
baoyongzhang/AirData | core/src/main/java/com/baoyz/airdata/crud/Update.java | // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
//
// Path: core/src/main/java/com/baoyz/airdata/ContentValuesWrapper.java
// public class ContentValuesWrapper {
//
// private ContentValues values;
//
// public static ContentValuesWrapper wrap(ContentValues values) {
// ContentValuesWrapper wrapper = new ContentValuesWrapper();
// wrapper.values = values;
// return wrapper;
// }
//
// public void put(String key, Boolean value) {
// values.put(key, value);
// }
//
// public void put(String key, Byte value) {
// values.put(key, value);
// }
//
// public void put(String key, Short value) {
// values.put(key, value);
// }
//
// public void put(String key, Integer value) {
// values.put(key, value);
// }
//
// public void put(String key, Long value) {
// values.put(key, value);
// }
//
// public void put(String key, Double value) {
// values.put(key, value);
// }
//
// public void put(String key, Float value) {
// values.put(key, value);
// }
//
// public void put(String key, String value) {
// values.put(key, value);
// }
//
// public void put(String key, byte[] value) {
// values.put(key, value);
// }
//
// public void put(String key, Byte[] value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// byte[] bytes = new byte[value.length];
// System.arraycopy(value, 0, bytes, 0, bytes.length);
// put(key, bytes);
// }
//
// public void put(String key, char value) {
// values.put(key, (int) value);
// }
//
// public void put(String key, Character value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// put(key, (char) value);
// }
//
// public void put(String key, Date value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// values.put(key, value.getTime());
// }
//
// public ContentValues getValues() {
// return values;
// }
// }
| import android.content.ContentValues;
import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper;
import com.baoyz.airdata.ContentValuesWrapper; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Update {
private Class table;
private String where;
private String[] whereArgs;
private ContentValuesWrapper values;
private AbstractDatabase database; | // Path: core/src/main/java/com/baoyz/airdata/AbstractDatabase.java
// public abstract class AbstractDatabase {
//
// AirDatabaseHelper mDatabaseHelper;
// private Context mContext;
//
// public AbstractDatabase(Context context) {
// if (!(context instanceof Application)) {
// // TODO throw exception
// }
// mContext = context;
// mDatabaseHelper = new AirDatabaseHelperImpl(mContext, this);
// }
//
// public SQLiteDatabase getDatabase() {
// return mDatabaseHelper.getDatabase();
// }
//
// public String getName() {
// return null;
// }
//
// public int getVersion() {
// return 1;
// }
//
// public <T> List<T> query(Class<T> clazz) {
// return mDatabaseHelper.queryAll(clazz);
// }
//
// public long save(Object obj) {
// return mDatabaseHelper.save(obj);
// }
//
// public long delete(Object obj) {
// return mDatabaseHelper.delete(obj);
// }
//
// public long update(Object obj) {
// return mDatabaseHelper.update(obj);
// }
//
// public void beginTransaction(){
// mDatabaseHelper.getDatabase().beginTransaction();
// }
//
// public void endTransaction(){
// mDatabaseHelper.getDatabase().endTransaction();
// }
//
// public void setTransactionSuccessful(){
// mDatabaseHelper.getDatabase().setTransactionSuccessful();
// }
//
// public AirDatabaseHelper getDatabaseHelper() {
// return mDatabaseHelper;
// }
// }
//
// Path: core/src/main/java/com/baoyz/airdata/AirDatabaseHelper.java
// public interface AirDatabaseHelper {
//
// long save(Object obj);
//
// int delete(Object obj);
//
// int update(Object obj);
//
// <T> int update(Class<T> clazz, ContentValuesWrapper valuesWrapper, String where, String[] whereArgs);
//
// <T> int delete(Class<T> clazz, String where, String[] whereArgs);
//
// <T> List<T> queryAll(Class<T> clazz);
//
// <T> List<T> query(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// <T> Cursor rawQuery(Class<T> clazz, boolean distinct, String[] columns,
// String selection, String[] selectionArgs, String groupBy,
// String having, String orderBy, String limit);
//
// void destory();
//
// SQLiteDatabase getDatabase();
// }
//
// Path: core/src/main/java/com/baoyz/airdata/ContentValuesWrapper.java
// public class ContentValuesWrapper {
//
// private ContentValues values;
//
// public static ContentValuesWrapper wrap(ContentValues values) {
// ContentValuesWrapper wrapper = new ContentValuesWrapper();
// wrapper.values = values;
// return wrapper;
// }
//
// public void put(String key, Boolean value) {
// values.put(key, value);
// }
//
// public void put(String key, Byte value) {
// values.put(key, value);
// }
//
// public void put(String key, Short value) {
// values.put(key, value);
// }
//
// public void put(String key, Integer value) {
// values.put(key, value);
// }
//
// public void put(String key, Long value) {
// values.put(key, value);
// }
//
// public void put(String key, Double value) {
// values.put(key, value);
// }
//
// public void put(String key, Float value) {
// values.put(key, value);
// }
//
// public void put(String key, String value) {
// values.put(key, value);
// }
//
// public void put(String key, byte[] value) {
// values.put(key, value);
// }
//
// public void put(String key, Byte[] value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// byte[] bytes = new byte[value.length];
// System.arraycopy(value, 0, bytes, 0, bytes.length);
// put(key, bytes);
// }
//
// public void put(String key, char value) {
// values.put(key, (int) value);
// }
//
// public void put(String key, Character value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// put(key, (char) value);
// }
//
// public void put(String key, Date value) {
// if (value == null) {
// values.putNull(key);
// return;
// }
// values.put(key, value.getTime());
// }
//
// public ContentValues getValues() {
// return values;
// }
// }
// Path: core/src/main/java/com/baoyz/airdata/crud/Update.java
import android.content.ContentValues;
import com.baoyz.airdata.AbstractDatabase;
import com.baoyz.airdata.AirDatabaseHelper;
import com.baoyz.airdata.ContentValuesWrapper;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 baoyongzhang <baoyz94@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.baoyz.airdata.crud;
/**
* AirData
* Created by baoyz on 15/7/19.
*/
public class Update {
private Class table;
private String where;
private String[] whereArgs;
private ContentValuesWrapper values;
private AbstractDatabase database; | private AirDatabaseHelper helper; |
baoyongzhang/AirData | compiler/src/main/java/com/baoyz/airdata/utils/DataType.java | // Path: core/src/main/java/com/baoyz/airdata/serializer/ValueSerializer.java
// public interface ValueSerializer<S, D> {
//
// Class<S> getSourceClass();
// Class<D> getDistClass();
//
// D serialize(S source);
// S deserialize(D source);
// }
| import com.baoyz.airdata.serializer.ValueSerializer;
import java.util.HashMap;
import javax.lang.model.type.TypeMirror; |
public static boolean isBoolean(TypeMirror type) {
return "boolean".equals(type.toString());
}
public static String getTypeString(TypeMirror type) {
SQLiteType sqLiteType = TYPE_MAP.get(type.toString());
if (sqLiteType != null) {
switch (sqLiteType) {
case INTEGER:
return "INTEGER";
case REAL:
return "REAL";
case TEXT:
return "TEXT";
case BLOB:
return "BLOB";
}
}
return "NULL";
}
public static String getCursorMethod(TypeMirror type) {
return METHOD_MAP.get(type.toString());
}
public static boolean isSupport(TypeMirror type) {
return getCursorMethod(type) != null;
}
| // Path: core/src/main/java/com/baoyz/airdata/serializer/ValueSerializer.java
// public interface ValueSerializer<S, D> {
//
// Class<S> getSourceClass();
// Class<D> getDistClass();
//
// D serialize(S source);
// S deserialize(D source);
// }
// Path: compiler/src/main/java/com/baoyz/airdata/utils/DataType.java
import com.baoyz.airdata.serializer.ValueSerializer;
import java.util.HashMap;
import javax.lang.model.type.TypeMirror;
public static boolean isBoolean(TypeMirror type) {
return "boolean".equals(type.toString());
}
public static String getTypeString(TypeMirror type) {
SQLiteType sqLiteType = TYPE_MAP.get(type.toString());
if (sqLiteType != null) {
switch (sqLiteType) {
case INTEGER:
return "INTEGER";
case REAL:
return "REAL";
case TEXT:
return "TEXT";
case BLOB:
return "BLOB";
}
}
return "NULL";
}
public static String getCursorMethod(TypeMirror type) {
return METHOD_MAP.get(type.toString());
}
public static boolean isSupport(TypeMirror type) {
return getCursorMethod(type) != null;
}
| public static ValueSerializer getSerializer(TypeMirror type) { |
jcodagnone/jiolsucker | iolsucker/src/main/java/ar/com/leak/iolsucker/view/common/TagRepublishRepositoryStrategy.java | // Path: api/src/main/java/ar/com/leak/iolsucker/model/Material.java
// public interface Material {
//
// /**
// * @return <code>true</code> si el material es un directorio
// */
// boolean isFolder();
//
// /**
// * @return nombre del material. es un path relativo.
// * Ej: "practicas/tp1/Ej1.pdf"
// */
// String getName();
//
// /**
// * @return una descripción del archivo
// */
// String getDescription();
//
// /**
// * @return un <code>InputStream</code> que permitirá leer el contenido del
// * material
// *
// * @throws IOException si hubo problemas en conseguir el stream
// */
// InputStream getInputStream() throws IOException;
//
// /**
// *
// * @return el tamaño estimado del archivo. Debe retornar 0 o un número
// * negativo si se desconoce
// */
// long getEstimatedSize();
//
// /**
// * @return la fecha de la ultima modificación del archivo.
// * Si no está disponible, la convención es retornar la fecha del
// * inicio de la epoch (unix!)
// */
// Date getLastModified();
// }
| import java.io.File;
import java.util.*;
import org.apache.commons.lang.Validate;
import ar.com.leak.iolsucker.model.Material; | /**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.view.common;
/**
* Implementación de <code>RepublishRepositoryStrategy</code> que renombra
* el archivo existente a uno en el mismo directorio, pero agregandole antes
* de la extensión
* <p/>
* No me gusta mucho, porque estamos esperando que nadie publique un archivo
* con el mismo nombre...por hay lo mejor es hacer otra estrategia que mueva
* los archivos a un atico.
*
* @author Juan F. Codagnone
* @since Sep 6, 2005
*/
public class TagRepublishRepositoryStrategy
implements RepublishRepositoryStrategy {
/** mensaje para agregarle al archivo viejo */
private final String tag;
/** @see #OldRepublishRepositoryStrategy(String) */
public TagRepublishRepositoryStrategy() {
this("old_republicado_");
}
/**
* Creates the OldRepublishRepositoryStrategy.
*
* @param tag mensaje a agregarle al archivo viejo
*/
public TagRepublishRepositoryStrategy(final String tag) {
Validate.notNull(tag, "tag");
Validate.notEmpty(tag);
this.tag = tag;
}
/** @see RepublishRepositoryStrategy#republish(Material, java.io.File) */ | // Path: api/src/main/java/ar/com/leak/iolsucker/model/Material.java
// public interface Material {
//
// /**
// * @return <code>true</code> si el material es un directorio
// */
// boolean isFolder();
//
// /**
// * @return nombre del material. es un path relativo.
// * Ej: "practicas/tp1/Ej1.pdf"
// */
// String getName();
//
// /**
// * @return una descripción del archivo
// */
// String getDescription();
//
// /**
// * @return un <code>InputStream</code> que permitirá leer el contenido del
// * material
// *
// * @throws IOException si hubo problemas en conseguir el stream
// */
// InputStream getInputStream() throws IOException;
//
// /**
// *
// * @return el tamaño estimado del archivo. Debe retornar 0 o un número
// * negativo si se desconoce
// */
// long getEstimatedSize();
//
// /**
// * @return la fecha de la ultima modificación del archivo.
// * Si no está disponible, la convención es retornar la fecha del
// * inicio de la epoch (unix!)
// */
// Date getLastModified();
// }
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/common/TagRepublishRepositoryStrategy.java
import java.io.File;
import java.util.*;
import org.apache.commons.lang.Validate;
import ar.com.leak.iolsucker.model.Material;
/**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.view.common;
/**
* Implementación de <code>RepublishRepositoryStrategy</code> que renombra
* el archivo existente a uno en el mismo directorio, pero agregandole antes
* de la extensión
* <p/>
* No me gusta mucho, porque estamos esperando que nadie publique un archivo
* con el mismo nombre...por hay lo mejor es hacer otra estrategia que mueva
* los archivos a un atico.
*
* @author Juan F. Codagnone
* @since Sep 6, 2005
*/
public class TagRepublishRepositoryStrategy
implements RepublishRepositoryStrategy {
/** mensaje para agregarle al archivo viejo */
private final String tag;
/** @see #OldRepublishRepositoryStrategy(String) */
public TagRepublishRepositoryStrategy() {
this("old_republicado_");
}
/**
* Creates the OldRepublishRepositoryStrategy.
*
* @param tag mensaje a agregarle al archivo viejo
*/
public TagRepublishRepositoryStrategy(final String tag) {
Validate.notNull(tag, "tag");
Validate.notEmpty(tag);
this.tag = tag;
}
/** @see RepublishRepositoryStrategy#republish(Material, java.io.File) */ | public final void republish(final Material material, |
jcodagnone/jiolsucker | sharepoint/src/main/java/com/zaubersoftware/jiol/sharepoint/SharepointIolDAO.java | // Path: api/src/main/java/ar/com/leak/iolsucker/model/Course.java
// public interface Course {
//
// /**
// * @return el nombre del recurso. El nombre es un path. Por ejemplo:
// * "practicas/tp1/Ej1.pdf". No debe tener una / al principio.
// */
// String getName();
//
// /**
// * @return el código de la materia. Ej: "71.04"
// */
// String getCode();
//
// /**
// * @return el nivel de la materia. tipicamente 4 para materias de grado
// */
// int getLevel();
//
// /**
// *
// * @return una colleción con elementos de tipo <code>Material</code>, con
// * el material didactico de la materia.
// * @see Material
// */
// Collection <Material> getFiles();
//
// /** entero que corresponde a materias de grado...todo: enum */
// int LEVEL_GRADO = 4;
// }
//
// Path: api/src/main/java/ar/com/leak/iolsucker/model/IolDAO.java
// public interface IolDAO {
//
// /**
// * @return una coleccion de <code>Course</code> con los cursos a los que
// * el usuario está registrado
// */
// Collection <Course> getUserCourses();
//
// /**
// * @return una colección con las noticias no leidas
// */
// Collection <News> getUnreadNews();
//
// /**
// *
// * @return una colección con todas las noticias
// */
// Collection <News> getNews();
//
//
// /**
// * Le indica al DAO que puede liberar sus recursos
// *
// * @throws Exception cuando hay algún error
// */
// void dispose() throws Exception;
// }
//
// Path: api/src/main/java/ar/com/leak/iolsucker/model/LoginInfo.java
// public interface LoginInfo {
//
// /**
// * @return el nombre de usuario
// */
// String getUsername();
//
// /**
// * @return la password
// */
// String getPassword();
// }
//
// Path: api/src/main/java/ar/com/leak/iolsucker/model/News.java
// public interface News {
// /**
// * @return el título de la noticia
// */
// String getTitle();
//
// /**
// * @return el contenido de la noticia
// */
// String getBody();
//
// /**
// * marca como leida a la noticia
// *
// */
// void markAsReaded();
// }
| import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;
import javax.xml.ws.soap.SOAPFaultException;
import org.apache.commons.lang.UnhandledException;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ar.com.leak.iolsucker.model.Course;
import ar.com.leak.iolsucker.model.IolDAO;
import ar.com.leak.iolsucker.model.LoginInfo;
import ar.com.leak.iolsucker.model.News;
import ar.com.zauber.commons.async.DelegateTaskExecutor;
import ar.com.zauber.commons.async.WaitableExecutor;
import com.microsoft.schemas.sharepoint.soap.ArrayOfSFPUrl;
import com.microsoft.schemas.sharepoint.soap.ArrayOfSListWithTime;
import com.microsoft.schemas.sharepoint.soap.ArrayOfSWebWithTime;
import com.microsoft.schemas.sharepoint.soap.ArrayOfString;
import com.microsoft.schemas.sharepoint.soap.SWebMetadata;
import com.microsoft.schemas.sharepoint.soap.SWebWithTime;
import com.microsoft.schemas.sharepoint.soap.SiteData;
import com.microsoft.schemas.sharepoint.soap.SiteDataSoap; | /**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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.zaubersoftware.jiol.sharepoint;
/**
* Implementation agains IOL2 (sharepoint based)
*
*
* @author Juan F. Codagnone
* @since Mar 8, 2011
*/
public class SharepointIolDAO implements IolDAO {
private final LoginInfo login;
private final Logger logger = LoggerFactory.getLogger(SharepointIolDAO.class);
private final URISharepointStrategy uriStrategy;
/**
* Creates the SharepointIolDAO.
*/
public SharepointIolDAO(final LoginInfo login,
final URISharepointStrategy uriSharepointStrategy) throws MalformedURLException, URISyntaxException {
Validate.notNull(login);
Validate.notNull(uriSharepointStrategy);
this.login = login;
this.uriStrategy = uriSharepointStrategy;
}
| // Path: api/src/main/java/ar/com/leak/iolsucker/model/Course.java
// public interface Course {
//
// /**
// * @return el nombre del recurso. El nombre es un path. Por ejemplo:
// * "practicas/tp1/Ej1.pdf". No debe tener una / al principio.
// */
// String getName();
//
// /**
// * @return el código de la materia. Ej: "71.04"
// */
// String getCode();
//
// /**
// * @return el nivel de la materia. tipicamente 4 para materias de grado
// */
// int getLevel();
//
// /**
// *
// * @return una colleción con elementos de tipo <code>Material</code>, con
// * el material didactico de la materia.
// * @see Material
// */
// Collection <Material> getFiles();
//
// /** entero que corresponde a materias de grado...todo: enum */
// int LEVEL_GRADO = 4;
// }
//
// Path: api/src/main/java/ar/com/leak/iolsucker/model/IolDAO.java
// public interface IolDAO {
//
// /**
// * @return una coleccion de <code>Course</code> con los cursos a los que
// * el usuario está registrado
// */
// Collection <Course> getUserCourses();
//
// /**
// * @return una colección con las noticias no leidas
// */
// Collection <News> getUnreadNews();
//
// /**
// *
// * @return una colección con todas las noticias
// */
// Collection <News> getNews();
//
//
// /**
// * Le indica al DAO que puede liberar sus recursos
// *
// * @throws Exception cuando hay algún error
// */
// void dispose() throws Exception;
// }
//
// Path: api/src/main/java/ar/com/leak/iolsucker/model/LoginInfo.java
// public interface LoginInfo {
//
// /**
// * @return el nombre de usuario
// */
// String getUsername();
//
// /**
// * @return la password
// */
// String getPassword();
// }
//
// Path: api/src/main/java/ar/com/leak/iolsucker/model/News.java
// public interface News {
// /**
// * @return el título de la noticia
// */
// String getTitle();
//
// /**
// * @return el contenido de la noticia
// */
// String getBody();
//
// /**
// * marca como leida a la noticia
// *
// */
// void markAsReaded();
// }
// Path: sharepoint/src/main/java/com/zaubersoftware/jiol/sharepoint/SharepointIolDAO.java
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;
import javax.xml.ws.soap.SOAPFaultException;
import org.apache.commons.lang.UnhandledException;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ar.com.leak.iolsucker.model.Course;
import ar.com.leak.iolsucker.model.IolDAO;
import ar.com.leak.iolsucker.model.LoginInfo;
import ar.com.leak.iolsucker.model.News;
import ar.com.zauber.commons.async.DelegateTaskExecutor;
import ar.com.zauber.commons.async.WaitableExecutor;
import com.microsoft.schemas.sharepoint.soap.ArrayOfSFPUrl;
import com.microsoft.schemas.sharepoint.soap.ArrayOfSListWithTime;
import com.microsoft.schemas.sharepoint.soap.ArrayOfSWebWithTime;
import com.microsoft.schemas.sharepoint.soap.ArrayOfString;
import com.microsoft.schemas.sharepoint.soap.SWebMetadata;
import com.microsoft.schemas.sharepoint.soap.SWebWithTime;
import com.microsoft.schemas.sharepoint.soap.SiteData;
import com.microsoft.schemas.sharepoint.soap.SiteDataSoap;
/**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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.zaubersoftware.jiol.sharepoint;
/**
* Implementation agains IOL2 (sharepoint based)
*
*
* @author Juan F. Codagnone
* @since Mar 8, 2011
*/
public class SharepointIolDAO implements IolDAO {
private final LoginInfo login;
private final Logger logger = LoggerFactory.getLogger(SharepointIolDAO.class);
private final URISharepointStrategy uriStrategy;
/**
* Creates the SharepointIolDAO.
*/
public SharepointIolDAO(final LoginInfo login,
final URISharepointStrategy uriSharepointStrategy) throws MalformedURLException, URISyntaxException {
Validate.notNull(login);
Validate.notNull(uriSharepointStrategy);
this.login = login;
this.uriStrategy = uriSharepointStrategy;
}
| private Collection<Course> courses; |
jcodagnone/jiolsucker | iolsucker/src/main/java/ar/com/leak/iolsucker/controller/ClearNews.java | // Path: api/src/main/java/ar/com/leak/iolsucker/model/IolDAO.java
// public interface IolDAO {
//
// /**
// * @return una coleccion de <code>Course</code> con los cursos a los que
// * el usuario está registrado
// */
// Collection <Course> getUserCourses();
//
// /**
// * @return una colección con las noticias no leidas
// */
// Collection <News> getUnreadNews();
//
// /**
// *
// * @return una colección con todas las noticias
// */
// Collection <News> getNews();
//
//
// /**
// * Le indica al DAO que puede liberar sus recursos
// *
// * @throws Exception cuando hay algún error
// */
// void dispose() throws Exception;
// }
//
// Path: api/src/main/java/ar/com/leak/iolsucker/model/News.java
// public interface News {
// /**
// * @return el título de la noticia
// */
// String getTitle();
//
// /**
// * @return el contenido de la noticia
// */
// String getBody();
//
// /**
// * marca como leida a la noticia
// *
// */
// void markAsReaded();
// }
| import org.apache.commons.collections.Closure;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ar.com.leak.iolsucker.model.IolDAO;
import ar.com.leak.iolsucker.model.News; | /**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.controller;
/**
*
* Marca como leidas a todas las noticias de IOL
*
* @author Juan F. Codagnone
* @since Jul 5, 2005
*/
public class ClearNews implements Runnable {
/** class logger */
private final Logger logger = LoggerFactory.getLogger(ClearNews.class);
/** dao a usar */
private final IolDAO dao;
/**
* Crea el ClearNews.
*
* @param dao el dao usado por el controlador
*/
public ClearNews(final IolDAO dao) {
this.dao = dao;
}
/** @see Runnable#run() */
public final void run() {
CollectionUtils.forAllDo(dao.getUnreadNews(), new Closure() {
public void execute(final Object object) { | // Path: api/src/main/java/ar/com/leak/iolsucker/model/IolDAO.java
// public interface IolDAO {
//
// /**
// * @return una coleccion de <code>Course</code> con los cursos a los que
// * el usuario está registrado
// */
// Collection <Course> getUserCourses();
//
// /**
// * @return una colección con las noticias no leidas
// */
// Collection <News> getUnreadNews();
//
// /**
// *
// * @return una colección con todas las noticias
// */
// Collection <News> getNews();
//
//
// /**
// * Le indica al DAO que puede liberar sus recursos
// *
// * @throws Exception cuando hay algún error
// */
// void dispose() throws Exception;
// }
//
// Path: api/src/main/java/ar/com/leak/iolsucker/model/News.java
// public interface News {
// /**
// * @return el título de la noticia
// */
// String getTitle();
//
// /**
// * @return el contenido de la noticia
// */
// String getBody();
//
// /**
// * marca como leida a la noticia
// *
// */
// void markAsReaded();
// }
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/controller/ClearNews.java
import org.apache.commons.collections.Closure;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ar.com.leak.iolsucker.model.IolDAO;
import ar.com.leak.iolsucker.model.News;
/**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.controller;
/**
*
* Marca como leidas a todas las noticias de IOL
*
* @author Juan F. Codagnone
* @since Jul 5, 2005
*/
public class ClearNews implements Runnable {
/** class logger */
private final Logger logger = LoggerFactory.getLogger(ClearNews.class);
/** dao a usar */
private final IolDAO dao;
/**
* Crea el ClearNews.
*
* @param dao el dao usado por el controlador
*/
public ClearNews(final IolDAO dao) {
this.dao = dao;
}
/** @see Runnable#run() */
public final void run() {
CollectionUtils.forAllDo(dao.getUnreadNews(), new Closure() {
public void execute(final Object object) { | final News news = (News)object; |
jcodagnone/jiolsucker | iolsucker/src/main/java/ar/com/leak/iolsucker/view/common/NullRepublishRepositoryStrategy.java | // Path: api/src/main/java/ar/com/leak/iolsucker/model/Material.java
// public interface Material {
//
// /**
// * @return <code>true</code> si el material es un directorio
// */
// boolean isFolder();
//
// /**
// * @return nombre del material. es un path relativo.
// * Ej: "practicas/tp1/Ej1.pdf"
// */
// String getName();
//
// /**
// * @return una descripción del archivo
// */
// String getDescription();
//
// /**
// * @return un <code>InputStream</code> que permitirá leer el contenido del
// * material
// *
// * @throws IOException si hubo problemas en conseguir el stream
// */
// InputStream getInputStream() throws IOException;
//
// /**
// *
// * @return el tamaño estimado del archivo. Debe retornar 0 o un número
// * negativo si se desconoce
// */
// long getEstimatedSize();
//
// /**
// * @return la fecha de la ultima modificación del archivo.
// * Si no está disponible, la convención es retornar la fecha del
// * inicio de la epoch (unix!)
// */
// Date getLastModified();
// }
| import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ar.com.leak.iolsucker.model.Material; | /**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.view.common;
/**
* Implementación trucha de <code>RepublishRepositoryStrategy</code>
*
* @author Juan F. Codagnone
* @since Sep 6, 2005
*/
public class NullRepublishRepositoryStrategy
implements RepublishRepositoryStrategy {
/** the logger ...*/
private final Logger logger = LoggerFactory.getLogger(
NullRepublishRepositoryStrategy.class);
/** @see RepublishRepositoryStrategy#republish(Material, java.io.File) */ | // Path: api/src/main/java/ar/com/leak/iolsucker/model/Material.java
// public interface Material {
//
// /**
// * @return <code>true</code> si el material es un directorio
// */
// boolean isFolder();
//
// /**
// * @return nombre del material. es un path relativo.
// * Ej: "practicas/tp1/Ej1.pdf"
// */
// String getName();
//
// /**
// * @return una descripción del archivo
// */
// String getDescription();
//
// /**
// * @return un <code>InputStream</code> que permitirá leer el contenido del
// * material
// *
// * @throws IOException si hubo problemas en conseguir el stream
// */
// InputStream getInputStream() throws IOException;
//
// /**
// *
// * @return el tamaño estimado del archivo. Debe retornar 0 o un número
// * negativo si se desconoce
// */
// long getEstimatedSize();
//
// /**
// * @return la fecha de la ultima modificación del archivo.
// * Si no está disponible, la convención es retornar la fecha del
// * inicio de la epoch (unix!)
// */
// Date getLastModified();
// }
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/common/NullRepublishRepositoryStrategy.java
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ar.com.leak.iolsucker.model.Material;
/**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.view.common;
/**
* Implementación trucha de <code>RepublishRepositoryStrategy</code>
*
* @author Juan F. Codagnone
* @since Sep 6, 2005
*/
public class NullRepublishRepositoryStrategy
implements RepublishRepositoryStrategy {
/** the logger ...*/
private final Logger logger = LoggerFactory.getLogger(
NullRepublishRepositoryStrategy.class);
/** @see RepublishRepositoryStrategy#republish(Material, java.io.File) */ | public final void republish(final Material material, |
jcodagnone/jiolsucker | sharepoint/src/main/java/com/zaubersoftware/jiol/sharepoint/JAXWSharepointServiceFactory.java | // Path: api/src/main/java/ar/com/leak/iolsucker/model/LoginInfo.java
// public interface LoginInfo {
//
// /**
// * @return el nombre de usuario
// */
// String getUsername();
//
// /**
// * @return la password
// */
// String getPassword();
// }
| import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.Map;
import javax.xml.ws.BindingProvider;
import org.apache.commons.lang.UnhandledException;
import org.apache.commons.lang.Validate;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.http.Header;
import org.apache.http.HttpVersion;
import org.apache.http.client.params.ClientParamBean;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParamBean;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParamBean;
import ar.com.leak.iolsucker.model.LoginInfo;
import ar.com.zauber.leviathan.api.URIFetcher;
import ar.com.zauber.leviathan.impl.httpclient.HTTPClientURIFetcher;
import ar.com.zauber.leviathan.impl.httpclient.charset.FixedCharsetStrategy;
import com.microsoft.schemas.sharepoint.soap.Authentication;
import com.microsoft.schemas.sharepoint.soap.AuthenticationSoap;
import com.microsoft.schemas.sharepoint.soap.LoginErrorCode;
import com.microsoft.schemas.sharepoint.soap.LoginResult; | /**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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.zaubersoftware.jiol.sharepoint;
/**
* Maneja autenticacion de servicios JAX-WS
*
* @author Juan F. Codagnone
* @since Mar 8, 2011
*/
public class JAXWSharepointServiceFactory implements SharepointServiceFactory {
private final URIFetcher uriFetcher;
private final Map<?, ?> cookies;
/**
* Creates the JAXWSharepointServiceFactory
*
*/
public JAXWSharepointServiceFactory(final URISharepointStrategy uriStrategy, | // Path: api/src/main/java/ar/com/leak/iolsucker/model/LoginInfo.java
// public interface LoginInfo {
//
// /**
// * @return el nombre de usuario
// */
// String getUsername();
//
// /**
// * @return la password
// */
// String getPassword();
// }
// Path: sharepoint/src/main/java/com/zaubersoftware/jiol/sharepoint/JAXWSharepointServiceFactory.java
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.Map;
import javax.xml.ws.BindingProvider;
import org.apache.commons.lang.UnhandledException;
import org.apache.commons.lang.Validate;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.http.Header;
import org.apache.http.HttpVersion;
import org.apache.http.client.params.ClientParamBean;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParamBean;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParamBean;
import ar.com.leak.iolsucker.model.LoginInfo;
import ar.com.zauber.leviathan.api.URIFetcher;
import ar.com.zauber.leviathan.impl.httpclient.HTTPClientURIFetcher;
import ar.com.zauber.leviathan.impl.httpclient.charset.FixedCharsetStrategy;
import com.microsoft.schemas.sharepoint.soap.Authentication;
import com.microsoft.schemas.sharepoint.soap.AuthenticationSoap;
import com.microsoft.schemas.sharepoint.soap.LoginErrorCode;
import com.microsoft.schemas.sharepoint.soap.LoginResult;
/**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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.zaubersoftware.jiol.sharepoint;
/**
* Maneja autenticacion de servicios JAX-WS
*
* @author Juan F. Codagnone
* @since Mar 8, 2011
*/
public class JAXWSharepointServiceFactory implements SharepointServiceFactory {
private final URIFetcher uriFetcher;
private final Map<?, ?> cookies;
/**
* Creates the JAXWSharepointServiceFactory
*
*/
public JAXWSharepointServiceFactory(final URISharepointStrategy uriStrategy, | final LoginInfo credentialsProvider) { |
jcodagnone/jiolsucker | iolsucker/src/main/java/ar/com/leak/iolsucker/container/swing/ProgressView.java | // Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/common/JTextAreaAppender.java
// public class JTextAreaAppender extends AppenderSkeleton {
// /** visual component */
// private final JTextArea area = new JTextArea();
// /** layout log4j layout to use (injected) */
// private final Layout layout;
// /** number of rows to show */
// private static final int NUMBER_OF_ROWS = 10;
// /**
// * Crea el JTextAreaAppend.
// * @param layout log4j layout to use
// */
// public JTextAreaAppender(final Layout layout) {
// this.layout = layout;
// area.setRows(NUMBER_OF_ROWS);
// area.setEditable(false);
// area.setLineWrap(true);
// }
//
// /**
// * @return the visual component
// */
// public final JComponent asJComponent() {
// return area;
// }
//
// /** @see AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent) */
// protected final void append(final LoggingEvent event) {
// area.append(layout.format(event));
// }
//
// /** @see org.apache.log4j.Appender#close() */
// public final void close() {
// // nothing to do
// }
//
// /** @see org.apache.log4j.Appender#requiresLayout() */
// public final boolean requiresLayout() {
// return false;
// }
// }
| import javax.swing.*;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.Filter;
import ar.com.leak.iolsucker.view.common.JTextAreaAppender; | /**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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.
*/
/*
/*
* Copyright 2005 Juan F. Codagnone <juam at users dot sourceforge dot net>
*
* 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 ar.com.leak.iolsucker.container.swing;
/**
* TODO Agregar comentarios pertinentes
*
* @author Juan F. Codagnone
* @since Apr 12, 2005
*/
public class ProgressView extends Box {
/**
* Creates the ProgressView.
*
* @param layout layout log4j
* @param filter filtro log4j
* @param action que hace el boton de la vista
*/
public ProgressView(final Layout layout, final Filter filter,
final Action action) {
super(BoxLayout.Y_AXIS); | // Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/common/JTextAreaAppender.java
// public class JTextAreaAppender extends AppenderSkeleton {
// /** visual component */
// private final JTextArea area = new JTextArea();
// /** layout log4j layout to use (injected) */
// private final Layout layout;
// /** number of rows to show */
// private static final int NUMBER_OF_ROWS = 10;
// /**
// * Crea el JTextAreaAppend.
// * @param layout log4j layout to use
// */
// public JTextAreaAppender(final Layout layout) {
// this.layout = layout;
// area.setRows(NUMBER_OF_ROWS);
// area.setEditable(false);
// area.setLineWrap(true);
// }
//
// /**
// * @return the visual component
// */
// public final JComponent asJComponent() {
// return area;
// }
//
// /** @see AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent) */
// protected final void append(final LoggingEvent event) {
// area.append(layout.format(event));
// }
//
// /** @see org.apache.log4j.Appender#close() */
// public final void close() {
// // nothing to do
// }
//
// /** @see org.apache.log4j.Appender#requiresLayout() */
// public final boolean requiresLayout() {
// return false;
// }
// }
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/container/swing/ProgressView.java
import javax.swing.*;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.Filter;
import ar.com.leak.iolsucker.view.common.JTextAreaAppender;
/**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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.
*/
/*
/*
* Copyright 2005 Juan F. Codagnone <juam at users dot sourceforge dot net>
*
* 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 ar.com.leak.iolsucker.container.swing;
/**
* TODO Agregar comentarios pertinentes
*
* @author Juan F. Codagnone
* @since Apr 12, 2005
*/
public class ProgressView extends Box {
/**
* Creates the ProgressView.
*
* @param layout layout log4j
* @param filter filtro log4j
* @param action que hace el boton de la vista
*/
public ProgressView(final Layout layout, final Filter filter,
final Action action) {
super(BoxLayout.Y_AXIS); | JTextAreaAppender appender = new JTextAreaAppender(layout); |
jcodagnone/jiolsucker | iolsucker/src/test/java/ar/com/leak/iolsucker/view/common/TextChangelogObserverTest.java | // Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public interface Repository {
// /**
// * Mensaje que le avisa al repositorio que se tiene esta materia.
// *
// * @param course un curso
// */
// void touch(Course course);
//
// /**
// * Sincroniza el material del curso en el repositorio (tipicamente
// * descarga los archivos)
// *
// * @param course un curso
// */
// void syncMaterial(Course course);
//
// /**
// * @param observer observer. El argumento que deben recibir es del tipo
// * ObservableAction
// */
// void addRepositoryListener(Observer observer);
//
// /**
// * @param observers list of observers to add
// */
// void setRepositoryListeners(List /*Observer*/ observers);
//
// /**
// * Una acción observable del repositorio
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public class ObservableAction {
// /** un mensaje...*/
// private final String msg;
// /** un tipo de acción...*/
// private final ObservableActionEnum type;
// /** el archivo que se modificó */
// private final File file;
//
// /**
// * Argumento pasado a los observers
// *
// * @param msg un mensaje
// * @param type un tipo de acción
// * @param file archivo que cambió
// */
// public ObservableAction(final String msg,
// final ObservableActionEnum type,
// final File file) {
// this.msg = msg;
// this.type = type;
// this.file = file;
// }
//
// /** @return el mensaje */
// public final String getMsg() {
// return msg;
// }
//
// /** @return un tipo de acción */
// public final ObservableActionEnum getType() {
// return type;
// }
//
// /** @return the file */
// public final File getFile() {
// return file;
// }
// }
//
// /**
// * Type safe enum con las acciones observables por el navegador
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public static final class ObservableActionEnum {
// /** name of the enum entry*/
// private final String name;
//
// /** se creó un nuevo directorio */
// public static final ObservableActionEnum NEW_FOLDER =
// new ObservableActionEnum("nueva carpeta");
// /** se creó un nuevo archivo */
// public static final ObservableActionEnum NEW_FILE =
// new ObservableActionEnum("nuevo archivo");
//
// /** se republicó un nuevo archivo */
// public static final ObservableActionEnum REPUBLISHED_FILE =
// new ObservableActionEnum("se republicó archivo");
//
// /**
// * Crea el ObservableActionEnum.
// *
// * @param name name of the enum entry
// */
// private ObservableActionEnum(final String name) {
// this.name = name;
// }
//
// /** @see Object#toString() */
// public String toString() {
// return name;
// }
// }
// }
//
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public static final class ObservableActionEnum {
// /** name of the enum entry*/
// private final String name;
//
// /** se creó un nuevo directorio */
// public static final ObservableActionEnum NEW_FOLDER =
// new ObservableActionEnum("nueva carpeta");
// /** se creó un nuevo archivo */
// public static final ObservableActionEnum NEW_FILE =
// new ObservableActionEnum("nuevo archivo");
//
// /** se republicó un nuevo archivo */
// public static final ObservableActionEnum REPUBLISHED_FILE =
// new ObservableActionEnum("se republicó archivo");
//
// /**
// * Crea el ObservableActionEnum.
// *
// * @param name name of the enum entry
// */
// private ObservableActionEnum(final String name) {
// this.name = name;
// }
//
// /** @see Object#toString() */
// public String toString() {
// return name;
// }
// }
| import java.io.*;
import ar.com.leak.iolsucker.view.Repository;
import ar.com.leak.iolsucker.view.Repository.ObservableActionEnum;
import junit.framework.TestCase; | /**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.view.common;
/**
* tests TextChangelogObserver
*
* @author Juan F. Codagnone
* @since Aug 18, 2005
* @link TextChangelogObserver
*/
public class TextChangelogObserverTest extends TestCase {
/**
* tests something...
*
* @throws Exception on error
*/
public final void testBulk() throws Exception {
final File file = File.createTempFile("TextChangelogObersver_tmp",
"txt");
final TextChangelogObserver o =
new TextChangelogObserver(file);
final int numberToTest = 10;
for(int i = 0; i < numberToTest; i++) { | // Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public interface Repository {
// /**
// * Mensaje que le avisa al repositorio que se tiene esta materia.
// *
// * @param course un curso
// */
// void touch(Course course);
//
// /**
// * Sincroniza el material del curso en el repositorio (tipicamente
// * descarga los archivos)
// *
// * @param course un curso
// */
// void syncMaterial(Course course);
//
// /**
// * @param observer observer. El argumento que deben recibir es del tipo
// * ObservableAction
// */
// void addRepositoryListener(Observer observer);
//
// /**
// * @param observers list of observers to add
// */
// void setRepositoryListeners(List /*Observer*/ observers);
//
// /**
// * Una acción observable del repositorio
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public class ObservableAction {
// /** un mensaje...*/
// private final String msg;
// /** un tipo de acción...*/
// private final ObservableActionEnum type;
// /** el archivo que se modificó */
// private final File file;
//
// /**
// * Argumento pasado a los observers
// *
// * @param msg un mensaje
// * @param type un tipo de acción
// * @param file archivo que cambió
// */
// public ObservableAction(final String msg,
// final ObservableActionEnum type,
// final File file) {
// this.msg = msg;
// this.type = type;
// this.file = file;
// }
//
// /** @return el mensaje */
// public final String getMsg() {
// return msg;
// }
//
// /** @return un tipo de acción */
// public final ObservableActionEnum getType() {
// return type;
// }
//
// /** @return the file */
// public final File getFile() {
// return file;
// }
// }
//
// /**
// * Type safe enum con las acciones observables por el navegador
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public static final class ObservableActionEnum {
// /** name of the enum entry*/
// private final String name;
//
// /** se creó un nuevo directorio */
// public static final ObservableActionEnum NEW_FOLDER =
// new ObservableActionEnum("nueva carpeta");
// /** se creó un nuevo archivo */
// public static final ObservableActionEnum NEW_FILE =
// new ObservableActionEnum("nuevo archivo");
//
// /** se republicó un nuevo archivo */
// public static final ObservableActionEnum REPUBLISHED_FILE =
// new ObservableActionEnum("se republicó archivo");
//
// /**
// * Crea el ObservableActionEnum.
// *
// * @param name name of the enum entry
// */
// private ObservableActionEnum(final String name) {
// this.name = name;
// }
//
// /** @see Object#toString() */
// public String toString() {
// return name;
// }
// }
// }
//
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public static final class ObservableActionEnum {
// /** name of the enum entry*/
// private final String name;
//
// /** se creó un nuevo directorio */
// public static final ObservableActionEnum NEW_FOLDER =
// new ObservableActionEnum("nueva carpeta");
// /** se creó un nuevo archivo */
// public static final ObservableActionEnum NEW_FILE =
// new ObservableActionEnum("nuevo archivo");
//
// /** se republicó un nuevo archivo */
// public static final ObservableActionEnum REPUBLISHED_FILE =
// new ObservableActionEnum("se republicó archivo");
//
// /**
// * Crea el ObservableActionEnum.
// *
// * @param name name of the enum entry
// */
// private ObservableActionEnum(final String name) {
// this.name = name;
// }
//
// /** @see Object#toString() */
// public String toString() {
// return name;
// }
// }
// Path: iolsucker/src/test/java/ar/com/leak/iolsucker/view/common/TextChangelogObserverTest.java
import java.io.*;
import ar.com.leak.iolsucker.view.Repository;
import ar.com.leak.iolsucker.view.Repository.ObservableActionEnum;
import junit.framework.TestCase;
/**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.view.common;
/**
* tests TextChangelogObserver
*
* @author Juan F. Codagnone
* @since Aug 18, 2005
* @link TextChangelogObserver
*/
public class TextChangelogObserverTest extends TestCase {
/**
* tests something...
*
* @throws Exception on error
*/
public final void testBulk() throws Exception {
final File file = File.createTempFile("TextChangelogObersver_tmp",
"txt");
final TextChangelogObserver o =
new TextChangelogObserver(file);
final int numberToTest = 10;
for(int i = 0; i < numberToTest; i++) { | o.update(null, new Repository.ObservableAction("ble ble ble " + i, |
jcodagnone/jiolsucker | iolsucker/src/test/java/ar/com/leak/iolsucker/view/common/TextChangelogObserverTest.java | // Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public interface Repository {
// /**
// * Mensaje que le avisa al repositorio que se tiene esta materia.
// *
// * @param course un curso
// */
// void touch(Course course);
//
// /**
// * Sincroniza el material del curso en el repositorio (tipicamente
// * descarga los archivos)
// *
// * @param course un curso
// */
// void syncMaterial(Course course);
//
// /**
// * @param observer observer. El argumento que deben recibir es del tipo
// * ObservableAction
// */
// void addRepositoryListener(Observer observer);
//
// /**
// * @param observers list of observers to add
// */
// void setRepositoryListeners(List /*Observer*/ observers);
//
// /**
// * Una acción observable del repositorio
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public class ObservableAction {
// /** un mensaje...*/
// private final String msg;
// /** un tipo de acción...*/
// private final ObservableActionEnum type;
// /** el archivo que se modificó */
// private final File file;
//
// /**
// * Argumento pasado a los observers
// *
// * @param msg un mensaje
// * @param type un tipo de acción
// * @param file archivo que cambió
// */
// public ObservableAction(final String msg,
// final ObservableActionEnum type,
// final File file) {
// this.msg = msg;
// this.type = type;
// this.file = file;
// }
//
// /** @return el mensaje */
// public final String getMsg() {
// return msg;
// }
//
// /** @return un tipo de acción */
// public final ObservableActionEnum getType() {
// return type;
// }
//
// /** @return the file */
// public final File getFile() {
// return file;
// }
// }
//
// /**
// * Type safe enum con las acciones observables por el navegador
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public static final class ObservableActionEnum {
// /** name of the enum entry*/
// private final String name;
//
// /** se creó un nuevo directorio */
// public static final ObservableActionEnum NEW_FOLDER =
// new ObservableActionEnum("nueva carpeta");
// /** se creó un nuevo archivo */
// public static final ObservableActionEnum NEW_FILE =
// new ObservableActionEnum("nuevo archivo");
//
// /** se republicó un nuevo archivo */
// public static final ObservableActionEnum REPUBLISHED_FILE =
// new ObservableActionEnum("se republicó archivo");
//
// /**
// * Crea el ObservableActionEnum.
// *
// * @param name name of the enum entry
// */
// private ObservableActionEnum(final String name) {
// this.name = name;
// }
//
// /** @see Object#toString() */
// public String toString() {
// return name;
// }
// }
// }
//
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public static final class ObservableActionEnum {
// /** name of the enum entry*/
// private final String name;
//
// /** se creó un nuevo directorio */
// public static final ObservableActionEnum NEW_FOLDER =
// new ObservableActionEnum("nueva carpeta");
// /** se creó un nuevo archivo */
// public static final ObservableActionEnum NEW_FILE =
// new ObservableActionEnum("nuevo archivo");
//
// /** se republicó un nuevo archivo */
// public static final ObservableActionEnum REPUBLISHED_FILE =
// new ObservableActionEnum("se republicó archivo");
//
// /**
// * Crea el ObservableActionEnum.
// *
// * @param name name of the enum entry
// */
// private ObservableActionEnum(final String name) {
// this.name = name;
// }
//
// /** @see Object#toString() */
// public String toString() {
// return name;
// }
// }
| import java.io.*;
import ar.com.leak.iolsucker.view.Repository;
import ar.com.leak.iolsucker.view.Repository.ObservableActionEnum;
import junit.framework.TestCase; | /**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.view.common;
/**
* tests TextChangelogObserver
*
* @author Juan F. Codagnone
* @since Aug 18, 2005
* @link TextChangelogObserver
*/
public class TextChangelogObserverTest extends TestCase {
/**
* tests something...
*
* @throws Exception on error
*/
public final void testBulk() throws Exception {
final File file = File.createTempFile("TextChangelogObersver_tmp",
"txt");
final TextChangelogObserver o =
new TextChangelogObserver(file);
final int numberToTest = 10;
for(int i = 0; i < numberToTest; i++) {
o.update(null, new Repository.ObservableAction("ble ble ble " + i, | // Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public interface Repository {
// /**
// * Mensaje que le avisa al repositorio que se tiene esta materia.
// *
// * @param course un curso
// */
// void touch(Course course);
//
// /**
// * Sincroniza el material del curso en el repositorio (tipicamente
// * descarga los archivos)
// *
// * @param course un curso
// */
// void syncMaterial(Course course);
//
// /**
// * @param observer observer. El argumento que deben recibir es del tipo
// * ObservableAction
// */
// void addRepositoryListener(Observer observer);
//
// /**
// * @param observers list of observers to add
// */
// void setRepositoryListeners(List /*Observer*/ observers);
//
// /**
// * Una acción observable del repositorio
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public class ObservableAction {
// /** un mensaje...*/
// private final String msg;
// /** un tipo de acción...*/
// private final ObservableActionEnum type;
// /** el archivo que se modificó */
// private final File file;
//
// /**
// * Argumento pasado a los observers
// *
// * @param msg un mensaje
// * @param type un tipo de acción
// * @param file archivo que cambió
// */
// public ObservableAction(final String msg,
// final ObservableActionEnum type,
// final File file) {
// this.msg = msg;
// this.type = type;
// this.file = file;
// }
//
// /** @return el mensaje */
// public final String getMsg() {
// return msg;
// }
//
// /** @return un tipo de acción */
// public final ObservableActionEnum getType() {
// return type;
// }
//
// /** @return the file */
// public final File getFile() {
// return file;
// }
// }
//
// /**
// * Type safe enum con las acciones observables por el navegador
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public static final class ObservableActionEnum {
// /** name of the enum entry*/
// private final String name;
//
// /** se creó un nuevo directorio */
// public static final ObservableActionEnum NEW_FOLDER =
// new ObservableActionEnum("nueva carpeta");
// /** se creó un nuevo archivo */
// public static final ObservableActionEnum NEW_FILE =
// new ObservableActionEnum("nuevo archivo");
//
// /** se republicó un nuevo archivo */
// public static final ObservableActionEnum REPUBLISHED_FILE =
// new ObservableActionEnum("se republicó archivo");
//
// /**
// * Crea el ObservableActionEnum.
// *
// * @param name name of the enum entry
// */
// private ObservableActionEnum(final String name) {
// this.name = name;
// }
//
// /** @see Object#toString() */
// public String toString() {
// return name;
// }
// }
// }
//
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public static final class ObservableActionEnum {
// /** name of the enum entry*/
// private final String name;
//
// /** se creó un nuevo directorio */
// public static final ObservableActionEnum NEW_FOLDER =
// new ObservableActionEnum("nueva carpeta");
// /** se creó un nuevo archivo */
// public static final ObservableActionEnum NEW_FILE =
// new ObservableActionEnum("nuevo archivo");
//
// /** se republicó un nuevo archivo */
// public static final ObservableActionEnum REPUBLISHED_FILE =
// new ObservableActionEnum("se republicó archivo");
//
// /**
// * Crea el ObservableActionEnum.
// *
// * @param name name of the enum entry
// */
// private ObservableActionEnum(final String name) {
// this.name = name;
// }
//
// /** @see Object#toString() */
// public String toString() {
// return name;
// }
// }
// Path: iolsucker/src/test/java/ar/com/leak/iolsucker/view/common/TextChangelogObserverTest.java
import java.io.*;
import ar.com.leak.iolsucker.view.Repository;
import ar.com.leak.iolsucker.view.Repository.ObservableActionEnum;
import junit.framework.TestCase;
/**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.view.common;
/**
* tests TextChangelogObserver
*
* @author Juan F. Codagnone
* @since Aug 18, 2005
* @link TextChangelogObserver
*/
public class TextChangelogObserverTest extends TestCase {
/**
* tests something...
*
* @throws Exception on error
*/
public final void testBulk() throws Exception {
final File file = File.createTempFile("TextChangelogObersver_tmp",
"txt");
final TextChangelogObserver o =
new TextChangelogObserver(file);
final int numberToTest = 10;
for(int i = 0; i < numberToTest; i++) {
o.update(null, new Repository.ObservableAction("ble ble ble " + i, | ObservableActionEnum.NEW_FILE, new File("/bar/" + i))); |
jcodagnone/jiolsucker | iolsucker/src/main/java/ar/com/leak/iolsucker/view/common/TextChangelogObserver.java | // Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public interface Repository {
// /**
// * Mensaje que le avisa al repositorio que se tiene esta materia.
// *
// * @param course un curso
// */
// void touch(Course course);
//
// /**
// * Sincroniza el material del curso en el repositorio (tipicamente
// * descarga los archivos)
// *
// * @param course un curso
// */
// void syncMaterial(Course course);
//
// /**
// * @param observer observer. El argumento que deben recibir es del tipo
// * ObservableAction
// */
// void addRepositoryListener(Observer observer);
//
// /**
// * @param observers list of observers to add
// */
// void setRepositoryListeners(List /*Observer*/ observers);
//
// /**
// * Una acción observable del repositorio
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public class ObservableAction {
// /** un mensaje...*/
// private final String msg;
// /** un tipo de acción...*/
// private final ObservableActionEnum type;
// /** el archivo que se modificó */
// private final File file;
//
// /**
// * Argumento pasado a los observers
// *
// * @param msg un mensaje
// * @param type un tipo de acción
// * @param file archivo que cambió
// */
// public ObservableAction(final String msg,
// final ObservableActionEnum type,
// final File file) {
// this.msg = msg;
// this.type = type;
// this.file = file;
// }
//
// /** @return el mensaje */
// public final String getMsg() {
// return msg;
// }
//
// /** @return un tipo de acción */
// public final ObservableActionEnum getType() {
// return type;
// }
//
// /** @return the file */
// public final File getFile() {
// return file;
// }
// }
//
// /**
// * Type safe enum con las acciones observables por el navegador
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public static final class ObservableActionEnum {
// /** name of the enum entry*/
// private final String name;
//
// /** se creó un nuevo directorio */
// public static final ObservableActionEnum NEW_FOLDER =
// new ObservableActionEnum("nueva carpeta");
// /** se creó un nuevo archivo */
// public static final ObservableActionEnum NEW_FILE =
// new ObservableActionEnum("nuevo archivo");
//
// /** se republicó un nuevo archivo */
// public static final ObservableActionEnum REPUBLISHED_FILE =
// new ObservableActionEnum("se republicó archivo");
//
// /**
// * Crea el ObservableActionEnum.
// *
// * @param name name of the enum entry
// */
// private ObservableActionEnum(final String name) {
// this.name = name;
// }
//
// /** @see Object#toString() */
// public String toString() {
// return name;
// }
// }
// }
//
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public class ObservableAction {
// /** un mensaje...*/
// private final String msg;
// /** un tipo de acción...*/
// private final ObservableActionEnum type;
// /** el archivo que se modificó */
// private final File file;
//
// /**
// * Argumento pasado a los observers
// *
// * @param msg un mensaje
// * @param type un tipo de acción
// * @param file archivo que cambió
// */
// public ObservableAction(final String msg,
// final ObservableActionEnum type,
// final File file) {
// this.msg = msg;
// this.type = type;
// this.file = file;
// }
//
// /** @return el mensaje */
// public final String getMsg() {
// return msg;
// }
//
// /** @return un tipo de acción */
// public final ObservableActionEnum getType() {
// return type;
// }
//
// /** @return the file */
// public final File getFile() {
// return file;
// }
// }
| import java.io.File;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import org.apache.log4j.*;
import org.apache.log4j.spi.LoggingEvent;
import ar.com.leak.iolsucker.view.Repository;
import ar.com.leak.iolsucker.view.Repository.ObservableAction; | /**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.view.common;
/**
* Changelog de lo que pasa en el repositorio en formato txt
*
* @author Juan F. Codagnone
* @since Aug 18, 2005
*/
public class TextChangelogObserver implements Observer {
/** an appender */
private final Appender appender;
/**
* Creates the TextChangelogObserver.
*
* @param outputFile cangelog filename
* @throws IOException on error
*/
public TextChangelogObserver(final File outputFile) throws IOException {
appender = new RollingFileAppender(
new PatternLayout("%d{HH:mm:ss} - %m%n"),
outputFile.getAbsolutePath(), true);
}
/** @see java.util.Observer#update(Observable, Object) */
public final void update(final Observable o, final Object arg) { | // Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public interface Repository {
// /**
// * Mensaje que le avisa al repositorio que se tiene esta materia.
// *
// * @param course un curso
// */
// void touch(Course course);
//
// /**
// * Sincroniza el material del curso en el repositorio (tipicamente
// * descarga los archivos)
// *
// * @param course un curso
// */
// void syncMaterial(Course course);
//
// /**
// * @param observer observer. El argumento que deben recibir es del tipo
// * ObservableAction
// */
// void addRepositoryListener(Observer observer);
//
// /**
// * @param observers list of observers to add
// */
// void setRepositoryListeners(List /*Observer*/ observers);
//
// /**
// * Una acción observable del repositorio
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public class ObservableAction {
// /** un mensaje...*/
// private final String msg;
// /** un tipo de acción...*/
// private final ObservableActionEnum type;
// /** el archivo que se modificó */
// private final File file;
//
// /**
// * Argumento pasado a los observers
// *
// * @param msg un mensaje
// * @param type un tipo de acción
// * @param file archivo que cambió
// */
// public ObservableAction(final String msg,
// final ObservableActionEnum type,
// final File file) {
// this.msg = msg;
// this.type = type;
// this.file = file;
// }
//
// /** @return el mensaje */
// public final String getMsg() {
// return msg;
// }
//
// /** @return un tipo de acción */
// public final ObservableActionEnum getType() {
// return type;
// }
//
// /** @return the file */
// public final File getFile() {
// return file;
// }
// }
//
// /**
// * Type safe enum con las acciones observables por el navegador
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public static final class ObservableActionEnum {
// /** name of the enum entry*/
// private final String name;
//
// /** se creó un nuevo directorio */
// public static final ObservableActionEnum NEW_FOLDER =
// new ObservableActionEnum("nueva carpeta");
// /** se creó un nuevo archivo */
// public static final ObservableActionEnum NEW_FILE =
// new ObservableActionEnum("nuevo archivo");
//
// /** se republicó un nuevo archivo */
// public static final ObservableActionEnum REPUBLISHED_FILE =
// new ObservableActionEnum("se republicó archivo");
//
// /**
// * Crea el ObservableActionEnum.
// *
// * @param name name of the enum entry
// */
// private ObservableActionEnum(final String name) {
// this.name = name;
// }
//
// /** @see Object#toString() */
// public String toString() {
// return name;
// }
// }
// }
//
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public class ObservableAction {
// /** un mensaje...*/
// private final String msg;
// /** un tipo de acción...*/
// private final ObservableActionEnum type;
// /** el archivo que se modificó */
// private final File file;
//
// /**
// * Argumento pasado a los observers
// *
// * @param msg un mensaje
// * @param type un tipo de acción
// * @param file archivo que cambió
// */
// public ObservableAction(final String msg,
// final ObservableActionEnum type,
// final File file) {
// this.msg = msg;
// this.type = type;
// this.file = file;
// }
//
// /** @return el mensaje */
// public final String getMsg() {
// return msg;
// }
//
// /** @return un tipo de acción */
// public final ObservableActionEnum getType() {
// return type;
// }
//
// /** @return the file */
// public final File getFile() {
// return file;
// }
// }
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/common/TextChangelogObserver.java
import java.io.File;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import org.apache.log4j.*;
import org.apache.log4j.spi.LoggingEvent;
import ar.com.leak.iolsucker.view.Repository;
import ar.com.leak.iolsucker.view.Repository.ObservableAction;
/**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.view.common;
/**
* Changelog de lo que pasa en el repositorio en formato txt
*
* @author Juan F. Codagnone
* @since Aug 18, 2005
*/
public class TextChangelogObserver implements Observer {
/** an appender */
private final Appender appender;
/**
* Creates the TextChangelogObserver.
*
* @param outputFile cangelog filename
* @throws IOException on error
*/
public TextChangelogObserver(final File outputFile) throws IOException {
appender = new RollingFileAppender(
new PatternLayout("%d{HH:mm:ss} - %m%n"),
outputFile.getAbsolutePath(), true);
}
/** @see java.util.Observer#update(Observable, Object) */
public final void update(final Observable o, final Object arg) { | final Repository.ObservableAction action = (ObservableAction)arg; |
jcodagnone/jiolsucker | iolsucker/src/main/java/ar/com/leak/iolsucker/view/common/TextChangelogObserver.java | // Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public interface Repository {
// /**
// * Mensaje que le avisa al repositorio que se tiene esta materia.
// *
// * @param course un curso
// */
// void touch(Course course);
//
// /**
// * Sincroniza el material del curso en el repositorio (tipicamente
// * descarga los archivos)
// *
// * @param course un curso
// */
// void syncMaterial(Course course);
//
// /**
// * @param observer observer. El argumento que deben recibir es del tipo
// * ObservableAction
// */
// void addRepositoryListener(Observer observer);
//
// /**
// * @param observers list of observers to add
// */
// void setRepositoryListeners(List /*Observer*/ observers);
//
// /**
// * Una acción observable del repositorio
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public class ObservableAction {
// /** un mensaje...*/
// private final String msg;
// /** un tipo de acción...*/
// private final ObservableActionEnum type;
// /** el archivo que se modificó */
// private final File file;
//
// /**
// * Argumento pasado a los observers
// *
// * @param msg un mensaje
// * @param type un tipo de acción
// * @param file archivo que cambió
// */
// public ObservableAction(final String msg,
// final ObservableActionEnum type,
// final File file) {
// this.msg = msg;
// this.type = type;
// this.file = file;
// }
//
// /** @return el mensaje */
// public final String getMsg() {
// return msg;
// }
//
// /** @return un tipo de acción */
// public final ObservableActionEnum getType() {
// return type;
// }
//
// /** @return the file */
// public final File getFile() {
// return file;
// }
// }
//
// /**
// * Type safe enum con las acciones observables por el navegador
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public static final class ObservableActionEnum {
// /** name of the enum entry*/
// private final String name;
//
// /** se creó un nuevo directorio */
// public static final ObservableActionEnum NEW_FOLDER =
// new ObservableActionEnum("nueva carpeta");
// /** se creó un nuevo archivo */
// public static final ObservableActionEnum NEW_FILE =
// new ObservableActionEnum("nuevo archivo");
//
// /** se republicó un nuevo archivo */
// public static final ObservableActionEnum REPUBLISHED_FILE =
// new ObservableActionEnum("se republicó archivo");
//
// /**
// * Crea el ObservableActionEnum.
// *
// * @param name name of the enum entry
// */
// private ObservableActionEnum(final String name) {
// this.name = name;
// }
//
// /** @see Object#toString() */
// public String toString() {
// return name;
// }
// }
// }
//
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public class ObservableAction {
// /** un mensaje...*/
// private final String msg;
// /** un tipo de acción...*/
// private final ObservableActionEnum type;
// /** el archivo que se modificó */
// private final File file;
//
// /**
// * Argumento pasado a los observers
// *
// * @param msg un mensaje
// * @param type un tipo de acción
// * @param file archivo que cambió
// */
// public ObservableAction(final String msg,
// final ObservableActionEnum type,
// final File file) {
// this.msg = msg;
// this.type = type;
// this.file = file;
// }
//
// /** @return el mensaje */
// public final String getMsg() {
// return msg;
// }
//
// /** @return un tipo de acción */
// public final ObservableActionEnum getType() {
// return type;
// }
//
// /** @return the file */
// public final File getFile() {
// return file;
// }
// }
| import java.io.File;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import org.apache.log4j.*;
import org.apache.log4j.spi.LoggingEvent;
import ar.com.leak.iolsucker.view.Repository;
import ar.com.leak.iolsucker.view.Repository.ObservableAction; | /**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.view.common;
/**
* Changelog de lo que pasa en el repositorio en formato txt
*
* @author Juan F. Codagnone
* @since Aug 18, 2005
*/
public class TextChangelogObserver implements Observer {
/** an appender */
private final Appender appender;
/**
* Creates the TextChangelogObserver.
*
* @param outputFile cangelog filename
* @throws IOException on error
*/
public TextChangelogObserver(final File outputFile) throws IOException {
appender = new RollingFileAppender(
new PatternLayout("%d{HH:mm:ss} - %m%n"),
outputFile.getAbsolutePath(), true);
}
/** @see java.util.Observer#update(Observable, Object) */
public final void update(final Observable o, final Object arg) { | // Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public interface Repository {
// /**
// * Mensaje que le avisa al repositorio que se tiene esta materia.
// *
// * @param course un curso
// */
// void touch(Course course);
//
// /**
// * Sincroniza el material del curso en el repositorio (tipicamente
// * descarga los archivos)
// *
// * @param course un curso
// */
// void syncMaterial(Course course);
//
// /**
// * @param observer observer. El argumento que deben recibir es del tipo
// * ObservableAction
// */
// void addRepositoryListener(Observer observer);
//
// /**
// * @param observers list of observers to add
// */
// void setRepositoryListeners(List /*Observer*/ observers);
//
// /**
// * Una acción observable del repositorio
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public class ObservableAction {
// /** un mensaje...*/
// private final String msg;
// /** un tipo de acción...*/
// private final ObservableActionEnum type;
// /** el archivo que se modificó */
// private final File file;
//
// /**
// * Argumento pasado a los observers
// *
// * @param msg un mensaje
// * @param type un tipo de acción
// * @param file archivo que cambió
// */
// public ObservableAction(final String msg,
// final ObservableActionEnum type,
// final File file) {
// this.msg = msg;
// this.type = type;
// this.file = file;
// }
//
// /** @return el mensaje */
// public final String getMsg() {
// return msg;
// }
//
// /** @return un tipo de acción */
// public final ObservableActionEnum getType() {
// return type;
// }
//
// /** @return the file */
// public final File getFile() {
// return file;
// }
// }
//
// /**
// * Type safe enum con las acciones observables por el navegador
// *
// * @author Juan F. Codagnone
// * @since Aug 3, 2005
// */
// public static final class ObservableActionEnum {
// /** name of the enum entry*/
// private final String name;
//
// /** se creó un nuevo directorio */
// public static final ObservableActionEnum NEW_FOLDER =
// new ObservableActionEnum("nueva carpeta");
// /** se creó un nuevo archivo */
// public static final ObservableActionEnum NEW_FILE =
// new ObservableActionEnum("nuevo archivo");
//
// /** se republicó un nuevo archivo */
// public static final ObservableActionEnum REPUBLISHED_FILE =
// new ObservableActionEnum("se republicó archivo");
//
// /**
// * Crea el ObservableActionEnum.
// *
// * @param name name of the enum entry
// */
// private ObservableActionEnum(final String name) {
// this.name = name;
// }
//
// /** @see Object#toString() */
// public String toString() {
// return name;
// }
// }
// }
//
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/Repository.java
// public class ObservableAction {
// /** un mensaje...*/
// private final String msg;
// /** un tipo de acción...*/
// private final ObservableActionEnum type;
// /** el archivo que se modificó */
// private final File file;
//
// /**
// * Argumento pasado a los observers
// *
// * @param msg un mensaje
// * @param type un tipo de acción
// * @param file archivo que cambió
// */
// public ObservableAction(final String msg,
// final ObservableActionEnum type,
// final File file) {
// this.msg = msg;
// this.type = type;
// this.file = file;
// }
//
// /** @return el mensaje */
// public final String getMsg() {
// return msg;
// }
//
// /** @return un tipo de acción */
// public final ObservableActionEnum getType() {
// return type;
// }
//
// /** @return the file */
// public final File getFile() {
// return file;
// }
// }
// Path: iolsucker/src/main/java/ar/com/leak/iolsucker/view/common/TextChangelogObserver.java
import java.io.File;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import org.apache.log4j.*;
import org.apache.log4j.spi.LoggingEvent;
import ar.com.leak.iolsucker.view.Repository;
import ar.com.leak.iolsucker.view.Repository.ObservableAction;
/**
* Copyright (c) 2005-2011 Juan F. Codagnone <http://juan.zaubersoftware.com>
*
* 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 ar.com.leak.iolsucker.view.common;
/**
* Changelog de lo que pasa en el repositorio en formato txt
*
* @author Juan F. Codagnone
* @since Aug 18, 2005
*/
public class TextChangelogObserver implements Observer {
/** an appender */
private final Appender appender;
/**
* Creates the TextChangelogObserver.
*
* @param outputFile cangelog filename
* @throws IOException on error
*/
public TextChangelogObserver(final File outputFile) throws IOException {
appender = new RollingFileAppender(
new PatternLayout("%d{HH:mm:ss} - %m%n"),
outputFile.getAbsolutePath(), true);
}
/** @see java.util.Observer#update(Observable, Object) */
public final void update(final Observable o, final Object arg) { | final Repository.ObservableAction action = (ObservableAction)arg; |
inouire/baggle | baggle-client/src/inouire/baggle/client/threads/AutoRefresh.java | // Path: baggle-client/src/inouire/baggle/client/Main.java
// public class Main {
//
// //global variables
// public static String LOCALE=System.getProperty("user.language");
//
// public final static String VERSION = "3.7";
// public final static int BUILD=3700;
//
// public static final String OFFICIAL_WEBSITE="http://baggle.org";
// public static String MASTER_SERVER_HOST="masterserver.baggle.org";
// public static int MASTER_SERVER_PORT=80;
//
// public static String STATIC_SERVER_IP="localhost";
// public static int STATIC_SERVER_PORT=42705;
//
// public static boolean STORE_CONFIG_LOCALLY=false;
// public static String CONNECT_ONLY_TO=null;
// public static File CONFIG_FOLDER;
//
// public static MainFrame mainFrame;
//
// public static ServerConnection connection;
// public static BotServerConnection bot;
//
// public static CachedServersList cachedServers;
// public static CachedServersList cachedLANServers;
//
// public static AvatarFactory avatarFactory;
// public static UserConfiguration configuration;
//
// public static void printUsage(){
// System.out.println("B@ggle client version "+Main.VERSION);
// System.out.println("Usage: \n\t-M [master server host]"+
// "\n\t-P [master server port]"+
// "\n\t-l (store config file in current directory)");
// System.out.println("All parameters are optionnal.");
// }
//
// /**
// * Main function for baggle-client.
// * Schedules all the others
// * @param Args the command line Arguments
// */
// public static void main(String[] args) throws InterruptedException {
//
// Utils.setBestLookAndFeelAvailable();
//
// printUsage();
//
// SimpleLog.initConsoleConfig();
// SimpleLog.logger.setLevel(Level.INFO);
//
// MASTER_SERVER_HOST = Args.getStringOption("-M",args,MASTER_SERVER_HOST);
// MASTER_SERVER_PORT = Args.getIntegerOption("-P", args, MASTER_SERVER_PORT);
// STORE_CONFIG_LOCALLY = Args.getOption("-l",args);
// CONNECT_ONLY_TO = Args.getStringOption("--only",args,CONNECT_ONLY_TO);
//
// //set path of config folder
// if(Main.STORE_CONFIG_LOCALLY){
// CONFIG_FOLDER=new File(".baggle"+File.separator);
// }else{
// CONFIG_FOLDER=new File(System.getProperty("user.home")+File.separator+".baggle"+File.separator);
// }
//
// //init graphical elements
// avatarFactory=new AvatarFactory();
//
// //init main frame with connect panel only (for faster startup)
// mainFrame = new MainFrame();
// mainFrame.initConnectionPanel();
// mainFrame.setVisible(true);
//
// //load configuration
// configuration = new UserConfiguration();
// configuration.loadFromFile();
//
// //load cached servers list
// cachedServers = new CachedServersList(Main.MASTER_SERVER_HOST);
// cachedServers.loadList(7);
//
// //set auto refresh for server detection
// Timer T = new Timer();
// T.schedule(new AutoRefresh(), 0, 120000);//every 2 minutes
//
// //now init the game part of the main frame
// mainFrame.initGamePanel();
//
// //check for new version in the background
// mainFrame.connectionPane.sideConnectionPane.newVersionPane.checkForNewVersion();
// }
// }
| import java.util.TimerTask;
import inouire.baggle.client.Main;
import inouire.basics.SimpleLog; | package inouire.baggle.client.threads;
/**
*
* @author edouard
*/
public class AutoRefresh extends TimerTask{
@Override
public void run() {
| // Path: baggle-client/src/inouire/baggle/client/Main.java
// public class Main {
//
// //global variables
// public static String LOCALE=System.getProperty("user.language");
//
// public final static String VERSION = "3.7";
// public final static int BUILD=3700;
//
// public static final String OFFICIAL_WEBSITE="http://baggle.org";
// public static String MASTER_SERVER_HOST="masterserver.baggle.org";
// public static int MASTER_SERVER_PORT=80;
//
// public static String STATIC_SERVER_IP="localhost";
// public static int STATIC_SERVER_PORT=42705;
//
// public static boolean STORE_CONFIG_LOCALLY=false;
// public static String CONNECT_ONLY_TO=null;
// public static File CONFIG_FOLDER;
//
// public static MainFrame mainFrame;
//
// public static ServerConnection connection;
// public static BotServerConnection bot;
//
// public static CachedServersList cachedServers;
// public static CachedServersList cachedLANServers;
//
// public static AvatarFactory avatarFactory;
// public static UserConfiguration configuration;
//
// public static void printUsage(){
// System.out.println("B@ggle client version "+Main.VERSION);
// System.out.println("Usage: \n\t-M [master server host]"+
// "\n\t-P [master server port]"+
// "\n\t-l (store config file in current directory)");
// System.out.println("All parameters are optionnal.");
// }
//
// /**
// * Main function for baggle-client.
// * Schedules all the others
// * @param Args the command line Arguments
// */
// public static void main(String[] args) throws InterruptedException {
//
// Utils.setBestLookAndFeelAvailable();
//
// printUsage();
//
// SimpleLog.initConsoleConfig();
// SimpleLog.logger.setLevel(Level.INFO);
//
// MASTER_SERVER_HOST = Args.getStringOption("-M",args,MASTER_SERVER_HOST);
// MASTER_SERVER_PORT = Args.getIntegerOption("-P", args, MASTER_SERVER_PORT);
// STORE_CONFIG_LOCALLY = Args.getOption("-l",args);
// CONNECT_ONLY_TO = Args.getStringOption("--only",args,CONNECT_ONLY_TO);
//
// //set path of config folder
// if(Main.STORE_CONFIG_LOCALLY){
// CONFIG_FOLDER=new File(".baggle"+File.separator);
// }else{
// CONFIG_FOLDER=new File(System.getProperty("user.home")+File.separator+".baggle"+File.separator);
// }
//
// //init graphical elements
// avatarFactory=new AvatarFactory();
//
// //init main frame with connect panel only (for faster startup)
// mainFrame = new MainFrame();
// mainFrame.initConnectionPanel();
// mainFrame.setVisible(true);
//
// //load configuration
// configuration = new UserConfiguration();
// configuration.loadFromFile();
//
// //load cached servers list
// cachedServers = new CachedServersList(Main.MASTER_SERVER_HOST);
// cachedServers.loadList(7);
//
// //set auto refresh for server detection
// Timer T = new Timer();
// T.schedule(new AutoRefresh(), 0, 120000);//every 2 minutes
//
// //now init the game part of the main frame
// mainFrame.initGamePanel();
//
// //check for new version in the background
// mainFrame.connectionPane.sideConnectionPane.newVersionPane.checkForNewVersion();
// }
// }
// Path: baggle-client/src/inouire/baggle/client/threads/AutoRefresh.java
import java.util.TimerTask;
import inouire.baggle.client.Main;
import inouire.basics.SimpleLog;
package inouire.baggle.client.threads;
/**
*
* @author edouard
*/
public class AutoRefresh extends TimerTask{
@Override
public void run() {
| if(!Main.mainFrame.inRoom()){ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/ACCEPTDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class ACCEPTDatagram {
public String auth=null;
public Integer id=null;
public String lang=null;
public Boolean chat=null;
public Integer min=null;
public Boolean pf=null;
public String mode=null;
public Integer time=null;
public Boolean big=false;
public Boolean rewardbigwords=false;
//ACCEPT|id=654|auth=45RT76TR|lang=fr|chat=yes|min=3|pf=no|mode=trad|time=120|big=false|rewardbigwords=no
public ACCEPTDatagram(String auth,int id,String lang,boolean chat,int min,boolean pf, String mode,Integer time, boolean big,boolean rewardbigwords){
this.auth=auth;
this.id=id;
this.lang=lang;
this.chat=chat;
this.min=min;
this.pf=pf;
this.mode=mode;
this.time=time;
this.big=big;
this.rewardbigwords=rewardbigwords;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/ACCEPTDatagram.java
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class ACCEPTDatagram {
public String auth=null;
public Integer id=null;
public String lang=null;
public Boolean chat=null;
public Integer min=null;
public Boolean pf=null;
public String mode=null;
public Integer time=null;
public Boolean big=false;
public Boolean rewardbigwords=false;
//ACCEPT|id=654|auth=45RT76TR|lang=fr|chat=yes|min=3|pf=no|mode=trad|time=120|big=false|rewardbigwords=no
public ACCEPTDatagram(String auth,int id,String lang,boolean chat,int min,boolean pf, String mode,Integer time, boolean big,boolean rewardbigwords){
this.auth=auth;
this.id=id;
this.lang=lang;
this.chat=chat;
this.min=min;
this.pf=pf;
this.mode=mode;
this.time=time;
this.big=big;
this.rewardbigwords=rewardbigwords;
}
| public ACCEPTDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/PROGRESSDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class PROGRESSDatagram {
public Integer id=null;
public Integer prog=null;
//PROGRESS|id=657|prog=35
public PROGRESSDatagram(int id,int prog){
this.id=id;
this.prog=prog;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/PROGRESSDatagram.java
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class PROGRESSDatagram {
public Integer id=null;
public Integer prog=null;
//PROGRESS|id=657|prog=35
public PROGRESSDatagram(int id,int prog){
this.id=id;
this.prog=prog;
}
| public PROGRESSDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/CONNECTDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class CONNECTDatagram {
public String nick=null;
public String logo=null;
public String pwd=null;
//CONNECT|nick=Edouard|logo=tux
public CONNECTDatagram(String nick,String logo){
this.nick=nick;
this.logo=logo;
}
//CONNECT|nick=Edouard|logo=tux|pwd=hehehe
public CONNECTDatagram(String nick,String logo,String pwd){
this.nick=nick;
this.logo=logo;
this.pwd=pwd;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/CONNECTDatagram.java
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class CONNECTDatagram {
public String nick=null;
public String logo=null;
public String pwd=null;
//CONNECT|nick=Edouard|logo=tux
public CONNECTDatagram(String nick,String logo){
this.nick=nick;
this.logo=logo;
}
//CONNECT|nick=Edouard|logo=tux|pwd=hehehe
public CONNECTDatagram(String nick,String logo,String pwd){
this.nick=nick;
this.logo=logo;
this.pwd=pwd;
}
| public CONNECTDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-server/src/inouire/baggle/server/core/OccasionalTask.java | // Path: baggle-server/src/inouire/baggle/server/Main.java
// public class Main {
//
// public static String VERSION = "3.6.2";
// public static boolean WITH_GUI = false;
// public static String CONFIG_FILE="";
// public static String DEFAULT_CONFIG_FILE="conf/baggle-server_config.myml";
// public static boolean DEV_MODE;
//
// //core process
// public static BaggleServer server;
//
// //main frame (gui only)
// public static MainFrame mainFrame = null;
//
//
// private static final String[] helpFlags = new String[] {"help","-h","--help"};
// private static final String[] guiFlags = new String[] {"-g","--gui"};
// private static final String[] configFlags = new String[] {"-c","--config"};
//
// /**
// * Main function
// * @param args the command line arguments
// */
// public static void main(String[] args) {
//
// if(Args.getOption(helpFlags, args)){
// printHelp();
// return;
// }else{
// printVersion();
// System.out.println("Use --help option to know more about the provided options");
// }
//
// WITH_GUI = Args.getOption(guiFlags, args);
// DEV_MODE = Args.getOption("--dev", args);
//
// SimpleLog.initConsoleConfig();
//
// if(WITH_GUI){
// SimpleLog.logger.info("Starting graphical user interface");
// DEFAULT_CONFIG_FILE = System.getProperty("user.home")+File.separator+".baggle"+File.separator+"baggle-server_config.myml";
// }
//
// SimpleLog.logger.info("Loading server configuration");
// ServerConfiguration server_config=null;
//
// //use config file from args
// if(Args.getOption(configFlags, args)){
// CONFIG_FILE=Args.getStringOption(configFlags, args, CONFIG_FILE);
// if(CONFIG_FILE.length()>0){
// server_config = ServerConfiguration.loadFromFile(CONFIG_FILE);
// }else{
// SimpleLog.logger.error("You must specify a config file after -c option");
// }
// }else{ //or use default config file
// CONFIG_FILE=DEFAULT_CONFIG_FILE;
// if(!new File(CONFIG_FILE).exists()){
// server_config = ServerConfiguration.createDefault(CONFIG_FILE);
// SimpleLog.logger.info("Default config file has been created in "+CONFIG_FILE+". You can edit it and restart b@ggle server.");
// SimpleLog.logger.info("Un fichier de configuration par défaut a été créé dans "+CONFIG_FILE+". Editez le (ou pas) et "+
// "redémarrez b@ggle server pour prendre en compte les modifications.");
// }else{
// server_config = ServerConfiguration.loadFromFile(CONFIG_FILE);
// }
// }
//
// if(server_config==null){
// SimpleLog.logger.error("Impossible to load server configuration from "+CONFIG_FILE);
// return;
// }
//
// //log in a room-named file
// String log_file = "log/"+server_config.get("room.name").replaceAll(" ","-")+".log";
// SimpleLog.logger.info("From now on everything will be logged into "+log_file+", see ya !");
// if(DEV_MODE){
// SimpleLog.initDevConfig();
// }else{
// SimpleLog.initProdConfig(log_file);
// }
//
//
// //start server, with or without gui assistant
// if(WITH_GUI){
// mainFrame = new MainFrame(server_config);
// mainFrame.setVisible(true);
// }else{
// server = new BaggleServer(server_config);
// server.startServer();
// }
//
// }
//
// /**
// * Displays basic options for the program
// */
// public static void printHelp(){
// printVersion();
// System.out.println("Usage:"
// + "\n\t--gui Use graphical user interface to start the server"
// + "\n\t-c [config file] Use specified config file instead"
// + "\n\t (by default "+DEFAULT_CONFIG_FILE+" is used)");
// }
//
// /**
// * Displays name and version for the program
// */
// public static void printVersion(){
// System.out.println("B@ggle server version "+Main.VERSION);
// }
//
// }
| import java.util.TimerTask;
import inouire.baggle.server.Main;
import inouire.basics.SimpleLog; | package inouire.baggle.server.core;
/**
*
* @author Edouard de Labareyre
*/
public class OccasionalTask extends TimerTask{
@Override
public void run() {
//~5 minutes
| // Path: baggle-server/src/inouire/baggle/server/Main.java
// public class Main {
//
// public static String VERSION = "3.6.2";
// public static boolean WITH_GUI = false;
// public static String CONFIG_FILE="";
// public static String DEFAULT_CONFIG_FILE="conf/baggle-server_config.myml";
// public static boolean DEV_MODE;
//
// //core process
// public static BaggleServer server;
//
// //main frame (gui only)
// public static MainFrame mainFrame = null;
//
//
// private static final String[] helpFlags = new String[] {"help","-h","--help"};
// private static final String[] guiFlags = new String[] {"-g","--gui"};
// private static final String[] configFlags = new String[] {"-c","--config"};
//
// /**
// * Main function
// * @param args the command line arguments
// */
// public static void main(String[] args) {
//
// if(Args.getOption(helpFlags, args)){
// printHelp();
// return;
// }else{
// printVersion();
// System.out.println("Use --help option to know more about the provided options");
// }
//
// WITH_GUI = Args.getOption(guiFlags, args);
// DEV_MODE = Args.getOption("--dev", args);
//
// SimpleLog.initConsoleConfig();
//
// if(WITH_GUI){
// SimpleLog.logger.info("Starting graphical user interface");
// DEFAULT_CONFIG_FILE = System.getProperty("user.home")+File.separator+".baggle"+File.separator+"baggle-server_config.myml";
// }
//
// SimpleLog.logger.info("Loading server configuration");
// ServerConfiguration server_config=null;
//
// //use config file from args
// if(Args.getOption(configFlags, args)){
// CONFIG_FILE=Args.getStringOption(configFlags, args, CONFIG_FILE);
// if(CONFIG_FILE.length()>0){
// server_config = ServerConfiguration.loadFromFile(CONFIG_FILE);
// }else{
// SimpleLog.logger.error("You must specify a config file after -c option");
// }
// }else{ //or use default config file
// CONFIG_FILE=DEFAULT_CONFIG_FILE;
// if(!new File(CONFIG_FILE).exists()){
// server_config = ServerConfiguration.createDefault(CONFIG_FILE);
// SimpleLog.logger.info("Default config file has been created in "+CONFIG_FILE+". You can edit it and restart b@ggle server.");
// SimpleLog.logger.info("Un fichier de configuration par défaut a été créé dans "+CONFIG_FILE+". Editez le (ou pas) et "+
// "redémarrez b@ggle server pour prendre en compte les modifications.");
// }else{
// server_config = ServerConfiguration.loadFromFile(CONFIG_FILE);
// }
// }
//
// if(server_config==null){
// SimpleLog.logger.error("Impossible to load server configuration from "+CONFIG_FILE);
// return;
// }
//
// //log in a room-named file
// String log_file = "log/"+server_config.get("room.name").replaceAll(" ","-")+".log";
// SimpleLog.logger.info("From now on everything will be logged into "+log_file+", see ya !");
// if(DEV_MODE){
// SimpleLog.initDevConfig();
// }else{
// SimpleLog.initProdConfig(log_file);
// }
//
//
// //start server, with or without gui assistant
// if(WITH_GUI){
// mainFrame = new MainFrame(server_config);
// mainFrame.setVisible(true);
// }else{
// server = new BaggleServer(server_config);
// server.startServer();
// }
//
// }
//
// /**
// * Displays basic options for the program
// */
// public static void printHelp(){
// printVersion();
// System.out.println("Usage:"
// + "\n\t--gui Use graphical user interface to start the server"
// + "\n\t-c [config file] Use specified config file instead"
// + "\n\t (by default "+DEFAULT_CONFIG_FILE+" is used)");
// }
//
// /**
// * Displays name and version for the program
// */
// public static void printVersion(){
// System.out.println("B@ggle server version "+Main.VERSION);
// }
//
// }
// Path: baggle-server/src/inouire/baggle/server/core/OccasionalTask.java
import java.util.TimerTask;
import inouire.baggle.server.Main;
import inouire.basics.SimpleLog;
package inouire.baggle.server.core;
/**
*
* @author Edouard de Labareyre
*/
public class OccasionalTask extends TimerTask{
@Override
public void run() {
//~5 minutes
| if(Main.server.configuration.registerToMasterServer){ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/SERVERDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class SERVERDatagram {
public String ip=null;
public Integer port=null;
//SERVER|ip=92.168.0.4|port=12345 (master -> client)
public SERVERDatagram(String ip, Integer port) {
this.ip = ip;
this.port = port;
}
//SERVER|port=12345 (server -> master)
public SERVERDatagram(Integer port) {
this.ip = null;
this.port = port;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/SERVERDatagram.java
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class SERVERDatagram {
public String ip=null;
public Integer port=null;
//SERVER|ip=92.168.0.4|port=12345 (master -> client)
public SERVERDatagram(String ip, Integer port) {
this.ip = ip;
this.port = port;
}
//SERVER|port=12345 (server -> master)
public SERVERDatagram(Integer port) {
this.ip = null;
this.port = port;
}
| public SERVERDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/DENYDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class DENYDatagram {
public String reason=null;
//DENY|reason=server_full
public DENYDatagram(String reason){
this.reason=reason.toLowerCase();
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/DENYDatagram.java
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class DENYDatagram {
public String reason=null;
//DENY|reason=server_full
public DENYDatagram(String reason){
this.reason=reason.toLowerCase();
}
| public DENYDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/CLIENTDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class CLIENTDatagram {
public String version=null;
public String os=null;
public Integer id=null;
//CLIENT|version=2.0 web|os=GNU/Linux (client -> server)
public CLIENTDatagram(String version,String os){
this.version=version;
this.os=os;
this.id=null;
}
//CLIENT|id=564|version=2.0 web|os=GNU/Linux (server -> client)
public CLIENTDatagram(int id,String version,String os){
this.version=version;
this.os=os;
this.id=id;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/CLIENTDatagram.java
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class CLIENTDatagram {
public String version=null;
public String os=null;
public Integer id=null;
//CLIENT|version=2.0 web|os=GNU/Linux (client -> server)
public CLIENTDatagram(String version,String os){
this.version=version;
this.os=os;
this.id=null;
}
//CLIENT|id=564|version=2.0 web|os=GNU/Linux (server -> client)
public CLIENTDatagram(int id,String version,String os){
this.version=version;
this.os=os;
this.id=id;
}
| public CLIENTDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/TIMEDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class TIMEDatagram {
public Integer rem=null;
public Integer tot=null;
//TIME|rem=87|tot=180
public TIMEDatagram(int rem,int tot){
this.rem=rem;
this.tot=tot;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/TIMEDatagram.java
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class TIMEDatagram {
public Integer rem=null;
public Integer tot=null;
//TIME|rem=87|tot=180
public TIMEDatagram(int rem,int tot){
this.rem=rem;
this.tot=tot;
}
| public TIMEDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/CHATDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/Key.java
// public enum Key{
// CONNECT,RECONNECT,DISCONNECT,
// ACCEPT,DENY,PASSWORD,
// START,STOP,PROGRESS,TIME,
// JOIN,LEAVE,WORD,CHAT,STATUS,
// SCORE,RESULT,
// CLIENT,
// PING,SERVER,
// SUBMIT,GETLIST
// }
| package inouire.baggle.datagrams;import inouire.baggle.types.IllegalDatagramException;
import inouire.baggle.types.Key; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
public class CHATDatagram{
public String msg=null;
public Integer id=null;
//CHAT|msg=Bonjour tout le monde! (client -> server)
public CHATDatagram(String msg){
this.msg=msg;
this.id=null;
}
//CHAT|id=657|msg=Bonjour Edouard, comment vas tu ? (server -> client)
public CHATDatagram(int id,String msg){
this.msg=msg;
this.id=id;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/Key.java
// public enum Key{
// CONNECT,RECONNECT,DISCONNECT,
// ACCEPT,DENY,PASSWORD,
// START,STOP,PROGRESS,TIME,
// JOIN,LEAVE,WORD,CHAT,STATUS,
// SCORE,RESULT,
// CLIENT,
// PING,SERVER,
// SUBMIT,GETLIST
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/CHATDatagram.java
package inouire.baggle.datagrams;import inouire.baggle.types.IllegalDatagramException;
import inouire.baggle.types.Key;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
public class CHATDatagram{
public String msg=null;
public Integer id=null;
//CHAT|msg=Bonjour tout le monde! (client -> server)
public CHATDatagram(String msg){
this.msg=msg;
this.id=null;
}
//CHAT|id=657|msg=Bonjour Edouard, comment vas tu ? (server -> client)
public CHATDatagram(int id,String msg){
this.msg=msg;
this.id=id;
}
| public CHATDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/CHATDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/Key.java
// public enum Key{
// CONNECT,RECONNECT,DISCONNECT,
// ACCEPT,DENY,PASSWORD,
// START,STOP,PROGRESS,TIME,
// JOIN,LEAVE,WORD,CHAT,STATUS,
// SCORE,RESULT,
// CLIENT,
// PING,SERVER,
// SUBMIT,GETLIST
// }
| package inouire.baggle.datagrams;import inouire.baggle.types.IllegalDatagramException;
import inouire.baggle.types.Key; | }catch(Exception e){
throw new IllegalDatagramException();
}
checkDatagram();
}
private void checkDatagram() throws IllegalDatagramException {
if(msg==null){
throw new IllegalDatagramException();
}
}
private void parseArg(String arg){
String [] keyValue = Datagram.decompArg(arg);
if(keyValue!=null){
String key=keyValue[0];
String value=keyValue[1];
if(key.equals("msg")){
msg=Datagram.addAccents(value);
}else if(key.equals("id")){
id=Integer.parseInt(value);
}
}
}
@Override
public String toString(){
if(id==null){ | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/Key.java
// public enum Key{
// CONNECT,RECONNECT,DISCONNECT,
// ACCEPT,DENY,PASSWORD,
// START,STOP,PROGRESS,TIME,
// JOIN,LEAVE,WORD,CHAT,STATUS,
// SCORE,RESULT,
// CLIENT,
// PING,SERVER,
// SUBMIT,GETLIST
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/CHATDatagram.java
package inouire.baggle.datagrams;import inouire.baggle.types.IllegalDatagramException;
import inouire.baggle.types.Key;
}catch(Exception e){
throw new IllegalDatagramException();
}
checkDatagram();
}
private void checkDatagram() throws IllegalDatagramException {
if(msg==null){
throw new IllegalDatagramException();
}
}
private void parseArg(String arg){
String [] keyValue = Datagram.decompArg(arg);
if(keyValue!=null){
String key=keyValue[0];
String value=keyValue[1];
if(key.equals("msg")){
msg=Datagram.addAccents(value);
}else if(key.equals("id")){
id=Integer.parseInt(value);
}
}
}
@Override
public String toString(){
if(id==null){ | return Key.CHAT+"|msg="+msg; |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/JOINDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class JOINDatagram {
public String nick=null;
public String logo=null;
public Integer id=null;
//JOIN|nick=Edouard|logo=tux|id=654
public JOINDatagram(String nick,String logo,int id){
this.nick=nick;
this.logo=logo;
this.id=id;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/JOINDatagram.java
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class JOINDatagram {
public String nick=null;
public String logo=null;
public Integer id=null;
//JOIN|nick=Edouard|logo=tux|id=654
public JOINDatagram(String nick,String logo,int id){
this.nick=nick;
this.logo=logo;
this.id=id;
}
| public JOINDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/RECONNECTDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class RECONNECTDatagram {
public String auth=null;
public Integer id=null;
//RECONNECT|auth=45RT76TR|id=125
public RECONNECTDatagram(String auth,int id){
this.auth=auth;
this.id=id;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/RECONNECTDatagram.java
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class RECONNECTDatagram {
public String auth=null;
public Integer id=null;
//RECONNECT|auth=45RT76TR|id=125
public RECONNECTDatagram(String auth,int id){
this.auth=auth;
this.id=id;
}
| public RECONNECTDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-client/src/inouire/baggle/client/gui/modules/MiniBoardPanel.java | // Path: baggle-client/src/inouire/baggle/client/gui/ColorFactory.java
// public class ColorFactory {
// final static public Color BROWN_BOARD= new Color(74,50,19);
// final static public Color BLUE_BOARD = new Color(28,47,85);
// final static public Color GREEN_BOARD = new Color(23,77,19);
// final static public Color RED_BOARD = new Color(113,38,35);
// final static public Color PURPLE_BOARD = new Color(58,42,69);
//
// final static public Color LIGHT_BLUE = new Color(164,178,207);
// final static public Color LIGHT_RED = new Color(255,113,113);
// final static public Color LIGHT_GREEN = new Color(157,195,104);
//
// final static public Color VERY_LIGHT_GRAY = new Color(220,220,220);
// final static public Color LIGHT_GRAY = new Color(190,190,190);
//
// final static public Color YELLOW_NOTIF = new Color(255,250,151);
//
// final static public Color SERVER_BG=Color.LIGHT_GRAY;
// final static public Color MOBILE_BG=Color.LIGHT_GRAY;
// final static public Color UNKNOWN_BG=Color.LIGHT_GRAY;
// final static public Color ROBOT_BG=new Color(255,250,151);
//
// final static public Color DONKEY_BG=new Color(159,196,123);
// final static public Color LADYBUG_BG=new Color(255,215,247);
// final static public Color HAT_BG=new Color(127,141,157);
// final static public Color TIGER_BG=new Color(211,214,255);
// final static public Color TUX_BG=new Color(255,219,151);
// final static public Color WINE_BG=new Color(255,155,155);
// final static public Color COFFEE_BG =new Color(199,192,175);
// final static public Color COLORS_BG=new Color(210,214,234);
//
// final static public Color GOOD_WORD = new Color(70,122,15);
// final static public Color BAD_WORD = new Color(187,41,41);
//
// // new Color(246,205,147),
// // new Color(191,191,191),
// // new Color(219,180,121),
// // new Color(175,180,132),
// // new Color(220,220,220),
//
//
// public static Color getAvatarColor(String name){
// Color c=Color.LIGHT_GRAY;
// if(name.equals("robot")){
// c=ROBOT_BG;
// }else if(name.equals("donkey")){
// c=DONKEY_BG;
// }else if(name.equals("ladybug")){
// c=LADYBUG_BG;
// }else if(name.equals("hat")){
// c=HAT_BG;
// }else if(name.equals("tiger")){
// c=TIGER_BG;
// }else if(name.equals("tux")){
// c=TUX_BG;
// }else if(name.equals("wine")){
// c=WINE_BG;
// }else if(name.equals("coffee")){
// c=COFFEE_BG;
// }else if(name.equals("colors")){
// c=COLORS_BG;
// }
// return c;
// }
//
// public static Color getBoardColor(boolean big_board,String game_mode){
// Color c;
// if(big_board){
// if(game_mode.equalsIgnoreCase("trad")){
// c=ColorFactory.PURPLE_BOARD;
// }else{
// c=ColorFactory.BROWN_BOARD;
// }
// }else{
// if(game_mode.equalsIgnoreCase("all")){
// c=ColorFactory.BLUE_BOARD;
// }else{
// c=ColorFactory.GREEN_BOARD;
// }
// }
// return c;
// }
//
// }
| import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import inouire.baggle.client.gui.ColorFactory; | package inouire.baggle.client.gui.modules;
/**
* @author Edouard de Labareyre
*/
public class MiniBoardPanel extends JComponent{
private MiniDice[][] des;
private Color boardColor;
private String grid;
public int size;
boolean is_highlighted=false;
final static private int b=4;//taille du bord
final static private int i=1;//taille de l'inter-dé
final static int STYLE=Font.BOLD;
public MiniBoardPanel(){
this.size = 0; | // Path: baggle-client/src/inouire/baggle/client/gui/ColorFactory.java
// public class ColorFactory {
// final static public Color BROWN_BOARD= new Color(74,50,19);
// final static public Color BLUE_BOARD = new Color(28,47,85);
// final static public Color GREEN_BOARD = new Color(23,77,19);
// final static public Color RED_BOARD = new Color(113,38,35);
// final static public Color PURPLE_BOARD = new Color(58,42,69);
//
// final static public Color LIGHT_BLUE = new Color(164,178,207);
// final static public Color LIGHT_RED = new Color(255,113,113);
// final static public Color LIGHT_GREEN = new Color(157,195,104);
//
// final static public Color VERY_LIGHT_GRAY = new Color(220,220,220);
// final static public Color LIGHT_GRAY = new Color(190,190,190);
//
// final static public Color YELLOW_NOTIF = new Color(255,250,151);
//
// final static public Color SERVER_BG=Color.LIGHT_GRAY;
// final static public Color MOBILE_BG=Color.LIGHT_GRAY;
// final static public Color UNKNOWN_BG=Color.LIGHT_GRAY;
// final static public Color ROBOT_BG=new Color(255,250,151);
//
// final static public Color DONKEY_BG=new Color(159,196,123);
// final static public Color LADYBUG_BG=new Color(255,215,247);
// final static public Color HAT_BG=new Color(127,141,157);
// final static public Color TIGER_BG=new Color(211,214,255);
// final static public Color TUX_BG=new Color(255,219,151);
// final static public Color WINE_BG=new Color(255,155,155);
// final static public Color COFFEE_BG =new Color(199,192,175);
// final static public Color COLORS_BG=new Color(210,214,234);
//
// final static public Color GOOD_WORD = new Color(70,122,15);
// final static public Color BAD_WORD = new Color(187,41,41);
//
// // new Color(246,205,147),
// // new Color(191,191,191),
// // new Color(219,180,121),
// // new Color(175,180,132),
// // new Color(220,220,220),
//
//
// public static Color getAvatarColor(String name){
// Color c=Color.LIGHT_GRAY;
// if(name.equals("robot")){
// c=ROBOT_BG;
// }else if(name.equals("donkey")){
// c=DONKEY_BG;
// }else if(name.equals("ladybug")){
// c=LADYBUG_BG;
// }else if(name.equals("hat")){
// c=HAT_BG;
// }else if(name.equals("tiger")){
// c=TIGER_BG;
// }else if(name.equals("tux")){
// c=TUX_BG;
// }else if(name.equals("wine")){
// c=WINE_BG;
// }else if(name.equals("coffee")){
// c=COFFEE_BG;
// }else if(name.equals("colors")){
// c=COLORS_BG;
// }
// return c;
// }
//
// public static Color getBoardColor(boolean big_board,String game_mode){
// Color c;
// if(big_board){
// if(game_mode.equalsIgnoreCase("trad")){
// c=ColorFactory.PURPLE_BOARD;
// }else{
// c=ColorFactory.BROWN_BOARD;
// }
// }else{
// if(game_mode.equalsIgnoreCase("all")){
// c=ColorFactory.BLUE_BOARD;
// }else{
// c=ColorFactory.GREEN_BOARD;
// }
// }
// return c;
// }
//
// }
// Path: baggle-client/src/inouire/baggle/client/gui/modules/MiniBoardPanel.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import inouire.baggle.client.gui.ColorFactory;
package inouire.baggle.client.gui.modules;
/**
* @author Edouard de Labareyre
*/
public class MiniBoardPanel extends JComponent{
private MiniDice[][] des;
private Color boardColor;
private String grid;
public int size;
boolean is_highlighted=false;
final static private int b=4;//taille du bord
final static private int i=1;//taille de l'inter-dé
final static int STYLE=Font.BOLD;
public MiniBoardPanel(){
this.size = 0; | this.boardColor = ColorFactory.BROWN_BOARD; |
inouire/baggle | baggle-server/src/inouire/baggle/server/core/FrequentTask.java | // Path: baggle-server/src/inouire/baggle/server/Main.java
// public class Main {
//
// public static String VERSION = "3.6.2";
// public static boolean WITH_GUI = false;
// public static String CONFIG_FILE="";
// public static String DEFAULT_CONFIG_FILE="conf/baggle-server_config.myml";
// public static boolean DEV_MODE;
//
// //core process
// public static BaggleServer server;
//
// //main frame (gui only)
// public static MainFrame mainFrame = null;
//
//
// private static final String[] helpFlags = new String[] {"help","-h","--help"};
// private static final String[] guiFlags = new String[] {"-g","--gui"};
// private static final String[] configFlags = new String[] {"-c","--config"};
//
// /**
// * Main function
// * @param args the command line arguments
// */
// public static void main(String[] args) {
//
// if(Args.getOption(helpFlags, args)){
// printHelp();
// return;
// }else{
// printVersion();
// System.out.println("Use --help option to know more about the provided options");
// }
//
// WITH_GUI = Args.getOption(guiFlags, args);
// DEV_MODE = Args.getOption("--dev", args);
//
// SimpleLog.initConsoleConfig();
//
// if(WITH_GUI){
// SimpleLog.logger.info("Starting graphical user interface");
// DEFAULT_CONFIG_FILE = System.getProperty("user.home")+File.separator+".baggle"+File.separator+"baggle-server_config.myml";
// }
//
// SimpleLog.logger.info("Loading server configuration");
// ServerConfiguration server_config=null;
//
// //use config file from args
// if(Args.getOption(configFlags, args)){
// CONFIG_FILE=Args.getStringOption(configFlags, args, CONFIG_FILE);
// if(CONFIG_FILE.length()>0){
// server_config = ServerConfiguration.loadFromFile(CONFIG_FILE);
// }else{
// SimpleLog.logger.error("You must specify a config file after -c option");
// }
// }else{ //or use default config file
// CONFIG_FILE=DEFAULT_CONFIG_FILE;
// if(!new File(CONFIG_FILE).exists()){
// server_config = ServerConfiguration.createDefault(CONFIG_FILE);
// SimpleLog.logger.info("Default config file has been created in "+CONFIG_FILE+". You can edit it and restart b@ggle server.");
// SimpleLog.logger.info("Un fichier de configuration par défaut a été créé dans "+CONFIG_FILE+". Editez le (ou pas) et "+
// "redémarrez b@ggle server pour prendre en compte les modifications.");
// }else{
// server_config = ServerConfiguration.loadFromFile(CONFIG_FILE);
// }
// }
//
// if(server_config==null){
// SimpleLog.logger.error("Impossible to load server configuration from "+CONFIG_FILE);
// return;
// }
//
// //log in a room-named file
// String log_file = "log/"+server_config.get("room.name").replaceAll(" ","-")+".log";
// SimpleLog.logger.info("From now on everything will be logged into "+log_file+", see ya !");
// if(DEV_MODE){
// SimpleLog.initDevConfig();
// }else{
// SimpleLog.initProdConfig(log_file);
// }
//
//
// //start server, with or without gui assistant
// if(WITH_GUI){
// mainFrame = new MainFrame(server_config);
// mainFrame.setVisible(true);
// }else{
// server = new BaggleServer(server_config);
// server.startServer();
// }
//
// }
//
// /**
// * Displays basic options for the program
// */
// public static void printHelp(){
// printVersion();
// System.out.println("Usage:"
// + "\n\t--gui Use graphical user interface to start the server"
// + "\n\t-c [config file] Use specified config file instead"
// + "\n\t (by default "+DEFAULT_CONFIG_FILE+" is used)");
// }
//
// /**
// * Displays name and version for the program
// */
// public static void printVersion(){
// System.out.println("B@ggle server version "+Main.VERSION);
// }
//
// }
| import java.util.TimerTask;
import inouire.baggle.server.Main; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.server.core;
/**
*
* @author Edouard de Labareyre
*/
public class FrequentTask extends TimerTask{
@Override
public void run() {
//period should be ~10 sec | // Path: baggle-server/src/inouire/baggle/server/Main.java
// public class Main {
//
// public static String VERSION = "3.6.2";
// public static boolean WITH_GUI = false;
// public static String CONFIG_FILE="";
// public static String DEFAULT_CONFIG_FILE="conf/baggle-server_config.myml";
// public static boolean DEV_MODE;
//
// //core process
// public static BaggleServer server;
//
// //main frame (gui only)
// public static MainFrame mainFrame = null;
//
//
// private static final String[] helpFlags = new String[] {"help","-h","--help"};
// private static final String[] guiFlags = new String[] {"-g","--gui"};
// private static final String[] configFlags = new String[] {"-c","--config"};
//
// /**
// * Main function
// * @param args the command line arguments
// */
// public static void main(String[] args) {
//
// if(Args.getOption(helpFlags, args)){
// printHelp();
// return;
// }else{
// printVersion();
// System.out.println("Use --help option to know more about the provided options");
// }
//
// WITH_GUI = Args.getOption(guiFlags, args);
// DEV_MODE = Args.getOption("--dev", args);
//
// SimpleLog.initConsoleConfig();
//
// if(WITH_GUI){
// SimpleLog.logger.info("Starting graphical user interface");
// DEFAULT_CONFIG_FILE = System.getProperty("user.home")+File.separator+".baggle"+File.separator+"baggle-server_config.myml";
// }
//
// SimpleLog.logger.info("Loading server configuration");
// ServerConfiguration server_config=null;
//
// //use config file from args
// if(Args.getOption(configFlags, args)){
// CONFIG_FILE=Args.getStringOption(configFlags, args, CONFIG_FILE);
// if(CONFIG_FILE.length()>0){
// server_config = ServerConfiguration.loadFromFile(CONFIG_FILE);
// }else{
// SimpleLog.logger.error("You must specify a config file after -c option");
// }
// }else{ //or use default config file
// CONFIG_FILE=DEFAULT_CONFIG_FILE;
// if(!new File(CONFIG_FILE).exists()){
// server_config = ServerConfiguration.createDefault(CONFIG_FILE);
// SimpleLog.logger.info("Default config file has been created in "+CONFIG_FILE+". You can edit it and restart b@ggle server.");
// SimpleLog.logger.info("Un fichier de configuration par défaut a été créé dans "+CONFIG_FILE+". Editez le (ou pas) et "+
// "redémarrez b@ggle server pour prendre en compte les modifications.");
// }else{
// server_config = ServerConfiguration.loadFromFile(CONFIG_FILE);
// }
// }
//
// if(server_config==null){
// SimpleLog.logger.error("Impossible to load server configuration from "+CONFIG_FILE);
// return;
// }
//
// //log in a room-named file
// String log_file = "log/"+server_config.get("room.name").replaceAll(" ","-")+".log";
// SimpleLog.logger.info("From now on everything will be logged into "+log_file+", see ya !");
// if(DEV_MODE){
// SimpleLog.initDevConfig();
// }else{
// SimpleLog.initProdConfig(log_file);
// }
//
//
// //start server, with or without gui assistant
// if(WITH_GUI){
// mainFrame = new MainFrame(server_config);
// mainFrame.setVisible(true);
// }else{
// server = new BaggleServer(server_config);
// server.startServer();
// }
//
// }
//
// /**
// * Displays basic options for the program
// */
// public static void printHelp(){
// printVersion();
// System.out.println("Usage:"
// + "\n\t--gui Use graphical user interface to start the server"
// + "\n\t-c [config file] Use specified config file instead"
// + "\n\t (by default "+DEFAULT_CONFIG_FILE+" is used)");
// }
//
// /**
// * Displays name and version for the program
// */
// public static void printVersion(){
// System.out.println("B@ggle server version "+Main.VERSION);
// }
//
// }
// Path: baggle-server/src/inouire/baggle/server/core/FrequentTask.java
import java.util.TimerTask;
import inouire.baggle.server.Main;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.server.core;
/**
*
* @author Edouard de Labareyre
*/
public class FrequentTask extends TimerTask{
@Override
public void run() {
//period should be ~10 sec | Main.server.gameThread.players.pauseInactivePlayers(); |
inouire/baggle | baggle-client/src/inouire/baggle/client/UserConfiguration.java | // Path: baggle-datagrams/src/inouire/utils/Utils.java
// public class Utils {
//
//
// public static String createRandomPassword(){
// Random r=new Random();
// int nb_letters=r.nextInt(5)+5;
// String password="";
// for(int k=0;k<nb_letters;k++){
// password+=r.nextInt(10)+"";
// }
// return password;
// }
//
// public static int getIntValue(String string_value, int default_value){
// int int_value;
// try{
// int_value=Integer.parseInt(string_value);
// }catch(NumberFormatException nfe){
// int_value=default_value;
// System.err.println("Impossible to cast "+string_value+" to integer");
// }
// return int_value;
// }
//
// public static boolean getBoolValue(String string_value, boolean default_value){
// boolean bool_value;
// try{
// bool_value=Boolean.parseBoolean(string_value);
// }catch(NumberFormatException nfe){
// bool_value=default_value;
// System.err.println("Impossible to cast "+string_value+" to boolean");
// }
// return bool_value;
// }
//
// public static void setBestLookAndFeelAvailable(){
// String system_lf = UIManager.getSystemLookAndFeelClassName().toLowerCase();
// if(system_lf.contains("metal")){
// try {
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
// }catch (Exception e) {}
// }else{
// try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// }catch (Exception e) {}
// }
// }
// }
| import inouire.basics.SimpleLog;
import java.io.*;
import inouire.utils.Utils; | * Load the configuration from file
*/
public void loadFromFile(){
FileInputStream in;
try {
in = new FileInputStream(CONFIG_FILE);
} catch (FileNotFoundException ex) {
SimpleLog.logger.error("Impossible to open file at "+CONFIG_FILE.getAbsolutePath());
return;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try{
String line="";
String[] arg;
ConfigKey key;
String value;
while((line = reader.readLine()) != null ){
arg= line.split("=");
if(arg.length==2){
key=ConfigKey.valueOf(arg[0].trim().toUpperCase());
value=arg[1].trim();
switch(key){
case NAME:
NAME=value;
break;
case AVATAR:
AVATAR=value.toLowerCase();
break;
case POSX: | // Path: baggle-datagrams/src/inouire/utils/Utils.java
// public class Utils {
//
//
// public static String createRandomPassword(){
// Random r=new Random();
// int nb_letters=r.nextInt(5)+5;
// String password="";
// for(int k=0;k<nb_letters;k++){
// password+=r.nextInt(10)+"";
// }
// return password;
// }
//
// public static int getIntValue(String string_value, int default_value){
// int int_value;
// try{
// int_value=Integer.parseInt(string_value);
// }catch(NumberFormatException nfe){
// int_value=default_value;
// System.err.println("Impossible to cast "+string_value+" to integer");
// }
// return int_value;
// }
//
// public static boolean getBoolValue(String string_value, boolean default_value){
// boolean bool_value;
// try{
// bool_value=Boolean.parseBoolean(string_value);
// }catch(NumberFormatException nfe){
// bool_value=default_value;
// System.err.println("Impossible to cast "+string_value+" to boolean");
// }
// return bool_value;
// }
//
// public static void setBestLookAndFeelAvailable(){
// String system_lf = UIManager.getSystemLookAndFeelClassName().toLowerCase();
// if(system_lf.contains("metal")){
// try {
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
// }catch (Exception e) {}
// }else{
// try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// }catch (Exception e) {}
// }
// }
// }
// Path: baggle-client/src/inouire/baggle/client/UserConfiguration.java
import inouire.basics.SimpleLog;
import java.io.*;
import inouire.utils.Utils;
* Load the configuration from file
*/
public void loadFromFile(){
FileInputStream in;
try {
in = new FileInputStream(CONFIG_FILE);
} catch (FileNotFoundException ex) {
SimpleLog.logger.error("Impossible to open file at "+CONFIG_FILE.getAbsolutePath());
return;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try{
String line="";
String[] arg;
ConfigKey key;
String value;
while((line = reader.readLine()) != null ){
arg= line.split("=");
if(arg.length==2){
key=ConfigKey.valueOf(arg[0].trim().toUpperCase());
value=arg[1].trim();
switch(key){
case NAME:
NAME=value;
break;
case AVATAR:
AVATAR=value.toLowerCase();
break;
case POSX: | POSX=Utils.getIntValue(value, -1); |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/STARTDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class STARTDatagram {
public String grid=null;
public Integer max=null;
//START|grid=BAGGLEBAGGLEBAGG|max=78
public STARTDatagram(String grid,int max){
this.grid=grid;
this.max=max;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/STARTDatagram.java
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class STARTDatagram {
public String grid=null;
public Integer max=null;
//START|grid=BAGGLEBAGGLEBAGG|max=78
public STARTDatagram(String grid,int max){
this.grid=grid;
this.max=max;
}
| public STARTDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-client/src/inouire/baggle/client/CachedServersList.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import inouire.baggle.types.IllegalDatagramException;
import inouire.basics.SimpleLog; | * Load the server list from file
* @param nb_days the max age in days for validity of an entry. invalid entry is not loaded
*/
public void loadList(int nb_days){
long timestamp_min = System.currentTimeMillis()-(86400000*nb_days);
FileInputStream in;
try {
in = new FileInputStream(LIST_FILE);
} catch (FileNotFoundException ex) {
SimpleLog.logger.warn("Impossible to open file at "+LIST_FILE.getAbsolutePath());
return;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try{
String line="";
String[] content;
ConfigKey key;
String value;
while((line = reader.readLine()) != null ){
content = line.split("\\|");
try{
ServerEntry entry = new ServerEntry(content);
if(entry.timestamp > timestamp_min){
cached_servers.add(entry);
}else{
SimpleLog.logger.debug("Not adding server entry, too old: "+line);
} | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-client/src/inouire/baggle/client/CachedServersList.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import inouire.baggle.types.IllegalDatagramException;
import inouire.basics.SimpleLog;
* Load the server list from file
* @param nb_days the max age in days for validity of an entry. invalid entry is not loaded
*/
public void loadList(int nb_days){
long timestamp_min = System.currentTimeMillis()-(86400000*nb_days);
FileInputStream in;
try {
in = new FileInputStream(LIST_FILE);
} catch (FileNotFoundException ex) {
SimpleLog.logger.warn("Impossible to open file at "+LIST_FILE.getAbsolutePath());
return;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try{
String line="";
String[] content;
ConfigKey key;
String value;
while((line = reader.readLine()) != null ){
content = line.split("\\|");
try{
ServerEntry entry = new ServerEntry(content);
if(entry.timestamp > timestamp_min){
cached_servers.add(entry);
}else{
SimpleLog.logger.debug("Not adding server entry, too old: "+line);
} | }catch(IllegalDatagramException ide){ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/STOPDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class STOPDatagram {
public String reason=null;
//STOP|reason=eot (or reset or nogame...)
public STOPDatagram(String reason){
this.reason=reason;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/STOPDatagram.java
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class STOPDatagram {
public String reason=null;
//STOP|reason=eot (or reset or nogame...)
public STOPDatagram(String reason){
this.reason=reason;
}
| public STOPDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/STATUSDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/Status.java
// public enum Status{
// IDLE,READY,PAUSE,RESET
// }
| import inouire.baggle.types.IllegalDatagramException;
import inouire.baggle.types.Status; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class STATUSDatagram {
public Status state=null;
public Integer id=null;
//STATUS|state=ready (client -> server)
public STATUSDatagram(Status state){
this.state=state;
this.id=null;
}
//STATE|id=player|state=ready (server -> client)
public STATUSDatagram(int id,Status state){
this.id=id;
this.state=state;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/Status.java
// public enum Status{
// IDLE,READY,PAUSE,RESET
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/STATUSDatagram.java
import inouire.baggle.types.IllegalDatagramException;
import inouire.baggle.types.Status;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class STATUSDatagram {
public Status state=null;
public Integer id=null;
//STATUS|state=ready (client -> server)
public STATUSDatagram(Status state){
this.state=state;
this.id=null;
}
//STATE|id=player|state=ready (server -> client)
public STATUSDatagram(int id,Status state){
this.id=id;
this.state=state;
}
| public STATUSDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/PINGDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | public Integer port=null;
public String players=null;
public Boolean big=false;
public Boolean rewardbigwords=false;
public Integer returnPort=null;
public PINGDatagram(int returnPort){
this.returnPort=returnPort;
}
//PING|lang=fr|chat=yes|min=3|pf=no|mode=trad|nb=3|max=5|name=salut a toi|priv=no|grid=BAGRIURGUIGIUEG|time=120|players=bibi,beber,mika|big=no|rewardbigwords=no
public PINGDatagram(int port,String name,String lang,boolean chat,int min,boolean pf, String mode,int nb,int max,boolean priv,String grid,int time,String players, boolean big, boolean rewardbigwords){
this.port=port;
this.lang=lang;
this.chat=chat;
this.min=min;
this.pf=pf;
this.mode=mode;
this.nb=nb;
this.max=max;
this.name=name;
this.priv=priv;
this.grid=grid;
this.time=time;
this.players=players;
this.big=big;
this.rewardbigwords=rewardbigwords;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/PINGDatagram.java
import inouire.baggle.types.IllegalDatagramException;
public Integer port=null;
public String players=null;
public Boolean big=false;
public Boolean rewardbigwords=false;
public Integer returnPort=null;
public PINGDatagram(int returnPort){
this.returnPort=returnPort;
}
//PING|lang=fr|chat=yes|min=3|pf=no|mode=trad|nb=3|max=5|name=salut a toi|priv=no|grid=BAGRIURGUIGIUEG|time=120|players=bibi,beber,mika|big=no|rewardbigwords=no
public PINGDatagram(int port,String name,String lang,boolean chat,int min,boolean pf, String mode,int nb,int max,boolean priv,String grid,int time,String players, boolean big, boolean rewardbigwords){
this.port=port;
this.lang=lang;
this.chat=chat;
this.min=min;
this.pf=pf;
this.mode=mode;
this.nb=nb;
this.max=max;
this.name=name;
this.priv=priv;
this.grid=grid;
this.time=time;
this.players=players;
this.big=big;
this.rewardbigwords=rewardbigwords;
}
| public PINGDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/RESULTDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import java.util.Arrays;
import java.util.LinkedList;
import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class RESULTDatagram {
public LinkedList<String> words;
public Integer score=null;
public Integer id=null;
public Integer rank=null;
//RESULT|id=657|score=4|words=une,tel,ces,ses
public RESULTDatagram(int id,int score,LinkedList<String> words){
this.id=id;
this.score=score;
this.words=words;
}
//RESULT|id=657|rank=2|score=4|words=une,tel,ces,ses
public RESULTDatagram(int id,int score,LinkedList<String> words,int rank){
this.id=id;
this.score=score;
this.words=words;
this.rank=rank;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/RESULTDatagram.java
import java.util.Arrays;
import java.util.LinkedList;
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class RESULTDatagram {
public LinkedList<String> words;
public Integer score=null;
public Integer id=null;
public Integer rank=null;
//RESULT|id=657|score=4|words=une,tel,ces,ses
public RESULTDatagram(int id,int score,LinkedList<String> words){
this.id=id;
this.score=score;
this.words=words;
}
//RESULT|id=657|rank=2|score=4|words=une,tel,ces,ses
public RESULTDatagram(int id,int score,LinkedList<String> words,int rank){
this.id=id;
this.score=score;
this.words=words;
this.rank=rank;
}
| public RESULTDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/LEAVEDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class LEAVEDatagram {
public Integer id=null;
//LEAVE|id=654
public LEAVEDatagram(int id){
this.id=id;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/LEAVEDatagram.java
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class LEAVEDatagram {
public Integer id=null;
//LEAVE|id=654
public LEAVEDatagram(int id){
this.id=id;
}
| public LEAVEDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-server/src/inouire/baggle/server/gui/ChoicePanel.java | // Path: baggle-server/src/inouire/baggle/server/Main.java
// public class Main {
//
// public static String VERSION = "3.6.2";
// public static boolean WITH_GUI = false;
// public static String CONFIG_FILE="";
// public static String DEFAULT_CONFIG_FILE="conf/baggle-server_config.myml";
// public static boolean DEV_MODE;
//
// //core process
// public static BaggleServer server;
//
// //main frame (gui only)
// public static MainFrame mainFrame = null;
//
//
// private static final String[] helpFlags = new String[] {"help","-h","--help"};
// private static final String[] guiFlags = new String[] {"-g","--gui"};
// private static final String[] configFlags = new String[] {"-c","--config"};
//
// /**
// * Main function
// * @param args the command line arguments
// */
// public static void main(String[] args) {
//
// if(Args.getOption(helpFlags, args)){
// printHelp();
// return;
// }else{
// printVersion();
// System.out.println("Use --help option to know more about the provided options");
// }
//
// WITH_GUI = Args.getOption(guiFlags, args);
// DEV_MODE = Args.getOption("--dev", args);
//
// SimpleLog.initConsoleConfig();
//
// if(WITH_GUI){
// SimpleLog.logger.info("Starting graphical user interface");
// DEFAULT_CONFIG_FILE = System.getProperty("user.home")+File.separator+".baggle"+File.separator+"baggle-server_config.myml";
// }
//
// SimpleLog.logger.info("Loading server configuration");
// ServerConfiguration server_config=null;
//
// //use config file from args
// if(Args.getOption(configFlags, args)){
// CONFIG_FILE=Args.getStringOption(configFlags, args, CONFIG_FILE);
// if(CONFIG_FILE.length()>0){
// server_config = ServerConfiguration.loadFromFile(CONFIG_FILE);
// }else{
// SimpleLog.logger.error("You must specify a config file after -c option");
// }
// }else{ //or use default config file
// CONFIG_FILE=DEFAULT_CONFIG_FILE;
// if(!new File(CONFIG_FILE).exists()){
// server_config = ServerConfiguration.createDefault(CONFIG_FILE);
// SimpleLog.logger.info("Default config file has been created in "+CONFIG_FILE+". You can edit it and restart b@ggle server.");
// SimpleLog.logger.info("Un fichier de configuration par défaut a été créé dans "+CONFIG_FILE+". Editez le (ou pas) et "+
// "redémarrez b@ggle server pour prendre en compte les modifications.");
// }else{
// server_config = ServerConfiguration.loadFromFile(CONFIG_FILE);
// }
// }
//
// if(server_config==null){
// SimpleLog.logger.error("Impossible to load server configuration from "+CONFIG_FILE);
// return;
// }
//
// //log in a room-named file
// String log_file = "log/"+server_config.get("room.name").replaceAll(" ","-")+".log";
// SimpleLog.logger.info("From now on everything will be logged into "+log_file+", see ya !");
// if(DEV_MODE){
// SimpleLog.initDevConfig();
// }else{
// SimpleLog.initProdConfig(log_file);
// }
//
//
// //start server, with or without gui assistant
// if(WITH_GUI){
// mainFrame = new MainFrame(server_config);
// mainFrame.setVisible(true);
// }else{
// server = new BaggleServer(server_config);
// server.startServer();
// }
//
// }
//
// /**
// * Displays basic options for the program
// */
// public static void printHelp(){
// printVersion();
// System.out.println("Usage:"
// + "\n\t--gui Use graphical user interface to start the server"
// + "\n\t-c [config file] Use specified config file instead"
// + "\n\t (by default "+DEFAULT_CONFIG_FILE+" is used)");
// }
//
// /**
// * Displays name and version for the program
// */
// public static void printVersion(){
// System.out.println("B@ggle server version "+Main.VERSION);
// }
//
// }
| import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import inouire.baggle.server.Main; | package inouire.baggle.server.gui;
/**
*
* @author edouard
*/
public class ChoicePanel extends JPanel{
public ChoicePanel(){
JPanel a=new JPanel();
JPanel b=new JPanel();
JPanel c=new JPanel();
| // Path: baggle-server/src/inouire/baggle/server/Main.java
// public class Main {
//
// public static String VERSION = "3.6.2";
// public static boolean WITH_GUI = false;
// public static String CONFIG_FILE="";
// public static String DEFAULT_CONFIG_FILE="conf/baggle-server_config.myml";
// public static boolean DEV_MODE;
//
// //core process
// public static BaggleServer server;
//
// //main frame (gui only)
// public static MainFrame mainFrame = null;
//
//
// private static final String[] helpFlags = new String[] {"help","-h","--help"};
// private static final String[] guiFlags = new String[] {"-g","--gui"};
// private static final String[] configFlags = new String[] {"-c","--config"};
//
// /**
// * Main function
// * @param args the command line arguments
// */
// public static void main(String[] args) {
//
// if(Args.getOption(helpFlags, args)){
// printHelp();
// return;
// }else{
// printVersion();
// System.out.println("Use --help option to know more about the provided options");
// }
//
// WITH_GUI = Args.getOption(guiFlags, args);
// DEV_MODE = Args.getOption("--dev", args);
//
// SimpleLog.initConsoleConfig();
//
// if(WITH_GUI){
// SimpleLog.logger.info("Starting graphical user interface");
// DEFAULT_CONFIG_FILE = System.getProperty("user.home")+File.separator+".baggle"+File.separator+"baggle-server_config.myml";
// }
//
// SimpleLog.logger.info("Loading server configuration");
// ServerConfiguration server_config=null;
//
// //use config file from args
// if(Args.getOption(configFlags, args)){
// CONFIG_FILE=Args.getStringOption(configFlags, args, CONFIG_FILE);
// if(CONFIG_FILE.length()>0){
// server_config = ServerConfiguration.loadFromFile(CONFIG_FILE);
// }else{
// SimpleLog.logger.error("You must specify a config file after -c option");
// }
// }else{ //or use default config file
// CONFIG_FILE=DEFAULT_CONFIG_FILE;
// if(!new File(CONFIG_FILE).exists()){
// server_config = ServerConfiguration.createDefault(CONFIG_FILE);
// SimpleLog.logger.info("Default config file has been created in "+CONFIG_FILE+". You can edit it and restart b@ggle server.");
// SimpleLog.logger.info("Un fichier de configuration par défaut a été créé dans "+CONFIG_FILE+". Editez le (ou pas) et "+
// "redémarrez b@ggle server pour prendre en compte les modifications.");
// }else{
// server_config = ServerConfiguration.loadFromFile(CONFIG_FILE);
// }
// }
//
// if(server_config==null){
// SimpleLog.logger.error("Impossible to load server configuration from "+CONFIG_FILE);
// return;
// }
//
// //log in a room-named file
// String log_file = "log/"+server_config.get("room.name").replaceAll(" ","-")+".log";
// SimpleLog.logger.info("From now on everything will be logged into "+log_file+", see ya !");
// if(DEV_MODE){
// SimpleLog.initDevConfig();
// }else{
// SimpleLog.initProdConfig(log_file);
// }
//
//
// //start server, with or without gui assistant
// if(WITH_GUI){
// mainFrame = new MainFrame(server_config);
// mainFrame.setVisible(true);
// }else{
// server = new BaggleServer(server_config);
// server.startServer();
// }
//
// }
//
// /**
// * Displays basic options for the program
// */
// public static void printHelp(){
// printVersion();
// System.out.println("Usage:"
// + "\n\t--gui Use graphical user interface to start the server"
// + "\n\t-c [config file] Use specified config file instead"
// + "\n\t (by default "+DEFAULT_CONFIG_FILE+" is used)");
// }
//
// /**
// * Displays name and version for the program
// */
// public static void printVersion(){
// System.out.println("B@ggle server version "+Main.VERSION);
// }
//
// }
// Path: baggle-server/src/inouire/baggle/server/gui/ChoicePanel.java
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import inouire.baggle.server.Main;
package inouire.baggle.server.gui;
/**
*
* @author edouard
*/
public class ChoicePanel extends JPanel{
public ChoicePanel(){
JPanel a=new JPanel();
JPanel b=new JPanel();
JPanel c=new JPanel();
| JLabel al = new JLabel("b@ggle-server v"+Main.VERSION); |
inouire/baggle | baggle-client/src/inouire/baggle/client/ServerEntry.java | // Path: baggle-datagrams/src/inouire/baggle/datagrams/Datagram.java
// public abstract class Datagram {
//
// public static String[] decompArg(String arg){
// String[] decomp = arg.split("=");
// if(decomp.length!=2){
// return null;
// }else{
// decomp[0]=decomp[0].trim().toLowerCase();
// decomp[1]=decomp[1].trim();
// }
// return decomp;
// }
//
//
// public static String replaceAccents(String s){
// String t=s;
// t=t.replaceAll("é", "é");
// t=t.replaceAll("è", "&eagrave;");
// t=t.replaceAll("ê", "ê");
// t=t.replaceAll("ë", "ë");
//
// t=t.replaceAll("î", "î");
// t=t.replaceAll("ï", "ï");
//
// t=t.replaceAll("à", "à");
// t=t.replaceAll("â", "â");
//
// t=t.replaceAll("ô","ô");
//
// t=t.replaceAll("û","û");
// t=t.replaceAll("ù","ù");
// t=t.replaceAll("ü","ü");
//
// t=t.replaceAll("ç","ç");
// return t;
// }
//
// public static String addAccents(String s){
// String t=s;
// t=t.replaceAll("é","é");
// t=t.replaceAll("&eagrave;","è");
// t=t.replaceAll("ê","ê");
// t=t.replaceAll("ë","ë");
//
// t=t.replaceAll("î","î");
// t=t.replaceAll("ï","ï");
//
// t=t.replaceAll("à","à");
// t=t.replaceAll("â","â");
//
// t=t.replaceAll("ô","ô");
//
// t=t.replaceAll("û","û");
// t=t.replaceAll("ù","ù");
// t=t.replaceAll("ü","ü");
//
// t=t.replaceAll("ç","ç");
// return t;
// }
//
// public static String removeAccents(String s){
// s=s.replaceAll("é", "e");
// s=s.replaceAll("è", "e");
// s=s.replaceAll("ê", "e");
// s=s.replaceAll("ë", "e");
// s=s.replaceAll("à", "a");
// s=s.replaceAll("â", "a");
// s=s.replaceAll("ä", "a");
// s=s.replaceAll("î", "i");
// s=s.replaceAll("ï", "i");
// s=s.replaceAll("ô", "o");
// s=s.replaceAll("ö", "o");
// s=s.replaceAll("û", "u");
// s=s.replaceAll("ù", "u");
// s=s.replaceAll("ü","u");
// s=s.replaceAll("ç", "c");
// return s;
// }
//
// public static boolean isChatMessage(String s) {
// s=s.trim();
// if(s.length()<3){
// if(s.equalsIgnoreCase("ok")){
// return true;
// }else{
// return false;
// }
// }else if(s.length() >= 16){
// return true;
// }
// for(char c : s.toUpperCase().toCharArray()){
// if(c<'A'||c>'Z'){
// return true;
// }
// }
// return false;
// }
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import java.net.InetSocketAddress;
import java.net.SocketAddress;
import inouire.baggle.datagrams.Datagram;
import inouire.baggle.types.IllegalDatagramException; | package inouire.baggle.client;
/**
*
* @author edouard
*/
public class ServerEntry {
public String host=null;
public Integer port=null;
public Long timestamp=null;
//host=192.168.0.1|timestamp=7657654
public ServerEntry(String host){
this.host=host;
this.timestamp=System.currentTimeMillis();
}
//host=192.168.0.1|port=12345|timestamp=7657654
public ServerEntry(String host,int port){
this.host=host;
this.port=port;
this.timestamp=System.currentTimeMillis();
}
| // Path: baggle-datagrams/src/inouire/baggle/datagrams/Datagram.java
// public abstract class Datagram {
//
// public static String[] decompArg(String arg){
// String[] decomp = arg.split("=");
// if(decomp.length!=2){
// return null;
// }else{
// decomp[0]=decomp[0].trim().toLowerCase();
// decomp[1]=decomp[1].trim();
// }
// return decomp;
// }
//
//
// public static String replaceAccents(String s){
// String t=s;
// t=t.replaceAll("é", "é");
// t=t.replaceAll("è", "&eagrave;");
// t=t.replaceAll("ê", "ê");
// t=t.replaceAll("ë", "ë");
//
// t=t.replaceAll("î", "î");
// t=t.replaceAll("ï", "ï");
//
// t=t.replaceAll("à", "à");
// t=t.replaceAll("â", "â");
//
// t=t.replaceAll("ô","ô");
//
// t=t.replaceAll("û","û");
// t=t.replaceAll("ù","ù");
// t=t.replaceAll("ü","ü");
//
// t=t.replaceAll("ç","ç");
// return t;
// }
//
// public static String addAccents(String s){
// String t=s;
// t=t.replaceAll("é","é");
// t=t.replaceAll("&eagrave;","è");
// t=t.replaceAll("ê","ê");
// t=t.replaceAll("ë","ë");
//
// t=t.replaceAll("î","î");
// t=t.replaceAll("ï","ï");
//
// t=t.replaceAll("à","à");
// t=t.replaceAll("â","â");
//
// t=t.replaceAll("ô","ô");
//
// t=t.replaceAll("û","û");
// t=t.replaceAll("ù","ù");
// t=t.replaceAll("ü","ü");
//
// t=t.replaceAll("ç","ç");
// return t;
// }
//
// public static String removeAccents(String s){
// s=s.replaceAll("é", "e");
// s=s.replaceAll("è", "e");
// s=s.replaceAll("ê", "e");
// s=s.replaceAll("ë", "e");
// s=s.replaceAll("à", "a");
// s=s.replaceAll("â", "a");
// s=s.replaceAll("ä", "a");
// s=s.replaceAll("î", "i");
// s=s.replaceAll("ï", "i");
// s=s.replaceAll("ô", "o");
// s=s.replaceAll("ö", "o");
// s=s.replaceAll("û", "u");
// s=s.replaceAll("ù", "u");
// s=s.replaceAll("ü","u");
// s=s.replaceAll("ç", "c");
// return s;
// }
//
// public static boolean isChatMessage(String s) {
// s=s.trim();
// if(s.length()<3){
// if(s.equalsIgnoreCase("ok")){
// return true;
// }else{
// return false;
// }
// }else if(s.length() >= 16){
// return true;
// }
// for(char c : s.toUpperCase().toCharArray()){
// if(c<'A'||c>'Z'){
// return true;
// }
// }
// return false;
// }
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-client/src/inouire/baggle/client/ServerEntry.java
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import inouire.baggle.datagrams.Datagram;
import inouire.baggle.types.IllegalDatagramException;
package inouire.baggle.client;
/**
*
* @author edouard
*/
public class ServerEntry {
public String host=null;
public Integer port=null;
public Long timestamp=null;
//host=192.168.0.1|timestamp=7657654
public ServerEntry(String host){
this.host=host;
this.timestamp=System.currentTimeMillis();
}
//host=192.168.0.1|port=12345|timestamp=7657654
public ServerEntry(String host,int port){
this.host=host;
this.port=port;
this.timestamp=System.currentTimeMillis();
}
| public ServerEntry(String[] content) throws IllegalDatagramException{ |
inouire/baggle | baggle-client/src/inouire/baggle/client/ServerEntry.java | // Path: baggle-datagrams/src/inouire/baggle/datagrams/Datagram.java
// public abstract class Datagram {
//
// public static String[] decompArg(String arg){
// String[] decomp = arg.split("=");
// if(decomp.length!=2){
// return null;
// }else{
// decomp[0]=decomp[0].trim().toLowerCase();
// decomp[1]=decomp[1].trim();
// }
// return decomp;
// }
//
//
// public static String replaceAccents(String s){
// String t=s;
// t=t.replaceAll("é", "é");
// t=t.replaceAll("è", "&eagrave;");
// t=t.replaceAll("ê", "ê");
// t=t.replaceAll("ë", "ë");
//
// t=t.replaceAll("î", "î");
// t=t.replaceAll("ï", "ï");
//
// t=t.replaceAll("à", "à");
// t=t.replaceAll("â", "â");
//
// t=t.replaceAll("ô","ô");
//
// t=t.replaceAll("û","û");
// t=t.replaceAll("ù","ù");
// t=t.replaceAll("ü","ü");
//
// t=t.replaceAll("ç","ç");
// return t;
// }
//
// public static String addAccents(String s){
// String t=s;
// t=t.replaceAll("é","é");
// t=t.replaceAll("&eagrave;","è");
// t=t.replaceAll("ê","ê");
// t=t.replaceAll("ë","ë");
//
// t=t.replaceAll("î","î");
// t=t.replaceAll("ï","ï");
//
// t=t.replaceAll("à","à");
// t=t.replaceAll("â","â");
//
// t=t.replaceAll("ô","ô");
//
// t=t.replaceAll("û","û");
// t=t.replaceAll("ù","ù");
// t=t.replaceAll("ü","ü");
//
// t=t.replaceAll("ç","ç");
// return t;
// }
//
// public static String removeAccents(String s){
// s=s.replaceAll("é", "e");
// s=s.replaceAll("è", "e");
// s=s.replaceAll("ê", "e");
// s=s.replaceAll("ë", "e");
// s=s.replaceAll("à", "a");
// s=s.replaceAll("â", "a");
// s=s.replaceAll("ä", "a");
// s=s.replaceAll("î", "i");
// s=s.replaceAll("ï", "i");
// s=s.replaceAll("ô", "o");
// s=s.replaceAll("ö", "o");
// s=s.replaceAll("û", "u");
// s=s.replaceAll("ù", "u");
// s=s.replaceAll("ü","u");
// s=s.replaceAll("ç", "c");
// return s;
// }
//
// public static boolean isChatMessage(String s) {
// s=s.trim();
// if(s.length()<3){
// if(s.equalsIgnoreCase("ok")){
// return true;
// }else{
// return false;
// }
// }else if(s.length() >= 16){
// return true;
// }
// for(char c : s.toUpperCase().toCharArray()){
// if(c<'A'||c>'Z'){
// return true;
// }
// }
// return false;
// }
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import java.net.InetSocketAddress;
import java.net.SocketAddress;
import inouire.baggle.datagrams.Datagram;
import inouire.baggle.types.IllegalDatagramException; | throw new IllegalDatagramException();
}
checkDatagram();
}
public String getHost(){
return host;
}
public int getPort(){
return port;
}
public SocketAddress getSocketAddress(){
if(port==null){
return null;
}else{
return new InetSocketAddress(host,port);
}
}
public Boolean equals(ServerEntry server_entry){
return (host.equals(server_entry.host) && port.equals(server_entry.port));
}
private void checkDatagram() throws IllegalDatagramException {
if(host==null || timestamp==null){
throw new IllegalDatagramException();
}
}
private void parseArg(String arg){ | // Path: baggle-datagrams/src/inouire/baggle/datagrams/Datagram.java
// public abstract class Datagram {
//
// public static String[] decompArg(String arg){
// String[] decomp = arg.split("=");
// if(decomp.length!=2){
// return null;
// }else{
// decomp[0]=decomp[0].trim().toLowerCase();
// decomp[1]=decomp[1].trim();
// }
// return decomp;
// }
//
//
// public static String replaceAccents(String s){
// String t=s;
// t=t.replaceAll("é", "é");
// t=t.replaceAll("è", "&eagrave;");
// t=t.replaceAll("ê", "ê");
// t=t.replaceAll("ë", "ë");
//
// t=t.replaceAll("î", "î");
// t=t.replaceAll("ï", "ï");
//
// t=t.replaceAll("à", "à");
// t=t.replaceAll("â", "â");
//
// t=t.replaceAll("ô","ô");
//
// t=t.replaceAll("û","û");
// t=t.replaceAll("ù","ù");
// t=t.replaceAll("ü","ü");
//
// t=t.replaceAll("ç","ç");
// return t;
// }
//
// public static String addAccents(String s){
// String t=s;
// t=t.replaceAll("é","é");
// t=t.replaceAll("&eagrave;","è");
// t=t.replaceAll("ê","ê");
// t=t.replaceAll("ë","ë");
//
// t=t.replaceAll("î","î");
// t=t.replaceAll("ï","ï");
//
// t=t.replaceAll("à","à");
// t=t.replaceAll("â","â");
//
// t=t.replaceAll("ô","ô");
//
// t=t.replaceAll("û","û");
// t=t.replaceAll("ù","ù");
// t=t.replaceAll("ü","ü");
//
// t=t.replaceAll("ç","ç");
// return t;
// }
//
// public static String removeAccents(String s){
// s=s.replaceAll("é", "e");
// s=s.replaceAll("è", "e");
// s=s.replaceAll("ê", "e");
// s=s.replaceAll("ë", "e");
// s=s.replaceAll("à", "a");
// s=s.replaceAll("â", "a");
// s=s.replaceAll("ä", "a");
// s=s.replaceAll("î", "i");
// s=s.replaceAll("ï", "i");
// s=s.replaceAll("ô", "o");
// s=s.replaceAll("ö", "o");
// s=s.replaceAll("û", "u");
// s=s.replaceAll("ù", "u");
// s=s.replaceAll("ü","u");
// s=s.replaceAll("ç", "c");
// return s;
// }
//
// public static boolean isChatMessage(String s) {
// s=s.trim();
// if(s.length()<3){
// if(s.equalsIgnoreCase("ok")){
// return true;
// }else{
// return false;
// }
// }else if(s.length() >= 16){
// return true;
// }
// for(char c : s.toUpperCase().toCharArray()){
// if(c<'A'||c>'Z'){
// return true;
// }
// }
// return false;
// }
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-client/src/inouire/baggle/client/ServerEntry.java
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import inouire.baggle.datagrams.Datagram;
import inouire.baggle.types.IllegalDatagramException;
throw new IllegalDatagramException();
}
checkDatagram();
}
public String getHost(){
return host;
}
public int getPort(){
return port;
}
public SocketAddress getSocketAddress(){
if(port==null){
return null;
}else{
return new InetSocketAddress(host,port);
}
}
public Boolean equals(ServerEntry server_entry){
return (host.equals(server_entry.host) && port.equals(server_entry.port));
}
private void checkDatagram() throws IllegalDatagramException {
if(host==null || timestamp==null){
throw new IllegalDatagramException();
}
}
private void parseArg(String arg){ | String [] keyValue = Datagram.decompArg(arg); |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/WORDDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/Words.java
// public enum Words{
// GOOD,NOT_IN_DIC,NOT_IN_GRID,SHORT,FILTERED,ALREADY_FOUND
// }
| import inouire.baggle.types.IllegalDatagramException;
import inouire.baggle.types.Words; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
/**
*
* @author Edouard de Labareyre
*/
public class WORDDatagram {
public String word=null; | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/Words.java
// public enum Words{
// GOOD,NOT_IN_DIC,NOT_IN_GRID,SHORT,FILTERED,ALREADY_FOUND
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/WORDDatagram.java
import inouire.baggle.types.IllegalDatagramException;
import inouire.baggle.types.Words;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
/**
*
* @author Edouard de Labareyre
*/
public class WORDDatagram {
public String word=null; | public Words status=null; |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/WORDDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/Words.java
// public enum Words{
// GOOD,NOT_IN_DIC,NOT_IN_GRID,SHORT,FILTERED,ALREADY_FOUND
// }
| import inouire.baggle.types.IllegalDatagramException;
import inouire.baggle.types.Words; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
/**
*
* @author Edouard de Labareyre
*/
public class WORDDatagram {
public String word=null;
public Words status=null;
//WORD|word=pointu
public WORDDatagram(String word){
this.word=word;
this.status=null;
}
//WORD|word=pointu|status=GOOD
public WORDDatagram(String word,Words status){
this.word=word;
this.status=status;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
//
// Path: baggle-datagrams/src/inouire/baggle/types/Words.java
// public enum Words{
// GOOD,NOT_IN_DIC,NOT_IN_GRID,SHORT,FILTERED,ALREADY_FOUND
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/WORDDatagram.java
import inouire.baggle.types.IllegalDatagramException;
import inouire.baggle.types.Words;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
/**
*
* @author Edouard de Labareyre
*/
public class WORDDatagram {
public String word=null;
public Words status=null;
//WORD|word=pointu
public WORDDatagram(String word){
this.word=word;
this.status=null;
}
//WORD|word=pointu|status=GOOD
public WORDDatagram(String word,Words status){
this.word=word;
this.status=status;
}
| public WORDDatagram(String[] args) throws IllegalDatagramException{ |
inouire/baggle | baggle-datagrams/src/inouire/baggle/datagrams/SCOREDatagram.java | // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
| import inouire.baggle.types.IllegalDatagramException; | /* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class SCOREDatagram {
public Integer score=null;
public Integer id=null;
//SCORE|id=657|score=210
public SCOREDatagram(int id,int score){
this.id=id;
this.score=score;
}
| // Path: baggle-datagrams/src/inouire/baggle/types/IllegalDatagramException.java
// public class IllegalDatagramException extends Exception{
//
// }
// Path: baggle-datagrams/src/inouire/baggle/datagrams/SCOREDatagram.java
import inouire.baggle.types.IllegalDatagramException;
/* Copyright 2009-2018 Edouard Garnier de Labareyre
*
* This file is part of B@ggle.
*
* B@ggle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B@ggle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B@ggle. If not, see <http://www.gnu.org/licenses/>.
*/
package inouire.baggle.datagrams;
public class SCOREDatagram {
public Integer score=null;
public Integer id=null;
//SCORE|id=657|score=210
public SCOREDatagram(int id,int score){
this.id=id;
this.score=score;
}
| public SCOREDatagram(String[] args) throws IllegalDatagramException{ |
cdapio/netty-http | src/test/java/io/cdap/http/HandlerHookTest.java | // Path: src/main/java/io/cdap/http/internal/HandlerInfo.java
// public class HandlerInfo {
// private final String handlerName;
// private final String methodName;
//
// public HandlerInfo(String handlerName, String methodName) {
// this.handlerName = handlerName;
// this.methodName = methodName;
// }
//
// public String getHandlerName() {
// return handlerName;
// }
//
// public String getMethodName() {
// return methodName;
// }
// }
| import io.cdap.http.internal.HandlerInfo;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit; | }
private void awaitPostHook() throws Exception {
handlerHook1.awaitPost();
handlerHook2.awaitPost();
}
private static class TestHandlerHook extends AbstractHandlerHook {
private volatile int numPreCalls = 0;
private volatile int numPostCalls = 0;
private final CyclicBarrier postBarrier = new CyclicBarrier(2);
public int getNumPreCalls() {
return numPreCalls;
}
public int getNumPostCalls() {
return numPostCalls;
}
public void reset() {
numPreCalls = 0;
numPostCalls = 0;
}
public void awaitPost() throws Exception {
postBarrier.await();
}
@Override | // Path: src/main/java/io/cdap/http/internal/HandlerInfo.java
// public class HandlerInfo {
// private final String handlerName;
// private final String methodName;
//
// public HandlerInfo(String handlerName, String methodName) {
// this.handlerName = handlerName;
// this.methodName = methodName;
// }
//
// public String getHandlerName() {
// return handlerName;
// }
//
// public String getMethodName() {
// return methodName;
// }
// }
// Path: src/test/java/io/cdap/http/HandlerHookTest.java
import io.cdap.http.internal.HandlerInfo;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
}
private void awaitPostHook() throws Exception {
handlerHook1.awaitPost();
handlerHook2.awaitPost();
}
private static class TestHandlerHook extends AbstractHandlerHook {
private volatile int numPreCalls = 0;
private volatile int numPostCalls = 0;
private final CyclicBarrier postBarrier = new CyclicBarrier(2);
public int getNumPreCalls() {
return numPreCalls;
}
public int getNumPostCalls() {
return numPostCalls;
}
public void reset() {
numPreCalls = 0;
numPostCalls = 0;
}
public void awaitPost() throws Exception {
postBarrier.await();
}
@Override | public boolean preCall(HttpRequest request, HttpResponder responder, HandlerInfo handlerInfo) { |
cdapio/netty-http | src/test/java/io/cdap/http/InternalHttpResponderTest.java | // Path: src/main/java/io/cdap/http/internal/InternalHttpResponder.java
// public class InternalHttpResponder extends AbstractHttpResponder {
//
// private static final Logger LOG = LoggerFactory.getLogger(InternalHttpResponder.class);
//
// private InternalHttpResponse response;
//
// @Override
// public ChunkResponder sendChunkStart(final HttpResponseStatus status, HttpHeaders headers) {
// return new ChunkResponder() {
//
// private ByteBuf contentChunks = Unpooled.EMPTY_BUFFER;
// private boolean closed;
//
// @Override
// public void sendChunk(ByteBuffer chunk) throws IOException {
// sendChunk(Unpooled.wrappedBuffer(chunk));
// }
//
// @Override
// public synchronized void sendChunk(ByteBuf chunk) throws IOException {
// if (closed) {
// throw new IOException("ChunkResponder already closed.");
// }
// contentChunks = Unpooled.wrappedBuffer(contentChunks, chunk);
// }
//
// @Override
// public synchronized void close() throws IOException {
// if (closed) {
// return;
// }
// closed = true;
// response = new AbstractInternalResponse(status.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new ByteBufInputStream(contentChunks.duplicate());
// }
// };
// }
// };
// }
//
// @Override
// public void sendContent(HttpResponseStatus status, final ByteBuf content, HttpHeaders headers) {
// response = new AbstractInternalResponse(status.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new ByteBufInputStream(content.duplicate());
// }
// };
// }
//
// @Override
// public void sendFile(final File file, HttpHeaders headers) {
// response = new AbstractInternalResponse(HttpResponseStatus.OK.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new FileInputStream(file);
// }
// };
// }
//
// @Override
// public void sendContent(HttpResponseStatus status, BodyProducer bodyProducer, HttpHeaders headers) {
// // Buffer all contents produced by the body producer
// ByteBuf contentChunks = Unpooled.EMPTY_BUFFER;
// try {
// ByteBuf chunk = bodyProducer.nextChunk();
// while (chunk.isReadable()) {
// contentChunks = Unpooled.wrappedBuffer(contentChunks, chunk);
// chunk = bodyProducer.nextChunk();
// }
//
// bodyProducer.finished();
// final ByteBuf finalContentChunks = contentChunks;
// response = new AbstractInternalResponse(status.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new ByteBufInputStream(finalContentChunks.duplicate());
// }
// };
// } catch (Throwable t) {
// try {
// bodyProducer.handleError(t);
// } catch (Throwable et) {
// LOG.warn("Exception raised from BodyProducer.handleError() for {}", bodyProducer, et);
// }
// }
// }
//
// /**
// * Returns the the last {@link InternalHttpResponse} created via one of the send methods.
// *
// * @throws IllegalStateException if there is no {@link InternalHttpResponse} available
// */
// public InternalHttpResponse getResponse() {
// if (response == null) {
// throw new IllegalStateException("No InternalHttpResponse available");
// }
// return response;
// }
//
// /**
// * Abstract implementation of {@link InternalHttpResponse}.
// */
// private abstract static class AbstractInternalResponse implements InternalHttpResponse {
// private final int statusCode;
//
// AbstractInternalResponse(int statusCode) {
// this.statusCode = statusCode;
// }
//
// @Override
// public int getStatusCode() {
// return statusCode;
// }
// }
// }
//
// Path: src/main/java/io/cdap/http/internal/InternalHttpResponse.java
// public interface InternalHttpResponse {
//
// int getStatusCode();
//
// /**
// * Opens an {@link InputStream} that contains the response content. The caller is responsible of closing the
// * returned stream.
// *
// * @return an {@link InputStream} for reading response content
// * @throws IOException if failed to open the stream
// */
// InputStream openInputStream() throws IOException;
// }
| import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.cdap.http.internal.InternalHttpResponder;
import io.cdap.http.internal.InternalHttpResponse;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.junit.Assert;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException; | /*
* Copyright © 2014-2019 Cask Data, 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 io.cdap.http;
/**
*
*/
public class InternalHttpResponderTest {
@Test
public void testSendJson() throws IOException { | // Path: src/main/java/io/cdap/http/internal/InternalHttpResponder.java
// public class InternalHttpResponder extends AbstractHttpResponder {
//
// private static final Logger LOG = LoggerFactory.getLogger(InternalHttpResponder.class);
//
// private InternalHttpResponse response;
//
// @Override
// public ChunkResponder sendChunkStart(final HttpResponseStatus status, HttpHeaders headers) {
// return new ChunkResponder() {
//
// private ByteBuf contentChunks = Unpooled.EMPTY_BUFFER;
// private boolean closed;
//
// @Override
// public void sendChunk(ByteBuffer chunk) throws IOException {
// sendChunk(Unpooled.wrappedBuffer(chunk));
// }
//
// @Override
// public synchronized void sendChunk(ByteBuf chunk) throws IOException {
// if (closed) {
// throw new IOException("ChunkResponder already closed.");
// }
// contentChunks = Unpooled.wrappedBuffer(contentChunks, chunk);
// }
//
// @Override
// public synchronized void close() throws IOException {
// if (closed) {
// return;
// }
// closed = true;
// response = new AbstractInternalResponse(status.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new ByteBufInputStream(contentChunks.duplicate());
// }
// };
// }
// };
// }
//
// @Override
// public void sendContent(HttpResponseStatus status, final ByteBuf content, HttpHeaders headers) {
// response = new AbstractInternalResponse(status.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new ByteBufInputStream(content.duplicate());
// }
// };
// }
//
// @Override
// public void sendFile(final File file, HttpHeaders headers) {
// response = new AbstractInternalResponse(HttpResponseStatus.OK.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new FileInputStream(file);
// }
// };
// }
//
// @Override
// public void sendContent(HttpResponseStatus status, BodyProducer bodyProducer, HttpHeaders headers) {
// // Buffer all contents produced by the body producer
// ByteBuf contentChunks = Unpooled.EMPTY_BUFFER;
// try {
// ByteBuf chunk = bodyProducer.nextChunk();
// while (chunk.isReadable()) {
// contentChunks = Unpooled.wrappedBuffer(contentChunks, chunk);
// chunk = bodyProducer.nextChunk();
// }
//
// bodyProducer.finished();
// final ByteBuf finalContentChunks = contentChunks;
// response = new AbstractInternalResponse(status.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new ByteBufInputStream(finalContentChunks.duplicate());
// }
// };
// } catch (Throwable t) {
// try {
// bodyProducer.handleError(t);
// } catch (Throwable et) {
// LOG.warn("Exception raised from BodyProducer.handleError() for {}", bodyProducer, et);
// }
// }
// }
//
// /**
// * Returns the the last {@link InternalHttpResponse} created via one of the send methods.
// *
// * @throws IllegalStateException if there is no {@link InternalHttpResponse} available
// */
// public InternalHttpResponse getResponse() {
// if (response == null) {
// throw new IllegalStateException("No InternalHttpResponse available");
// }
// return response;
// }
//
// /**
// * Abstract implementation of {@link InternalHttpResponse}.
// */
// private abstract static class AbstractInternalResponse implements InternalHttpResponse {
// private final int statusCode;
//
// AbstractInternalResponse(int statusCode) {
// this.statusCode = statusCode;
// }
//
// @Override
// public int getStatusCode() {
// return statusCode;
// }
// }
// }
//
// Path: src/main/java/io/cdap/http/internal/InternalHttpResponse.java
// public interface InternalHttpResponse {
//
// int getStatusCode();
//
// /**
// * Opens an {@link InputStream} that contains the response content. The caller is responsible of closing the
// * returned stream.
// *
// * @return an {@link InputStream} for reading response content
// * @throws IOException if failed to open the stream
// */
// InputStream openInputStream() throws IOException;
// }
// Path: src/test/java/io/cdap/http/InternalHttpResponderTest.java
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.cdap.http.internal.InternalHttpResponder;
import io.cdap.http.internal.InternalHttpResponse;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.junit.Assert;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
/*
* Copyright © 2014-2019 Cask Data, 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 io.cdap.http;
/**
*
*/
public class InternalHttpResponderTest {
@Test
public void testSendJson() throws IOException { | InternalHttpResponder responder = new InternalHttpResponder(); |
cdapio/netty-http | src/test/java/io/cdap/http/InternalHttpResponderTest.java | // Path: src/main/java/io/cdap/http/internal/InternalHttpResponder.java
// public class InternalHttpResponder extends AbstractHttpResponder {
//
// private static final Logger LOG = LoggerFactory.getLogger(InternalHttpResponder.class);
//
// private InternalHttpResponse response;
//
// @Override
// public ChunkResponder sendChunkStart(final HttpResponseStatus status, HttpHeaders headers) {
// return new ChunkResponder() {
//
// private ByteBuf contentChunks = Unpooled.EMPTY_BUFFER;
// private boolean closed;
//
// @Override
// public void sendChunk(ByteBuffer chunk) throws IOException {
// sendChunk(Unpooled.wrappedBuffer(chunk));
// }
//
// @Override
// public synchronized void sendChunk(ByteBuf chunk) throws IOException {
// if (closed) {
// throw new IOException("ChunkResponder already closed.");
// }
// contentChunks = Unpooled.wrappedBuffer(contentChunks, chunk);
// }
//
// @Override
// public synchronized void close() throws IOException {
// if (closed) {
// return;
// }
// closed = true;
// response = new AbstractInternalResponse(status.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new ByteBufInputStream(contentChunks.duplicate());
// }
// };
// }
// };
// }
//
// @Override
// public void sendContent(HttpResponseStatus status, final ByteBuf content, HttpHeaders headers) {
// response = new AbstractInternalResponse(status.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new ByteBufInputStream(content.duplicate());
// }
// };
// }
//
// @Override
// public void sendFile(final File file, HttpHeaders headers) {
// response = new AbstractInternalResponse(HttpResponseStatus.OK.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new FileInputStream(file);
// }
// };
// }
//
// @Override
// public void sendContent(HttpResponseStatus status, BodyProducer bodyProducer, HttpHeaders headers) {
// // Buffer all contents produced by the body producer
// ByteBuf contentChunks = Unpooled.EMPTY_BUFFER;
// try {
// ByteBuf chunk = bodyProducer.nextChunk();
// while (chunk.isReadable()) {
// contentChunks = Unpooled.wrappedBuffer(contentChunks, chunk);
// chunk = bodyProducer.nextChunk();
// }
//
// bodyProducer.finished();
// final ByteBuf finalContentChunks = contentChunks;
// response = new AbstractInternalResponse(status.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new ByteBufInputStream(finalContentChunks.duplicate());
// }
// };
// } catch (Throwable t) {
// try {
// bodyProducer.handleError(t);
// } catch (Throwable et) {
// LOG.warn("Exception raised from BodyProducer.handleError() for {}", bodyProducer, et);
// }
// }
// }
//
// /**
// * Returns the the last {@link InternalHttpResponse} created via one of the send methods.
// *
// * @throws IllegalStateException if there is no {@link InternalHttpResponse} available
// */
// public InternalHttpResponse getResponse() {
// if (response == null) {
// throw new IllegalStateException("No InternalHttpResponse available");
// }
// return response;
// }
//
// /**
// * Abstract implementation of {@link InternalHttpResponse}.
// */
// private abstract static class AbstractInternalResponse implements InternalHttpResponse {
// private final int statusCode;
//
// AbstractInternalResponse(int statusCode) {
// this.statusCode = statusCode;
// }
//
// @Override
// public int getStatusCode() {
// return statusCode;
// }
// }
// }
//
// Path: src/main/java/io/cdap/http/internal/InternalHttpResponse.java
// public interface InternalHttpResponse {
//
// int getStatusCode();
//
// /**
// * Opens an {@link InputStream} that contains the response content. The caller is responsible of closing the
// * returned stream.
// *
// * @return an {@link InputStream} for reading response content
// * @throws IOException if failed to open the stream
// */
// InputStream openInputStream() throws IOException;
// }
| import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.cdap.http.internal.InternalHttpResponder;
import io.cdap.http.internal.InternalHttpResponse;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.junit.Assert;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException; | /*
* Copyright © 2014-2019 Cask Data, 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 io.cdap.http;
/**
*
*/
public class InternalHttpResponderTest {
@Test
public void testSendJson() throws IOException {
InternalHttpResponder responder = new InternalHttpResponder();
JsonObject output = new JsonObject();
output.addProperty("data", "this is some data");
responder.sendJson(HttpResponseStatus.OK, output.toString());
| // Path: src/main/java/io/cdap/http/internal/InternalHttpResponder.java
// public class InternalHttpResponder extends AbstractHttpResponder {
//
// private static final Logger LOG = LoggerFactory.getLogger(InternalHttpResponder.class);
//
// private InternalHttpResponse response;
//
// @Override
// public ChunkResponder sendChunkStart(final HttpResponseStatus status, HttpHeaders headers) {
// return new ChunkResponder() {
//
// private ByteBuf contentChunks = Unpooled.EMPTY_BUFFER;
// private boolean closed;
//
// @Override
// public void sendChunk(ByteBuffer chunk) throws IOException {
// sendChunk(Unpooled.wrappedBuffer(chunk));
// }
//
// @Override
// public synchronized void sendChunk(ByteBuf chunk) throws IOException {
// if (closed) {
// throw new IOException("ChunkResponder already closed.");
// }
// contentChunks = Unpooled.wrappedBuffer(contentChunks, chunk);
// }
//
// @Override
// public synchronized void close() throws IOException {
// if (closed) {
// return;
// }
// closed = true;
// response = new AbstractInternalResponse(status.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new ByteBufInputStream(contentChunks.duplicate());
// }
// };
// }
// };
// }
//
// @Override
// public void sendContent(HttpResponseStatus status, final ByteBuf content, HttpHeaders headers) {
// response = new AbstractInternalResponse(status.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new ByteBufInputStream(content.duplicate());
// }
// };
// }
//
// @Override
// public void sendFile(final File file, HttpHeaders headers) {
// response = new AbstractInternalResponse(HttpResponseStatus.OK.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new FileInputStream(file);
// }
// };
// }
//
// @Override
// public void sendContent(HttpResponseStatus status, BodyProducer bodyProducer, HttpHeaders headers) {
// // Buffer all contents produced by the body producer
// ByteBuf contentChunks = Unpooled.EMPTY_BUFFER;
// try {
// ByteBuf chunk = bodyProducer.nextChunk();
// while (chunk.isReadable()) {
// contentChunks = Unpooled.wrappedBuffer(contentChunks, chunk);
// chunk = bodyProducer.nextChunk();
// }
//
// bodyProducer.finished();
// final ByteBuf finalContentChunks = contentChunks;
// response = new AbstractInternalResponse(status.code()) {
// @Override
// public InputStream openInputStream() throws IOException {
// return new ByteBufInputStream(finalContentChunks.duplicate());
// }
// };
// } catch (Throwable t) {
// try {
// bodyProducer.handleError(t);
// } catch (Throwable et) {
// LOG.warn("Exception raised from BodyProducer.handleError() for {}", bodyProducer, et);
// }
// }
// }
//
// /**
// * Returns the the last {@link InternalHttpResponse} created via one of the send methods.
// *
// * @throws IllegalStateException if there is no {@link InternalHttpResponse} available
// */
// public InternalHttpResponse getResponse() {
// if (response == null) {
// throw new IllegalStateException("No InternalHttpResponse available");
// }
// return response;
// }
//
// /**
// * Abstract implementation of {@link InternalHttpResponse}.
// */
// private abstract static class AbstractInternalResponse implements InternalHttpResponse {
// private final int statusCode;
//
// AbstractInternalResponse(int statusCode) {
// this.statusCode = statusCode;
// }
//
// @Override
// public int getStatusCode() {
// return statusCode;
// }
// }
// }
//
// Path: src/main/java/io/cdap/http/internal/InternalHttpResponse.java
// public interface InternalHttpResponse {
//
// int getStatusCode();
//
// /**
// * Opens an {@link InputStream} that contains the response content. The caller is responsible of closing the
// * returned stream.
// *
// * @return an {@link InputStream} for reading response content
// * @throws IOException if failed to open the stream
// */
// InputStream openInputStream() throws IOException;
// }
// Path: src/test/java/io/cdap/http/InternalHttpResponderTest.java
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.cdap.http.internal.InternalHttpResponder;
import io.cdap.http.internal.InternalHttpResponse;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.junit.Assert;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
/*
* Copyright © 2014-2019 Cask Data, 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 io.cdap.http;
/**
*
*/
public class InternalHttpResponderTest {
@Test
public void testSendJson() throws IOException {
InternalHttpResponder responder = new InternalHttpResponder();
JsonObject output = new JsonObject();
output.addProperty("data", "this is some data");
responder.sendJson(HttpResponseStatus.OK, output.toString());
| InternalHttpResponse response = responder.getResponse(); |
cdapio/netty-http | src/main/java/io/cdap/http/AbstractHandlerHook.java | // Path: src/main/java/io/cdap/http/internal/HandlerInfo.java
// public class HandlerInfo {
// private final String handlerName;
// private final String methodName;
//
// public HandlerInfo(String handlerName, String methodName) {
// this.handlerName = handlerName;
// this.methodName = methodName;
// }
//
// public String getHandlerName() {
// return handlerName;
// }
//
// public String getMethodName() {
// return methodName;
// }
// }
| import io.cdap.http.internal.HandlerInfo;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus; | /*
* Copyright © 2014-2019 Cask Data, 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 io.cdap.http;
/**
* A base implementation of {@link HandlerHook} that provides no-op for both
* {@link HandlerHook#preCall(HttpRequest, HttpResponder, HandlerInfo)}
* and {@link HandlerHook#postCall(HttpRequest, HttpResponseStatus, HandlerInfo)} methods.
*/
public abstract class AbstractHandlerHook implements HandlerHook {
@Override | // Path: src/main/java/io/cdap/http/internal/HandlerInfo.java
// public class HandlerInfo {
// private final String handlerName;
// private final String methodName;
//
// public HandlerInfo(String handlerName, String methodName) {
// this.handlerName = handlerName;
// this.methodName = methodName;
// }
//
// public String getHandlerName() {
// return handlerName;
// }
//
// public String getMethodName() {
// return methodName;
// }
// }
// Path: src/main/java/io/cdap/http/AbstractHandlerHook.java
import io.cdap.http.internal.HandlerInfo;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
/*
* Copyright © 2014-2019 Cask Data, 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 io.cdap.http;
/**
* A base implementation of {@link HandlerHook} that provides no-op for both
* {@link HandlerHook#preCall(HttpRequest, HttpResponder, HandlerInfo)}
* and {@link HandlerHook#postCall(HttpRequest, HttpResponseStatus, HandlerInfo)} methods.
*/
public abstract class AbstractHandlerHook implements HandlerHook {
@Override | public boolean preCall(HttpRequest request, HttpResponder responder, HandlerInfo handlerInfo) { |
MummyDing/Leisure | app/src/main/java/com/mummyding/app/leisure/support/Settings.java | // Path: app/src/main/java/com/mummyding/app/leisure/LeisureApplication.java
// public class LeisureApplication extends Application {
// public static Context AppContext = null;
// @Override
// public void onCreate() {
// super.onCreate();
// AppContext = getApplicationContext();
// Fresco.initialize(AppContext);
// }
// }
| import com.mummyding.app.leisure.LeisureApplication;
import android.content.Context;
import android.content.SharedPreferences; | /*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.support;
/**
* Created by mummyding on 15-12-6.
* GitHub: https://github.com/MummyDing/
* Blog: http://blog.csdn.net/mummyding
*/
public class Settings {
public static boolean needRecreate = false;
public static boolean isShakeMode = true;
public static boolean noPicMode = false;
public static boolean isNightMode = false;
public static boolean isAutoRefresh = false;
public static boolean isExitConfirm = true;
public static int searchID = 0;
public static int swipeID = 0;
public static final String XML_NAME = "settings";
public static final String SHAKE_TO_RETURN = "shake_to_return_new";
public static final String NO_PIC_MODE = "no_pic_mode";
public static final String NIGHT_MODE = "night_mode";
public static final String AUTO_REFRESH = "auto_refresh";
public static final String LANGUAGE = "language";
public static final String EXIT_CONFIRM = "exit_confirm";
public static final String CLEAR_CACHE = "clear_cache";
public static final String SEARCH = "search";
public static final String SWIPE_BACK = "swipe_back";
private static Settings sInstance;
private SharedPreferences mPrefs;
public static Settings getInstance() {
if (sInstance == null) { | // Path: app/src/main/java/com/mummyding/app/leisure/LeisureApplication.java
// public class LeisureApplication extends Application {
// public static Context AppContext = null;
// @Override
// public void onCreate() {
// super.onCreate();
// AppContext = getApplicationContext();
// Fresco.initialize(AppContext);
// }
// }
// Path: app/src/main/java/com/mummyding/app/leisure/support/Settings.java
import com.mummyding.app.leisure.LeisureApplication;
import android.content.Context;
import android.content.SharedPreferences;
/*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.support;
/**
* Created by mummyding on 15-12-6.
* GitHub: https://github.com/MummyDing/
* Blog: http://blog.csdn.net/mummyding
*/
public class Settings {
public static boolean needRecreate = false;
public static boolean isShakeMode = true;
public static boolean noPicMode = false;
public static boolean isNightMode = false;
public static boolean isAutoRefresh = false;
public static boolean isExitConfirm = true;
public static int searchID = 0;
public static int swipeID = 0;
public static final String XML_NAME = "settings";
public static final String SHAKE_TO_RETURN = "shake_to_return_new";
public static final String NO_PIC_MODE = "no_pic_mode";
public static final String NIGHT_MODE = "night_mode";
public static final String AUTO_REFRESH = "auto_refresh";
public static final String LANGUAGE = "language";
public static final String EXIT_CONFIRM = "exit_confirm";
public static final String CLEAR_CACHE = "clear_cache";
public static final String SEARCH = "search";
public static final String SWIPE_BACK = "swipe_back";
private static Settings sInstance;
private SharedPreferences mPrefs;
public static Settings getInstance() {
if (sInstance == null) { | sInstance = new Settings(LeisureApplication.AppContext); |
MummyDing/Leisure | app/src/main/java/com/mummyding/app/leisure/database/cache/BaseCollectionCache.java | // Path: app/src/main/java/com/mummyding/app/leisure/LeisureApplication.java
// public class LeisureApplication extends Application {
// public static Context AppContext = null;
// @Override
// public void onCreate() {
// super.onCreate();
// AppContext = getApplicationContext();
// Fresco.initialize(AppContext);
// }
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/database/DatabaseHelper.java
// public class DatabaseHelper extends SQLiteOpenHelper {
// private static final String DB_NAME= "Leisure";
// private static DatabaseHelper instance = null;
// private static final int DB_VERSION = 2;
// public static final String DELETE_TABLE_DATA = "delete from ";
// public static final String DROP_TABLE = "drop table if exists ";
// private DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
// super(context, name, factory, version);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL(DailyTable.CREATE_TABLE);
// db.execSQL(DailyTable.CREATE_COLLECTION_TABLE);
//
// db.execSQL(NewsTable.CREATE_TABLE);
// db.execSQL(NewsTable.CREATE_COLLECTION_TABLE);
//
// db.execSQL(ReadingTable.CREATE_TABLE);
// db.execSQL(ReadingTable.CREATE_COLLECTION_TABLE);
//
// db.execSQL(ScienceTable.CREATE_TABLE);
// db.execSQL(ScienceTable.CREATE_COLLECTION_TABLE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if(oldVersion == 1){
// db.execSQL(DROP_TABLE+DailyTable.NAME);
// db.execSQL(DROP_TABLE+DailyTable.COLLECTION_NAME);
// db.execSQL(DailyTable.CREATE_TABLE);
// db.execSQL(DailyTable.CREATE_COLLECTION_TABLE);
// }
// }
// public static synchronized DatabaseHelper instance(Context context){
// if(instance == null){
// instance = new DatabaseHelper(context,DB_NAME,null,DB_VERSION);
// }
// return instance;
// }
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/database/cache/ICache.java
// public interface ICache<T>{
// void addToCollection(T object);
// void execSQL(String sql);
// List<T> getList();
// boolean hasData();
// void load();
// void loadFromCache();
// void cache();
// }
| import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import com.mummyding.app.leisure.LeisureApplication;
import com.mummyding.app.leisure.database.DatabaseHelper;
import com.mummyding.app.leisure.database.cache.ICache;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.database.cache;
/**
* Created by mummyding on 15-12-3.
* Abstract Class. It provides a common framework for collection cache.<br>
* @author MummyDing
* @version Leisure 1.0
*/
public abstract class BaseCollectionCache<T> implements ICache<T> {
protected DatabaseHelper mHelper;
protected SQLiteDatabase db;
protected List<T> mList = new ArrayList<>();
protected Handler mHandler;
public BaseCollectionCache(Handler mHandler) {
this.mHandler = mHandler; | // Path: app/src/main/java/com/mummyding/app/leisure/LeisureApplication.java
// public class LeisureApplication extends Application {
// public static Context AppContext = null;
// @Override
// public void onCreate() {
// super.onCreate();
// AppContext = getApplicationContext();
// Fresco.initialize(AppContext);
// }
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/database/DatabaseHelper.java
// public class DatabaseHelper extends SQLiteOpenHelper {
// private static final String DB_NAME= "Leisure";
// private static DatabaseHelper instance = null;
// private static final int DB_VERSION = 2;
// public static final String DELETE_TABLE_DATA = "delete from ";
// public static final String DROP_TABLE = "drop table if exists ";
// private DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
// super(context, name, factory, version);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL(DailyTable.CREATE_TABLE);
// db.execSQL(DailyTable.CREATE_COLLECTION_TABLE);
//
// db.execSQL(NewsTable.CREATE_TABLE);
// db.execSQL(NewsTable.CREATE_COLLECTION_TABLE);
//
// db.execSQL(ReadingTable.CREATE_TABLE);
// db.execSQL(ReadingTable.CREATE_COLLECTION_TABLE);
//
// db.execSQL(ScienceTable.CREATE_TABLE);
// db.execSQL(ScienceTable.CREATE_COLLECTION_TABLE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if(oldVersion == 1){
// db.execSQL(DROP_TABLE+DailyTable.NAME);
// db.execSQL(DROP_TABLE+DailyTable.COLLECTION_NAME);
// db.execSQL(DailyTable.CREATE_TABLE);
// db.execSQL(DailyTable.CREATE_COLLECTION_TABLE);
// }
// }
// public static synchronized DatabaseHelper instance(Context context){
// if(instance == null){
// instance = new DatabaseHelper(context,DB_NAME,null,DB_VERSION);
// }
// return instance;
// }
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/database/cache/ICache.java
// public interface ICache<T>{
// void addToCollection(T object);
// void execSQL(String sql);
// List<T> getList();
// boolean hasData();
// void load();
// void loadFromCache();
// void cache();
// }
// Path: app/src/main/java/com/mummyding/app/leisure/database/cache/BaseCollectionCache.java
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import com.mummyding.app.leisure.LeisureApplication;
import com.mummyding.app.leisure.database.DatabaseHelper;
import com.mummyding.app.leisure.database.cache.ICache;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.database.cache;
/**
* Created by mummyding on 15-12-3.
* Abstract Class. It provides a common framework for collection cache.<br>
* @author MummyDing
* @version Leisure 1.0
*/
public abstract class BaseCollectionCache<T> implements ICache<T> {
protected DatabaseHelper mHelper;
protected SQLiteDatabase db;
protected List<T> mList = new ArrayList<>();
protected Handler mHandler;
public BaseCollectionCache(Handler mHandler) {
this.mHandler = mHandler; | mHelper = DatabaseHelper.instance(LeisureApplication.AppContext); |
MummyDing/Leisure | app/src/main/java/com/mummyding/app/leisure/ui/about/DemoVideoActivity.java | // Path: app/src/main/java/com/mummyding/app/leisure/support/CONSTANT.java
// public class CONSTANT {
// public static final String TYPE_UTF8_CHARSET = "charset=UTF-8";
//
// public static final String VERSION_URL ="https://raw.githubusercontent.com/MummyDing/Leisure/master/currentVersion.txt"; //"https://raw.githubusercontent.com/MummyDing/Leisure/master/currentVersion.txt";
//
// public static final String CURRENT_VERSION = "2.1";
//
// public static final String DEMO_VIDEO_URL = "http://v.qq.com/page/l/e/8/l0176duy7e8.html";
//
// public static final String MONTH [] =
// {"","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"};
//
// public static final String placeHolderUri="http://pic.baike.soso.com/p/20140126/20140126144232-793838389.jpg";
// public static final int ID_SUCCESS = 1;
// public static final int ID_FAILURE = 2;
// public static final int ID_LOAD_FROM_NET = 3;
// public static final int ID_UPDATE_UI = 4;
// public static final int ID_FROM_CACHE = 5;
//
// public static final int exitConfirmTime = 2000;
// public static final float shakeValue=25f;
//
// public static final int NIGHT_BRIGHTNESS = 40;
// public static final int DAY_BRIGHTNESS = 150;
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/ui/support/WebViewUrlActivity.java
// public class WebViewUrlActivity extends BaseWebViewActivity {
// @Override
// protected String getData() {
// return getIntent().getStringExtra(getString(R.string.id_url));
// }
// @Override
// protected void loadData() {
// webView.post(new Runnable() {
// @Override
// public void run() {
// webView.loadUrl(data);
// }
// });
// }
// }
| import com.mummyding.app.leisure.support.CONSTANT;
import com.mummyding.app.leisure.ui.support.WebViewUrlActivity; | /*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.ui.about;
/**
* Created by mummyding on 15-12-11.
* GitHub: https://github.com/MummyDing/
* Blog: http://blog.csdn.net/mummyding
*/
public class DemoVideoActivity extends WebViewUrlActivity{
@Override
protected void loadData() {
webView.post(new Runnable() {
@Override
public void run() { | // Path: app/src/main/java/com/mummyding/app/leisure/support/CONSTANT.java
// public class CONSTANT {
// public static final String TYPE_UTF8_CHARSET = "charset=UTF-8";
//
// public static final String VERSION_URL ="https://raw.githubusercontent.com/MummyDing/Leisure/master/currentVersion.txt"; //"https://raw.githubusercontent.com/MummyDing/Leisure/master/currentVersion.txt";
//
// public static final String CURRENT_VERSION = "2.1";
//
// public static final String DEMO_VIDEO_URL = "http://v.qq.com/page/l/e/8/l0176duy7e8.html";
//
// public static final String MONTH [] =
// {"","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"};
//
// public static final String placeHolderUri="http://pic.baike.soso.com/p/20140126/20140126144232-793838389.jpg";
// public static final int ID_SUCCESS = 1;
// public static final int ID_FAILURE = 2;
// public static final int ID_LOAD_FROM_NET = 3;
// public static final int ID_UPDATE_UI = 4;
// public static final int ID_FROM_CACHE = 5;
//
// public static final int exitConfirmTime = 2000;
// public static final float shakeValue=25f;
//
// public static final int NIGHT_BRIGHTNESS = 40;
// public static final int DAY_BRIGHTNESS = 150;
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/ui/support/WebViewUrlActivity.java
// public class WebViewUrlActivity extends BaseWebViewActivity {
// @Override
// protected String getData() {
// return getIntent().getStringExtra(getString(R.string.id_url));
// }
// @Override
// protected void loadData() {
// webView.post(new Runnable() {
// @Override
// public void run() {
// webView.loadUrl(data);
// }
// });
// }
// }
// Path: app/src/main/java/com/mummyding/app/leisure/ui/about/DemoVideoActivity.java
import com.mummyding.app.leisure.support.CONSTANT;
import com.mummyding.app.leisure.ui.support.WebViewUrlActivity;
/*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.ui.about;
/**
* Created by mummyding on 15-12-11.
* GitHub: https://github.com/MummyDing/
* Blog: http://blog.csdn.net/mummyding
*/
public class DemoVideoActivity extends WebViewUrlActivity{
@Override
protected void loadData() {
webView.post(new Runnable() {
@Override
public void run() { | webView.loadUrl(CONSTANT.DEMO_VIDEO_URL); |
MummyDing/Leisure | app/src/main/java/com/mummyding/app/leisure/support/HttpUtil.java | // Path: app/src/main/java/com/mummyding/app/leisure/LeisureApplication.java
// public class LeisureApplication extends Application {
// public static Context AppContext = null;
// @Override
// public void onCreate() {
// super.onCreate();
// AppContext = getApplicationContext();
// Fresco.initialize(AppContext);
// }
// }
| import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
import com.mummyding.app.leisure.LeisureApplication;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.util.concurrent.TimeUnit; |
package com.mummyding.app.leisure.support;
/**
* Created by mummyding on 15-11-22.<br>
* Utils for Post Data via network and get network state of cell phone.
* @author MummyDing
* @version Leisure 1.0
*/
public class HttpUtil {
private static final OkHttpClient mOkHttpClient = new OkHttpClient();
public static boolean isWIFI = true;
static{
mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
mOkHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
}
/**
* 该不会开启异步线程。
* @param request
* @return
* @throws IOException
*/
public static Response execute(Request request) throws IOException{
return mOkHttpClient.newCall(request).execute();
}
/**
* 开启异步线程访问网络
* @param request
* @param responseCallback
*/
public static void enqueue(Request request, Callback responseCallback){
mOkHttpClient.newCall(request).enqueue(responseCallback);
}
/**
* 开启异步线程访问网络, 且不在意返回结果(实现空callback)
* @param request
*/
public static void enqueue(Request request){
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Response arg0) throws IOException {
}
@Override
public void onFailure(Request arg0, IOException arg1) {
}
});
}
public static boolean readNetworkState() {
| // Path: app/src/main/java/com/mummyding/app/leisure/LeisureApplication.java
// public class LeisureApplication extends Application {
// public static Context AppContext = null;
// @Override
// public void onCreate() {
// super.onCreate();
// AppContext = getApplicationContext();
// Fresco.initialize(AppContext);
// }
// }
// Path: app/src/main/java/com/mummyding/app/leisure/support/HttpUtil.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
import com.mummyding.app.leisure.LeisureApplication;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
package com.mummyding.app.leisure.support;
/**
* Created by mummyding on 15-11-22.<br>
* Utils for Post Data via network and get network state of cell phone.
* @author MummyDing
* @version Leisure 1.0
*/
public class HttpUtil {
private static final OkHttpClient mOkHttpClient = new OkHttpClient();
public static boolean isWIFI = true;
static{
mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
mOkHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
}
/**
* 该不会开启异步线程。
* @param request
* @return
* @throws IOException
*/
public static Response execute(Request request) throws IOException{
return mOkHttpClient.newCall(request).execute();
}
/**
* 开启异步线程访问网络
* @param request
* @param responseCallback
*/
public static void enqueue(Request request, Callback responseCallback){
mOkHttpClient.newCall(request).enqueue(responseCallback);
}
/**
* 开启异步线程访问网络, 且不在意返回结果(实现空callback)
* @param request
*/
public static void enqueue(Request request){
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Response arg0) throws IOException {
}
@Override
public void onFailure(Request arg0, IOException arg1) {
}
});
}
public static boolean readNetworkState() {
| ConnectivityManager cm = (ConnectivityManager) LeisureApplication.AppContext.getSystemService(Context.CONNECTIVITY_SERVICE); |
MummyDing/Leisure | app/src/main/java/com/mummyding/app/leisure/support/ImageUtil.java | // Path: app/src/main/java/com/mummyding/app/leisure/LeisureApplication.java
// public class LeisureApplication extends Application {
// public static Context AppContext = null;
// @Override
// public void onCreate() {
// super.onCreate();
// AppContext = getApplicationContext();
// Fresco.initialize(AppContext);
// }
// }
| import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.graphics.Palette;
import com.facebook.drawee.view.SimpleDraweeView;
import com.mummyding.app.leisure.LeisureApplication; | package com.mummyding.app.leisure.support;
/**
* Created by MummyDing on 16-2-10.
* GitHub: https://github.com/MummyDing
* Blog: http://blog.csdn.net/mummyding
*/
public class ImageUtil {
public static int getImageColor(Bitmap bitmap){
Palette palette = Palette.from(bitmap).generate();
if(palette == null || palette.getDarkMutedSwatch() == null){
return Color.LTGRAY;
}
return palette.getDarkMutedSwatch().getRgb();
}
public static Bitmap getBitmap(SimpleDraweeView imageView){
Bitmap bitmap;
if (imageView.getDrawable() instanceof BitmapDrawable) {
bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
Drawable d = imageView.getDrawable();
bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
d.draw(canvas);
}
return bitmap;
}
public static Bitmap bitmapToCircle(Bitmap bitmap){
//处理Bitmap 转成正方形
Bitmap newBitmap = dealRawBitmap(bitmap);
//将newBitmap 转换成圆形 | // Path: app/src/main/java/com/mummyding/app/leisure/LeisureApplication.java
// public class LeisureApplication extends Application {
// public static Context AppContext = null;
// @Override
// public void onCreate() {
// super.onCreate();
// AppContext = getApplicationContext();
// Fresco.initialize(AppContext);
// }
// }
// Path: app/src/main/java/com/mummyding/app/leisure/support/ImageUtil.java
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.graphics.Palette;
import com.facebook.drawee.view.SimpleDraweeView;
import com.mummyding.app.leisure.LeisureApplication;
package com.mummyding.app.leisure.support;
/**
* Created by MummyDing on 16-2-10.
* GitHub: https://github.com/MummyDing
* Blog: http://blog.csdn.net/mummyding
*/
public class ImageUtil {
public static int getImageColor(Bitmap bitmap){
Palette palette = Palette.from(bitmap).generate();
if(palette == null || palette.getDarkMutedSwatch() == null){
return Color.LTGRAY;
}
return palette.getDarkMutedSwatch().getRgb();
}
public static Bitmap getBitmap(SimpleDraweeView imageView){
Bitmap bitmap;
if (imageView.getDrawable() instanceof BitmapDrawable) {
bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
Drawable d = imageView.getDrawable();
bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
d.draw(canvas);
}
return bitmap;
}
public static Bitmap bitmapToCircle(Bitmap bitmap){
//处理Bitmap 转成正方形
Bitmap newBitmap = dealRawBitmap(bitmap);
//将newBitmap 转换成圆形 | return toRoundCorner(newBitmap, DisplayUtil.dip2px(LeisureApplication.AppContext,50)); |
MummyDing/Leisure | app/src/main/java/com/mummyding/app/leisure/model/reading/BookBean.java | // Path: app/src/main/java/com/mummyding/app/leisure/LeisureApplication.java
// public class LeisureApplication extends Application {
// public static Context AppContext = null;
// @Override
// public void onCreate() {
// super.onCreate();
// AppContext = getApplicationContext();
// Fresco.initialize(AppContext);
// }
// }
| import com.mummyding.app.leisure.R;
import java.io.Serializable;
import android.content.Context;
import com.mummyding.app.leisure.LeisureApplication; | public void setSummary(String summary) {
this.summary = summary;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getInfo() {
if(Info == null) return toString();
return Info;
}
public void setInfo(String info) {
Info = info;
}
public int getIs_collected() {
return is_collected;
}
public void setIs_collected(int is_collected) {
this.is_collected = is_collected;
}
@Override
public String toString() { | // Path: app/src/main/java/com/mummyding/app/leisure/LeisureApplication.java
// public class LeisureApplication extends Application {
// public static Context AppContext = null;
// @Override
// public void onCreate() {
// super.onCreate();
// AppContext = getApplicationContext();
// Fresco.initialize(AppContext);
// }
// }
// Path: app/src/main/java/com/mummyding/app/leisure/model/reading/BookBean.java
import com.mummyding.app.leisure.R;
import java.io.Serializable;
import android.content.Context;
import com.mummyding.app.leisure.LeisureApplication;
public void setSummary(String summary) {
this.summary = summary;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getInfo() {
if(Info == null) return toString();
return Info;
}
public void setInfo(String info) {
Info = info;
}
public int getIs_collected() {
return is_collected;
}
public void setIs_collected(int is_collected) {
this.is_collected = is_collected;
}
@Override
public String toString() { | Context mContext = LeisureApplication.AppContext; |
MummyDing/Leisure | app/src/main/java/com/mummyding/app/leisure/ui/support/SwipeBackActivity.java | // Path: app/src/main/java/com/mummyding/app/leisure/support/Settings.java
// public class Settings {
//
// public static boolean needRecreate = false;
// public static boolean isShakeMode = true;
// public static boolean noPicMode = false;
// public static boolean isNightMode = false;
// public static boolean isAutoRefresh = false;
// public static boolean isExitConfirm = true;
// public static int searchID = 0;
// public static int swipeID = 0;
//
// public static final String XML_NAME = "settings";
//
// public static final String SHAKE_TO_RETURN = "shake_to_return_new";
//
// public static final String NO_PIC_MODE = "no_pic_mode";
//
// public static final String NIGHT_MODE = "night_mode";
//
// public static final String AUTO_REFRESH = "auto_refresh";
//
// public static final String LANGUAGE = "language";
//
// public static final String EXIT_CONFIRM = "exit_confirm";
//
// public static final String CLEAR_CACHE = "clear_cache";
//
// public static final String SEARCH = "search";
//
// public static final String SWIPE_BACK = "swipe_back";
// private static Settings sInstance;
//
// private SharedPreferences mPrefs;
//
// public static Settings getInstance() {
// if (sInstance == null) {
// sInstance = new Settings(LeisureApplication.AppContext);
// }
// return sInstance;
// }
//
// private Settings(Context context) {
// mPrefs = context.getSharedPreferences(XML_NAME, Context.MODE_PRIVATE);
// }
//
// public Settings putBoolean(String key, boolean value) {
// mPrefs.edit().putBoolean(key, value).commit();
// return this;
// }
//
// public boolean getBoolean(String key, boolean def) {
// return mPrefs.getBoolean(key, def);
// }
//
// public Settings putInt(String key, int value) {
// mPrefs.edit().putInt(key, value).commit();
// return this;
// }
//
// public int getInt(String key, int defValue) {
// return mPrefs.getInt(key, defValue);
// }
//
// public Settings putString(String key, String value) {
// mPrefs.edit().putString(key, value).commit();
// return this;
// }
//
// public String getString(String key, String defValue) {
// return mPrefs.getString(key, defValue);
// }
//
// }
| import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import com.mummyding.app.leisure.R;
import com.mummyding.app.leisure.support.Settings; | package com.mummyding.app.leisure.ui.support;
/**
* 滑动关闭页面基类,使用时继承此类并使用BlankTheme主题即可
*/
/**
* this file was written by @NashLegend {https://github.com/NashLegend} -- MummyDing
*/
public class SwipeBackActivity extends AppCompatActivity {
private SwipeLayout swipeLayout;
/**
* 是否可以滑动关闭页面
*/
protected boolean swipeEnabled = true;
/**
* 是否可以在页面任意位置右滑关闭页面,如果是false则从左边滑才可以关闭。
*/
protected boolean swipeAnyWhere = false;
public SwipeBackActivity() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
swipeLayout = new SwipeLayout(this);
| // Path: app/src/main/java/com/mummyding/app/leisure/support/Settings.java
// public class Settings {
//
// public static boolean needRecreate = false;
// public static boolean isShakeMode = true;
// public static boolean noPicMode = false;
// public static boolean isNightMode = false;
// public static boolean isAutoRefresh = false;
// public static boolean isExitConfirm = true;
// public static int searchID = 0;
// public static int swipeID = 0;
//
// public static final String XML_NAME = "settings";
//
// public static final String SHAKE_TO_RETURN = "shake_to_return_new";
//
// public static final String NO_PIC_MODE = "no_pic_mode";
//
// public static final String NIGHT_MODE = "night_mode";
//
// public static final String AUTO_REFRESH = "auto_refresh";
//
// public static final String LANGUAGE = "language";
//
// public static final String EXIT_CONFIRM = "exit_confirm";
//
// public static final String CLEAR_CACHE = "clear_cache";
//
// public static final String SEARCH = "search";
//
// public static final String SWIPE_BACK = "swipe_back";
// private static Settings sInstance;
//
// private SharedPreferences mPrefs;
//
// public static Settings getInstance() {
// if (sInstance == null) {
// sInstance = new Settings(LeisureApplication.AppContext);
// }
// return sInstance;
// }
//
// private Settings(Context context) {
// mPrefs = context.getSharedPreferences(XML_NAME, Context.MODE_PRIVATE);
// }
//
// public Settings putBoolean(String key, boolean value) {
// mPrefs.edit().putBoolean(key, value).commit();
// return this;
// }
//
// public boolean getBoolean(String key, boolean def) {
// return mPrefs.getBoolean(key, def);
// }
//
// public Settings putInt(String key, int value) {
// mPrefs.edit().putInt(key, value).commit();
// return this;
// }
//
// public int getInt(String key, int defValue) {
// return mPrefs.getInt(key, defValue);
// }
//
// public Settings putString(String key, String value) {
// mPrefs.edit().putString(key, value).commit();
// return this;
// }
//
// public String getString(String key, String defValue) {
// return mPrefs.getString(key, defValue);
// }
//
// }
// Path: app/src/main/java/com/mummyding/app/leisure/ui/support/SwipeBackActivity.java
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import com.mummyding.app.leisure.R;
import com.mummyding.app.leisure.support.Settings;
package com.mummyding.app.leisure.ui.support;
/**
* 滑动关闭页面基类,使用时继承此类并使用BlankTheme主题即可
*/
/**
* this file was written by @NashLegend {https://github.com/NashLegend} -- MummyDing
*/
public class SwipeBackActivity extends AppCompatActivity {
private SwipeLayout swipeLayout;
/**
* 是否可以滑动关闭页面
*/
protected boolean swipeEnabled = true;
/**
* 是否可以在页面任意位置右滑关闭页面,如果是false则从左边滑才可以关闭。
*/
protected boolean swipeAnyWhere = false;
public SwipeBackActivity() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
swipeLayout = new SwipeLayout(this);
| Settings.swipeID = Settings.getInstance().getInt(Settings.SWIPE_BACK,0); |
MummyDing/Leisure | app/src/main/java/com/mummyding/app/leisure/database/cache/BaseCache.java | // Path: app/src/main/java/com/mummyding/app/leisure/LeisureApplication.java
// public class LeisureApplication extends Application {
// public static Context AppContext = null;
// @Override
// public void onCreate() {
// super.onCreate();
// AppContext = getApplicationContext();
// Fresco.initialize(AppContext);
// }
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/database/DatabaseHelper.java
// public class DatabaseHelper extends SQLiteOpenHelper {
// private static final String DB_NAME= "Leisure";
// private static DatabaseHelper instance = null;
// private static final int DB_VERSION = 2;
// public static final String DELETE_TABLE_DATA = "delete from ";
// public static final String DROP_TABLE = "drop table if exists ";
// private DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
// super(context, name, factory, version);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL(DailyTable.CREATE_TABLE);
// db.execSQL(DailyTable.CREATE_COLLECTION_TABLE);
//
// db.execSQL(NewsTable.CREATE_TABLE);
// db.execSQL(NewsTable.CREATE_COLLECTION_TABLE);
//
// db.execSQL(ReadingTable.CREATE_TABLE);
// db.execSQL(ReadingTable.CREATE_COLLECTION_TABLE);
//
// db.execSQL(ScienceTable.CREATE_TABLE);
// db.execSQL(ScienceTable.CREATE_COLLECTION_TABLE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if(oldVersion == 1){
// db.execSQL(DROP_TABLE+DailyTable.NAME);
// db.execSQL(DROP_TABLE+DailyTable.COLLECTION_NAME);
// db.execSQL(DailyTable.CREATE_TABLE);
// db.execSQL(DailyTable.CREATE_COLLECTION_TABLE);
// }
// }
// public static synchronized DatabaseHelper instance(Context context){
// if(instance == null){
// instance = new DatabaseHelper(context,DB_NAME,null,DB_VERSION);
// }
// return instance;
// }
// }
| import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import com.mummyding.app.leisure.LeisureApplication;
import com.mummyding.app.leisure.database.DatabaseHelper;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.database.cache;
/**
* Created by mummyding on 15-11-26.
* Abstract Class. if provides a common framework for data cache(except Collection Cache)<br>
* And it supports Generic, so it is flexible.<br>
* @author MummyDing
* @version Leisure 1.0
*/
public abstract class BaseCache<T> implements ICache<T> {
protected Context mContext = LeisureApplication.AppContext; | // Path: app/src/main/java/com/mummyding/app/leisure/LeisureApplication.java
// public class LeisureApplication extends Application {
// public static Context AppContext = null;
// @Override
// public void onCreate() {
// super.onCreate();
// AppContext = getApplicationContext();
// Fresco.initialize(AppContext);
// }
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/database/DatabaseHelper.java
// public class DatabaseHelper extends SQLiteOpenHelper {
// private static final String DB_NAME= "Leisure";
// private static DatabaseHelper instance = null;
// private static final int DB_VERSION = 2;
// public static final String DELETE_TABLE_DATA = "delete from ";
// public static final String DROP_TABLE = "drop table if exists ";
// private DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
// super(context, name, factory, version);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL(DailyTable.CREATE_TABLE);
// db.execSQL(DailyTable.CREATE_COLLECTION_TABLE);
//
// db.execSQL(NewsTable.CREATE_TABLE);
// db.execSQL(NewsTable.CREATE_COLLECTION_TABLE);
//
// db.execSQL(ReadingTable.CREATE_TABLE);
// db.execSQL(ReadingTable.CREATE_COLLECTION_TABLE);
//
// db.execSQL(ScienceTable.CREATE_TABLE);
// db.execSQL(ScienceTable.CREATE_COLLECTION_TABLE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if(oldVersion == 1){
// db.execSQL(DROP_TABLE+DailyTable.NAME);
// db.execSQL(DROP_TABLE+DailyTable.COLLECTION_NAME);
// db.execSQL(DailyTable.CREATE_TABLE);
// db.execSQL(DailyTable.CREATE_COLLECTION_TABLE);
// }
// }
// public static synchronized DatabaseHelper instance(Context context){
// if(instance == null){
// instance = new DatabaseHelper(context,DB_NAME,null,DB_VERSION);
// }
// return instance;
// }
// }
// Path: app/src/main/java/com/mummyding/app/leisure/database/cache/BaseCache.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import com.mummyding.app.leisure.LeisureApplication;
import com.mummyding.app.leisure.database.DatabaseHelper;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.database.cache;
/**
* Created by mummyding on 15-11-26.
* Abstract Class. if provides a common framework for data cache(except Collection Cache)<br>
* And it supports Generic, so it is flexible.<br>
* @author MummyDing
* @version Leisure 1.0
*/
public abstract class BaseCache<T> implements ICache<T> {
protected Context mContext = LeisureApplication.AppContext; | protected DatabaseHelper mHelper; |
MummyDing/Leisure | app/src/main/java/com/mummyding/app/leisure/support/adapter/BaseListAdapter.java | // Path: app/src/main/java/com/mummyding/app/leisure/database/cache/BaseCollectionCache.java
// public abstract class BaseCollectionCache<T> implements ICache<T> {
//
// protected DatabaseHelper mHelper;
// protected SQLiteDatabase db;
//
//
// protected List<T> mList = new ArrayList<>();
//
// protected Handler mHandler;
//
// public BaseCollectionCache(Handler mHandler) {
// this.mHandler = mHandler;
// mHelper = DatabaseHelper.instance(LeisureApplication.AppContext);
// }
//
// @Override
// public void addToCollection(T object) {
//
// }
//
// @Override
// public void execSQL(String sql) {
// db = mHelper.getWritableDatabase();
// db.execSQL(sql);
// }
//
// @Override
// public List<T> getList() {
// return mList;
// }
//
// @Override
// public boolean hasData() {
// return !mList.isEmpty();
// }
//
// @Override
// public void load() {
//
// }
//
//
// @Override
// public void cache() {
//
// }
//
// protected Cursor query(String sql){
// return mHelper.getReadableDatabase().rawQuery(sql,null);
// }
//
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/database/cache/ICache.java
// public interface ICache<T>{
// void addToCollection(T object);
// void execSQL(String sql);
// List<T> getList();
// boolean hasData();
// void load();
// void loadFromCache();
// void cache();
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/support/HttpUtil.java
// public class HttpUtil {
// private static final OkHttpClient mOkHttpClient = new OkHttpClient();
// public static boolean isWIFI = true;
// static{
// mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
// mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
// mOkHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
// }
// /**
// * 该不会开启异步线程。
// * @param request
// * @return
// * @throws IOException
// */
// public static Response execute(Request request) throws IOException{
// return mOkHttpClient.newCall(request).execute();
// }
// /**
// * 开启异步线程访问网络
// * @param request
// * @param responseCallback
// */
// public static void enqueue(Request request, Callback responseCallback){
// mOkHttpClient.newCall(request).enqueue(responseCallback);
// }
// /**
// * 开启异步线程访问网络, 且不在意返回结果(实现空callback)
// * @param request
// */
// public static void enqueue(Request request){
// mOkHttpClient.newCall(request).enqueue(new Callback() {
//
// @Override
// public void onResponse(Response arg0) throws IOException {
//
// }
//
// @Override
// public void onFailure(Request arg0, IOException arg1) {
//
// }
// });
// }
//
// public static boolean readNetworkState() {
//
// ConnectivityManager cm = (ConnectivityManager) LeisureApplication.AppContext.getSystemService(Context.CONNECTIVITY_SERVICE);
//
// if (cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
// isWIFI = (cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI);
// return true;
// } else {
//
// return false;
// }
// }
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import com.mummyding.app.leisure.database.cache.BaseCollectionCache;
import com.mummyding.app.leisure.database.cache.ICache;
import com.mummyding.app.leisure.support.HttpUtil;
import java.util.List; | /*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.support.adapter;
/**
* Created by mummyding on 15-12-3.<br>
* Abstract. It provides a common framework for RecyclerView adapter.<br>
* All RecyclerView adapter inherits from this method.
* @author MummyDing
* @version Leisure 1.0
*/
public abstract class BaseListAdapter<M,VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH>{
protected List<M> mItems;
protected Context mContext; | // Path: app/src/main/java/com/mummyding/app/leisure/database/cache/BaseCollectionCache.java
// public abstract class BaseCollectionCache<T> implements ICache<T> {
//
// protected DatabaseHelper mHelper;
// protected SQLiteDatabase db;
//
//
// protected List<T> mList = new ArrayList<>();
//
// protected Handler mHandler;
//
// public BaseCollectionCache(Handler mHandler) {
// this.mHandler = mHandler;
// mHelper = DatabaseHelper.instance(LeisureApplication.AppContext);
// }
//
// @Override
// public void addToCollection(T object) {
//
// }
//
// @Override
// public void execSQL(String sql) {
// db = mHelper.getWritableDatabase();
// db.execSQL(sql);
// }
//
// @Override
// public List<T> getList() {
// return mList;
// }
//
// @Override
// public boolean hasData() {
// return !mList.isEmpty();
// }
//
// @Override
// public void load() {
//
// }
//
//
// @Override
// public void cache() {
//
// }
//
// protected Cursor query(String sql){
// return mHelper.getReadableDatabase().rawQuery(sql,null);
// }
//
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/database/cache/ICache.java
// public interface ICache<T>{
// void addToCollection(T object);
// void execSQL(String sql);
// List<T> getList();
// boolean hasData();
// void load();
// void loadFromCache();
// void cache();
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/support/HttpUtil.java
// public class HttpUtil {
// private static final OkHttpClient mOkHttpClient = new OkHttpClient();
// public static boolean isWIFI = true;
// static{
// mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
// mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
// mOkHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
// }
// /**
// * 该不会开启异步线程。
// * @param request
// * @return
// * @throws IOException
// */
// public static Response execute(Request request) throws IOException{
// return mOkHttpClient.newCall(request).execute();
// }
// /**
// * 开启异步线程访问网络
// * @param request
// * @param responseCallback
// */
// public static void enqueue(Request request, Callback responseCallback){
// mOkHttpClient.newCall(request).enqueue(responseCallback);
// }
// /**
// * 开启异步线程访问网络, 且不在意返回结果(实现空callback)
// * @param request
// */
// public static void enqueue(Request request){
// mOkHttpClient.newCall(request).enqueue(new Callback() {
//
// @Override
// public void onResponse(Response arg0) throws IOException {
//
// }
//
// @Override
// public void onFailure(Request arg0, IOException arg1) {
//
// }
// });
// }
//
// public static boolean readNetworkState() {
//
// ConnectivityManager cm = (ConnectivityManager) LeisureApplication.AppContext.getSystemService(Context.CONNECTIVITY_SERVICE);
//
// if (cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
// isWIFI = (cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI);
// return true;
// } else {
//
// return false;
// }
// }
// }
// Path: app/src/main/java/com/mummyding/app/leisure/support/adapter/BaseListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import com.mummyding.app.leisure.database.cache.BaseCollectionCache;
import com.mummyding.app.leisure.database.cache.ICache;
import com.mummyding.app.leisure.support.HttpUtil;
import java.util.List;
/*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.support.adapter;
/**
* Created by mummyding on 15-12-3.<br>
* Abstract. It provides a common framework for RecyclerView adapter.<br>
* All RecyclerView adapter inherits from this method.
* @author MummyDing
* @version Leisure 1.0
*/
public abstract class BaseListAdapter<M,VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH>{
protected List<M> mItems;
protected Context mContext; | protected ICache<M> mCache; |
MummyDing/Leisure | app/src/main/java/com/mummyding/app/leisure/support/adapter/BaseListAdapter.java | // Path: app/src/main/java/com/mummyding/app/leisure/database/cache/BaseCollectionCache.java
// public abstract class BaseCollectionCache<T> implements ICache<T> {
//
// protected DatabaseHelper mHelper;
// protected SQLiteDatabase db;
//
//
// protected List<T> mList = new ArrayList<>();
//
// protected Handler mHandler;
//
// public BaseCollectionCache(Handler mHandler) {
// this.mHandler = mHandler;
// mHelper = DatabaseHelper.instance(LeisureApplication.AppContext);
// }
//
// @Override
// public void addToCollection(T object) {
//
// }
//
// @Override
// public void execSQL(String sql) {
// db = mHelper.getWritableDatabase();
// db.execSQL(sql);
// }
//
// @Override
// public List<T> getList() {
// return mList;
// }
//
// @Override
// public boolean hasData() {
// return !mList.isEmpty();
// }
//
// @Override
// public void load() {
//
// }
//
//
// @Override
// public void cache() {
//
// }
//
// protected Cursor query(String sql){
// return mHelper.getReadableDatabase().rawQuery(sql,null);
// }
//
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/database/cache/ICache.java
// public interface ICache<T>{
// void addToCollection(T object);
// void execSQL(String sql);
// List<T> getList();
// boolean hasData();
// void load();
// void loadFromCache();
// void cache();
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/support/HttpUtil.java
// public class HttpUtil {
// private static final OkHttpClient mOkHttpClient = new OkHttpClient();
// public static boolean isWIFI = true;
// static{
// mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
// mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
// mOkHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
// }
// /**
// * 该不会开启异步线程。
// * @param request
// * @return
// * @throws IOException
// */
// public static Response execute(Request request) throws IOException{
// return mOkHttpClient.newCall(request).execute();
// }
// /**
// * 开启异步线程访问网络
// * @param request
// * @param responseCallback
// */
// public static void enqueue(Request request, Callback responseCallback){
// mOkHttpClient.newCall(request).enqueue(responseCallback);
// }
// /**
// * 开启异步线程访问网络, 且不在意返回结果(实现空callback)
// * @param request
// */
// public static void enqueue(Request request){
// mOkHttpClient.newCall(request).enqueue(new Callback() {
//
// @Override
// public void onResponse(Response arg0) throws IOException {
//
// }
//
// @Override
// public void onFailure(Request arg0, IOException arg1) {
//
// }
// });
// }
//
// public static boolean readNetworkState() {
//
// ConnectivityManager cm = (ConnectivityManager) LeisureApplication.AppContext.getSystemService(Context.CONNECTIVITY_SERVICE);
//
// if (cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
// isWIFI = (cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI);
// return true;
// } else {
//
// return false;
// }
// }
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import com.mummyding.app.leisure.database.cache.BaseCollectionCache;
import com.mummyding.app.leisure.database.cache.ICache;
import com.mummyding.app.leisure.support.HttpUtil;
import java.util.List; | /*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.support.adapter;
/**
* Created by mummyding on 15-12-3.<br>
* Abstract. It provides a common framework for RecyclerView adapter.<br>
* All RecyclerView adapter inherits from this method.
* @author MummyDing
* @version Leisure 1.0
*/
public abstract class BaseListAdapter<M,VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH>{
protected List<M> mItems;
protected Context mContext;
protected ICache<M> mCache;
protected boolean isCollection = false;
public BaseListAdapter(Context context, ICache<M> cache) {
mContext = context;
mCache = cache;
mItems = cache.getList();
| // Path: app/src/main/java/com/mummyding/app/leisure/database/cache/BaseCollectionCache.java
// public abstract class BaseCollectionCache<T> implements ICache<T> {
//
// protected DatabaseHelper mHelper;
// protected SQLiteDatabase db;
//
//
// protected List<T> mList = new ArrayList<>();
//
// protected Handler mHandler;
//
// public BaseCollectionCache(Handler mHandler) {
// this.mHandler = mHandler;
// mHelper = DatabaseHelper.instance(LeisureApplication.AppContext);
// }
//
// @Override
// public void addToCollection(T object) {
//
// }
//
// @Override
// public void execSQL(String sql) {
// db = mHelper.getWritableDatabase();
// db.execSQL(sql);
// }
//
// @Override
// public List<T> getList() {
// return mList;
// }
//
// @Override
// public boolean hasData() {
// return !mList.isEmpty();
// }
//
// @Override
// public void load() {
//
// }
//
//
// @Override
// public void cache() {
//
// }
//
// protected Cursor query(String sql){
// return mHelper.getReadableDatabase().rawQuery(sql,null);
// }
//
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/database/cache/ICache.java
// public interface ICache<T>{
// void addToCollection(T object);
// void execSQL(String sql);
// List<T> getList();
// boolean hasData();
// void load();
// void loadFromCache();
// void cache();
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/support/HttpUtil.java
// public class HttpUtil {
// private static final OkHttpClient mOkHttpClient = new OkHttpClient();
// public static boolean isWIFI = true;
// static{
// mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
// mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
// mOkHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
// }
// /**
// * 该不会开启异步线程。
// * @param request
// * @return
// * @throws IOException
// */
// public static Response execute(Request request) throws IOException{
// return mOkHttpClient.newCall(request).execute();
// }
// /**
// * 开启异步线程访问网络
// * @param request
// * @param responseCallback
// */
// public static void enqueue(Request request, Callback responseCallback){
// mOkHttpClient.newCall(request).enqueue(responseCallback);
// }
// /**
// * 开启异步线程访问网络, 且不在意返回结果(实现空callback)
// * @param request
// */
// public static void enqueue(Request request){
// mOkHttpClient.newCall(request).enqueue(new Callback() {
//
// @Override
// public void onResponse(Response arg0) throws IOException {
//
// }
//
// @Override
// public void onFailure(Request arg0, IOException arg1) {
//
// }
// });
// }
//
// public static boolean readNetworkState() {
//
// ConnectivityManager cm = (ConnectivityManager) LeisureApplication.AppContext.getSystemService(Context.CONNECTIVITY_SERVICE);
//
// if (cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
// isWIFI = (cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI);
// return true;
// } else {
//
// return false;
// }
// }
// }
// Path: app/src/main/java/com/mummyding/app/leisure/support/adapter/BaseListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import com.mummyding.app.leisure.database.cache.BaseCollectionCache;
import com.mummyding.app.leisure.database.cache.ICache;
import com.mummyding.app.leisure.support.HttpUtil;
import java.util.List;
/*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.support.adapter;
/**
* Created by mummyding on 15-12-3.<br>
* Abstract. It provides a common framework for RecyclerView adapter.<br>
* All RecyclerView adapter inherits from this method.
* @author MummyDing
* @version Leisure 1.0
*/
public abstract class BaseListAdapter<M,VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH>{
protected List<M> mItems;
protected Context mContext;
protected ICache<M> mCache;
protected boolean isCollection = false;
public BaseListAdapter(Context context, ICache<M> cache) {
mContext = context;
mCache = cache;
mItems = cache.getList();
| if(cache instanceof BaseCollectionCache){ |
MummyDing/Leisure | app/src/main/java/com/mummyding/app/leisure/support/adapter/BaseListAdapter.java | // Path: app/src/main/java/com/mummyding/app/leisure/database/cache/BaseCollectionCache.java
// public abstract class BaseCollectionCache<T> implements ICache<T> {
//
// protected DatabaseHelper mHelper;
// protected SQLiteDatabase db;
//
//
// protected List<T> mList = new ArrayList<>();
//
// protected Handler mHandler;
//
// public BaseCollectionCache(Handler mHandler) {
// this.mHandler = mHandler;
// mHelper = DatabaseHelper.instance(LeisureApplication.AppContext);
// }
//
// @Override
// public void addToCollection(T object) {
//
// }
//
// @Override
// public void execSQL(String sql) {
// db = mHelper.getWritableDatabase();
// db.execSQL(sql);
// }
//
// @Override
// public List<T> getList() {
// return mList;
// }
//
// @Override
// public boolean hasData() {
// return !mList.isEmpty();
// }
//
// @Override
// public void load() {
//
// }
//
//
// @Override
// public void cache() {
//
// }
//
// protected Cursor query(String sql){
// return mHelper.getReadableDatabase().rawQuery(sql,null);
// }
//
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/database/cache/ICache.java
// public interface ICache<T>{
// void addToCollection(T object);
// void execSQL(String sql);
// List<T> getList();
// boolean hasData();
// void load();
// void loadFromCache();
// void cache();
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/support/HttpUtil.java
// public class HttpUtil {
// private static final OkHttpClient mOkHttpClient = new OkHttpClient();
// public static boolean isWIFI = true;
// static{
// mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
// mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
// mOkHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
// }
// /**
// * 该不会开启异步线程。
// * @param request
// * @return
// * @throws IOException
// */
// public static Response execute(Request request) throws IOException{
// return mOkHttpClient.newCall(request).execute();
// }
// /**
// * 开启异步线程访问网络
// * @param request
// * @param responseCallback
// */
// public static void enqueue(Request request, Callback responseCallback){
// mOkHttpClient.newCall(request).enqueue(responseCallback);
// }
// /**
// * 开启异步线程访问网络, 且不在意返回结果(实现空callback)
// * @param request
// */
// public static void enqueue(Request request){
// mOkHttpClient.newCall(request).enqueue(new Callback() {
//
// @Override
// public void onResponse(Response arg0) throws IOException {
//
// }
//
// @Override
// public void onFailure(Request arg0, IOException arg1) {
//
// }
// });
// }
//
// public static boolean readNetworkState() {
//
// ConnectivityManager cm = (ConnectivityManager) LeisureApplication.AppContext.getSystemService(Context.CONNECTIVITY_SERVICE);
//
// if (cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
// isWIFI = (cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI);
// return true;
// } else {
//
// return false;
// }
// }
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import com.mummyding.app.leisure.database.cache.BaseCollectionCache;
import com.mummyding.app.leisure.database.cache.ICache;
import com.mummyding.app.leisure.support.HttpUtil;
import java.util.List; | /*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.support.adapter;
/**
* Created by mummyding on 15-12-3.<br>
* Abstract. It provides a common framework for RecyclerView adapter.<br>
* All RecyclerView adapter inherits from this method.
* @author MummyDing
* @version Leisure 1.0
*/
public abstract class BaseListAdapter<M,VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH>{
protected List<M> mItems;
protected Context mContext;
protected ICache<M> mCache;
protected boolean isCollection = false;
public BaseListAdapter(Context context, ICache<M> cache) {
mContext = context;
mCache = cache;
mItems = cache.getList();
if(cache instanceof BaseCollectionCache){
isCollection = true;
}
| // Path: app/src/main/java/com/mummyding/app/leisure/database/cache/BaseCollectionCache.java
// public abstract class BaseCollectionCache<T> implements ICache<T> {
//
// protected DatabaseHelper mHelper;
// protected SQLiteDatabase db;
//
//
// protected List<T> mList = new ArrayList<>();
//
// protected Handler mHandler;
//
// public BaseCollectionCache(Handler mHandler) {
// this.mHandler = mHandler;
// mHelper = DatabaseHelper.instance(LeisureApplication.AppContext);
// }
//
// @Override
// public void addToCollection(T object) {
//
// }
//
// @Override
// public void execSQL(String sql) {
// db = mHelper.getWritableDatabase();
// db.execSQL(sql);
// }
//
// @Override
// public List<T> getList() {
// return mList;
// }
//
// @Override
// public boolean hasData() {
// return !mList.isEmpty();
// }
//
// @Override
// public void load() {
//
// }
//
//
// @Override
// public void cache() {
//
// }
//
// protected Cursor query(String sql){
// return mHelper.getReadableDatabase().rawQuery(sql,null);
// }
//
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/database/cache/ICache.java
// public interface ICache<T>{
// void addToCollection(T object);
// void execSQL(String sql);
// List<T> getList();
// boolean hasData();
// void load();
// void loadFromCache();
// void cache();
// }
//
// Path: app/src/main/java/com/mummyding/app/leisure/support/HttpUtil.java
// public class HttpUtil {
// private static final OkHttpClient mOkHttpClient = new OkHttpClient();
// public static boolean isWIFI = true;
// static{
// mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
// mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
// mOkHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
// }
// /**
// * 该不会开启异步线程。
// * @param request
// * @return
// * @throws IOException
// */
// public static Response execute(Request request) throws IOException{
// return mOkHttpClient.newCall(request).execute();
// }
// /**
// * 开启异步线程访问网络
// * @param request
// * @param responseCallback
// */
// public static void enqueue(Request request, Callback responseCallback){
// mOkHttpClient.newCall(request).enqueue(responseCallback);
// }
// /**
// * 开启异步线程访问网络, 且不在意返回结果(实现空callback)
// * @param request
// */
// public static void enqueue(Request request){
// mOkHttpClient.newCall(request).enqueue(new Callback() {
//
// @Override
// public void onResponse(Response arg0) throws IOException {
//
// }
//
// @Override
// public void onFailure(Request arg0, IOException arg1) {
//
// }
// });
// }
//
// public static boolean readNetworkState() {
//
// ConnectivityManager cm = (ConnectivityManager) LeisureApplication.AppContext.getSystemService(Context.CONNECTIVITY_SERVICE);
//
// if (cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
// isWIFI = (cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI);
// return true;
// } else {
//
// return false;
// }
// }
// }
// Path: app/src/main/java/com/mummyding/app/leisure/support/adapter/BaseListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import com.mummyding.app.leisure.database.cache.BaseCollectionCache;
import com.mummyding.app.leisure.database.cache.ICache;
import com.mummyding.app.leisure.support.HttpUtil;
import java.util.List;
/*
* Copyright (C) 2015 MummyDing
*
* This file is part of Leisure( <https://github.com/MummyDing/Leisure> )
*
* Leisure is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* `
* Leisure is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Leisure. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mummyding.app.leisure.support.adapter;
/**
* Created by mummyding on 15-12-3.<br>
* Abstract. It provides a common framework for RecyclerView adapter.<br>
* All RecyclerView adapter inherits from this method.
* @author MummyDing
* @version Leisure 1.0
*/
public abstract class BaseListAdapter<M,VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH>{
protected List<M> mItems;
protected Context mContext;
protected ICache<M> mCache;
protected boolean isCollection = false;
public BaseListAdapter(Context context, ICache<M> cache) {
mContext = context;
mCache = cache;
mItems = cache.getList();
if(cache instanceof BaseCollectionCache){
isCollection = true;
}
| HttpUtil.readNetworkState(); |
sct/HexxitGear | src/sct/hexxitgear/ClientProxy.java | // Path: src/sct/hexxitgear/control/HGKeyHandler.java
// @SideOnly(Side.CLIENT)
// public class HGKeyHandler extends KeyBindingRegistry.KeyHandler {
//
// public static KeyBinding activateHexxitArmor = new KeyBinding("Activate Hexxit Gear Armor", Keyboard.KEY_X);
// public static KeyBinding[] keybindArray = new KeyBinding[]{activateHexxitArmor};
// public static boolean[] repeats = new boolean[keybindArray.length];
//
// public HGKeyHandler() {
// super(keybindArray, repeats);
// }
//
// @Override
// public void keyDown(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd, boolean isRepeat) {
// EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer;
//
// if (player == null || tickEnd)
// return;
//
// if (kb.equals(activateHexxitArmor)) {
// if (ArmorSet.getPlayerArmorSet(player.username) != null) {
// Object[] data = new Object[] { player.username };
// PacketDispatcher.sendPacketToServer(PacketWrapper.createPacket(HexxitGear.modNetworkChannel, Packets.armorAbility, data));
// //ArmorSet.readArmorPacket(player.username);
// }
// }
// }
//
// @Override
// public void keyUp(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd) {
//
// }
//
// @Override
// public EnumSet<TickType> ticks() {
// return EnumSet.of(TickType.CLIENT);
// }
//
// @Override
// public String getLabel() {
// return "hexxitGearKeybinds";
// }
// }
//
// Path: src/sct/hexxitgear/tick/PlayerTickHandler.java
// public class PlayerTickHandler implements ITickHandler {
//
// private int tickCounter = 0;
//
// @Override
// public void tickStart(EnumSet<TickType> type, Object... tickData) {
// if (type.equals(EnumSet.of(TickType.PLAYER))) {
// for (Object tick : tickData) {
// if (tick instanceof EntityPlayer) {
// EntityPlayer player = (EntityPlayer) tick;
// if (tickCounter > 20) {
// ArmorSet.getMatchingSet(player);
// tickCounter = 0;
// }
// tickCounter++;
//
// if (ArmorSet.getPlayerArmorSet(player.username) != null) {
// ArmorSet armorSet = ArmorSet.getPlayerArmorSet(player.username);
// armorSet.applyBuffs(player);
// }
//
// // We run this outside of the check for an armorset just incase a player takes off armor mid ability
// AbilityHandler bh = AbilityHandler.getPlayerAbilityHandler(player.username);
// if (bh != null) {
// bh.onTick(player);
// }
// }
// }
// }
// }
//
// @Override
// public void tickEnd(EnumSet<TickType> type, Object... tickData) {
// }
//
// @Override
// public EnumSet<TickType> ticks() {
// return EnumSet.of(TickType.PLAYER);
// }
//
// @Override
// public String getLabel() {
// return "HGPlayerTicks";
// }
// }
| import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.client.registry.KeyBindingRegistry;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.entity.player.EntityPlayer;
import sct.hexxitgear.control.HGKeyHandler;
import sct.hexxitgear.tick.PlayerTickHandler; | /*
* HexxitGear
* Copyright (C) 2013 Ryan Cohen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sct.hexxitgear;
public class ClientProxy extends CommonProxy {
@Override
public int addArmor(String armorName) {
return RenderingRegistry.addNewArmourRendererPrefix(armorName);
}
@Override
public EntityPlayer findPlayer(String playerName) {
for (Object a : FMLClientHandler.instance().getClient().theWorld.playerEntities) {
EntityPlayer player = (EntityPlayer) a;
if (player.username.toLowerCase().equals(playerName.toLowerCase())) {
return player;
}
}
return null;
}
@Override
public void registerHandlers() {
super.registerHandlers(); | // Path: src/sct/hexxitgear/control/HGKeyHandler.java
// @SideOnly(Side.CLIENT)
// public class HGKeyHandler extends KeyBindingRegistry.KeyHandler {
//
// public static KeyBinding activateHexxitArmor = new KeyBinding("Activate Hexxit Gear Armor", Keyboard.KEY_X);
// public static KeyBinding[] keybindArray = new KeyBinding[]{activateHexxitArmor};
// public static boolean[] repeats = new boolean[keybindArray.length];
//
// public HGKeyHandler() {
// super(keybindArray, repeats);
// }
//
// @Override
// public void keyDown(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd, boolean isRepeat) {
// EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer;
//
// if (player == null || tickEnd)
// return;
//
// if (kb.equals(activateHexxitArmor)) {
// if (ArmorSet.getPlayerArmorSet(player.username) != null) {
// Object[] data = new Object[] { player.username };
// PacketDispatcher.sendPacketToServer(PacketWrapper.createPacket(HexxitGear.modNetworkChannel, Packets.armorAbility, data));
// //ArmorSet.readArmorPacket(player.username);
// }
// }
// }
//
// @Override
// public void keyUp(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd) {
//
// }
//
// @Override
// public EnumSet<TickType> ticks() {
// return EnumSet.of(TickType.CLIENT);
// }
//
// @Override
// public String getLabel() {
// return "hexxitGearKeybinds";
// }
// }
//
// Path: src/sct/hexxitgear/tick/PlayerTickHandler.java
// public class PlayerTickHandler implements ITickHandler {
//
// private int tickCounter = 0;
//
// @Override
// public void tickStart(EnumSet<TickType> type, Object... tickData) {
// if (type.equals(EnumSet.of(TickType.PLAYER))) {
// for (Object tick : tickData) {
// if (tick instanceof EntityPlayer) {
// EntityPlayer player = (EntityPlayer) tick;
// if (tickCounter > 20) {
// ArmorSet.getMatchingSet(player);
// tickCounter = 0;
// }
// tickCounter++;
//
// if (ArmorSet.getPlayerArmorSet(player.username) != null) {
// ArmorSet armorSet = ArmorSet.getPlayerArmorSet(player.username);
// armorSet.applyBuffs(player);
// }
//
// // We run this outside of the check for an armorset just incase a player takes off armor mid ability
// AbilityHandler bh = AbilityHandler.getPlayerAbilityHandler(player.username);
// if (bh != null) {
// bh.onTick(player);
// }
// }
// }
// }
// }
//
// @Override
// public void tickEnd(EnumSet<TickType> type, Object... tickData) {
// }
//
// @Override
// public EnumSet<TickType> ticks() {
// return EnumSet.of(TickType.PLAYER);
// }
//
// @Override
// public String getLabel() {
// return "HGPlayerTicks";
// }
// }
// Path: src/sct/hexxitgear/ClientProxy.java
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.client.registry.KeyBindingRegistry;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.entity.player.EntityPlayer;
import sct.hexxitgear.control.HGKeyHandler;
import sct.hexxitgear.tick.PlayerTickHandler;
/*
* HexxitGear
* Copyright (C) 2013 Ryan Cohen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sct.hexxitgear;
public class ClientProxy extends CommonProxy {
@Override
public int addArmor(String armorName) {
return RenderingRegistry.addNewArmourRendererPrefix(armorName);
}
@Override
public EntityPlayer findPlayer(String playerName) {
for (Object a : FMLClientHandler.instance().getClient().theWorld.playerEntities) {
EntityPlayer player = (EntityPlayer) a;
if (player.username.toLowerCase().equals(playerName.toLowerCase())) {
return player;
}
}
return null;
}
@Override
public void registerHandlers() {
super.registerHandlers(); | TickRegistry.registerTickHandler(new PlayerTickHandler(), Side.CLIENT); |
sct/HexxitGear | src/sct/hexxitgear/ClientProxy.java | // Path: src/sct/hexxitgear/control/HGKeyHandler.java
// @SideOnly(Side.CLIENT)
// public class HGKeyHandler extends KeyBindingRegistry.KeyHandler {
//
// public static KeyBinding activateHexxitArmor = new KeyBinding("Activate Hexxit Gear Armor", Keyboard.KEY_X);
// public static KeyBinding[] keybindArray = new KeyBinding[]{activateHexxitArmor};
// public static boolean[] repeats = new boolean[keybindArray.length];
//
// public HGKeyHandler() {
// super(keybindArray, repeats);
// }
//
// @Override
// public void keyDown(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd, boolean isRepeat) {
// EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer;
//
// if (player == null || tickEnd)
// return;
//
// if (kb.equals(activateHexxitArmor)) {
// if (ArmorSet.getPlayerArmorSet(player.username) != null) {
// Object[] data = new Object[] { player.username };
// PacketDispatcher.sendPacketToServer(PacketWrapper.createPacket(HexxitGear.modNetworkChannel, Packets.armorAbility, data));
// //ArmorSet.readArmorPacket(player.username);
// }
// }
// }
//
// @Override
// public void keyUp(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd) {
//
// }
//
// @Override
// public EnumSet<TickType> ticks() {
// return EnumSet.of(TickType.CLIENT);
// }
//
// @Override
// public String getLabel() {
// return "hexxitGearKeybinds";
// }
// }
//
// Path: src/sct/hexxitgear/tick/PlayerTickHandler.java
// public class PlayerTickHandler implements ITickHandler {
//
// private int tickCounter = 0;
//
// @Override
// public void tickStart(EnumSet<TickType> type, Object... tickData) {
// if (type.equals(EnumSet.of(TickType.PLAYER))) {
// for (Object tick : tickData) {
// if (tick instanceof EntityPlayer) {
// EntityPlayer player = (EntityPlayer) tick;
// if (tickCounter > 20) {
// ArmorSet.getMatchingSet(player);
// tickCounter = 0;
// }
// tickCounter++;
//
// if (ArmorSet.getPlayerArmorSet(player.username) != null) {
// ArmorSet armorSet = ArmorSet.getPlayerArmorSet(player.username);
// armorSet.applyBuffs(player);
// }
//
// // We run this outside of the check for an armorset just incase a player takes off armor mid ability
// AbilityHandler bh = AbilityHandler.getPlayerAbilityHandler(player.username);
// if (bh != null) {
// bh.onTick(player);
// }
// }
// }
// }
// }
//
// @Override
// public void tickEnd(EnumSet<TickType> type, Object... tickData) {
// }
//
// @Override
// public EnumSet<TickType> ticks() {
// return EnumSet.of(TickType.PLAYER);
// }
//
// @Override
// public String getLabel() {
// return "HGPlayerTicks";
// }
// }
| import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.client.registry.KeyBindingRegistry;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.entity.player.EntityPlayer;
import sct.hexxitgear.control.HGKeyHandler;
import sct.hexxitgear.tick.PlayerTickHandler; | /*
* HexxitGear
* Copyright (C) 2013 Ryan Cohen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sct.hexxitgear;
public class ClientProxy extends CommonProxy {
@Override
public int addArmor(String armorName) {
return RenderingRegistry.addNewArmourRendererPrefix(armorName);
}
@Override
public EntityPlayer findPlayer(String playerName) {
for (Object a : FMLClientHandler.instance().getClient().theWorld.playerEntities) {
EntityPlayer player = (EntityPlayer) a;
if (player.username.toLowerCase().equals(playerName.toLowerCase())) {
return player;
}
}
return null;
}
@Override
public void registerHandlers() {
super.registerHandlers();
TickRegistry.registerTickHandler(new PlayerTickHandler(), Side.CLIENT); | // Path: src/sct/hexxitgear/control/HGKeyHandler.java
// @SideOnly(Side.CLIENT)
// public class HGKeyHandler extends KeyBindingRegistry.KeyHandler {
//
// public static KeyBinding activateHexxitArmor = new KeyBinding("Activate Hexxit Gear Armor", Keyboard.KEY_X);
// public static KeyBinding[] keybindArray = new KeyBinding[]{activateHexxitArmor};
// public static boolean[] repeats = new boolean[keybindArray.length];
//
// public HGKeyHandler() {
// super(keybindArray, repeats);
// }
//
// @Override
// public void keyDown(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd, boolean isRepeat) {
// EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer;
//
// if (player == null || tickEnd)
// return;
//
// if (kb.equals(activateHexxitArmor)) {
// if (ArmorSet.getPlayerArmorSet(player.username) != null) {
// Object[] data = new Object[] { player.username };
// PacketDispatcher.sendPacketToServer(PacketWrapper.createPacket(HexxitGear.modNetworkChannel, Packets.armorAbility, data));
// //ArmorSet.readArmorPacket(player.username);
// }
// }
// }
//
// @Override
// public void keyUp(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd) {
//
// }
//
// @Override
// public EnumSet<TickType> ticks() {
// return EnumSet.of(TickType.CLIENT);
// }
//
// @Override
// public String getLabel() {
// return "hexxitGearKeybinds";
// }
// }
//
// Path: src/sct/hexxitgear/tick/PlayerTickHandler.java
// public class PlayerTickHandler implements ITickHandler {
//
// private int tickCounter = 0;
//
// @Override
// public void tickStart(EnumSet<TickType> type, Object... tickData) {
// if (type.equals(EnumSet.of(TickType.PLAYER))) {
// for (Object tick : tickData) {
// if (tick instanceof EntityPlayer) {
// EntityPlayer player = (EntityPlayer) tick;
// if (tickCounter > 20) {
// ArmorSet.getMatchingSet(player);
// tickCounter = 0;
// }
// tickCounter++;
//
// if (ArmorSet.getPlayerArmorSet(player.username) != null) {
// ArmorSet armorSet = ArmorSet.getPlayerArmorSet(player.username);
// armorSet.applyBuffs(player);
// }
//
// // We run this outside of the check for an armorset just incase a player takes off armor mid ability
// AbilityHandler bh = AbilityHandler.getPlayerAbilityHandler(player.username);
// if (bh != null) {
// bh.onTick(player);
// }
// }
// }
// }
// }
//
// @Override
// public void tickEnd(EnumSet<TickType> type, Object... tickData) {
// }
//
// @Override
// public EnumSet<TickType> ticks() {
// return EnumSet.of(TickType.PLAYER);
// }
//
// @Override
// public String getLabel() {
// return "HGPlayerTicks";
// }
// }
// Path: src/sct/hexxitgear/ClientProxy.java
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.client.registry.KeyBindingRegistry;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.entity.player.EntityPlayer;
import sct.hexxitgear.control.HGKeyHandler;
import sct.hexxitgear.tick.PlayerTickHandler;
/*
* HexxitGear
* Copyright (C) 2013 Ryan Cohen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sct.hexxitgear;
public class ClientProxy extends CommonProxy {
@Override
public int addArmor(String armorName) {
return RenderingRegistry.addNewArmourRendererPrefix(armorName);
}
@Override
public EntityPlayer findPlayer(String playerName) {
for (Object a : FMLClientHandler.instance().getClient().theWorld.playerEntities) {
EntityPlayer player = (EntityPlayer) a;
if (player.username.toLowerCase().equals(playerName.toLowerCase())) {
return player;
}
}
return null;
}
@Override
public void registerHandlers() {
super.registerHandlers();
TickRegistry.registerTickHandler(new PlayerTickHandler(), Side.CLIENT); | KeyBindingRegistry.registerKeyBinding(new HGKeyHandler()); |
sct/HexxitGear | src/sct/hexxitgear/item/ItemHexxitArmor.java | // Path: src/sct/hexxitgear/gui/HGCreativeTab.java
// public class HGCreativeTab extends CreativeTabs {
//
// public static final HGCreativeTab tab = new HGCreativeTab("Hexxit Gear");
//
// public HGCreativeTab(String label) {
// super(label);
// }
//
// @Override
// public ItemStack getIconItemStack() {
// return new ItemStack(HexxitGear.tribalHelmet, 1, 0);
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public String getTranslatedTabLabel() {
// return this.getTabLabel();
// }
// }
| import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraftforge.common.ISpecialArmor;
import sct.hexxitgear.gui.HGCreativeTab; | /*
* HexxitGear
* Copyright (C) 2013 Ryan Cohen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sct.hexxitgear.item;
public class ItemHexxitArmor extends ItemArmor implements ISpecialArmor {
public ItemHexxitArmor(int par1, EnumArmorMaterial par2EnumArmorMaterial, int par3, int par4) {
super(par1, par2EnumArmorMaterial, par3, par4); | // Path: src/sct/hexxitgear/gui/HGCreativeTab.java
// public class HGCreativeTab extends CreativeTabs {
//
// public static final HGCreativeTab tab = new HGCreativeTab("Hexxit Gear");
//
// public HGCreativeTab(String label) {
// super(label);
// }
//
// @Override
// public ItemStack getIconItemStack() {
// return new ItemStack(HexxitGear.tribalHelmet, 1, 0);
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public String getTranslatedTabLabel() {
// return this.getTabLabel();
// }
// }
// Path: src/sct/hexxitgear/item/ItemHexxitArmor.java
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraftforge.common.ISpecialArmor;
import sct.hexxitgear.gui.HGCreativeTab;
/*
* HexxitGear
* Copyright (C) 2013 Ryan Cohen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sct.hexxitgear.item;
public class ItemHexxitArmor extends ItemArmor implements ISpecialArmor {
public ItemHexxitArmor(int par1, EnumArmorMaterial par2EnumArmorMaterial, int par3, int par4) {
super(par1, par2EnumArmorMaterial, par3, par4); | setCreativeTab(HGCreativeTab.tab); |
sct/HexxitGear | src/sct/hexxitgear/item/ItemHexicalEssence.java | // Path: src/sct/hexxitgear/gui/HGCreativeTab.java
// public class HGCreativeTab extends CreativeTabs {
//
// public static final HGCreativeTab tab = new HGCreativeTab("Hexxit Gear");
//
// public HGCreativeTab(String label) {
// super(label);
// }
//
// @Override
// public ItemStack getIconItemStack() {
// return new ItemStack(HexxitGear.tribalHelmet, 1, 0);
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public String getTranslatedTabLabel() {
// return this.getTabLabel();
// }
// }
| import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.item.Item;
import sct.hexxitgear.gui.HGCreativeTab; | /*
* HexxitGear
* Copyright (C) 2013 Ryan Cohen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sct.hexxitgear.item;
public class ItemHexicalEssence extends Item {
public ItemHexicalEssence(int id) {
super(id); | // Path: src/sct/hexxitgear/gui/HGCreativeTab.java
// public class HGCreativeTab extends CreativeTabs {
//
// public static final HGCreativeTab tab = new HGCreativeTab("Hexxit Gear");
//
// public HGCreativeTab(String label) {
// super(label);
// }
//
// @Override
// public ItemStack getIconItemStack() {
// return new ItemStack(HexxitGear.tribalHelmet, 1, 0);
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public String getTranslatedTabLabel() {
// return this.getTabLabel();
// }
// }
// Path: src/sct/hexxitgear/item/ItemHexicalEssence.java
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.item.Item;
import sct.hexxitgear.gui.HGCreativeTab;
/*
* HexxitGear
* Copyright (C) 2013 Ryan Cohen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sct.hexxitgear.item;
public class ItemHexicalEssence extends Item {
public ItemHexicalEssence(int id) {
super(id); | setCreativeTab(HGCreativeTab.tab); |
sct/HexxitGear | src/sct/hexxitgear/CommonProxy.java | // Path: src/sct/hexxitgear/tick/PlayerTickHandler.java
// public class PlayerTickHandler implements ITickHandler {
//
// private int tickCounter = 0;
//
// @Override
// public void tickStart(EnumSet<TickType> type, Object... tickData) {
// if (type.equals(EnumSet.of(TickType.PLAYER))) {
// for (Object tick : tickData) {
// if (tick instanceof EntityPlayer) {
// EntityPlayer player = (EntityPlayer) tick;
// if (tickCounter > 20) {
// ArmorSet.getMatchingSet(player);
// tickCounter = 0;
// }
// tickCounter++;
//
// if (ArmorSet.getPlayerArmorSet(player.username) != null) {
// ArmorSet armorSet = ArmorSet.getPlayerArmorSet(player.username);
// armorSet.applyBuffs(player);
// }
//
// // We run this outside of the check for an armorset just incase a player takes off armor mid ability
// AbilityHandler bh = AbilityHandler.getPlayerAbilityHandler(player.username);
// if (bh != null) {
// bh.onTick(player);
// }
// }
// }
// }
// }
//
// @Override
// public void tickEnd(EnumSet<TickType> type, Object... tickData) {
// }
//
// @Override
// public EnumSet<TickType> ticks() {
// return EnumSet.of(TickType.PLAYER);
// }
//
// @Override
// public String getLabel() {
// return "HGPlayerTicks";
// }
// }
| import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.entity.player.EntityPlayer;
import sct.hexxitgear.tick.PlayerTickHandler; | /*
* HexxitGear
* Copyright (C) 2013 Ryan Cohen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sct.hexxitgear;
public class CommonProxy {
public void init () {
registerHandlers();
}
public int addArmor(String armorName) {
return 0;
}
public EntityPlayer findPlayer(String playerName) {
return null;
}
public void registerHandlers() { | // Path: src/sct/hexxitgear/tick/PlayerTickHandler.java
// public class PlayerTickHandler implements ITickHandler {
//
// private int tickCounter = 0;
//
// @Override
// public void tickStart(EnumSet<TickType> type, Object... tickData) {
// if (type.equals(EnumSet.of(TickType.PLAYER))) {
// for (Object tick : tickData) {
// if (tick instanceof EntityPlayer) {
// EntityPlayer player = (EntityPlayer) tick;
// if (tickCounter > 20) {
// ArmorSet.getMatchingSet(player);
// tickCounter = 0;
// }
// tickCounter++;
//
// if (ArmorSet.getPlayerArmorSet(player.username) != null) {
// ArmorSet armorSet = ArmorSet.getPlayerArmorSet(player.username);
// armorSet.applyBuffs(player);
// }
//
// // We run this outside of the check for an armorset just incase a player takes off armor mid ability
// AbilityHandler bh = AbilityHandler.getPlayerAbilityHandler(player.username);
// if (bh != null) {
// bh.onTick(player);
// }
// }
// }
// }
// }
//
// @Override
// public void tickEnd(EnumSet<TickType> type, Object... tickData) {
// }
//
// @Override
// public EnumSet<TickType> ticks() {
// return EnumSet.of(TickType.PLAYER);
// }
//
// @Override
// public String getLabel() {
// return "HGPlayerTicks";
// }
// }
// Path: src/sct/hexxitgear/CommonProxy.java
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.entity.player.EntityPlayer;
import sct.hexxitgear.tick.PlayerTickHandler;
/*
* HexxitGear
* Copyright (C) 2013 Ryan Cohen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sct.hexxitgear;
public class CommonProxy {
public void init () {
registerHandlers();
}
public int addArmor(String armorName) {
return 0;
}
public EntityPlayer findPlayer(String playerName) {
return null;
}
public void registerHandlers() { | TickRegistry.registerTickHandler(new PlayerTickHandler(), Side.SERVER); |
sct/HexxitGear | src/sct/hexxitgear/item/ItemHexicalDiamond.java | // Path: src/sct/hexxitgear/gui/HGCreativeTab.java
// public class HGCreativeTab extends CreativeTabs {
//
// public static final HGCreativeTab tab = new HGCreativeTab("Hexxit Gear");
//
// public HGCreativeTab(String label) {
// super(label);
// }
//
// @Override
// public ItemStack getIconItemStack() {
// return new ItemStack(HexxitGear.tribalHelmet, 1, 0);
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public String getTranslatedTabLabel() {
// return this.getTabLabel();
// }
// }
| import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.item.Item;
import sct.hexxitgear.gui.HGCreativeTab; | /*
* HexxitGear
* Copyright (C) 2013 Ryan Cohen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sct.hexxitgear.item;
public class ItemHexicalDiamond extends Item {
public ItemHexicalDiamond(int id) {
super(id); | // Path: src/sct/hexxitgear/gui/HGCreativeTab.java
// public class HGCreativeTab extends CreativeTabs {
//
// public static final HGCreativeTab tab = new HGCreativeTab("Hexxit Gear");
//
// public HGCreativeTab(String label) {
// super(label);
// }
//
// @Override
// public ItemStack getIconItemStack() {
// return new ItemStack(HexxitGear.tribalHelmet, 1, 0);
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public String getTranslatedTabLabel() {
// return this.getTabLabel();
// }
// }
// Path: src/sct/hexxitgear/item/ItemHexicalDiamond.java
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.item.Item;
import sct.hexxitgear.gui.HGCreativeTab;
/*
* HexxitGear
* Copyright (C) 2013 Ryan Cohen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package sct.hexxitgear.item;
public class ItemHexicalDiamond extends Item {
public ItemHexicalDiamond(int id) {
super(id); | setCreativeTab(HGCreativeTab.tab); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.