repo_name
stringlengths 7
104
| file_path
stringlengths 11
238
| context
list | import_statement
stringlengths 103
6.85k
| code
stringlengths 60
38.4k
| next_line
stringlengths 10
824
| gold_snippet_index
int32 0
8
|
---|---|---|---|---|---|---|
sastix/cms | server/src/main/java/com/sastix/cms/server/services/content/impl/ZipHandlerServiceImpl.java | [
"@Getter @Setter @NoArgsConstructor @ToString\npublic class CreateResourceDTO {\n\n /**\n * The media-type of this new resource.\n */\n @NotNull\n private String resourceMediaType;\n\n /**\n * The author creating this resource.\n */\n @NotNull\n private String resourceAuthor;\n\n /**\n * The byte[] array of this resource.\n */\n private byte[] resourceBinary;\n\n /**\n * The URI holding this resource.\n */\n private String resourceExternalURI;\n\n /**\n * The name of the resource with optional relative path.\n */\n @NotNull\n private String resourceName;\n\n /**\n * A system-specific tenant identifier for multi-tenancy reasons.\n */\n @NotNull\n private String resourceTenantId;\n \n // TODO: Should we add a parentResourceUID?\n \n /**\n * Constructor with mandatory fields.\n *\n * @param resourceMediaType a String with the media type\n * @param resourceAuthor a String with the author\n * @param resourceName a String with resource name\n * @param resourceTenantId a String with the tenant id\n */\n public CreateResourceDTO(final String resourceMediaType,\n final String resourceAuthor,\n final String resourceName,\n final String resourceTenantId) {\n this.resourceMediaType = resourceMediaType;\n this.resourceAuthor = resourceAuthor;\n this.resourceName = resourceName;\n this.resourceTenantId = resourceTenantId;\n }\n\n}",
"@Getter @Setter @NoArgsConstructor @ToString\npublic class ResourceDTO {\n\n /**\n * The UID of the object to lock.\n */\n @NotNull\n private String resourceUID;\n\n /**\n * The author requesting the lock.\n */\n @NotNull\n private String author;\n\n /**\n * If available, this URI can fetch this resource on a subsequent request, as R/O content.\n */\n private String resourceURI;\n\n /**\n * A list of all linked resources for this UID, valid only if this UID is a \"package\" containing several other resources that have been inserted.\n */\n private List<ResourceDTO> resourcesList;\n\n /**\n * Constructor with the mandatory fields.\n *\n * @param resourceUID a String with the resource UID\n * @param author a String with the author\n */\n public ResourceDTO(final String resourceUID, final String author) {\n this.resourceUID = resourceUID;\n this.author = author;\n }\n\n}",
"@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = Constants.RESOURCE_ACCESS_ERROR)\npublic class ResourceAccessError extends GeneralResourceException {\n\n /**\n * Serial Version UID.\n */\n private static final long serialVersionUID = 7739893346328334895L;\n\n /**\n * Constructor that allows a specific error message to be specified.\n *\n * @param message detail message.\n */\n public ResourceAccessError(String message) {\n super(message);\n }\n}",
"@Entity\n@Table(name = \"resource\")\n@NamedQueries({\n @NamedQuery(name = \"Resource.findAll\", query = \"SELECT resource FROM Resource resource\")\n , @NamedQuery(name = \"Resource.findByAuthor\", query = \"SELECT resource FROM Resource resource WHERE resource.author = :author\")\n , @NamedQuery(name = \"Resource.findByAuthorContaining\", query = \"SELECT resource FROM Resource resource WHERE resource.author like :author\")\n , @NamedQuery(name = \"Resource.findByName\", query = \"SELECT resource FROM Resource resource WHERE resource.name = :name\")\n , @NamedQuery(name = \"Resource.findByNameContaining\", query = \"SELECT resource FROM Resource resource WHERE resource.name like :name\")\n , @NamedQuery(name = \"Resource.findByMediaType\", query = \"SELECT resource FROM Resource resource WHERE resource.mediaType = :mediaType\")\n , @NamedQuery(name = \"Resource.findByMediaTypeContaining\", query = \"SELECT resource FROM Resource resource WHERE resource.mediaType like :mediaType\")\n , @NamedQuery(name = \"Resource.findByPath\", query = \"SELECT resource FROM Resource resource WHERE resource.path = :path\")\n , @NamedQuery(name = \"Resource.findByPathContaining\", query = \"SELECT resource FROM Resource resource WHERE resource.path like :path\")\n , @NamedQuery(name = \"Resource.findByUid\", query = \"SELECT resource FROM Resource resource WHERE resource.uid = :uid\")\n , @NamedQuery(name = \"Resource.findByUidContaining\", query = \"SELECT resource FROM Resource resource WHERE resource.uid like :uid\")\n})\n@Getter @Setter @NoArgsConstructor\npublic class Resource implements Serializable {\n\n public static final String FIND_ALL = \"Resource.findAll\";\n public static final String FIND_BY_AUTHOR = \"Resource.findByAuthor\";\n public static final String FIND_BY_AUTHOR_CONTAINING = \"Resource.findByAuthorContaining\";\n public static final String FIND_BY_NAME = \"Resource.findByName\";\n public static final String FIND_BY_NAME_CONTAINING = \"Resource.findByNameContaining\";\n public static final String FIND_BY_MEDIATYPE = \"Resource.findByMediaType\";\n public static final String FIND_BY_MEDIATYPE_CONTAINING = \"Resource.findByMediaTypeContaining\";\n public static final String FIND_BY_PATH = \"Resource.findByPath\";\n public static final String FIND_BY_PATH_CONTAINING = \"Resource.findByPathContaining\";\n public static final String FIND_BY_UID = \"Resource.findByUid\";\n public static final String FIND_BY_UID_CONTAINING = \"Resource.findByUidContaining\";\n private static final long serialVersionUID = -7222707205353947820L;\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Integer id;\n\n @Column(name = \"author\", nullable = false, unique = false)\n private String author;\n\n @Column(name = \"name\", nullable = false, unique = false)\n private String name;\n\n @Column(name = \"media_type\", nullable = false, unique = false)\n private String mediaType;\n\n @Column(name = \"path\", length = 512, nullable = false, unique = false)\n private String path;\n\n @Column(name = \"uid\", length = 255, nullable = false, unique = false)\n private String uid;\n\n @Column(name = \"uri\", length = 255, nullable = false, unique = false)\n private String uri;\n\n @Column(name = \"resource_tenant_id\", nullable = false)\n private String resourceTenantId;\n \n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"resource_id\")\n private Resource resource;\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"resource\")\n private Set<Resource> resources = new HashSet<Resource>(0);\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"resource\")\n private Set<Revision> revisions = new HashSet<Revision>(0);\n\n}",
"public interface DistributedCacheService {\n\n void cacheIt(String uri, String tenantId);\n\n void updateCache(String uri, String tenantId);\n}",
"public interface HashedDirectoryService {\n\n String storeFile(final String UURI, final String tenantID, final byte[] resourceBinary) throws IOException;\n\n String replaceFile(final String UURI, final String tenantID, final byte[] resourceBinary) throws IOException;\n\n String storeFile(final String UURI, final String tenantID, final URI resourceURI) throws IOException;\n\n String replaceFile(final String UURI, final String tenantID, final URI resourceURI) throws IOException;\n\n String storeFile(final String UURI, final String tenantID, final String resourceURI) throws IOException, URISyntaxException;\n\n String replaceFile(final String UURI, final String tenantID, final String resourceURI) throws IOException, URISyntaxException;\n\n Path getDataByUID(final String UID, final String tenantID) throws IOException;\n\n byte[] getBytesByUID(final String UID, final String tenantID) throws IOException;\n\n Path getDataByURI(final String resourceURI, final String tenantID) throws IOException, URISyntaxException;\n\n byte[] getBytesByURI(final String resourceURI, final String tenantID) throws IOException;\n\n long getFileSize(final String resourceURI, final String tenantID) throws IOException;\n\n String hashText(String text);\n\n String getAbsolutePath(String resourceURI, final String tenantID);\n\n String createTenantDirectory(final String tenantID) throws IOException;\n\n String getVolume();\n\n void setVolume(String value);\n\n void storeChecksum(final String tenantID, final String checksum) throws IOException;\n\n String getChecksum(final String tenantID) throws IOException;\n}",
"public interface ResourceService extends ContentApi {\n\n Path getDataPath(DataDTO dataDTO) throws ResourceAccessError;\n\n ResponseEntity<InputStreamResource> getResponseInputStream(String uuid) throws ResourceAccessError, IOException;\n\n MultipartFileSender getMultipartFileSender(String uuid) throws ResourceAccessError, IOException;\n\n Resource insertResource(final CreateResourceDTO createResourceDTO);\n\n Resource insertChildResource(final CreateResourceDTO createResourceDTO, final String parentUid, final Resource parentResource);\n\n\n}",
"public interface ZipHandlerService {\n\n ResourceDTO handleZip(Resource zipResource);\n\n boolean isZip(Resource zipResource);\n}"
] | import com.sastix.cms.common.content.CreateResourceDTO;
import com.sastix.cms.common.content.ResourceDTO;
import com.sastix.cms.common.content.exceptions.ResourceAccessError;
import com.sastix.cms.server.domain.entities.Resource;
import com.sastix.cms.server.services.content.DistributedCacheService;
import com.sastix.cms.server.services.content.HashedDirectoryService;
import com.sastix.cms.server.services.content.ResourceService;
import com.sastix.cms.server.services.content.ZipHandlerService;
import org.apache.tika.Tika;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.GsonJsonParser;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; | /*
* Copyright(c) 2017 the original author or authors.
*
* 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.sastix.cms.server.services.content.impl;
@Slf4j
@Service
public class ZipHandlerServiceImpl implements ZipHandlerService {
public static final String METADATA_XML_FILE = "imsmanifest.xml";
public static final String METADATA_JSON_FILE = "info.json";
public static final String METADATA_STARTPAGE = "startpage";
public static final String METADATA_STARTPAGE_CAMEL = "startPage";
private final GsonJsonParser gsonJsonParser = new GsonJsonParser();
@Autowired
DistributedCacheService distributedCacheService;
@Autowired | HashedDirectoryService hashedDirectoryService; | 5 |
melloc/roguelike | game/src/main/java/edu/brown/cs/roguelike/game/GUIApp.java | [
"public final class Vec2i implements Serializable {\r\n\tprivate static final long serialVersionUID = 5659632794862666943L;\r\n\t\r\n\t/**\r\n\t * Since {@link Vec2i} instances are immutable, their x and y fields may be accessed without getters.\r\n\t */\r\n\tpublic final int x, y;\r\n\t\r\n\t/**\r\n\t * Creates a new vector from an x and y component.\r\n\t * @param x the x-component of the vector\r\n\t * @param y the y-component of the vector\r\n\t */\r\n\tpublic Vec2i(int x, int y) {\r\n\t\tthis.x = x;\r\n\t\tthis.y = y;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Factory method that creates a {@code Vec2i} by {@linkplain Math#round(float) rounding} the components of a {@link Vec2f} to the nearest integer.\r\n\t * @param v the Vec2f to round\r\n\t * @return a Vec2i created by rounding the components of {@code v}\r\n\t */\r\n\tpublic final static Vec2i fromRounded(Vec2f v) {\r\n\t\treturn new Vec2i(round(v.x), round(v.y));\r\n\t}\r\n\t\r\n\t/**\r\n\t * Factory method that creates a {@code Vec2i} by taking the {@linkplain Math#floor(double) floor} of the components of a {@link Vec2f}.\r\n\t * @param v the {@code Vec2f} to floor\r\n\t * @return a {@code Vec2i} created by taking the floor of the components of {@code v}\r\n\t */\r\n\tpublic final static Vec2i fromFloored(Vec2f v) {\r\n\t\treturn new Vec2i((int)floor(v.x), (int)floor(v.y));\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Factory method that creates a {@code Vec2i} by taking the {@linkplain Math#ceil(double) ceiling} of the components of a {@link Vec2f}.\r\n\t * @param v the {@code Vec2f} to ceil\r\n\t * @return a {@code Vec2i} created by taking the ceiling of the components of {@code v}\r\n\t */\r\n\tpublic final static Vec2i fromCeiled(Vec2f v) {\r\n\t\treturn new Vec2i((int)ceil(v.x), (int)ceil(v.y));\r\n\t}\r\n\t\r\n\t/*\r\n\t * Vector ops\r\n\t */\r\n\t\r\n\t/**\r\n\t * Multiplies the vector by a scalar.\r\n\t * @param s the scalar by which to multiply this vector\r\n\t * @return a new {@link Vec2i} instance where each component has been multiplied by {@code s}\r\n\t */\r\n\tpublic final Vec2i smult(int s) {\r\n\t\treturn new Vec2i(x*s, y*s);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Divides the vector by a scalar. Note that this is integer division.\r\n\t * @param s\t\tthe scalar by which to divide this vector\r\n\t * @return\t\ta new {@link Vec2i} instance where each component has been divided by\r\n\t * \t\t\t\t{@code s}\r\n\t */\r\n\tpublic final Vec2i sdiv(int s) {\r\n\t\treturn new Vec2i(x/s, y/s);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Multiplies the vector piecewise by another vector. NOT A DOT PRODUCT.\r\n\t * @param v the vector by which to multiply this vector\r\n\t * @return a new {@link Vec2i} instance where each component has been multiplied by the corresponding component in {@code v}\r\n\t */\r\n\tpublic final Vec2i pmult(Vec2i v) {\r\n\t\treturn new Vec2i(x*v.x, y*v.y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Primitive version of {@link #pmult(Vec2i)}.\r\n\t */\r\n\tpublic final Vec2i pmult(int x, int y) {\r\n\t\treturn new Vec2i(this.x * x, this.y * y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Divides the vector piecewise by another vector.\r\n\t * @param v the vector by which to divide this vector\r\n\t * @return a new {@link Vec2i} instance where each component has been divided by the corresponding component in {@code v}\r\n\t */\r\n\tpublic final Vec2i pdiv(Vec2i v) {\r\n\t\treturn new Vec2i(x/v.x, y/v.y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Primitive version of {@link #pdiv(Vec2i)}.\r\n\t */\r\n\tpublic final Vec2i pdiv(int x, int y) {\r\n\t\treturn new Vec2i(this.x/x, this.y/y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Adds another vector to this vector.\r\n\t * @param v the vector to add to this vector\r\n\t * @return a new {@link Vec2i} instance where each component has added the corresponding component in {@code v}\r\n\t */\r\n\tpublic final Vec2i plus(Vec2i v) {\r\n\t\treturn new Vec2i(x + v.x, y + v.y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Primitive version of {@link #plus(Vec2i)}.\r\n\t */\r\n\tpublic final Vec2i plus(int x, int y) {\r\n\t\treturn new Vec2i(this.x + x, this.y + y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Subtracts another vector from this vector.\r\n\t * @param v the vector to subtract from this vector\r\n\t * @return a new {@link Vec2i} instance where each component has added the corresponding component in {@code v}\r\n\t */\r\n\tpublic final Vec2i minus(Vec2i v) {\r\n\t\treturn new Vec2i(x - v.x, y - v.y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Primitive version of {@link #minus(Vec2i)}.\r\n\t */\r\n\tpublic final Vec2i minus(int x, int y) {\r\n\t\treturn new Vec2i(this.x - x, this.y - y);\r\n\t}\r\n\t\r\n\tpublic Dimension toDimension() {\r\n\t\treturn new Dimension(this.x, this.y);\r\n\t}\r\n\t\r\n\t/*\r\n\t * Object overrides\r\n\t */\r\n\r\n\t@Override\r\n\tpublic final int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + x;\r\n\t\tresult = prime * result + y;\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic final boolean equals(Object obj) {\r\n\t\tif (obj == null || obj.getClass() != Vec2i.class)\r\n\t\t\treturn false;\r\n\t\tVec2i other = (Vec2i) obj;\r\n\t\treturn x == other.x && y == other.y;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic final String toString() {\r\n\t\treturn new StringBuilder(\"(\").append(x).append(\", \").append(y).append(\")\").toString();\r\n\t}\r\n\r\n\tpublic static Vec2i fromPoint(Point pt) {\r\n\t\treturn new Vec2i(pt.x, pt.y);\r\n\t}\r\n\r\n\tpublic Point toPoint() {\r\n\t\treturn new Point(this.x, this.y);\r\n\t}\r\n}\r",
"public class ConfigurationException extends Exception {\n\t\n\t/**\n\t * Generated \n\t */\n\tprivate static final long serialVersionUID = 5399497813931843528L;\n\n\tpublic ConfigurationException(String msg) {\n\t\tsuper(msg);\n\t}\n\t\n\tpublic ConfigurationException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n\n}",
"public class CumulativeTurnManager extends TurnManager {\n\t\n\t/**\n\t * Generated\n\t */\n\tprivate static final long serialVersionUID = 2226734907191258919L;\n\t\n\tprivate final int pointsPerTurn;\n\t\n\t// If the player has less than minPtsPerTurn, they won't be given the\n\t// chance to go again during that turn. This helps to alleviate \n\t// player action lag. There may be a better way to do this\n\tprivate final int minPtsPerTurn;\n\t\n\n\tpublic CumulativeTurnManager(Application app, Game game, int pointsPerTurn) {\n\t\tsuper(app, game, pointsPerTurn);\n\t\tthis.pointsPerTurn = pointsPerTurn;\n\t\tthis.minPtsPerTurn = pointsPerTurn/2;\n\t}\n\t\n\t@Override\n\tpublic void takeTurnWithoutAnnounce(Action playerAction) {\n\t\t\n\t\tAction nextAction = null;\n\t\tint cost;\n\t\t\n\t\tEntityManager em = game.getCurrentLevel().getManager();\n\t\t\n\t\tEntityActionManager mainMgr = em.getEntity(\"main\").get(0);\n\t\t\n\t\t// if the player doesn't have an Action queued, then set one\n\t\tif (!mainMgr.hasNextAction()) { \n\t\t\tmainMgr.setNextAction(playerAction);\n\t\t} // otherwise try to do the action that has been queued\n\t\t\n\t\t// Player's turn:\n\t\tnextAction = mainMgr.getNextAction();\n\t\tcost = (nextAction instanceof Wait) ? \n\t\t\t\tpointsPerTurn : nextAction.getCost();\n\t\t\n\t\t// if the Player can take the action, then take it\n\t\tif (cost <= mainMgr.getActionPoints()) {\n\t\t\tmainMgr.takeNextAction();\n\t\t\tmainMgr.useActionPoints(cost);\n\t\t}\n\t\t\n\t\t// if there are more than minPtsPerTurn remaining, then return \n\t\t// and wait for player's next input\n\t\tif (mainMgr.getActionPoints() > minPtsPerTurn) return;\n\t\telse { // continue and grant APs for this turn\n\t\t\tmainMgr.addActionPoints(pointsPerTurn);\n\t\t}\n\n\t\t// take care of monsters:\n\t\t\n\t\tList<EntityActionManager> monsterMgrs = em.getEntity(\"monster\");\n\n\t\tfor (EntityActionManager mgr: monsterMgrs) {\n\n\t\t\tdo { // actions\n\t\t\t\t// check to make sure this monster still exists and hasn't been\n\t\t\t\t// concurrently removed\n\t\t\t\tif (em.reallyExists(mgr)) { \n\n\t\t\t\t\tnextAction = mgr.getNextAction();\n\t\t\t\t\tcost = (nextAction instanceof Wait) ? \n\t\t\t\t\t\t\tpointsPerTurn : nextAction.getCost();\n\n\t\t\t\t\t// if the monster can afford it, take the action\n\t\t\t\t\tif (cost <= mgr.getActionPoints()) {\n\t\t\t\t\t\tmgr.takeNextAction();\n\t\t\t\t\t\tmgr.useActionPoints(cost);\n\t\t\t\t\t} else { break; }\n\t\t\t\t} \n\t\t\t} \n\t\t\t// until we have too few points to try again\n\t\t\t// TODO: consider making the lower bound minPtsPerTurn? \n\t\t\twhile (mgr.getActionPoints() > 0);\n\t\t\t\n\t\t\t// finally, grant points for this turn\n\t\t\tmgr.addActionPoints(pointsPerTurn);\n\t\t}\n\t}\n}",
"public abstract class Game implements Saveable {\n\t\n\t/**\n\t * Generated\n\t */\n\tprivate static final long serialVersionUID = 4193150732888666463L;\n\n\tprotected GameState gameState;\n\t\n\tprotected Hashtable<Integer,Level> levels = new Hashtable<Integer,Level>();\n;\n\tprotected Level currentLevel;\n\tprotected Vec2i levelSize;\n\tprotected final Vec2i MAP_SIZE;\n \n public Game(Vec2i mapSize) {\n \tthis.MAP_SIZE = mapSize;\n \tthis.init();\n }\n \n /**Initalizes the first level\n * @throws ConfigurationException **/\n\tpublic void createInitalLevel(BSPLevelGenerator lg) throws ConfigurationException {\n\t\tthis.currentLevel = lg.generateLevel(MAP_SIZE, 1);\n\t\tlevels.put(1, currentLevel);\n\t\t\n\t\t//TODO: Get character name\n\t\tMainCharacter mc = new MainCharacter(\"Robert the Rogue\");\n\t\t\n\t\tcurrentLevel.placeCharacter(mc, true);\n\t}\n \n /**\n * Moves the player to the level indicated by depth\n * @param depth - The depth the player is moving to\n * @param levelGen - The level generator to use if new levels are needed\n * @throws ConfigurationException - A configuration problem exists\n */\n public void gotoLevel(int depth, LevelGenerator levelGen) throws ConfigurationException {\n \tif(levels.get(depth) == null) {\n \t\tLevel newLevel = levelGen.generateLevel(MAP_SIZE, depth);\n \t\t\n \t\tMainCharacter mc = currentLevel.removePlayer();\n \t\tnewLevel.placeCharacter(mc, currentLevel.getDepth() < depth);\n \t\tlevels.put(depth,newLevel);\n \t\tcurrentLevel = newLevel;\n \t}\n \telse {\n \t\tMainCharacter mc = currentLevel.removePlayer();\n \t\tlevels.get(depth).placeCharacter(mc, currentLevel.getDepth() < depth);\n \t\tcurrentLevel = levels.get(depth);\n \t}\n }\n \n private void init() {\n \tthis.gameState = GameState.INIT;\n }\n \n public void start() {\n \tthis.gameState = GameState.RUNNING;\n }\n \n public void win() { \n \tthis.gameState = GameState.WIN;\n }\n \n public void loss() { \n \tthis.gameState = GameState.LOSS;\n }\n \n public GameState getState() { \n \treturn this.gameState;\n }\n \n public Level getCurrentLevel() { return this.currentLevel; }\n\n \n /**\n * Takes a LevelGenerator to prevent the need to serialize a local copy\n * \n * @deprecated Use gotoLevel\n * \n * @param lg\n * @return\n * @throws ConfigurationException\n */\n public Level generateNewLevel(LevelGenerator lg) throws ConfigurationException {\n \tthis.currentLevel = lg.generateLevel(MAP_SIZE, 3);\n \treturn currentLevel;\n }\n \n \n \n\t/*** BEGIN Saveable ***/\n\n\tprivate UUID id;\n\t\n\t/** initialize id **/\n\t{\n\t\tthis.id = UUID.randomUUID();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\t\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tGame other = (Game) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (id.equals(other.id))\n\t\t\t// return true if ids are the same\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic UUID getId() {\n\t\treturn this.id;\n\t}\n\t\n\t/*** END Saveable ***/\n\n}",
"public abstract class Application extends LanternaFrontend {\n\n /**\n * This stack contains all elements in the game that should be drawn.\n * The element on top of the stack is considered the `active` element,\n * and receives all key presses.\n */\n\tprotected Stack<Layer> layers = new Stack<Layer>();\n\t\n\tpublic Stack<Layer> getLayers() {return layers;}\n\t\n\tpublic Application(String title) {\n\t\tsuper(title);\n\t}\n\n\t@Override\n\tprotected void onTick(long nanosSincePreviousTick) {\n\t\tfor (Layer layer : layers)\n\t\t\tlayer.tick(nanosSincePreviousTick);\n\t}\n\n\t@Override\n\tprotected void onDraw(Section s) {\n\t\tfor (Layer layer : layers)\n\t\t\tlayer.doDraw(s);\n\t}\n\t\n /**\n * Takes care of any initialization that is necessary for the game. For \n * example, any {@link Layer}'s that need to be added to the stack should\n * be added here. Any other preparation that is necessary should also be \n * done here.\n *\n * @param screenSize The initial size of the screen. This is provided in \n * case there is a need to determine where things should initially be drawn\n * until the next resize (which may never happen, so passing this in is \n * sort of important).\n *\n * @return Boolean indicating whether initialization was sucessful.\n */\n\tprotected abstract boolean initialize(Vec2i screenSize);\n\n\t@Override\n\tprotected void onKeyPressed(Key k) {\n\t\tif (!layers.isEmpty()) {\n\t\t\tLayer active = layers.peek();\n\t\t\tactive.propagateAction(active.getActionForKey(k));\n\t\t}\n\t}\n\t\n\tpublic abstract void deleteSaveFile();\n\t\n\t\n\tprivate boolean initialized = false;\n\n\t@Override\n\tprotected void onResize(Vec2i newSize) {\n\t\tif (!initialized)\n\t\t\tinitialized = initialize(newSize);\n\t\t\t\n\t\tfor (Layer layer : layers)\n\t\t\tlayer.updateSize(newSize);\n\t}\n\n}",
"public class BSPLevelGenerator implements LevelGenerator{\r\n\tprivate final int depthMax = 3;\r\n\r\n\r\n\t//-----------------------------------------------------------------------CONSTANTS-----------------------------------------------------------------------------------------------------------------\r\n\t/*\r\n\tprivate float roomMin; //min % the room occupies of sublevel\r\n\tprivate float roomMax; //max % the room occupies of sublevel\r\n\tprivate float roomBuffer; //% on each side of room must be from edge\r\n\t */\r\n\r\n\tprivate final float splitMin = 0.1f; // min % to split at\r\n\tprivate final float splitMax = 0.9f; // max % to split at\r\n\r\n\tprivate final int minWallThickness = 2; //Should be >= 2\r\n\r\n\tprivate int minRoomDim = 5;\r\n\r\n\tprivate int splitTries = 7;\r\n\r\n\r\n\t//---------------------------------------------------------------------END CONSTANTS------------------------------------------------------------------------------------------------------\r\n\r\n\tTile[][] tiles;\r\n\tRandomGen rand;\r\n\r\n\tprivate String configDir;\r\n\r\n\tpublic BSPLevelGenerator(String configDir) {\r\n\t\tthis.configDir = configDir;\r\n\t}\r\n\r\n\t/**\r\n\t * Generates a full level whose size is levelSize\r\n\t * @throws ConfigurationException \r\n\t */\r\n\tpublic Level generateLevel(Vec2i levelSize, int depth) throws ConfigurationException {\r\n\t\trand = new RandomGen(System.nanoTime());\r\n\t\ttiles = new Tile[levelSize.x][levelSize.y];\r\n\r\n\t\t//Init with solid map\r\n\t\tfillWithSolids(tiles);\r\n\r\n\t\tSubLevel fullLevel = new SubLevel(new Vec2i(0,0), levelSize,0);\r\n\t\tsplitAndBuild(fullLevel);\r\n\r\n\t\tLevel level = new Level(tiles,fullLevel.rooms,fullLevel.hallways);\r\n\r\n\t\tcreateStairs(level);\r\n\r\n\t\tlevel.setDepth(depth); \r\n\t\tMonsterGenerator mg = new ProgressiveMonsterGenerator(configDir);\r\n\t\tmg.populateLevel(level);\r\n\r\n\t\tItemGenerator ig = new ProgressiveItemGenerator(configDir); \r\n\t\tig.populateLevel(level);\r\n\r\n\t\treturn level;\r\n\t}\r\n\r\n\r\n\r\n\t/**Creates the up and down stairs**/\r\n\tprivate void createStairs(Level level) {\r\n\r\n\t\tRoom r = level.getRooms().get(rand.getRandom(level.getRooms().size()));\r\n\t\tint mX = rand.getRandom(r.min.x, r.max.x);\r\n\t\tint mY = rand.getRandom(r.min.y, r.max.y);\r\n\t\tTile t = level.getTiles()[mX][mY];\t\r\n\t\tlevel.upStairs = t;\r\n\t\tt.setType(TileType.UP_STAIRS);\r\n\r\n\t\tRoom r2;\r\n\t\tTile t2;\r\n\r\n\t\tif(level.getRooms().size() == 1) {\r\n\t\t\tr2 = r;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tdo {\r\n\t\t\t\tr2 = level.getRooms().get(rand.getRandom(level.getRooms().size()));\r\n\t\t\t}\r\n\t\t\twhile (r2 == r);\r\n\t\t}\r\n\r\n\t\tint x = rand.getRandom(r2.min.x, r2.max.x);\r\n\t\tint y = rand.getRandom(r2.min.y, r2.max.y);\r\n\t\tt2 = level.getTiles()[x][y];\t\r\n\r\n\t\tlevel.downStairs = t2;\r\n\t\tt2.setType(TileType.DOWN_STAIRS);\r\n\t}\r\n\r\n\r\n\r\n\r\n\t/**\r\n\t * Splits the sublevel recursively until it builds rooms, then connects the rooms together\r\n\t * In the end, curr is populated with the current hallways and rooms\r\n\t */\r\n\r\n\tprivate void splitAndBuild(SubLevel curr) {\r\n\t\tboolean makeRoom = false;\r\n\t\tint splitAttempts = 0;\r\n\r\n\t\tif(curr.depth == depthMax) //Check to see if you should make a room\r\n\t\t{\r\n\t\t\tmakeRoom = true;\r\n\t\t}\r\n\t\tif(makeRoom) {\r\n\t\t\tmakeRoom(curr);\r\n\t\t}\r\n\t\telse{ \r\n\r\n\t\t\t//Split into two more sub-levels, recur, then connect\r\n\t\t\tSplit s = (rand.getRandom(2) == 0) ? Split.VER : Split.HOR;\r\n\r\n\t\t\tif(s == Split.HOR) {\r\n\t\t\t\tfloat height = (curr.max.y-curr.min.y);\r\n\t\t\t\tif(height < 4*minWallThickness + 2*minRoomDim) {\r\n\t\t\t\t\ts = Split.VER;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse { //VER\r\n\t\t\t\tfloat width = (curr.max.x-curr.min.x);\r\n\t\t\t\tif(width < 4*minWallThickness + 2*minRoomDim) {\r\n\t\t\t\t\ts = Split.HOR;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\r\n\t\t\tSubLevel s1,s2;\r\n\r\n\r\n\t\t\tif(s == Split.HOR){\r\n\t\t\t\tfloat height = (curr.max.y-curr.min.y);\r\n\r\n\t\t\t\tif(height < 4*minWallThickness + 2*minRoomDim) {\r\n\t\t\t\t\tmakeRoom(curr);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tint splitVal = Math.round(curr.min.y + height*splitMin+ rand.getRandom(Math.round((height*(splitMax-splitMin)))));\r\n\r\n\t\t\t\twhile(splitVal - curr.min.y < 2*minWallThickness + minRoomDim || curr.max.y - splitVal -1 < 2*minWallThickness + minRoomDim ) {\r\n\t\t\t\t\tif(splitAttempts >= splitTries) {\r\n\t\t\t\t\t\tmakeRoom(curr);\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tsplitAttempts++;\r\n\t\t\t\t\tsplitVal = Math.round(curr.min.y + height*splitMin+ rand.getRandom(Math.round((height*(splitMax-splitMin)))));\r\n\t\t\t\t}\r\n\r\n\t\t\t\t//S1 gets [0-splitVal], S2 gets [SplitVal+1,Max]\r\n\t\t\t\ts1 = new SubLevel(new Vec2i(curr.min.x,curr.min.y), new Vec2i(curr.max.x,splitVal), curr.depth+1);\r\n\t\t\t\ts2 = new SubLevel(new Vec2i(curr.min.x,splitVal+1), new Vec2i(curr.max.x,curr.max.y), curr.depth+1);\r\n\t\t\t}\r\n\t\t\telse { //VER\r\n\t\t\t\tfloat width = (curr.max.x-curr.min.x);\r\n\r\n\t\t\t\tif(width < 4*minWallThickness + 2*minRoomDim) {\r\n\t\t\t\t\tmakeRoom(curr);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tint maxVal = Math.round((width*(splitMax-splitMin)));\r\n\t\t\t\tint splitVal = Math.round(curr.min.x + width*splitMin+ rand.getRandom(maxVal));\r\n\r\n\t\t\t\twhile(splitVal - curr.min.x < 2*minWallThickness + minRoomDim || curr.max.x - splitVal -1 < 2*minWallThickness + minRoomDim ) {\r\n\t\t\t\t\tif(splitAttempts >= splitTries) {\r\n\t\t\t\t\t\tmakeRoom(curr);\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tsplitAttempts++;\r\n\t\t\t\t\tmaxVal = Math.round((width*(splitMax-splitMin)));\r\n\t\t\t\t\tsplitVal = Math.round(curr.min.x + width*splitMin+ rand.getRandom(maxVal));\r\n\t\t\t\t}\r\n\r\n\t\t\t\t//S1 gets [0-splitVal], S2 gets [SplitVal+1,Max]\r\n\t\t\t\ts1 = new SubLevel(new Vec2i(curr.min.x,curr.min.y), new Vec2i(splitVal,curr.max.y), curr.depth+1);\r\n\t\t\t\ts2 = new SubLevel(new Vec2i(splitVal+1,curr.min.y), new Vec2i(curr.max.x,curr.max.y), curr.depth+1);\r\n\t\t\t}\r\n\r\n\t\t\tsplitAndBuild(s1);\r\n\t\t\tsplitAndBuild(s2);\r\n\r\n\t\t\tRange range = s1.overLap(s2, s);\r\n\t\t\tif(range != null)\r\n\t\t\t{\r\n\t\t\t\tint hpt;\r\n\t\t\t\tHallwayPoint hp1;\r\n\t\t\t\tHallwayPoint hp2;\r\n\t\t\t\tdo{\r\n\t\t\t\t\thpt = rand.getRandom(range.min,range.max);\r\n\t\t\t\t\thp1 = s1.getHallwayPoint(s, true, hpt);\r\n\t\t\t\t\thp2 = s2.getHallwayPoint(s, false, hpt);\r\n\t\t\t\t}\r\n\t\t\t\twhile (!testHallway(hp1.point,hp2.point));\r\n\r\n\t\t\t\tHallway new_hallway = new Hallway(hp1.point,hp2.point);\r\n\r\n\t\t\t\tpaintHallway(hp1.point,hp2.point,true, new_hallway, TileType.FLOOR);\r\n\r\n\t\t\t\thp1.space.connectToHallway(new_hallway);\r\n\t\t\t\thp2.space.connectToHallway(new_hallway);\r\n\r\n\t\t\t\tif(hp1.space.needDoor())\r\n\t\t\t\t\tmakeDoor(hp1.point,s, new_hallway, true);\r\n\t\t\t\tif(hp2.space.needDoor())\r\n\t\t\t\t\tmakeDoor(hp2.point,s, new_hallway, false);\r\n\r\n\t\t\t\tcurr.hallways.add(new_hallway);\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\t//Make L-Shaped corridor\r\n\t\t\t\tif(s == Split.HOR) {\r\n\r\n\t\t\t\t\tHallwayPoint hp1;\r\n\t\t\t\t\tHallwayPoint hp2;\r\n\t\t\t\t\tVec2i corner;\r\n\t\t\t\t\tdo{\r\n\t\t\t\t\t\tint cx = rand.getRandom(s1.intersectMin.x, s1.intersectMax.x);\r\n\t\t\t\t\t\tint cy = rand.getRandom(s2.intersectMin.y, s2.intersectMax.y);\r\n\t\t\t\t\t\tcorner = new Vec2i(cx,cy);\r\n\r\n\t\t\t\t\t\thp1 = s1.getHallwayPoint(Split.HOR, true, cx);\r\n\t\t\t\t\t\thp2 = s2.getHallwayPoint(Split.VER, (s2.intersectMin.x < s1.intersectMax.x), cy);\r\n\t\t\t\t\t}\r\n\t\t\t\t\twhile (!testHallway(hp1.point,corner) && !testHallway(hp2.point,corner));\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tHallway new_hallway1 = new Hallway(hp1.point,corner);\r\n\t\t\t\t\thp1.space.connectToHallway(new_hallway1);\r\n\r\n\t\t\t\t\tHallway new_hallway2;\r\n\r\n\t\t\t\t\tif (s2.intersectMin.x > s1.intersectMax.x) \r\n\t\t\t\t\t\tnew_hallway2 = new Hallway(hp2.point,corner);\r\n\t\t\t\t\telse \r\n\t\t\t\t\t\tnew_hallway2 = new Hallway(corner,hp2.point);\r\n\r\n\r\n\t\t\t\t\thp2.space.connectToHallway(new_hallway2);\r\n\r\n\t\t\t\t\tnew_hallway1.connectToHallway(new_hallway2);\r\n\r\n\t\t\t\t\t//Paint in\r\n\t\t\t\t\tpaintHallway(hp1.point,corner,true,new_hallway1, TileType.FLOOR);\r\n\t\t\t\t\tpaintHallway(hp2.point,corner,true,new_hallway2, TileType.FLOOR);\r\n\r\n\t\t\t\t\tif(hp1.space.needDoor())\r\n\t\t\t\t\t\tmakeDoor(hp1.point,s, new_hallway1, true);\r\n\t\t\t\t\tif(hp2.space.needDoor())\r\n\t\t\t\t\t\tmakeDoor(hp2.point,s, new_hallway2, false);\r\n\r\n\t\t\t\t\tcurr.hallways.add(new_hallway1);\r\n\t\t\t\t\tcurr.hallways.add(new_hallway2);\r\n\t\t\t\t}\r\n\t\t\t\telse{ //VER\r\n\r\n\t\t\t\t\tHallwayPoint hp1;\r\n\t\t\t\t\tHallwayPoint hp2;\r\n\t\t\t\t\tVec2i corner;\r\n\r\n\t\t\t\t\tdo{\r\n\t\t\t\t\t\tint cx = s1.intersectMin.x + rand.getRandom(s1.intersectMax.x - s1.intersectMin.x);\r\n\t\t\t\t\t\tint cy = s2.intersectMin.y + rand.getRandom(s2.intersectMax.y - s2.intersectMin.y);\r\n\t\t\t\t\t\tcorner = new Vec2i(cx,cy);\r\n\r\n\t\t\t\t\t\thp1 = s1.getHallwayPoint(Split.HOR, (s1.intersectMin.y < s2.intersectMax.y), cx);\r\n\t\t\t\t\t\thp2 = s2.getHallwayPoint(Split.VER, false, cy);\r\n\t\t\t\t\t}\r\n\t\t\t\t\twhile (!testHallway(hp1.point,corner) && !testHallway(hp2.point,corner));\r\n\r\n\t\t\t\t\tHallway new_hallway1;\r\n\t\t\t\t\tif (s1.intersectMin.y < s2.intersectMax.y)\r\n\t\t\t\t\t\tnew_hallway1 = new Hallway(hp1.point,corner);\r\n\t\t\t\t\telse \r\n\t\t\t\t\t\tnew_hallway1 = new Hallway(corner,hp1.point);\r\n\r\n\t\t\t\t\thp1.space.connectToHallway(new_hallway1);\r\n\r\n\t\t\t\t\tHallway new_hallway2 = new Hallway(corner,hp2.point);\r\n\t\t\t\t\thp2.space.connectToHallway(new_hallway2);\r\n\r\n\t\t\t\t\tnew_hallway1.connectToHallway(new_hallway2);\r\n\r\n\t\t\t\t\t//Paint in\r\n\t\t\t\t\tpaintHallway(hp1.point,corner,true, new_hallway1, TileType.FLOOR);\r\n\t\t\t\t\tpaintHallway(hp2.point,corner,true, new_hallway2, TileType.FLOOR);\r\n\r\n\t\t\t\t\tif(hp1.space.needDoor())\r\n\t\t\t\t\t\tmakeDoor(hp1.point,s,new_hallway1, true);\r\n\t\t\t\t\tif(hp2.space.needDoor())\r\n\t\t\t\t\t\tmakeDoor(hp2.point,s,new_hallway2, false);\r\n\r\n\t\t\t\t\tcurr.hallways.add(new_hallway1);\r\n\t\t\t\t\tcurr.hallways.add(new_hallway2);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t//Combine into a single sublevel\r\n\t\t\tcurr.rooms.addAll(s1.rooms);\r\n\t\t\tcurr.rooms.addAll(s2.rooms);\r\n\t\t\tcurr.hallways.addAll(s1.hallways);\r\n\t\t\tcurr.hallways.addAll(s2.hallways);\r\n\r\n\t\t\tint maxIX = Math.max(s1.intersectMax.x, s2.intersectMax.x);\r\n\t\t\tint maxIY = Math.max(s1.intersectMax.y, s2.intersectMax.y);\r\n\t\t\tint minIX = Math.min(s1.intersectMin.x, s2.intersectMin.x);\r\n\t\t\tint minIY = Math.min(s1.intersectMin.y, s2.intersectMin.y);\r\n\r\n\t\t\tcurr.intersectMax = new Vec2i(maxIX,maxIY);\r\n\t\t\tcurr.intersectMin = new Vec2i(minIX,minIY);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\t/**Makes a door at location, using the split and side to accurately place it in the wall**/\r\n\tprivate void makeDoor(Vec2i point, Split s, Space space, boolean b) {\r\n\t\tint xOff=0;\r\n\t\tint yOff=0;\r\n\r\n\t\tif(s == Split.HOR) \r\n\t\t\tyOff = 1;\r\n\t\telse\r\n\t\t\txOff = 1;\r\n\t\tif(!b) {\r\n\t\t\txOff *= -1;\r\n\t\t\tyOff *= -1;\r\n\t\t}\r\n\r\n\t\tTile t = tiles[point.x+xOff][point.y+yOff];\r\n\t\tt.setType(TileType.DOOR);\r\n\t\tt.setSpace(space);\r\n\t}\r\n\r\n\r\n\t/**\r\n\t * Makes a room inside the sublevel\r\n\t * @param curr - the area to make the room in\r\n\t */\r\n\tprivate void makeRoom(SubLevel curr) {\r\n\t\tint maxWidth = curr.max.x - curr.min.x- 1*minWallThickness - 1;\r\n\t\tint maxHeight = curr.max.y - curr.min.y - 1*minWallThickness - 1;\r\n\r\n\r\n\t\t//Randomly Select room coordinates\r\n\t\tint minX = rand.getRandom(minWallThickness,maxWidth-minRoomDim);\r\n\t\tint maxX = rand.getRandom(minX+minRoomDim, maxWidth);\r\n\r\n\t\tint minY = rand.getRandom(minWallThickness,maxHeight-minRoomDim);\r\n\t\tint maxY = rand.getRandom(minY+minRoomDim, maxHeight);\r\n\r\n\t\t/*\r\n\t\tint minY = minWallThickness+rand.getRandom(maxHeightprivate void paintCellRectangle(Vec2i min, Vec2i max, boolean passable, TileType t) {\r\n\t\tfor(int i = min.x; i <= max.x; i++) {\r\n\t\t\tfor(int j = min.y; j <= max.y; j++) {\r\n\t\t\t\tTile x = tiles[i][j];\r\n\t\t\t\tx.setType(t);\r\n\t\t\t}\r\n\t\t}-minRoomDim);\r\n\t\tint maxY = minY + minRoomDim + rand.getRandom(maxHeight-minY-minRoomDim);\r\n\t\t */\r\n\r\n\t\tVec2i min = curr.min.plus(minX, minY);\r\n\t\tVec2i max = curr.min.plus(maxX, maxY);\r\n\r\n\t\tRoom r = new Room(min,max);\r\n\r\n\t\t//Paint room to tile array\r\n\t\tpaintCellRectangle(min,max,true, r, TileType.FLOOR);\r\n\t\tpaintCellRectangle( curr.min.plus(minX-1,minY-1), curr.min.plus(minX-1,maxY+1),false, null, TileType.WALL_VER);\r\n\t\tpaintCellRectangle( curr.min.plus(maxX+1,minY-1), curr.min.plus(maxX+1,maxY+1),false, null, TileType.WALL_VER);\r\n\t\tpaintCellRectangle( curr.min.plus(minX-1,minY-1), curr.min.plus(maxX+1,minY-1),false, null, TileType.WALL_HOR);\r\n\t\tpaintCellRectangle( curr.min.plus(minX-1,maxY+1), curr.min.plus(maxX+1,maxY+1),false, null, TileType.WALL_HOR);\r\n\t\t\r\n\t\tcurr.rooms.add(r);\r\n\r\n\t\t//Hallways dont got to ends of rooms\r\n\t\tcurr.intersectMin = min;\r\n\t\tcurr.intersectMax = max;\r\n\r\n\t\t//Hallways dont got to ends of rooms\r\n\t\t//curr.intersectMin = min.plus(1,1);\r\n\t\t//curr.intersectMax = max.plus(-1,-1);\r\n\t}\r\n\r\n\t/**\r\n\t * Puts a cell with the given attributes in the rectangle given by\r\n\t * min,max inclusive.\r\n\t */\r\n\tprivate void paintCellRectangle(Vec2i min, Vec2i max, boolean passable,\r\n\t\t\tSpace space, TileType t) {\r\n\t\tfor(int i = min.x; i <= max.x; i++) {\r\n\t\t\tfor(int j = min.y; j <= max.y; j++) {\r\n\t\t\t\tTile x = tiles[i][j];\r\n\t\t\t\tx.setSpace(space);\r\n\t\t\t\tx.setType(t);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**Tests to see if a hallway can be laid. returns true if there are no problems**/\r\n\tprivate boolean testHallway(Vec2i a, Vec2i b) {\r\n\t\tif(a.x > b.x || a.y > b.y) {\r\n\t\t\ttestHallway(b,a);\r\n\t\t}\r\n\r\n\t\tif(a.x == b.x) {\r\n\t\t\tfor(int i = a.x-1; i <= a.x+1; i++) {\r\n\t\t\t\tfor(int j = a.y+2; j <= b.y-2; j++) {\r\n\t\t\t\t\tTile x = tiles[i][j];\r\n\t\t\t\t\tif(x.getType() != TileType.SOLID) {\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse{\r\n\t\t\tfor(int y = a.y-1; y <= a.y+1; y++) {\r\n\t\t\t\tfor(int x = a.x+2; x <= b.x-2; x++) {\r\n\t\t\t\t\tTile t = tiles[x][y];\r\n\t\t\t\t\tif(t.getType() != TileType.SOLID) {\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\t/**Paints a hallway onto the tile array**/\r\n\tprivate void paintHallway(Vec2i a, Vec2i b, boolean passable, \r\n\t\t\tSpace space, TileType t) {\r\n\t\tif(a.x > b.x || a.y > b.y) {\r\n\t\t\tpaintHallway(b,a,passable, space, t);\r\n\t\t}\r\n\t\tfor(int i = a.x; i <= b.x; i++) {\r\n\t\t\tfor(int j = a.y; j <= b.y; j++) {\r\n\t\t\t\tTile x = tiles[i][j];\r\n\t\t\t\tx.setType(t);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**Fills the tiles with all walls **/\r\n\tprivate void fillWithSolids(Tile[][] tiles) {\r\n\t\tfor(int i = 0; i < tiles.length; i++) {\r\n\t\t\tfor(int j = 0; j<tiles[0].length; j++) {\r\n\t\t\t\ttiles[i][j] = new Tile(TileType.SOLID);\r\n\t\t\t\ttiles[i][j].setLocation(new Vec2i(i,j));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n}\r",
"public class SaveManager {\n\t\n\tprivate static final String fileExtension = \".rog\";\n\t\n\tprivate String saveFile;\n\n\tpublic SaveManager(String saveFile) {\n\t\tif (saveFile.endsWith(fileExtension))\n\t\t\tthis.saveFile = saveFile;\n\t\telse this.saveFile = saveFile + fileExtension;\n\t}\n\n\t/**\n\t * Saves the current level, obliterating anything that\n\t * was already there\n\t * \n\t * @throws SaveLoadException\n\t */\n\tpublic void saveLevel(Level l) throws SaveLoadException {\n\t\ttry {\n\t\t\tFileOutputStream fos = new FileOutputStream(this.saveFile);\n\t\t\tObjectOutputStream oos = new ObjectOutputStream(fos);\n\t\t\t\n\t\t\toos.writeObject(l);\n\t\t\tfos.close();\n\t\t\toos.close();\n\t\t} catch (Exception e) {\n\t\t\tthrow new SaveLoadException(e);\n\t\t}\n\t}\n\t\n\tpublic void deleteSave() {\n\t\tFile f = new File(saveFile);\n\t\tif(f.exists()) \n\t\t\tf.delete();\n\t\t\n\t}\n\n\t/**\n\t * \n\t * Attempts to load a savegame from saveFile\n\t * \n\t * @throws SaveLoadException if there was no save file\n\t */\n\tpublic Level loadLevel() throws SaveLoadException {\n\t\t\n\t\tLevel l = null;\n\n\t\ttry {\n\t\t\tFileInputStream fis = new FileInputStream(this.saveFile);\n\t\t\tObjectInputStream ois = new ObjectInputStream(fis);\n\t\t\n\t\t\tObject o = ois.readObject();\n\t\t\tois.close();\n\t\t\t\n\t\t\tif (o instanceof Level) {\n\t\t\t\tl = (Level)o;\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tthrow new SaveLoadException(\n\t\t\t\t\t\t\"Save file was not a Level object. Found: \" \n\t\t\t\t\t\t\t\t+ o + \" instead\");\n\t\t\t}\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tthrow new SaveLoadException(e);\n\t\t}\n\t\t\n\t\treturn l;\n\t}\n\t\n\t/**\n\t * Saves the game, obliterating anything that\n\t * was already there\n\t * \n\t * @throws SaveLoadException\n\t */\n\tpublic void saveGame(Game g) throws SaveLoadException {\n\t\ttry {\n\t\t\tFileOutputStream fos = new FileOutputStream(this.saveFile);\n\t\t\tObjectOutputStream oos = new ObjectOutputStream(fos);\n\t\t\t\n\t\t\toos.writeObject(g);\n\t\t\toos.close();\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SaveLoadException(e);\n\t\t}\n\t}\n\n\t/**\n\t * \n\t * Attempts to load a savegame from saveFile\n\t * \n\t * @throws SaveLoadException if there was no save file\n\t */\n\tpublic Game loadGame() throws SaveLoadException {\n\t\t\n\t\tGame g = null;\n\n\t\ttry {\n\t\t\tFileInputStream fis = new FileInputStream(this.saveFile);\n\t\t\tObjectInputStream ois = new ObjectInputStream(fis);\n\t\t\n\t\t\tObject o = ois.readObject();\n\t\t\tois.close();\n\t\t\t\n\t\t\tif (o instanceof Game) {\n\t\t\t\tg = (Game)o;\n\t\t\t} else {\n\t\t\t\tthrow new SaveLoadException(\n\t\t\t\t\t\t\"Save file was not a Game object. Found: \" \n\t\t\t\t\t\t\t\t+ o + \" instead\");\n\t\t\t}\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tthrow new SaveLoadException(e);\n\t\t}\n\t\t\n\t\treturn g;\n\t}\n\n}"
] | import cs195n.Vec2i;
import edu.brown.cs.roguelike.engine.config.ConfigurationException;
import edu.brown.cs.roguelike.engine.game.CumulativeTurnManager;
import edu.brown.cs.roguelike.engine.game.Game;
import edu.brown.cs.roguelike.engine.graphics.Application;
import edu.brown.cs.roguelike.engine.proc.BSPLevelGenerator;
import edu.brown.cs.roguelike.engine.save.SaveManager; | package edu.brown.cs.roguelike.game;
public class GUIApp extends Application {
private final static Vec2i SCREEN_SIZE = new Vec2i(80,30);
private final static int POINTS_PER_TURN = 10;
private SaveManager sm; | private CumulativeTurnManager tm; | 2 |
IncQueryLabs/smarthome-cep-demonstrator | runtime/com.incquerylabs.smarthome.eventbus.api/src/main/java/com/incquerylabs/smarthome/eventbus/api/IEventSubscriber.java | [
"public class GroupItemStateChangedEvent extends ItemStateChangedEvent {\n\n\tpublic GroupItemStateChangedEvent(Item item, State newState, State oldState) {\n\t\tsuper(item, newState, oldState);\n\t}\n\t\n @Override\n public String toString() {\n return String.format(\"%s group state changed from %s to %s\", item.getName(), oldState, newState);\n }\n}",
"public class ItemAddedEvent implements ItemEvent {\n protected final Item item;\n\n\tpublic ItemAddedEvent(Item item) {\n\t\tsuper();\n\t\tthis.item = item;\n\t}\n\n\tpublic Item getItem() {\n\t\treturn item;\n\t}\n\t\n\tpublic String getName() {\n\t\treturn item.getName();\n\t}\n\t\n @Override\n public String toString() {\n return \"Item '\" + item.getName() + \"' has been added.\";\n }\n}",
"public class ItemCommandEvent extends ItemCommandBase implements ItemEvent {\n\n\tpublic ItemCommandEvent(Item item, Command command) {\n\t\tsuper(item, command);\n\t}\n}",
"public class ItemRemovedEvent implements ItemEvent {\n protected final String itemName;\n\n\tpublic ItemRemovedEvent(String itemName) {\n\t\tsuper();\n\t\tthis.itemName = itemName;\n\t}\n\t\n\tpublic String getName() {\n\t\treturn itemName;\n\t}\n\t\n @Override\n public String toString() {\n return \"Item '\" + itemName + \"' has been removed.\";\n }\n}",
"public class ItemStateChangedEvent extends ItemStateChangedBase implements ItemEvent {\n\n public ItemStateChangedEvent(Item item, State newState, State oldState) {\n super(item, newState, oldState);\n }\n}",
"public class ItemStateEvent implements ItemEvent {\n protected final Item item;\n protected final State itemState;\n\n\tpublic ItemStateEvent(Item item, State itemState) {\n\t\tsuper();\n\t\tthis.item = item;\n\t\tthis.itemState = itemState;\n\t}\n\n\tpublic Item getItem() {\n\t\treturn item;\n\t}\n\t\n public String getName() {\n return this.item.getName();\n }\n\n\tpublic State getItemState() {\n\t\treturn itemState;\n\t}\n\t\n @Override\n public String toString() {\n return String.format(\"%s updated to %s\", item.getName(), itemState);\n }\n}",
"public class ItemUpdatedEvent {\n protected final Item newItem;\n protected final String oldItemName;\n\t\n\tpublic ItemUpdatedEvent(Item newItem, String oldItemName) {\n\t\tsuper();\n\t\tthis.newItem = newItem;\n\t\tthis.oldItemName = oldItemName;\n\t}\n\n\tpublic Item getNewItem() {\n\t\treturn newItem;\n\t}\n\n\tpublic String getOldItemName() {\n\t\treturn oldItemName;\n\t}\n\t\n @Override\n public String toString() {\n return \"Item '\" + oldItemName + \"' has been updated.\";\n }\n}"
] | import java.util.Collection;
import org.eclipse.smarthome.core.items.Item;
import com.incquerylabs.smarthome.eventbus.api.events.GroupItemStateChangedEvent;
import com.incquerylabs.smarthome.eventbus.api.events.ItemAddedEvent;
import com.incquerylabs.smarthome.eventbus.api.events.ItemCommandEvent;
import com.incquerylabs.smarthome.eventbus.api.events.ItemRemovedEvent;
import com.incquerylabs.smarthome.eventbus.api.events.ItemStateChangedEvent;
import com.incquerylabs.smarthome.eventbus.api.events.ItemStateEvent;
import com.incquerylabs.smarthome.eventbus.api.events.ItemUpdatedEvent; | package com.incquerylabs.smarthome.eventbus.api;
public interface IEventSubscriber {
public void stateUpdated(ItemStateEvent event);
public void stateChanged(ItemStateChangedEvent event);
public void groupStateChanged(GroupItemStateChangedEvent event);
public void commandReceived(ItemCommandEvent event);
public void initItems(Collection<Item> items);
public void itemAdded(ItemAddedEvent event);
| public void itemRemoved(ItemRemovedEvent event); | 3 |
integeruser/jgltut | src/integeruser/jgltut/tut13/GeomImpostor.java | [
"public enum MouseButtons {\n MB_LEFT_BTN,\n MB_RIGHT_BTN,\n MB_MIDDLE_BTN\n}",
"public static class ViewData {\n public Vector3f targetPos;\n public Quaternionf orient;\n public float radius;\n public float degSpinRotation;\n\n public ViewData(Vector3f targetPos, Quaternionf orient, float radius, float degSpinRotation) {\n this.targetPos = targetPos;\n this.orient = orient;\n this.radius = radius;\n this.degSpinRotation = degSpinRotation;\n }\n\n public ViewData(ViewData viewData) {\n targetPos = new Vector3f(viewData.targetPos);\n orient = new Quaternionf(viewData.orient);\n radius = viewData.radius;\n degSpinRotation = viewData.degSpinRotation;\n }\n}",
"public static class ViewPole extends ViewProvider {\n private enum RotateMode {\n RM_DUAL_AXIS_ROTATE,\n RM_BIAXIAL_ROTATE,\n RM_XZ_AXIS_ROTATE,\n RM_Y_AXIS_ROTATE,\n RM_SPIN_VIEW_AXIS\n }\n\n private enum TargetOffsetDir {\n DIR_UP,\n DIR_DOWN,\n DIR_FORWARD,\n DIR_BACKWARD,\n DIR_RIGHT,\n DIR_LEFT\n }\n\n private ViewData currView;\n private ViewScale viewScale;\n\n private ViewData initialView;\n private MouseButtons actionButton;\n private boolean rightKeyboardCtrls;\n\n // Used when rotating.\n private boolean isDragging;\n private RotateMode rotateMode;\n\n private float degStarDragSpin;\n private Vector2i startDragMouseLoc;\n private Quaternionf startDragOrient;\n\n private Vector3f offsets[] = {\n new Vector3f(0.0f, 1.0f, 0.0f),\n new Vector3f(0.0f, -1.0f, 0.0f),\n new Vector3f(0.0f, 0.0f, -1.0f),\n new Vector3f(0.0f, 0.0f, 1.0f),\n new Vector3f(1.0f, 0.0f, 0.0f),\n new Vector3f(-1.0f, 0.0f, 0.0f)\n };\n\n ////////////////////////////////\n public ViewPole(ViewData initialView, ViewScale viewScale) {\n this(initialView, viewScale, MouseButtons.MB_LEFT_BTN, false);\n }\n\n public ViewPole(ViewData initialView, ViewScale viewScale, MouseButtons actionButton) {\n this(initialView, viewScale, actionButton, false);\n }\n\n public ViewPole(ViewData initialView, ViewScale viewScale, MouseButtons actionButton, boolean rightKeyboardCtrls) {\n currView = new ViewData(initialView);\n this.viewScale = viewScale;\n this.initialView = initialView;\n this.actionButton = actionButton;\n this.rightKeyboardCtrls = rightKeyboardCtrls;\n }\n\n ////////////////////////////////\n @Override\n public void mouseMove(Vector2i position) {\n if (isDragging) {\n onDragRotate(position);\n }\n }\n\n @Override\n public void mouseClick(MouseButtons button, boolean isPressed, MouseModifiers modifiers, Vector2i position) {\n if (isPressed) {\n // Ignore all other button presses when dragging.\n if (!isDragging) {\n if (button == actionButton) {\n if (modifiers == MouseModifiers.MM_KEY_CTRL) {\n beginDragRotate(position, RotateMode.RM_BIAXIAL_ROTATE);\n } else if (modifiers == MouseModifiers.MM_KEY_ALT) {\n beginDragRotate(position, RotateMode.RM_SPIN_VIEW_AXIS);\n } else {\n beginDragRotate(position, RotateMode.RM_DUAL_AXIS_ROTATE);\n }\n }\n }\n } else {\n // Ignore all other button releases when not dragging\n if (isDragging) {\n if (button == actionButton) {\n if (rotateMode == RotateMode.RM_DUAL_AXIS_ROTATE || rotateMode == RotateMode.RM_SPIN_VIEW_AXIS\n || rotateMode == RotateMode.RM_BIAXIAL_ROTATE) {\n endDragRotate(position);\n }\n }\n }\n }\n }\n\n @Override\n public void mouseWheel(int direction, MouseModifiers modifiers, Vector2i position) {\n if (direction > 0) {\n moveCloser(modifiers != MouseModifiers.MM_KEY_SHIFT);\n } else {\n moveAway(modifiers != MouseModifiers.MM_KEY_SHIFT);\n }\n }\n\n\n @Override\n public void charPress(int key, boolean isShiftPressed, float lastFrameDuration) {\n if (rightKeyboardCtrls) {\n switch (key) {\n case GLFW_KEY_I:\n offsetTargetPos(\n TargetOffsetDir.DIR_FORWARD,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_K:\n offsetTargetPos(\n TargetOffsetDir.DIR_BACKWARD,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_L:\n offsetTargetPos(\n TargetOffsetDir.DIR_RIGHT,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_J:\n offsetTargetPos(\n TargetOffsetDir.DIR_LEFT,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_O:\n offsetTargetPos(\n TargetOffsetDir.DIR_UP,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_U:\n offsetTargetPos(\n TargetOffsetDir.DIR_DOWN,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n }\n } else {\n switch (key) {\n case GLFW_KEY_W:\n offsetTargetPos(\n TargetOffsetDir.DIR_FORWARD,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_S:\n offsetTargetPos(\n TargetOffsetDir.DIR_BACKWARD,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_D:\n offsetTargetPos(\n TargetOffsetDir.DIR_RIGHT,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_A:\n offsetTargetPos(\n TargetOffsetDir.DIR_LEFT,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_E:\n offsetTargetPos(\n TargetOffsetDir.DIR_UP,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_Q:\n offsetTargetPos(\n TargetOffsetDir.DIR_DOWN,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n }\n }\n }\n\n\n @Override\n public Matrix4f calcMatrix() {\n Matrix4f mat = new Matrix4f();\n\n // Remember: these transforms are in reverse order.\n\n // In this space, we are facing in the correct direction. Which means that the camera point\n // is directly behind us by the radius number of units.\n mat.translate(new Vector3f(0.0f, 0.0f, -currView.radius));\n\n // Rotate the world to look in the right direction.\n Quaternionf angleAxis = new Quaternionf().setAngleAxis((float) Math.toRadians(currView.degSpinRotation), 0.0f, 0.0f, 1.0f);\n Quaternionf fullRotation = angleAxis.mul(currView.orient);\n\n mat.mul(fullRotation.get(new Matrix4f()));\n\n // Translate the world by the negation of the lookat point, placing the origin at the lookat point.\n mat.translate(new Vector3f(currView.targetPos).negate());\n return mat;\n }\n\n ////////////////////////////////\n public void reset() {\n if (!isDragging) {\n currView = new ViewData(initialView);\n }\n }\n\n\n public ViewData getView() {\n return currView;\n }\n\n ////////////////////////////////\n private void beginDragRotate(Vector2i ptStart, RotateMode rotMode) {\n rotateMode = rotMode;\n startDragMouseLoc = ptStart;\n degStarDragSpin = currView.degSpinRotation;\n startDragOrient = currView.orient;\n isDragging = true;\n }\n\n\n private void onDragRotate(Vector2i ptCurr) {\n Vector2i diff = new Vector2i(ptCurr).sub(startDragMouseLoc);\n int diffX = diff.x;\n int diffY = diff.y;\n\n switch (rotateMode) {\n case RM_DUAL_AXIS_ROTATE:\n processXYChange(diffX, diffY);\n break;\n\n case RM_BIAXIAL_ROTATE:\n if (Math.abs(diffX) > Math.abs(diffY)) {\n processXChange(diffX, true);\n } else {\n processYChange(diffY, true);\n }\n break;\n\n case RM_XZ_AXIS_ROTATE:\n processXChange(diffX);\n break;\n\n case RM_Y_AXIS_ROTATE:\n processYChange(diffY);\n break;\n\n case RM_SPIN_VIEW_AXIS:\n processSpinAxis(diffX, diffY);\n break;\n }\n }\n\n\n private void endDragRotate(Vector2i ptEnd) {\n endDragRotate(ptEnd, true);\n }\n\n private void endDragRotate(Vector2i ptEnd, boolean keepResults) {\n if (keepResults) {\n onDragRotate(ptEnd);\n } else {\n currView.orient = startDragOrient;\n }\n\n isDragging = false;\n }\n\n\n private void processXChange(int diffX) {\n processXChange(diffX, false);\n }\n\n private void processXChange(int diffX, boolean clearY) {\n float degAngleDiff = diffX * viewScale.rotationScale;\n\n // Rotate about the world-space Y axis.\n Quaternionf angleAxisY = new Quaternionf().setAngleAxis((float) Math.toRadians(degAngleDiff), 0.0f, 1.0f, 0.0f);\n currView.orient = new Quaternionf(startDragOrient).mul(angleAxisY);\n }\n\n\n private void processYChange(int diffY) {\n processYChange(diffY, false);\n }\n\n private void processYChange(int diffY, boolean clearXZ) {\n float degAngleDiff = diffY * viewScale.rotationScale;\n\n // Rotate about the local-space X axis.\n Quaternionf angleAxisX = new Quaternionf().setAngleAxis((float) Math.toRadians(degAngleDiff), 1.0f, 0.0f, 0.0f);\n currView.orient = angleAxisX.mul(startDragOrient);\n }\n\n\n private void processXYChange(int diffX, int diffY) {\n float degXAngleDiff = (diffX * viewScale.rotationScale);\n float degYAngleDiff = (diffY * viewScale.rotationScale);\n\n // Rotate about the world-space Y axis.\n Quaternionf angleAxisY = new Quaternionf().setAngleAxis((float) Math.toRadians(degXAngleDiff), 0.0f, 1.0f, 0.0f);\n currView.orient = new Quaternionf(startDragOrient).mul(angleAxisY);\n // Rotate about the local-space X axis.\n Quaternionf angleAxisX = new Quaternionf().setAngleAxis((float) Math.toRadians(degYAngleDiff), 1.0f, 0.0f, 0.0f);\n currView.orient = angleAxisX.mul(currView.orient);\n }\n\n\n private void processSpinAxis(int diffX, int diffY) {\n float degSpinDiff = diffX * viewScale.rotationScale;\n currView.degSpinRotation = degSpinDiff + degStarDragSpin;\n }\n\n\n private void moveCloser(boolean largeStep) {\n if (largeStep) {\n currView.radius -= viewScale.largeRadiusDelta;\n } else {\n currView.radius -= viewScale.smallRadiusDelta;\n }\n\n if (currView.radius < viewScale.minRadius) {\n currView.radius = viewScale.minRadius;\n }\n }\n\n\n private void moveAway(boolean largeStep) {\n if (largeStep) {\n currView.radius += viewScale.largeRadiusDelta;\n } else {\n currView.radius += viewScale.smallRadiusDelta;\n }\n\n if (currView.radius > viewScale.maxRadius) {\n currView.radius = viewScale.maxRadius;\n }\n }\n\n\n private void offsetTargetPos(TargetOffsetDir dir, float worldDistance, float lastFrameDuration) {\n Vector3f offsetDir = new Vector3f(offsets[dir.ordinal()]);\n offsetTargetPos(offsetDir.mul(worldDistance).mul(lastFrameDuration), lastFrameDuration);\n }\n\n private void offsetTargetPos(Vector3f cameraOffset, float lastFrameDuration) {\n Matrix4f currMat = calcMatrix();\n Quaternionf orientation = new Quaternionf();\n currMat.getNormalizedRotation(orientation);\n\n Quaternionf invOrient = new Quaternionf(orientation).conjugate();\n Vector3f worldOffset = invOrient.transform(new Vector3f(cameraOffset));\n\n currView.targetPos.add(worldOffset);\n }\n}",
"public static class ViewScale {\n public float minRadius;\n public float maxRadius;\n public float largeRadiusDelta;\n public float smallRadiusDelta;\n public float largePosOffset;\n public float smallPosOffset;\n public float rotationScale;\n\n public ViewScale(float minRadius, float maxRadius, float largeRadiusDelta, float smallRadiusDelta,\n float largePosOffset, float smallPosOffset, float rotationScale) {\n this.minRadius = minRadius;\n this.maxRadius = maxRadius;\n this.largeRadiusDelta = largeRadiusDelta;\n this.smallRadiusDelta = smallRadiusDelta;\n this.largePosOffset = largePosOffset;\n this.smallPosOffset = smallPosOffset;\n this.rotationScale = rotationScale;\n }\n}",
"public abstract class Tutorial {\n protected long window;\n\n protected DoubleBuffer mouseBuffer1 = BufferUtils.createDoubleBuffer(1);\n protected DoubleBuffer mouseBuffer2 = BufferUtils.createDoubleBuffer(1);\n\n // Measured in seconds\n protected float elapsedTime;\n protected float lastFrameDuration;\n\n private double lastFrameTimestamp;\n\n protected FloatBuffer vec4Buffer = BufferUtils.createFloatBuffer(4);\n protected FloatBuffer mat3Buffer = BufferUtils.createFloatBuffer(9);\n protected FloatBuffer mat4Buffer = BufferUtils.createFloatBuffer(16);\n protected ByteBuffer projectionBlockBuffer = BufferUtils.createByteBuffer(ProjectionBlock.BYTES);\n protected ByteBuffer unprojectionBlockBuffer = BufferUtils.createByteBuffer(UnprojectionBlock.BYTES);\n protected ByteBuffer lightBlockBuffer = BufferUtils.createByteBuffer(LightBlock.BYTES);\n protected ByteBuffer materialBlockBuffer = BufferUtils.createByteBuffer(MaterialBlock.BYTES);\n\n ////////////////////////////////\n\n public final void start(int width, int height) {\n try {\n GLFWErrorCallback.createPrint(System.err).set();\n\n initGLFW();\n initWindow(width, height);\n\n glfwSwapInterval(1);\n GL.createCapabilities();\n\n initCallbacks();\n init();\n initViewport();\n\n printInfo();\n\n loop();\n\n glfwFreeCallbacks(window);\n glfwDestroyWindow(window);\n } finally {\n glfwTerminate();\n glfwSetErrorCallback(null).free();\n }\n }\n\n\n private void initGLFW() {\n if (!glfwInit()) throw new IllegalStateException(\"Unable to initialize GLFW\");\n\n glfwDefaultWindowHints();\n glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);\n glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);\n if (Platform.get() == Platform.MACOSX) {\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);\n glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n }\n }\n\n private void initWindow(int width, int height) {\n window = glfwCreateWindow(width, height, \"jgltut\", NULL, NULL);\n if (window == NULL) throw new RuntimeException(\"Failed to create the GLFW window\");\n\n GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());\n glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);\n\n glfwMakeContextCurrent(window);\n glfwShowWindow(window);\n }\n\n private void initViewport() {\n // From http://www.glfw.org/faq.html#why-is-my-output-in-the-lower-left-corner-of-the-window:\n // \"On OS X with a Retina display, and possibly on other platforms in the future, screen coordinates and\n // pixels do not map 1:1. Use the framebuffer size, which is in pixels, instead of the window size.\"\n int[] w = new int[1], h = new int[1];\n glfwGetFramebufferSize(window, w, h);\n reshape(w[0], h[0]);\n }\n\n private void initCallbacks() {\n glfwSetFramebufferSizeCallback(window, (window, width, height) -> {\n reshape(width, height);\n });\n\n glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {\n if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) glfwSetWindowShouldClose(window, true);\n });\n }\n\n private void printInfo() {\n System.out.println();\n System.out.println(\"-----------------------------------------------------------\");\n\n System.out.format(\"%-18s%s\\n\", \"Running:\", getClass().getName());\n System.out.format(\"%-18s%s\\n\", \"OpenGL version:\", glGetString(GL_VERSION));\n\n if (!GL.getCapabilities().OpenGL33) {\n System.out.println(\"You must have at least OpenGL 3.3 to run this tutorial.\");\n }\n }\n\n private void loop() {\n long startTime = System.nanoTime();\n while (!glfwWindowShouldClose(window)) {\n elapsedTime = (float) ((System.nanoTime() - startTime) / 1000000000.0);\n\n double now = System.nanoTime();\n lastFrameDuration = (float) ((now - lastFrameTimestamp) / 1000000000.0);\n lastFrameTimestamp = now;\n\n update();\n display();\n\n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n }\n\n ////////////////////////////////\n\n protected abstract void init();\n\n protected abstract void display();\n\n protected abstract void reshape(int w, int h);\n\n protected abstract void update();\n\n ////////////////////////////////\n\n protected final boolean isKeyPressed(int key) {\n return glfwGetKey(window, key) == 1;\n }\n\n protected final boolean isMouseButtonPressed(int key) {\n return glfwGetMouseButton(window, key) == 1;\n }\n}",
"public class Framework {\n public static String COMMON_DATAPATH = \"/integeruser/jgltut/data/\";\n public static String CURRENT_TUTORIAL_DATAPATH = null;\n\n\n public static String findFileOrThrow(String fileName) {\n // search the file in '/jgltut/tut##/data/'\n InputStream fileStream = Framework.class.getResourceAsStream(CURRENT_TUTORIAL_DATAPATH + fileName);\n if (fileStream != null) return CURRENT_TUTORIAL_DATAPATH + fileName;\n\n // search the file in '/jgltut/data/'\n fileStream = Framework.class.getResourceAsStream(COMMON_DATAPATH + fileName);\n if (fileStream != null) return COMMON_DATAPATH + fileName;\n\n throw new RuntimeException(\"Could not find the file \" + fileName);\n }\n\n ////////////////////////////////\n public static int loadShader(int shaderType, String shaderFilename) {\n String filePath = Framework.findFileOrThrow(shaderFilename);\n String shaderCode = loadShaderFile(filePath);\n return Shader.compileShader(shaderType, shaderCode);\n }\n\n private static String loadShaderFile(String shaderFilePath) {\n StringBuilder text = new StringBuilder();\n\n try {\n BufferedReader reader = new BufferedReader(new InputStreamReader(Framework.class.getResourceAsStream(shaderFilePath)));\n\n String line;\n while ((line = reader.readLine()) != null) {\n text.append(line).append(\"\\n\");\n }\n\n reader.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return text.toString();\n }\n\n\n public static int createProgram(ArrayList<Integer> shaders) {\n try {\n int prog = Shader.linkProgram(shaders);\n return prog;\n } finally {\n for (Integer shader : shaders) {\n glDeleteShader(shader);\n }\n }\n }\n}",
"public class Mesh {\n public Mesh(String filename) {\n ArrayList<Attribute> attribs = new ArrayList<>(16);\n ArrayList<IndexData> indexData = new ArrayList<>();\n ArrayList<NamedVAO> namedVaoList = new ArrayList<>();\n\n Document doc = null;\n try {\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n\n String meshPath = Framework.findFileOrThrow(filename);\n doc = dBuilder.parse(Mesh.class.getResourceAsStream(meshPath));\n } catch (ParserConfigurationException | SAXException | IOException e) {\n e.printStackTrace();\n System.exit(-1);\n }\n\n Element meshElement = doc.getDocumentElement();\n NodeList attrs = meshElement.getElementsByTagName(\"attribute\");\n for (int i = 0; i < attrs.getLength(); i++) {\n // crea un Attribute e lo aggiunge a attribs\n Attribute a = new Attribute(attrs.item(i));\n attribs.add(a);\n }\n\n NodeList vaos = meshElement.getElementsByTagName(\"vao\");\n for (int i = 0; i < vaos.getLength(); i++) {\n // crea un NamedVAO con ProcessVAO e lo aggiunge a namedVaoList\n NamedVAO namedVao = new NamedVAO(vaos.item(i));\n namedVaoList.add(namedVao);\n }\n\n NodeList cmds = meshElement.getElementsByTagName(\"indices\");\n for (int i = 0; i < cmds.getLength(); i++) {\n // aggiunge a primitives il risultato di ProcessRenderCmd\n RenderCmd r = new RenderCmd(cmds.item(i));\n primitives.add(r);\n // aggiunge a indexData il risultato di IndexData\n IndexData in = new IndexData(cmds.item(i));\n indexData.add(in);\n }\n\n NodeList arrays = meshElement.getElementsByTagName(\"arrays\");\n for (int i = 0; i < arrays.getLength(); i++) {\n // aggiunge a primitives il risultato di ProcessRenderCmd\n RenderCmd r = new RenderCmd(arrays.item(i));\n primitives.add(r);\n }\n\n // calcola la lunghezza del buffer controllando che tutti gli array di\n // attributi abbiano la stessa lunghezza\n int iAttrbBufferSize = 0;\n ArrayList<Integer> attribStartLocs = new ArrayList<>(attribs.size());\n int iNumElements = 0;\n\n for (int i = 0; i < attribs.size(); i++) {\n iAttrbBufferSize = iAttrbBufferSize % 16 != 0 ?\n (iAttrbBufferSize + (16 - iAttrbBufferSize % 16))\n : iAttrbBufferSize;\n attribStartLocs.add(iAttrbBufferSize);\n Attribute attrib = attribs.get(i);\n\n iAttrbBufferSize += attrib.calcByteSize();\n\n if (iNumElements != 0) {\n if (iNumElements != attrib.numElements()) {\n throw new RuntimeException(\"Some of the attribute arrays have different element counts.\");\n }\n } else {\n iNumElements = attrib.numElements();\n }\n }\n\n // crea e binda il VAO\n oVAO = glGenVertexArrays();\n glBindVertexArray(oVAO);\n\n // Crea i buffer object\n oAttribArraysBuffer = glGenBuffers();\n glBindBuffer(GL_ARRAY_BUFFER, oAttribArraysBuffer);\n glBufferData(GL_ARRAY_BUFFER, iAttrbBufferSize, GL_STATIC_DRAW);\n\n // Inserisce i dati degli attributi nel buffer object\n for (int i = 0; i < attribs.size(); i++) {\n Attribute attrib = attribs.get(i);\n attrib.fillBoundBufferObject(attribStartLocs.get(i));\n attrib.setupAttributeArray(attribStartLocs.get(i));\n }\n\n // riempie i vari VAOs\n for (int i = 0; i < namedVaoList.size(); i++) {\n NamedVAO namedVao = namedVaoList.get(i);\n\n int vao = glGenVertexArrays();\n glBindVertexArray(vao);\n\n List<Integer> attributeArray = namedVao.attributes;\n for (int j = 0; j < attributeArray.size(); j++) {\n int idAttrib = attributeArray.get(j);\n int iAttribOffset = -1;\n for (int iCount = 0; iCount < attribs.size(); iCount++) {\n if (attribs.get(iCount).attribIndex == idAttrib) {\n iAttribOffset = iCount;\n break;\n }\n }\n\n Attribute attrib = attribs.get(iAttribOffset);\n attrib.setupAttributeArray(attribStartLocs.get(iAttribOffset));\n }\n\n namedVAOs.put(namedVao.name, vao);\n }\n\n glBindVertexArray(0);\n\n // Calcola la lunghezza dell'index buffer\n int iIndexBufferSize = 0;\n ArrayList<Integer> indexStartLocs = new ArrayList<>(indexData.size());\n for (int i = 0; i < indexData.size(); i++) {\n iIndexBufferSize = iIndexBufferSize % 16 != 0 ?\n (iIndexBufferSize + (16 - iIndexBufferSize % 16))\n : iIndexBufferSize;\n\n indexStartLocs.add(iIndexBufferSize);\n IndexData currData = indexData.get(i);\n\n iIndexBufferSize += currData.calcByteSize();\n }\n\n // Crea l'index buffer object\n if (iIndexBufferSize > 0) {\n glBindVertexArray(oVAO);\n\n oIndexBuffer = glGenBuffers();\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oIndexBuffer);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, iIndexBufferSize,\n GL_STATIC_DRAW);\n\n // gli inserisce i dati\n for (int i = 0; i < indexData.size(); i++) {\n IndexData currData = indexData.get(i);\n currData.fillBoundBufferObject(indexStartLocs.get(i));\n }\n\n // crea i RenderCmd\n int iCurrIndexed = 0;\n for (int i = 0; i < primitives.size(); i++) {\n RenderCmd prim = primitives.get(i);\n if (prim.isIndexedCmd) {\n prim.start = indexStartLocs.get(iCurrIndexed);\n prim.elemCount = indexData.get(iCurrIndexed)\n .getDataNumElem();\n prim.eIndexDataType = indexData.get(iCurrIndexed).attribType.glType;\n iCurrIndexed++;\n }\n }\n\n for (Integer idVAO : namedVAOs.values()) {\n glBindVertexArray(idVAO);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oIndexBuffer);\n }\n\n glBindVertexArray(0);\n }\n }\n\n public void render() {\n if (oVAO == 0) {\n return;\n }\n\n glBindVertexArray(oVAO);\n\n for (RenderCmd cmd : primitives) {\n cmd.render();\n }\n\n glBindVertexArray(0);\n }\n\n public void render(String meshName) {\n Integer vao = namedVAOs.get(meshName);\n if (vao == null) {\n return;\n }\n\n glBindVertexArray(vao);\n\n for (RenderCmd cmd : primitives) {\n cmd.render();\n }\n\n glBindVertexArray(0);\n }\n\n ////////////////////////////////\n private int oAttribArraysBuffer = 0;\n private int oIndexBuffer = 0;\n private int oVAO = 0;\n\n private ArrayList<RenderCmd> primitives = new ArrayList<>();\n private Map<String, Integer> namedVAOs = new HashMap<>();\n\n ////////////////////////////////\n public abstract static class ParseFunc {\n abstract public Buffer parse(String strToParse);\n }\n\n public abstract static class WriteFunc {\n abstract public void writeToBuffer(int eBuffer, Buffer theData, int iOffset);\n }\n\n\n private static class Attribute {\n Attribute(Node attributeNode) {\n NamedNodeMap attrs = attributeNode.getAttributes();\n\n {\n Node indexNode = attrs.getNamedItem(\"index\");\n if (indexNode == null) {\n throw new RuntimeException(\"Missing 'index' attribute in an 'attribute' element.\");\n }\n\n int index = Integer.parseInt(indexNode.getNodeValue());\n if (!((0 <= index) && (index < 16))) {\n throw new RuntimeException(\"Attribute index must be between 0 and 16.\");\n }\n\n attribIndex = index;\n }\n\n {\n Node sizeNode = attrs.getNamedItem(\"size\");\n if (sizeNode == null) {\n throw new RuntimeException(\"Missing 'size' attribute in an 'attribute' element.\");\n }\n\n int size = Integer.parseInt(sizeNode.getNodeValue());\n if (!((1 <= size) && (size < 5))) {\n throw new RuntimeException(\"Attribute size must be between 1 and 4.\");\n }\n\n this.size = size;\n }\n\n {\n String strType;\n Node typeNode = attrs.getNamedItem(\"type\");\n if (typeNode == null) {\n throw new RuntimeException(\"Missing 'type' attribute in an 'attribute' element.\");\n }\n\n strType = typeNode.getNodeValue();\n attribType = AttribType.get(strType);\n }\n\n {\n Node integralNode = attrs.getNamedItem(\"integral\");\n if (integralNode == null) {\n isIntegral = false;\n } else {\n String strIntegral = integralNode.getNodeValue();\n switch (strIntegral) {\n case \"true\":\n isIntegral = true;\n break;\n case \"false\":\n isIntegral = false;\n break;\n default:\n throw new RuntimeException(\"Incorrect 'integral' value for the 'attribute'.\");\n }\n\n if (attribType.normalized) {\n throw new RuntimeException(\"Attribute cannot be both 'integral' and a normalized 'type'.\");\n }\n\n if (attribType.glType == GL_FLOAT\n || attribType.glType == GL_HALF_FLOAT\n || attribType.glType == GL_DOUBLE) {\n throw new RuntimeException(\"Attribute cannot be both 'integral' and a floating-point 'type'.\");\n }\n }\n }\n\n {\n String strData = attributeNode.getChildNodes().item(0).getNodeValue();\n dataArray = attribType.parse(strData);\n }\n }\n\n\n int numElements() {\n return getDataNumElem() / size;\n }\n\n int calcByteSize() {\n return getDataNumElem() * attribType.numBytes;\n }\n\n void fillBoundBufferObject(int offset) {\n attribType.writeToBuffer(GL_ARRAY_BUFFER, dataArray, offset);\n }\n\n void setupAttributeArray(int offset) {\n glEnableVertexAttribArray(attribIndex);\n if (isIntegral) {\n glVertexAttribIPointer(attribIndex, size, attribType.glType, 0, offset);\n } else {\n glVertexAttribPointer(attribIndex, size, attribType.glType,\n attribType.normalized, 0, offset);\n }\n }\n\n ////////////////////////////////\n\n private int attribIndex = 0xFFFFFFFF;\n private AttribType attribType = null;\n private int size = -1;\n private boolean isIntegral = false;\n private Buffer dataArray;\n\n\n private int getDataNumElem() {\n return dataArray.limit();\n }\n }\n\n private static class AttribType {\n AttribType(boolean normalized, int glType, int numBytes, ParseFunc parseFunc, WriteFunc writeFunc) {\n this.normalized = normalized;\n this.glType = glType;\n this.numBytes = numBytes;\n this.parseFunc = parseFunc;\n this.writeFunc = writeFunc;\n }\n\n\n Buffer parse(String strData) {\n return parseFunc.parse(strData);\n }\n\n void writeToBuffer(int eBuffer, Buffer buffer, int offset) {\n writeFunc.writeToBuffer(eBuffer, buffer, offset);\n }\n\n\n static AttribType get(String type) {\n AttribType attType = allAttribType.get(type);\n if (attType == null) {\n throw new RuntimeException(\"Unknown 'type' field.\");\n }\n\n return attType;\n }\n\n ////////////////////////////////\n\n private static final Map<String, AttribType> allAttribType = new HashMap<>();\n private static final Map<String, Integer> allPrimitiveType = new HashMap<>();\n\n private boolean normalized;\n private int glType;\n private int numBytes;\n\n private ParseFunc parseFunc;\n private WriteFunc writeFunc;\n\n private static ParseFunc parseFloats = new ParseFunc() {\n public Buffer parse(String strToParse) {\n Scanner scn = new Scanner(strToParse);\n scn.useDelimiter(\"\\\\s+\");\n ArrayList<Float> array = new ArrayList<>();\n\n while (scn.hasNext()) {\n array.add(Float.parseFloat(scn.next()));\n }\n\n FloatBuffer buff = BufferUtils.createFloatBuffer(array.size());\n for (Float data : array) {\n buff.put(data);\n }\n buff.flip();\n\n scn.close();\n return buff;\n }\n };\n private static ParseFunc parseInts = new ParseFunc() {\n public Buffer parse(String strToParse) {\n Scanner scn = new Scanner(strToParse);\n scn.useDelimiter(\"\\\\s+\");\n ArrayList<Integer> array = new ArrayList<>();\n\n while (scn.hasNext()) {\n array.add((int) Long.parseLong(scn.next()));\n }\n\n IntBuffer buff = BufferUtils.createIntBuffer(array.size());\n for (Integer data : array) {\n buff.put(data);\n }\n buff.flip();\n\n scn.close();\n return buff;\n }\n };\n private static ParseFunc parseShorts = new ParseFunc() {\n public Buffer parse(String strToParse) {\n Scanner scn = new Scanner(strToParse);\n scn.useDelimiter(\"\\\\s+\");\n ArrayList<Short> array = new ArrayList<>();\n\n while (scn.hasNext()) {\n array.add((short) Integer.parseInt(scn.next()));\n }\n\n ShortBuffer buff = BufferUtils.createShortBuffer(array.size());\n for (Short data : array) {\n buff.put(data);\n }\n buff.flip();\n\n scn.close();\n return buff;\n }\n };\n private static ParseFunc parseBytes = new ParseFunc() {\n public Buffer parse(String strToParse) {\n Scanner scn = new Scanner(strToParse);\n scn.useDelimiter(\"\\\\s+\");\n ArrayList<Byte> array = new ArrayList<>();\n\n while (scn.hasNext()) {\n array.add((byte) Short.parseShort(scn.next()));\n }\n\n ByteBuffer buff = BufferUtils.createByteBuffer(array.size());\n for (Byte data : array) {\n buff.put(data);\n }\n buff.flip();\n\n scn.close();\n return buff;\n }\n };\n\n private static WriteFunc writeFloats = new WriteFunc() {\n public void writeToBuffer(int eBuffer, Buffer theData, int iOffset) {\n glBufferSubData(eBuffer, iOffset, (FloatBuffer) theData);\n }\n };\n private static WriteFunc writeInts = new WriteFunc() {\n public void writeToBuffer(int eBuffer, Buffer theData, int iOffset) {\n glBufferSubData(eBuffer, iOffset, (IntBuffer) theData);\n }\n };\n private static WriteFunc writeShorts = new WriteFunc() {\n public void writeToBuffer(int eBuffer, Buffer theData, int iOffset) {\n glBufferSubData(eBuffer, iOffset, (ShortBuffer) theData);\n }\n };\n private static WriteFunc writeBytes = new WriteFunc() {\n public void writeToBuffer(int eBuffer, Buffer theData, int iOffset) {\n glBufferSubData(eBuffer, iOffset, (ByteBuffer) theData);\n }\n };\n\n static {\n allAttribType.put(\"float\", new AttribType(false, GL_FLOAT,\n Float.SIZE / 8, parseFloats, writeFloats));\n // {\"half\", false, GL_HALF_FLOAT, sizeof(GLhalfARB), ParseFloats,\n // WriteFloats},\n allAttribType.put(\"int\", new AttribType(false, GL_INT,\n Integer.SIZE / 8, parseInts, writeInts));\n allAttribType.put(\"uint\", new AttribType(false, GL_UNSIGNED_INT,\n Integer.SIZE / 8, parseInts, writeInts));\n // {\"norm-int\", true, GL_INT, sizeof(GLint), ParseInts, WriteInts},\n // {\"norm-uint\", true, GL_UNSIGNED_INT, sizeof(GLuint), ParseUInts,\n // WriteUInts},\n allAttribType.put(\"short\", new AttribType(false, GL_SHORT,\n Short.SIZE / 8, parseShorts, writeShorts));\n allAttribType.put(\"ushort\",\n new AttribType(false, GL_UNSIGNED_SHORT, Short.SIZE / 8,\n parseShorts, writeShorts));\n // {\"norm-short\", true, GL_SHORT, sizeof(GLshort), ParseShorts,\n // WriteShorts},\n // {\"norm-ushort\", true, GL_UNSIGNED_SHORT, sizeof(GLushort),\n // ParseUShorts, WriteUShorts},\n allAttribType.put(\"byte\", new AttribType(false, GL_BYTE,\n Byte.SIZE / 8, parseBytes, writeBytes));\n allAttribType.put(\"ubyte\", new AttribType(false, GL_UNSIGNED_BYTE,\n Byte.SIZE / 8, parseBytes, writeBytes));\n // {\"norm-byte\", true, GL_BYTE, sizeof(GLbyte), ParseBytes,\n // WriteBytes},\n // {\"norm-ubyte\", true, GL_UNSIGNED_BYTE, sizeof(GLubyte),\n // ParseUBytes, WriteUBytes},\n\n allPrimitiveType.put(\"triangles\", GL_TRIANGLES);\n allPrimitiveType.put(\"tri-strip\", GL_TRIANGLE_STRIP);\n allPrimitiveType.put(\"tri-fan\", GL_TRIANGLE_FAN);\n allPrimitiveType.put(\"lines\", GL_LINES);\n allPrimitiveType.put(\"line-strip\", GL_LINE_STRIP);\n allPrimitiveType.put(\"line-loop\", GL_LINE_LOOP);\n allPrimitiveType.put(\"points\", GL_POINTS);\n }\n }\n\n ////////////////////////////////\n private static class RenderCmd {\n private boolean isIndexedCmd;\n private int primType;\n private int start;\n private int elemCount;\n private int eIndexDataType; // Only if isIndexedCmd is true.\n\n\n RenderCmd(Node cmdNode) {\n NamedNodeMap attrs = cmdNode.getAttributes();\n\n {\n Node cmdAttr = attrs.getNamedItem(\"cmd\");\n if (cmdAttr == null) {\n throw new RuntimeException(\"Missing 'cmd' attribute in an 'arrays' or 'indices' element.\");\n }\n\n String strCmd = cmdAttr.getNodeValue();\n Integer primitive = AttribType.allPrimitiveType.get(strCmd);\n if (primitive == null) {\n throw new RuntimeException(\"Unknown 'cmd' field.\");\n }\n\n primType = primitive;\n }\n\n if (cmdNode.getNodeName().equals(\"indices\")) {\n isIndexedCmd = true;\n } else if (cmdNode.getNodeName().equals(\"arrays\")) {\n isIndexedCmd = false;\n\n {\n Node nodeStart = cmdNode.getAttributes().getNamedItem(\"start\");\n if (nodeStart == null) {\n throw new RuntimeException(\"Missing 'start' attribute in an 'arrays' element.\");\n }\n\n int iStart = Integer.parseInt(nodeStart.getNodeValue());\n if (iStart < 0) {\n throw new RuntimeException(\"Attribute 'start' must be between 0 or greater.\");\n }\n\n start = iStart;\n }\n {\n Node nodeCount = cmdNode.getAttributes().getNamedItem(\"count\");\n if (nodeCount == null) {\n throw new RuntimeException(\"Missing 'count' attribute in an 'arrays' element.\");\n }\n\n int iCount = Integer.parseInt(nodeCount.getNodeValue());\n if (iCount <= 0) {\n throw new RuntimeException(\"Attribute 'count' must be greater than 0.\");\n }\n\n elemCount = iCount;\n }\n } else {\n throw new RuntimeException(\"Bad element. Must be 'indices' or 'arrays'.\");\n }\n }\n\n\n void render() {\n if (isIndexedCmd) {\n glDrawElements(primType, elemCount, eIndexDataType, start);\n } else {\n glDrawArrays(primType, start, elemCount);\n }\n }\n }\n\n private static class IndexData {\n private AttribType attribType;\n private Buffer dataArray;\n\n\n IndexData(Node indexElem) {\n NamedNodeMap attrs = indexElem.getAttributes();\n // controlla che type sia valido\n {\n Node typeAttr = attrs.getNamedItem(\"type\");\n if (typeAttr == null) {\n throw new RuntimeException(\"Missing 'type' attribute in an 'index' element.\");\n }\n\n String strType = typeAttr.getNodeValue();\n if (!(strType.equals(\"uint\") || strType.equals(\"ushort\") || strType.equals(\"ubyte\"))) {\n throw new RuntimeException(\"Improper 'type' attribute value on 'index' element.\");\n }\n\n attribType = AttribType.get(strType);\n }\n\n // legge gli indici\n {\n String strIndex = indexElem.getChildNodes().item(0).getNodeValue();\n dataArray = attribType.parse(strIndex);\n if (dataArray.limit() == 0) {\n throw new RuntimeException(\"The index element must have an array of values.\");\n }\n }\n }\n\n\n void fillBoundBufferObject(int iOffset) {\n attribType.writeToBuffer(GL_ELEMENT_ARRAY_BUFFER, dataArray,\n iOffset);\n }\n\n int getDataNumElem() {\n return dataArray.limit();\n }\n\n int calcByteSize() {\n return getDataNumElem() * attribType.numBytes;\n }\n }\n\n private static class NamedVAO {\n private String name;\n private ArrayList<Integer> attributes;\n\n\n NamedVAO(Node itemVao) {\n attributes = new ArrayList<>();\n\n NamedNodeMap attrs = itemVao.getAttributes();\n {\n Node nameAttr = attrs.getNamedItem(\"name\");\n if (nameAttr == null) {\n throw new RuntimeException(\"Missing 'name' attribute in an 'vao' element.\");\n }\n\n name = nameAttr.getNodeValue();\n }\n\n Element elemVao = (Element) itemVao;\n NodeList sources = elemVao.getElementsByTagName(\"source\");\n for (int sourceIndex = 0; sourceIndex < sources.getLength(); sourceIndex++) {\n Node attrib = sources.item(sourceIndex).getAttributes().getNamedItem(\"attrib\");\n if (attrib == null) {\n throw new RuntimeException(\"Missing 'attrib' attribute in an 'source' element.\");\n }\n\n attributes.add(Integer.parseInt(attrib.getNodeValue()));\n }\n }\n }\n}",
"public class MousePole {\n public static void forwardMouseMotion(Pole forward, int x, int y) {\n forward.mouseMove(new Vector2i(x, y));\n }\n\n public static void forwardMouseButton(long window, Pole forwardPole, int button, boolean state, int x, int y) {\n MouseModifiers modifiers = calcModifiers(window);\n Vector2i mouseLoc = new Vector2i(x, y);\n MouseButtons mouseButtons = null;\n\n switch (button) {\n case 0:\n mouseButtons = MouseButtons.MB_LEFT_BTN;\n break;\n\n case 1:\n mouseButtons = MouseButtons.MB_RIGHT_BTN;\n break;\n\n case 2:\n mouseButtons = MouseButtons.MB_MIDDLE_BTN;\n break;\n }\n\n forwardPole.mouseClick(mouseButtons, state, modifiers, mouseLoc);\n }\n\n public static void forwardMouseWheel(long window, Pole forward, int direction, int x, int y) {\n forward.mouseWheel(direction, calcModifiers(window), new Vector2i(x, y));\n }\n\n\n private static MouseModifiers calcModifiers(long window) {\n if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == 1 || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == 1)\n return MouseModifiers.MM_KEY_SHIFT;\n if (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == 1 || glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == 1)\n return MouseModifiers.MM_KEY_CTRL;\n if (glfwGetKey(window, GLFW_KEY_MENU) == 1)\n return MouseModifiers.MM_KEY_ALT;\n return null;\n }\n}",
"public class Timer {\n public enum Type {\n LOOP,\n SINGLE\n }\n\n ////////////////////////////////\n public Timer(Type type, float duration) {\n this.type = type;\n secDuration = duration;\n }\n\n ////////////////////////////////\n\n /**\n * Updates the time for the timer. Returns true if the timer has reached the end.\n * Will only return true for SINGLE timers that have reached their duration.\n *\n * @param elapsedTime the time passed since the application start (in milliseconds)\n */\n public boolean update(float elapsedTime) {\n float absCurrTime = elapsedTime;\n\n if (!hasUpdated) {\n absPrevTime = absCurrTime;\n hasUpdated = true;\n }\n\n if (isPaused) {\n absPrevTime = absCurrTime;\n return false;\n }\n\n float deltaTime = absCurrTime - absPrevTime;\n secAccumTime += deltaTime;\n\n absPrevTime = absCurrTime;\n return type == Type.SINGLE && secAccumTime > secDuration;\n }\n\n\n /**\n * Subtracts secRewind from the current time and continues from there.\n */\n public void rewind(float secRewind) {\n secAccumTime -= secRewind;\n\n if (secAccumTime < 0.0f) {\n secAccumTime = 0.0f;\n }\n }\n\n /**\n * Adds secRewind to the current time and continues from there.\n */\n public void fastForward(float secFF) {\n secAccumTime += secFF;\n }\n\n\n /**\n * Returns true if the timer is paused.\n */\n public boolean isPaused() {\n return isPaused;\n }\n\n /**\n * Pauses/unpauses. Returns true if the timer is paused after the toggling.\n */\n public boolean togglePause() {\n isPaused = !isPaused;\n return isPaused;\n }\n\n /**\n * Sets the pause state to the given value.\n */\n public void setPause(boolean pause) {\n isPaused = pause;\n }\n\n\n /**\n * Returns a number [0, 1], representing progress through the duration.\n * Only used for SINGLE and LOOP timers.\n */\n public float getAlpha() {\n switch (type) {\n case LOOP:\n return (secAccumTime % secDuration) / secDuration;\n\n case SINGLE:\n return Math.min(Math.max(secAccumTime / secDuration, 0.0f), 1.0f);\n\n default:\n break;\n }\n\n return -1.0f; // Garbage.\n }\n\n ////////////////////////////////\n\n private Type type;\n private float secDuration;\n\n private boolean hasUpdated;\n private boolean isPaused;\n\n private float absPrevTime;\n private float secAccumTime;\n}"
] | import integeruser.jglsdk.glutil.MousePoles.MouseButtons;
import integeruser.jglsdk.glutil.MousePoles.ViewData;
import integeruser.jglsdk.glutil.MousePoles.ViewPole;
import integeruser.jglsdk.glutil.MousePoles.ViewScale;
import integeruser.jgltut.Tutorial;
import integeruser.jgltut.commons.*;
import integeruser.jgltut.framework.Framework;
import integeruser.jgltut.framework.Mesh;
import integeruser.jgltut.framework.MousePole;
import integeruser.jgltut.framework.Timer;
import org.joml.*;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL15;
import java.lang.Math;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;
import static org.lwjgl.opengl.GL31.*;
import static org.lwjgl.opengl.GL32.*; | package integeruser.jgltut.tut13;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
* Original: https://bitbucket.org/alfonse/gltut/src/default/Tut%2013%20Impostors/GeomImpostor.cpp
* <p>
* Part III. Illumination
* Chapter 13. Lies and Impostors
* <p>
* W,A,S,D - move the cameras forward/backwards and left/right, relative to the camera's current orientation. Holding
* SHIFT with these keys will move in smaller increments.
* Q,E - raise and lower the camera, relative to its current orientation. Holding SHIFT with these keys will move
* in smaller increments.
* P - toggle pausing on/off.
* -,= - rewind/jump forward time by 0.5 second (of real-time).
* T - toggle viewing the look-at point.
* G - toggle the drawing of the light source.
* <p>
* LEFT CLICKING and DRAGGING - rotate the camera around the target point, both horizontally and vertically.
* LEFT CLICKING and DRAGGING + CTRL - rotate the camera around the target point, either horizontally or vertically.
* LEFT CLICKING and DRAGGING + ALT - change the camera's up direction.
* WHEEL SCROLLING - move the camera closer to it's target point or farther away.
*/
public class GeomImpostor extends Tutorial {
public static void main(String[] args) {
Framework.CURRENT_TUTORIAL_DATAPATH = "/integeruser/jgltut/tut13/data/";
new GeomImpostor().start(500, 500);
}
@Override
protected void init() {
initializePrograms();
planeMesh = new Mesh("LargePlane.xml");
cubeMesh = new Mesh("UnitCube.xml");
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CW);
final float depthZNear = 0.0f;
final float depthZFar = 1.0f;
glEnable(GL_DEPTH_TEST);
glDepthMask(true);
glDepthFunc(GL_LEQUAL);
glDepthRange(depthZNear, depthZFar);
glEnable(GL_DEPTH_CLAMP);
// Setup our Uniform Buffers
lightUniformBuffer = glGenBuffers();
glBindBuffer(GL_UNIFORM_BUFFER, lightUniformBuffer);
GL15.glBufferData(GL_UNIFORM_BUFFER, LightBlock.BYTES, GL_DYNAMIC_DRAW);
projectionUniformBuffer = glGenBuffers();
glBindBuffer(GL_UNIFORM_BUFFER, projectionUniformBuffer);
glBufferData(GL_UNIFORM_BUFFER, ProjectionBlock.BYTES, GL_DYNAMIC_DRAW);
// Bind the static buffers.
glBindBufferRange(GL_UNIFORM_BUFFER, lightBlockIndex, lightUniformBuffer, 0, LightBlock.BYTES);
glBindBufferRange(GL_UNIFORM_BUFFER, projectionBlockIndex, projectionUniformBuffer, 0, ProjectionBlock.BYTES);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
imposterVBO = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, imposterVBO);
glBufferData(GL_ARRAY_BUFFER, NUMBER_OF_SPHERES * 4 * Float.BYTES, GL_STREAM_DRAW);
imposterVAO = glGenVertexArrays();
glBindVertexArray(imposterVAO);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, false, 16, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 1, GL_FLOAT, false, 16, 12);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnable(GL_PROGRAM_POINT_SIZE);
createMaterials();
glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
if (action == GLFW_PRESS) {
switch (key) {
case GLFW_KEY_P:
sphereTimer.togglePause();
break;
case GLFW_KEY_MINUS:
sphereTimer.rewind(0.5f);
break;
case GLFW_KEY_EQUAL:
sphereTimer.fastForward(0.5f);
break;
case GLFW_KEY_T:
drawCameraPos = !drawCameraPos;
break;
case GLFW_KEY_G:
drawLights = !drawLights;
break;
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, true);
break;
}
}
});
glfwSetMouseButtonCallback(window, (window, button, action, mods) -> {
boolean pressed = action == GLFW_PRESS;
glfwGetCursorPos(window, mouseBuffer1, mouseBuffer2);
int x = (int) mouseBuffer1.get(0);
int y = (int) mouseBuffer2.get(0); | MousePole.forwardMouseButton(window, viewPole, button, pressed, x, y); | 7 |
CagataySonmez/EdgeCloudSim | src/edu/boun/edgecloudsim/applications/sample_app2/SampleNetworkModel.java | [
"public class SimManager extends SimEntity {\r\n\tprivate static final int CREATE_TASK = 0;\r\n\tprivate static final int CHECK_ALL_VM = 1;\r\n\tprivate static final int GET_LOAD_LOG = 2;\r\n\tprivate static final int PRINT_PROGRESS = 3;\r\n\tprivate static final int STOP_SIMULATION = 4;\r\n\t\r\n\tprivate String simScenario;\r\n\tprivate String orchestratorPolicy;\r\n\tprivate int numOfMobileDevice;\r\n\tprivate NetworkModel networkModel;\r\n\tprivate MobilityModel mobilityModel;\r\n\tprivate ScenarioFactory scenarioFactory;\r\n\tprivate EdgeOrchestrator edgeOrchestrator;\r\n\tprivate EdgeServerManager edgeServerManager;\r\n\tprivate CloudServerManager cloudServerManager;\r\n\tprivate MobileServerManager mobileServerManager;\r\n\tprivate LoadGeneratorModel loadGeneratorModel;\r\n\tprivate MobileDeviceManager mobileDeviceManager;\r\n\t\r\n\tprivate static SimManager instance = null;\r\n\t\r\n\tpublic SimManager(ScenarioFactory _scenarioFactory, int _numOfMobileDevice, String _simScenario, String _orchestratorPolicy) throws Exception {\r\n\t\tsuper(\"SimManager\");\r\n\t\tsimScenario = _simScenario;\r\n\t\tscenarioFactory = _scenarioFactory;\r\n\t\tnumOfMobileDevice = _numOfMobileDevice;\r\n\t\torchestratorPolicy = _orchestratorPolicy;\r\n\r\n\t\tSimLogger.print(\"Creating tasks...\");\r\n\t\tloadGeneratorModel = scenarioFactory.getLoadGeneratorModel();\r\n\t\tloadGeneratorModel.initializeModel();\r\n\t\tSimLogger.printLine(\"Done, \");\r\n\t\t\r\n\t\tSimLogger.print(\"Creating device locations...\");\r\n\t\tmobilityModel = scenarioFactory.getMobilityModel();\r\n\t\tmobilityModel.initialize();\r\n\t\tSimLogger.printLine(\"Done.\");\r\n\r\n\t\t//Generate network model\r\n\t\tnetworkModel = scenarioFactory.getNetworkModel();\r\n\t\tnetworkModel.initialize();\r\n\t\t\r\n\t\t//Generate edge orchestrator\r\n\t\tedgeOrchestrator = scenarioFactory.getEdgeOrchestrator();\r\n\t\tedgeOrchestrator.initialize();\r\n\t\t\r\n\t\t//Create Physical Servers\r\n\t\tedgeServerManager = scenarioFactory.getEdgeServerManager();\r\n\t\tedgeServerManager.initialize();\r\n\t\t\r\n\t\t//Create Physical Servers on cloud\r\n\t\tcloudServerManager = scenarioFactory.getCloudServerManager();\r\n\t\tcloudServerManager.initialize();\r\n\t\t\r\n\t\t//Create Physical Servers on mobile devices\r\n\t\tmobileServerManager = scenarioFactory.getMobileServerManager();\r\n\t\tmobileServerManager.initialize();\r\n\r\n\t\t//Create Client Manager\r\n\t\tmobileDeviceManager = scenarioFactory.getMobileDeviceManager();\r\n\t\tmobileDeviceManager.initialize();\r\n\t\t\r\n\t\tinstance = this;\r\n\t}\r\n\t\r\n\tpublic static SimManager getInstance(){\r\n\t\treturn instance;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Triggering CloudSim to start simulation\r\n\t */\r\n\tpublic void startSimulation() throws Exception{\r\n\t\t//Starts the simulation\r\n\t\tSimLogger.print(super.getName()+\" is starting...\");\r\n\t\t\r\n\t\t//Start Edge Datacenters & Generate VMs\r\n\t\tedgeServerManager.startDatacenters();\r\n\t\tedgeServerManager.createVmList(mobileDeviceManager.getId());\r\n\t\t\r\n\t\t//Start Edge Datacenters & Generate VMs\r\n\t\tcloudServerManager.startDatacenters();\r\n\t\tcloudServerManager.createVmList(mobileDeviceManager.getId());\r\n\t\t\r\n\t\t//Start Mobile Datacenters & Generate VMs\r\n\t\tmobileServerManager.startDatacenters();\r\n\t\tmobileServerManager.createVmList(mobileDeviceManager.getId());\r\n\t\t\r\n\t\tCloudSim.startSimulation();\r\n\t}\r\n\r\n\tpublic String getSimulationScenario(){\r\n\t\treturn simScenario;\r\n\t}\r\n\r\n\tpublic String getOrchestratorPolicy(){\r\n\t\treturn orchestratorPolicy;\r\n\t}\r\n\t\r\n\tpublic ScenarioFactory getScenarioFactory(){\r\n\t\treturn scenarioFactory;\r\n\t}\r\n\t\r\n\tpublic int getNumOfMobileDevice(){\r\n\t\treturn numOfMobileDevice;\r\n\t}\r\n\t\r\n\tpublic NetworkModel getNetworkModel(){\r\n\t\treturn networkModel;\r\n\t}\r\n\r\n\tpublic MobilityModel getMobilityModel(){\r\n\t\treturn mobilityModel;\r\n\t}\r\n\t\r\n\tpublic EdgeOrchestrator getEdgeOrchestrator(){\r\n\t\treturn edgeOrchestrator;\r\n\t}\r\n\t\r\n\tpublic EdgeServerManager getEdgeServerManager(){\r\n\t\treturn edgeServerManager;\r\n\t}\r\n\t\r\n\tpublic CloudServerManager getCloudServerManager(){\r\n\t\treturn cloudServerManager;\r\n\t}\r\n\t\r\n\tpublic MobileServerManager getMobileServerManager(){\r\n\t\treturn mobileServerManager;\r\n\t}\r\n\r\n\tpublic LoadGeneratorModel getLoadGeneratorModel(){\r\n\t\treturn loadGeneratorModel;\r\n\t}\r\n\t\r\n\tpublic MobileDeviceManager getMobileDeviceManager(){\r\n\t\treturn mobileDeviceManager;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void startEntity() {\r\n\t\tint hostCounter=0;\r\n\r\n\t\tfor(int i= 0; i<edgeServerManager.getDatacenterList().size(); i++) {\r\n\t\t\tList<? extends Host> list = edgeServerManager.getDatacenterList().get(i).getHostList();\r\n\t\t\tfor (int j=0; j < list.size(); j++) {\r\n\t\t\t\tmobileDeviceManager.submitVmList(edgeServerManager.getVmList(hostCounter));\r\n\t\t\t\thostCounter++;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tfor(int i = 0; i<SimSettings.getInstance().getNumOfCloudHost(); i++) {\r\n\t\t\tmobileDeviceManager.submitVmList(cloudServerManager.getVmList(i));\r\n\t\t}\r\n\r\n\t\tfor(int i=0; i<numOfMobileDevice; i++){\r\n\t\t\tif(mobileServerManager.getVmList(i) != null)\r\n\t\t\t\tmobileDeviceManager.submitVmList(mobileServerManager.getVmList(i));\r\n\t\t}\r\n\t\t\r\n\t\t//Creation of tasks are scheduled here!\r\n\t\tfor(int i=0; i< loadGeneratorModel.getTaskList().size(); i++)\r\n\t\t\tschedule(getId(), loadGeneratorModel.getTaskList().get(i).getStartTime(), CREATE_TASK, loadGeneratorModel.getTaskList().get(i));\r\n\t\t\r\n\t\t//Periodic event loops starts from here!\r\n\t\tschedule(getId(), 5, CHECK_ALL_VM);\r\n\t\tschedule(getId(), SimSettings.getInstance().getSimulationTime()/100, PRINT_PROGRESS);\r\n\t\tschedule(getId(), SimSettings.getInstance().getVmLoadLogInterval(), GET_LOAD_LOG);\r\n\t\tschedule(getId(), SimSettings.getInstance().getSimulationTime(), STOP_SIMULATION);\r\n\t\t\r\n\t\tSimLogger.printLine(\"Done.\");\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void processEvent(SimEvent ev) {\r\n\t\tsynchronized(this){\r\n\t\t\tswitch (ev.getTag()) {\r\n\t\t\tcase CREATE_TASK:\r\n\t\t\t\ttry {\r\n\t\t\t\t\tTaskProperty edgeTask = (TaskProperty) ev.getData();\r\n\t\t\t\t\tmobileDeviceManager.submitTask(edgeTask);\t\t\t\t\t\t\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\tSystem.exit(1);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase CHECK_ALL_VM:\r\n\t\t\t\tint totalNumOfVm = SimSettings.getInstance().getNumOfEdgeVMs();\r\n\t\t\t\tif(EdgeVmAllocationPolicy_Custom.getCreatedVmNum() != totalNumOfVm){\r\n\t\t\t\t\tSimLogger.printLine(\"All VMs cannot be created! Terminating simulation...\");\r\n\t\t\t\t\tSystem.exit(1);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase GET_LOAD_LOG:\r\n\t\t\t\tSimLogger.getInstance().addVmUtilizationLog(\r\n\t\t\t\t\t\tCloudSim.clock(),\r\n\t\t\t\t\t\tedgeServerManager.getAvgUtilization(),\r\n\t\t\t\t\t\tcloudServerManager.getAvgUtilization(),\r\n\t\t\t\t\t\tmobileServerManager.getAvgUtilization());\r\n\t\t\t\t\r\n\t\t\t\tschedule(getId(), SimSettings.getInstance().getVmLoadLogInterval(), GET_LOAD_LOG);\r\n\t\t\t\tbreak;\r\n\t\t\tcase PRINT_PROGRESS:\r\n\t\t\t\tint progress = (int)((CloudSim.clock()*100)/SimSettings.getInstance().getSimulationTime());\r\n\t\t\t\tif(progress % 10 == 0)\r\n\t\t\t\t\tSimLogger.print(Integer.toString(progress));\r\n\t\t\t\telse\r\n\t\t\t\t\tSimLogger.print(\".\");\r\n\t\t\t\tif(CloudSim.clock() < SimSettings.getInstance().getSimulationTime())\r\n\t\t\t\t\tschedule(getId(), SimSettings.getInstance().getSimulationTime()/100, PRINT_PROGRESS);\r\n\r\n\t\t\t\tbreak;\r\n\t\t\tcase STOP_SIMULATION:\r\n\t\t\t\tSimLogger.printLine(\"100\");\r\n\t\t\t\tCloudSim.terminateSimulation();\r\n\t\t\t\ttry {\r\n\t\t\t\t\tSimLogger.getInstance().simStopped();\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\tSystem.exit(1);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tSimLogger.printLine(getName() + \": unknown event type\");\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void shutdownEntity() {\r\n\t\tedgeServerManager.terminateDatacenters();\r\n\t\tcloudServerManager.terminateDatacenters();\r\n\t\tmobileServerManager.terminateDatacenters();\r\n\t}\r\n}\r",
"public class SimSettings {\r\n\tprivate static SimSettings instance = null;\r\n\tprivate Document edgeDevicesDoc = null;\r\n\r\n\tpublic static final double CLIENT_ACTIVITY_START_TIME = 10;\r\n\r\n\t//enumarations for the VM types\r\n\tpublic static enum VM_TYPES { MOBILE_VM, EDGE_VM, CLOUD_VM }\r\n\r\n\t//enumarations for the VM types\r\n\tpublic static enum NETWORK_DELAY_TYPES { WLAN_DELAY, MAN_DELAY, WAN_DELAY, GSM_DELAY }\r\n\r\n\t//predifined IDs for the components.\r\n\tpublic static final int CLOUD_DATACENTER_ID = 1000;\r\n\tpublic static final int MOBILE_DATACENTER_ID = 1001;\r\n\tpublic static final int EDGE_ORCHESTRATOR_ID = 1002;\r\n\tpublic static final int GENERIC_EDGE_DEVICE_ID = 1003;\r\n\r\n\t//delimiter for output file.\r\n\tpublic static final String DELIMITER = \";\";\r\n\r\n\tprivate double SIMULATION_TIME; //minutes unit in properties file\r\n\tprivate double WARM_UP_PERIOD; //minutes unit in properties file\r\n\tprivate double INTERVAL_TO_GET_VM_LOAD_LOG; //minutes unit in properties file\r\n\tprivate double INTERVAL_TO_GET_LOCATION_LOG; //minutes unit in properties file\r\n\tprivate double INTERVAL_TO_GET_AP_DELAY_LOG; //minutes unit in properties file\r\n\tprivate boolean FILE_LOG_ENABLED; //boolean to check file logging option\r\n\tprivate boolean DEEP_FILE_LOG_ENABLED; //boolean to check deep file logging option\r\n\r\n\tprivate int MIN_NUM_OF_MOBILE_DEVICES;\r\n\tprivate int MAX_NUM_OF_MOBILE_DEVICES;\r\n\tprivate int MOBILE_DEVICE_COUNTER_SIZE;\r\n\tprivate int WLAN_RANGE;\r\n\r\n\tprivate int NUM_OF_EDGE_DATACENTERS;\r\n\tprivate int NUM_OF_EDGE_HOSTS;\r\n\tprivate int NUM_OF_EDGE_VMS;\r\n\tprivate int NUM_OF_PLACE_TYPES;\r\n\r\n\tprivate double WAN_PROPAGATION_DELAY; //seconds unit in properties file\r\n\tprivate double GSM_PROPAGATION_DELAY; //seconds unit in properties file\r\n\tprivate double LAN_INTERNAL_DELAY; //seconds unit in properties file\r\n\tprivate int BANDWITH_WLAN; //Mbps unit in properties file\r\n\tprivate int BANDWITH_MAN; //Mbps unit in properties file\r\n\tprivate int BANDWITH_WAN; //Mbps unit in properties file\r\n\tprivate int BANDWITH_GSM; //Mbps unit in properties file\r\n\r\n\tprivate int NUM_OF_HOST_ON_CLOUD_DATACENTER;\r\n\tprivate int NUM_OF_VM_ON_CLOUD_HOST;\r\n\tprivate int CORE_FOR_CLOUD_VM;\r\n\tprivate int MIPS_FOR_CLOUD_VM; //MIPS\r\n\tprivate int RAM_FOR_CLOUD_VM; //MB\r\n\tprivate int STORAGE_FOR_CLOUD_VM; //Byte\r\n\r\n\tprivate int CORE_FOR_VM;\r\n\tprivate int MIPS_FOR_VM; //MIPS\r\n\tprivate int RAM_FOR_VM; //MB\r\n\tprivate int STORAGE_FOR_VM; //Byte\r\n\r\n\tprivate String[] SIMULATION_SCENARIOS;\r\n\tprivate String[] ORCHESTRATOR_POLICIES;\r\n\r\n\tprivate double NORTHERN_BOUND;\r\n\tprivate double EASTERN_BOUND;\r\n\tprivate double SOUTHERN_BOUND;\r\n\tprivate double WESTERN_BOUND;\r\n\r\n\t// mean waiting time (minute) is stored for each place types\r\n\tprivate double[] mobilityLookUpTable;\r\n\r\n\t// following values are stored for each applications defined in applications.xml\r\n\t// [0] usage percentage (%)\r\n\t// [1] prob. of selecting cloud (%)\r\n\t// [2] poisson mean (sec)\r\n\t// [3] active period (sec)\r\n\t// [4] idle period (sec)\r\n\t// [5] avg data upload (KB)\r\n\t// [6] avg data download (KB)\r\n\t// [7] avg task length (MI)\r\n\t// [8] required # of cores\r\n\t// [9] vm utilization on edge (%)\r\n\t// [10] vm utilization on cloud (%)\r\n\t// [11] vm utilization on mobile (%)\r\n\t// [12] delay sensitivity [0-1]\r\n\tprivate double[][] taskLookUpTable = null;\r\n\r\n\tprivate String[] taskNames = null;\r\n\r\n\tprivate SimSettings() {\r\n\t\tNUM_OF_PLACE_TYPES = 0;\r\n\t}\r\n\r\n\tpublic static SimSettings getInstance() {\r\n\t\tif(instance == null) {\r\n\t\t\tinstance = new SimSettings();\r\n\t\t}\r\n\t\treturn instance;\r\n\t}\r\n\r\n\t/**\r\n\t * Reads configuration file and stores information to local variables\r\n\t * @param propertiesFile\r\n\t * @return\r\n\t */\r\n\tpublic boolean initialize(String propertiesFile, String edgeDevicesFile, String applicationsFile){\r\n\t\tboolean result = false;\r\n\t\tInputStream input = null;\r\n\t\ttry {\r\n\t\t\tinput = new FileInputStream(propertiesFile);\r\n\r\n\t\t\t// load a properties file\r\n\t\t\tProperties prop = new Properties();\r\n\t\t\tprop.load(input);\r\n\r\n\t\t\tSIMULATION_TIME = (double)60 * Double.parseDouble(prop.getProperty(\"simulation_time\")); //seconds\r\n\t\t\tWARM_UP_PERIOD = (double)60 * Double.parseDouble(prop.getProperty(\"warm_up_period\")); //seconds\r\n\t\t\tINTERVAL_TO_GET_VM_LOAD_LOG = (double)60 * Double.parseDouble(prop.getProperty(\"vm_load_check_interval\")); //seconds\r\n\t\t\tINTERVAL_TO_GET_LOCATION_LOG = (double)60 * Double.parseDouble(prop.getProperty(\"location_check_interval\")); //seconds\r\n\t\t\tINTERVAL_TO_GET_AP_DELAY_LOG = (double)60 * Double.parseDouble(prop.getProperty(\"ap_delay_check_interval\", \"0\")); //seconds\t\t\r\n\t\t\tFILE_LOG_ENABLED = Boolean.parseBoolean(prop.getProperty(\"file_log_enabled\"));\r\n\t\t\tDEEP_FILE_LOG_ENABLED = Boolean.parseBoolean(prop.getProperty(\"deep_file_log_enabled\"));\r\n\r\n\t\t\tMIN_NUM_OF_MOBILE_DEVICES = Integer.parseInt(prop.getProperty(\"min_number_of_mobile_devices\"));\r\n\t\t\tMAX_NUM_OF_MOBILE_DEVICES = Integer.parseInt(prop.getProperty(\"max_number_of_mobile_devices\"));\r\n\t\t\tMOBILE_DEVICE_COUNTER_SIZE = Integer.parseInt(prop.getProperty(\"mobile_device_counter_size\"));\r\n\t\t\tWLAN_RANGE = Integer.parseInt(prop.getProperty(\"wlan_range\", \"0\"));\r\n\r\n\t\t\tWAN_PROPAGATION_DELAY = Double.parseDouble(prop.getProperty(\"wan_propagation_delay\", \"0\"));\r\n\t\t\tGSM_PROPAGATION_DELAY = Double.parseDouble(prop.getProperty(\"gsm_propagation_delay\", \"0\"));\r\n\t\t\tLAN_INTERNAL_DELAY = Double.parseDouble(prop.getProperty(\"lan_internal_delay\", \"0\"));\r\n\t\t\tBANDWITH_WLAN = 1000 * Integer.parseInt(prop.getProperty(\"wlan_bandwidth\"));\r\n\t\t\tBANDWITH_MAN = 1000 * Integer.parseInt(prop.getProperty(\"man_bandwidth\", \"0\"));\r\n\t\t\tBANDWITH_WAN = 1000 * Integer.parseInt(prop.getProperty(\"wan_bandwidth\", \"0\"));\r\n\t\t\tBANDWITH_GSM = 1000 * Integer.parseInt(prop.getProperty(\"gsm_bandwidth\", \"0\"));\r\n\r\n\t\t\tNUM_OF_HOST_ON_CLOUD_DATACENTER = Integer.parseInt(prop.getProperty(\"number_of_host_on_cloud_datacenter\"));\r\n\t\t\tNUM_OF_VM_ON_CLOUD_HOST = Integer.parseInt(prop.getProperty(\"number_of_vm_on_cloud_host\"));\r\n\t\t\tCORE_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"core_for_cloud_vm\"));\r\n\t\t\tMIPS_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"mips_for_cloud_vm\"));\r\n\t\t\tRAM_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"ram_for_cloud_vm\"));\r\n\t\t\tSTORAGE_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"storage_for_cloud_vm\"));\r\n\r\n\t\t\tRAM_FOR_VM = Integer.parseInt(prop.getProperty(\"ram_for_mobile_vm\"));\r\n\t\t\tCORE_FOR_VM = Integer.parseInt(prop.getProperty(\"core_for_mobile_vm\"));\r\n\t\t\tMIPS_FOR_VM = Integer.parseInt(prop.getProperty(\"mips_for_mobile_vm\"));\r\n\t\t\tSTORAGE_FOR_VM = Integer.parseInt(prop.getProperty(\"storage_for_mobile_vm\"));\r\n\r\n\t\t\tORCHESTRATOR_POLICIES = prop.getProperty(\"orchestrator_policies\").split(\",\");\r\n\r\n\t\t\tSIMULATION_SCENARIOS = prop.getProperty(\"simulation_scenarios\").split(\",\");\r\n\r\n\t\t\tNORTHERN_BOUND = Double.parseDouble(prop.getProperty(\"northern_bound\", \"0\"));\r\n\t\t\tSOUTHERN_BOUND = Double.parseDouble(prop.getProperty(\"southern_bound\", \"0\"));\r\n\t\t\tEASTERN_BOUND = Double.parseDouble(prop.getProperty(\"eastern_bound\", \"0\"));\r\n\t\t\tWESTERN_BOUND = Double.parseDouble(prop.getProperty(\"western_bound\", \"0\"));\r\n\r\n\t\t\t//avg waiting time in a place (min)\r\n\t\t\tdouble place1_mean_waiting_time = Double.parseDouble(prop.getProperty(\"attractiveness_L1_mean_waiting_time\"));\r\n\t\t\tdouble place2_mean_waiting_time = Double.parseDouble(prop.getProperty(\"attractiveness_L2_mean_waiting_time\"));\r\n\t\t\tdouble place3_mean_waiting_time = Double.parseDouble(prop.getProperty(\"attractiveness_L3_mean_waiting_time\"));\r\n\r\n\t\t\t//mean waiting time (minute)\r\n\t\t\tmobilityLookUpTable = new double[]{\r\n\t\t\t\t\tplace1_mean_waiting_time, //ATTRACTIVENESS_L1\r\n\t\t\t\t\tplace2_mean_waiting_time, //ATTRACTIVENESS_L2\r\n\t\t\t\t\tplace3_mean_waiting_time //ATTRACTIVENESS_L3\r\n\t\t\t};\r\n\r\n\r\n\t\t} catch (IOException ex) {\r\n\t\t\tex.printStackTrace();\r\n\t\t} finally {\r\n\t\t\tif (input != null) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tinput.close();\r\n\t\t\t\t\tresult = true;\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tparseApplicationsXML(applicationsFile);\r\n\t\tparseEdgeDevicesXML(edgeDevicesFile);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the parsed XML document for edge_devices.xml\r\n\t */\r\n\tpublic Document getEdgeDevicesDocument(){\r\n\t\treturn edgeDevicesDoc;\r\n\t}\r\n\r\n\r\n\t/**\r\n\t * returns simulation time (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getSimulationTime()\r\n\t{\r\n\t\treturn SIMULATION_TIME;\r\n\t}\r\n\r\n\t/**\r\n\t * returns warm up period (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getWarmUpPeriod()\r\n\t{\r\n\t\treturn WARM_UP_PERIOD; \r\n\t}\r\n\r\n\t/**\r\n\t * returns VM utilization log collection interval (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getVmLoadLogInterval()\r\n\t{\r\n\t\treturn INTERVAL_TO_GET_VM_LOAD_LOG; \r\n\t}\r\n\r\n\t/**\r\n\t * returns VM location log collection interval (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getLocationLogInterval()\r\n\t{\r\n\t\treturn INTERVAL_TO_GET_LOCATION_LOG; \r\n\t}\r\n\r\n\t/**\r\n\t * returns VM location log collection interval (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getApDelayLogInterval()\r\n\t{\r\n\t\treturn INTERVAL_TO_GET_AP_DELAY_LOG; \r\n\t}\r\n\r\n\t/**\r\n\t * returns deep statistics logging status from properties file\r\n\t */\r\n\tpublic boolean getDeepFileLoggingEnabled()\r\n\t{\r\n\t\treturn FILE_LOG_ENABLED && DEEP_FILE_LOG_ENABLED; \r\n\t}\r\n\r\n\t/**\r\n\t * returns deep statistics logging status from properties file\r\n\t */\r\n\tpublic boolean getFileLoggingEnabled()\r\n\t{\r\n\t\treturn FILE_LOG_ENABLED; \r\n\t}\r\n\r\n\t/**\r\n\t * returns WAN propagation delay (in second unit) from properties file\r\n\t */\r\n\tpublic double getWanPropagationDelay()\r\n\t{\r\n\t\treturn WAN_PROPAGATION_DELAY;\r\n\t}\r\n\r\n\t/**\r\n\t * returns GSM propagation delay (in second unit) from properties file\r\n\t */\r\n\tpublic double getGsmPropagationDelay()\r\n\t{\r\n\t\treturn GSM_PROPAGATION_DELAY;\r\n\t}\r\n\r\n\t/**\r\n\t * returns internal LAN propagation delay (in second unit) from properties file\r\n\t */\r\n\tpublic double getInternalLanDelay()\r\n\t{\r\n\t\treturn LAN_INTERNAL_DELAY;\r\n\t}\r\n\r\n\t/**\r\n\t * returns WLAN bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getWlanBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_WLAN;\r\n\t}\r\n\r\n\t/**\r\n\t * returns MAN bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getManBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_MAN;\r\n\t}\r\n\r\n\t/**\r\n\t * returns WAN bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getWanBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_WAN; \r\n\t}\r\n\r\n\t/**\r\n\t * returns GSM bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getGsmBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_GSM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the minimum number of the mobile devices used in the simulation\r\n\t */\r\n\tpublic int getMinNumOfMobileDev()\r\n\t{\r\n\t\treturn MIN_NUM_OF_MOBILE_DEVICES;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the maximum number of the mobile devices used in the simulation\r\n\t */\r\n\tpublic int getMaxNumOfMobileDev()\r\n\t{\r\n\t\treturn MAX_NUM_OF_MOBILE_DEVICES;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of increase on mobile devices\r\n\t * while iterating from min to max mobile device\r\n\t */\r\n\tpublic int getMobileDevCounterSize()\r\n\t{\r\n\t\treturn MOBILE_DEVICE_COUNTER_SIZE;\r\n\t}\r\n\r\n\t/**\r\n\t * returns edge device range in meter\r\n\t */\r\n\tpublic int getWlanRange()\r\n\t{\r\n\t\treturn WLAN_RANGE;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of edge datacenters\r\n\t */\r\n\tpublic int getNumOfEdgeDatacenters()\r\n\t{\r\n\t\treturn NUM_OF_EDGE_DATACENTERS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of edge hosts running on the datacenters\r\n\t */\r\n\tpublic int getNumOfEdgeHosts()\r\n\t{\r\n\t\treturn NUM_OF_EDGE_HOSTS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of edge VMs running on the hosts\r\n\t */\r\n\tpublic int getNumOfEdgeVMs()\r\n\t{\r\n\t\treturn NUM_OF_EDGE_VMS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of different place types\r\n\t */\r\n\tpublic int getNumOfPlaceTypes()\r\n\t{\r\n\t\treturn NUM_OF_PLACE_TYPES;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cloud datacenters\r\n\t */\r\n\tpublic int getNumOfCloudHost()\r\n\t{\r\n\t\treturn NUM_OF_HOST_ON_CLOUD_DATACENTER;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cloud VMs per Host\r\n\t */\r\n\tpublic int getNumOfCloudVMsPerHost()\r\n\t{\r\n\t\treturn NUM_OF_VM_ON_CLOUD_HOST;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the total number of cloud VMs\r\n\t */\r\n\tpublic int getNumOfCloudVMs()\r\n\t{\r\n\t\treturn NUM_OF_VM_ON_CLOUD_HOST * NUM_OF_HOST_ON_CLOUD_DATACENTER;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cores for cloud VMs\r\n\t */\r\n\tpublic int getCoreForCloudVM()\r\n\t{\r\n\t\treturn CORE_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns MIPS of the central cloud VMs\r\n\t */\r\n\tpublic int getMipsForCloudVM()\r\n\t{\r\n\t\treturn MIPS_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns RAM of the central cloud VMs\r\n\t */\r\n\tpublic int getRamForCloudVM()\r\n\t{\r\n\t\treturn RAM_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns Storage of the central cloud VMs\r\n\t */\r\n\tpublic int getStorageForCloudVM()\r\n\t{\r\n\t\treturn STORAGE_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns RAM of the mobile (processing unit) VMs\r\n\t */\r\n\tpublic int getRamForMobileVM()\r\n\t{\r\n\t\treturn RAM_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cores for mobile VMs\r\n\t */\r\n\tpublic int getCoreForMobileVM()\r\n\t{\r\n\t\treturn CORE_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns MIPS of the mobile (processing unit) VMs\r\n\t */\r\n\tpublic int getMipsForMobileVM()\r\n\t{\r\n\t\treturn MIPS_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns Storage of the mobile (processing unit) VMs\r\n\t */\r\n\tpublic int getStorageForMobileVM()\r\n\t{\r\n\t\treturn STORAGE_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns simulation screnarios as string\r\n\t */\r\n\tpublic String[] getSimulationScenarios()\r\n\t{\r\n\t\treturn SIMULATION_SCENARIOS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns orchestrator policies as string\r\n\t */\r\n\tpublic String[] getOrchestratorPolicies()\r\n\t{\r\n\t\treturn ORCHESTRATOR_POLICIES;\r\n\t}\r\n\r\n\r\n\tpublic double getNorthernBound() {\r\n\t\treturn NORTHERN_BOUND;\r\n\t}\r\n\r\n\tpublic double getEasternBound() {\r\n\t\treturn EASTERN_BOUND;\r\n\t}\r\n\r\n\tpublic double getSouthernBound() {\r\n\t\treturn SOUTHERN_BOUND;\r\n\t}\r\n\r\n\tpublic double getWesternBound() {\r\n\t\treturn WESTERN_BOUND;\r\n\t}\r\n\r\n\t/**\r\n\t * returns mobility characteristic within an array\r\n\t * the result includes mean waiting time (minute) or each place type\r\n\t */ \r\n\tpublic double[] getMobilityLookUpTable()\r\n\t{\r\n\t\treturn mobilityLookUpTable;\r\n\t}\r\n\r\n\t/**\r\n\t * returns application characteristic within two dimensional array\r\n\t * the result includes the following values for each application type\r\n\t * [0] usage percentage (%)\r\n\t * [1] prob. of selecting cloud (%)\r\n\t * [2] poisson mean (sec)\r\n\t * [3] active period (sec)\r\n\t * [4] idle period (sec)\r\n\t * [5] avg data upload (KB)\r\n\t * [6] avg data download (KB)\r\n\t * [7] avg task length (MI)\r\n\t * [8] required # of cores\r\n\t * [9] vm utilization on edge (%)\r\n\t * [10] vm utilization on cloud (%)\r\n\t * [11] vm utilization on mobile (%)\r\n\t * [12] delay sensitivity [0-1]\r\n\t * [13] maximum delay requirement (sec)\r\n\t */ \r\n\tpublic double[][] getTaskLookUpTable()\r\n\t{\r\n\t\treturn taskLookUpTable;\r\n\t}\r\n\r\n\tpublic double[] getTaskProperties(String taskName) {\r\n\t\tdouble[] result = null;\r\n\t\tint index = -1;\r\n\t\tfor (int i=0;i<taskNames.length;i++) {\r\n\t\t\tif (taskNames[i].equals(taskName)) {\r\n\t\t\t\tindex = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(index >= 0 && index < taskLookUpTable.length)\r\n\t\t\tresult = taskLookUpTable[index];\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpublic String getTaskName(int taskType)\r\n\t{\r\n\t\treturn taskNames[taskType];\r\n\t}\r\n\r\n\tprivate void isAttributePresent(Element element, String key) {\r\n\t\tString value = element.getAttribute(key);\r\n\t\tif (value.isEmpty() || value == null){\r\n\t\t\tthrow new IllegalArgumentException(\"Attribute '\" + key + \"' is not found in '\" + element.getNodeName() +\"'\");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void isElementPresent(Element element, String key) {\r\n\t\ttry {\r\n\t\t\tString value = element.getElementsByTagName(key).item(0).getTextContent();\r\n\t\t\tif (value.isEmpty() || value == null){\r\n\t\t\t\tthrow new IllegalArgumentException(\"Element '\" + key + \"' is not found in '\" + element.getNodeName() +\"'\");\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new IllegalArgumentException(\"Element '\" + key + \"' is not found in '\" + element.getNodeName() +\"'\");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate Boolean checkElement(Element element, String key) {\r\n\t\tBoolean result = true;\r\n\t\ttry {\r\n\t\t\tString value = element.getElementsByTagName(key).item(0).getTextContent();\r\n\t\t\tif (value.isEmpty() || value == null){\r\n\t\t\t\tresult = false;\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tresult = false;\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tprivate void parseApplicationsXML(String filePath)\r\n\t{\r\n\t\tDocument doc = null;\r\n\t\ttry {\t\r\n\t\t\tFile devicesFile = new File(filePath);\r\n\t\t\tDocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\r\n\t\t\tDocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\r\n\t\t\tdoc = dBuilder.parse(devicesFile);\r\n\t\t\tdoc.getDocumentElement().normalize();\r\n\r\n\t\t\tString mandatoryAttributes[] = {\r\n\t\t\t\t\t\"usage_percentage\", //usage percentage [0-100]\r\n\t\t\t\t\t\"prob_cloud_selection\", //prob. of selecting cloud [0-100]\r\n\t\t\t\t\t\"poisson_interarrival\", //poisson mean (sec)\r\n\t\t\t\t\t\"active_period\", //active period (sec)\r\n\t\t\t\t\t\"idle_period\", //idle period (sec)\r\n\t\t\t\t\t\"data_upload\", //avg data upload (KB)\r\n\t\t\t\t\t\"data_download\", //avg data download (KB)\r\n\t\t\t\t\t\"task_length\", //avg task length (MI)\r\n\t\t\t\t\t\"required_core\", //required # of core\r\n\t\t\t\t\t\"vm_utilization_on_edge\", //vm utilization on edge vm [0-100]\r\n\t\t\t\t\t\"vm_utilization_on_cloud\", //vm utilization on cloud vm [0-100]\r\n\t\t\t\t\t\"vm_utilization_on_mobile\", //vm utilization on mobile vm [0-100]\r\n\t\t\t\"delay_sensitivity\"}; //delay_sensitivity [0-1]\r\n\r\n\t\t\tString optionalAttributes[] = {\r\n\t\t\t\"max_delay_requirement\"}; //maximum delay requirement (sec)\r\n\r\n\t\t\tNodeList appList = doc.getElementsByTagName(\"application\");\r\n\t\t\ttaskLookUpTable = new double[appList.getLength()]\r\n\t\t\t\t\t[mandatoryAttributes.length + optionalAttributes.length];\r\n\r\n\t\t\ttaskNames = new String[appList.getLength()];\r\n\t\t\tfor (int i = 0; i < appList.getLength(); i++) {\r\n\t\t\t\tNode appNode = appList.item(i);\r\n\r\n\t\t\t\tElement appElement = (Element) appNode;\r\n\t\t\t\tisAttributePresent(appElement, \"name\");\r\n\t\t\t\tString taskName = appElement.getAttribute(\"name\");\r\n\t\t\t\ttaskNames[i] = taskName;\r\n\r\n\t\t\t\tfor(int m=0; m<mandatoryAttributes.length; m++){\r\n\t\t\t\t\tisElementPresent(appElement, mandatoryAttributes[m]);\r\n\t\t\t\t\ttaskLookUpTable[i][m] = Double.parseDouble(appElement.\r\n\t\t\t\t\t\t\tgetElementsByTagName(mandatoryAttributes[m]).item(0).getTextContent());\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfor(int o=0; o<optionalAttributes.length; o++){\r\n\t\t\t\t\tdouble value = 0;\r\n\t\t\t\t\tif(checkElement(appElement, optionalAttributes[o]))\r\n\t\t\t\t\t\tvalue = Double.parseDouble(appElement.getElementsByTagName(optionalAttributes[o]).item(0).getTextContent());\r\n\r\n\t\t\t\t\ttaskLookUpTable[i][mandatoryAttributes.length + o] = value;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tSimLogger.printLine(\"Edge Devices XML cannot be parsed! Terminating simulation...\");\r\n\t\t\te.printStackTrace();\r\n\t\t\tSystem.exit(1);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void parseEdgeDevicesXML(String filePath)\r\n\t{\r\n\t\ttry {\t\r\n\t\t\tFile devicesFile = new File(filePath);\r\n\t\t\tDocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\r\n\t\t\tDocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\r\n\t\t\tedgeDevicesDoc = dBuilder.parse(devicesFile);\r\n\t\t\tedgeDevicesDoc.getDocumentElement().normalize();\r\n\r\n\t\t\tNodeList datacenterList = edgeDevicesDoc.getElementsByTagName(\"datacenter\");\r\n\t\t\tfor (int i = 0; i < datacenterList.getLength(); i++) {\r\n\t\t\t\tNUM_OF_EDGE_DATACENTERS++;\r\n\t\t\t\tNode datacenterNode = datacenterList.item(i);\r\n\r\n\t\t\t\tElement datacenterElement = (Element) datacenterNode;\r\n\t\t\t\tisAttributePresent(datacenterElement, \"arch\");\r\n\t\t\t\tisAttributePresent(datacenterElement, \"os\");\r\n\t\t\t\tisAttributePresent(datacenterElement, \"vmm\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerBw\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerSec\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerMem\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerStorage\");\r\n\r\n\t\t\t\tElement location = (Element)datacenterElement.getElementsByTagName(\"location\").item(0);\r\n\t\t\t\tisElementPresent(location, \"attractiveness\");\r\n\t\t\t\tisElementPresent(location, \"wlan_id\");\r\n\t\t\t\tisElementPresent(location, \"x_pos\");\r\n\t\t\t\tisElementPresent(location, \"y_pos\");\r\n\r\n\t\t\t\tString attractiveness = location.getElementsByTagName(\"attractiveness\").item(0).getTextContent();\r\n\t\t\t\tint placeTypeIndex = Integer.parseInt(attractiveness);\r\n\t\t\t\tif(NUM_OF_PLACE_TYPES < placeTypeIndex+1)\r\n\t\t\t\t\tNUM_OF_PLACE_TYPES = placeTypeIndex+1;\r\n\r\n\t\t\t\tNodeList hostList = datacenterElement.getElementsByTagName(\"host\");\r\n\t\t\t\tfor (int j = 0; j < hostList.getLength(); j++) {\r\n\t\t\t\t\tNUM_OF_EDGE_HOSTS++;\r\n\t\t\t\t\tNode hostNode = hostList.item(j);\r\n\r\n\t\t\t\t\tElement hostElement = (Element) hostNode;\r\n\t\t\t\t\tisElementPresent(hostElement, \"core\");\r\n\t\t\t\t\tisElementPresent(hostElement, \"mips\");\r\n\t\t\t\t\tisElementPresent(hostElement, \"ram\");\r\n\t\t\t\t\tisElementPresent(hostElement, \"storage\");\r\n\r\n\t\t\t\t\tNodeList vmList = hostElement.getElementsByTagName(\"VM\");\r\n\t\t\t\t\tfor (int k = 0; k < vmList.getLength(); k++) {\r\n\t\t\t\t\t\tNUM_OF_EDGE_VMS++;\r\n\t\t\t\t\t\tNode vmNode = vmList.item(k);\r\n\r\n\t\t\t\t\t\tElement vmElement = (Element) vmNode;\r\n\t\t\t\t\t\tisAttributePresent(vmElement, \"vmm\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"core\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"mips\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"ram\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"storage\");\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t} catch (Exception e) {\r\n\t\t\tSimLogger.printLine(\"Edge Devices XML cannot be parsed! Terminating simulation...\");\r\n\t\t\te.printStackTrace();\r\n\t\t\tSystem.exit(1);\r\n\t\t}\r\n\t}\r\n}\r",
"public class Task extends Cloudlet {\r\n\tprivate Location submittedLocation;\r\n\tprivate double creationTime;\r\n\tprivate int type;\r\n\tprivate int mobileDeviceId;\r\n\tprivate int hostIndex;\r\n\tprivate int vmIndex;\r\n\tprivate int datacenterId;\r\n\r\n\tpublic Task(int _mobileDeviceId, int cloudletId, long cloudletLength, int pesNumber,\r\n\t\t\tlong cloudletFileSize, long cloudletOutputSize,\r\n\t\t\tUtilizationModel utilizationModelCpu,\r\n\t\t\tUtilizationModel utilizationModelRam,\r\n\t\t\tUtilizationModel utilizationModelBw) {\r\n\t\tsuper(cloudletId, cloudletLength, pesNumber, cloudletFileSize,\r\n\t\t\t\tcloudletOutputSize, utilizationModelCpu, utilizationModelRam,\r\n\t\t\t\tutilizationModelBw);\r\n\t\t\r\n\t\tmobileDeviceId = _mobileDeviceId;\r\n\t\tcreationTime = CloudSim.clock();\r\n\t}\r\n\r\n\t\r\n\tpublic void setSubmittedLocation(Location _submittedLocation){\r\n\t\tsubmittedLocation =_submittedLocation;\r\n\t}\r\n\r\n\tpublic void setAssociatedDatacenterId(int _datacenterId){\r\n\t\tdatacenterId=_datacenterId;\r\n\t}\r\n\t\r\n\tpublic void setAssociatedHostId(int _hostIndex){\r\n\t\thostIndex=_hostIndex;\r\n\t}\r\n\r\n\tpublic void setAssociatedVmId(int _vmIndex){\r\n\t\tvmIndex=_vmIndex;\r\n\t}\r\n\t\r\n\tpublic void setTaskType(int _type){\r\n\t\ttype=_type;\r\n\t}\r\n\r\n\tpublic int getMobileDeviceId(){\r\n\t\treturn mobileDeviceId;\r\n\t}\r\n\t\r\n\tpublic Location getSubmittedLocation(){\r\n\t\treturn submittedLocation;\r\n\t}\r\n\t\r\n\tpublic int getAssociatedDatacenterId(){\r\n\t\treturn datacenterId;\r\n\t}\r\n\t\r\n\tpublic int getAssociatedHostId(){\r\n\t\treturn hostIndex;\r\n\t}\r\n\r\n\tpublic int getAssociatedVmId(){\r\n\t\treturn vmIndex;\r\n\t}\r\n\t\r\n\tpublic int getTaskType(){\r\n\t\treturn type;\r\n\t}\r\n\t\r\n\tpublic double getCreationTime() {\r\n\t\treturn creationTime;\r\n\t}\r\n}\r",
"public abstract class NetworkModel {\r\n\tprotected int numberOfMobileDevices;\r\n\tprotected String simScenario;\r\n\r\n\tpublic NetworkModel(int _numberOfMobileDevices, String _simScenario){\r\n\t\tnumberOfMobileDevices=_numberOfMobileDevices;\r\n\t\tsimScenario = _simScenario;\r\n\t};\r\n\r\n\t/**\r\n\t * initializes custom network model\r\n\t */\r\n\tpublic abstract void initialize();\r\n\r\n\t/**\r\n\t * calculates the upload delay from source to destination device\r\n\t */\r\n\tpublic abstract double getUploadDelay(int sourceDeviceId, int destDeviceId, Task task);\r\n\r\n\t/**\r\n\t * calculates the download delay from source to destination device\r\n\t */\r\n\tpublic abstract double getDownloadDelay(int sourceDeviceId, int destDeviceId, Task task);\r\n\r\n\t/**\r\n\t * Mobile device manager should inform network manager about the network operation\r\n\t * This information may be important for some network delay models\r\n\t */\r\n\tpublic abstract void uploadStarted(Location accessPointLocation, int destDeviceId);\r\n\tpublic abstract void uploadFinished(Location accessPointLocation, int destDeviceId);\r\n\tpublic abstract void downloadStarted(Location accessPointLocation, int sourceDeviceId);\r\n\tpublic abstract void downloadFinished(Location accessPointLocation, int sourceDeviceId);\r\n}\r",
"public class Location {\r\n\tprivate int xPos;\r\n\tprivate int yPos;\r\n\tprivate int servingWlanId;\r\n\tprivate int placeTypeIndex;\r\n\tpublic Location(int _placeTypeIndex, int _servingWlanId, int _xPos, int _yPos){\r\n\t\tservingWlanId = _servingWlanId;\r\n\t\tplaceTypeIndex=_placeTypeIndex;\r\n\t\txPos = _xPos;\r\n\t\tyPos = _yPos;\r\n\t}\r\n\t\r\n\t/*\r\n\t * Default Constructor: Creates an empty Location\r\n\t */\r\n\tpublic Location() {\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic boolean equals(Object other){\r\n\t\tboolean result = false;\r\n\t if (other == null) return false;\r\n\t if (!(other instanceof Location))return false;\r\n\t if (other == this) return true;\r\n\t \r\n\t Location otherLocation = (Location)other;\r\n\t if(this.xPos == otherLocation.xPos && this.yPos == otherLocation.yPos)\r\n\t \tresult = true;\r\n\r\n\t return result;\r\n\t}\r\n\r\n\tpublic int getServingWlanId(){\r\n\t\treturn servingWlanId;\r\n\t}\r\n\t\r\n\tpublic int getPlaceTypeIndex(){\r\n\t\treturn placeTypeIndex;\r\n\t}\r\n\t\r\n\tpublic int getXPos(){\r\n\t\treturn xPos;\r\n\t}\r\n\t\r\n\tpublic int getYPos(){\r\n\t\treturn yPos;\r\n\t}\r\n}\r",
"public class SimLogger {\r\n\tpublic static enum TASK_STATUS {\r\n\t\tCREATED, UPLOADING, PROCESSING, DOWNLOADING, COMLETED,\r\n\t\tREJECTED_DUE_TO_VM_CAPACITY, REJECTED_DUE_TO_BANDWIDTH,\r\n\t\tUNFINISHED_DUE_TO_BANDWIDTH, UNFINISHED_DUE_TO_MOBILITY,\r\n\t\tREJECTED_DUE_TO_WLAN_COVERAGE\r\n\t}\r\n\t\r\n\tpublic static enum NETWORK_ERRORS {\r\n\t\tLAN_ERROR, MAN_ERROR, WAN_ERROR, GSM_ERROR, NONE\r\n\t}\r\n\r\n\tprivate long startTime;\r\n\tprivate long endTime;\r\n\tprivate static boolean fileLogEnabled;\r\n\tprivate static boolean printLogEnabled;\r\n\tprivate String filePrefix;\r\n\tprivate String outputFolder;\r\n\tprivate Map<Integer, LogItem> taskMap;\r\n\tprivate LinkedList<VmLoadLogItem> vmLoadList;\r\n\tprivate LinkedList<ApDelayLogItem> apDelayList;\r\n\r\n\tprivate static SimLogger singleton = new SimLogger();\r\n\t\r\n\tprivate int numOfAppTypes;\r\n\t\r\n\tprivate File successFile = null, failFile = null;\r\n\tprivate FileWriter successFW = null, failFW = null;\r\n\tprivate BufferedWriter successBW = null, failBW = null;\r\n\r\n\t// extract following values for each app type.\r\n\t// last index is average of all app types\r\n\tprivate int[] uncompletedTask = null;\r\n\tprivate int[] uncompletedTaskOnCloud = null;\r\n\tprivate int[] uncompletedTaskOnEdge = null;\r\n\tprivate int[] uncompletedTaskOnMobile = null;\r\n\r\n\tprivate int[] completedTask = null;\r\n\tprivate int[] completedTaskOnCloud = null;\r\n\tprivate int[] completedTaskOnEdge = null;\r\n\tprivate int[] completedTaskOnMobile = null;\r\n\r\n\tprivate int[] failedTask = null;\r\n\tprivate int[] failedTaskOnCloud = null;\r\n\tprivate int[] failedTaskOnEdge = null;\r\n\tprivate int[] failedTaskOnMobile = null;\r\n\r\n\tprivate double[] networkDelay = null;\r\n\tprivate double[] gsmDelay = null;\r\n\tprivate double[] wanDelay = null;\r\n\tprivate double[] manDelay = null;\r\n\tprivate double[] lanDelay = null;\r\n\t\r\n\tprivate double[] gsmUsage = null;\r\n\tprivate double[] wanUsage = null;\r\n\tprivate double[] manUsage = null;\r\n\tprivate double[] lanUsage = null;\r\n\r\n\tprivate double[] serviceTime = null;\r\n\tprivate double[] serviceTimeOnCloud = null;\r\n\tprivate double[] serviceTimeOnEdge = null;\r\n\tprivate double[] serviceTimeOnMobile = null;\r\n\r\n\tprivate double[] processingTime = null;\r\n\tprivate double[] processingTimeOnCloud = null;\r\n\tprivate double[] processingTimeOnEdge = null;\r\n\tprivate double[] processingTimeOnMobile = null;\r\n\r\n\tprivate int[] failedTaskDueToVmCapacity = null;\r\n\tprivate int[] failedTaskDueToVmCapacityOnCloud = null;\r\n\tprivate int[] failedTaskDueToVmCapacityOnEdge = null;\r\n\tprivate int[] failedTaskDueToVmCapacityOnMobile = null;\r\n\t\r\n\tprivate double[] cost = null;\r\n\tprivate double[] QoE = null;\r\n\tprivate int[] failedTaskDuetoBw = null;\r\n\tprivate int[] failedTaskDuetoLanBw = null;\r\n\tprivate int[] failedTaskDuetoManBw = null;\r\n\tprivate int[] failedTaskDuetoWanBw = null;\r\n\tprivate int[] failedTaskDuetoGsmBw = null;\r\n\tprivate int[] failedTaskDuetoMobility = null;\r\n\tprivate int[] refectedTaskDuetoWlanRange = null;\r\n\t\r\n\tprivate double[] orchestratorOverhead = null;\r\n\r\n\t/*\r\n\t * A private Constructor prevents any other class from instantiating.\r\n\t */\r\n\tprivate SimLogger() {\r\n\t\tfileLogEnabled = false;\r\n\t\tprintLogEnabled = false;\r\n\t}\r\n\r\n\t/* Static 'instance' method */\r\n\tpublic static SimLogger getInstance() {\r\n\t\treturn singleton;\r\n\t}\r\n\r\n\tpublic static void enableFileLog() {\r\n\t\tfileLogEnabled = true;\r\n\t}\r\n\r\n\tpublic static void enablePrintLog() {\r\n\t\tprintLogEnabled = true;\r\n\t}\r\n\r\n\tpublic static boolean isFileLogEnabled() {\r\n\t\treturn fileLogEnabled;\r\n\t}\r\n\r\n\tpublic static void disableFileLog() {\r\n\t\tfileLogEnabled = false;\r\n\t}\r\n\t\r\n\tpublic static void disablePrintLog() {\r\n\t\tprintLogEnabled = false;\r\n\t}\r\n\t\r\n\tpublic String getOutputFolder() {\r\n\t\treturn outputFolder;\r\n\t}\r\n\r\n\tprivate void appendToFile(BufferedWriter bw, String line) throws IOException {\r\n\t\tbw.write(line);\r\n\t\tbw.newLine();\r\n\t}\r\n\r\n\tpublic static void printLine(String msg) {\r\n\t\tif (printLogEnabled)\r\n\t\t\tSystem.out.println(msg);\r\n\t}\r\n\r\n\tpublic static void print(String msg) {\r\n\t\tif (printLogEnabled)\r\n\t\t\tSystem.out.print(msg);\r\n\t}\r\n\r\n\tpublic void simStarted(String outFolder, String fileName) {\r\n\t\tstartTime = System.currentTimeMillis();\r\n\t\tfilePrefix = fileName;\r\n\t\toutputFolder = outFolder;\r\n\t\ttaskMap = new HashMap<Integer, LogItem>();\r\n\t\tvmLoadList = new LinkedList<VmLoadLogItem>();\r\n\t\tapDelayList = new LinkedList<ApDelayLogItem>();\r\n\t\t\r\n\t\tnumOfAppTypes = SimSettings.getInstance().getTaskLookUpTable().length;\r\n\t\t\r\n\t\tif (SimSettings.getInstance().getDeepFileLoggingEnabled()) {\r\n\t\t\ttry {\r\n\t\t\t\tsuccessFile = new File(outputFolder, filePrefix + \"_SUCCESS.log\");\r\n\t\t\t\tsuccessFW = new FileWriter(successFile, true);\r\n\t\t\t\tsuccessBW = new BufferedWriter(successFW);\r\n\r\n\t\t\t\tfailFile = new File(outputFolder, filePrefix + \"_FAIL.log\");\r\n\t\t\t\tfailFW = new FileWriter(failFile, true);\r\n\t\t\t\tfailBW = new BufferedWriter(failFW);\r\n\t\t\t\t\r\n\t\t\t\tappendToFile(successBW, \"#auto generated file!\");\r\n\t\t\t\tappendToFile(failBW, \"#auto generated file!\");\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t\tSystem.exit(1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// extract following values for each app type.\r\n\t\t// last index is average of all app types\r\n\t\tuncompletedTask = new int[numOfAppTypes + 1];\r\n\t\tuncompletedTaskOnCloud = new int[numOfAppTypes + 1];\r\n\t\tuncompletedTaskOnEdge = new int[numOfAppTypes + 1];\r\n\t\tuncompletedTaskOnMobile = new int[numOfAppTypes + 1];\r\n\r\n\t\tcompletedTask = new int[numOfAppTypes + 1];\r\n\t\tcompletedTaskOnCloud = new int[numOfAppTypes + 1];\r\n\t\tcompletedTaskOnEdge = new int[numOfAppTypes + 1];\r\n\t\tcompletedTaskOnMobile = new int[numOfAppTypes + 1];\r\n\r\n\t\tfailedTask = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskOnCloud = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskOnEdge = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskOnMobile = new int[numOfAppTypes + 1];\r\n\r\n\t\tnetworkDelay = new double[numOfAppTypes + 1];\r\n\t\tgsmDelay = new double[numOfAppTypes + 1];\r\n\t\twanDelay = new double[numOfAppTypes + 1];\r\n\t\tmanDelay = new double[numOfAppTypes + 1];\r\n\t\tlanDelay = new double[numOfAppTypes + 1];\r\n\t\t\r\n\t\tgsmUsage = new double[numOfAppTypes + 1];\r\n\t\twanUsage = new double[numOfAppTypes + 1];\r\n\t\tmanUsage = new double[numOfAppTypes + 1];\r\n\t\tlanUsage = new double[numOfAppTypes + 1];\r\n\r\n\t\tserviceTime = new double[numOfAppTypes + 1];\r\n\t\tserviceTimeOnCloud = new double[numOfAppTypes + 1];\r\n\t\tserviceTimeOnEdge = new double[numOfAppTypes + 1];\r\n\t\tserviceTimeOnMobile = new double[numOfAppTypes + 1];\r\n\r\n\t\tprocessingTime = new double[numOfAppTypes + 1];\r\n\t\tprocessingTimeOnCloud = new double[numOfAppTypes + 1];\r\n\t\tprocessingTimeOnEdge = new double[numOfAppTypes + 1];\r\n\t\tprocessingTimeOnMobile = new double[numOfAppTypes + 1];\r\n\r\n\t\tfailedTaskDueToVmCapacity = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDueToVmCapacityOnCloud = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDueToVmCapacityOnEdge = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDueToVmCapacityOnMobile = new int[numOfAppTypes + 1];\r\n\t\t\r\n\t\tcost = new double[numOfAppTypes + 1];\r\n\t\tQoE = new double[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoLanBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoManBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoWanBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoGsmBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoMobility = new int[numOfAppTypes + 1];\r\n\t\trefectedTaskDuetoWlanRange = new int[numOfAppTypes + 1];\r\n\r\n\t\torchestratorOverhead = new double[numOfAppTypes + 1];\r\n\t}\r\n\r\n\tpublic void addLog(int deviceId, int taskId, int taskType,\r\n\t\t\tint taskLenght, int taskInputType, int taskOutputSize) {\r\n\t\t// printLine(taskId+\"->\"+taskStartTime);\r\n\t\ttaskMap.put(taskId, new LogItem(deviceId, taskType, taskLenght, taskInputType, taskOutputSize));\r\n\t}\r\n\r\n\tpublic void taskStarted(int taskId, double time) {\r\n\t\ttaskMap.get(taskId).taskStarted(time);\r\n\t}\r\n\r\n\tpublic void setUploadDelay(int taskId, double delay, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).setUploadDelay(delay, delayType);\r\n\t}\r\n\r\n\tpublic void setDownloadDelay(int taskId, double delay, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).setDownloadDelay(delay, delayType);\r\n\t}\r\n\t\r\n\tpublic void taskAssigned(int taskId, int datacenterId, int hostId, int vmId, int vmType) {\r\n\t\ttaskMap.get(taskId).taskAssigned(datacenterId, hostId, vmId, vmType);\r\n\t}\r\n\r\n\tpublic void taskExecuted(int taskId) {\r\n\t\ttaskMap.get(taskId).taskExecuted();\r\n\t}\r\n\r\n\tpublic void taskEnded(int taskId, double time) {\r\n\t\ttaskMap.get(taskId).taskEnded(time);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void rejectedDueToVMCapacity(int taskId, double time, int vmType) {\r\n\t\ttaskMap.get(taskId).taskRejectedDueToVMCapacity(time, vmType);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n public void rejectedDueToWlanCoverage(int taskId, double time, int vmType) {\r\n \ttaskMap.get(taskId).taskRejectedDueToWlanCoverage(time, vmType);\r\n\t\trecordLog(taskId);\r\n }\r\n \r\n\tpublic void rejectedDueToBandwidth(int taskId, double time, int vmType, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).taskRejectedDueToBandwidth(time, vmType, delayType);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void failedDueToBandwidth(int taskId, double time, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).taskFailedDueToBandwidth(time, delayType);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void failedDueToMobility(int taskId, double time) {\r\n\t\ttaskMap.get(taskId).taskFailedDueToMobility(time);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void setQoE(int taskId, double QoE){\r\n\t\ttaskMap.get(taskId).setQoE(QoE);\r\n\t}\r\n\t\r\n\tpublic void setOrchestratorOverhead(int taskId, double overhead){\r\n\t\ttaskMap.get(taskId).setOrchestratorOverhead(overhead);\r\n\t}\r\n\r\n\tpublic void addVmUtilizationLog(double time, double loadOnEdge, double loadOnCloud, double loadOnMobile) {\r\n\t\tif(SimSettings.getInstance().getLocationLogInterval() != 0)\r\n\t\t\tvmLoadList.add(new VmLoadLogItem(time, loadOnEdge, loadOnCloud, loadOnMobile));\r\n\t}\r\n\r\n\tpublic void addApDelayLog(double time, double[] apUploadDelays, double[] apDownloadDelays) {\r\n\t\tif(SimSettings.getInstance().getApDelayLogInterval() != 0)\r\n\t\t\tapDelayList.add(new ApDelayLogItem(time, apUploadDelays, apDownloadDelays));\r\n\t}\r\n\t\r\n\tpublic void simStopped() throws IOException {\r\n\t\tendTime = System.currentTimeMillis();\r\n\t\tFile vmLoadFile = null, locationFile = null, apUploadDelayFile = null, apDownloadDelayFile = null;\r\n\t\tFileWriter vmLoadFW = null, locationFW = null, apUploadDelayFW = null, apDownloadDelayFW = null;\r\n\t\tBufferedWriter vmLoadBW = null, locationBW = null, apUploadDelayBW = null, apDownloadDelayBW = null;\r\n\r\n\t\t// Save generic results to file for each app type. last index is average\r\n\t\t// of all app types\r\n\t\tFile[] genericFiles = new File[numOfAppTypes + 1];\r\n\t\tFileWriter[] genericFWs = new FileWriter[numOfAppTypes + 1];\r\n\t\tBufferedWriter[] genericBWs = new BufferedWriter[numOfAppTypes + 1];\r\n\r\n\t\t// open all files and prepare them for write\r\n\t\tif (fileLogEnabled) {\r\n\t\t\tvmLoadFile = new File(outputFolder, filePrefix + \"_VM_LOAD.log\");\r\n\t\t\tvmLoadFW = new FileWriter(vmLoadFile, true);\r\n\t\t\tvmLoadBW = new BufferedWriter(vmLoadFW);\r\n\r\n\t\t\tlocationFile = new File(outputFolder, filePrefix + \"_LOCATION.log\");\r\n\t\t\tlocationFW = new FileWriter(locationFile, true);\r\n\t\t\tlocationBW = new BufferedWriter(locationFW);\r\n\r\n\t\t\tapUploadDelayFile = new File(outputFolder, filePrefix + \"_AP_UPLOAD_DELAY.log\");\r\n\t\t\tapUploadDelayFW = new FileWriter(apUploadDelayFile, true);\r\n\t\t\tapUploadDelayBW = new BufferedWriter(apUploadDelayFW);\r\n\r\n\t\t\tapDownloadDelayFile = new File(outputFolder, filePrefix + \"_AP_DOWNLOAD_DELAY.log\");\r\n\t\t\tapDownloadDelayFW = new FileWriter(apDownloadDelayFile, true);\r\n\t\t\tapDownloadDelayBW = new BufferedWriter(apDownloadDelayFW);\r\n\r\n\t\t\tfor (int i = 0; i < numOfAppTypes + 1; i++) {\r\n\t\t\t\tString fileName = \"ALL_APPS_GENERIC.log\";\r\n\r\n\t\t\t\tif (i < numOfAppTypes) {\r\n\t\t\t\t\t// if related app is not used in this simulation, just discard it\r\n\t\t\t\t\tif (SimSettings.getInstance().getTaskLookUpTable()[i][0] == 0)\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfileName = SimSettings.getInstance().getTaskName(i) + \"_GENERIC.log\";\r\n\t\t\t\t}\r\n\r\n\t\t\t\tgenericFiles[i] = new File(outputFolder, filePrefix + \"_\" + fileName);\r\n\t\t\t\tgenericFWs[i] = new FileWriter(genericFiles[i], true);\r\n\t\t\t\tgenericBWs[i] = new BufferedWriter(genericFWs[i]);\r\n\t\t\t\tappendToFile(genericBWs[i], \"#auto generated file!\");\r\n\t\t\t}\r\n\r\n\t\t\tappendToFile(vmLoadBW, \"#auto generated file!\");\r\n\t\t\tappendToFile(locationBW, \"#auto generated file!\");\r\n\t\t\tappendToFile(apUploadDelayBW, \"#auto generated file!\");\r\n\t\t\tappendToFile(apDownloadDelayBW, \"#auto generated file!\");\r\n\t\t}\r\n\r\n\t\t//the tasks in the map is not completed yet!\r\n\t\tfor (Map.Entry<Integer, LogItem> entry : taskMap.entrySet()) {\r\n\t\t\tLogItem value = entry.getValue();\r\n\r\n\t\t\tuncompletedTask[value.getTaskType()]++;\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tuncompletedTaskOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tuncompletedTaskOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tuncompletedTaskOnEdge[value.getTaskType()]++;\r\n\t\t}\r\n\r\n\t\t// calculate total values\r\n\t\tuncompletedTask[numOfAppTypes] = IntStream.of(uncompletedTask).sum();\r\n\t\tuncompletedTaskOnCloud[numOfAppTypes] = IntStream.of(uncompletedTaskOnCloud).sum();\r\n\t\tuncompletedTaskOnEdge[numOfAppTypes] = IntStream.of(uncompletedTaskOnEdge).sum();\r\n\t\tuncompletedTaskOnMobile[numOfAppTypes] = IntStream.of(uncompletedTaskOnMobile).sum();\r\n\r\n\t\tcompletedTask[numOfAppTypes] = IntStream.of(completedTask).sum();\r\n\t\tcompletedTaskOnCloud[numOfAppTypes] = IntStream.of(completedTaskOnCloud).sum();\r\n\t\tcompletedTaskOnEdge[numOfAppTypes] = IntStream.of(completedTaskOnEdge).sum();\r\n\t\tcompletedTaskOnMobile[numOfAppTypes] = IntStream.of(completedTaskOnMobile).sum();\r\n\r\n\t\tfailedTask[numOfAppTypes] = IntStream.of(failedTask).sum();\r\n\t\tfailedTaskOnCloud[numOfAppTypes] = IntStream.of(failedTaskOnCloud).sum();\r\n\t\tfailedTaskOnEdge[numOfAppTypes] = IntStream.of(failedTaskOnEdge).sum();\r\n\t\tfailedTaskOnMobile[numOfAppTypes] = IntStream.of(failedTaskOnMobile).sum();\r\n\r\n\t\tnetworkDelay[numOfAppTypes] = DoubleStream.of(networkDelay).sum();\r\n\t\tlanDelay[numOfAppTypes] = DoubleStream.of(lanDelay).sum();\r\n\t\tmanDelay[numOfAppTypes] = DoubleStream.of(manDelay).sum();\r\n\t\twanDelay[numOfAppTypes] = DoubleStream.of(wanDelay).sum();\r\n\t\tgsmDelay[numOfAppTypes] = DoubleStream.of(gsmDelay).sum();\r\n\t\t\r\n\t\tlanUsage[numOfAppTypes] = DoubleStream.of(lanUsage).sum();\r\n\t\tmanUsage[numOfAppTypes] = DoubleStream.of(manUsage).sum();\r\n\t\twanUsage[numOfAppTypes] = DoubleStream.of(wanUsage).sum();\r\n\t\tgsmUsage[numOfAppTypes] = DoubleStream.of(gsmUsage).sum();\r\n\r\n\t\tserviceTime[numOfAppTypes] = DoubleStream.of(serviceTime).sum();\r\n\t\tserviceTimeOnCloud[numOfAppTypes] = DoubleStream.of(serviceTimeOnCloud).sum();\r\n\t\tserviceTimeOnEdge[numOfAppTypes] = DoubleStream.of(serviceTimeOnEdge).sum();\r\n\t\tserviceTimeOnMobile[numOfAppTypes] = DoubleStream.of(serviceTimeOnMobile).sum();\r\n\r\n\t\tprocessingTime[numOfAppTypes] = DoubleStream.of(processingTime).sum();\r\n\t\tprocessingTimeOnCloud[numOfAppTypes] = DoubleStream.of(processingTimeOnCloud).sum();\r\n\t\tprocessingTimeOnEdge[numOfAppTypes] = DoubleStream.of(processingTimeOnEdge).sum();\r\n\t\tprocessingTimeOnMobile[numOfAppTypes] = DoubleStream.of(processingTimeOnMobile).sum();\r\n\r\n\t\tfailedTaskDueToVmCapacity[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacity).sum();\r\n\t\tfailedTaskDueToVmCapacityOnCloud[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacityOnCloud).sum();\r\n\t\tfailedTaskDueToVmCapacityOnEdge[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacityOnEdge).sum();\r\n\t\tfailedTaskDueToVmCapacityOnMobile[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacityOnMobile).sum();\r\n\t\t\r\n\t\tcost[numOfAppTypes] = DoubleStream.of(cost).sum();\r\n\t\tQoE[numOfAppTypes] = DoubleStream.of(QoE).sum();\r\n\t\tfailedTaskDuetoBw[numOfAppTypes] = IntStream.of(failedTaskDuetoBw).sum();\r\n\t\tfailedTaskDuetoGsmBw[numOfAppTypes] = IntStream.of(failedTaskDuetoGsmBw).sum();\r\n\t\tfailedTaskDuetoWanBw[numOfAppTypes] = IntStream.of(failedTaskDuetoWanBw).sum();\r\n\t\tfailedTaskDuetoManBw[numOfAppTypes] = IntStream.of(failedTaskDuetoManBw).sum();\r\n\t\tfailedTaskDuetoLanBw[numOfAppTypes] = IntStream.of(failedTaskDuetoLanBw).sum();\r\n\t\tfailedTaskDuetoMobility[numOfAppTypes] = IntStream.of(failedTaskDuetoMobility).sum();\r\n\t\trefectedTaskDuetoWlanRange[numOfAppTypes] = IntStream.of(refectedTaskDuetoWlanRange).sum();\r\n\r\n\t\torchestratorOverhead[numOfAppTypes] = DoubleStream.of(orchestratorOverhead).sum();\r\n\t\t\r\n\t\t// calculate server load\r\n\t\tdouble totalVmLoadOnEdge = 0;\r\n\t\tdouble totalVmLoadOnCloud = 0;\r\n\t\tdouble totalVmLoadOnMobile = 0;\r\n\t\tfor (VmLoadLogItem entry : vmLoadList) {\r\n\t\t\ttotalVmLoadOnEdge += entry.getEdgeLoad();\r\n\t\t\ttotalVmLoadOnCloud += entry.getCloudLoad();\r\n\t\t\ttotalVmLoadOnMobile += entry.getMobileLoad();\r\n\t\t\tif (fileLogEnabled && SimSettings.getInstance().getVmLoadLogInterval() != 0)\r\n\t\t\t\tappendToFile(vmLoadBW, entry.toString());\r\n\t\t}\r\n\r\n\t\tif (fileLogEnabled) {\r\n\t\t\t// write location info to file for each location\r\n\t\t\t// assuming each location has only one access point\r\n\t\t\tdouble locationLogInterval = SimSettings.getInstance().getLocationLogInterval();\r\n\t\t\tif(locationLogInterval != 0) {\r\n\t\t\t\tfor (int t = 1; t < (SimSettings.getInstance().getSimulationTime() / locationLogInterval); t++) {\r\n\t\t\t\t\tint[] locationInfo = new int[SimSettings.getInstance().getNumOfEdgeDatacenters()];\r\n\t\t\t\t\tDouble time = t * SimSettings.getInstance().getLocationLogInterval();\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (time < SimSettings.CLIENT_ACTIVITY_START_TIME)\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (int i = 0; i < SimManager.getInstance().getNumOfMobileDevice(); i++) {\r\n\t\t\t\t\t\tLocation loc = SimManager.getInstance().getMobilityModel().getLocation(i, time);\r\n\t\t\t\t\t\tlocationInfo[loc.getServingWlanId()]++;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tlocationBW.write(time.toString());\r\n\t\t\t\t\tfor (int i = 0; i < locationInfo.length; i++)\r\n\t\t\t\t\t\tlocationBW.write(SimSettings.DELIMITER + locationInfo[i]);\r\n\r\n\t\t\t\t\tlocationBW.newLine();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// write delay info to file for each access point\r\n\t\t\tif(SimSettings.getInstance().getApDelayLogInterval() != 0) {\r\n\t\t\t\tfor (ApDelayLogItem entry : apDelayList) {\r\n\t\t\t\t\tappendToFile(apUploadDelayBW, entry.getUploadStat());\r\n\t\t\t\t\tappendToFile(apDownloadDelayBW, entry.getDownloadStat());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfor (int i = 0; i < numOfAppTypes + 1; i++) {\r\n\r\n\t\t\t\tif (i < numOfAppTypes) {\r\n\t\t\t\t\t// if related app is not used in this simulation, just discard it\r\n\t\t\t\t\tif (SimSettings.getInstance().getTaskLookUpTable()[i][0] == 0)\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by\r\n\t\t\t\t// zero problem\r\n\t\t\t\tdouble _serviceTime = (completedTask[i] == 0) ? 0.0 : (serviceTime[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _networkDelay = (completedTask[i] == 0) ? 0.0 : (networkDelay[i] / ((double) completedTask[i] - (double)completedTaskOnMobile[i]));\r\n\t\t\t\tdouble _processingTime = (completedTask[i] == 0) ? 0.0 : (processingTime[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _vmLoadOnEdge = (vmLoadList.size() == 0) ? 0.0 : (totalVmLoadOnEdge / (double) vmLoadList.size());\r\n\t\t\t\tdouble _vmLoadOnClould = (vmLoadList.size() == 0) ? 0.0 : (totalVmLoadOnCloud / (double) vmLoadList.size());\r\n\t\t\t\tdouble _vmLoadOnMobile = (vmLoadList.size() == 0) ? 0.0 : (totalVmLoadOnMobile / (double) vmLoadList.size());\r\n\t\t\t\tdouble _cost = (completedTask[i] == 0) ? 0.0 : (cost[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _QoE1 = (completedTask[i] == 0) ? 0.0 : (QoE[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _QoE2 = (completedTask[i] == 0) ? 0.0 : (QoE[i] / (double) (failedTask[i] + completedTask[i]));\r\n\r\n\t\t\t\tdouble _lanDelay = (lanUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (lanDelay[i] / (double) lanUsage[i]);\r\n\t\t\t\tdouble _manDelay = (manUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (manDelay[i] / (double) manUsage[i]);\r\n\t\t\t\tdouble _wanDelay = (wanUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (wanDelay[i] / (double) wanUsage[i]);\r\n\t\t\t\tdouble _gsmDelay = (gsmUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (gsmDelay[i] / (double) gsmUsage[i]);\r\n\t\t\t\t\r\n\t\t\t\t// write generic results\r\n\t\t\t\tString genericResult1 = Integer.toString(completedTask[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTask[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTask[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTime) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_processingTime) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_networkDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(0) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_cost) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacity[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoMobility[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_QoE1) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_QoE2) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(refectedTaskDuetoWlanRange[i]);\r\n\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by zero problem\r\n\t\t\t\tdouble _serviceTimeOnEdge = (completedTaskOnEdge[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (serviceTimeOnEdge[i] / (double) completedTaskOnEdge[i]);\r\n\t\t\t\tdouble _processingTimeOnEdge = (completedTaskOnEdge[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (processingTimeOnEdge[i] / (double) completedTaskOnEdge[i]);\r\n\t\t\t\tString genericResult2 = Integer.toString(completedTaskOnEdge[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskOnEdge[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTaskOnEdge[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTimeOnEdge) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_processingTimeOnEdge) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(0.0) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_vmLoadOnEdge) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacityOnEdge[i]);\r\n\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by zero problem\r\n\t\t\t\tdouble _serviceTimeOnCloud = (completedTaskOnCloud[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (serviceTimeOnCloud[i] / (double) completedTaskOnCloud[i]);\r\n\t\t\t\tdouble _processingTimeOnCloud = (completedTaskOnCloud[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (processingTimeOnCloud[i] / (double) completedTaskOnCloud[i]);\r\n\t\t\t\tString genericResult3 = Integer.toString(completedTaskOnCloud[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskOnCloud[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTaskOnCloud[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTimeOnCloud) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_processingTimeOnCloud) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(0.0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_vmLoadOnClould) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacityOnCloud[i]);\r\n\t\t\t\t\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by zero problem\r\n\t\t\t\tdouble _serviceTimeOnMobile = (completedTaskOnMobile[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (serviceTimeOnMobile[i] / (double) completedTaskOnMobile[i]);\r\n\t\t\t\tdouble _processingTimeOnMobile = (completedTaskOnMobile[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (processingTimeOnMobile[i] / (double) completedTaskOnMobile[i]);\r\n\t\t\t\tString genericResult4 = Integer.toString(completedTaskOnMobile[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskOnMobile[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTaskOnMobile[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTimeOnMobile) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_processingTimeOnMobile) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(0.0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_vmLoadOnMobile) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacityOnMobile[i]);\r\n\t\t\t\t\r\n\t\t\t\tString genericResult5 = Double.toString(_lanDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_manDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_wanDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_gsmDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoLanBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoManBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoWanBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoGsmBw[i]);\r\n\t\t\t\t\r\n\t\t\t\t//performance related values\r\n\t\t\t\tdouble _orchestratorOverhead = orchestratorOverhead[i] / (double) (failedTask[i] + completedTask[i]);\r\n\t\t\t\t\r\n\t\t\t\tString genericResult6 = Long.toString((endTime-startTime)/60) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_orchestratorOverhead);\r\n\t\t\t\t\t\t\r\n\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult1);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult2);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult3);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult4);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult5);\r\n\t\t\t\t\r\n\t\t\t\t//append performance related values only to ALL_ALLPS file\r\n\t\t\t\tif(i == numOfAppTypes) {\r\n\t\t\t\t\tappendToFile(genericBWs[i], genericResult6);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tprintLine(SimSettings.getInstance().getTaskName(i));\r\n\t\t\t\t\tprintLine(\"# of tasks (Edge/Cloud): \"\r\n\t\t\t\t\t\t\t+ (failedTask[i] + completedTask[i]) + \"(\"\r\n\t\t\t\t\t\t\t+ (failedTaskOnEdge[i] + completedTaskOnEdge[i]) + \"/\" \r\n\t\t\t\t\t\t\t+ (failedTaskOnCloud[i]+ completedTaskOnCloud[i]) + \")\" );\r\n\t\t\t\t\t\r\n\t\t\t\t\tprintLine(\"# of failed tasks (Edge/Cloud): \"\r\n\t\t\t\t\t\t\t+ failedTask[i] + \"(\"\r\n\t\t\t\t\t\t\t+ failedTaskOnEdge[i] + \"/\"\r\n\t\t\t\t\t\t\t+ failedTaskOnCloud[i] + \")\");\r\n\t\t\t\t\t\r\n\t\t\t\t\tprintLine(\"# of completed tasks (Edge/Cloud): \"\r\n\t\t\t\t\t\t\t+ completedTask[i] + \"(\"\r\n\t\t\t\t\t\t\t+ completedTaskOnEdge[i] + \"/\"\r\n\t\t\t\t\t\t\t+ completedTaskOnCloud[i] + \")\");\r\n\t\t\t\t\t\r\n\t\t\t\t\tprintLine(\"---------------------------------------\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// close open files\r\n\t\t\tif (SimSettings.getInstance().getDeepFileLoggingEnabled()) {\r\n\t\t\t\tsuccessBW.close();\r\n\t\t\t\tfailBW.close();\r\n\t\t\t}\r\n\t\t\tvmLoadBW.close();\r\n\t\t\tlocationBW.close();\r\n\t\t\tapUploadDelayBW.close();\r\n\t\t\tapDownloadDelayBW.close();\r\n\t\t\tfor (int i = 0; i < numOfAppTypes + 1; i++) {\r\n\t\t\t\tif (i < numOfAppTypes) {\r\n\t\t\t\t\t// if related app is not used in this simulation, just\r\n\t\t\t\t\t// discard it\r\n\t\t\t\t\tif (SimSettings.getInstance().getTaskLookUpTable()[i][0] == 0)\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tgenericBWs[i].close();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\r\n\t\t// printout important results\r\n\t\tprintLine(\"# of tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ (failedTask[numOfAppTypes] + completedTask[numOfAppTypes]) + \"(\"\r\n\t\t\t\t+ (failedTaskOnEdge[numOfAppTypes] + completedTaskOnEdge[numOfAppTypes]) + \"/\" \r\n\t\t\t\t+ (failedTaskOnCloud[numOfAppTypes]+ completedTaskOnCloud[numOfAppTypes]) + \"/\" \r\n\t\t\t\t+ (failedTaskOnMobile[numOfAppTypes]+ completedTaskOnMobile[numOfAppTypes]) + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of failed tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ failedTask[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ failedTaskOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskOnMobile[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of completed tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ completedTask[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ completedTaskOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ completedTaskOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ completedTaskOnMobile[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of uncompleted tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ uncompletedTask[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ uncompletedTaskOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ uncompletedTaskOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ uncompletedTaskOnMobile[numOfAppTypes] + \")\");\r\n\r\n\t\tprintLine(\"# of failed tasks due to vm capacity (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ failedTaskDueToVmCapacity[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ failedTaskDueToVmCapacityOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskDueToVmCapacityOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskDueToVmCapacityOnMobile[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of failed tasks due to Mobility/WLAN Range/Network(WLAN/MAN/WAN/GSM): \"\r\n\t\t\t\t+ failedTaskDuetoMobility[numOfAppTypes]\r\n\t\t\t\t+ \"/\" + refectedTaskDuetoWlanRange[numOfAppTypes]\r\n\t\t\t\t+ \"/\" + failedTaskDuetoBw[numOfAppTypes] \r\n\t\t\t\t+ \"(\" + failedTaskDuetoLanBw[numOfAppTypes] \r\n\t\t\t\t+ \"/\" + failedTaskDuetoManBw[numOfAppTypes] \r\n\t\t\t\t+ \"/\" + failedTaskDuetoWanBw[numOfAppTypes] \r\n\t\t\t\t+ \"/\" + failedTaskDuetoGsmBw[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"percentage of failed tasks: \"\r\n\t\t\t\t+ String.format(\"%.6f\", ((double) failedTask[numOfAppTypes] * (double) 100)\r\n\t\t\t\t\t\t/ (double) (completedTask[numOfAppTypes] + failedTask[numOfAppTypes]))\r\n\t\t\t\t+ \"%\");\r\n\r\n\t\tprintLine(\"average service time: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTime[numOfAppTypes] / (double) completedTask[numOfAppTypes])\r\n\t\t\t\t+ \" seconds. (\" + \"on Edge: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTimeOnEdge[numOfAppTypes] / (double) completedTaskOnEdge[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Cloud: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTimeOnCloud[numOfAppTypes] / (double) completedTaskOnCloud[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Mobile: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTimeOnMobile[numOfAppTypes] / (double) completedTaskOnMobile[numOfAppTypes])\r\n\t\t\t\t+ \")\");\r\n\r\n\t\tprintLine(\"average processing time: \"\r\n\t\t\t\t+ String.format(\"%.6f\", processingTime[numOfAppTypes] / (double) completedTask[numOfAppTypes])\r\n\t\t\t\t+ \" seconds. (\" + \"on Edge: \"\r\n\t\t\t\t+ String.format(\"%.6f\", processingTimeOnEdge[numOfAppTypes] / (double) completedTaskOnEdge[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Cloud: \" \r\n\t\t\t\t+ String.format(\"%.6f\", processingTimeOnCloud[numOfAppTypes] / (double) completedTaskOnCloud[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Mobile: \" \r\n\t\t\t\t+ String.format(\"%.6f\", processingTimeOnMobile[numOfAppTypes] / (double) completedTaskOnMobile[numOfAppTypes])\r\n\t\t\t\t+ \")\");\r\n\r\n\t\tprintLine(\"average network delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", networkDelay[numOfAppTypes] / ((double) completedTask[numOfAppTypes] - (double) completedTaskOnMobile[numOfAppTypes]))\r\n\t\t\t\t+ \" seconds. (\" + \"LAN delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", lanDelay[numOfAppTypes] / (double) lanUsage[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"MAN delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", manDelay[numOfAppTypes] / (double) manUsage[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"WAN delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", wanDelay[numOfAppTypes] / (double) wanUsage[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"GSM delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", gsmDelay[numOfAppTypes] / (double) gsmUsage[numOfAppTypes]) + \")\");\r\n\r\n\t\tprintLine(\"average server utilization Edge/Cloud/Mobile: \" \r\n\t\t\t\t+ String.format(\"%.6f\", totalVmLoadOnEdge / (double) vmLoadList.size()) + \"/\"\r\n\t\t\t\t+ String.format(\"%.6f\", totalVmLoadOnCloud / (double) vmLoadList.size()) + \"/\"\r\n\t\t\t\t+ String.format(\"%.6f\", totalVmLoadOnMobile / (double) vmLoadList.size()));\r\n\r\n\t\tprintLine(\"average cost: \" + cost[numOfAppTypes] / completedTask[numOfAppTypes] + \"$\");\r\n\t\tprintLine(\"average overhead: \" + orchestratorOverhead[numOfAppTypes] / (failedTask[numOfAppTypes] + completedTask[numOfAppTypes]) + \" ns\");\r\n\t\tprintLine(\"average QoE (for all): \" + QoE[numOfAppTypes] / (failedTask[numOfAppTypes] + completedTask[numOfAppTypes]) + \"%\");\r\n\t\tprintLine(\"average QoE (for executed): \" + QoE[numOfAppTypes] / completedTask[numOfAppTypes] + \"%\");\r\n\r\n\t\t// clear related collections (map list etc.)\r\n\t\ttaskMap.clear();\r\n\t\tvmLoadList.clear();\r\n\t\tapDelayList.clear();\r\n\t}\r\n\t\r\n\tprivate void recordLog(int taskId){\r\n\t\tLogItem value = taskMap.remove(taskId);\r\n\t\t\r\n\t\tif (value.isInWarmUpPeriod())\r\n\t\t\treturn;\r\n\r\n\t\tif (value.getStatus() == SimLogger.TASK_STATUS.COMLETED) {\r\n\t\t\tcompletedTask[value.getTaskType()]++;\r\n\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tcompletedTaskOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tcompletedTaskOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tcompletedTaskOnEdge[value.getTaskType()]++;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tfailedTask[value.getTaskType()]++;\r\n\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tfailedTaskOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tfailedTaskOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tfailedTaskOnEdge[value.getTaskType()]++;\r\n\t\t}\r\n\r\n\t\tif (value.getStatus() == SimLogger.TASK_STATUS.COMLETED) {\r\n\t\t\tcost[value.getTaskType()] += value.getCost();\r\n\t\t\tQoE[value.getTaskType()] += value.getQoE();\r\n\t\t\tserviceTime[value.getTaskType()] += value.getServiceTime();\r\n\t\t\tnetworkDelay[value.getTaskType()] += value.getNetworkDelay();\r\n\t\t\tprocessingTime[value.getTaskType()] += (value.getServiceTime() - value.getNetworkDelay());\r\n\t\t\torchestratorOverhead[value.getTaskType()] += value.getOrchestratorOverhead();\r\n\t\t\t\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.WLAN_DELAY) != 0) {\r\n\t\t\t\tlanUsage[value.getTaskType()]++;\r\n\t\t\t\tlanDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.WLAN_DELAY);\r\n\t\t\t}\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.MAN_DELAY) != 0) {\r\n\t\t\t\tmanUsage[value.getTaskType()]++;\r\n\t\t\t\tmanDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.MAN_DELAY);\r\n\t\t\t}\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.WAN_DELAY) != 0) {\r\n\t\t\t\twanUsage[value.getTaskType()]++;\r\n\t\t\t\twanDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.WAN_DELAY);\r\n\t\t\t}\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.GSM_DELAY) != 0) {\r\n\t\t\t\tgsmUsage[value.getTaskType()]++;\r\n\t\t\t\tgsmDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.GSM_DELAY);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal()) {\r\n\t\t\t\tserviceTimeOnCloud[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t\tprocessingTimeOnCloud[value.getTaskType()] += (value.getServiceTime() - value.getNetworkDelay());\r\n\t\t\t}\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal()) {\r\n\t\t\t\tserviceTimeOnMobile[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t\tprocessingTimeOnMobile[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tserviceTimeOnEdge[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t\tprocessingTimeOnEdge[value.getTaskType()] += (value.getServiceTime() - value.getNetworkDelay());\r\n\t\t\t}\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.REJECTED_DUE_TO_VM_CAPACITY) {\r\n\t\t\tfailedTaskDueToVmCapacity[value.getTaskType()]++;\r\n\t\t\t\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tfailedTaskDueToVmCapacityOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tfailedTaskDueToVmCapacityOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tfailedTaskDueToVmCapacityOnEdge[value.getTaskType()]++;\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.REJECTED_DUE_TO_BANDWIDTH\r\n\t\t\t\t|| value.getStatus() == SimLogger.TASK_STATUS.UNFINISHED_DUE_TO_BANDWIDTH) {\r\n\t\t\tfailedTaskDuetoBw[value.getTaskType()]++;\r\n\t\t\tif (value.getNetworkError() == NETWORK_ERRORS.LAN_ERROR)\r\n\t\t\t\tfailedTaskDuetoLanBw[value.getTaskType()]++;\r\n\t\t\telse if (value.getNetworkError() == NETWORK_ERRORS.MAN_ERROR)\r\n\t\t\t\tfailedTaskDuetoManBw[value.getTaskType()]++;\r\n\t\t\telse if (value.getNetworkError() == NETWORK_ERRORS.WAN_ERROR)\r\n\t\t\t\tfailedTaskDuetoWanBw[value.getTaskType()]++;\r\n\t\t\telse if (value.getNetworkError() == NETWORK_ERRORS.GSM_ERROR)\r\n\t\t\t\tfailedTaskDuetoGsmBw[value.getTaskType()]++;\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.UNFINISHED_DUE_TO_MOBILITY) {\r\n\t\t\tfailedTaskDuetoMobility[value.getTaskType()]++;\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.REJECTED_DUE_TO_WLAN_COVERAGE) {\r\n\t\t\trefectedTaskDuetoWlanRange[value.getTaskType()]++;;\r\n }\r\n\t\t\r\n\t\t//if deep file logging is enabled, record every task result\r\n\t\tif (SimSettings.getInstance().getDeepFileLoggingEnabled()){\r\n\t\t\ttry {\r\n\t\t\t\tif (value.getStatus() == SimLogger.TASK_STATUS.COMLETED)\r\n\t\t\t\t\tappendToFile(successBW, value.toString(taskId));\r\n\t\t\t\telse\r\n\t\t\t\t\tappendToFile(failBW, value.toString(taskId));\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t\tSystem.exit(1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r"
] | import org.cloudbus.cloudsim.core.CloudSim;
import edu.boun.edgecloudsim.core.SimManager;
import edu.boun.edgecloudsim.core.SimSettings;
import edu.boun.edgecloudsim.edge_client.Task;
import edu.boun.edgecloudsim.network.NetworkModel;
import edu.boun.edgecloudsim.utils.Location;
import edu.boun.edgecloudsim.utils.SimLogger;
| /*
* Title: EdgeCloudSim - Network Model
*
* Description:
* SampleNetworkModel uses
* -> the result of an empirical study for the WLAN and WAN delays
* The experimental network model is developed
* by taking measurements from the real life deployments.
*
* -> MMPP/MMPP/1 queue model for MAN delay
* MAN delay is observed via a single server queue model with
* Markov-modulated Poisson process (MMPP) arrivals.
*
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
* Copyright (c) 2017, Bogazici University, Istanbul, Turkey
*/
package edu.boun.edgecloudsim.applications.sample_app2;
public class SampleNetworkModel extends NetworkModel {
public static enum NETWORK_TYPE {WLAN, LAN};
public static enum LINK_TYPE {DOWNLOAD, UPLOAD};
public static double MAN_BW = 1300*1024; //Kbps
@SuppressWarnings("unused")
private int manClients;
private int[] wanClients;
private int[] wlanClients;
private double lastMM1QueueUpdateTime;
private double ManPoissonMeanForDownload; //seconds
private double ManPoissonMeanForUpload; //seconds
private double avgManTaskInputSize; //bytes
private double avgManTaskOutputSize; //bytes
//record last n task statistics during MM1_QUEUE_MODEL_UPDATE_INTEVAL seconds to simulate mmpp/m/1 queue model
private double totalManTaskInputSize;
private double totalManTaskOutputSize;
private double numOfManTaskForDownload;
private double numOfManTaskForUpload;
public static final double[] experimentalWlanDelay = {
/*1 Client*/ 88040.279 /*(Kbps)*/,
/*2 Clients*/ 45150.982 /*(Kbps)*/,
/*3 Clients*/ 30303.641 /*(Kbps)*/,
/*4 Clients*/ 27617.211 /*(Kbps)*/,
/*5 Clients*/ 24868.616 /*(Kbps)*/,
/*6 Clients*/ 22242.296 /*(Kbps)*/,
/*7 Clients*/ 20524.064 /*(Kbps)*/,
/*8 Clients*/ 18744.889 /*(Kbps)*/,
/*9 Clients*/ 17058.827 /*(Kbps)*/,
/*10 Clients*/ 15690.455 /*(Kbps)*/,
/*11 Clients*/ 14127.744 /*(Kbps)*/,
/*12 Clients*/ 13522.408 /*(Kbps)*/,
/*13 Clients*/ 13177.631 /*(Kbps)*/,
/*14 Clients*/ 12811.330 /*(Kbps)*/,
/*15 Clients*/ 12584.387 /*(Kbps)*/,
/*15 Clients*/ 12135.161 /*(Kbps)*/,
/*16 Clients*/ 11705.638 /*(Kbps)*/,
/*17 Clients*/ 11276.116 /*(Kbps)*/,
/*18 Clients*/ 10846.594 /*(Kbps)*/,
/*19 Clients*/ 10417.071 /*(Kbps)*/,
/*20 Clients*/ 9987.549 /*(Kbps)*/,
/*21 Clients*/ 9367.587 /*(Kbps)*/,
/*22 Clients*/ 8747.625 /*(Kbps)*/,
/*23 Clients*/ 8127.663 /*(Kbps)*/,
/*24 Clients*/ 7907.701 /*(Kbps)*/,
/*25 Clients*/ 7887.739 /*(Kbps)*/,
/*26 Clients*/ 7690.831 /*(Kbps)*/,
/*27 Clients*/ 7393.922 /*(Kbps)*/,
/*28 Clients*/ 7297.014 /*(Kbps)*/,
/*29 Clients*/ 7100.106 /*(Kbps)*/,
/*30 Clients*/ 6903.197 /*(Kbps)*/,
/*31 Clients*/ 6701.986 /*(Kbps)*/,
/*32 Clients*/ 6500.776 /*(Kbps)*/,
/*33 Clients*/ 6399.565 /*(Kbps)*/,
/*34 Clients*/ 6098.354 /*(Kbps)*/,
/*35 Clients*/ 5897.143 /*(Kbps)*/,
/*36 Clients*/ 5552.127 /*(Kbps)*/,
/*37 Clients*/ 5207.111 /*(Kbps)*/,
/*38 Clients*/ 4862.096 /*(Kbps)*/,
/*39 Clients*/ 4517.080 /*(Kbps)*/,
/*40 Clients*/ 4172.064 /*(Kbps)*/,
/*41 Clients*/ 4092.922 /*(Kbps)*/,
/*42 Clients*/ 4013.781 /*(Kbps)*/,
/*43 Clients*/ 3934.639 /*(Kbps)*/,
/*44 Clients*/ 3855.498 /*(Kbps)*/,
/*45 Clients*/ 3776.356 /*(Kbps)*/,
/*46 Clients*/ 3697.215 /*(Kbps)*/,
/*47 Clients*/ 3618.073 /*(Kbps)*/,
/*48 Clients*/ 3538.932 /*(Kbps)*/,
/*49 Clients*/ 3459.790 /*(Kbps)*/,
/*50 Clients*/ 3380.649 /*(Kbps)*/,
/*51 Clients*/ 3274.611 /*(Kbps)*/,
/*52 Clients*/ 3168.573 /*(Kbps)*/,
/*53 Clients*/ 3062.536 /*(Kbps)*/,
/*54 Clients*/ 2956.498 /*(Kbps)*/,
/*55 Clients*/ 2850.461 /*(Kbps)*/,
/*56 Clients*/ 2744.423 /*(Kbps)*/,
/*57 Clients*/ 2638.386 /*(Kbps)*/,
/*58 Clients*/ 2532.348 /*(Kbps)*/,
/*59 Clients*/ 2426.310 /*(Kbps)*/,
/*60 Clients*/ 2320.273 /*(Kbps)*/,
/*61 Clients*/ 2283.828 /*(Kbps)*/,
/*62 Clients*/ 2247.383 /*(Kbps)*/,
/*63 Clients*/ 2210.939 /*(Kbps)*/,
/*64 Clients*/ 2174.494 /*(Kbps)*/,
/*65 Clients*/ 2138.049 /*(Kbps)*/,
/*66 Clients*/ 2101.604 /*(Kbps)*/,
/*67 Clients*/ 2065.160 /*(Kbps)*/,
/*68 Clients*/ 2028.715 /*(Kbps)*/,
/*69 Clients*/ 1992.270 /*(Kbps)*/,
/*70 Clients*/ 1955.825 /*(Kbps)*/,
/*71 Clients*/ 1946.788 /*(Kbps)*/,
/*72 Clients*/ 1937.751 /*(Kbps)*/,
/*73 Clients*/ 1928.714 /*(Kbps)*/,
/*74 Clients*/ 1919.677 /*(Kbps)*/,
/*75 Clients*/ 1910.640 /*(Kbps)*/,
/*76 Clients*/ 1901.603 /*(Kbps)*/,
/*77 Clients*/ 1892.566 /*(Kbps)*/,
/*78 Clients*/ 1883.529 /*(Kbps)*/,
/*79 Clients*/ 1874.492 /*(Kbps)*/,
/*80 Clients*/ 1865.455 /*(Kbps)*/,
/*81 Clients*/ 1833.185 /*(Kbps)*/,
/*82 Clients*/ 1800.915 /*(Kbps)*/,
/*83 Clients*/ 1768.645 /*(Kbps)*/,
/*84 Clients*/ 1736.375 /*(Kbps)*/,
/*85 Clients*/ 1704.106 /*(Kbps)*/,
/*86 Clients*/ 1671.836 /*(Kbps)*/,
/*87 Clients*/ 1639.566 /*(Kbps)*/,
/*88 Clients*/ 1607.296 /*(Kbps)*/,
/*89 Clients*/ 1575.026 /*(Kbps)*/,
/*90 Clients*/ 1542.756 /*(Kbps)*/,
/*91 Clients*/ 1538.544 /*(Kbps)*/,
/*92 Clients*/ 1534.331 /*(Kbps)*/,
/*93 Clients*/ 1530.119 /*(Kbps)*/,
/*94 Clients*/ 1525.906 /*(Kbps)*/,
/*95 Clients*/ 1521.694 /*(Kbps)*/,
/*96 Clients*/ 1517.481 /*(Kbps)*/,
/*97 Clients*/ 1513.269 /*(Kbps)*/,
/*98 Clients*/ 1509.056 /*(Kbps)*/,
/*99 Clients*/ 1504.844 /*(Kbps)*/,
/*100 Clients*/ 1500.631 /*(Kbps)*/
};
public static final double[] experimentalWanDelay = {
/*1 Client*/ 20703.973 /*(Kbps)*/,
/*2 Clients*/ 12023.957 /*(Kbps)*/,
/*3 Clients*/ 9887.785 /*(Kbps)*/,
/*4 Clients*/ 8915.775 /*(Kbps)*/,
/*5 Clients*/ 8259.277 /*(Kbps)*/,
/*6 Clients*/ 7560.574 /*(Kbps)*/,
/*7 Clients*/ 7262.140 /*(Kbps)*/,
/*8 Clients*/ 7155.361 /*(Kbps)*/,
/*9 Clients*/ 7041.153 /*(Kbps)*/,
/*10 Clients*/ 6994.595 /*(Kbps)*/,
/*11 Clients*/ 6653.232 /*(Kbps)*/,
/*12 Clients*/ 6111.868 /*(Kbps)*/,
/*13 Clients*/ 5570.505 /*(Kbps)*/,
/*14 Clients*/ 5029.142 /*(Kbps)*/,
/*15 Clients*/ 4487.779 /*(Kbps)*/,
/*16 Clients*/ 3899.729 /*(Kbps)*/,
/*17 Clients*/ 3311.680 /*(Kbps)*/,
/*18 Clients*/ 2723.631 /*(Kbps)*/,
/*19 Clients*/ 2135.582 /*(Kbps)*/,
/*20 Clients*/ 1547.533 /*(Kbps)*/,
/*21 Clients*/ 1500.252 /*(Kbps)*/,
/*22 Clients*/ 1452.972 /*(Kbps)*/,
/*23 Clients*/ 1405.692 /*(Kbps)*/,
/*24 Clients*/ 1358.411 /*(Kbps)*/,
/*25 Clients*/ 1311.131 /*(Kbps)*/
};
public SampleNetworkModel(int _numberOfMobileDevices, String _simScenario) {
super(_numberOfMobileDevices, _simScenario);
}
@Override
public void initialize() {
wanClients = new int[SimSettings.getInstance().getNumOfEdgeDatacenters()]; //we have one access point for each datacenter
wlanClients = new int[SimSettings.getInstance().getNumOfEdgeDatacenters()]; //we have one access point for each datacenter
int numOfApp = SimSettings.getInstance().getTaskLookUpTable().length;
SimSettings SS = SimSettings.getInstance();
for(int taskIndex=0; taskIndex<numOfApp; taskIndex++) {
if(SS.getTaskLookUpTable()[taskIndex][0] == 0) {
SimLogger.printLine("Usage percentage of task " + taskIndex + " is 0! Terminating simulation...");
System.exit(0);
}
else{
double weight = SS.getTaskLookUpTable()[taskIndex][0]/(double)100;
//assume half of the tasks use the MAN at the beginning
ManPoissonMeanForDownload += ((SS.getTaskLookUpTable()[taskIndex][2])*weight) * 4;
ManPoissonMeanForUpload = ManPoissonMeanForDownload;
avgManTaskInputSize += SS.getTaskLookUpTable()[taskIndex][5]*weight;
avgManTaskOutputSize += SS.getTaskLookUpTable()[taskIndex][6]*weight;
}
}
ManPoissonMeanForDownload = ManPoissonMeanForDownload/numOfApp;
ManPoissonMeanForUpload = ManPoissonMeanForUpload/numOfApp;
avgManTaskInputSize = avgManTaskInputSize/numOfApp;
avgManTaskOutputSize = avgManTaskOutputSize/numOfApp;
lastMM1QueueUpdateTime = SimSettings.CLIENT_ACTIVITY_START_TIME;
totalManTaskOutputSize = 0;
numOfManTaskForDownload = 0;
totalManTaskInputSize = 0;
numOfManTaskForUpload = 0;
}
/**
* source device is always mobile device in our simulation scenarios!
*/
@Override
public double getUploadDelay(int sourceDeviceId, int destDeviceId, Task task) {
double delay = 0;
//special case for man communication
if(sourceDeviceId == destDeviceId && sourceDeviceId == SimSettings.GENERIC_EDGE_DEVICE_ID){
return delay = getManUploadDelay();
}
| Location accessPointLocation = SimManager.getInstance().getMobilityModel().getLocation(sourceDeviceId,CloudSim.clock());
| 4 |
aurbroszniowski/Rainfall-core | src/main/java/io/rainfall/execution/Executions.java | [
"public abstract class Execution {\n\n public enum ExecutionState {\n UNKNOWN,\n BEGINNING,\n ENDING\n }\n\n /**\n * Provide an easy way to mark all operations as underway.\n *\n * @param scenario the test scenario\n * @param state phase of execution of the scenario\n */\n public void markExecutionState(Scenario scenario, ExecutionState state) {\n final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations();\n for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) {\n for (WeightedOperation op : operationRangeMap.getAll()) {\n op.markExecutionState(state);\n }\n }\n }\n\n protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom();\n\n public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario,\n final Map<Class<? extends Configuration>, Configuration> configurations,\n final List<AssertionEvaluator> assertions) throws TestException;\n\n public abstract String toString();\n\n}",
"public interface Unit {\n\n}",
"public class Every extends TimeMeasurement {\n\n public static Every every(int nb, TimeDivision timeDivision) {\n return new Every(nb, timeDivision);\n }\n\n public Every(int count, TimeDivision timeDivision) {\n super(count, timeDivision);\n }\n\n @Override\n public String toString() {\n return \"every \" + super.toString();\n }\n}",
"public class From extends UnitMeasurement {\n\n public static From from(int count, Unit unit) {\n return new From(count, unit);\n }\n\n public From(final int count, final Unit unit) {\n super(count, unit);\n }\n\n @Override\n public String toString() {\n return \"from \" + super.toString();\n }\n}",
"public class Over extends TimeMeasurement {\n\n public static Over over(int count, TimeDivision timeDivision) {\n return new Over(count, timeDivision);\n }\n\n public Over(int count, TimeDivision timeDivision) {\n super(count, timeDivision);\n }\n\n @Override\n public String toString() {\n return \"over \" + super.toString();\n }\n}",
"public class TimeDivision implements Unit {\n\n private TimeUnit timeUnit;\n\n public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS);\n\n public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES);\n\n public TimeDivision(TimeUnit timeUnit) {\n this.timeUnit = timeUnit;\n }\n\n public TimeUnit getTimeUnit() {\n return timeUnit;\n }\n\n @Override\n public String toString() {\n return timeUnit.name().toLowerCase();\n }\n}",
"public class To extends UnitMeasurement {\n\n public static To to(int count, Unit unit) {\n return new To(count, unit);\n }\n\n public To(int count, Unit unit) {\n super(count, unit);\n }\n\n @Override\n public String toString() {\n return \"to \" + super.toString();\n }\n}"
] | import io.rainfall.Execution;
import io.rainfall.Unit;
import io.rainfall.unit.Every;
import io.rainfall.unit.From;
import io.rainfall.unit.Over;
import io.rainfall.unit.TimeDivision;
import io.rainfall.unit.To;
import java.util.function.Function; | /*
* Copyright (c) 2014-2022 Aurélien Broszniowski
*
* 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.rainfall.execution;
/**
* @author Aurelien Broszniowski
*/
public class Executions {
public static Execution once(int nb, Unit unit) {
return new Times(nb);
}
public static Times times(long occurrences) {
return new Times(occurrences);
}
| public static InParallel inParallel(int count, Unit unit, Every every, Over over) { | 4 |
jenkinsci/ghprb-plugin | src/test/java/org/jenkinsci/plugins/ghprb/manager/impl/downstreambuilds/BuildFlowBuildManagerTest.java | [
"public abstract class GhprbITBaseTestCase {\n\n @Mock\n protected GHCommitPointer commitPointer;\n\n @Mock\n protected GHPullRequest ghPullRequest;\n\n @Mock\n protected GhprbGitHub ghprbGitHub;\n\n @Mock\n protected GHRepository ghRepository;\n\n @Mock\n protected GHUser ghUser;\n\n @Mock\n protected Ghprb helper;\n\n @Mock\n protected GhprbPullRequest ghprbPullRequest;\n\n protected GhprbBuilds builds;\n\n protected GhprbTrigger trigger;\n\n protected GHRateLimit ghRateLimit = new GHRateLimit();\n\n protected void beforeTest(\n Map<String, Object> globalConfig,\n Map<String, Object> triggerConfig,\n AbstractProject<?, ?> project\n ) throws Exception {\n project.addProperty(new GithubProjectProperty(\"https://github.com/user/dropwizard\"));\n GhprbTestUtil.setupGhprbTriggerDescriptor(globalConfig);\n\n trigger = GhprbTestUtil.getTrigger(triggerConfig);\n\n GitHub gitHub = trigger.getGitHub();\n\n given(gitHub.getRepository(anyString())).willReturn(ghRepository);\n\n given(ghPullRequest.getHead()).willReturn(commitPointer);\n given(ghPullRequest.getUser()).willReturn(ghUser);\n\n given(commitPointer.getRef()).willReturn(\"ref\");\n given(commitPointer.getSha()).willReturn(\"sha\");\n\n given(ghRepository.getName()).willReturn(\"dropwizard\");\n\n GhprbTestUtil.mockPR(ghPullRequest, commitPointer, new DateTime(), new DateTime().plusDays(1));\n\n given(ghRepository.getPullRequests(eq(GHIssueState.OPEN)))\n .willReturn(newArrayList(ghPullRequest))\n .willReturn(newArrayList(ghPullRequest));\n given(ghRepository.getPullRequest(Mockito.anyInt())).willReturn(ghPullRequest);\n\n given(ghUser.getEmail()).willReturn(\"[email protected]\");\n given(ghUser.getLogin()).willReturn(\"user\");\n\n ghRateLimit.remaining = GhprbTestUtil.INITIAL_RATE_LIMIT;\n\n GhprbTestUtil.mockCommitList(ghPullRequest);\n\n GhprbRepository repo = Mockito.spy(new GhprbRepository(\"user/dropwizard\", trigger));\n Mockito.doReturn(ghRepository).when(repo).getGitHubRepo();\n Mockito.doNothing().when(repo).addComment(Mockito.anyInt(), Mockito.anyString(), any(Run.class), any(TaskListener.class));\n Mockito.doReturn(ghprbPullRequest).when(repo).getPullRequest(Mockito.anyInt());\n\n Mockito.doReturn(repo).when(trigger).getRepository();\n\n builds = new GhprbBuilds(trigger, repo);\n\n // Creating spy on ghprb, configuring repo\n given(helper.getGitHub()).willReturn(ghprbGitHub);\n given(helper.getTrigger()).willReturn(trigger);\n given(helper.isWhitelisted(ghUser)).willReturn(true);\n given(helper.getBuilds()).willReturn(builds);\n\n Mockito.doCallRealMethod().when(trigger).run();\n\n\n // Configuring and adding Ghprb trigger\n project.addTrigger(trigger);\n\n // Configuring Git SCM\n GitSCM scm = GhprbTestUtil.provideGitSCM();\n project.setScm(scm);\n\n trigger.start(project, true);\n trigger.setHelper(helper);\n }\n\n}",
"public final class GhprbTestUtil {\n\n public static final int INITIAL_RATE_LIMIT = 5000;\n\n public static final String GHPRB_PLUGIN_NAME = \"ghprb\";\n\n public static final String PAYLOAD = \"{\"\n + \" \\\"action\\\": \\\"created\\\",\"\n + \" \\\"issue\\\": {\"\n + \" \\\"url\\\": \\\"https://api.github.com/repos/user/dropwizard/issues/1\\\",\"\n + \" \\\"labels_url\\\": \\\"https://api.github.com/repos/user/dropwizard/issues/1/labels{/name}\\\",\"\n + \" \\\"comments_url\\\": \\\"https://api.github.com/repos/user/dropwizard/issues/1/comments\\\",\"\n + \" \\\"events_url\\\": \\\"https://api.github.com/repos/user/dropwizard/issues/1/events\\\",\"\n + \" \\\"html_url\\\": \\\"https://github.com/user/dropwizard/pull/1\\\",\"\n + \" \\\"id\\\": 44444444,\"\n + \" \\\"number\\\": 1,\"\n + \" \\\"title\\\": \\\"Adding version command\\\",\"\n + \" \\\"user\\\": {\"\n + \" \\\"login\\\": \\\"user\\\",\"\n + \" \\\"id\\\": 444444,\"\n + \" \\\"avatar_url\\\": \\\"https://avatars.githubusercontent.com/u/444444?v=3\\\",\"\n + \" \\\"gravatar_id\\\": \\\"\\\",\"\n + \" \\\"url\\\": \\\"https://api.github.com/users/user\\\",\"\n + \" \\\"html_url\\\": \\\"https://github.com/user\\\",\"\n + \" \\\"followers_url\\\": \\\"https://api.github.com/users/user/followers\\\",\"\n + \" \\\"following_url\\\": \\\"https://api.github.com/users/user/following{/other_user}\\\",\"\n + \" \\\"gists_url\\\": \\\"https://api.github.com/users/user/gists{/gist_id}\\\",\"\n + \" \\\"starred_url\\\": \\\"https://api.github.com/users/user/starred{/owner}{/repo}\\\",\"\n + \" \\\"subscriptions_url\\\": \\\"https://api.github.com/users/user/subscriptions\\\",\"\n + \" \\\"organizations_url\\\": \\\"https://api.github.com/users/user/orgs\\\",\"\n + \" \\\"repos_url\\\": \\\"https://api.github.com/users/user/repos\\\",\"\n + \" \\\"events_url\\\": \\\"https://api.github.com/users/user/events{/privacy}\\\",\"\n + \" \\\"received_events_url\\\": \\\"https://api.github.com/users/user/received_events\\\",\"\n + \" \\\"type\\\": \\\"User\\\",\"\n + \" \\\"site_admin\\\": false\"\n + \" },\"\n + \" \\\"labels\\\": [\"\n + \"\"\n + \" ],\"\n + \" \\\"state\\\": \\\"open\\\",\"\n + \" \\\"locked\\\": false,\"\n + \" \\\"assignee\\\": null,\"\n + \" \\\"milestone\\\": null,\"\n + \" \\\"comments\\\": 2,\"\n + \" \\\"created_at\\\": \\\"2014-09-22T20:05:14Z\\\",\"\n + \" \\\"updated_at\\\": \\\"2015-01-14T14:50:53Z\\\",\"\n + \" \\\"closed_at\\\": null,\"\n + \" \\\"pull_request\\\": {\"\n + \" \\\"url\\\": \\\"https://api.github.com/repos/user/dropwizard/pulls/1\\\",\"\n + \" \\\"html_url\\\": \\\"https://github.com/user/dropwizard/pull/1\\\",\"\n + \" \\\"diff_url\\\": \\\"https://github.com/user/dropwizard/pull/1.diff\\\",\"\n + \" \\\"patch_url\\\": \\\"https://github.com/user/dropwizard/pull/1.patch\\\"\"\n + \" },\"\n + \" \\\"body\\\": \\\"\\\"\"\n + \" },\"\n + \" \\\"comment\\\": {\"\n + \" \\\"url\\\": \\\"https://api.github.com/repos/user/dropwizard/issues/comments/44444444\\\",\"\n + \" \\\"html_url\\\": \\\"https://github.com/user/dropwizard/pull/1#issuecomment-44444444\\\",\"\n + \" \\\"issue_url\\\": \\\"https://api.github.com/repos/user/dropwizard/issues/1\\\",\"\n + \" \\\"id\\\": 44444444,\"\n + \" \\\"user\\\": {\"\n + \" \\\"login\\\": \\\"user\\\",\"\n + \" \\\"id\\\": 444444,\"\n + \" \\\"avatar_url\\\": \\\"https://avatars.githubusercontent.com/u/444444?v=3\\\",\"\n + \" \\\"gravatar_id\\\": \\\"\\\",\"\n + \" \\\"url\\\": \\\"https://api.github.com/users/user\\\",\"\n + \" \\\"html_url\\\": \\\"https://github.com/user\\\",\"\n + \" \\\"followers_url\\\": \\\"https://api.github.com/users/user/followers\\\",\"\n + \" \\\"following_url\\\": \\\"https://api.github.com/users/user/following{/other_user}\\\",\"\n + \" \\\"gists_url\\\": \\\"https://api.github.com/users/user/gists{/gist_id}\\\",\"\n + \" \\\"starred_url\\\": \\\"https://api.github.com/users/user/starred{/owner}{/repo}\\\",\"\n + \" \\\"subscriptions_url\\\": \\\"https://api.github.com/users/user/subscriptions\\\",\"\n + \" \\\"organizations_url\\\": \\\"https://api.github.com/users/user/orgs\\\",\"\n + \" \\\"repos_url\\\": \\\"https://api.github.com/users/user/repos\\\",\"\n + \" \\\"events_url\\\": \\\"https://api.github.com/users/user/events{/privacy}\\\",\"\n + \" \\\"received_events_url\\\": \\\"https://api.github.com/users/user/received_events\\\",\"\n + \" \\\"type\\\": \\\"User\\\",\"\n + \" \\\"site_admin\\\": false\"\n + \" },\"\n + \" \\\"created_at\\\": \\\"2015-01-14T14:50:53Z\\\",\"\n + \" \\\"updated_at\\\": \\\"2015-01-14T14:50:53Z\\\",\"\n + \" \\\"body\\\": \\\"retest this please\\\"\"\n + \" },\"\n + \" \\\"repository\\\": {\"\n + \" \\\"id\\\": 44444444,\"\n + \" \\\"name\\\": \\\"Testing\\\",\"\n + \" \\\"full_name\\\": \\\"user/dropwizard\\\",\"\n + \" \\\"owner\\\": {\"\n + \" \\\"login\\\": \\\"user\\\",\"\n + \" \\\"id\\\": 444444,\"\n + \" \\\"avatar_url\\\": \\\"https://avatars.githubusercontent.com/u/444444?v=3\\\",\"\n + \" \\\"gravatar_id\\\": \\\"\\\",\"\n + \" \\\"url\\\": \\\"https://api.github.com/users/user\\\",\"\n + \" \\\"html_url\\\": \\\"https://github.com/user\\\",\"\n + \" \\\"followers_url\\\": \\\"https://api.github.com/users/user/followers\\\",\"\n + \" \\\"following_url\\\": \\\"https://api.github.com/users/user/following{/other_user}\\\",\"\n + \" \\\"gists_url\\\": \\\"https://api.github.com/users/user/gists{/gist_id}\\\",\"\n + \" \\\"starred_url\\\": \\\"https://api.github.com/users/user/starred{/owner}{/repo}\\\",\"\n + \" \\\"subscriptions_url\\\": \\\"https://api.github.com/users/user/subscriptions\\\",\"\n + \" \\\"organizations_url\\\": \\\"https://api.github.com/users/user/orgs\\\",\"\n + \" \\\"repos_url\\\": \\\"https://api.github.com/users/user/repos\\\",\"\n + \" \\\"events_url\\\": \\\"https://api.github.com/users/user/events{/privacy}\\\",\"\n + \" \\\"received_events_url\\\": \\\"https://api.github.com/users/user/received_events\\\",\"\n + \" \\\"type\\\": \\\"User\\\",\"\n + \" \\\"site_admin\\\": false\"\n + \" },\"\n + \" \\\"private\\\": false,\"\n + \" \\\"html_url\\\": \\\"https://github.com/user/dropwizard\\\",\"\n + \" \\\"description\\\": \\\"\\\",\"\n + \" \\\"fork\\\": false,\"\n + \" \\\"url\\\": \\\"https://api.github.com/repos/user/dropwizard\\\",\"\n + \" \\\"forks_url\\\": \\\"https://api.github.com/repos/user/dropwizard/forks\\\",\"\n + \" \\\"keys_url\\\": \\\"https://api.github.com/repos/user/dropwizard/keys{/key_id}\\\",\"\n + \" \\\"collaborators_url\\\": \\\"https://api.github.com/repos/user/dropwizard/collaborators{/collaborator}\\\",\"\n + \" \\\"teams_url\\\": \\\"https://api.github.com/repos/user/dropwizard/teams\\\",\"\n + \" \\\"hooks_url\\\": \\\"https://api.github.com/repos/user/dropwizard/hooks\\\",\"\n + \" \\\"issue_events_url\\\": \\\"https://api.github.com/repos/user/dropwizard/issues/events{/number}\\\",\"\n + \" \\\"events_url\\\": \\\"https://api.github.com/repos/user/dropwizard/events\\\",\"\n + \" \\\"assignees_url\\\": \\\"https://api.github.com/repos/user/dropwizard/assignees{/user}\\\",\"\n + \" \\\"branches_url\\\": \\\"https://api.github.com/repos/user/dropwizard/branches{/branch}\\\",\"\n + \" \\\"tags_url\\\": \\\"https://api.github.com/repos/user/dropwizard/tags\\\",\"\n + \" \\\"blobs_url\\\": \\\"https://api.github.com/repos/user/dropwizard/git/blobs{/sha}\\\",\"\n + \" \\\"git_tags_url\\\": \\\"https://api.github.com/repos/user/dropwizard/git/tags{/sha}\\\",\"\n + \" \\\"git_refs_url\\\": \\\"https://api.github.com/repos/user/dropwizard/git/refs{/sha}\\\",\"\n + \" \\\"trees_url\\\": \\\"https://api.github.com/repos/user/dropwizard/git/trees{/sha}\\\",\"\n + \" \\\"statuses_url\\\": \\\"https://api.github.com/repos/user/dropwizard/statuses/{sha}\\\",\"\n + \" \\\"languages_url\\\": \\\"https://api.github.com/repos/user/dropwizard/languages\\\",\"\n + \" \\\"stargazers_url\\\": \\\"https://api.github.com/repos/user/dropwizard/stargazers\\\",\"\n + \" \\\"contributors_url\\\": \\\"https://api.github.com/repos/user/dropwizard/contributors\\\",\"\n + \" \\\"subscribers_url\\\": \\\"https://api.github.com/repos/user/dropwizard/subscribers\\\",\"\n + \" \\\"subscription_url\\\": \\\"https://api.github.com/repos/user/dropwizard/subscription\\\",\"\n + \" \\\"commits_url\\\": \\\"https://api.github.com/repos/user/dropwizard/commits{/sha}\\\",\"\n + \" \\\"git_commits_url\\\": \\\"https://api.github.com/repos/user/dropwizard/git/commits{/sha}\\\",\"\n + \" \\\"comments_url\\\": \\\"https://api.github.com/repos/user/dropwizard/comments{/number}\\\",\"\n + \" \\\"issue_comment_url\\\": \\\"https://api.github.com/repos/user/dropwizard/issues/comments/{number}\\\",\"\n + \" \\\"contents_url\\\": \\\"https://api.github.com/repos/user/dropwizard/contents/{path}\\\",\"\n + \" \\\"compare_url\\\": \\\"https://api.github.com/repos/user/dropwizard/compare/{base}...{head}\\\",\"\n + \" \\\"merges_url\\\": \\\"https://api.github.com/repos/user/dropwizard/merges\\\",\"\n + \" \\\"archive_url\\\": \\\"https://api.github.com/repos/user/dropwizard/{archive_format}{/ref}\\\",\"\n + \" \\\"downloads_url\\\": \\\"https://api.github.com/repos/user/dropwizard/downloads\\\",\"\n + \" \\\"issues_url\\\": \\\"https://api.github.com/repos/user/dropwizard/issues{/number}\\\",\"\n + \" \\\"pulls_url\\\": \\\"https://api.github.com/repos/user/dropwizard/pulls{/number}\\\",\"\n + \" \\\"milestones_url\\\": \\\"https://api.github.com/repos/user/dropwizard/milestones{/number}\\\",\"\n + \" \\\"notifications_url\\\": \\\"https://api.github.com/repos/user/dropwizard/notifications{?since,all,participating}\\\",\"\n + \" \\\"labels_url\\\": \\\"https://api.github.com/repos/user/dropwizard/labels{/name}\\\",\"\n + \" \\\"releases_url\\\": \\\"https://api.github.com/repos/user/dropwizard/releases{/id}\\\",\"\n + \" \\\"created_at\\\": \\\"2014-07-23T15:52:14Z\\\",\"\n + \" \\\"updated_at\\\": \\\"2014-09-04T21:10:34Z\\\",\"\n + \" \\\"pushed_at\\\": \\\"2015-01-14T14:13:58Z\\\",\"\n + \" \\\"git_url\\\": \\\"git://github.com/user/dropwizard.git\\\",\"\n + \" \\\"ssh_url\\\": \\\"[email protected]:user/dropwizard.git\\\",\"\n + \" \\\"clone_url\\\": \\\"https://github.com/user/dropwizard.git\\\",\"\n + \" \\\"svn_url\\\": \\\"https://github.com/user/dropwizard\\\",\"\n + \" \\\"homepage\\\": null,\"\n + \" \\\"size\\\": 20028,\"\n + \" \\\"stargazers_count\\\": 0,\"\n + \" \\\"watchers_count\\\": 0,\"\n + \" \\\"language\\\": \\\"JavaScript\\\",\"\n + \" \\\"has_issues\\\": true,\"\n + \" \\\"has_downloads\\\": true,\"\n + \" \\\"has_wiki\\\": true,\"\n + \" \\\"has_pages\\\": false,\"\n + \" \\\"forks_count\\\": 0,\"\n + \" \\\"mirror_url\\\": null,\"\n + \" \\\"open_issues_count\\\": 1,\"\n + \" \\\"forks\\\": 0,\"\n + \" \\\"open_issues\\\": 1,\"\n + \" \\\"watchers\\\": 0,\"\n + \" \\\"default_branch\\\": \\\"master\\\"\"\n + \" },\"\n + \" \\\"sender\\\": {\"\n + \" \\\"login\\\": \\\"user\\\",\"\n + \" \\\"id\\\": 444444,\"\n + \" \\\"avatar_url\\\": \\\"https://avatars.githubusercontent.com/u/444444?v=3\\\",\"\n + \" \\\"gravatar_id\\\": \\\"\\\",\"\n + \" \\\"url\\\": \\\"https://api.github.com/users/user\\\",\"\n + \" \\\"html_url\\\": \\\"https://github.com/user\\\",\"\n + \" \\\"followers_url\\\": \\\"https://api.github.com/users/user/followers\\\",\"\n + \" \\\"following_url\\\": \\\"https://api.github.com/users/user/following{/other_user}\\\",\"\n + \" \\\"gists_url\\\": \\\"https://api.github.com/users/user/gists{/gist_id}\\\",\"\n + \" \\\"starred_url\\\": \\\"https://api.github.com/users/user/starred{/owner}{/repo}\\\",\"\n + \" \\\"subscriptions_url\\\": \\\"https://api.github.com/users/user/subscriptions\\\",\"\n + \" \\\"organizations_url\\\": \\\"https://api.github.com/users/user/orgs\\\",\"\n + \" \\\"repos_url\\\": \\\"https://api.github.com/users/user/repos\\\",\"\n + \" \\\"events_url\\\": \\\"https://api.github.com/users/user/events{/privacy}\\\",\"\n + \" \\\"received_events_url\\\": \\\"https://api.github.com/users/user/received_events\\\",\"\n + \" \\\"type\\\": \\\"User\\\",\"\n + \" \\\"site_admin\\\": false\"\n + \" }\"\n + \"}\";\n\n private static RequestImpl req;\n\n @SuppressWarnings(value = {\"rawtypes\", \"unchecked\"})\n public static void mockCommitList(GHPullRequest ghPullRequest) {\n PagedIterator itr = Mockito.mock(PagedIterator.class);\n PagedIterable pagedItr = Mockito.mock(PagedIterable.class);\n\n Mockito.when(ghPullRequest.listCommits()).thenReturn(pagedItr);\n Mockito.when(pagedItr.iterator()).thenReturn(itr);\n Mockito.when(itr.hasNext()).thenReturn(false);\n }\n\n public static void mockPR(GHPullRequest prToMock, GHCommitPointer commitPointer, DateTime... updatedDate) throws Exception {\n\n given(prToMock.getHead()).willReturn(commitPointer);\n given(prToMock.getBase()).willReturn(commitPointer);\n given(prToMock.getUrl()).willReturn(new URL(\"http://127.0.0.1\"));\n given(prToMock.getApiURL()).willReturn(new URL(\"http://127.0.0.1\"));\n\n if (updatedDate.length > 1) {\n given(prToMock.getUpdatedAt())\n .willReturn(updatedDate[0].toDate())\n .willReturn(updatedDate[0].toDate())\n .willReturn(updatedDate[1].toDate())\n .willReturn(updatedDate[1].toDate())\n .willReturn(updatedDate[1].toDate());\n } else {\n given(prToMock.getUpdatedAt()).willReturn(updatedDate[0].toDate());\n }\n }\n\n private static final String API_URL = \"https://api.github.com\";\n\n private static String setUpCredentials() throws Exception {\n return Ghprb.createCredentials(API_URL, \"accessToken\");\n }\n\n private static String credentialsId;\n\n private static String getCredentialsId() throws Exception {\n if (credentialsId == null) {\n credentialsId = setUpCredentials();\n }\n return credentialsId;\n }\n\n public static void setupGhprbTriggerDescriptor(Map<String, Object> config) throws Exception {\n setupReq();\n if (config == null) {\n config = new HashMap<>();\n }\n JSONObject jsonObject = new JSONObject();\n\n jsonObject.put(\"serverAPIUrl\", \"https://api.github.com\");\n jsonObject.put(\"username\", \"user\");\n jsonObject.put(\"password\", \"1111\");\n jsonObject.put(\"accessToken\", \"accessToken\");\n jsonObject.put(\"adminlist\", \"user\");\n jsonObject.put(\"allowMembersOfWhitelistedOrgsAsAdmin\", \"false\");\n jsonObject.put(\"publishedURL\", \"defaultPublishedURL\");\n jsonObject.put(\"requestForTestingPhrase\", \"test this\");\n jsonObject.put(\"whitelistPhrase\", \"\");\n jsonObject.put(\"okToTestPhrase\", \"ok to test\");\n jsonObject.put(\"retestPhrase\", \"retest this please\");\n jsonObject.put(\"skipBuildPhrase\", \"[skip ci]\");\n jsonObject.put(\"blackListCommitAuthor\", \"[bot1 bot2]\");\n jsonObject.put(\"cron\", \"0 0 31 2 0\");\n jsonObject.put(\"useComments\", \"true\");\n jsonObject.put(\"useDetailedComments\", \"false\");\n jsonObject.put(\"manageWebhooks\", \"true\");\n jsonObject.put(\"logExcerptLines\", \"0\");\n jsonObject.put(\"unstableAs\", \"FAILURE\");\n jsonObject.put(\"testMode\", \"true\");\n jsonObject.put(\"autoCloseFailedPullRequests\", \"false\");\n jsonObject.put(\"displayBuildErrorsOnDownstreamBuilds\", \"false\");\n jsonObject.put(\"msgSuccess\", \"Success\");\n jsonObject.put(\"msgFailure\", \"Failure\");\n jsonObject.put(\"commitStatusContext\", \"Status Context\");\n jsonObject.put(\"blackListLabels\", \"in progress\");\n jsonObject.put(\"whiteListLabels\", \"\");\n\n JSONObject githubAuth = new JSONObject();\n githubAuth.put(\"credentialsId\", getCredentialsId());\n githubAuth.put(\"serverAPIUrl\", API_URL);\n githubAuth.put(\"secret\", null);\n\n jsonObject.put(\"githubAuth\", githubAuth);\n\n\n for (Entry<String, Object> next : config.entrySet()) {\n jsonObject.put(next.getKey(), next.getValue());\n }\n\n\n GhprbTrigger.getDscp().configure(req, jsonObject);\n }\n\n static void setFinal(Object o, Field field, Object newValue) throws Exception {\n field.setAccessible(true);\n\n Field modifiersField = Field.class.getDeclaredField(\"modifiers\");\n modifiersField.setAccessible(true);\n int prevModifiers = field.getModifiers();\n modifiersField.setInt(field, prevModifiers & ~Modifier.FINAL);\n\n field.set(o, newValue);\n modifiersField.setInt(field, prevModifiers);\n modifiersField.setAccessible(false);\n field.setAccessible(false);\n\n }\n\n @SuppressWarnings(\"unchecked\")\n private static void setupReq() throws Exception {\n MetaClass meta = Mockito.mock(MetaClass.class);\n SingleLinkedList<MethodRef> list = SingleLinkedList.empty();\n given(meta.getPostConstructMethods()).willReturn(list);\n\n\n WebApp webApp = Mockito.mock(WebApp.class);\n setFinal(webApp, WebApp.class.getDeclaredField(\"bindInterceptors\"), new ArrayList<BindInterceptor>(0));\n\n given(webApp.getMetaClass(Mockito.any(GhprbTrigger.class))).willReturn(meta);\n\n req = Mockito.mock(RequestImpl.class);\n\n given(req.bindJSON(any(Class.class), any(JSONObject.class))).willCallRealMethod();\n given(req.bindJSON(any(Class.class), any(Class.class), any(JSONObject.class))).willCallRealMethod();\n given(req.setBindInterceptor(any(BindInterceptor.class))).willCallRealMethod();\n given(req.setBindListener(any(BindInterceptor.class))).willCallRealMethod();\n given(req.getWebApp()).willReturn(webApp);\n\n req.setBindListener(BindInterceptor.NOOP);\n req.setBindInterceptor(BindInterceptor.NOOP);\n req.setBindInterceptor(BindInterceptor.NOOP);\n\n }\n\n public static GitSCM provideGitSCM() {\n return new GitSCM(newArrayList(\n new UserRemoteConfig(\"https://github.com/user/dropwizard\",\n \"\", \"refs/pull/*:refs/remotes/origin/pr/*\", \"\")),\n newArrayList(new BranchSpec(\"${sha1}\")),\n false,\n null,\n null,\n \"\",\n null);\n }\n\n\n public static GhprbTrigger getTrigger() throws Exception {\n return getTrigger(null);\n }\n\n public static GhprbTrigger getTrigger(Map<String, Object> values) throws Exception {\n setupReq();\n if (values == null) {\n values = new HashMap<>();\n }\n\n JSONObject defaults = new JSONObject();\n defaults.put(\"adminlist\", \"user\");\n defaults.put(\"whitelist\", \"user\");\n defaults.put(\"orgslist\", \"\");\n defaults.put(\"cron\", \"0 0 31 2 0\");\n defaults.put(\"triggerPhrase\", \"retest this please\");\n defaults.put(\"onlyTriggerPhrase\", false);\n defaults.put(\"useGitHubHooks\", false);\n defaults.put(\"permitAll\", false);\n defaults.put(\"autoCloseFailedPullRequests\", false);\n defaults.put(\"displayBuildErrorsOnDownstreamBuilds\", false);\n defaults.put(\"allowMembersOfWhitelistedOrgsAsAdmin\", false);\n defaults.put(\"gitHubApi\", \"https://api.github.com\");\n\n for (Entry<String, Object> next : values.entrySet()) {\n defaults.put(next.getKey(), next.getValue());\n }\n\n GhprbTrigger trigger = spy(req.bindJSON(GhprbTrigger.class, defaults));\n\n GHRateLimit limit = new GHRateLimit();\n limit.remaining = INITIAL_RATE_LIMIT;\n\n GitHub github = Mockito.mock(GitHub.class);\n given(github.getRateLimit()).willReturn(limit);\n\n Mockito.doReturn(github).when(trigger).getGitHub();\n\n return trigger;\n }\n\n public static void waitForBuildsToFinish(Job<?, ?> project) throws InterruptedException {\n while (project.isBuilding() || project.isInQueue()) {\n // THEN\n Thread.sleep(500);\n }\n }\n\n public static void triggerRunAndWait(int numOfTriggers, GhprbTrigger trigger, Job<?, ?> project) throws InterruptedException {\n for (int i = 0; i < numOfTriggers; ++i) {\n trigger.run();\n waitForBuildsToFinish(project);\n }\n\n }\n\n public static void triggerRunsAtOnceThenWait(int numOfTriggers, GhprbTrigger trigger, Job<?, ?> project) throws InterruptedException {\n for (int i = 0; i < numOfTriggers; ++i) {\n trigger.run();\n }\n waitForBuildsToFinish(project);\n\n }\n\n public static List<String> checkClassForGetters(Class<?> clazz) {\n Field[] fields = clazz.getDeclaredFields();\n List<Field> xmlFields = new ArrayList<>();\n List<String> errors = new ArrayList<>();\n\n for (Field field : fields) {\n int modifiers = field.getModifiers();\n if (modifiers == (Modifier.PRIVATE) || modifiers == (Modifier.PRIVATE | Modifier.FINAL)) {\n xmlFields.add(field);\n }\n }\n\n for (Field field : xmlFields) {\n String getter = \"get\" + StringUtils.capitalize(field.getName());\n try {\n Method method = clazz.getDeclaredMethod(getter);\n int modifier = method.getModifiers();\n if (!Modifier.isPublic(modifier)) {\n errors.add(getter + \" is not a public method\");\n }\n } catch (Exception e) {\n String wrongGetter = \"is\" + StringUtils.capitalize(field.getName());\n try {\n clazz.getDeclaredMethod(wrongGetter);\n errors.add(\"Setter is using the wrong name, is \" + wrongGetter + \" and should be \" + getter);\n } catch (Exception err) {\n errors.add(\"Missing \" + getter);\n }\n }\n }\n return errors;\n }\n\n private GhprbTestUtil() {\n }\n}",
"public interface GhprbBuildManager {\n\n /**\n * Calculate the build URL of a build\n *\n * @param publishedURL the public jenkins url\n * @return the build URL\n */\n String calculateBuildUrl(String publishedURL);\n\n /**\n * Returns downstream builds as an iterator\n *\n * @return the iterator\n */\n Iterator<?> downstreamProjects();\n\n /**\n * Print tests result of a build in one line.\n *\n * @return the tests result\n */\n String getOneLineTestResults();\n\n /**\n * Print tests result of a build\n *\n * @return the tests result\n */\n String getTestResults();\n}",
"public final class GhprbBuildManagerFactoryUtil {\n\n private GhprbBuildManagerFactoryUtil() {\n }\n\n /**\n * Gets an instance of a library that is able to calculate build urls depending of build type.\n * <p>\n * If the class representing the build type is not present on the classloader then default implementation is returned.\n *\n * @param build the job from Jenkins\n * @return a buildManager\n */\n public static GhprbBuildManager getBuildManager(Run<?, ?> build) {\n JobConfiguration jobConfiguration = JobConfiguration.builder().printStackTrace(false).build();\n\n return getBuildManager(build, jobConfiguration);\n }\n\n public static GhprbBuildManager getBuildManager(Run<?, ?> build, JobConfiguration jobConfiguration) {\n try {\n if (build instanceof FlowRun) {\n return new BuildFlowBuildManager(build, jobConfiguration);\n }\n } catch (NoClassDefFoundError ncdfe) {\n }\n\n return new GhprbDefaultBuildManager(build);\n }\n\n}",
"public class JenkinsRuleWithBuildFlow extends JenkinsRule {\n\n public BuildFlow createBuildFlowProject() throws IOException {\n return createBuildFlowProject(createUniqueProjectName());\n }\n\n public BuildFlow createBuildFlowProject(String name) throws IOException {\n return jenkins.createProject(BuildFlow.class, name);\n }\n}"
] | import com.cloudbees.plugins.flow.BuildFlow;
import com.cloudbees.plugins.flow.FlowRun;
import com.cloudbees.plugins.flow.JobInvocation;
import org.jenkinsci.plugins.ghprb.GhprbITBaseTestCase;
import org.jenkinsci.plugins.ghprb.GhprbTestUtil;
import org.jenkinsci.plugins.ghprb.manager.GhprbBuildManager;
import org.jenkinsci.plugins.ghprb.manager.factory.GhprbBuildManagerFactoryUtil;
import org.jenkinsci.plugins.ghprb.rules.JenkinsRuleWithBuildFlow;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Iterator;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.BDDMockito.given; | package org.jenkinsci.plugins.ghprb.manager.impl.downstreambuilds;
/**
* @author mdelapenya (Manuel de la Peña)
*/
@RunWith(MockitoJUnitRunner.class)
public class BuildFlowBuildManagerTest extends GhprbITBaseTestCase {
@Rule | public JenkinsRuleWithBuildFlow jenkinsRule = new JenkinsRuleWithBuildFlow(); | 4 |
criticalmaps/criticalmaps-android | app/src/main/java/de/stephanlindauer/criticalmaps/service/ServerSyncService.java | [
"public class App extends Application {\n\n private static AppComponent appComponent;\n\n public static AppComponent components() {\n return appComponent;\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n if (BuildConfig.DEBUG) {\n Timber.plant(new Timber.DebugTree());\n } else {\n Timber.plant(new NoOpTree());\n }\n\n appComponent = DaggerAppComponent.builder().app(this).build();\n }\n\n private static class NoOpTree extends Timber.Tree {\n @Override\n protected void log(int priority, String tag, @NotNull String message, Throwable t) {\n }\n }\n}",
"public final class NetworkConnectivityChangedEvent {\n public boolean isConnected;\n}",
"public class PullServerHandler extends AsyncTask<Void, Void, String> {\n\n //dependencies\n private final ChatModel chatModel;\n private final OwnLocationModel ownLocationModel;\n private final UserModel userModel;\n private final ServerResponseProcessor serverResponseProcessor;\n private final OkHttpClient okHttpClient;\n private final SharedPreferences sharedPreferences;\n private final LocationUpdateManager locationUpdateManager;\n\n @Inject\n public PullServerHandler(ChatModel chatModel,\n OwnLocationModel ownLocationModel,\n UserModel userModel,\n ServerResponseProcessor serverResponseProcessor,\n OkHttpClient okHttpClient,\n SharedPreferences sharedPreferences,\n LocationUpdateManager locationUpdateManager) {\n this.chatModel = chatModel;\n this.ownLocationModel = ownLocationModel;\n this.userModel = userModel;\n this.serverResponseProcessor = serverResponseProcessor;\n this.okHttpClient = okHttpClient;\n this.sharedPreferences = sharedPreferences;\n this.locationUpdateManager = locationUpdateManager;\n }\n\n @Override\n protected String doInBackground(Void... params) {\n String jsonPostString = getJsonObject().toString();\n\n final RequestBody body = RequestBody.create(MediaType.parse(\"application/json\"), jsonPostString);\n final Request request = new Request.Builder().url(Endpoints.MAIN_POST).post(body).build();\n\n try {\n final Response response = okHttpClient.newCall(request).execute();\n if (response.isSuccessful()) {\n //noinspection ConstantConditions \"Returns a non-null value if this response was [...] returned from Call.execute().\"\n return response.body().string();\n }\n } catch (IOException e) {\n Timber.e(e);\n }\n return \"\";\n }\n\n @Override\n protected void onPostExecute(String result) {\n if (!result.isEmpty()) {\n serverResponseProcessor.process(result);\n }\n }\n\n private JSONObject getJsonObject() {\n JSONObject jsonObject = new JSONObject();\n\n try {\n jsonObject.put(\"device\", userModel.getChangingDeviceToken());\n\n final boolean isObserverModeActive = new BooleanPreference(\n sharedPreferences, SharedPrefsKeys.OBSERVER_MODE_ACTIVE).get();\n\n Timber.d(\"observer mode enabled: %s\", isObserverModeActive);\n\n if (!isObserverModeActive && ownLocationModel.hasPreciseLocation()\n && locationUpdateManager.isUpdating()) {\n jsonObject.put(\"location\", ownLocationModel.getLocationJson());\n }\n\n if (chatModel.hasOutgoingMessages()) {\n JSONArray messages = chatModel.getOutgoingMessagesAsJson();\n jsonObject.put(\"messages\", messages);\n }\n } catch (JSONException e) {\n Timber.e(e);\n }\n return jsonObject;\n }\n}",
"@Singleton\npublic class LocationUpdateManager {\n\n private final OwnLocationModel ownLocationModel;\n private final EventBus eventBus;\n private final PermissionCheckHandler permissionCheckHandler;\n private final App app;\n private boolean isUpdating = false;\n\n //const\n private static final float LOCATION_REFRESH_DISTANCE = 20; //20 meters\n private static final long LOCATION_REFRESH_TIME = 12 * 1000; //12 seconds\n private static final int LOCATION_NEW_THRESHOLD = 30 * 1000; //30 seconds\n private static final String[] USED_PROVIDERS = new String[]{\n LocationManager.GPS_PROVIDER,\n LocationManager.NETWORK_PROVIDER};\n\n //misc\n private final LocationManager locationManager;\n private Location lastPublishedLocation;\n\n private final LocationListener locationListener = new LocationListener() {\n @Override\n public void onLocationChanged(final Location location) {\n if (shouldPublishNewLocation(location)) {\n publishNewLocation(location);\n lastPublishedLocation = location;\n }\n }\n\n @Override\n public void onStatusChanged(String s, int i, Bundle bundle) {\n // Notes after some testing:\n // - seems to be only called for GPS provider\n // - calls not necessarily consistent with location fixes\n // - recurrent AVAILABLE calls for GPS\n // -> not usable\n }\n\n @Override\n public void onProviderEnabled(String s) {\n postStatusEvent();\n }\n\n @Override\n public void onProviderDisabled(String s) {\n postStatusEvent();\n }\n };\n\n @Inject\n public LocationUpdateManager(App app,\n OwnLocationModel ownLocationModel,\n EventBus eventBus,\n PermissionCheckHandler permissionCheckHandler) {\n this.app = app;\n this.ownLocationModel = ownLocationModel;\n this.eventBus = eventBus;\n this.permissionCheckHandler = permissionCheckHandler;\n locationManager = (LocationManager) app.getSystemService(Context.LOCATION_SERVICE);\n }\n\n @Produce\n public GpsStatusChangedEvent produceStatusEvent() {\n return Events.GPS_STATUS_CHANGED_EVENT;\n }\n\n @Produce\n public NewLocationEvent produceLocationEvent() {\n return Events.NEW_LOCATION_EVENT;\n }\n\n private void postStatusEvent() {\n setStatusEvent();\n eventBus.post(Events.GPS_STATUS_CHANGED_EVENT);\n }\n\n private void setAndPostPermissionPermanentlyDeniedEvent() {\n Events.GPS_STATUS_CHANGED_EVENT.status =\n GpsStatusChangedEvent.Status.PERMISSION_PERMANENTLY_DENIED;\n eventBus.post(Events.GPS_STATUS_CHANGED_EVENT);\n }\n\n private void setStatusEvent() {\n // isProviderEnabled() doesn't throw when permission is not granted, so we can use it safely\n if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {\n Events.GPS_STATUS_CHANGED_EVENT.status = GpsStatusChangedEvent.Status.HIGH_ACCURACY;\n isUpdating = true;\n } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {\n Events.GPS_STATUS_CHANGED_EVENT.status = GpsStatusChangedEvent.Status.LOW_ACCURACY;\n isUpdating = true;\n } else {\n isUpdating = false;\n Events.GPS_STATUS_CHANGED_EVENT.status = GpsStatusChangedEvent.Status.DISABLED;\n }\n }\n\n private boolean checkIfAtLeastOneProviderExits() {\n final List<String> allProviders = locationManager.getAllProviders();\n boolean atLeastOneProviderExists = false;\n for (String provider : USED_PROVIDERS) {\n if (allProviders.contains(provider)) {\n atLeastOneProviderExists = true;\n }\n }\n return atLeastOneProviderExists;\n }\n\n // Usage of this method should rather be handled by listening to the GpsStatusChangedEvent,\n // unfortunately this is not possible in PullServerHandler because we can't register on non\n // main thread\n public boolean isUpdating() {\n return isUpdating;\n }\n\n public void initializeAndStartListening() {\n boolean noProviderExists = !checkIfAtLeastOneProviderExits();\n boolean noPermission = !checkPermission();\n\n if (noProviderExists) {\n Events.GPS_STATUS_CHANGED_EVENT.status = GpsStatusChangedEvent.Status.NONEXISTENT;\n } else if (noPermission) {\n Events.GPS_STATUS_CHANGED_EVENT.status = GpsStatusChangedEvent.Status.NO_PERMISSIONS;\n } else {\n setStatusEvent();\n }\n eventBus.register(this);\n\n // Short-circuit here: if no provider exists don't start listening\n if (noProviderExists) {\n return;\n }\n\n // If permissions are not granted, don't start listening\n if (noPermission) {\n return;\n }\n\n startListening();\n }\n\n public void startListening() {\n // Set GPS status in case we're coming back after permission request\n postStatusEvent();\n\n // To get a quick first location, query all providers for last known location and treat them\n // like regular fixes by piping them through our normal flow\n final List<String> providers = locationManager.getAllProviders();\n for (String provider : providers) {\n @SuppressLint(\"MissingPermission\")\n Location location = locationManager.getLastKnownLocation(provider);\n if (location != null) {\n locationListener.onLocationChanged(location);\n }\n }\n\n registerLocationListeners();\n }\n\n private void registerLocationListeners() {\n // register existing providers; if one isn't enabled, the listener will take care of that\n requestLocationUpdatesIfProviderExists(LocationManager.GPS_PROVIDER);\n requestLocationUpdatesIfProviderExists(LocationManager.NETWORK_PROVIDER);\n }\n\n @SuppressLint(\"MissingPermission\")\n private void requestLocationUpdatesIfProviderExists(String provider) {\n if (locationManager.getProvider(provider) != null) {\n locationManager.requestLocationUpdates(provider,\n LOCATION_REFRESH_TIME,\n LOCATION_REFRESH_DISTANCE,\n locationListener);\n }\n }\n\n public boolean checkPermission() {\n return PermissionCheckHandler.checkPermissionGranted(\n Manifest.permission.ACCESS_FINE_LOCATION); //TODO does this exist on devices with only network location?\n }\n\n public void requestPermission() {\n PermissionRequest permissionRequest = new PermissionRequest(\n Manifest.permission.ACCESS_FINE_LOCATION,\n app.getString(R.string.map_location_permissions_rationale_text),\n this::startListening,\n null,\n this::setAndPostPermissionPermanentlyDeniedEvent);\n permissionCheckHandler.requestPermissionWithRationaleIfNeeded(permissionRequest);\n }\n\n public void handleShutdown() {\n locationManager.removeUpdates(locationListener);\n try {\n eventBus.unregister(this);\n } catch (IllegalArgumentException ignored) {\n }\n }\n\n private void publishNewLocation(Location location) {\n GeoPoint newLocation = new GeoPoint(location.getLatitude(), location.getLongitude());\n ownLocationModel.setLocation(newLocation, location.getAccuracy());\n eventBus.post(Events.NEW_LOCATION_EVENT);\n }\n\n private boolean shouldPublishNewLocation(Location location) {\n // Any location is better than no location\n if (lastPublishedLocation == null) {\n return true;\n }\n\n // Average speed of the CM is ~4 m/s so anything over 30 seconds old, may already\n // be well over 120m off. So a newer fix is assumed to be always better.\n long timeDelta = location.getTime() - lastPublishedLocation.getTime();\n boolean isSignificantlyNewer = timeDelta > LOCATION_NEW_THRESHOLD;\n boolean isSignificantlyOlder = timeDelta < -LOCATION_NEW_THRESHOLD;\n boolean isNewer = timeDelta > 0;\n\n if (isSignificantlyNewer) {\n return true;\n } else if (isSignificantlyOlder) {\n return false;\n }\n\n int accuracyDelta = (int) (location.getAccuracy() - lastPublishedLocation.getAccuracy());\n boolean isLessAccurate = accuracyDelta > 0;\n boolean isMoreAccurate = accuracyDelta < 0;\n boolean isSignificantlyLessAccurate = accuracyDelta > 120;\n\n boolean isFromSameProvider = location.getProvider().equals(lastPublishedLocation.getProvider());\n\n if (isMoreAccurate) {\n return true;\n } else if (isNewer && !isLessAccurate) {\n return true;\n } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {\n return true;\n }\n\n return false;\n }\n}",
"@Singleton\npublic class EventBus {\n\n private final Bus bus = new Bus();\n\n @Inject\n public EventBus() {\n }\n\n public void post(Object event) {\n bus.post(event);\n }\n\n public void register(Object object) {\n bus.register(object);\n }\n\n public void unregister(Object object) {\n bus.unregister(object);\n }\n}",
"public class TrackingInfoNotificationBuilder {\n //const\n public static final int NOTIFICATION_ID = 12456;\n private static final int INTENT_CLOSE_ID = 176456;\n private static final int INTENT_OPEN_ID = 133256;\n private static final String NOTIFICATION_CHANNEL_ID = \"cm_notification_channel_id\";\n\n public static Notification getNotification(Application application) {\n Intent openIntent = new Intent(application, Main.class);\n openIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n openIntent.putExtra(\"shouldClose\", false);\n PendingIntent openPendingIntent = PendingIntent.getActivity(application, INTENT_OPEN_ID,\n openIntent, PendingIntent.FLAG_UPDATE_CURRENT);\n\n Intent closeIntent = new Intent(application, Main.class);\n closeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n closeIntent.putExtra(\"shouldClose\", true);\n PendingIntent closePendingIntent = PendingIntent.getActivity(application, INTENT_CLOSE_ID,\n closeIntent, PendingIntent.FLAG_UPDATE_CURRENT);\n\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {\n NotificationManager mNotificationManager =\n (NotificationManager) application.getSystemService(Application.NOTIFICATION_SERVICE);\n\n NotificationChannel notificationChannel =\n new NotificationChannel(NOTIFICATION_CHANNEL_ID,\n application.getString(R.string.notification_channel_name),\n NotificationManager.IMPORTANCE_LOW); // no sound, status bar visibility\n\n notificationChannel.setDescription(\n application.getString(R.string.notification_channel_description_max300chars));\n notificationChannel.setBypassDnd(true);\n notificationChannel.setShowBadge(false);\n notificationChannel.enableLights(false);\n notificationChannel.enableVibration(false);\n notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);\n\n mNotificationManager.createNotificationChannel(notificationChannel);\n }\n\n NotificationCompat.Builder builder =\n new NotificationCompat.Builder(application, NOTIFICATION_CHANNEL_ID)\n .setSmallIcon(R.drawable.ic_stat_logo)\n .setContentTitle(application.getString(R.string.notification_tracking_title))\n .setContentText(application.getString(R.string.notification_tracking_text))\n .setStyle(new NotificationCompat.BigTextStyle()\n .bigText(application.getString(R.string.notification_tracking_text)))\n .setPriority(NotificationCompat.PRIORITY_MAX)\n .setContentIntent(openPendingIntent)\n .addAction(R.drawable.ic_notification_open,\n application.getString(R.string.notification_tracking_open),\n openPendingIntent)\n .addAction(R.drawable.ic_notification_close,\n application.getString(R.string.notification_tracking_close),\n closePendingIntent);\n\n return builder.build();\n }\n}"
] | import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import androidx.core.content.ContextCompat;
import com.squareup.otto.Subscribe;
import java.util.Timer;
import java.util.TimerTask;
import javax.inject.Inject;
import javax.inject.Provider;
import de.stephanlindauer.criticalmaps.App;
import de.stephanlindauer.criticalmaps.events.NetworkConnectivityChangedEvent;
import de.stephanlindauer.criticalmaps.handler.NetworkConnectivityChangeHandler;
import de.stephanlindauer.criticalmaps.handler.PullServerHandler;
import de.stephanlindauer.criticalmaps.managers.LocationUpdateManager;
import de.stephanlindauer.criticalmaps.provider.EventBus;
import de.stephanlindauer.criticalmaps.utils.TrackingInfoNotificationBuilder; | package de.stephanlindauer.criticalmaps.service;
public class ServerSyncService extends Service {
@SuppressWarnings("FieldCanBeLocal")
private final int SERVER_SYNC_INTERVAL = 12 * 1000; // 12 sec -> 5 times a minute
private Timer timerPullServer;
@Inject
LocationUpdateManager locationUpdateManager;
@Inject
NetworkConnectivityChangeHandler networkConnectivityChangeHandler;
@Inject
Provider<PullServerHandler> pullServerHandler;
@Inject | EventBus eventBus; | 4 |
w3c/epubcheck | src/main/java/com/adobe/epubcheck/bitmap/BitmapChecker.java | [
"public final class EPUBLocation implements Comparable<EPUBLocation>\n{\n\n public static EPUBLocation create(String fileName)\n {\n return new EPUBLocation(fileName, -1, -1, null);\n }\n\n public static EPUBLocation create(String fileName, String context)\n {\n return new EPUBLocation(fileName, -1, -1, context);\n }\n\n public static EPUBLocation create(String fileName, int lineNumber, int column)\n {\n return new EPUBLocation(fileName, lineNumber, column, null);\n }\n\n public static EPUBLocation create(String fileName, int lineNumber, int column, String context)\n {\n return new EPUBLocation(fileName, lineNumber, column, context);\n }\n\n @JsonProperty\n private final String path;\n @JsonProperty\n private final int line;\n @JsonProperty\n private final int column;\n @JsonProperty\n @JsonSerialize(using = JsonWriter.OptionalJsonSerializer.class)\n private final Optional<String> context;\n\n private EPUBLocation(String path, int lineNumber, int column, String context)\n {\n Preconditions.checkNotNull(path);\n this.path = path;\n this.line = lineNumber;\n this.column = column;\n this.context = Optional.fromNullable(context);\n }\n\n public String getPath()\n {\n return this.path;\n }\n\n public int getLine()\n {\n return this.line;\n }\n\n public int getColumn()\n {\n return this.column;\n }\n\n public Optional<String> getContext()\n {\n return this.context;\n }\n \n \n\n @Override\n public String toString()\n {\n return path + \"[\" + line + \",\" + column + \"]\";\n }\n\n @Override\n public boolean equals(Object obj)\n {\n if (obj == this)\n {\n return true;\n }\n if (obj == null || obj.getClass() != this.getClass())\n {\n return false;\n }\n\n EPUBLocation other = (EPUBLocation) obj;\n return !(this.getContext() == null && other.getContext() != null)\n && this.getPath().equals(other.getPath()) && this.getLine() == other.getLine()\n && this.getColumn() == other.getColumn()\n && (this.getContext() == null || this.getContext().equals(other.getContext()));\n }\n\n int safeCompare(String a, String b)\n {\n if (a == null && b != null) return -1;\n if (a != null && b == null) return 1;\n if (a == null /* && b == null */) return 0;\n return a.compareTo(b);\n }\n\n @Override\n public int compareTo(EPUBLocation o)\n {\n int comp = safeCompare(this.path, o.path);\n if (comp != 0)\n {\n return comp;\n }\n\n comp = line - o.line;\n if (comp != 0)\n {\n return comp < 0 ? -1 : 1;\n }\n\n comp = column - o.column;\n if (comp != 0)\n {\n return comp < 0 ? -1 : 1;\n }\n comp = safeCompare(context.orNull(), o.context.orNull());\n if (comp != 0)\n {\n return comp;\n }\n\n return 0;\n }\n}",
"public interface Report\n{\n /**\n * Called when a violation of the standard is found in epub.\n *\n * @param id Id of the message being reported\n * @param location location information for the message\n * @param args Arguments referenced by the format\n * string for the message.\n */\n public void message(MessageId id, EPUBLocation location, Object... args);\n\n /**\n * Called when a violation of the standard is found in epub.\n *\n * @param message The message being reported\n * @param location location information for the message\n * @param args Arguments referenced by the format\n * string for the message.\n */\n void message(Message message, EPUBLocation location, Object... args);\n\n /**\n * Called when when a feature is found in epub.\n *\n * @param resource name of the resource in the epub zip container that has this feature\n * or null if the feature is on the container level.\n * @param feature a keyword to know what kind of feature has been found\n * @param value value found\n */\n public void info(String resource, FeatureEnum feature, String value);\n\n public int getErrorCount();\n\n public int getWarningCount();\n\n public int getFatalErrorCount();\n\n public int getInfoCount();\n\n public int getUsageCount();\n\n /**\n * Called to create a report after the checks have been made\n */\n public int generate();\n\n /**\n * Called when a report if first created\n */\n public void initialize();\n\n public void setEpubFileName(String value);\n\n public String getEpubFileName();\n\n void setCustomMessageFile(String customMessageFileName);\n\n String getCustomMessageFile();\n\n public int getReportingLevel();\n\n public void setReportingLevel(int level);\n\n void close();\n\n void setOverrideFile(File customMessageFile);\n\n MessageDictionary getDictionary();\n}",
"public enum MessageId implements Comparable<MessageId>\n{\n // General info messages\n INF_001(\"INF-001\"),\n \n // Messages relating to accessibility\n ACC_001(\"ACC-001\"),\n ACC_002(\"ACC-002\"),\n ACC_003(\"ACC-003\"),\n ACC_004(\"ACC-004\"),\n ACC_005(\"ACC-005\"),\n ACC_006(\"ACC-006\"),\n ACC_007(\"ACC-007\"),\n ACC_008(\"ACC-008\"),\n ACC_009(\"ACC-009\"),\n ACC_010(\"ACC-010\"),\n ACC_011(\"ACC-011\"),\n ACC_012(\"ACC-012\"),\n ACC_013(\"ACC-013\"),\n ACC_014(\"ACC-014\"),\n ACC_015(\"ACC-015\"),\n ACC_016(\"ACC-016\"),\n ACC_017(\"ACC-017\"),\n\n // Messages relating to the checker configuration\n CHK_001(\"CHK-001\"),\n CHK_002(\"CHK-002\"),\n CHK_003(\"CHK-003\"),\n CHK_004(\"CHK-004\"),\n CHK_005(\"CHK-005\"),\n CHK_006(\"CHK-006\"),\n CHK_007(\"CHK-007\"),\n CHK_008(\"CHK-008\"),\n\n // Messages associated with styles\n CSS_001(\"CSS-001\"),\n CSS_002(\"CSS-002\"),\n CSS_003(\"CSS-003\"),\n CSS_004(\"CSS-004\"),\n CSS_005(\"CSS-005\"),\n CSS_006(\"CSS-006\"),\n CSS_007(\"CSS-007\"),\n CSS_008(\"CSS-008\"),\n CSS_009(\"CSS-009\"),\n CSS_010(\"CSS-010\"),\n CSS_011(\"CSS-011\"),\n CSS_012(\"CSS-012\"),\n CSS_013(\"CSS-013\"),\n CSS_015(\"CSS-015\"),\n CSS_016(\"CSS-016\"),\n CSS_017(\"CSS-017\"),\n CSS_019(\"CSS-019\"),\n CSS_020(\"CSS-020\"),\n CSS_021(\"CSS-021\"),\n CSS_022(\"CSS-022\"),\n CSS_023(\"CSS-023\"),\n CSS_024(\"CSS-024\"),\n CSS_025(\"CSS-025\"),\n CSS_028(\"CSS-028\"),\n\n // Messages relating to xhtml markup\n HTM_001(\"HTM-001\"),\n HTM_002(\"HTM-002\"),\n HTM_003(\"HTM-003\"),\n HTM_004(\"HTM-004\"),\n HTM_005(\"HTM-005\"),\n HTM_006(\"HTM-006\"),\n HTM_007(\"HTM-007\"),\n HTM_008(\"HTM-008\"),\n HTM_009(\"HTM-009\"),\n HTM_010(\"HTM-010\"),\n HTM_011(\"HTM-011\"),\n HTM_012(\"HTM-012\"),\n HTM_013(\"HTM-013\"),\n HTM_014(\"HTM-014\"),\n HTM_014a(\"HTM-014a\"),\n HTM_015(\"HTM-015\"),\n HTM_016(\"HTM-016\"),\n HTM_017(\"HTM-017\"),\n HTM_018(\"HTM-018\"),\n HTM_019(\"HTM-019\"),\n HTM_020(\"HTM-020\"),\n HTM_021(\"HTM-021\"),\n HTM_022(\"HTM-022\"),\n HTM_023(\"HTM-023\"),\n HTM_024(\"HTM-024\"),\n HTM_025(\"HTM-025\"),\n HTM_027(\"HTM-027\"),\n HTM_028(\"HTM-028\"),\n HTM_029(\"HTM-029\"),\n HTM_033(\"HTM-033\"),\n HTM_036(\"HTM-036\"),\n HTM_038(\"HTM-038\"),\n HTM_044(\"HTM-044\"),\n HTM_045(\"HTM-045\"),\n HTM_046(\"HTM-046\"),\n HTM_047(\"HTM-047\"),\n HTM_048(\"HTM-048\"),\n HTM_049(\"HTM-049\"),\n HTM_050(\"HTM-050\"),\n HTM_051(\"HTM-051\"),\n HTM_052(\"HTM-052\"),\n HTM_053(\"HTM_053\"),\n\n // Messages associated with media (images, audio and video)\n MED_001(\"MED-001\"),\n MED_002(\"MED-002\"),\n MED_003(\"MED-003\"),\n MED_004(\"MED-004\"),\n MED_005(\"MED-005\"),\n MED_006(\"MED_006\"),\n MED_007(\"MED_007\"),\n MED_008(\"MED-008\"),\n MED_009(\"MED-009\"),\n MED_010(\"MED_010\"),\n MED_011(\"MED_011\"),\n MED_012(\"MED_012\"),\n MED_013(\"MED_013\"),\n MED_014(\"MED_014\"),\n MED_015(\"MED_015\"),\n\n // Epub3 based table of content errors\n NAV_001(\"NAV-001\"),\n NAV_002(\"NAV-002\"),\n NAV_003(\"NAV-003\"),\n NAV_004(\"NAV-004\"),\n NAV_005(\"NAV-005\"),\n NAV_006(\"NAV-006\"),\n NAV_007(\"NAV-007\"),\n NAV_008(\"NAV-008\"),\n NAV_009(\"NAV-009\"),\n NAV_010(\"NAV-010\"),\n NAV_011(\"NAV-011\"),\n\n // Epub2 based table of content messages\n NCX_001(\"NCX-001\"),\n NCX_002(\"NCX-002\"),\n NCX_003(\"NCX-003\"),\n NCX_004(\"NCX-004\"),\n NCX_005(\"NCX-005\"),\n NCX_006(\"NCX-006\"),\n\n // Messages related to the markup in the OPF file\n OPF_001(\"OPF-001\"),\n OPF_002(\"OPF-002\"),\n OPF_003(\"OPF-003\"),\n OPF_004(\"OPF-004\"),\n OPF_004a(\"OPF-004a\"),\n OPF_004b(\"OPF-004b\"),\n OPF_004c(\"OPF-004c\"),\n OPF_004d(\"OPF-004d\"),\n OPF_004e(\"OPF-004e\"),\n OPF_004f(\"OPF-004f\"),\n OPF_005(\"OPF-005\"),\n OPF_006(\"OPF-006\"),\n OPF_007(\"OPF-007\"),\n OPF_007a(\"OPF-007a\"),\n OPF_007b(\"OPF-007b\"),\n OPF_008(\"OPF-008\"),\n OPF_009(\"OPF-009\"),\n OPF_010(\"OPF-010\"),\n OPF_011(\"OPF-011\"),\n OPF_012(\"OPF-012\"),\n OPF_013(\"OPF-013\"),\n OPF_014(\"OPF-014\"),\n OPF_015(\"OPF-015\"),\n OPF_016(\"OPF-016\"),\n OPF_017(\"OPF-017\"),\n OPF_018(\"OPF-018\"),\n OPF_018b(\"OPF-018b\"),\n OPF_019(\"OPF-019\"),\n OPF_020(\"OPF-020\"),\n OPF_021(\"OPF-021\"),\n OPF_025(\"OPF-025\"),\n OPF_026(\"OPF-026\"),\n OPF_027(\"OPF-027\"),\n OPF_028(\"OPF-028\"),\n OPF_029(\"OPF-029\"),\n OPF_030(\"OPF-030\"),\n OPF_031(\"OPF-031\"),\n OPF_032(\"OPF-032\"),\n OPF_033(\"OPF-033\"),\n OPF_034(\"OPF-034\"),\n OPF_035(\"OPF-035\"),\n OPF_036(\"OPF-036\"),\n OPF_037(\"OPF-037\"),\n OPF_038(\"OPF-038\"),\n OPF_039(\"OPF-039\"),\n OPF_040(\"OPF-040\"),\n OPF_041(\"OPF-041\"),\n OPF_042(\"OPF-042\"),\n OPF_043(\"OPF-043\"),\n OPF_044(\"OPF-044\"),\n OPF_045(\"OPF-045\"),\n OPF_046(\"OPF-046\"),\n OPF_047(\"OPF-047\"),\n OPF_048(\"OPF-048\"),\n OPF_049(\"OPF-049\"),\n OPF_050(\"OPF-050\"),\n OPF_051(\"OPF-051\"),\n OPF_052(\"OPF-052\"),\n OPF_053(\"OPF-053\"),\n OPF_054(\"OPF-054\"),\n OPF_055(\"OPF-055\"),\n OPF_056(\"OPF-056\"),\n OPF_057(\"OPF-057\"),\n OPF_058(\"OPF-058\"),\n OPF_059(\"OPF-059\"),\n OPF_060(\"OPF-060\"),\n OPF_061(\"OPF-061\"),\n OPF_062(\"OPF-062\"),\n OPF_063(\"OPF-063\"),\n OPF_064(\"OPF-064\"),\n OPF_065(\"OPF-065\"),\n OPF_066(\"OPF-066\"),\n OPF_067(\"OPF-067\"),\n OPF_068(\"OPF-068\"),\n OPF_069(\"OPF-069\"),\n OPF_070(\"OPF-070\"),\n OPF_071(\"OPF-071\"),\n OPF_072(\"OPF-072\"),\n OPF_073(\"OPF-073\"),\n OPF_074(\"OPF-074\"),\n OPF_075(\"OPF-075\"),\n OPF_076(\"OPF-076\"),\n OPF_077(\"OPF-077\"),\n OPF_078(\"OPF-078\"),\n OPF_079(\"OPF-079\"),\n OPF_080(\"OPF-080\"),\n OPF_081(\"OPF-081\"),\n OPF_082(\"OPF-082\"),\n OPF_083(\"OPF-083\"),\n OPF_084(\"OPF-084\"),\n OPF_085(\"OPF-085\"),\n OPF_086(\"OPF-086\"),\n OPF_086b(\"OPF-086b\"),\n OPF_087(\"OPF-087\"),\n OPF_088(\"OPF-088\"),\n OPF_089(\"OPF-089\"),\n OPF_090(\"OPF-090\"),\n\n // Messages relating to the entire package\n PKG_001(\"PKG-001\"),\n PKG_003(\"PKG-003\"),\n PKG_004(\"PKG-004\"),\n PKG_005(\"PKG-005\"),\n PKG_006(\"PKG-006\"),\n PKG_007(\"PKG-007\"),\n PKG_008(\"PKG-008\"),\n PKG_009(\"PKG-009\"),\n PKG_010(\"PKG-010\"),\n PKG_011(\"PKG-011\"),\n PKG_012(\"PKG-012\"),\n PKG_013(\"PKG-013\"),\n PKG_014(\"PKG-014\"),\n PKG_015(\"PKG-015\"),\n PKG_016(\"PKG-016\"),\n PKG_017(\"PKG-017\"),\n PKG_018(\"PKG-018\"),\n PKG_020(\"PKG-020\"),\n PKG_021(\"PKG-021\"),\n PKG_022(\"PKG-022\"),\n PKG_023(\"PKG-023\"),\n PKG_024(\"PKG-024\"),\n\n // Messages relating to resources\n RSC_001(\"RSC-001\"),\n RSC_002(\"RSC-002\"),\n RSC_003(\"RSC-003\"),\n RSC_004(\"RSC-004\"),\n RSC_005(\"RSC-005\"),\n RSC_006(\"RSC-006\"),\n RSC_006b(\"RSC-006b\"),\n RSC_007(\"RSC-007\"),\n RSC_007w(\"RSC-007w\"),\n RSC_008(\"RSC-008\"),\n RSC_009(\"RSC-009\"),\n RSC_010(\"RSC-010\"),\n RSC_011(\"RSC-011\"),\n RSC_012(\"RSC-012\"),\n RSC_013(\"RSC-013\"),\n RSC_014(\"RSC-014\"),\n RSC_015(\"RSC-015\"),\n RSC_016(\"RSC-016\"),\n RSC_017(\"RSC-017\"),\n RSC_018(\"RSC-018\"),\n RSC_019(\"RSC-019\"),\n RSC_020(\"RSC-020\"),\n RSC_021(\"RSC-021\"),\n RSC_022(\"RSC-022\"),\n RSC_023(\"RSC-023\"),\n\n // Messages relating to scripting\n SCP_001(\"SCP-001\"),\n SCP_002(\"SCP-002\"),\n SCP_003(\"SCP-003\"),\n SCP_004(\"SCP-004\"),\n SCP_005(\"SCP-005\"),\n SCP_006(\"SCP-006\"),\n SCP_007(\"SCP-007\"),\n SCP_008(\"SCP-008\"),\n SCP_009(\"SCP-009\"),\n SCP_010(\"SCP-010\");\n\n private final String messageId;\n\n MessageId(String feature)\n {\n this.messageId = feature;\n }\n\n public String toString()\n {\n return messageId;\n }\n\n private static final Map<String, MessageId> map = new HashMap<String, MessageId>();\n\n static\n {\n for (MessageId type : MessageId.values())\n {\n map.put(type.messageId, type);\n }\n }\n\n public static MessageId fromString(String messageId)\n {\n if (map.containsKey(messageId))\n {\n return map.get(messageId);\n }\n throw new NoSuchElementException(\"MessageId.\" + messageId + \" not found\");\n }\n\n}",
"public abstract class OCFPackage implements GenericResourceProvider\n{\n final Hashtable<String, EncryptionFilter> enc;\n String uniqueIdentifier;\n private Report reporter;\n private final Supplier<OCFData> ocfData = Suppliers.memoize(new Supplier<OCFData>()\n {\n @Override\n public OCFData get()\n {\n Preconditions.checkNotNull(reporter);\n XMLParser containerParser = new XMLParser(new ValidationContextBuilder()\n .path(OCFData.containerEntry).resourceProvider(OCFPackage.this).report(reporter)\n .mimetype(\"xml\").build());\n OCFHandler containerHandler = new OCFHandler(containerParser);\n containerParser.addXMLHandler(containerHandler);\n containerParser.process();\n return containerHandler;\n }\n });\n\n private final Supplier<Map<String, OPFData>> opfData = Suppliers\n .memoize(new Supplier<Map<String, OPFData>>()\n {\n @Override\n public Map<String, OPFData> get()\n {\n Preconditions.checkNotNull(reporter);\n Map<String, OPFData> result = new HashMap<String, OPFData>();\n for (String opfPath : ocfData.get().getEntries(OPFData.OPF_MIME_TYPE))\n {\n OPFPeeker peeker = new OPFPeeker(opfPath, reporter, OCFPackage.this);\n try\n {\n result.put(opfPath, peeker.peek());\n } catch (InvalidVersionException e)\n {\n reporter.message(MessageId.OPF_001, EPUBLocation.create(opfPath),\n e.getMessage());\n } catch (IOException ignored)\n {\n // missing file will be reported later\n }\n }\n return Collections.unmodifiableMap(result);\n }\n });\n\n public OCFPackage()\n {\n this.enc = new Hashtable<String, EncryptionFilter>();\n }\n\n public void setEncryption(String name, EncryptionFilter encryptionFilter)\n {\n enc.put(name, encryptionFilter);\n }\n\n /**\n * @param name\n * the name of a relative file that is possibly in the container\n * @return true if the file is in the container, false otherwise\n */\n public abstract boolean hasEntry(String name);\n\n public abstract long getTimeEntry(String name);\n\n /**\n * @param name\n * the name of a relative file to fetch from the container.\n * @return an InputStream representing the data from the named file, possibly\n * decrypted if an appropriate encryption filter has been set\n */\n public abstract InputStream getInputStream(String name)\n throws IOException;\n\n /**\n * @return a list of all the entries in this container. May contain duplicate\n * entries (which is invalid in EPUB).\n * @throws IOException\n */\n public abstract List<String> getEntries()\n throws IOException;\n\n /**\n * @return a set of relative file names of files in this container (cleaned from duplicates)\n * @throws IOException\n */\n public abstract Set<String> getFileEntries()\n throws IOException;\n\n /**\n * @return a set of relative directory entries in this container (cleaned from duplicates)\n * @throws IOException\n */\n public abstract Set<String> getDirectoryEntries()\n throws IOException;\n\n /**\n * @param fileName\n * name of the file to test\n * @return true if I have an Encryption filter for this particular file.\n */\n public boolean canDecrypt(String fileName)\n {\n EncryptionFilter filter = enc.get(fileName);\n return filter == null || filter.canDecrypt();\n }\n\n /**\n * This method parses the container entry and stores important data, but does\n * /not/ validate the container against a schema definition.\n * <p>\n * The parsed OCFData objects are memoized.\n * </p>\n * <p>\n * This OCFPackage's reporter is used to report any error that may occur the\n * first time the OCFData is parsed.\n * </p>\n *\n */\n public OCFData getOcfData()\n {\n return ocfData.get();\n }\n\n /**\n * This method parses the OPF root files contained in an OCFContainer and\n * stores important data, but does /not/ validate the OPF file against a\n * schema definition.\n * <p>\n * The parsed OPFData objects are memoized.\n * </p>\n * <p>\n * This OCFPackage's reporter is used to report any error that may occur the\n * first time the OPFData is parsed.\n * </p>\n *\n * @return an map with the OPF root files as keys and the OPFData as values.\n */\n public Map<String, OPFData> getOpfData()\n {\n return opfData.get();\n }\n\n public abstract void reportMetadata(String fileName, Report report);\n\n public abstract String getName();\n\n public abstract String getPackagePath();\n\n public void setReport(Report reporter)\n {\n this.reporter = reporter;\n }\n}",
"public class OCFZipPackage extends OCFPackage\n{\n\n private final ZipFile zip;\n private List<String> allEntries = null;\n private Set<String> fileEntries;\n private Set<String> dirEntries;\n\n public OCFZipPackage(ZipFile zip)\n {\n super();\n this.zip = zip;\n }\n\n private void listEntries() throws\n IOException\n {\n synchronized (zip)\n {\n allEntries = new LinkedList<String>();\n fileEntries = new TreeSet<String>();\n dirEntries = new TreeSet<String>();\n\n try\n {\n for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); )\n {\n ZipEntry entry = entries.nextElement();\n allEntries.add(entry.getName());\n if (entry.isDirectory())\n {\n dirEntries.add(entry.getName());\n }\n else\n {\n fileEntries.add(entry.getName());\n }\n }\n }\n catch (IllegalArgumentException ex)\n {\n throw new IOException(ex.getMessage());\n }\n }\n }\n\n /* (non-Javadoc)\n * @see com.adobe.epubcheck.ocf.OCFPackage#hasEntry(java.lang.String)\n */\n public boolean hasEntry(String name)\n {\n return zip.getEntry(name) != null;\n }\n\n /* (non-Javadoc)\n * @see com.adobe.epubcheck.ocf.OCFPackage#getTimeEntry(java.lang.String)\n */\n public long getTimeEntry(String name)\n {\n ZipEntry entry = zip.getEntry(name);\n if (entry == null)\n {\n return 0L;\n }\n return entry.getTime();\n }\n\n /*\n * (non-Javadoc)\n * @see com.adobe.epubcheck.ocf.OCFPackage#getInputStream(java.lang.String)\n */\n @Override\n public InputStream getInputStream(String name) throws\n IOException\n {\n ZipEntry entry = zip.getEntry(name);\n if (entry == null)\n {\n return null;\n }\n InputStream in = zip.getInputStream(entry);\n EncryptionFilter filter = enc.get(name);\n if (filter == null)\n {\n return in;\n }\n if (filter.canDecrypt())\n {\n return filter.decrypt(in);\n }\n return null;\n }\n\n @Override\n public List<String> getEntries() throws\n IOException\n {\n synchronized (zip)\n {\n if (allEntries == null)\n {\n listEntries();\n }\n }\n return Collections.unmodifiableList(allEntries);\n }\n\n /* (non-Javadoc)\n * @see com.adobe.epubcheck.ocf.OCFPackage#getFileEntries()\n */\n @Override\n public Set<String> getFileEntries() throws\n IOException\n {\n synchronized (zip)\n {\n if (allEntries == null)\n {\n listEntries();\n }\n return Collections.unmodifiableSet(fileEntries);\n }\n }\n\n /* (non-Javadoc)\n * @see com.adobe.epubcheck.ocf.OCFPackage#getDirectoryEntries()\n */\n @Override\n public Set<String> getDirectoryEntries() throws\n IOException\n {\n synchronized (zip)\n {\n if (allEntries == null)\n {\n listEntries();\n }\n return Collections.unmodifiableSet(dirEntries);\n }\n }\n\n public void reportMetadata(String fileName, Report report)\n {\n ZipEntry entry = zip.getEntry(fileName);\n if (entry != null)\n {\n report.info(fileName, FeatureEnum.SIZE, String.valueOf(entry.getSize()));\n report.info(fileName, FeatureEnum.COMPRESSED_SIZE, String.valueOf(entry.getCompressedSize()));\n report.info(fileName, FeatureEnum.COMPRESSION_METHOD, this.getCompressionMethod(entry));\n InputStream inputStream = null;\n try\n {\n inputStream = zip.getInputStream(entry);\n if (inputStream != null)\n {\n report.info(fileName, FeatureEnum.SHA_256, getSHAHash(inputStream));\n }\n }\n catch (IOException e)\n {\n report.message(MessageId.PKG_008, EPUBLocation.create(fileName), fileName);\n }\n finally\n {\n if (inputStream != null)\n {\n try\n {\n inputStream.close();\n }\n catch (Exception ignore)\n {\n }\n }\n }\n }\n }\n\n private String getCompressionMethod(ZipEntry entry)\n {\n if (entry == null)\n {\n return \"\";\n }\n int method = entry.getMethod();\n if (method == ZipEntry.DEFLATED)\n {\n return \"Deflated\";\n }\n if (method == ZipEntry.STORED)\n {\n return \"Stored\";\n }\n return \"Unsupported\";\n }\n\n private static String getSHAHash(InputStream fis)\n {\n try\n {\n\n MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n byte[] dataBytes = new byte[1024];\n\n int nread;\n while ((nread = fis.read(dataBytes)) != -1)\n {\n md.update(dataBytes, 0, nread);\n }\n byte[] bytes = md.digest();\n\n //convert the byte to hex format method 1\n //StringBuilder sb = new StringBuilder();\n //for (int i = 0; i < bytes.length; i++)\n //{\n // sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));\n //}\n\n //convert the byte to hex format method 2\n StringBuilder hexString = new StringBuilder();\n for (byte aByte : bytes)\n {\n hexString.append(Integer.toHexString(0xFF & aByte));\n }\n\n return hexString.toString();\n }\n catch (Exception e)\n {\n return \"error!\";\n }\n finally\n {\n if (fis != null)\n {\n try\n {\n fis.close();\n }\n catch (IOException ignored)\n {\n }\n }\n }\n }\n\n public String getName()\n {\n return new File(this.zip.getName()).getName();\n }\n\n @Override\n public String getPackagePath()\n {\n return zip.getName();\n }\n}"
] | import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import com.adobe.epubcheck.api.EPUBLocation;
import com.adobe.epubcheck.api.Report;
import com.adobe.epubcheck.messages.MessageId;
import com.adobe.epubcheck.ocf.OCFPackage;
import com.adobe.epubcheck.ocf.OCFZipPackage;
import com.adobe.epubcheck.opf.ContentChecker;
import com.adobe.epubcheck.util.CheckUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader; | /*
* Copyright (c) 2007 Adobe Systems Incorporated
*
* 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.adobe.epubcheck.bitmap;
public class BitmapChecker implements ContentChecker
{
private final OCFPackage ocf; | private final Report report; | 1 |
sorinMD/MCTS | src/main/java/mcts/tree/selection/PUCT.java | [
"public interface Game {\n\n\t/**\n\t * @return a clone of the game state\n\t */\n\tpublic int[] getState();\n\n\tpublic int getWinner();\n\n\tpublic boolean isTerminal();\n\n\tpublic int getCurrentPlayer();\n\n\t/**\n\t * Updates the state description based on the chosen action\n\t * \n\t * @param a\n\t * the chosen action\n\t * @param sample\n\t * if this action was sampled according to an efficient game specific\n\t * method or not. A simple rule of thumb is if the options were\n\t * listed with sample true this should also be true and vice-versa.\n\t */\n\tpublic void performAction(int[] a, boolean sample);\n\n\t/**\n\t * @param sample\n\t * flag for deciding if should include all actions or just sample\n\t * from the legal ones. (e.g. usage: set to true if this is called\n\t * while performing rollouts)\n\t * @return a list of all the legal actions given the current state\n\t */\n\tpublic Options listPossiblities(boolean sample);\n\n\t/**\n\t * @return a clone of the game\n\t */\n\tpublic Game copy();\n\n\t/**\n\t * Method for sampling the next action at random or based on the chances built\n\t * into the game logic;\n\t * \n\t * @return the next action description\n\t */\n\tpublic int[] sampleNextAction();\n\n\t/**\n\t * Method for sampling the next action at random or based on the chances built\n\t * into the game logic;\n\t * \n\t * @return the index of the next legal action\n\t */\n\tpublic int sampleNextActionIndex();\n\n\tpublic TreeNode generateNode();\n\n\t/**\n\t * Executes one random action.\n\t * \n\t * @param belief\n\t */\n\tpublic void gameTick();\n}",
"public class GameFactory {\n\tpublic static final int TICTACTOE = 0;\n\tpublic static final int CATAN = 1;\n\t\n\tprivate GameConfig gameConfig;\n\tprivate Belief belief;\n\t\n\tpublic GameFactory(GameConfig gameConfig, Belief belief) {\n\t\tthis.gameConfig = gameConfig;\n\t\tthis.belief = belief;\n\t}\n\t\n\tpublic Game getNewGame(){\n\t\tif(gameConfig.id == CATAN){\n\t\t\tif(belief != null) {\n\t\t\t\tif(!CatanWithBelief.board.init)\n\t\t\t\t\t CatanWithBelief.initBoard();//we can safely create a new board here as this means that we don't need to use a specific board.\n\t\t\t\treturn new CatanWithBelief(((CatanConfig) gameConfig), (CatanFactoredBelief) belief);\n\t\t\t}else {\n\t\t\t\tif(!Catan.board.init)\n\t\t\t\t\t Catan.initBoard();\n\t\t\t\treturn new Catan(((CatanConfig) gameConfig));\n\t\t\t}\n\t\t}else\n\t\t\treturn new TicTacToe();\n\t} \n\t\n\tpublic Game getGame(int[] state){\n\t\tif(gameConfig.id == CATAN){\n\t\t\tif(belief != null)\n\t\t\t\treturn new CatanWithBelief(state, ((CatanConfig) gameConfig), (CatanFactoredBelief) belief);\n\t\t\telse\n\t\t\t\treturn new Catan(state, ((CatanConfig) gameConfig));\n\t\t}else\n\t\t\treturn new TicTacToe(state);\n\t} \n\n\tpublic GameConfig getConfig(){\n\t\treturn gameConfig;\n\t}\n\t\n\tpublic Belief getBelief() {\n\t\treturn belief;\n\t}\n\t\n\tpublic DeterminizationSampler getDeterminizationSampler() {\n\t\tif(gameConfig.id == CATAN && belief != null)\n\t\t\treturn new CatanDeterminizationSampler();\n\t\treturn new NullDeterminizationSampler();\n\t}\n\t\n\t/**\n\t * @return\n\t */\n\tpublic static int nMaxPlayers(){\n\t\treturn 4;\n\t}\n\t\n\tpublic GameFactory copy() {\n\t\tBelief clone = null;\n\t\tif(belief != null)\n\t\t\t clone = belief.copy();\n\t\tGameFactory factory = new GameFactory(gameConfig.copy(), clone);\n\t\treturn factory;\n\t}\n\t\n}",
"public class Tree {\n\tprivate ConcurrentHashMap<Key, TreeNode> nodes;\n\tprivate TreeNode root;\n\tprivate int maxTreeSize = 500000;\n\t\n\tpublic boolean maxSizeReached(){\n\t\treturn nodes.size() > maxTreeSize;\n\t}\n\t\n\tpublic Tree(Game currentState, int maxSize) {\n\t\tmaxTreeSize = maxSize;\n\t\tnodes = new ConcurrentHashMap<Key, TreeNode>(maxTreeSize);\n\t\troot = currentState.generateNode();\n\t\tnodes.put(root.getKey(), root);\n\t}\n\t\n\tpublic TreeNode getNode(Key k){\n\t\treturn nodes.get(k);\n\t}\n\t\n\tpublic void putNodeIfAbsent(TreeNode node){\n\t\tnodes.putIfAbsent(node.getKey(),node);\n\t}\n\t\n\tpublic TreeNode getRoot(){\n\t\treturn root;\n\t}\n\t\n\tpublic int getTreeSize(){\n\t\treturn nodes.size();\n\t}\n\t\t\n}",
"public class Key {\n\tprivate final int[] state;\n\tprivate final int[] belief;\n\t\n\tpublic Key(int[] s, int[] b) {\n\t\tstate = s;\n\t\tbelief = b;\n\t}\n\t\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif(obj instanceof Key){\n\t\t\treturn Arrays.equals(state, ((Key) obj).state) && Arrays.equals(belief, ((Key)obj).belief);\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n int result = 1;\n for (int element : state)\n result = 31 * result + element;\n \n if(belief != null) {\n for (int element : belief) {\n \tresult = 31 * result + element;\n }\n }\n \n return result;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn Arrays.toString(state);\n\t}\n\t\n}",
"public class StandardNode extends TreeNode{\n\t\n\tprivate ArrayList<Key> children;\n\t/**\n\t * The possible actions.\n\t */\n\tprivate ArrayList<int[]> actions;\n\t\n\t/**\n\t * The probabilities of actions to be legal.\n\t */\n\tprivate ArrayList<Double> actionProbs;\n\t\n\t//stats on actions required if afterstates are not used\n\tpublic int[] childVisits;\n\tpublic double[][] wins;\n\tpublic int[] vloss;\n\t\n\t/**\n\t * The P value (probability of selecting each action given a policy) of each\n\t * action in the same order as the children are set. At the moment this is\n\t * also used as value initialisation\n\t */\n\tpublic AtomicDoubleArray pValue;\n\t\n\tpublic StandardNode(int[] state, int[] belief, boolean terminal, int cpn) {\n\t\tsuper(state, belief, terminal, cpn);\n\t}\n\t\n\t/**\n\t * Adds the edges to the node.\n\t * @param children\n\t */\n\tpublic synchronized void addChildren(ArrayList<Key> children, ArrayList<int[]> acts, ArrayList<Double> actionProbs){\n\t\tif(!isLeaf())\n\t\t\treturn;\n\t\tthis.actions = acts;\n\t\tthis.children = children;\n\t\tthis.actionProbs = actionProbs;\n\t\t//initialise the pValue with a uniform distribution\n\t\tdouble[] dist = new double[children.size()];\n\t\tArrays.fill(dist, 1.0/children.size());\n\t\tpValue = new AtomicDoubleArray(dist);\n\t\t//stats on actions required only if afterstates are not used\n\t\tchildVisits = new int[children.size()];\n\t\twins = new double[GameFactory.nMaxPlayers()][];\n\t\tfor(int i = 0; i < GameFactory.nMaxPlayers(); i++){\n\t\t\twins[i] = new double[children.size()];\n\t\t}\n\t\tvloss = new int[children.size()];\n\t\tsetLeaf(false);\n\t}\n\t\n\tpublic ArrayList<Key> getChildren(){\n\t\treturn this.children;\n\t}\n\t\n\tpublic ArrayList<int[]> getActions(){\n\t\treturn this.actions;\n\t}\n\t\n\tpublic ArrayList<Double> getActionProbs(){\n\t\treturn this.actionProbs;\n\t}\n\t\n\tpublic boolean canExpand(){\n\t\treturn true;\n\t}\n\t\n\t/**\n\t * Used only if afterstates are not used, otherwise use the standard state update\n\t * @param reward\n\t * @param k\n\t * @param nRollouts\n\t */\n\tpublic synchronized void update(double[] reward, Key k, int nRollouts) {\n\t\tif(k != null)\n\t\tfor(int idx = 0; idx < children.size(); idx++){\n\t\t\tif(children.get(idx).equals(k)){\n\t\t\t\tfor(int i =0; i < wins.length; i++)\n\t\t\t\t\twins[i][idx]+=reward[i];\n\t\t\t\tvloss[idx] = 0;\n\t\t\t\tchildVisits[idx]+=nRollouts;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tnVisits+=nRollouts;\n\t}\n\t\n}",
"public abstract class TreeNode {\n\n\tprivate final int[] state;\n\tprivate final int[] belief;\n\t\n\tint nVisits;\n double[] wins;\n\tint vLoss;\n\tprivate final int currentPlayer;\n\tprivate boolean leaf = true;\n\tprivate final boolean terminal;\n\t/**\n\t * Field required for ISMCTS way of computing parentVisits when this node was legal\n\t */\n\tprivate int parentVisits;\n\t\n\t/**\n\t * Flag set when an external evaluation metric is used for seeding.\n\t */\n\tprivate boolean evaluated = false;\n\t\n\tpublic TreeNode(int[] state, int[] belief, boolean terminal, int cpn) {\n\t this.state = state;\n\t this.belief = belief;\n\t\tthis.terminal = terminal;\n\t\tcurrentPlayer = cpn;\n\t\tvLoss = 0;\n\t\tnVisits = 0;\n\t\tparentVisits = 0;\n\t wins = new double[GameFactory.nMaxPlayers()]; //TODO: find a way to set this value depending on the current game\n\t}\n\t\n\tpublic int getCurrentPlayer(){\n\t\treturn currentPlayer;\n\t}\n\t\n\t/**\n\t * @return a clone of the state\n\t */\n\tpublic int[] getState(){\n\t\treturn state.clone();\n\t}\n\t\n\tpublic boolean isLeaf(){\n\t\treturn leaf;\n\t}\n\t\n\tpublic void setLeaf(boolean leaf){\n\t\tthis.leaf = leaf;\n\t}\n\n\tpublic boolean isTerminal(){\n\t\treturn terminal;\n\t}\n\t\n\tpublic Key getKey(){\n\t\treturn new Key(state, belief);\n\t}\n\t\n\t/**\n\t * Update this node and remove the virtual loss.\n\t * \n\t * TODO: it remains to be seen if synchronising makes this too slow...\n\t * initial tests indicate this is a negligible increase, while it is\n\t * beneficial to synchronise the updates so that no results are lost\n\t */\n\tpublic synchronized void update(double[] reward, int nRollouts) {\n\t\tfor(int i = 0; i < wins.length; i++)\t\n\t\t\twins[i]+=reward[i];\n\t\tnVisits+=nRollouts;\n\t\tvLoss = 0;\n\t}\n\t\n\tpublic int getParentVisits() {\n\t\treturn parentVisits;\n\t}\n\t\n\tpublic void incrementParentVisits() {\n\t\tparentVisits++;\n\t}\n\t\n\tpublic double getWins(int pn) {\n\t\treturn wins[pn];\n\t}\n\t\n\tpublic int getnVisits() {\n\t\treturn nVisits;\n\t}\n\t\n\tpublic int getvLoss() {\n\t\treturn vLoss;\n\t}\n\t\n\tpublic void setEvaluated(boolean evaluated){\n\t\tthis.evaluated = evaluated;\n\t}\n\t\n\tpublic boolean isEvaluated(){\n\t\treturn evaluated;\n\t}\n\t\n\tpublic void incrementVLoss(){\n\t\tthis.vLoss++;\n\t}\n\t\n\t/**\n\t * Can this node be expanded?\n\t * \n\t * @return\n\t */\n\tpublic abstract boolean canExpand();\n\t\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif(obj instanceof TreeNode){\n\t\t\treturn Arrays.equals(state, ((TreeNode) obj).state);\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Arrays.hashCode(state);\n\t}\n\t\n}",
"public class Selection {\n\n\tprivate boolean b = false;\n\tprivate TreeNode node;\n\tprivate double actProb;\n\n\tpublic Selection(boolean b, TreeNode node, double prob) {\n\t\tthis.b = b;\n\t\tthis.node = node;\n\t\tthis.actProb = prob;\n\t}\n\n\tpublic boolean getBoolean() {\n\t\treturn b;\n\t}\n\n\tpublic TreeNode getNode() {\n\t\treturn node;\n\t}\n\t\n\tpublic double getActProb() {\n\t\treturn actProb;\n\t}\n}",
"public class Utils {\n\n\t\n public static ArrayList<Double> createActMask(ArrayList<int[]> stateActions, ArrayList<int[]> beliefActions){\n \tArrayList<Double> mask = new ArrayList<>(beliefActions.size());\n \t\n \t//this code works well and is faster if the order in which actions are listed is consistent...but this is not the case in Catan due to the discard action\n// \tint idx = 0;\n// \tfor(int[] act : stateActions) {\n// \t\twhile(idx < beliefActions.size()) {\n// \t\t\tif(Arrays.equals(act, beliefActions.get(idx))) {\n// \t\t\t\tmask.add(1.0);\n// \t\t\t\tidx++;\n// \t\t\t\tbreak;\n// \t\t\t}\n//\t\t\t\tmask.add(0.0);\n//\t\t\t\tidx++;\n// \t\t}\n// \t}\n// \t//pad the array to the correct size\n// \twhile(mask.size() != beliefActions.size())\n// \t\tmask.add(0.0);\n \t\n \t//this code is the safer but slightly slower option. It guarantees all actions are checked even if actions are not listed in the same order\n \tfor(int i = 0; i < beliefActions.size(); i++) {\n \t\tmask.add(0.0);\n \t\tint[] action = beliefActions.get(i);\n \t\tfor(int[] act : stateActions) {\n \t\t\tif(Arrays.equals(act, action)) {\n \t\t\t\tmask.set(i, 1.0);\n \t\t\t\tbreak;\n \t\t\t}\n \t\t}\n \t}\n \t\n \treturn mask;\n }\n}"
] | import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ThreadLocalRandom;
import com.google.common.util.concurrent.AtomicDoubleArray;
import mcts.game.Game;
import mcts.game.GameFactory;
import mcts.tree.Tree;
import mcts.tree.node.Key;
import mcts.tree.node.StandardNode;
import mcts.tree.node.TreeNode;
import mcts.utils.Selection;
import mcts.utils.Utils; | package mcts.tree.selection;
/**
* PUCT selection policy for handling a prior probability of certain actions
* being optimal (or for using an existing stochastic policy).
*
* @author sorinMD
*
*/
public class PUCT extends SelectionPolicy {
public PUCT() { }
/**
* Select node based on the best PUCT value.
* Ties are broken randomly.
* @param node
* @param tree
* @return
*/ | protected Selection selectChild(StandardNode node, Tree tree, GameFactory factory, Game obsGame){ | 6 |
zznate/intravert-ug | src/main/java/io/teknek/intravert/action/ActionFactory.java | [
"public class CreateColumnFamilyAction implements Action {\n\n @Override\n public void doAction(Operation operation, Response response, RequestContext request,\n ApplicationContext application) {\n String keyspace = (String) operation.getArguments().get(\"keyspace\");\n String columnFamily = (String) operation.getArguments().get(\"columnFamily\");\n boolean ignoreIfNotExists = (Boolean) operation.getArguments().get(\"ignoreIfNotExists\");\n if (!Schema.instance.getNonSystemTables().contains(keyspace)){\n throw new RuntimeException(\"keyspace \"+ keyspace + \" does not exist\");\n }\n KSMetaData ks = Schema.instance.getKSMetaData(keyspace);\n if (ks.cfMetaData().containsKey(columnFamily)){\n if (ignoreIfNotExists){\n response.getResults().put(operation.getId(), ResponseUtil.getDefaultHappy());\n return;\n } else {\n throw new RuntimeException (keyspace +\" already exists\");\n }\n }\n try {\n createColumnfamily(keyspace, columnFamily);\n } catch (InvalidRequestException | ConfigurationException e) {\n throw new RuntimeException(e);\n }\n response.getResults().put(operation.getId(), ResponseUtil.getDefaultHappy());\n }\n\n public static void createColumnfamily(String keyspace, String columnFamily) throws InvalidRequestException, ConfigurationException{\n CFMetaData cfm = null;\n CfDef def = new CfDef();\n def.unsetId();\n def.setKeyspace(keyspace);\n def.setName(columnFamily);\n cfm = CFMetaData.fromThrift(def);\n cfm.addDefaultIndexNames();\n MigrationManager.announceNewColumnFamily(cfm);\n }\n}",
"public class CreateFilterAction implements Action {\n\n public static final String IV_KEYSPACE = \"intravert\";\n public static final String FILTER_CF = \"filter\";\n \n @Override\n public void doAction(Operation operation, Response response, RequestContext request,\n ApplicationContext application) {\n String name = (String) operation.getArguments().get(\"name\");\n String scope = (String) operation.getArguments().get(\"scope\");\n NitDesc n = new NitDesc();\n n.setSpec(NitDesc.NitSpec.valueOf((String) operation.getArguments().get(\"spec\")));\n n.setTheClass((String) operation.getArguments().get(\"theClass\"));\n n.setScript((String) operation.getArguments().get(\"script\"));\n try {\n Filter f = FilterFactory.createFilter(io.teknek.nit.NitFactory.construct(n));\n if (\"session\".equalsIgnoreCase(scope)){\n request.getSession().putFilter(name, f);\n } else if (\"application\".equalsIgnoreCase(scope)){\n addFilterToCluster(f, n, name);\n application.putFilter(name, f);\n }\n } catch (NitException | WriteTimeoutException | InvalidRequestException | ConfigurationException | UnavailableException | OverloadedException e) {\n throw new RuntimeException(e);\n }\n Map m = new HashMap();\n m.put(Constants.RESULT, Constants.OK);\n response.getResults().put(operation.getId(), Arrays.asList(m));\n }\n\n \n public void maybeCreateColumnFamily() throws InvalidRequestException, ConfigurationException {\n List<String> keyspaces = Schema.instance.getNonSystemTables();\n if (!keyspaces.contains(IV_KEYSPACE)){\n CreateKeyspaceAction.createKeyspace(IV_KEYSPACE, 1);\n CFMetaData cfm = null;\n CfDef def = new CfDef();\n def.setKeyspace(IV_KEYSPACE);\n def.setName(FILTER_CF);\n cfm = CFMetaData.fromThrift(def);\n cfm.addDefaultIndexNames();\n MigrationManager.announceNewColumnFamily(cfm);\n }\n }\n \n public void addFilterToCluster(Filter f, NitDesc n, String name) throws InvalidRequestException, ConfigurationException, WriteTimeoutException, UnavailableException, OverloadedException{\n maybeCreateColumnFamily(); \n List<IMutation> changes = new ArrayList<>();\n {\n RowMutation rm = new RowMutation(IV_KEYSPACE, ByteBufferUtil.bytes(name));\n QueryPath qp = new QueryPath(FILTER_CF, null, ByteBufferUtil.bytes(\"spec\"));\n rm.add(qp, ByteBufferUtil.bytes(n.getSpec().toString()), System.nanoTime());\n changes.add(rm);\n }\n {\n RowMutation rm = new RowMutation(IV_KEYSPACE, ByteBufferUtil.bytes(name));\n QueryPath qp = new QueryPath(FILTER_CF, null, ByteBufferUtil.bytes(\"theClass\"));\n String cs = n.getTheClass() == null ? \"\" : n.getTheClass();\n rm.add(qp, ByteBufferUtil.bytes(cs), System.nanoTime());\n changes.add(rm);\n }\n {\n RowMutation rm = new RowMutation(IV_KEYSPACE, ByteBufferUtil.bytes(name));\n QueryPath qp = new QueryPath(FILTER_CF, null, ByteBufferUtil.bytes(\"script\"));\n String cs = n.getScript() == null ? \"\" : n.getScript();\n rm.add(qp, ByteBufferUtil.bytes(cs), System.nanoTime());\n changes.add(rm);\n } \n StorageProxy.mutate(changes, ConsistencyLevel.QUORUM);\n }\n}",
"public class CreateKeyspaceAction implements Action {\n\n @Override\n public void doAction(Operation operation, Response response, RequestContext request,\n ApplicationContext application) {\n String keyspace = (String) operation.getArguments().get(\"name\");\n int replication = (Integer) operation.getArguments().get(\"replication\");\n boolean ignoreIfNotExists = (Boolean) operation.getArguments().get(\"ignoreIfNotExists\");\n if (Schema.instance.getNonSystemTables().contains(keyspace)){\n if (ignoreIfNotExists){\n Map m = new HashMap();\n m.put(Constants.STATUS, Constants.OK);\n response.getResults().put(operation.getId(), Arrays.asList(m));\n return;\n } else {\n throw new RuntimeException (keyspace +\" already exists\");\n }\n }\n createKeyspace(keyspace, replication);\n Map m = new HashMap();\n m.put(Constants.STATUS, Constants.OK);\n response.getResults().put(operation.getId(), Arrays.asList(m));\n }\n\n public static void createKeyspace(String name, int replication){\n Collection<CFMetaData> cfDefs = new ArrayList<CFMetaData>(0);\n KsDef def = new KsDef();\n def.setName(name);\n def.setStrategy_class(\"SimpleStrategy\");\n Map<String, String> strat = new HashMap<String, String>();\n strat.put(\"replication_factor\", Integer.toString(replication));\n def.setStrategy_options(strat);\n KSMetaData ksm = null;\n try {\n ksm = KSMetaData.fromThrift(def,\n cfDefs.toArray(new CFMetaData[cfDefs.size()]));\n MigrationManager.announceNewKeyspace(ksm);\n } catch (ConfigurationException e) {\n throw new RuntimeException(e);\n }\n }\n}",
"public class GetKeyspaceAction implements Action {\n\n @Override\n public void doAction(Operation operator, Response response, RequestContext request,\n ApplicationContext application) {\n Map m = new HashMap();\n m.put(\"keyspace\", request.getSession().getCurrentKeyspace());\n response.getResults().put(operator.getId(), Arrays.asList(m));\n }\n\n}",
"public class SaveSessionAction implements Action {\n\n @Override\n public void doAction(Operation operator, Response respose, RequestContext request,\n ApplicationContext application) {\n respose.getResults().put(operator.getId(), ActionUtil.simpleResult(Constants.SESSION_ID, request.saveSession()));\n }\n\n}",
"public class LoadSessionAction implements Action {\n\n @Override\n public void doAction(Operation operator, Response response, RequestContext request,\n ApplicationContext application) {\n Long l = (Long) operator.getArguments().get(Constants.SESSION_ID);\n Session back = request.recoverSession(l);\n Map m = new HashMap();\n if (back != null){\n m.put(Constants.STATUS, Constants.OK);\n response.getResults().put(operator.getId(), Arrays.asList(m));\n } else {\n throw new RuntimeException(\"failed to recover session\");\n }\n }\n\n}",
"public class SetKeyspaceAction implements Action {\n\n @Override\n public void doAction(Operation o, Response response, RequestContext request,\n ApplicationContext application) {\n String name = (String) o.getArguments().get(\"name\");\n request.getSession().setCurrentKeyspace(name);\n response.getResults().put(o.getId(), ResponseUtil.getDefaultHappy());\n }\n\n}",
"public class SliceAction implements Action {\n\n @Override\n public void doAction(Operation operation, Response response, RequestContext request,\n ApplicationContext application) {\n String keyspace = (String) operation.getArguments().get(\"keyspace\");\n String columnFamily = (String) operation.getArguments().get(\"columnFamily\");\n Object rowkey = TypeUtil.convert(operation.getArguments().get(\"rowkey\"));\n Object start = TypeUtil.convert(operation.getArguments().get(\"start\"));\n Object end = TypeUtil.convert(operation.getArguments().get(\"end\"));\n List<ReadCommand> commands = new ArrayList<ReadCommand>(1);\n QueryPath path = new QueryPath(columnFamily, null);\n //TODO hardcode\n SliceFromReadCommand sr = new SliceFromReadCommand(keyspace,\n ByteBufferUtil.bytes((String)rowkey), path, ByteBufferUtil.bytes((String)start), ByteBufferUtil.bytes((String)end), false, 100);\n commands.add(sr);\n List<Row> results = null;\n List<Map> returnResults = new ArrayList<>();\n try {\n results = StorageProxy.read(commands, ConsistencyLevel.ONE);\n } catch (ReadTimeoutException | UnavailableException | IsBootstrappingException e) {\n throw new RuntimeException(e);\n }\n ColumnFamily cf = results.get(0).cf;\n if (cf == null) {\n response.getResults().put(operation.getId(), Arrays.asList(new HashMap()));\n return;\n }\n Iterator<IColumn> it = cf.iterator();\n while (it.hasNext()) {\n IColumn column = it.next();\n if (column.isLive()) {\n HashMap<String,Object> m = new HashMap<>(4);\n //TODO hard code\n try {\n m.put(\"name\", ByteBufferUtil.string(column.name()));\n m.put(\"value\", ByteBufferUtil.string(column.value()));\n } catch (CharacterCodingException e) {\n e.printStackTrace();\n }\n returnResults.add(m);\n }\n }\n response.getResults().put(operation.getId(), returnResults);\n }\n\n \n}",
"public class UpsertAction implements Action {\n\n @Override\n public void doAction(Operation operation, Response response, RequestContext request,\n ApplicationContext application) {\n String keyspace = (String) operation.getArguments().get(\"keyspace\");\n String columnFamily = (String) operation.getArguments().get(\"columnFamily\");\n Object rowkey = TypeUtil.convert(operation.getArguments().get(\"rowkey\"));\n Object column = TypeUtil.convert(operation.getArguments().get(\"column\"));\n Object value = TypeUtil.convert(operation.getArguments().get(\"value\"));\n List<IMutation> changes = new ArrayList<>();\n RowMutation rm = new RowMutation(keyspace, ByteBufferUtil.bytes((String)rowkey));\n QueryPath qp = new QueryPath(columnFamily, null, ByteBufferUtil.bytes((String) column));\n rm.add(qp, ByteBufferUtil.bytes((String) value), System.nanoTime());\n changes.add(rm);\n try {\n StorageProxy.mutate(changes, ConsistencyLevel.QUORUM);\n } catch (WriteTimeoutException | UnavailableException | OverloadedException e) {\n throw new RuntimeException(e);\n }\n response.getResults().put(operation.getId(), ResponseUtil.getDefaultHappy());\n \n }\n\n}"
] | import java.util.HashMap;
import java.util.Map;
import io.teknek.intravert.action.impl.CreateColumnFamilyAction;
import io.teknek.intravert.action.impl.CreateFilterAction;
import io.teknek.intravert.action.impl.CreateKeyspaceAction;
import io.teknek.intravert.action.impl.GetKeyspaceAction;
import io.teknek.intravert.action.impl.SaveSessionAction;
import io.teknek.intravert.action.impl.LoadSessionAction;
import io.teknek.intravert.action.impl.SetKeyspaceAction;
import io.teknek.intravert.action.impl.SliceAction;
import io.teknek.intravert.action.impl.UpsertAction; | package io.teknek.intravert.action;
public class ActionFactory {
public static final String CREATE_SESSION = "createsession";
public static final String LOAD_SESSION = "loadsession";
public static final String SET_KEYSPACE = "setkeyspace";
public static final String GET_KEYSPACE = "getkeyspace";
public static final String CREATE_FILTER = "createfilter";
public static final String UPSERT = "upsert";
public static final String CREATE_KEYSPACE = "createkeyspace";
public static final String CREATE_COLUMN_FAMILY ="createcolumnfamily";
public static final String SLICE ="slice";
private Map<String,Action> actions;
public ActionFactory(){
actions = new HashMap<String,Action>();
actions.put(CREATE_SESSION, new SaveSessionAction()); | actions.put(LOAD_SESSION, new LoadSessionAction()); | 5 |
badvision/jace | src/main/java/jace/cheat/MetaCheat.java | [
"public class Emulator {\r\n\r\n public static Emulator instance;\r\n public static EmulatorUILogic logic = new EmulatorUILogic();\r\n public static Thread mainThread;\r\n\r\n// public static void main(String... args) {\r\n// mainThread = Thread.currentThread();\r\n// instance = new Emulator(args);\r\n// }\r\n\r\n public static Apple2e computer;\r\n\r\n /**\r\n * Creates a new instance of Emulator\r\n * @param args\r\n */\r\n public Emulator(List<String> args) {\r\n instance = this;\r\n computer = new Apple2e();\r\n Configuration.buildTree();\r\n Configuration.loadSettings();\r\n mainThread = Thread.currentThread();\r\n applyConfiguration(args);\r\n }\r\n\r\n public void applyConfiguration(List<String> args) {\r\n Map<String, String> settings = new LinkedHashMap<>();\r\n if (args != null) {\r\n for (int i = 0; i < args.size(); i++) {\r\n if (args.get(i).startsWith(\"-\")) {\r\n String key = args.get(i).substring(1);\r\n if ((i + 1) < args.size()) {\r\n String val = args.get(i + 1);\r\n if (!val.startsWith(\"-\")) {\r\n settings.put(key, val);\r\n i++;\r\n } else {\r\n settings.put(key, \"true\");\r\n }\r\n } else {\r\n settings.put(key, \"true\");\r\n }\r\n } else {\r\n System.err.println(\"Did not understand parameter \" + args.get(i) + \", skipping.\");\r\n }\r\n }\r\n }\r\n Configuration.applySettings(settings);\r\n// EmulatorUILogic.registerDebugger();\r\n// computer.coldStart();\r\n }\r\n\r\n public static void resizeVideo() {\r\n// AbstractEmulatorFrame window = getFrame();\r\n// if (window != null) {\r\n// window.resizeVideo();\r\n// }\r\n }\r\n}",
"public class JaceApplication extends Application {\n\n static JaceApplication singleton;\n\n public Stage primaryStage;\n JaceUIController controller;\n\n static boolean romStarted = false;\n\n @Override\n public void start(Stage stage) throws Exception {\n singleton = this;\n primaryStage = stage;\n FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(\"/fxml/JaceUI.fxml\"));\n fxmlLoader.setResources(null);\n try {\n AnchorPane node = (AnchorPane) fxmlLoader.load();\n controller = fxmlLoader.getController();\n controller.initialize();\n Scene s = new Scene(node);\n primaryStage.setScene(s);\n primaryStage.setTitle(\"Jace\");\n EmulatorUILogic.scaleIntegerRatio();\n Utility.loadIcon(\"woz_figure.gif\").ifPresent(primaryStage.getIcons()::add);\n } catch (IOException exception) {\n throw new RuntimeException(exception);\n }\n\n primaryStage.show();\n new Thread(() -> {\n new Emulator(getParameters().getRaw());\n reconnectUIHooks();\n EmulatorUILogic.scaleIntegerRatio();\n while (Emulator.computer.getVideo() == null || Emulator.computer.getVideo().getFrameBuffer() == null) {\n Thread.yield();\n }\n bootWatchdog();\n }).start();\n primaryStage.setOnCloseRequest(event -> {\n Emulator.computer.deactivate();\n Platform.exit();\n System.exit(0);\n });\n }\n\n public void reconnectUIHooks() {\n controller.connectComputer(Emulator.computer, primaryStage); \n }\n\n public static JaceApplication getApplication() {\n return singleton;\n }\n\n Stage cheatStage;\n private MetacheatUI cheatController;\n\n public MetacheatUI showMetacheat() {\n if (cheatController == null) {\n cheatStage = new Stage(StageStyle.DECORATED);\n FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(\"/fxml/Metacheat.fxml\"));\n fxmlLoader.setResources(null);\n try {\n VBox node = fxmlLoader.load();\n cheatController = fxmlLoader.getController();\n Scene s = new Scene(node);\n cheatStage.setScene(s);\n cheatStage.setTitle(\"Jace: MetaCheat\");\n Utility.loadIcon(\"woz_figure.gif\").ifPresent(cheatStage.getIcons()::add);\n } catch (IOException exception) {\n throw new RuntimeException(exception);\n }\n\n }\n cheatStage.show();\n return cheatController;\n }\n\n /**\n * @param args the command line arguments\n */\n public static void main(String[] args) {\n launch(args);\n }\n\n /**\n * Start the computer and make sure it runs through the expected rom routine\n * for cold boot\n */\n private void bootWatchdog() {\n romStarted = false;\n RAMListener startListener = Emulator.computer.getMemory().\n observe(RAMEvent.TYPE.EXECUTE, 0x0FA62, (e) -> {\n romStarted = true;\n });\n Emulator.computer.coldStart();\n try {\n Thread.sleep(250);\n if (!romStarted) {\n Logger.getLogger(getClass().getName()).log(Level.WARNING, \"Boot not detected, performing a cold start\");\n Emulator.computer.coldStart();\n }\n } catch (InterruptedException ex) {\n Logger.getLogger(JaceApplication.class.getName()).log(Level.SEVERE, null, ex);\n }\n Emulator.computer.getMemory().removeListener(startListener);\n }\n\n}",
"public abstract class CPU extends Device {\r\n private static final Logger LOG = Logger.getLogger(CPU.class.getName());\r\n\r\n public CPU(Computer computer) {\r\n super(computer);\r\n }\r\n \r\n @Override\r\n public String getShortName() {\r\n return \"cpu\";\r\n }\r\n private Debugger debugger = null;\r\n @ConfigurableField(name = \"Enable trace to STDOUT\", shortName = \"trace\")\r\n public boolean trace = false;\r\n\r\n public boolean isTraceEnabled() {\r\n return trace;\r\n }\r\n\r\n public void setTraceEnabled(boolean t) {\r\n trace = t;\r\n }\r\n @ConfigurableField(name = \"Trace length\", shortName = \"traceSize\", description = \"Number of most recent trace lines to keep for debugging errors. Zero == disabled\")\r\n public int traceLength = 0;\r\n private ArrayList<String> traceLog = new ArrayList<>();\r\n\r\n public boolean isLogEnabled() {\r\n return (traceLength > 0);\r\n }\r\n\r\n public void log(String line) {\r\n if (!isLogEnabled()) {\r\n return;\r\n }\r\n while (traceLog.size() >= traceLength) {\r\n traceLog.remove(0);\r\n }\r\n traceLog.add(line);\r\n }\r\n \r\n public void dumpTrace() {\r\n computer.pause();\r\n ArrayList<String> newLog = new ArrayList<>();\r\n ArrayList<String> oldLog = traceLog;\r\n traceLog = newLog;\r\n computer.resume();\r\n LOG.log(Level.INFO, \"Most recent {0} instructions:\", traceLength);\r\n oldLog.stream().forEach(LOG::info);\r\n oldLog.clear();\r\n }\r\n\r\n public void setDebug(Debugger d) {\r\n debugger = d;\r\n suspend();\r\n }\r\n\r\n public void clearDebug() {\r\n debugger = null;\r\n resume();\r\n }\r\n //@ConfigurableField(name=\"Program Counter\")\r\n public int programCounter = 0;\r\n\r\n public int getProgramCounter() {\r\n return programCounter;\r\n }\r\n\r\n public void setProgramCounter(int programCounter) {\r\n this.programCounter = 0x00FFFF & programCounter;\r\n }\r\n\r\n public void incrementProgramCounter(int amount) {\r\n this.programCounter += amount;\r\n this.programCounter = 0x00FFFF & this.programCounter;\r\n }\r\n\r\n /**\r\n * Process a single tick of the main processor clock. Either we're waiting\r\n * to execute the next instruction, or the next instruction is ready to go\r\n */\r\n @Override\r\n public void tick() {\r\n try {\r\n if (debugger != null) {\r\n if (!debugger.isActive() && debugger.hasBreakpoints()) {\r\n debugger.getBreakpoints().stream().filter((i) -> (i == getProgramCounter())).forEach((_item) -> {\r\n debugger.setActive(true);\r\n });\r\n }\r\n if (debugger.isActive()) {\r\n debugger.updateStatus();\r\n if (!debugger.takeStep()) {\r\n // If the debugger is active and we aren't ready for the next step, sleep and exit\r\n // Without the sleep, this would constitute a very rapid-fire loop and would eat\r\n // an unnecessary amount of CPU.\r\n try {\r\n Thread.sleep(10);\r\n } catch (InterruptedException ex) {\r\n Logger.getLogger(CPU.class.getName()).log(Level.SEVERE, null, ex);\r\n }\r\n return;\r\n }\r\n }\r\n }\r\n } catch (Throwable t) {\r\n // ignore\r\n }\r\n executeOpcode();\r\n }\r\n /*\r\n * Execute the current opcode at the current program counter\r\n *@return number of cycles to wait until next command can be executed\r\n */\r\n\r\n protected abstract void executeOpcode();\r\n\r\n public abstract void reset();\r\n\r\n public abstract void generateInterrupt();\r\n\r\n abstract public void pushPC();\r\n\r\n @Override\r\n public void attach() {\r\n }\r\n\r\n abstract public void JSR(int pointer);\r\n\r\n boolean singleTraceEnabled = false;\r\n public String lastTrace = \"START\";\r\n public void performSingleTrace() {\r\n singleTraceEnabled = true;\r\n }\r\n public boolean isSingleTraceEnabled() {\r\n return singleTraceEnabled;\r\n }\r\n public String getLastTrace() {\r\n return lastTrace;\r\n }\r\n public void captureSingleTrace(String trace) {\r\n lastTrace = trace;\r\n singleTraceEnabled = false;\r\n }\r\n\r\n abstract public void clearState();\r\n}",
"public abstract class Computer implements Reconfigurable {\n\n public RAM memory;\n public CPU cpu;\n public Video video;\n public Keyboard keyboard;\n public StateManager stateManager;\n public Motherboard motherboard;\n public boolean romLoaded;\n @ConfigurableField(category = \"advanced\", name = \"State management\", shortName = \"rewind\", description = \"This enables rewind support, but consumes a lot of memory when active.\")\n public boolean enableStateManager;\n public final SoundMixer mixer;\n final private BooleanProperty runningProperty = new SimpleBooleanProperty(false);\n\n /**\n * Creates a new instance of Computer\n */\n public Computer() {\n keyboard = new Keyboard(this);\n mixer = new SoundMixer(this);\n romLoaded = false;\n }\n\n public RAM getMemory() {\n return memory;\n }\n\n public Motherboard getMotherboard() {\n return motherboard;\n }\n\n ChangeListener<Boolean> runningPropertyListener = (prop, oldVal, newVal) -> runningProperty.set(newVal);\n public void setMotherboard(Motherboard m) {\n if (motherboard != null && motherboard.isRunning()) {\n motherboard.suspend();\n }\n motherboard = m;\n }\n\n public BooleanProperty getRunningProperty() {\n return runningProperty;\n }\n \n public boolean isRunning() {\n return getRunningProperty().get();\n }\n \n public void notifyVBLStateChanged(boolean state) {\n for (Optional<Card> c : getMemory().cards) {\n c.ifPresent(card -> card.notifyVBLStateChanged(state));\n }\n if (state && stateManager != null) {\n stateManager.notifyVBLActive();\n }\n }\n\n public void setMemory(RAM memory) {\n if (this.memory != memory) {\n if (this.memory != null) {\n this.memory.detach();\n }\n memory.attach();\n }\n this.memory = memory;\n }\n\n public void waitForNextCycle() {\n //@TODO IMPLEMENT TIMER SLEEP CODE!\n }\n\n public Video getVideo() {\n return video;\n }\n\n public void setVideo(Video video) {\n this.video = video;\n }\n\n public CPU getCpu() {\n return cpu;\n }\n\n public void setCpu(CPU cpu) {\n this.cpu = cpu;\n }\n\n public void loadRom(String path) throws IOException {\n memory.loadRom(path);\n romLoaded = true;\n }\n\n public void deactivate() {\n if (cpu != null) {\n cpu.suspend();\n }\n if (motherboard != null) {\n motherboard.suspend();\n }\n if (video != null) {\n video.suspend(); \n }\n if (mixer != null) {\n mixer.detach();\n }\n }\n\n @InvokableAction(\n name = \"Cold boot\",\n description = \"Process startup sequence from power-up\",\n category = \"general\",\n alternatives = \"Full reset;reset emulator\",\n consumeKeyEvent = true,\n defaultKeyMapping = {\"Ctrl+Shift+Backspace\", \"Ctrl+Shift+Delete\"})\n public void invokeColdStart() {\n if (!romLoaded) {\n Thread delayedStart = new Thread(() -> {\n while (!romLoaded) {\n Thread.yield();\n }\n coldStart();\n });\n delayedStart.start();\n } else {\n coldStart();\n }\n }\n\n public abstract void coldStart();\n\n @InvokableAction(\n name = \"Warm boot\",\n description = \"Process user-initatiated reboot (ctrl+apple+reset)\",\n category = \"general\",\n alternatives = \"reboot;reset;three-finger-salute;restart\",\n defaultKeyMapping = {\"Ctrl+Ignore Alt+Ignore Meta+Backspace\", \"Ctrl+Ignore Alt+Ignore Meta+Delete\"})\n public void invokeWarmStart() {\n warmStart();\n }\n\n public abstract void warmStart();\n\n public Keyboard getKeyboard() {\n return this.keyboard;\n }\n\n protected abstract void doPause();\n\n protected abstract void doResume();\n\n @InvokableAction(name = \"Pause\", description = \"Stops the computer, allowing reconfiguration of core elements\", alternatives = \"freeze;halt\", defaultKeyMapping = {\"meta+pause\", \"alt+pause\"})\n public boolean pause() {\n boolean result = getRunningProperty().get();\n doPause();\n getRunningProperty().set(false);\n return result;\n }\n\n @InvokableAction(name = \"Resume\", description = \"Resumes the computer if it was previously paused\", alternatives = \"unpause;unfreeze;resume;play\", defaultKeyMapping = {\"meta+shift+pause\", \"alt+shift+pause\"})\n public void resume() {\n doResume();\n getRunningProperty().set(true);\n }\n\n @Override\n public void reconfigure() {\n mixer.reconfigure();\n if (enableStateManager) {\n stateManager = StateManager.getInstance(this);\n } else {\n stateManager = null;\n StateManager.getInstance(this).invalidate();\n }\n }\n}",
"public abstract class RAM implements Reconfigurable {\r\n\r\n public PagedMemory activeRead;\r\n public PagedMemory activeWrite;\r\n public List<RAMListener> listeners;\r\n public List<RAMListener>[] listenerMap;\r\n public List<RAMListener>[] ioListenerMap;\r\n public Optional<Card>[] cards;\r\n // card 0 = 80 column card firmware / system rom\r\n public int activeSlot = 0;\r\n protected final Computer computer;\r\n\r\n /**\r\n * Creates a new instance of RAM\r\n *\r\n * @param computer\r\n */\r\n public RAM(Computer computer) {\r\n this.computer = computer;\r\n listeners = new ArrayList<>();\r\n cards = new Optional[8];\r\n for (int i = 0; i < 8; i++) {\r\n cards[i] = Optional.empty();\r\n }\r\n refreshListenerMap();\r\n }\r\n\r\n public void setActiveCard(int slot) {\r\n if (activeSlot != slot) {\r\n activeSlot = slot;\r\n configureActiveMemory();\r\n } else if (!SoftSwitches.CXROM.getState()) {\r\n configureActiveMemory();\r\n }\r\n }\r\n\r\n public int getActiveSlot() {\r\n return activeSlot;\r\n }\r\n\r\n public Optional<Card>[] getAllCards() {\r\n return cards;\r\n }\r\n\r\n public Optional<Card> getCard(int slot) {\r\n if (slot >= 1 && slot <= 7) {\r\n return cards[slot];\r\n }\r\n return Optional.empty();\r\n }\r\n\r\n public void addCard(Card c, int slot) {\r\n removeCard(slot);\r\n cards[slot] = Optional.of(c);\r\n c.setSlot(slot);\r\n c.attach();\r\n }\r\n\r\n public void removeCard(Card c) {\r\n c.suspend();\r\n c.detach();\r\n removeCard(c.getSlot());\r\n }\r\n\r\n public void removeCard(int slot) {\r\n cards[slot].ifPresent(Card::suspend);\r\n cards[slot].ifPresent(Card::detach);\r\n cards[slot] = Optional.empty();\r\n }\r\n\r\n abstract public void configureActiveMemory();\r\n\r\n public void write(int address, byte b, boolean generateEvent, boolean requireSynchronization) {\r\n byte[] page = activeWrite.getMemoryPage(address);\r\n if (page == null) {\r\n if (generateEvent) {\r\n callListener(RAMEvent.TYPE.WRITE, address, 0, b, requireSynchronization);\r\n }\r\n } else {\r\n int offset = address & 0x0FF;\r\n byte old = page[offset];\r\n if (generateEvent) {\r\n page[offset] = callListener(RAMEvent.TYPE.WRITE, address, old, b, requireSynchronization);\r\n } else {\r\n page[offset] = b;\r\n }\r\n }\r\n }\r\n\r\n public void writeWord(int address, int w, boolean generateEvent, boolean requireSynchronization) {\r\n write(address, (byte) (w & 0x0ff), generateEvent, requireSynchronization);\r\n write(address + 1, (byte) (w >> 8), generateEvent, requireSynchronization);\r\n }\r\n \r\n public byte readRaw(int address) {\r\n // if (address >= 65536) return 0;\r\n return activeRead.getMemoryPage(address)[address & 0x0FF];\r\n }\r\n\r\n public byte read(int address, RAMEvent.TYPE eventType, boolean triggerEvent, boolean requireSyncronization) {\r\n // if (address >= 65536) return 0;\r\n byte value = activeRead.getMemoryPage(address)[address & 0x0FF];\r\n// if (triggerEvent || ((address & 0x0FF00) == 0x0C000)) {\r\n if (triggerEvent || (address & 0x0FFF0) == 0x0c030) {\r\n value = callListener(eventType, address, value, value, requireSyncronization);\r\n }\r\n return value;\r\n }\r\n\r\n public int readWordRaw(int address) {\r\n int lsb = 0x00ff & readRaw(address);\r\n int msb = (0x00ff & readRaw(address + 1)) << 8;\r\n return msb + lsb;\r\n }\r\n\r\n public int readWord(int address, RAMEvent.TYPE eventType, boolean triggerEvent, boolean requireSynchronization) {\r\n int lsb = 0x00ff & read(address, eventType, triggerEvent, requireSynchronization);\r\n int msb = (0x00ff & read(address + 1, eventType, triggerEvent, requireSynchronization)) << 8;\r\n int value = msb + lsb;\r\n return value;\r\n }\r\n\r\n private void mapListener(RAMListener l, int address) {\r\n if ((address & 0x0FF00) == 0x0C000) {\r\n int index = address & 0x0FF;\r\n List<RAMListener> ioListeners = ioListenerMap[index];\r\n if (ioListeners == null) {\r\n ioListeners = new ArrayList<>();\r\n ioListenerMap[index] = ioListeners;\r\n }\r\n if (!ioListeners.contains(l)) {\r\n ioListeners.add(l);\r\n }\r\n } else {\r\n int index = address >> 8;\r\n List<RAMListener> otherListeners = listenerMap[index];\r\n if (otherListeners == null) {\r\n otherListeners = new ArrayList<>();\r\n listenerMap[index] = otherListeners;\r\n }\r\n if (!otherListeners.contains(l)) {\r\n otherListeners.add(l);\r\n }\r\n }\r\n }\r\n\r\n private void addListenerRange(RAMListener l) {\r\n if (l.getScope() == RAMEvent.SCOPE.ADDRESS) {\r\n mapListener(l, l.getScopeStart());\r\n } else {\r\n int start = 0;\r\n int end = 0x0ffff;\r\n if (l.getScope() == RAMEvent.SCOPE.RANGE) {\r\n start = l.getScopeStart();\r\n end = l.getScopeEnd();\r\n }\r\n for (int i = start; i <= end; i++) {\r\n mapListener(l, i);\r\n }\r\n }\r\n }\r\n\r\n private void refreshListenerMap() {\r\n listenerMap = new ArrayList[256];\r\n ioListenerMap = new ArrayList[256];\r\n listeners.stream().forEach((l) -> {\r\n addListenerRange(l);\r\n });\r\n }\r\n\r\n public RAMListener observe(RAMEvent.TYPE type, int address, RAMEvent.RAMEventHandler handler) {\r\n return addListener(new RAMListener(type, RAMEvent.SCOPE.ADDRESS, RAMEvent.VALUE.ANY) {\r\n @Override\r\n protected void doConfig() {\r\n setScopeStart(address);\r\n }\r\n\r\n @Override\r\n protected void doEvent(RAMEvent e) {\r\n handler.handleEvent(e);\r\n }\r\n });\r\n }\r\n\r\n public RAMListener observe(RAMEvent.TYPE type, int address, boolean auxFlag, RAMEvent.RAMEventHandler handler) {\r\n return addListener(new RAMListener(type, RAMEvent.SCOPE.ADDRESS, RAMEvent.VALUE.ANY) {\r\n @Override\r\n protected void doConfig() {\r\n setScopeStart(address);\r\n }\r\n\r\n @Override\r\n protected void doEvent(RAMEvent e) {\r\n if (isAuxFlagCorrect(e, auxFlag)) {\r\n handler.handleEvent(e);\r\n }\r\n }\r\n });\r\n }\r\n\r\n public RAMListener observe(RAMEvent.TYPE type, int addressStart, int addressEnd, RAMEvent.RAMEventHandler handler) {\r\n return addListener(new RAMListener(type, RAMEvent.SCOPE.RANGE, RAMEvent.VALUE.ANY) {\r\n @Override\r\n protected void doConfig() {\r\n setScopeStart(addressStart);\r\n setScopeEnd(addressEnd);\r\n }\r\n\r\n @Override\r\n protected void doEvent(RAMEvent e) {\r\n handler.handleEvent(e);\r\n }\r\n });\r\n }\r\n\r\n public RAMListener observe(RAMEvent.TYPE type, int addressStart, int addressEnd, boolean auxFlag, RAMEvent.RAMEventHandler handler) {\r\n return addListener(new RAMListener(type, RAMEvent.SCOPE.RANGE, RAMEvent.VALUE.ANY) {\r\n @Override\r\n protected void doConfig() {\r\n setScopeStart(addressStart);\r\n setScopeEnd(addressEnd);\r\n }\r\n\r\n @Override\r\n protected void doEvent(RAMEvent e) {\r\n if (isAuxFlagCorrect(e, auxFlag)) {\r\n handler.handleEvent(e);\r\n }\r\n }\r\n });\r\n }\r\n\r\n private boolean isAuxFlagCorrect(RAMEvent e, boolean auxFlag) {\r\n if (e.getAddress() < 0x0100) {\r\n if (SoftSwitches.AUXZP.getState() != auxFlag) {\r\n return false;\r\n }\r\n } else if (SoftSwitches.RAMRD.getState() != auxFlag) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n public RAMListener addListener(final RAMListener l) {\r\n boolean restart = computer.pause();\r\n if (listeners.contains(l)) {\r\n return l;\r\n }\r\n listeners.add(l);\r\n addListenerRange(l);\r\n if (restart) {\r\n computer.resume();\r\n }\r\n return l;\r\n }\r\n\r\n public void removeListener(final RAMListener l) {\r\n boolean restart = computer.pause();\r\n listeners.remove(l);\r\n refreshListenerMap();\r\n if (restart) {\r\n computer.resume();\r\n }\r\n }\r\n\r\n public byte callListener(RAMEvent.TYPE t, int address, int oldValue, int newValue, boolean requireSyncronization) {\r\n List<RAMListener> activeListeners;\r\n if (requireSyncronization) {\r\n computer.getCpu().suspend();\r\n }\r\n if ((address & 0x0FF00) == 0x0C000) {\r\n activeListeners = ioListenerMap[address & 0x0FF];\r\n if (activeListeners == null && t.isRead()) {\r\n if (requireSyncronization) {\r\n computer.getCpu().resume();\r\n }\r\n return computer.getVideo().getFloatingBus();\r\n }\r\n } else {\r\n activeListeners = listenerMap[(address >> 8) & 0x0ff];\r\n }\r\n if (activeListeners != null) {\r\n RAMEvent e = new RAMEvent(t, RAMEvent.SCOPE.ADDRESS, RAMEvent.VALUE.ANY, address, oldValue, newValue);\r\n activeListeners.stream().forEach((l) -> {\r\n l.handleEvent(e);\r\n });\r\n if (requireSyncronization) {\r\n computer.getCpu().resume();\r\n }\r\n return (byte) e.getNewValue();\r\n }\r\n if (requireSyncronization) {\r\n computer.getCpu().resume();\r\n }\r\n return (byte) newValue;\r\n }\r\n\r\n abstract protected void loadRom(String path) throws IOException;\r\n\r\n abstract public void attach();\r\n\r\n abstract public void detach();\r\n\r\n abstract public void performExtendedCommand(int i);\r\n}\r",
"public class RAMEvent {\r\n\r\n static public interface RAMEventHandler {\r\n public void handleEvent(RAMEvent e);\r\n }\r\n\r\n public enum TYPE {\r\n\r\n READ(true),\r\n READ_DATA(true),\r\n EXECUTE(true),\r\n READ_OPERAND(true),\r\n WRITE(false),\r\n ANY(false);\r\n boolean read = false;\r\n\r\n TYPE(boolean r) {\r\n this.read = r;\r\n }\r\n\r\n public boolean isRead() {\r\n return read;\r\n }\r\n };\r\n\r\n public enum SCOPE {\r\n\r\n ADDRESS,\r\n RANGE,\r\n ANY\r\n };\r\n\r\n public enum VALUE {\r\n\r\n ANY,\r\n RANGE,\r\n EQUALS,\r\n NOT_EQUALS,\r\n CHANGE_BY\r\n };\r\n private TYPE type;\r\n private SCOPE scope;\r\n private VALUE value;\r\n private int address, oldValue, newValue;\r\n\r\n /**\r\n * Creates a new instance of RAMEvent\r\n * @param t\r\n * @param s\r\n * @param v\r\n * @param address\r\n * @param oldValue\r\n * @param newValue\r\n */\r\n public RAMEvent(TYPE t, SCOPE s, VALUE v, int address, int oldValue, int newValue) {\r\n setType(t);\r\n setScope(s);\r\n setValue(v);\r\n this.setAddress(address);\r\n this.setOldValue(oldValue);\r\n this.setNewValue(newValue);\r\n }\r\n\r\n public TYPE getType() {\r\n return type;\r\n }\r\n\r\n public final void setType(TYPE type) {\r\n this.type = type;\r\n }\r\n\r\n public SCOPE getScope() {\r\n return scope;\r\n }\r\n\r\n public final void setScope(SCOPE scope) {\r\n this.scope = scope;\r\n }\r\n\r\n public VALUE getValue() {\r\n return value;\r\n }\r\n\r\n public final void setValue(VALUE value) {\r\n this.value = value;\r\n }\r\n\r\n public int getAddress() {\r\n return address;\r\n }\r\n\r\n public final void setAddress(int address) {\r\n this.address = address;\r\n }\r\n\r\n public int getOldValue() {\r\n return oldValue;\r\n }\r\n\r\n public final void setOldValue(int oldValue) {\r\n this.oldValue = oldValue;\r\n }\r\n\r\n public int getNewValue() {\r\n return newValue;\r\n }\r\n\r\n public final void setNewValue(int newValue) {\r\n this.newValue = newValue;\r\n }\r\n}\r",
"public abstract class RAMListener implements RAMEvent.RAMEventHandler {\r\n \r\n private RAMEvent.TYPE type;\r\n private RAMEvent.SCOPE scope;\r\n private RAMEvent.VALUE value;\r\n private int scopeStart;\r\n private int scopeEnd;\r\n private int valueStart;\r\n private int valueEnd;\r\n private int valueAmount;\r\n\r\n /**\r\n * Creates a new instance of RAMListener\r\n * @param t\r\n * @param s\r\n * @param v\r\n */\r\n public RAMListener(RAMEvent.TYPE t, RAMEvent.SCOPE s, RAMEvent.VALUE v) {\r\n setType(t);\r\n setScope(s);\r\n setValue(v);\r\n doConfig();\r\n }\r\n\r\n public RAMEvent.TYPE getType() {\r\n return type;\r\n }\r\n\r\n public final void setType(RAMEvent.TYPE type) {\r\n this.type = type;\r\n }\r\n\r\n public RAMEvent.SCOPE getScope() {\r\n return scope;\r\n }\r\n\r\n public final void setScope(RAMEvent.SCOPE scope) {\r\n this.scope = scope;\r\n }\r\n\r\n public RAMEvent.VALUE getValue() {\r\n return value;\r\n }\r\n\r\n public final void setValue(RAMEvent.VALUE value) {\r\n this.value = value;\r\n }\r\n\r\n public int getScopeStart() {\r\n return scopeStart;\r\n }\r\n\r\n public void setScopeStart(int scopeStart) {\r\n this.scopeStart = scopeStart;\r\n }\r\n\r\n public int getScopeEnd() {\r\n return scopeEnd;\r\n }\r\n\r\n public void setScopeEnd(int scopeEnd) {\r\n this.scopeEnd = scopeEnd;\r\n }\r\n\r\n public int getValueStart() {\r\n return valueStart;\r\n }\r\n\r\n public void setValueStart(int valueStart) {\r\n this.valueStart = valueStart;\r\n }\r\n\r\n public int getValueEnd() {\r\n return valueEnd;\r\n }\r\n\r\n public void setValueEnd(int valueEnd) {\r\n this.valueEnd = valueEnd;\r\n }\r\n\r\n public int getValueAmount() {\r\n return valueAmount;\r\n }\r\n\r\n public void setValueAmount(int valueAmount) {\r\n this.valueAmount = valueAmount;\r\n }\r\n\r\n public boolean isRelevant(RAMEvent e) {\r\n // Skip event if it's not the right type\r\n if (type != TYPE.ANY && e.getType() != TYPE.ANY) {\r\n if ((type != e.getType())) {\r\n if (type == TYPE.READ) {\r\n if (!e.getType().isRead()) {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n }\r\n }\r\n // Skip event if it's not in the scope we care about\r\n if (scope != RAMEvent.SCOPE.ANY) {\r\n if (scope == RAMEvent.SCOPE.ADDRESS && e.getAddress() != scopeStart) {\r\n return false;\r\n } else if (scope == RAMEvent.SCOPE.RANGE && (e.getAddress() < scopeStart || e.getAddress() > scopeEnd)) {\r\n return false;\r\n }\r\n }\r\n\r\n // Skip event if the value modification is uninteresting\r\n if (value != RAMEvent.VALUE.ANY) {\r\n if (value == RAMEvent.VALUE.CHANGE_BY && e.getNewValue() - e.getOldValue() != valueAmount) {\r\n return false;\r\n } else if (value == RAMEvent.VALUE.EQUALS && e.getNewValue() != valueAmount) {\r\n return false;\r\n } else if (value == RAMEvent.VALUE.NOT_EQUALS && e.getNewValue() == valueAmount) {\r\n return false;\r\n } else if (value == RAMEvent.VALUE.RANGE && (e.getNewValue() < valueStart || e.getNewValue() > valueEnd)) {\r\n return false;\r\n }\r\n }\r\n\r\n // Ok, so we've filtered out the uninteresting stuff\r\n // If we've made it this far then the event is valid.\r\n return true;\r\n }\r\n \r\n @Override\r\n public void handleEvent(RAMEvent e) {\r\n if (isRelevant(e)) {\r\n doEvent(e);\r\n }\r\n }\r\n\r\n abstract protected void doConfig();\r\n\r\n abstract protected void doEvent(RAMEvent e);\r\n}\r",
"public class State extends HashMap<ObjectGraphNode, StateValue> implements Serializable {\n\n boolean deltaState;\n State previousState;\n State nextState;\n // Tail is only correct on the head node, everything else will likely be null\n State tail;\n Image screenshot;\n\n /**\n * Removing the next state allows a LRU buffer of states -- but states can't\n * simple be discarded, they have to be more carefully managed because most\n * states only track deltas. Things like memory have to be merged correctly.\n *\n * This state will merge with the next state and then remove it from the\n * linked list.\n *\n * @return\n */\n public State deleteNext() {\n if (nextState == null) {\n return null;\n }\n if (nextState.deltaState) {\n putAll(nextState);\n\n nextState = nextState.nextState;\n \n if (nextState == null) {\n tail = this;\n }\n return this;\n } else {\n nextState.tail = tail;\n nextState.previousState = previousState;\n return nextState;\n }\n }\n\n public void addState(State newState) {\n newState.previousState = this;\n nextState = newState;\n }\n\n public void apply() {\n Set<ObjectGraphNode> applied = new LinkedHashSet<>();\n State current = this;\n while (current != null) {\n for (StateValue val : current.values()) {\n if (!applied.contains(val.node)) {\n System.out.print(val.node.parent.parent != null ? val.node.parent.parent.name + \".\" : \"\");\n System.out.print(val.node.parent != null ? val.node.parent.name + \".\" : \"\");\n System.out.print(val.node.name);\n System.out.print(\"==\");\n System.out.println(val.value == null ? \"NULL\" : val.value.getClass().toString()); \n val.node.setCurrentValue(val.value);\n applied.add(val.node);\n }\n }\n if (!current.deltaState) {\n current = null;\n } else {\n current = current.previousState;\n }\n }\n }\n}",
"public class MetacheatUI {\n\n boolean isRetina;\n double drawScale;\n\n @FXML\n private Button pauseButton;\n\n @FXML\n private TextField searchStartAddressField;\n\n @FXML\n private TextField searchEndAddressField;\n\n @FXML\n private ScrollPane memoryViewPane;\n\n @FXML\n private StackPane memoryViewContents;\n \n @FXML\n private TabPane searchTypesTabPane;\n\n @FXML\n private TextField searchValueField;\n\n @FXML\n private RadioButton searchTypeByte;\n\n @FXML\n private ToggleGroup searchSize;\n\n @FXML\n private RadioButton searchTypeWord;\n\n @FXML\n private CheckBox searchTypeSigned;\n\n @FXML\n private RadioButton searchChangeNoneOption;\n\n @FXML\n private ToggleGroup changeSearchType;\n\n @FXML\n private RadioButton searchChangeAnyOption;\n\n @FXML\n private RadioButton searchChangeLessOption;\n\n @FXML\n private RadioButton searchChangeGreaterOption;\n\n @FXML\n private RadioButton searchChangeByOption;\n\n @FXML\n private TextField searchChangeByField;\n\n @FXML\n private Label searchStatusLabel;\n\n @FXML\n private ListView<MetaCheat.SearchResult> searchResultsListView;\n\n @FXML\n private CheckBox showValuesCheckbox;\n\n @FXML\n private TilePane watchesPane;\n\n @FXML\n private ListView<State> snapshotsListView;\n\n @FXML\n private TableView<DynamicCheat> cheatsTableView;\n\n @FXML\n private TextField codeInspectorAddress;\n\n @FXML\n private ListView<String> codeInspectorWriteList;\n\n @FXML\n private ListView<String> codeInspectorReadList;\n\n @FXML\n void createSnapshot(ActionEvent event) {\n\n }\n\n @FXML\n void deleteSnapshot(ActionEvent event) {\n\n }\n\n @FXML\n void diffSnapshots(ActionEvent event) {\n\n }\n\n @FXML\n void addCheat(ActionEvent event) {\n cheatEngine.addCheat(new DynamicCheat(0, \"?\"));\n }\n\n @FXML\n void deleteCheat(ActionEvent event) {\n cheatsTableView.getSelectionModel().getSelectedItems().forEach(cheatEngine::removeCheat);\n }\n\n @FXML\n void loadCheats(ActionEvent event) {\n boolean resume = Emulator.computer.pause();\n FileChooser chooser = new FileChooser();\n chooser.setTitle(\"Load cheats\");\n chooser.setInitialFileName(\"cheat.txt\");\n File saveFile = chooser.showOpenDialog(JaceApplication.getApplication().primaryStage);\n if (saveFile != null) {\n cheatEngine.loadCheats(saveFile);\n }\n if (resume) {\n Emulator.computer.resume();\n }\n }\n\n @FXML\n void saveCheats(ActionEvent event) {\n boolean resume = Emulator.computer.pause();\n FileChooser chooser = new FileChooser();\n chooser.setTitle(\"Save current cheats\");\n chooser.setInitialFileName(\"cheat.txt\");\n File saveFile = chooser.showSaveDialog(JaceApplication.getApplication().primaryStage);\n if (saveFile != null) {\n cheatEngine.saveCheats(saveFile);\n }\n if (resume) {\n Emulator.computer.resume();\n }\n }\n\n @FXML\n void newSearch(ActionEvent event) {\n Platform.runLater(() -> {\n cheatEngine.newSearch();\n updateSearchStats();\n });\n }\n\n @FXML\n void pauseClicked(ActionEvent event) {\n Application.invokeLater(() -> {\n if (Emulator.computer.isRunning()) {\n Emulator.computer.pause();\n } else {\n Emulator.computer.resume();\n }\n });\n }\n\n @FXML\n void search(ActionEvent event) {\n Platform.runLater(() -> {\n cheatEngine.performSearch();\n updateSearchStats();\n });\n }\n\n @FXML\n void zoomIn(ActionEvent event) {\n changeZoom(0.1);\n }\n\n @FXML\n void zoomOut(ActionEvent event) {\n changeZoom(-0.1);\n }\n\n @FXML\n void initialize() {\n assert pauseButton != null : \"fx:id=\\\"pauseButton\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchStartAddressField != null : \"fx:id=\\\"searchStartAddressField\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchEndAddressField != null : \"fx:id=\\\"searchEndAddressField\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert memoryViewPane != null : \"fx:id=\\\"memoryViewPane\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert memoryViewContents != null : \"fx:id=\\\"memoryViewContents\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchTypesTabPane != null : \"fx:id=\\\"searchTypesTabPane\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchValueField != null : \"fx:id=\\\"searchValueField\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchTypeByte != null : \"fx:id=\\\"searchTypeByte\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchSize != null : \"fx:id=\\\"searchSize\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchTypeWord != null : \"fx:id=\\\"searchTypeWord\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchTypeSigned != null : \"fx:id=\\\"searchTypeSigned\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchChangeNoneOption != null : \"fx:id=\\\"searchChangeNoneOption\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert changeSearchType != null : \"fx:id=\\\"changeSearchType\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchChangeAnyOption != null : \"fx:id=\\\"searchChangeAnyOption\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchChangeLessOption != null : \"fx:id=\\\"searchChangeLessOption\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchChangeGreaterOption != null : \"fx:id=\\\"searchChangeGreaterOption\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchChangeByOption != null : \"fx:id=\\\"searchChangeByOption\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchChangeByField != null : \"fx:id=\\\"searchChangeByField\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchStatusLabel != null : \"fx:id=\\\"searchStatusLabel\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert searchResultsListView != null : \"fx:id=\\\"searchResultsListView\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert watchesPane != null : \"fx:id=\\\"watchesPane\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert snapshotsListView != null : \"fx:id=\\\"snapshotsListView\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert codeInspectorAddress != null : \"fx:id=\\\"codeInspectorAddress\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert codeInspectorWriteList != null : \"fx:id=\\\"codeInspectorWriteList\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert codeInspectorReadList != null : \"fx:id=\\\"codeInspectorReadList\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n assert cheatsTableView != null : \"fx:id=\\\"cheatsTableView\\\" was not injected: check your FXML file 'Metacheat.fxml'.\";\n\n isRetina = Screen.getPrimary().getDpi() >= 110;\n\n Emulator.computer.getRunningProperty().addListener((val, oldVal, newVal) -> {\n Platform.runLater(() -> pauseButton.setText(newVal ? \"Pause\" : \"Resume\"));\n });\n\n searchTypesTabPane.getTabs().get(0).setUserData(SearchType.VALUE);\n searchTypesTabPane.getTabs().get(1).setUserData(SearchType.CHANGE);\n searchTypesTabPane.getTabs().get(2).setUserData(SearchType.TEXT);\n searchTypesTabPane.getSelectionModel().selectedItemProperty().addListener((prop, oldVal, newVal) -> {\n if (cheatEngine != null) {\n cheatEngine.setSearchType((SearchType) newVal.getUserData());\n }\n });\n\n searchChangeAnyOption.setUserData(SearchChangeType.ANY_CHANGE);\n searchChangeByOption.setUserData(SearchChangeType.AMOUNT);\n searchChangeGreaterOption.setUserData(SearchChangeType.GREATER);\n searchChangeLessOption.setUserData(SearchChangeType.LESS);\n searchChangeNoneOption.setUserData(SearchChangeType.NO_CHANGE);\n changeSearchType.selectedToggleProperty().addListener((ObservableValue<? extends Toggle> val, Toggle oldVal, Toggle newVal) -> {\n if (cheatEngine != null) {\n cheatEngine.setSearchChangeType((SearchChangeType) newVal.getUserData());\n }\n });\n\n searchTypeByte.setUserData(true);\n searchTypeWord.setUserData(false);\n searchSize.selectedToggleProperty().addListener((ObservableValue<? extends Toggle> val, Toggle oldVal, Toggle newVal) -> {\n if (cheatEngine != null) {\n cheatEngine.setByteSized((boolean) newVal.getUserData());\n }\n });\n\n searchResultsListView.setEditable(true);\n searchResultsListView.setOnEditStart((editEvent) -> {\n editEvent.consume();\n SearchResult result = cheatEngine.getSearchResults().get(editEvent.getIndex());\n addWatch(result.getAddress());\n });\n\n showValuesCheckbox.selectedProperty().addListener((prop, oldVal, newVal) -> {\n if (newVal) {\n redrawMemoryView();\n }\n });\n memoryViewPane.boundsInParentProperty().addListener((prop, oldVal, newVal) -> redrawMemoryView());\n drawScale = isRetina ? 0.5 : 1.0;\n\n watchesPane.setHgap(5);\n watchesPane.setVgap(5);\n\n searchStartAddressField.textProperty().addListener(addressRangeListener);\n searchEndAddressField.textProperty().addListener(addressRangeListener);\n\n TableColumn<DynamicCheat, Boolean> activeColumn = (TableColumn<DynamicCheat, Boolean>) cheatsTableView.getColumns().get(0);\n activeColumn.setCellValueFactory(new PropertyValueFactory<>(\"active\"));\n activeColumn.setCellFactory((TableColumn<DynamicCheat, Boolean> param) -> new CheckBoxTableCell<>());\n\n TableColumn<DynamicCheat, String> nameColumn = (TableColumn<DynamicCheat, String>) cheatsTableView.getColumns().get(1);\n nameColumn.setCellValueFactory(new PropertyValueFactory<>(\"name\"));\n nameColumn.setCellFactory((TableColumn<DynamicCheat, String> param) -> new TextFieldTableCell<>(new DefaultStringConverter()));\n\n TableColumn<DynamicCheat, Integer> addrColumn = (TableColumn<DynamicCheat, Integer>) cheatsTableView.getColumns().get(2);\n addrColumn.setCellValueFactory(new PropertyValueFactory<>(\"address\"));\n addrColumn.setCellFactory((TableColumn<DynamicCheat, Integer> param) -> {\n return new TextFieldTableCell<>(new IntegerStringConverter() {\n @Override\n public String toString(Integer value) {\n return \"$\" + Integer.toHexString(value);\n }\n\n @Override\n public Integer fromString(String value) {\n return cheatEngine.parseInt(value);\n }\n });\n });\n\n TableColumn<DynamicCheat, String> exprColumn = (TableColumn<DynamicCheat, String>) cheatsTableView.getColumns().get(3);\n exprColumn.setCellValueFactory(new PropertyValueFactory<>(\"expression\"));\n exprColumn.setCellFactory((TableColumn<DynamicCheat, String> param) -> new TextFieldTableCell<>(new DefaultStringConverter()));\n\n codeInspectorAddress.textProperty().addListener((prop, oldValue, newValue) -> {\n try {\n int address = cheatEngine.parseInt(newValue);\n MemoryCell cell = cheatEngine.getMemoryCell(address);\n currentlyInspecting = address;\n cheatEngine.onInspectorChanged();\n codeInspectorReadList.setItems(cell.readInstructionsDisassembly);\n codeInspectorWriteList.setItems(cell.writeInstructionsDisassembly);\n } catch (NumberFormatException ex) {\n }\n });\n }\n MetaCheat cheatEngine = null;\n\n public void registerMetacheatEngine(MetaCheat engine) {\n cheatEngine = engine;\n\n cheatsTableView.setItems(cheatEngine.getCheats());\n searchResultsListView.setItems(cheatEngine.getSearchResults());\n snapshotsListView.setItems(cheatEngine.getSnapshots());\n searchTypeSigned.selectedProperty().bindBidirectional(cheatEngine.signedProperty());\n searchStartAddressField.textProperty().bindBidirectional(cheatEngine.startAddressProperty());\n searchEndAddressField.textProperty().bindBidirectional(cheatEngine.endAddressProperty());\n searchValueField.textProperty().bindBidirectional(cheatEngine.searchValueProperty());\n searchChangeByField.textProperty().bindBidirectional(cheatEngine.searchChangeByProperty());\n\n Application.invokeLater(this::redrawMemoryView);\n }\n\n ChangeListener<String> addressRangeListener = (prop, oldVal, newVal) -> Application.invokeLater(this::redrawMemoryView);\n\n public static final int MEMORY_BOX_SIZE = 5;\n public static final int MEMORY_BOX_GAP = 1;\n public static final int MEMORY_BOX_TOTAL_SIZE = (MEMORY_BOX_SIZE + MEMORY_BOX_GAP);\n public static final int UPDATE_NODE_LIMIT = 10000;\n public int memoryViewColumns;\n public int memoryViewRows;\n\n public static Set<MemoryCell> redrawNodes = new ConcurrentSkipListSet<>();\n ScheduledExecutorService animationTimer = null;\n ScheduledFuture animationFuture = null;\n Tooltip memoryWatchTooltip = new Tooltip();\n\n private void memoryViewClicked(MouseEvent e, MemoryCell cell) {\n if (cheatEngine != null) {\n Watch currentWatch = (Watch) memoryWatchTooltip.getGraphic();\n if (currentWatch != null) {\n currentWatch.disconnect();\n }\n \n int addr = cell.address;\n Watch watch = new Watch(addr, this);\n\n Label addWatch = new Label(\"Watch >>\");\n addWatch.setOnMouseClicked((mouseEvent) -> {\n Watch newWatch = addWatch(addr);\n if (watch.holdingProperty().get()) {\n newWatch.holdingProperty().set(true);\n }\n memoryWatchTooltip.hide();\n });\n watch.getChildren().add(addWatch);\n\n Label addCheat = new Label(\"Cheat >>\");\n addCheat.setOnMouseClicked((mouseEvent) -> {\n Platform.runLater(() -> addCheat(addr, watch.getValue()));\n });\n watch.getChildren().add(addCheat);\n\n memoryWatchTooltip.setStyle(\"-fx-background-color:NAVY\");\n memoryWatchTooltip.onHidingProperty().addListener((prop, oldVal, newVal) -> {\n watch.disconnect();\n memoryWatchTooltip.setGraphic(null);\n });\n memoryWatchTooltip.setGraphic(watch);\n memoryWatchTooltip.show(memoryViewPane.getContent(), e.getScreenX() + 5, e.getScreenY() - 15);\n }\n }\n\n private void processMemoryViewUpdates() {\n if (!Emulator.computer.getRunningProperty().get()) {\n return;\n }\n Application.invokeLater(() -> {\n Iterator<MemoryCell> i = redrawNodes.iterator();\n for (int limit = 0; i.hasNext() && limit < UPDATE_NODE_LIMIT; limit++) {\n MemoryCell cell = i.next();\n i.remove();\n if (showValuesCheckbox.isSelected()) {\n int val = cell.value.get() & 0x0ff;\n cell.getShape().setFill(Color.rgb(val, val, val));\n } else {\n cell.getShape().setFill(Color.rgb(\n cell.writeCount.get(),\n cell.readCount.get(),\n cell.execCount.get()));\n }\n }\n });\n }\n\n public static int FRAME_RATE = 1000 / 60;\n\n public void redrawMemoryView() {\n if (cheatEngine == null) {\n return;\n }\n boolean resume = Emulator.computer.pause();\n\n if (animationTimer == null) {\n animationTimer = new ScheduledThreadPoolExecutor(1);\n }\n\n if (animationFuture != null) {\n animationFuture.cancel(false);\n }\n\n animationFuture = animationTimer.scheduleAtFixedRate(this::processMemoryViewUpdates, FRAME_RATE, FRAME_RATE, TimeUnit.MILLISECONDS);\n\n cheatEngine.initMemoryView();\n int pixelsPerBlock = 16 * MEMORY_BOX_TOTAL_SIZE;\n memoryViewColumns = (int) (memoryViewPane.getWidth() / pixelsPerBlock) * 16;\n memoryViewRows = ((cheatEngine.getEndAddress() - cheatEngine.getStartAddress()) / memoryViewColumns) + 1;\n \n memoryViewContents.prefWidthProperty().bind(memoryViewPane.widthProperty().multiply(drawScale).subtract(8));\n \n Group memoryView = new Group();\n memoryViewContents.setBackground(new Background(new BackgroundFill(Color.rgb(40, 40, 40), null, null)));\n for (int addr = cheatEngine.getStartAddress(); addr <= cheatEngine.getEndAddress(); addr++) {\n int col = (addr - cheatEngine.getStartAddress()) % memoryViewColumns;\n int row = (addr - cheatEngine.getStartAddress()) / memoryViewColumns;\n MemoryCell cell = cheatEngine.getMemoryCell(addr);\n Rectangle rect = new Rectangle(col * MEMORY_BOX_TOTAL_SIZE * drawScale, row * MEMORY_BOX_TOTAL_SIZE * drawScale, MEMORY_BOX_SIZE * drawScale, MEMORY_BOX_SIZE * drawScale);\n rect.setOnMouseClicked(e -> memoryViewClicked(e, cell));\n rect.setFill(Color.GRAY);\n cell.setShape(rect);\n memoryView.getChildren().add(rect);\n redrawNodes.add(cell);\n }\n memoryViewContents.getChildren().clear();\n memoryViewContents.getChildren().add(memoryView);\n MemoryCell.setListener((javafx.beans.value.ObservableValue<? extends jace.cheat.MemoryCell> prop, jace.cheat.MemoryCell oldCell, jace.cheat.MemoryCell newCell) -> {\n redrawNodes.add(newCell);\n });\n\n setZoom(1 / drawScale);\n\n if (resume) {\n Emulator.computer.resume();\n }\n }\n\n private void changeZoom(double amount) {\n if (memoryViewContents != null) {\n double zoom = memoryViewContents.getScaleX();\n zoom += amount;\n setZoom(zoom);\n }\n }\n\n private void setZoom(double zoom) {\n if (memoryViewContents != null) {\n memoryViewContents.setScaleX(zoom);\n memoryViewContents.setScaleY(zoom);\n// StackPane scrollArea = (StackPane) memoryViewCanvas.getParent();\n// scrollArea.setPrefSize(memoryViewCanvas.getWidth() * zoom, memoryViewCanvas.getHeight() * zoom);\n }\n }\n\n public void detach() {\n cheatsTableView.setItems(FXCollections.emptyObservableList());\n searchResultsListView.setItems(FXCollections.emptyObservableList());\n searchTypeSigned.selectedProperty().unbind();\n searchStartAddressField.textProperty().unbind();\n searchStartAddressField.textProperty().unbind();\n searchEndAddressField.textProperty().unbind();\n searchValueField.textProperty().unbind();\n searchChangeByField.textProperty().unbind();\n memoryWatchTooltip.hide();\n animationTimer.shutdown();\n animationTimer = null;\n cheatEngine = null;\n }\n\n private void updateSearchStats() {\n int size = cheatEngine.getSearchResults().size();\n searchStatusLabel.setText(size + (size == 1 ? \" result\" : \" results\") + \" found.\");\n }\n\n private Watch addWatch(int addr) {\n Watch watch = new Watch(addr, this);\n watch.setPadding(new Insets(5));\n watch.setOpaqueInsets(new Insets(10));\n\n Label addCheat = new Label(\"Cheat >>\");\n addCheat.setOnMouseClicked((mouseEvent) -> {\n addCheat(addr, watch.getValue());\n });\n addCheat.setTextFill(Color.WHITE);\n watch.getChildren().add(addCheat);\n\n Label close = new Label(\"Close X\");\n close.setOnMouseClicked((mouseEvent) -> {\n watch.disconnect();\n watchesPane.getChildren().remove(watch);\n });\n close.setTextFill(Color.WHITE);\n watch.getChildren().add(close);\n\n watchesPane.getChildren().add(watch);\n return watch;\n }\n\n private void addCheat(int addr, int val) {\n cheatEngine.addCheat(new DynamicCheat(addr, String.valueOf(val)));\n }\n\n int currentlyInspecting = 0;\n\n public void inspectAddress(int address) {\n codeInspectorAddress.setText(\"$\" + Integer.toHexString(address));\n }\n\n public boolean isInspecting(int address) {\n return currentlyInspecting == address;\n }\n}"
] | import jace.Emulator;
import jace.JaceApplication;
import jace.core.CPU;
import jace.core.Computer;
import jace.core.RAM;
import jace.core.RAMEvent;
import jace.core.RAMListener;
import jace.state.State;
import jace.ui.MetacheatUI;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
| }
public int getEndAddress() {
return endAddress;
}
public void setByteSized(boolean b) {
byteSized = b;
}
public void setSearchType(SearchType searchType) {
this.searchType = searchType;
}
public void setSearchChangeType(SearchChangeType searchChangeType) {
this.searchChangeType = searchChangeType;
}
public Property<Boolean> signedProperty() {
return signedProperty;
}
public Property<String> searchValueProperty() {
return searchValueProperty;
}
public Property<String> searchChangeByProperty() {
return changeByProperty;
}
public ObservableList<DynamicCheat> getCheats() {
return cheatList;
}
public ObservableList<SearchResult> getSearchResults() {
return resultList;
}
public ObservableList<State> getSnapshots() {
return snapshotList;
}
public Property<String> startAddressProperty() {
return startAddressProperty;
}
public Property<String> endAddressProperty() {
return endAddressProperty;
}
public void newSearch() {
RAM memory = Emulator.computer.getMemory();
resultList.clear();
int compare = parseInt(searchValueProperty.get());
for (int i = 0; i < 0x10000; i++) {
boolean signed = signedProperty.get();
int val
= byteSized
? signed ? memory.readRaw(i) : memory.readRaw(i) & 0x0ff
: signed ? memory.readWordRaw(i) : memory.readWordRaw(i) & 0x0ffff;
if (!searchType.equals(SearchType.VALUE) || val == compare) {
SearchResult result = new SearchResult(i, val);
resultList.add(result);
}
}
}
public void performSearch() {
RAM memory = Emulator.computer.getMemory();
boolean signed = signedProperty.get();
resultList.removeIf((SearchResult result) -> {
int val = byteSized
? signed ? memory.readRaw(result.address) : memory.readRaw(result.address) & 0x0ff
: signed ? memory.readWordRaw(result.address) : memory.readWordRaw(result.address) & 0x0ffff;
int last = result.lastObservedValue;
result.lastObservedValue = val;
switch (searchType) {
case VALUE:
int compare = parseInt(searchValueProperty.get());
return compare != val;
case CHANGE:
switch (searchChangeType) {
case AMOUNT:
int amount = parseInt(searchChangeByProperty().getValue());
return (val - last) != amount;
case GREATER:
return val <= last;
case ANY_CHANGE:
return val == last;
case LESS:
return val >= last;
case NO_CHANGE:
return val != last;
}
break;
case TEXT:
break;
}
return false;
});
}
RAMListener memoryViewListener = null;
private final Map<Integer, MemoryCell> memoryCells = new ConcurrentHashMap<>();
public MemoryCell getMemoryCell(int address) {
return memoryCells.get(address);
}
public void initMemoryView() {
RAM memory = Emulator.computer.getMemory();
for (int addr = getStartAddress(); addr <= getEndAddress(); addr++) {
if (getMemoryCell(addr) == null) {
MemoryCell cell = new MemoryCell();
cell.address = addr;
cell.value.set(memory.readRaw(addr));
memoryCells.put(addr, cell);
}
}
if (memoryViewListener == null) {
| memoryViewListener = memory.observe(RAMEvent.TYPE.ANY, startAddress, endAddress, this::processMemoryEvent);
| 5 |
wmaop/wm-aop | src/test/java/org/wmaop/aop/stub/StubManagerTest.java | [
"public class Advice {\n\n\tprivate final PointCut pointCut;\n\tprivate final Interceptor interceptor;\n\tprivate final String id;\n\tprivate AdviceState adviceState = AdviceState.NEW;\n\tprivate final Remit remit;\n\n\tpublic Advice(String id, Remit remit, PointCut pointCut, Interceptor interceptor) {\n\t\tthis.pointCut = pointCut;\n\t\tthis.interceptor = interceptor;\n\t\tthis.id = id;\n\t\tthis.remit = remit;\n\t}\n\n\tpublic Remit getRemit() {\n\t\treturn remit;\n\t}\n\n\tpublic PointCut getPointCut() {\n\t\treturn pointCut;\n\t}\n\n\tpublic boolean isApplicable(FlowPosition pipelinePosition, IData idata){\n\t\treturn pointCut.isApplicable(pipelinePosition, idata) && remit.isApplicable();\n\t}\n\t\n\tpublic Interceptor getInterceptor() {\n\t\treturn interceptor;\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic AdviceState getAdviceState() {\n\t\treturn adviceState;\n\t}\n\n\tpublic void setAdviceState(AdviceState adviceState) {\n\t\tthis.adviceState = adviceState;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn id + ' ' + adviceState + ' ' + pointCut + ' ' + interceptor + ' ' + pointCut.getInterceptPoint() + ' ' + remit;\n\t}\n\t\n\tpublic Map<String, Object> toMap() {\n\t\tMap<String, Object> am = new HashMap<>();\n\t\tam.put(\"state\", adviceState.toString());\n\t\tam.put(\"adviceId\", id);\n\t\tam.put(\"pointcut\", pointCut.toMap());\n\t\tam.put(\"interceptor\", interceptor.toMap());\n\t\tam.put(\"remit\", remit.toString());\n\t\treturn am;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tAdvice other = (Advice) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (!id.equals(other.id))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n}",
"public final class GlobalRemit implements Remit {\r\n\r\n\t@Override\r\n\tpublic final boolean isApplicable() {\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isApplicable(Scope scope) {\r\n\t\treturn scope == ALL || scope == GLOBAL;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn \"GlobalScope\";\r\n\t}\r\n}\r",
"public interface Interceptor {\n\n\tInterceptResult intercept(FlowPosition flowPosition, IData idata);\n\n\tint getInvokeCount();\n\n\tString getName();\n\n\tMap<String, Object> toMap();\n\n}",
"public interface FlowPositionMatcher extends Matcher<FlowPosition> {\r\n\r\n\tString getServiceName();\r\n\r\n}\r",
"public interface PointCut {\n\n\tboolean isApplicable(FlowPosition pipelinePosition, IData idata);\n\n\tInterceptPoint getInterceptPoint();\n\n\tFlowPositionMatcher getFlowPositionMatcher();\n\n\tObject toMap();\n}"
] | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.wmaop.aop.advice.Advice;
import org.wmaop.aop.advice.remit.GlobalRemit;
import org.wmaop.aop.interceptor.Interceptor;
import org.wmaop.aop.matcher.FlowPositionMatcher;
import org.wmaop.aop.pointcut.PointCut;
import com.wm.app.b2b.server.BaseService;
import com.wm.app.b2b.server.Package;
import com.wm.app.b2b.server.PackageManager;
import com.wm.app.b2b.server.Resources;
import com.wm.app.b2b.server.Server;
import com.wm.app.b2b.server.ServerClassLoader;
import com.wm.app.b2b.server.ns.Namespace;
import com.wm.lang.ns.NSException;
import com.wm.lang.ns.NSName;
import com.wm.lang.ns.NSNode; | package org.wmaop.aop.stub;
@RunWith(PowerMockRunner.class)
@PrepareForTest({PackageManager.class,Namespace.class,ServerClassLoader.class,Server.class})
public class StubManagerTest {
private StubManager stubManager;
private static final String SERVICE_NAME = "foo:bar";
@Rule
public TemporaryFolder tempFolder= new TemporaryFolder();
@Before
public void setUp() {
stubManager = new StubManager();
PowerMockito.mockStatic(PackageManager.class);
PowerMockito.mockStatic(ServerClassLoader.class);
PowerMockito.mockStatic(Server.class);
}
@Test
public void shouldRegisterStubService() {
assertFalse(stubManager.isRegisteredService(SERVICE_NAME));
PowerMockito.when(Server.getResources()).thenReturn(new Resources("",false));
stubManager.registerStubService(SERVICE_NAME);
assertTrue(stubManager.hasStub(SERVICE_NAME));
}
@Test
public void shouldUnregisterStubService() throws NSException {
Namespace ns = mockNamespace();
Package pkg = mockPackage();
stubManager.unregisterStubService(SERVICE_NAME);
verify(ns, times(1)).deleteNode((NSName) any(), eq(true), eq(pkg));
}
@Test
public void shouldUnregisterStubFromAdvice() { | Advice advice = createAdviceMock(); | 0 |
tomayac/rest-describe-and-compile | src/com/google/code/apis/rest/client/Tree/ResponseItem.java | [
"public class GuiFactory implements WindowResizeListener {\r\n private static DockPanel blockScreen;\r\n public static Strings strings;\r\n public static Notifications notifications; \r\n private DockPanel dockPanel;\r\n public static final String restCompile = \"restCompile\";\r\n public static final String restDescribe = \"restDescribe\";\r\n \r\n\t/**\r\n\t * Creates the GUI consisting of various panels\r\n\t */\r\n\tpublic GuiFactory() {\r\n // I18N strings\r\n strings = (Strings) GWT.create(Strings.class);\r\n notifications = (Notifications) GWT.create(Notifications.class);\r\n \r\n // disallow scrolling\r\n Window.enableScrolling(false);\r\n // resize the panels on main window resize\r\n Window.addWindowResizeListener(this); \r\n \r\n // main application\r\n dockPanel = new DockPanel(); \r\n dockPanel.setStyleName(\"restDescribe-mainApplicationPanel\");\r\n dockPanel.setWidth(\"99.7%\");\r\n dockPanel.setHeight(\"99.7%\"); \r\n dockPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_TOP); \r\n dockPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); \r\n\r\n // main menu\r\n MainMenuPanel mainMenuPanel = new MainMenuPanel(); \r\n dockPanel.add(mainMenuPanel, DockPanel.NORTH);\r\n dockPanel.setCellHeight(mainMenuPanel, \"10%\");\r\n\r\n // rest compile panel\r\n RestCompilePanel restCompilePanel = new RestCompilePanel(); \r\n dockPanel.add(restCompilePanel, DockPanel.NORTH);\r\n \r\n // request sample panel \r\n RequestUriPanel requestUriPanel = new RequestUriPanel();\r\n dockPanel.add(requestUriPanel, DockPanel.NORTH);\r\n dockPanel.setCellHeight(requestUriPanel, \"10%\"); \r\n \r\n // navigation panel\r\n ParameterPanel parameterPanel = new ParameterPanel(); \r\n dockPanel.add(parameterPanel, DockPanel.WEST);\r\n dockPanel.setCellHeight(parameterPanel, \"80%\");\r\n dockPanel.setCellWidth(parameterPanel, \"45%\");\r\n dockPanel.setCellVerticalAlignment(parameterPanel, HasVerticalAlignment.ALIGN_TOP);\r\n \r\n // wadl panel\r\n WadlPanel wadlPanel = new WadlPanel();\r\n dockPanel.add(wadlPanel, DockPanel.EAST); \r\n dockPanel.setCellHeight(wadlPanel, \"80%\");\r\n dockPanel.setCellWidth(wadlPanel, \"55%\");\r\n dockPanel.setCellVerticalAlignment(wadlPanel, HasVerticalAlignment.ALIGN_TOP);\r\n \r\n toggleMode(restDescribe);\r\n \r\n\t\tRootPanel.get().add(dockPanel);\r\n \r\n // semi-transparent screen blocker for dialogs\r\n blockScreen = new DockPanel(); \r\n HTML semiTransparentDiv = getBlockedScreenDiv(Window.getClientWidth(), Window.getClientHeight());\r\n blockScreen.add(semiTransparentDiv, DockPanel.SOUTH);\r\n blockScreen.setVisible(false); \r\n RootPanel.get().add(blockScreen);\r\n\r\n onWindowResized(Window.getClientWidth(), Window.getClientHeight());\r\n \r\n // reset the application\r\n GuiFactory.resetApplication(GuiFactory.strings.newRequestUri());\r\n\t}\r\n \r\n /* (non-Javadoc)\r\n * @see com.google.gwt.user.client.WindowResizeListener#onWindowResized(int, int)\r\n */\r\n public void onWindowResized(int width, int height) { \r\n RequestUriPanel.requestSampleArea.setHeight(Math.floor(0.1 * height) + \"px\"); \r\n RequestUriPanel.containerPanel.setWidth(Math.floor(0.97 * width) + \"px\");\r\n \r\n int panelHeight = height - RequestUriPanel.requestSamplePanel.getOffsetHeight() - MainMenuPanel.menuPanel.getOffsetHeight() - WadlPanel.wadlHeader.getOffsetHeight() - 80; \r\n ParameterPanel.parameterPanel.setHeight(\"100%\");\r\n ParameterPanel.parameterPanel.setWidth(\"100%\");\r\n ParameterPanel.requestArea.setHeight(panelHeight + \"px\");\r\n ParameterPanel.requestArea.setWidth(Math.floor(0.28 * width) + \"px\");\r\n \r\n WadlPanel.wadlPanel.setHeight(\"100%\");\r\n WadlPanel.wadlPanel.setWidth(\"95%\"); \r\n \r\n WadlPanel.wadlArea.setHeight(panelHeight + \"px\");\r\n WadlPanel.wadlArea.setWidth(Math.floor(0.58 * width) + \"px\"); \r\n \r\n GuiFactory.blockScreen.clear();\r\n GuiFactory.blockScreen.add(getBlockedScreenDiv(width, height), DockPanel.NORTH); \r\n }\r\n \r\n /**\r\n * Blocks the screen by means of a semi transparent blocking layer when dialogs are shown \r\n * @param isVisible Determines whether or not to display the blocking layer\r\n */\r\n public static void blockScreen(boolean isVisible) {\r\n blockScreen.setVisible(isVisible);\r\n }\r\n \r\n /**\r\n * Dynamically creates the semi transparent blocking layer html\r\n * @param width Current screen width\r\n * @param height Current screen height\r\n * @return The blocking layer html\r\n */\r\n private static HTML getBlockedScreenDiv(int width, int height) {\r\n return new HTML(\"<div style='z-index:0; width:\" + width + \"px; height:\" + height + \"px; position:absolute; left:0px; top:0px; background-color:black; opacity:.40; filter: alpha(opacity=40);'> </div>\");\r\n }\r\n \r\n /**\r\n * Resets the application and loads an initial request string\r\n * @param initialRequestString The initial request string\r\n */\r\n public static void resetApplication(String initialRequestString) {\r\n resetApplication();\r\n ReferenceManager.allRequestStrings.add(initialRequestString); \r\n RequestUriTree.listRequestSamples(ReferenceManager.allRequestStrings); \r\n }\r\n \r\n public static void toggleButtonsEnabled(boolean isEnabled) {\r\n WadlPanel.wadlSaveButton.setEnabled(isEnabled);\r\n WadlPanel.wadlPreviewButton.setEnabled(isEnabled);\r\n WadlPanel.resetButton.setEnabled(isEnabled);\r\n WadlPanel.fullscreenButton.setEnabled(isEnabled);\r\n WadlPanel.generateCodeButton.setEnabled(isEnabled);\r\n }\r\n \r\n public static void toggleMode(String mode) {\r\n boolean toggleBit = false;\r\n if (mode.equals(restCompile)) {\r\n toggleBit = true;\r\n if (FullscreenDialog.leaveFullscreenButton != null) {\r\n FullscreenDialog.leaveFullscreenButton.click();\r\n }\r\n RestCompilePanel.codeTextArea.setText(\"\");\r\n RestCompilePanel.buttonPanel.setVisible(false);\r\n RestCompilePanel.compilePanel.setVisible(false); \r\n MainMenuPanel.logo.setHTML(MainMenuPanel.restCompileLogo);\r\n }\r\n else if (mode.equals(restDescribe)) {\r\n toggleBit = false;\r\n MainMenuPanel.logo.setHTML(MainMenuPanel.restDescribeLogo);\r\n } \r\n \r\n WadlPanel.wadlPanel.setVisible(!toggleBit);\r\n RequestUriPanel.requestSamplePanel.setVisible(!toggleBit);\r\n ParameterPanel.parameterPanel.setVisible(!toggleBit);\r\n RestCompilePanel.restCompilePanel.setVisible(toggleBit);\r\n \r\n int width = Window.getClientWidth();\r\n int height = Window.getClientHeight();\r\n RequestUriPanel.requestSampleArea.setHeight(Math.floor(0.1 * height) + \"px\"); \r\n RequestUriPanel.containerPanel.setWidth(Math.floor(0.97 * width) + \"px\");\r\n \r\n int panelHeight = height - RequestUriPanel.requestSamplePanel.getOffsetHeight() - MainMenuPanel.menuPanel.getOffsetHeight() - WadlPanel.wadlHeader.getOffsetHeight() - 80; \r\n ParameterPanel.parameterPanel.setHeight(\"100%\");\r\n ParameterPanel.parameterPanel.setWidth(\"100%\");\r\n ParameterPanel.requestArea.setHeight(panelHeight + \"px\");\r\n ParameterPanel.requestArea.setWidth(Math.floor(0.28 * width) + \"px\");\r\n \r\n WadlPanel.wadlPanel.setHeight(\"100%\");\r\n WadlPanel.wadlPanel.setWidth(\"95%\"); \r\n \r\n WadlPanel.wadlArea.setHeight(panelHeight + \"px\");\r\n WadlPanel.wadlArea.setWidth(Math.floor(0.58 * width) + \"px\"); \r\n }\r\n\r\n /**\r\n * Resets the application without loading an inital uri\r\n */\r\n public static void resetApplication() {\r\n RestCompilePanel.paramToUseForName = \"\"; \r\n RequestUriPanel.uriTree.removeItems(); \r\n ParameterPanel.requestContainer.clear();\r\n WadlPanel.wadlArea.clear();\r\n if (Analyzer.application != null) { \r\n Analyzer.application.reset(); \r\n }\r\n ReferenceManager.clearReferences();\r\n toggleButtonsEnabled(false); \r\n }\r\n}\r",
"public class SettingsDialog {\n public static boolean alwaysShowDetails = false;\n public static boolean alwaysShowDetailsTemp = alwaysShowDetails;\n public static boolean treeItemsAlwaysOpen = true;\n public static boolean treeItemsAlwaysOpenTemp = treeItemsAlwaysOpen;\n public static int requestTimeoutSeconds = 180;\n public static int namingDepthLevel = 1;\n public static String pathToDiscoverer = \"./resources/Discoverer.php5\";\n public static String pathToJsonConverter = \"./resources/XML2JSON.php5\";\n public static boolean useEndpointAsName = true;\n public static String separationCharacter = \"_\";\n public static boolean useSeparationCharacter = false;\n public static boolean useSeparationCharacterTemp = useSeparationCharacter;\n public static String classDefaultSuffix = \"\";\n public static int indentWidth = 2;\n public static boolean indentWithSpaces = true; \n public static String templateSuffix = \"\"; //\"_TEMPLATE\"; \n private static final String confirm_de = \"<a href=\\\"RestDescribe.html?locale=de\\\">\" + GuiFactory.strings.confirmAndRestart() + \"</a>\"; \n private static final String confirm_enUS = \"<a href=\\\"RestDescribe.html?locale=en\\\">\" + GuiFactory.strings.confirmAndRestart() + \"</a>\";\n private static final String confirm_ca = \"<a href=\\\"RestDescribe.html?locale=ca\\\">\" + GuiFactory.strings.confirmAndRestart() + \"</a>\";\n\n /**\n * Creates the settings dialog\n */\n public static void show() {\n String panelHeight = \"3em\";\n String panelWidthLeft = \"15em\";\n String panelWidthRight = \"20em\";\n String textBoxWidth = \"8em\";\n final DialogBox dialogBox = new DialogBox(); \n dialogBox.setText(GuiFactory.strings.settingsLink()); \n \n VerticalPanel settingsPanel = new VerticalPanel(); \n TabPanel tabPanel = new TabPanel(); \n \n final ListBox languageListBox = new ListBox(); \n languageListBox.addItem(GuiFactory.strings.english_US());\n languageListBox.addItem(GuiFactory.strings.german());\n languageListBox.addItem(GuiFactory.strings.catalan());\n \n VerticalPanel generalPanel = new VerticalPanel(); \n \n HorizontalPanel languagePanel = new HorizontalPanel(); \n languagePanel.setHeight(panelHeight);\n HorizontalPanel languagePanelLeft = new HorizontalPanel();\n HorizontalPanel languagePanelRight = new HorizontalPanel();\n \n languagePanelLeft.setWidth(panelWidthLeft);\n languagePanelLeft.add(new HTML(\"<b>\" + GuiFactory.strings.language() + \"</b>\")); \n languagePanelRight.setWidth(panelWidthRight);\n languagePanelRight.add(new HTML(GuiFactory.strings.displayRestDescribe() + \": \"));\n languagePanelRight.add(languageListBox); \n \n languagePanel.add(languagePanelLeft);\n languagePanel.add(languagePanelRight); \n generalPanel.add(languagePanel);\n \n final HorizontalPanel confirmLangChange = new HorizontalPanel();\n confirmLangChange.setVisible(false);\n confirmLangChange.add(new HTML(GuiFactory.strings.cautionChangesGetLost() + \" \"));\n \n final HTML confirmLink = new HTML(\"\");\n confirmLangChange.add(confirmLink);\n confirmLangChange.add(new HTML(\".\")); \n generalPanel.add(confirmLangChange); \n languageListBox.addChangeListener(new ChangeListener() {\n public void onChange(Widget sender) { \n updateAndDisplayConfirmLink(languageListBox.getItemText(languageListBox.getSelectedIndex()), confirmLink, confirmLangChange);\n }\n });\n languageListBox.addClickListener(new ClickListener() {\n public void onClick(Widget sender) {\n updateAndDisplayConfirmLink(languageListBox.getItemText(languageListBox.getSelectedIndex()), confirmLink, confirmLangChange);\n } \n });\n \n final CheckBox detailsCheckBox = new CheckBox();\n detailsCheckBox.setChecked(alwaysShowDetails);\n detailsCheckBox.addClickListener(new ClickListener() {\n public void onClick(Widget sender) {\n if (detailsCheckBox.isChecked()) {\n alwaysShowDetailsTemp = true; \n }\n else {\n alwaysShowDetailsTemp = false;\n }\n }\n });\n \n final CheckBox treesCheckBox = new CheckBox();\n treesCheckBox.setChecked(treeItemsAlwaysOpen);\n treesCheckBox.addClickListener(new ClickListener() {\n public void onClick(Widget sender) {\n if (treesCheckBox.isChecked()) {\n treeItemsAlwaysOpenTemp = true; \n }\n else {\n treeItemsAlwaysOpenTemp = false;\n }\n }\n });\n \n final HorizontalPanel miniSepTextPanel = new HorizontalPanel();\n final CheckBox useSeparationCharacterCheckBox = new CheckBox();\n useSeparationCharacterCheckBox.setChecked(useSeparationCharacter);\n useSeparationCharacterCheckBox.addClickListener(new ClickListener() {\n public void onClick(Widget sender) { \n if (useSeparationCharacterCheckBox.isChecked()) {\n useSeparationCharacterTemp = true; \n }\n else {\n useSeparationCharacterTemp = false;\n }\n miniSepTextPanel.setVisible(useSeparationCharacterTemp);\n }\n });\n \n final TextBox timeoutSecondsTextBox = new TextBox();\n timeoutSecondsTextBox.setText(Integer.toString(requestTimeoutSeconds));\n timeoutSecondsTextBox.setWidth(panelHeight);\n timeoutSecondsTextBox.addChangeListener(new ChangeListener() {\n public void onChange(Widget sender) {\n try {\n requestTimeoutSeconds = Integer.parseInt(timeoutSecondsTextBox.getText());\n timeoutSecondsTextBox.removeStyleName(\"restDescribe-error\");\n } catch (NumberFormatException e) { \n timeoutSecondsTextBox.setStyleName(\"restDescribe-error\");\n }\n } \n }); \n \n miniSepTextPanel.setVisible(useSeparationCharacter);\n final TextBox separationCharacterTextBox = new TextBox(); \n separationCharacterTextBox.setText(separationCharacter);\n separationCharacterTextBox.setWidth(panelHeight);\n separationCharacterTextBox.addChangeListener(new ChangeListener() {\n public void onChange(Widget sender) {\n separationCharacter = separationCharacterTextBox.getText();\n } \n });\n \n final TextBox namingDepthTextBox = new TextBox();\n namingDepthTextBox.setText(Integer.toString(namingDepthLevel));\n namingDepthTextBox.setWidth(panelHeight);\n namingDepthTextBox.addChangeListener(new ChangeListener() {\n public void onChange(Widget sender) {\n try {\n namingDepthLevel = Integer.parseInt(namingDepthTextBox.getText());\n namingDepthTextBox.removeStyleName(\"restDescribe-error\");\n if (SettingsDialog.namingDepthLevel == 0) {\n namingDepthTextBox.setStyleName(\"restDescribe-error\");\n }\n } catch (NumberFormatException e) { \n namingDepthTextBox.setStyleName(\"restDescribe-error\");\n }\n } \n });\n \n final RadioButton useParameterAsNameRadio = new RadioButton(\"paramOrEndpoint\", GuiFactory.strings.useParam());\n useParameterAsNameRadio.setChecked(!useEndpointAsName);\n useParameterAsNameRadio.addClickListener(new ClickListener() {\n public void onClick(Widget sender) { \n useEndpointAsName = !useParameterAsNameRadio.isChecked(); \n } \n });\n \n final RadioButton useEndpointAsNameRadio = new RadioButton(\"paramOrEndpoint\", GuiFactory.strings.useEndpoint());\n useEndpointAsNameRadio.setChecked(useEndpointAsName);\n useEndpointAsNameRadio.addClickListener(new ClickListener() {\n public void onClick(Widget sender) { \n useEndpointAsName = useEndpointAsNameRadio.isChecked();\n } \n });\n \n final TextBox indentWidthTextBox = new TextBox();\n indentWidthTextBox.setWidth(panelHeight);\n indentWidthTextBox.setText(indentWidth + \"\");\n indentWidthTextBox.addChangeListener(new ChangeListener() {\n public void onChange(Widget sender) {\n try {\n indentWidth = Integer.parseInt(indentWidthTextBox.getText());\n indentWidthTextBox.removeStyleName(\"restDescribe-error\");\n if (SettingsDialog.indentWidth == 0) {\n indentWidthTextBox.setStyleName(\"restDescribe-error\");\n }\n } catch (NumberFormatException e) { \n indentWidthTextBox.setStyleName(\"restDescribe-error\");\n } \n } \n });\n \n final HorizontalPanel indentMiniPanel = new HorizontalPanel();\n final RadioButton indentWithSpacesRadio = new RadioButton(\"indent\", GuiFactory.strings.indentSpaces());\n indentWithSpacesRadio.setChecked(indentWithSpaces);\n indentWithSpacesRadio.addClickListener(new ClickListener() {\n public void onClick(Widget sender) { \n indentWithSpaces = indentWithSpacesRadio.isChecked();\n indentMiniPanel.setVisible(true);\n } \n });\n \n final RadioButton indentWithTabsRadio = new RadioButton(\"indent\", GuiFactory.strings.indentTabs());\n indentWithTabsRadio.setChecked(!indentWithSpaces);\n indentWithTabsRadio.addClickListener(new ClickListener() {\n public void onClick(Widget sender) { \n indentWithSpaces = !indentWithTabsRadio.isChecked();\n indentMiniPanel.setVisible(false);\n } \n });\n \n final TextBox classSuffixTextBox = new TextBox();\n classSuffixTextBox.setText(classDefaultSuffix);\n classSuffixTextBox.setWidth(textBoxWidth);\n classSuffixTextBox.addChangeListener(new ChangeListener() {\n public void onChange(Widget sender) {\n classDefaultSuffix = classSuffixTextBox.getText(); \n }\n });\n \n final TextBox pathToDiscovererTextBox = new TextBox();\n pathToDiscovererTextBox.setText(pathToDiscoverer);\n pathToDiscovererTextBox.setWidth(textBoxWidth);\n pathToDiscovererTextBox.addChangeListener(new ChangeListener() {\n public void onChange(Widget sender) { \n pathToDiscoverer = pathToDiscovererTextBox.getText(); \n } \n });\n \n // preferences\n VerticalPanel preferencesPanel = new VerticalPanel(); \n preferencesPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_TOP);\n \n // details\n HorizontalPanel detailsPanel = new HorizontalPanel(); \n detailsPanel.setHeight(panelHeight);\n HorizontalPanel detailsPanelLeft = new HorizontalPanel();\n HorizontalPanel detailsPanelRight = new HorizontalPanel(); \n detailsPanelLeft.setWidth(panelWidthLeft);\n detailsPanelLeft.add(new HTML(\"<b>\" + GuiFactory.strings.details() + \"</b>\"));\n detailsPanelRight.setWidth(panelWidthRight);\n detailsPanelRight.add(detailsCheckBox);\n detailsPanelRight.add(new HTML(GuiFactory.strings.displayDetails()));\n detailsPanel.add(detailsPanelLeft);\n detailsPanel.add(detailsPanelRight); \n preferencesPanel.add(detailsPanel);\n \n // tree items open\n HorizontalPanel treesPanel = new HorizontalPanel(); \n treesPanel.setHeight(panelHeight);\n HorizontalPanel treesPanelLeft = new HorizontalPanel();\n HorizontalPanel treesPanelRight = new HorizontalPanel(); \n treesPanelLeft.setWidth(panelWidthLeft);\n treesPanelLeft.add(new HTML(\"<b>\" + GuiFactory.strings.treesOpen() + \"</b>\"));\n treesPanelRight.setWidth(panelWidthRight);\n treesPanelRight.add(treesCheckBox);\n treesPanelRight.add(new HTML(GuiFactory.strings.treesAlwaysOpen()));\n treesPanel.add(treesPanelLeft);\n treesPanel.add(treesPanelRight); \n preferencesPanel.add(treesPanel);\n \n // request tab\n VerticalPanel requestPanel = new VerticalPanel(); \n requestPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_TOP);\n\n // path to discoverer\n HorizontalPanel pathPanel = new HorizontalPanel();\n pathPanel.setHeight(panelHeight);\n HorizontalPanel pathPanelLeft = new HorizontalPanel();\n HorizontalPanel pathPanelRight = new HorizontalPanel();\n pathPanelLeft.setWidth(panelWidthLeft);\n pathPanelLeft.add(new HTML(\"<b>\" + GuiFactory.strings.pathDiscover() + \"</b>\"));\n pathPanelRight.setWidth(panelWidthRight);\n pathPanelRight.add(pathToDiscovererTextBox);\n pathPanelRight.add(new HTML(GuiFactory.strings.pathToDiscoverer())); \n pathPanel.add(pathPanelLeft);\n pathPanel.add(pathPanelRight); \n requestPanel.add(pathPanel);\n \n // timeout\n HorizontalPanel timeoutPanel = new HorizontalPanel();\n timeoutPanel.setHeight(panelHeight);\n HorizontalPanel timeoutPanelLeft = new HorizontalPanel();\n HorizontalPanel timeoutPanelRight = new HorizontalPanel();\n timeoutPanelLeft.setWidth(panelWidthLeft);\n timeoutPanelLeft.add(new HTML(\"<b>\" + GuiFactory.strings.timeout() + \"</b>\"));\n timeoutPanelRight.setWidth(panelWidthRight);\n timeoutPanelRight.add(timeoutSecondsTextBox);\n timeoutPanelRight.add(new HTML(GuiFactory.strings.timeoutSeconds())); \n timeoutPanel.add(timeoutPanelLeft);\n timeoutPanel.add(timeoutPanelRight); \n requestPanel.add(timeoutPanel);\n \n // code generation tab\n VerticalPanel codeGenerationPanel = new VerticalPanel(); \n codeGenerationPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_TOP);\n \n // naming depth\n HorizontalPanel namingDepthPanel = new HorizontalPanel();\n namingDepthPanel.setHeight(panelHeight);\n HorizontalPanel namingDepthPanelLeft = new HorizontalPanel();\n HorizontalPanel namingDepthPanelRight = new HorizontalPanel();\n namingDepthPanelLeft.setWidth(panelWidthLeft);\n namingDepthPanelLeft.add(new HTML(\"<b>\" + GuiFactory.strings.namingDepth() + \"</b>\"));\n namingDepthPanelRight.setWidth(panelWidthRight);\n namingDepthPanelRight.add(namingDepthTextBox);\n namingDepthPanelRight.add(new HTML(GuiFactory.strings.namingDepthLevel())); \n namingDepthPanel.add(namingDepthPanelLeft);\n namingDepthPanel.add(namingDepthPanelRight); \n codeGenerationPanel.add(namingDepthPanel);\n \n // class default suffix\n HorizontalPanel classSuffixPanel = new HorizontalPanel();\n classSuffixPanel.setHeight(panelHeight);\n HorizontalPanel classSuffixPanelLeft = new HorizontalPanel();\n HorizontalPanel classSuffixPanelRight = new HorizontalPanel();\n classSuffixPanelLeft.setWidth(panelWidthLeft);\n classSuffixPanelLeft.add(new HTML(\"<b>\" + GuiFactory.strings.classSuffix() + \"</b>\"));\n classSuffixPanelRight.setWidth(panelWidthRight);\n classSuffixPanelRight.add(classSuffixTextBox);\n classSuffixPanelRight.add(new HTML(GuiFactory.strings.classDefaultSuffix())); \n classSuffixPanel.add(classSuffixPanelLeft);\n classSuffixPanel.add(classSuffixPanelRight); \n codeGenerationPanel.add(classSuffixPanel);\n \n // source for class names\n HorizontalPanel classNamePanel = new HorizontalPanel();\n classNamePanel.setHeight(panelHeight);\n HorizontalPanel classNamePanelLeft = new HorizontalPanel();\n HorizontalPanel classNamePanelRight = new HorizontalPanel();\n classNamePanelLeft.setWidth(panelWidthLeft);\n classNamePanelLeft.add(new HTML(\"<b>\" + GuiFactory.strings.className() + \"</b>\"));\n classNamePanelRight.setWidth(panelWidthRight);\n VerticalPanel radioPanel = new VerticalPanel(); \n radioPanel.add(useEndpointAsNameRadio);\n radioPanel.add(useParameterAsNameRadio);\n classNamePanelRight.add(radioPanel); \n classNamePanel.add(classNamePanelLeft);\n classNamePanel.add(classNamePanelRight); \n codeGenerationPanel.add(classNamePanel);\n \n // source for class names\n HorizontalPanel indentionPanel = new HorizontalPanel();\n indentionPanel.setHeight(panelHeight);\n HorizontalPanel indentionPanelLeft = new HorizontalPanel();\n HorizontalPanel indentionPanelRight = new HorizontalPanel();\n indentionPanelLeft.setWidth(panelWidthLeft);\n indentionPanelLeft.add(new HTML(\"<b>\" + GuiFactory.strings.indentionStyle() + \"</b>\"));\n indentionPanelRight.setWidth(panelWidthRight);\n VerticalPanel indentionRadioPanel = new VerticalPanel();\n indentionRadioPanel.add(indentWithSpacesRadio); \n indentMiniPanel.add(indentWidthTextBox);\n indentMiniPanel.add(new HTML(GuiFactory.strings.indentionWidth()));\n indentionRadioPanel.add(indentMiniPanel);\n indentionRadioPanel.add(indentWithTabsRadio);\n indentionPanelRight.add(indentionRadioPanel); \n indentionPanel.add(indentionPanelLeft);\n indentionPanel.add(indentionPanelRight); \n codeGenerationPanel.add(indentionPanel);\n \n // use separation character\n HorizontalPanel useSeparationCharacterPanel = new HorizontalPanel(); \n useSeparationCharacterPanel.setHeight(panelHeight);\n HorizontalPanel useSeparationCharacterPanelLeft = new HorizontalPanel();\n HorizontalPanel useSeparationCharacterPanelRight = new HorizontalPanel(); \n useSeparationCharacterPanelLeft.setWidth(panelWidthLeft);\n useSeparationCharacterPanelLeft.add(new HTML(\"<b>\" + GuiFactory.strings.sepChar() + \"</b>\"));\n useSeparationCharacterPanelRight.setWidth(panelWidthRight);\n VerticalPanel miniSepPanel = new VerticalPanel(); \n HorizontalPanel miniSepCheckPanel = new HorizontalPanel();\n miniSepPanel.add(miniSepCheckPanel);\n miniSepCheckPanel.add(useSeparationCharacterCheckBox);\n miniSepCheckPanel.add(new HTML(GuiFactory.strings.useSepChar())); \n miniSepTextPanel.add(separationCharacterTextBox);\n miniSepTextPanel.add(new HTML(GuiFactory.strings.sepWithChar()));\n miniSepPanel.add(miniSepTextPanel);\n useSeparationCharacterPanelRight.add(miniSepPanel); \n useSeparationCharacterPanel.add(useSeparationCharacterPanelLeft);\n useSeparationCharacterPanel.add(useSeparationCharacterPanelRight); \n codeGenerationPanel.add(useSeparationCharacterPanel);\n \n tabPanel.add(generalPanel, \"<a href=\\\"#\\\">\" + GuiFactory.strings.generalTab() + \"</a>\", true);\n tabPanel.add(preferencesPanel, \"<a href=\\\"#\\\">\" + GuiFactory.strings.preferencesTab() + \"</a>\", true);\n tabPanel.add(requestPanel, \"<a href=\\\"#\\\">\" + GuiFactory.strings.requestTab() + \"</a>\", true);\n tabPanel.add(codeGenerationPanel, \"<a href=\\\"#\\\">\" + GuiFactory.strings.codeGenerationTab() + \"</a>\", true);\n tabPanel.selectTab(0);\n \n // ok button\n HorizontalPanel buttonPanel = new HorizontalPanel();\n Button okButton = new Button(GuiFactory.strings.ok());\n buttonPanel.add(okButton);\n okButton.addClickListener(new ClickListener() {\n public void onClick(Widget sender) {\n // apply changes\n alwaysShowDetails = alwaysShowDetailsTemp;\n treeItemsAlwaysOpen = treeItemsAlwaysOpenTemp;\n useSeparationCharacter = useSeparationCharacterTemp; \n RestCompilePanel.generateCode(CodeGenerator.language);\n GuiFactory.blockScreen(false); \n dialogBox.hide();\n }\n });\n \n // cancel button\n Button closeButton = new Button(GuiFactory.strings.cancel());\n buttonPanel.add(closeButton);\n closeButton.addClickListener(new ClickListener() {\n public void onClick(Widget sender) { \n GuiFactory.blockScreen(false);\n dialogBox.hide();\n }\n });\n \n settingsPanel.add(new HTML(\"<br />\"));\n settingsPanel.add(tabPanel);\n settingsPanel.add(new HTML(\"<br />\"));\n settingsPanel.add(buttonPanel);\n settingsPanel.setCellHorizontalAlignment(buttonPanel, HasHorizontalAlignment.ALIGN_CENTER);\n \n dialogBox.setPopupPosition((int) Math.floor(Window.getClientWidth() / 4), (int) Math.floor(Window.getClientHeight() / 4));\n dialogBox.setWidget(settingsPanel); \n GuiFactory.blockScreen(true); \n dialogBox.show(); \n }\n \n private static void updateAndDisplayConfirmLink(String selectedLanguage, HTML confirmLink, HorizontalPanel confirmLangChange) {\n confirmLangChange.setVisible(true);\n confirmLink.setHTML(\"\");\n if (selectedLanguage.equals(GuiFactory.strings.german())) { \n confirmLink.setHTML(confirm_de);\n }\n else if (selectedLanguage.equals(GuiFactory.strings.english_US())) {\n confirmLink.setHTML(confirm_enUS);\n }\n else if (selectedLanguage.equals(GuiFactory.strings.catalan())) {\n confirmLink.setHTML(confirm_ca);\n } \n }\n}",
"public class SyntaxHighlighter {\r\n\tpublic SyntaxHighlighter() {\r\n\t\treturn;\r\n\t}\r\n \r\n public static String toHtml(String code) {\r\n code = encodeEntities(code);\r\n \r\n // <openTag>\r\n String regExp = \"(<\\\\??\\\\w+)(.*?)(\\\\??/?>)\";\r\n code = code.replaceAll(regExp, \"<span class=\\\"tag\\\">$1</span>$2<span class=\\\"tag\\\">$3</span>\\n<br />\");\r\n \r\n // attrib = \"string\"\r\n regExp = \"([a-zA-Z0-9_:]+\\\\s*=)(\\\\s*["a-zA-Z0-9_:#\\\\/\\\\.\\\\-\\\\s\\\\(\\\\)\\\\+]+"|['a-zA-Z0-9_:#\\\\/\\\\.\\\\-\\\\s\\\\(\\\\)\\\\+]+')\";\r\n code = code.replaceAll(regExp, \"<span class=\\\"attribute\\\">$1</span><span class=\\\"string\\\">$2</span>\");\r\n \r\n // </closeTag>\r\n regExp = \"(</\\\\w+>)\";\r\n code = code.replaceAll(regExp, \"<span class=\\\"tag\\\">$1</span>\\n<br />\");\r\n \r\n return code;\r\n }\r\n \r\n public static String encodeEntities(String code) {\r\n code = code.replaceAll(\"'\", \"'\"); \r\n code = code.replaceAll(\"\\\"\", \""\"); \r\n code = code.replaceAll(\"<\", \"<\"); \r\n code = code.replaceAll(\">\", \">\"); \r\n return code;\r\n }\r\n \r\n public static String htmlifyLineBreaksAndTabs(String code, int tabWidth) {\r\n code = encodeEntities(code);\r\n code = code.replaceAll(\"\\n\", \"<br />\");\r\n String tab = \"\";\r\n for (int i = 0; i < tabWidth; i++) tab += \" \";\r\n code = code.replaceAll(\"\\t\", tab);\r\n return code;\r\n }\r\n \r\n public static String highlight(String code) { \r\n code = encodeEntities(code);\r\n // complete tag\r\n String regExp = \"(^</?.*?>$)\"; \r\n code = code.replaceAll(regExp, \"<span class=\\\"tag\\\">$1</span>\");\r\n\r\n // opening tag \r\n regExp = \"(^<.*?\\\\s)\"; \r\n code = code.replaceAll(regExp, \"<span class=\\\"tag\\\">$1</span><span class=\\\"attribute\\\">\");\r\n \r\n // closing tag\r\n regExp = \"(/?>$)\"; \r\n code = code.replaceAll(regExp, \"</span><span class=\\\"tag\\\">$1</span>\"); \r\n \r\n // attribute strings\r\n regExp = \"(.*?)("(.*?")*)\";\r\n code = code.replaceAll(regExp, \"<span class=\\\"attribute\\\">$1</span><span class=\\\"string\\\">$2</span>\");\r\n regExp = \"('.*?')\";\r\n code = code.replaceAll(regExp, \"<span class=\\\"attribute\\\">$1</span><span class=\\\"string\\\">$2</span>\");\r\n\r\n // xml comments\r\n regExp = \"(<!--?.*?-->)\"; \r\n code = code.replaceAll(regExp, \"<span class=\\\"comment\\\">$1</span>\"); \r\n \r\n return code; \r\n }\r\n}\r",
"public class MethodNode extends GenericNode {\r\n private Vector allParams = new Vector(); \r\n private String name;\r\n private String id;\r\n private String href;\r\n private RequestNode request;\r\n private ResponseNode response; \r\n \r\n public MethodNode(String methodName, GenericNode node, ApplicationNode application) {\r\n name = methodName; \r\n super.parent = node;\r\n super.application = application;\r\n }\r\n \r\n public MethodNode(String methodId, boolean isReferenced, GenericNode node, ApplicationNode application) {\r\n name = null;\r\n id = null;\r\n href = \"#\" + methodId; \r\n super.parent = node;\r\n super.application = application;\r\n }\r\n \r\n public String getName() {\r\n return name;\r\n } \r\n \r\n public String getInternalMethodId() {\r\n String internalMethodId = \"\";\r\n if (this.getRequest() != null && this.getRequest().getAllParams() != null) {\r\n Vector allParams = this.getRequest().getAllParams();\r\n for (Iterator allParamsIterator = allParams.iterator(); allParamsIterator.hasNext(); /* empty */) {\r\n ParamNode param = (ParamNode) allParamsIterator.next();\r\n internalMethodId += param.getName();\r\n }\r\n }\r\n return internalMethodId;\r\n }\r\n \r\n public String getId() {\r\n return id;\r\n } \r\n \r\n public void updateId(String oldId, String newId) {\r\n if (oldId.equals(getId())) {\r\n id = newId; \r\n }\r\n }\r\n \r\n public void updateName(String oldName, String newName) {\r\n if (getName().equals(oldName)) {\r\n name = newName;\r\n }\r\n }\r\n\r\n public void addParam(ParamNode param) { \r\n allParams.add(param);\r\n }\r\n \r\n public Vector getAllParams() { \r\n return allParams;\r\n }\r\n\r\n public void addRequest(RequestNode requestNode) {\r\n request = requestNode;\r\n }\r\n \r\n public RequestNode getRequest() {\r\n return request;\r\n }\r\n\r\n public void addResponse(ResponseNode responseNode) {\r\n response = responseNode;\r\n }\r\n \r\n public ResponseNode getResponse() {\r\n return response;\r\n }\r\n\r\n /**\r\n * @return\r\n */\r\n public String getHref() { \r\n return href;\r\n }\r\n\r\n /**\r\n * @param methodId\r\n */\r\n public void setId(String methodId) {\r\n id = methodId; \r\n }\r\n\r\n /**\r\n * @param requestNode\r\n */\r\n public void removeRequest(RequestNode requestNode) {\r\n request = null; \r\n }\r\n \r\n /**\r\n * @param responseNode\r\n */\r\n public void removeResponse(ResponseNode responseNode) {\r\n response = null; \r\n }\r\n}\r",
"public class ResponseNode extends GenericNode {\r\n private Vector allParams = new Vector();\r\n private Vector allRepresentations = new Vector();\r\n private Vector allFaults = new Vector(); \r\n\r\n public ResponseNode(MethodNode method, ApplicationNode application) { \r\n super.parent = method;\r\n super.application = application;\r\n }\r\n \r\n public void addParam(ParamNode param) { \r\n if (!allParams.contains(param)) {\r\n allParams.add(param);\r\n }\r\n }\r\n \r\n public Vector getAllParams() { \r\n return allParams;\r\n }\r\n \r\n public void removeParam(ParamNode param) {\r\n if (allParams.contains(param)) {\r\n allParams.remove(param);\r\n } \r\n }\r\n\r\n public void addRepresentation(RepresentationNode representation) { \r\n if (!allRepresentations.contains(representation)) {\r\n allRepresentations.add(representation);\r\n }\r\n }\r\n \r\n public Vector getAllRepresentations() { \r\n return allRepresentations;\r\n }\r\n\r\n public void removeRepresentation(RepresentationNode representation) {\r\n if (allRepresentations.contains(representation)) {\r\n allRepresentations.remove(representation);\r\n } \r\n }\r\n\r\n public void removeFault(FaultNode fault) {\r\n if (allFaults.contains(fault)) {\r\n allFaults.remove(fault);\r\n } \r\n }\r\n \r\n public void addFault(FaultNode fault) {\r\n if (!allFaults.contains(fault)) {\r\n allFaults.add(fault);\r\n }\r\n }\r\n\r\n public Vector getAllFaults() { \r\n return allFaults;\r\n }\r\n}\r",
"public class WadlXml {\r\n private Document wadl = XMLParser.createDocument();\r\n private static final String xmlHeader = \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\\n\";\r\n \r\n // list of elements\r\n public static final String applicationNode = \"application\"; \r\n public static final String resourcesNode = \"resources\";\r\n public static final String resourceNode = \"resource\";\r\n public static final String resourceTypeNode = \"resource_type\";\r\n public static final String requestNode = \"request\";\r\n public static final String responseNode = \"response\"; \r\n public static final String methodNode = \"method\";\r\n public static final String paramNode = \"param\";\r\n public static final String docNode = \"doc\";\r\n public static final String grammarsNode = \"grammars\";\r\n public static final String includeNode = \"include\";\r\n public static final String representationNode = \"representation\";\r\n public static final String faultNode = \"fault\";\r\n public static final String optionNode = \"option\";\r\n public static final String linkNode = \"link\";\r\n \r\n // allowed child elements\r\n public static final String[] applicationChildren = {resourcesNode, grammarsNode, resourceTypeNode, methodNode, representationNode, paramNode, faultNode, docNode};\r\n public static final String[] resourcesChildren = {resourceNode, docNode};\r\n public static final String[] grammarsChildren = {includeNode, docNode};\r\n public static final String[] includeChildren = {docNode};\r\n public static final String[] optionChildren = {docNode};\r\n public static final String[] linkChildren = {docNode};\r\n public static final String[] resourceChildren = {paramNode, methodNode, resourceNode, docNode};\r\n public static final String[] resource_typeChildren = {paramNode, methodNode, docNode};\r\n public static final String[] methodChildren = {requestNode, responseNode, docNode};\r\n public static final String[] requestChildren = {representationNode, paramNode, docNode};\r\n public static final String[] responseChildren = {representationNode, faultNode, paramNode, docNode};\r\n public static final String[] representationChildren = {paramNode, docNode};\r\n public static final String[] paramChildren = {optionNode, linkNode, docNode};\r\n public static final String[] faultChildren = {paramNode, docNode};\r\n\r\n // list of attributes\r\n public static final String application_xmlns_xsi = \"xmlns:xsi\";\r\n public static final String application_xmlns_xsd = \"xmlns:xsd\"; \r\n public static final String application_xsi_schemaLocation = \"xsi:schemaLocation\";\r\n public static final String application_xmlns = \"xmlns\"; \r\n public static final String application_xmlns_extNs = \"xmlns:extNs\"; // for additional external namespaces\r\n public static final String doc_xml_lang = \"xml:lang\";\r\n public static final String doc_title = \"title\";\r\n public static final String include_href = \"href\";\r\n public static final String resources_base = \"base\";\r\n public static final String resource_href = \"href\";\r\n public static final String resource_id = \"id\";\r\n public static final String resource_path = \"path\";\r\n public static final String resource_type = \"type\";\r\n public static final String resource_queryType = \"queryType\";\r\n public static final String resource_type_id = \"id\";\r\n public static final String method_href = \"href\";\r\n public static final String method_id = \"id\";\r\n public static final String method_name = \"name\";\r\n public static final String representation_href = \"href\";\r\n public static final String representation_id = \"id\";\r\n public static final String representation_mediaType = \"mediaType\";\r\n public static final String representation_element = \"element\";\r\n public static final String representation_profile = \"profile\";\r\n public static final String representation_status = \"status\";\r\n public static final String fault_href = \"href\";\r\n public static final String fault_id = \"id\";\r\n public static final String fault_mediaType = \"mediaType\";\r\n public static final String fault_element = \"element\";\r\n public static final String fault_profile = \"profile\";\r\n public static final String fault_status = \"status\";\r\n public static final String param_id = \"id\";\r\n public static final String param_href = \"href\";\r\n public static final String param_name = \"name\";\r\n public static final String param_style = \"style\";\r\n public static final String param_type = \"type\";\r\n public static final String param_default = \"default\";\r\n public static final String param_path = \"path\";\r\n public static final String param_required = \"required\";\r\n public static final String param_repeating = \"repeating\";\r\n public static final String param_fixed = \"fixed\";\r\n public static final String option_value = \"value\";\r\n public static final String link_resource_type = \"resource_type\";\r\n public static final String link_rel = \"rel\";\r\n public static final String link_rev = \"rev\";\r\n \r\n // allowed attributes\r\n public static final String[] applicationAttributes = {application_xmlns_xsi, application_xmlns_xsd, application_xsi_schemaLocation, application_xmlns}; \r\n public static final String[] docAttributes = {doc_title, doc_xml_lang};\r\n public static final String[] includeAttributes = {include_href};\r\n public static final String[] resourcesAttributes = {resources_base};\r\n public static final String[] resourceAttributes = {resource_id, resource_path, resource_type, resource_queryType};\r\n public static final String[] resource_typeAttributes = {resource_type_id};\r\n public static final String[] methodAttributes = {method_href, method_id, method_name};\r\n public static final String[] representationAttributes = {representation_element, representation_href, representation_id, representation_mediaType, representation_profile, representation_status};\r\n public static final String[] faultAttributes = {fault_element, fault_href, fault_id, fault_mediaType, fault_profile, fault_status};\r\n public static final String[] paramAttributes = {param_id, param_href, param_name, param_style, param_type, param_default, param_path, param_required, param_repeating, param_fixed};\r\n public static final String[] optionAttributes = {option_value};\r\n public static final String[] linkAttributes = {link_rel, link_resource_type, link_rev};\r\n \r\n // default wadl namespace and schema stuff\r\n public static final String xmlns_xsi = \"http://www.w3.org/2001/XMLSchema-instance\";\r\n public static final String xmlns_xsd = \"http://www.w3.org/2001/XMLSchema\"; \r\n public static final String xsi_schemaLocation = \"http://research.sun.com/wadl/2006/10 wadl.xsd\";\r\n public static final String xmlns = \"http://research.sun.com/wadl/2006/10\"; \r\n \r\n public WadlXml(ApplicationNode application) { \r\n // <application> \r\n createApplicationElement(application); \r\n } \r\n \r\n public String dump() {\r\n if (wadl.hasChildNodes()) {\r\n String regExp = \"><\"; \r\n return (xmlHeader + wadl.toString()).replaceAll(regExp, \">\\n<\");\r\n }\r\n else {\r\n return \"\";\r\n }\r\n }\r\n \r\n private void createDocElements(Vector documentation, Node parentElement) { \r\n Iterator iterator = documentation.iterator();\r\n while (iterator.hasNext()) {\r\n // <doc xml:lang=\"\" title=\"xsd:string\">bla</doc>\r\n DocNode doc = (DocNode) iterator.next();\r\n Element docElement = wadl.createElement(docNode);\r\n docElement.setAttribute(doc_xml_lang, doc.getXmlLang());\r\n docElement.setAttribute(doc_title, doc.getTitle()); \r\n docElement.appendChild(wadl.createTextNode(doc.getText()));\r\n \r\n parentElement.appendChild(docElement);\r\n } \r\n }\r\n \r\n private void createApplicationElement(ApplicationNode application) {\r\n // applicationChildren = {resourcesNode, grammarsNode, resourceTypeNode, methodNode, representationNode, faultNode, docNode}\r\n Element applicationElement = wadl.createElement(applicationNode);\r\n applicationElement.setAttribute(application_xmlns_xsi, xmlns_xsi);\r\n applicationElement.setAttribute(application_xmlns_xsd, xmlns_xsd);\r\n applicationElement.setAttribute(application_xsi_schemaLocation, xsi_schemaLocation);\r\n applicationElement.setAttribute(application_xmlns, xmlns); \r\n \r\n // external additional namespaces\r\n Vector allNamespaces = application.getAllNamespaces();\r\n Iterator namespaceIterator = allNamespaces.iterator();\r\n int namespaceCounter = 0;\r\n // add additional application-specific namespaces\r\n while (namespaceIterator.hasNext()) {\r\n NamespaceAttribute namespace = (NamespaceAttribute) namespaceIterator.next();\r\n if (namespace.getName() == null) {\r\n applicationElement.setAttribute(application_xmlns_extNs + namespaceCounter, namespace.getValue());\r\n }\r\n else {\r\n applicationElement.setAttribute(namespace.getName(), namespace.getValue());\r\n }\r\n namespaceCounter++;\r\n } \r\n \r\n // <grammars>\r\n if (application.getGrammars() != null) {\r\n createGrammarsElement(application.getGrammars(), applicationElement); \r\n }\r\n \r\n // <resources base=\"xsd:anyURI\">\r\n if (application.getResources() != null) { \r\n createResourcesElement(application.getResources(), applicationElement); \r\n }\r\n \r\n // <resource_type>\r\n if (application.getAllResourceTypes() != null) {\r\n Vector allResourceTypes = application.getAllResourceTypes();\r\n Iterator allResourceTypesIterator = allResourceTypes.iterator();\r\n while (allResourceTypesIterator.hasNext()) {\r\n createResourceTypeElement((ResourceTypeNode) allResourceTypesIterator.next(), applicationElement);\r\n }\r\n }\r\n \r\n // <method>\r\n if (application.getAllMethods() != null) {\r\n Vector allMethods = application.getAllMethods();\r\n Iterator allMethodsIterator = allMethods.iterator();\r\n while (allMethodsIterator.hasNext()) {\r\n createMethodElement((MethodNode) allMethodsIterator.next(), applicationElement);\r\n }\r\n }\r\n \r\n // <representation>\r\n if (application.getAllRepresentations() != null) {\r\n Vector allRepresentations = application.getAllRepresentations();\r\n Iterator allRepresentationsIterator = allRepresentations.iterator();\r\n while (allRepresentationsIterator.hasNext()) {\r\n createRepresentationElement((RepresentationNode) allRepresentationsIterator.next(), applicationElement);\r\n }\r\n }\r\n \r\n // <param>\r\n if (application.getAllParams() != null) {\r\n Vector allParams = application.getAllParams();\r\n Iterator allParamsIterator = allParams.iterator();\r\n while (allParamsIterator.hasNext()) {\r\n createParamElement((ParamNode) allParamsIterator.next(), applicationElement);\r\n }\r\n }\r\n \r\n // <fault>\r\n if (application.getAllFaults() != null) {\r\n Vector allFaults = application.getAllFaults();\r\n Iterator allFaultsIterator = allFaults.iterator();\r\n while (allFaultsIterator.hasNext()) {\r\n createFaultElement((FaultNode) allFaultsIterator.next(), applicationElement);\r\n }\r\n }\r\n \r\n // <doc>\r\n if (application.getAllDocs() != null) { \r\n createDocElements(application.getAllDocs(), applicationElement); \r\n }\r\n \r\n wadl.appendChild(applicationElement);\r\n }\r\n \r\n /**\r\n * @param resourceType\r\n * @param applicationElement\r\n */\r\n private void createResourceTypeElement(ResourceTypeNode resourceType, Element applicationElement) {\r\n //resource_typeChildren = {paramNode, methodNode, docNode};\r\n Element resourceTypeElement = wadl.createElement(resourceTypeNode);\r\n \r\n // <param>\r\n Vector allResourceParams = resourceType.getAllParams();\r\n Iterator resourceParamIterator = allResourceParams.iterator();\r\n while (resourceParamIterator.hasNext()) { \r\n createParamElement((ParamNode) resourceParamIterator.next(), resourceTypeElement); \r\n }\r\n \r\n // <method>\r\n Vector allMethods = resourceType.getAllMethods();\r\n Iterator methodIterator = allMethods.iterator();\r\n while (methodIterator.hasNext()) { \r\n // <method name=\"{GET|POST|PUT|DELETE}\"> \r\n createMethodElement((MethodNode) methodIterator.next(), resourceTypeElement); \r\n }\r\n \r\n // <doc>\r\n createDocElements(resourceType.getAllDocs(), resourceTypeElement);\r\n \r\n applicationElement.appendChild(resourceTypeElement);\r\n }\r\n\r\n private void createGrammarsElement(GrammarsNode grammars, Element applicationElement) {\r\n // grammarsChildren = {includeNode, docNode} \r\n Element grammarsElement = wadl.createElement(grammarsNode);\r\n // <include> \r\n if (grammars != null) {\r\n Vector allIncludes = grammars.getAllIncludes();\r\n Iterator includeIterator = allIncludes.iterator();\r\n while (includeIterator.hasNext()) {\r\n Element includeElement = wadl.createElement(includeNode);\r\n includeElement.setAttribute(include_href, (String) includeIterator.next());\r\n grammarsElement.appendChild(includeElement);\r\n } \r\n } \r\n \r\n // <doc>\r\n createDocElements(grammars.getAllDocs(), grammarsElement);\r\n \r\n applicationElement.appendChild(grammarsElement); \r\n }\r\n\r\n private void createResourcesElement(ResourcesNode resources, Element applicationElement) {\r\n // resourcesChildren = {resourceNode, docNode}\r\n Element resourcesElement = wadl.createElement(resourcesNode); \r\n resourcesElement.setAttribute(resources_base, resources.getBase());\r\n \r\n // <resource path=\"xsd:string\">\r\n Vector allResources = resources.getAllResources();\r\n Iterator resourceIterator = allResources.iterator(); \r\n while (resourceIterator.hasNext()) { \r\n createResourceElement((ResourceNode) resourceIterator.next(), resourcesElement); \r\n }\r\n \r\n // <doc>\r\n createDocElements(resources.getAllDocs(), resourcesElement);\r\n \r\n applicationElement.appendChild(resourcesElement);\r\n }\r\n \r\n private void createResourceElement(ResourceNode resource, Element parentElement) {\r\n // resourceChildren = {paramNode, methodNode, resourceNode, docNode}\r\n Element resourceElement = wadl.createElement(resourceNode);\r\n if (resource.getHref() != null) {\r\n resourceElement.setAttribute(resource_href, resource.getHref());\r\n }\r\n else { \r\n resourceElement.setAttribute(resource_path, resource.getPath());\r\n if (resource.getId() != null) resourceElement.setAttribute(resource_id, resource.getId());\r\n }\r\n \r\n // <resource>\r\n Vector allInnerResources = resource.getAllResources();\r\n Iterator innerResourceIterator = allInnerResources.iterator(); \r\n while (innerResourceIterator.hasNext()) { \r\n createResourceElement((ResourceNode) innerResourceIterator.next(), resourceElement); \r\n }\r\n \r\n // <doc>\r\n createDocElements(resource.getAllDocs(), resourceElement); \r\n \r\n // <param>\r\n Vector allResourceParams = resource.getAllParams();\r\n Iterator resourceParamIterator = allResourceParams.iterator();\r\n while (resourceParamIterator.hasNext()) { \r\n createParamElement((ParamNode) resourceParamIterator.next(), resourceElement); \r\n }\r\n \r\n // <method>\r\n Vector allMethods = resource.getAllMethods();\r\n Iterator methodIterator = allMethods.iterator();\r\n while (methodIterator.hasNext()) { \r\n // <method name=\"{GET|POST|PUT|DELETE}\"> \r\n createMethodElement((MethodNode) methodIterator.next(), resourceElement); \r\n } \r\n \r\n parentElement.appendChild(resourceElement);\r\n }\r\n \r\n private void createMethodElement(MethodNode method, Element parentElement) {\r\n // methodChildren = {requestNode, responseNode, docNode};\r\n Element methodElement = wadl.createElement(methodNode);\r\n if (method.getHref() != null) {\r\n methodElement.setAttribute(method_href, method.getHref());\r\n }\r\n else {\r\n methodElement.setAttribute(method_name, method.getName());\r\n if (method.getId() != null) methodElement.setAttribute(method_id, method.getId());\r\n }\r\n \r\n // <request> \r\n createRequestElement(method.getRequest(), methodElement); \r\n \r\n // <response>\r\n createResponseElement(method.getResponse(), methodElement);\r\n \r\n // <doc>\r\n createDocElements(method.getAllDocs(), methodElement);\r\n \r\n parentElement.appendChild(methodElement);\r\n }\r\n \r\n private void createRequestElement(RequestNode request, Element parentElement) {\r\n if (request == null) {\r\n return;\r\n }\r\n // requestChildren = {representationNode, paramNode, docNode}\r\n Element requestElement = wadl.createElement(requestNode);\r\n \r\n // <param>\r\n Vector allParams = request.getAllParams();\r\n Iterator paramIterator = allParams.iterator();\r\n while (paramIterator.hasNext()) { \r\n // <param id=\"\"? name=\"\"1 style=\"{query|header}\"1 type=\"xsd:string\"? default=\"\"? required=\"\"? repeating=\"\"? fixed=\"xsd:string\"? /> \r\n createParamElement((ParamNode) paramIterator.next(), requestElement); \r\n }\r\n \r\n // <representation>\r\n Vector allRepresentations = request.getAllRepresentations();\r\n Iterator allRepresentationsIterator = allRepresentations.iterator();\r\n while (allRepresentationsIterator.hasNext()) {\r\n // <representation mediaType=\"\"? element=\"\"? profile=\"\"? status=\"\"? />* \r\n createRepresentationElement((RepresentationNode) allRepresentationsIterator.next(), requestElement); \r\n }\r\n \r\n // <doc>\r\n createDocElements(request.getAllDocs(), requestElement);\r\n\r\n parentElement.appendChild(requestElement);\r\n }\r\n \r\n private void createParamElement(ParamNode param, Element parentElement) {\r\n // paramChildren = {optionNode, linkNode, docNode}\r\n Element paramElement = wadl.createElement(paramNode);\r\n if (param.getHref() != null) {\r\n paramElement.setAttribute(param_href, param.getHref());\r\n }\r\n else {\r\n if (!param.getName().equals(\"\")) paramElement.setAttribute(param_name, param.getName()); \r\n if (!param.getType().equals(\"\")) paramElement.setAttribute(param_type, param.getType());\r\n if (!param.getStyle().equals(\"\")) paramElement.setAttribute(param_style, param.getStyle());\r\n if (!param.getDefaultValue().equals(\"\")) paramElement.setAttribute(param_default, param.getDefaultValue());\r\n if (!param.getFixedValue().equals(\"\")) paramElement.setAttribute(param_fixed, param.getFixedValue());\r\n if (!param.getPath().equals(\"\")) paramElement.setAttribute(param_path, param.getPath());\r\n if (param.getIsRequired()) paramElement.setAttribute(param_required, \"\" + param.getIsRequired());\r\n if (param.getIsRepeating()) paramElement.setAttribute(param_repeating, \"\" + param.getIsRepeating());\r\n if (param.getId() != null) paramElement.setAttribute(param_id, param.getId());\r\n } \r\n \r\n // <option>\r\n if (param.getOptions().size() > 0) {\r\n Iterator optionsIterator = param.getOptions().iterator();\r\n while (optionsIterator.hasNext()) {\r\n Element optionElement = wadl.createElement(optionNode);\r\n optionElement.setAttribute(option_value, (String) optionsIterator.next());\r\n paramElement.appendChild(optionElement);\r\n }\r\n }\r\n \r\n // <link>\r\n if (param.getAllLinks() != null) {\r\n \r\n } \r\n \r\n // <doc>\r\n Vector paramDoc = param.getAllDocs();\r\n Iterator paramDocIterator = paramDoc.iterator();\r\n while (paramDocIterator.hasNext()) {\r\n DocNode docNode = (DocNode) paramDocIterator.next();\r\n if (docNode.getText().equals(\"\")) {\r\n docNode.setText(\"Estimated Type (\" + param.getEstimateQuality() + \"): [\" + param.getType() + \"]\");\r\n }\r\n }\r\n createDocElements(paramDoc, paramElement);\r\n \r\n parentElement.appendChild(paramElement);\r\n }\r\n \r\n private void createResponseElement(ResponseNode response, Element parentElement) {\r\n if (response == null) {\r\n return;\r\n }\r\n // responseChildren = {representationNode, faultNode, paramNode, docNode}\r\n Element responseElement = wadl.createElement(responseNode);\r\n \r\n // <representation>\r\n Vector allRepresentations = response.getAllRepresentations();\r\n Iterator allRepresentationsIterator = allRepresentations.iterator();\r\n while (allRepresentationsIterator.hasNext()) {\r\n // <representation mediaType=\"\"? element=\"\"? profile=\"\"? status=\"\"? />* \r\n createRepresentationElement((RepresentationNode) allRepresentationsIterator.next(), responseElement); \r\n }\r\n\r\n // <fault>\r\n Vector allFaults = response.getAllFaults();\r\n Iterator allFaultsIterator = allFaults.iterator();\r\n while (allFaultsIterator.hasNext()) {\r\n // <fault mediaType=\"\"? element=\"\"? profile=\"\"? status=\"\"? />* \r\n createFaultElement((FaultNode) allFaultsIterator.next(), responseElement); \r\n }\r\n \r\n // <param>\r\n Vector allParams = response.getAllParams();\r\n Iterator paramIterator = allParams.iterator();\r\n while (paramIterator.hasNext()) { \r\n // <param id=\"\"? name=\"\"1 style=\"{query|header}\"1 type=\"xsd:string\"? default=\"\"? required=\"\"? repeating=\"\"? fixed=\"xsd:string\"? /> \r\n createParamElement((ParamNode) paramIterator.next(), responseElement);\r\n }\r\n \r\n // <doc>\r\n createDocElements(response.getAllDocs(), responseElement);\r\n \r\n parentElement.appendChild(responseElement);\r\n }\r\n \r\n private void createRepresentationElement(RepresentationNode representation, Element parentElement) {\r\n // representationChildren = {paramNode, docNode}\r\n Element representationElement = wadl.createElement(representationNode);\r\n if (representation.getHref() != null) {\r\n representationElement.setAttribute(representation_href, representation.getHref());\r\n }\r\n else {\r\n if (!representation.getMediaType().equals(\"\")) representationElement.setAttribute(representation_mediaType, representation.getMediaType());\r\n if (!representation.getElement().equals(\"\")) representationElement.setAttribute(representation_element, representation.getElement());\r\n if (!representation.getStatus().equals(\"\")) representationElement.setAttribute(representation_status, representation.getStatus());\r\n if (!representation.getProfile().equals(\"\")) representationElement.setAttribute(representation_profile, representation.getProfile());\r\n if (representation.getId() != null) representationElement.setAttribute(representation_id, representation.getId());\r\n } \r\n \r\n // <param>\r\n Vector allRepresentationParams = representation.getAllParams();\r\n Iterator representationParamIterator = allRepresentationParams.iterator();\r\n while (representationParamIterator.hasNext()) { \r\n // <param id=\"\"? name=\"\"1 style=\"{query|header}\"1 type=\"xsd:string\"? default=\"\"? required=\"\"? repeating=\"\"? fixed=\"xsd:string\"? /> \r\n createParamElement((ParamNode) representationParamIterator.next(), representationElement); \r\n }\r\n \r\n // <doc>\r\n createDocElements(representation.getAllDocs(), representationElement);\r\n \r\n parentElement.appendChild(representationElement);\r\n }\r\n \r\n private void createFaultElement(FaultNode fault, Element parentElement) {\r\n // faultChildren = {paramNode, docNode}\r\n Element faultElement = wadl.createElement(faultNode);\r\n \r\n // <fault>\r\n if (fault.getHref() != null) {\r\n faultElement.setAttribute(fault_href, fault.getHref());\r\n }\r\n else { \r\n if (!fault.getMediaType().equals(\"\")) faultElement.setAttribute(fault_mediaType, fault.getMediaType());\r\n if (!fault.getElement().equals(\"\")) faultElement.setAttribute(fault_element, fault.getElement());\r\n if (!fault.getStatus().equals(\"\")) faultElement.setAttribute(fault_status, fault.getStatus());\r\n if (!fault.getProfile().equals(\"\")) faultElement.setAttribute(fault_profile, fault.getProfile());\r\n if (fault.getId() != null) faultElement.setAttribute(fault_id, fault.getId());\r\n } \r\n \r\n // <doc>\r\n createDocElements(fault.getAllDocs(), faultElement);\r\n \r\n parentElement.appendChild(faultElement);\r\n }\r\n}\r"
] | import java.util.Vector;
import com.google.code.apis.rest.client.GUI.GuiFactory;
import com.google.code.apis.rest.client.GUI.SettingsDialog;
import com.google.code.apis.rest.client.Util.SyntaxHighlighter;
import com.google.code.apis.rest.client.Wadl.MethodNode;
import com.google.code.apis.rest.client.Wadl.ResponseNode;
import com.google.code.apis.rest.client.Wadl.WadlXml;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.Widget;
| package com.google.code.apis.rest.client.Tree;
public class ResponseItem extends Composite {
public ResponseItem(final MethodNode method, final TreeItem methodTreeItem) {
HorizontalPanel containerPanel = new HorizontalPanel();
| HTML response = new HTML(SyntaxHighlighter.highlight("<" + WadlXml.responseNode + ">"));
| 2 |
uiuc-ischool-scanr/SAIL | src/core/AnnotationTask.java | [
"public class Prediction {\n\t\n\t\n\tInstances original, labled, unlabled, ep_instances, sns_instances;\n\tString inputFile, outputDir;\n\tMODELTYPE classifierType;\n\tint clsIndex;\n\tString filePrefix;\n\tClassifier cls;\n\t\n\tprivate static int CLASSINDEX = 44;\n\tprivate static String stringAttr = \"3,4,6,8,10-12,14,42,43,45\";\n\tprivate static String removeAttr = \"3,4,6,10-12,14,42,43,45-last\";\n\t\n\t/*private static int CLASSINDEX = 19;\n\tprivate static String stringAttr = \"3,4,6,8,10-12,14,17,18,20\";\n\tprivate static String removeAttr = \"3,4,6,10-12,14,17,18,20-last\";*/\n\t//FilteredClassifier cls;\n\tpublic static enum outDirIndex {ORIGINAL, LABELED, UPDATES, MODELS};\n\tpublic static final String[] outDirs = {\"original\", \"labled\", \"updates\", \"models\"};\n\tprivate static final String SentimentModelFile = \"./data/models/All_filtered_pos_j48.model\"; // This file no longer exists.\n\tprivate static String SentimentModelFile_word = \"./data/models/All_filtered_pos_SGD_10000_3.model\";\n\tprivate String customModelFile = \"\";\n\tprivate static String FILEPREFIX = \"Sentiment\";\n\tprivate boolean showProbability =true;\n\tpublic static enum MODELTYPE {\n\t\tSENTIMENT(\"Meta Model\"),\n\t\tSENTIMENT_WORD(\"Word Model\"),\n\t\tCUSTOM(\"Custom...\");\n\t\tprivate String text;\n\t\tprivate MODELTYPE(String text) {\n\t\t\t// TODO Auto-generated constructor stub\n\t\t\tthis.text = text;\n\t\t}\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\t// TODO Auto-generated method stub\n\t\t\treturn this.text;\n\t\t}\n\t\t\n\t};\n\tprivate ArrayList<Double[][]> classDist;\n\tprivate String[] classNames = {\"positive\", \"negative\"};\n\tprivate int classProbIndex = -1;\n\t\n\tpublic static void setModelParams(int class_index, String string_list, String remove_list, String model){\n\t\tCLASSINDEX = class_index;\n\t\tstringAttr = string_list;\n\t\tremoveAttr = remove_list;\n\t\tSentimentModelFile_word = model;\n\t}\n\t\n\t\n\tpublic Prediction(String inputFile, String outputDir, MODELTYPE classifierType) {\n\t\t// TODO Auto-generated constructor stub\n\t\tthis.inputFile = inputFile;\n\t\tthis.outputDir = outputDir;\n\t\tthis.classifierType = classifierType;\n\t\tthis.setInstances(this.inputFile);\n\t}\n\t\n\tpublic Prediction(String inputFile, String outputDir, MODELTYPE classifierType, String prefix) {\n\t\t// TODO Auto-generated constructor stub\n\t\tthis(inputFile, outputDir, classifierType);\n\t\tthis.filePrefix = prefix;\n\t}\n\n\t/**\n\t * @return the customModelFile\n\t */\n\tpublic String getCustomModelFile() {\n\t\treturn customModelFile;\n\t}\n\n\t/**\n\t * @param customModelFile the customModelFile to set\n\t */\n\tpublic void setCustomModelFile(String customModelFile) {\n\t\tthis.customModelFile = customModelFile;\n\t\tSystem.out.println(\"Using custom model file for predictions: \"+customModelFile);\n\t}\n\n\t/**\n\t * @param args\n\t */\n\tpublic static void main(String[] args) {\n\t\t// TODO Auto-generated method stub\n\t\tString inputFile = \"./output/Supplementary_POS.tsv\";\n\t\tString outputDir = \"./output\";\n\t\tPrediction obj = new Prediction(inputFile, outputDir, MODELTYPE.SENTIMENT);\n\t\tobj.doPredictions(false);\n\t}\n\n\tprivate void prepareOutputFolder() {\n\t\tfor (String dirName : outDirs) {\n\t\t\tdirName = outputDir + \"/\" + dirName;\n\t\t\tUtils.createFolder(dirName);\n\t\t}\n\t}\n\t\n\t/**\n\t * \n\t * \n\t * @param predicted - if false then do the predictions else do not do the predictions\n\t */\n\tpublic int doPredictions(boolean predicted) {\n\t\t//classDist = new ArrayList<Double[][]>();\n\t\tint status = 0;\n\t\tthis.prepareOutputFolder();\n\t\tfor(int i = 0; i < unlabled.numInstances(); i++){\n\t\t\t/*\n\t\t\t * Distribution stored as:\n\t\t\t * {{E, P}, {S, NS}}\n\t\t\t */\n\t\t\t//classDist.add(TweetCorpusStatistics.getNullDist()); \n\t\t}\n\t\tstatus = setClassifier(classifierType);\n\t\tif(status > 0){\n\t\t\tSystem.err.println(\"Error in setting classifier.\");\n\t\t\treturn 1;\n\t\t}\n\t\tlabled = new Instances(unlabled);\n\t\tlabled.setClassIndex(labled.numAttributes() - 1);\n\t\tif(!predicted){\n\t\t\tstatus = performClassification();\n\t\t\tif(status > 0){\n\t\t\t\tSystem.err.println(\"Error in performing classification\");\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t}\n\t\t\n\t\tstatus = writePredictions(labled, \"/\"+Utils.getOutDir(Utils.OutDirIndex.LABELED)+\"/\"+filePrefix);\n\t\tif(status < 0){\n\t\t\tSystem.err.println(\"Writing output file failed: \"+Utils.getOutDir(Utils.OutDirIndex.LABELED));\n\t\t\treturn 3;\n\t\t}\n\t\ttry {\n\t\t\tRemove r = new Remove();\n\t\t\tstatus = writePredictions(original, \"/\"+Utils.getOutDir(Utils.OutDirIndex.ORIGINAL)+\"/\"+filePrefix);\n\t\t\tif(status < 0){\n\t\t\t\tSystem.err.println(\"Writing output file failed: \"+Utils.getOutDir(Utils.OutDirIndex.ORIGINAL));\n\t\t\t\treturn 4;\n\t\t\t}\n\t\t\t//writeStats(original);\n\t\t} catch (Exception e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t\treturn 5;\n\t\t}\n\t\treturn 0;\n\t}\n\t\n\tpublic String printDist(Double[][] dist){\n\t\tString distStr = \"\";\n\t\tif(dist != null)\n\t\t\tdistStr = dist[0][0]+\"\\t\"+dist[0][1]+\"\\t\"+dist[1][0]+\"\\t\"+dist[1][1];\n\t\treturn distStr;\n\t}\n\tpublic void writeStats(Instances tweetInstances){\n\t\t//TweetCorpusStatistics stats = new TweetCorpusStatistics();\n\t\tSystem.out.println(\"Stats Instances: \\n\"+tweetInstances.toSummaryString());\n\t\tfor(int i =0; i < tweetInstances.size(); i++){\n\t\t\tString user = tweetInstances.get(i).stringValue(11-1);\n\t\t\tString mentions = tweetInstances.get(i).stringValue(3-1);\n\t\t\tString hashtags = tweetInstances.get(i).stringValue(14-1);\n\t\t\tString epClass = tweetInstances.get(i).stringValue(15-1);\n\t\t\tString snsClass = tweetInstances.get(i).stringValue(16-1);\n\t\t\tSystem.out.println(\"Tweet Details:\\t\"+user+\"\\t\"+mentions+\"\\t\"+hashtags+\"\\t\"+printDist(classDist.get(i)));\n\t\t\t//stats.updateStatistics(user, mentions, hashtags, epClass+\",\"+snsClass, classDist.get(i));\n\t\t}\n\t}\n\tpublic int performClassification() {\n\t\tfor (int i = 0; i < unlabled.numInstances(); i++) {\n\t\t\tdouble clsLabel = 0;\n\t\t\t//Double[][] instanceDist = classDist.get(i);\n\t\t\tdouble[] dist = {-1., -1.};\n\t\t\t//int distIndex = 0;\n\t\t\tif(classifierType == MODELTYPE.SENTIMENT || classifierType == MODELTYPE.SENTIMENT_WORD\n\t\t\t\t\t|| classifierType == MODELTYPE.CUSTOM){\n\t\t\t\t//distIndex = 0;\n\t\t\t}\n\t\t\t//System.out.println(unlabled.instance(i).toString(4));\n\t\t\ttry {\n\t\t\t\tdist = cls.distributionForInstance(unlabled.instance(i));\n\t\t\t\t//System.out.println(\"Distributions for \"+filePrefix+\" :\\t\"+dist[0]+\",\"+dist[1]+\",\"+dist[2]);\n\t\t\t\t//instanceDist[distIndex][0] = dist[0];\n\t\t\t\t//instanceDist[distIndex][1] = dist[1];\n\t\t\t\tclsLabel = cls.classifyInstance(unlabled.instance(i));\n\t\t\t\t//System.out.println(\"CLSLABEL: \" + clsLabel);\n\t\t\t} catch (Exception e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t\tSystem.err.println(\"Classification task failed.\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tlabled.instance(i).setClassValue(clsLabel);\n\t\t\toriginal.instance(i).setValue(clsIndex, clsLabel);\n\t\t\tif(showProbability){\n\t\t\t\toriginal.instance(i).setValue(classProbIndex, Double.max(dist[0], dist[1]));\n\t\t\t}\n\t\t\t//classDist.set(i, instanceDist);\n\t\t}\n\t\treturn 0;\n\t}\n\t\n\tpublic String updateModel(String inputFile, ArrayList<Double[]> metrics){\n\t\tString output = \"\";\n\t\tthis.setInstances(inputFile);\n\t\tFilteredClassifier fcls = (FilteredClassifier)this.cls;\n\t\tSGD cls = (SGD) fcls.getClassifier();\n\t\tFilter filter = fcls.getFilter();\n\t\tInstances insAll;\n\t\ttry {\n\t\t\tinsAll = Filter.useFilter(this.unlabled, filter);\n\t\t\tif(insAll.size() > 0){\n\t\t\t\tRandom rand = new Random(10);\n\t\t\t\tint folds = 10 > insAll.size() ? 2: 10;\n\t\t\t\tInstances randData = new Instances(insAll);\n\t\t\t\trandData.randomize(rand);\n\t\t\t\tif (randData.classAttribute().isNominal()){\n\t\t\t randData.stratify(folds);\n\t\t\t\t}\n\t\t\t\tEvaluation eval = new Evaluation(randData);\n\t\t\t\teval.evaluateModel(cls, insAll);\n\t\t\t\tSystem.out.println(\"Initial Evaluation\");\n\t\t\t\tSystem.out.println(eval.toSummaryString());\n\t\t\t\tSystem.out.println(eval.toClassDetailsString());\n\t\t\t\tmetrics.add(new Double[]{eval.fMeasure(0), eval.fMeasure(1), eval.weightedFMeasure()});\n\t\t\t\toutput += \"\\n====\"+\"Initial Evaluation\"+\"====\\n\";\n\t\t\t\toutput += \"\\n\"+eval.toSummaryString();\n\t\t\t\toutput += \"\\n\"+eval.toClassDetailsString();\n\t\t\t\tSystem.out.println(\"Cross Validated Evaluation\");\n\t\t\t\toutput += \"\\n====\"+\"Cross Validated Evaluation\"+\"====\\n\";\n\t\t\t\tfor (int n = 0; n < folds; n++) {\n\t\t\t\t\tInstances train = randData.trainCV(folds, n);\n\t\t\t Instances test = randData.testCV(folds, n);\n\n\t\t for (int i = 0; i < train.numInstances(); i++) {\n\t\t cls.updateClassifier(train.instance(i));\n\t\t }\n\n\t\t\t eval.evaluateModel(cls, test);\n\t\t\t System.out.println(\"Cross Validated Evaluation fold: \" + n);\n\t\t\t\t\toutput += \"\\n====\"+\"Cross Validated Evaluation fold (\"+n+\")====\\n\";\n\t\t\t System.out.println(eval.toSummaryString());\n\t\t\t\t\tSystem.out.println(eval.toClassDetailsString());\n\t\t\t\t\toutput += \"\\n\"+eval.toSummaryString();\n\t\t\t\t\toutput += \"\\n\"+eval.toClassDetailsString();\n\t\t\t\t\tmetrics.add(new Double[]{eval.fMeasure(0), eval.fMeasure(1), eval.weightedFMeasure()});\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < insAll.numInstances(); i++) {\n\t cls.updateClassifier(insAll.instance(i));\n\t }\n\t\t eval.evaluateModel(cls, insAll);\n\t\t System.out.println(\"Final Evaluation\");\n\t\t System.out.println(eval.toSummaryString());\n\t\t\t\tSystem.out.println(eval.toClassDetailsString());\n\t\t\t\toutput += \"\\n====\"+\"Final Evaluation\"+\"====\\n\";\n\t\t\t\toutput += \"\\n\"+eval.toSummaryString();\n\t\t\t\toutput += \"\\n\"+eval.toClassDetailsString();\n\t\t\t\tmetrics.add(new Double[]{eval.fMeasure(0), eval.fMeasure(1), eval.weightedFMeasure()});\n\t\t\t\tfcls.setClassifier(cls);\n\t\t\t\tString modelFilePath = outputDir+\"/\"+Utils.getOutDir(Utils.OutDirIndex.MODELS)+\n\t\t\t\t\t\t\"/updatedClassifier.model\";\n\t\t\t\tweka.core.SerializationHelper.write(modelFilePath, fcls);\n\t\t\t\toutput += \"\\n\" + \"Updated Model saved at: \"+modelFilePath;\n\t\t\t} else {\n\t\t\t\toutput += \"No new instances for training the model.\";\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn output;\n\t}\n\n\tpublic int setClassifier(MODELTYPE classifierType) {\n\t\tString modelFile = \"\";\n\t\tcls = null;\n\t\ttry {\n\t\t\tif (classifierType == MODELTYPE.SENTIMENT) {\n\t\t\t\tmodelFile = SentimentModelFile;\n\t\t\t\tclsIndex = CLASSINDEX-1;\n\t\t\t\t\n\t\t\t\t\tcls = (J48) weka.core.SerializationHelper\n\t\t\t\t\t\t\t.read(modelFile);\n\t\t\t\t\n\t\t\t\t//filePrefix = FILEPREFIX;\n\t\t\t} else if (classifierType == MODELTYPE.SENTIMENT_WORD) {\n\t\t\t\tmodelFile = SentimentModelFile_word;\n\t\t\t\tclsIndex = CLASSINDEX-1;\n\t\t\t\tcls = (FilteredClassifier) weka.core.SerializationHelper\n\t\t\t\t\t\t.read(modelFile);\n\t\t\t\t//filePrefix = FILEPREFIX;\n\t\t\t} else if (classifierType == MODELTYPE.CUSTOM){\n\t\t\t\tmodelFile = getCustomModelFile();\n\t\t\t\t//this.classifierType = MODELTYPE.SENTIMENT_WORD; \n\t\t\t\tclsIndex = CLASSINDEX-1;\n\t\t\t\tcls = (FilteredClassifier) weka.core.SerializationHelper\n\t\t\t\t\t\t.read(modelFile);\n\t\t\t} else {\n\t\t\t\tSystem.out.println(\"Wrong Classifier type\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t\treturn 2;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic int setInstances(String inputFile) {\n\t\t//String[] nominalVals = {\"42:positive,neutral,negative\"};\n\t\tString[] nominalVals = {CLASSINDEX+\":\"+StringUtils.join(classNames, \",\")};\n\t\toriginal = null;\n\t\ttry {\n\t\t\tSystem.out.println(\"[In Prediction] Loading instances. \");\n\t\t\tCSVLoader csvSource = new CSVLoader();\n\t\t\tcsvSource.setSource(new File(inputFile));\n\t\t\tcsvSource.setFieldSeparator(\"\\t\");\n\t\t\tcsvSource.setNominalAttributes(CLASSINDEX+\"\");\n\t\t\tcsvSource.setStringAttributes(stringAttr);\n\t\t\tcsvSource.setNominalLabelSpecs(nominalVals);\n\t\t\toriginal = csvSource.getDataSet();\n\t\t\tunlabled = original;\n\t\t\tclassProbIndex = original.numAttributes()-1;\n\t\t\t//System.out.println(unlabled.toSummaryString());\n\t\t\tRemove r = new Remove();\n\t\t\t//r.setAttributeIndices(\"3-4,6,10-12,14\");\n\t\t\tif(classifierType == MODELTYPE.SENTIMENT || classifierType == MODELTYPE.SENTIMENT_WORD\n\t\t\t\t\t|| classifierType == MODELTYPE.CUSTOM){\n\t\t\t\tif(showProbability){\n\t\t\t\t\t/*\n\t\t\t\t\tAdd afilter;\n\t\t\t\t\tafilter = new Add();\n\t\t\t\t\tafilter.setAttributeName(\"last\");\n\t\t\t\t\tafilter.setAttributeName(\"prediction_prob\");\n\t\t\t\t\tafilter.setInputFormat(original);\n\t\t\t\t\toriginal = Filter.useFilter(original, afilter);\n\t\t\t\t\tclassProbIndex = original.numAttributes()-1;*/\n\t\t\t\t}\n\t\t\t\tif(classifierType == MODELTYPE.SENTIMENT){\n\t\t\t\t\tr.setAttributeIndices(\"3,4,6,8,10-12,14,42,43,45-last\");\n\t\t\t\t\tSystem.out.println(\"Filtering instances for SENTIMENT\");\n\t\t\t\t}\n\t\t\t\telse if(classifierType == MODELTYPE.SENTIMENT_WORD || classifierType == MODELTYPE.CUSTOM){\n\t\t\t\t\tr.setAttributeIndices(removeAttr);\n\t\t\t\t\tSystem.out.println(\"Filtering instances for SENTIMENT WORD\");\n\t\t\t\t}\n\t\t\t}\n\t\t\t//r.setAttributeIndices(\"3-4,6,10-12,14,40-41,43-last\");\n\t\t\tr.setInputFormat(unlabled);\n\t\t\tunlabled = Remove.useFilter(unlabled, r);\n\t\t\t//System.out.println(unlabled.toSummaryString());\n\t\t\tr = new Remove();\n\t\t\t//System.out.println(unlabled.toSummaryString());\n\t\t\t\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t\treturn 1;\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t\treturn 2;\n\t\t} catch (Exception e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t\treturn 3;\n\t\t}\n\t\tint cIdx = unlabled.numAttributes() - 1;\n\t\tunlabled.setClassIndex(cIdx);\n\t\tSystem.out.println(\"Class Attribute is: \"+unlabled.classAttribute()+\" at index: \"+unlabled.classIndex());\n\t\treturn 0;\n\t}\n\n\tpublic int writePredictions(Instances ins, String filePrefix) {\n\t\ttry {\n\t\t\tSystem.out.println(\"Trying to create the following files:\");\n\t\t\tSystem.out.println(outputDir+ \"/\" + filePrefix + \".arff\");\n\t\t\tSystem.out.println(outputDir+ \"/\" + filePrefix + \".tsv\");\n\t\t\tBufferedWriter writer = new BufferedWriter(new FileWriter(outputDir\n\t\t\t\t\t+ \"/\" + filePrefix + \".arff\"));\n\t\t\twriter.write(ins.toString());\n\t\t\twriter.newLine();\n\t\t\twriter.flush();\n\t\t\twriter.close();\n\t\t\tCSVSaver s = new CSVSaver();\n\n\t\t\ts.setFile(new File(outputDir + \"/\" + filePrefix + \".tsv\"));\n\t\t\ts.setInstances(ins);\n\t\t\ts.setFieldSeparator(\"\\t\");\n\t\t\ts.writeBatch();\n\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t}\n\n}",
"public static enum MODELTYPE {\n\tSENTIMENT(\"Meta Model\"),\n\tSENTIMENT_WORD(\"Word Model\"),\n\tCUSTOM(\"Custom...\");\n\tprivate String text;\n\tprivate MODELTYPE(String text) {\n\t\t// TODO Auto-generated constructor stub\n\t\tthis.text = text;\n\t}\n\t@Override\n\tpublic String toString() {\n\t\t// TODO Auto-generated method stub\n\t\treturn this.text;\n\t}\n\t\t\n};",
"public static enum outDirIndex {ORIGINAL, LABELED, UPDATES, MODELS};",
"public class ReadTweetCorpus {\n\n\t/**\n\t * @param args\n\t */\n\t\n\tpublic static enum COL_INDECIES{MESSAGE,AUTHOR,TIME,SENTIMENT,URL,\n\t\tT_FOLLOWERS,T_FOLLOWING,T_REPLY_COUNT,T_RETWEETS,T_TWEETS};\n\t\n\tprivate String[] colNames; // Names of columns mapping to COL_INDECIES\n\tprivate String inFile;\n\tprivate String outFile;\n\tprivate static String[] POS_KEYSET = {\"D\", \"#\", \"E\", \"G\", \"!\", \"&\", \"@\", \"A\", \"$\",\n\t \"L\", \"M\", \"N\", \"O\", \",\", \"U\", \"T\", \"V\", \"P\", \n\t \"S\", \"R\", \"~\", \"^\", \"Y\", \"X\", \"Z\"};\n\tprivate HashMap<String, String> sentimentLexicon;\n\tprivate HashSet<String> queryTerms;\n\t\n\tpublic ReadTweetCorpus(){\n\t\tthis.colNames = new String[3];\n\t}\n\t\n\tpublic ReadTweetCorpus(String inFile,String outFile, String[] colNames){\n\t\tthis();\n\t\tthis.inFile = inFile;\n\t\tthis.outFile = outFile;\n\t\tthis.colNames = colNames;\n\t}\n\t\n\tpublic ReadTweetCorpus(String inFile,String outFile, String[] colNames, String lexiconPath, String queryTermsPath){\n\t\tthis(inFile,outFile,colNames);\n\t\tupdateSentimentLexicon(lexiconPath);\n\t\tupdateQueryTermsSet(queryTermsPath);\n\t}\n\t\n\tprivate void updateSentimentLexicon(String lexiconPath){\n\t\tsentimentLexicon = new HashMap<String, String>();\n\t\tCSVReader cr = null;\n\t\tString[] csvLine;\n\t\tString key, value;\n\t\ttry {\n\t\t\tcr = new CSVReader(new FileReader(lexiconPath), '\\t');\n\t\t\twhile((csvLine=cr.readNext())!=null){\n\t\t\t\tkey = csvLine[0].toLowerCase();\n\t\t\t\tvalue = csvLine[1].toLowerCase();\n\t\t\t\tif(!sentimentLexicon.containsKey(key)){\n\t\t\t\t\t// Only first instance of semtiment is considered.\n\t\t\t\t\tsentimentLexicon.put(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcr.close();\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\tprivate void updateQueryTermsSet(String queryListPath){\n\t\tqueryTerms = new HashSet<String>();\n\t\tCSVReader cr = null;\n\t\tString[] csvLine;\n\t\ttry {\n\t\t\tcr = new CSVReader(new FileReader(queryListPath), '\\t');\n\t\t\twhile((csvLine=cr.readNext())!=null){\n\t\t\t\tqueryTerms.add(csvLine[0].toLowerCase());\n\t\t\t}\n\t\t\tcr.close();\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\tpublic int writeData(){\n\t\tCSVWriter cw = null;\n\t\tCSVReader cr = null;\n\t\tint lines_read = 0;\n\t\tString[] tweetList = null;\n\t try {\n\t \tSystem.out.println(\"[In ReadTweetCorpus Task] reading Data: \"+this.inFile);\n\t \tSystem.out.println(\"[In ReadTweetCorpus Task] writing Data: \"+this.outFile);\n\t \tcr = new CSVReader(new FileReader(this.inFile), '\\t');\n\t \tint[] ids = this.getColIds(cr.readNext());\n\t \tlines_read += 1;\n\t\t\tcw = new CSVWriter(new FileWriter(this.outFile), '\\t', '\\\"','\\\\');\n\t\t\tString header = \"c_emo\\tc_hash\\tm_mention\\turl\\tc_url\\ttweet_text\\tc_mention\"\n\t\t\t\t\t+ \"\\tparsed_text\\tlength\\tm_emo\\tuser\\tpublished_date\\tc_quote\"\n\t\t\t\t\t+ \"\\tm_hash\";\n\t\t\tPOSFeatures.init();\t\t\n\t\t\tfor(String key:POS_KEYSET){\n\t\t\t\theader += \"\\t\"+key;\n\t\t\t}\n\t\t\tif(sentimentLexicon.size() > 0 || queryTerms.size() > 0){\n\t\t\t\tDictionaryFeatures.init(sentimentLexicon, queryTerms);\n\t\t\t\theader+=\"\\t\"+StringUtils.join(DictionaryFeatures.getKeys(),\"\\t\");\n\t\t\t}\n\t\t\t/*\n\t\t\t * Twitter Followers\tTwitter Following\tTwitter Reply Count\tTwitter Reply to\tTwitter Retweet of\tTwitter Retweets\tTwitter Tweets\n\t\t\t * */\n\t\t\theader += \"\\te/p/i\\ts/ns/na\\tsentiment\";\n\t\t\theader += \"\\tt_url\\tTwitter Followers\\tTwitter Following\\tTwitter Reply Count\\tTwitter Retweets\\tTwitter Tweets\\tprediction_prob\"; \n\t\t\t//header += \"\\tt_url\\tt_followers\\tt_following\\tt_replies\\tt_retweets\\tt_tweets\";\n\t\t\tcw.writeNext(header.split(\"\\t\"));\n\t\t\tSystem.out.println(\"[In ReadTweetCorpus Task] starting tweet parsing.\");\n ParseTweet pt;\n while ((tweetList = cr.readNext())!= null) {\n \tlines_read += 1;\n //System.out.println(\"Length of columns: \"+tweetList.length);\n //System.out.println(\"Length of ids: \"+ids.length);\n \tString author = \"\", pub_time = \"\";\n \tif(ids[COL_INDECIES.AUTHOR.ordinal()] > -1){\n \t\tauthor = tweetList[ids[COL_INDECIES.AUTHOR.ordinal()]];\n \t}\n \tif(ids[COL_INDECIES.TIME.ordinal()] > -1){\n \t\tpub_time = tweetList[ids[COL_INDECIES.TIME.ordinal()]];\n \t}\n pt = new ParseTweet(tweetList[ids[COL_INDECIES.MESSAGE.ordinal()]],\n \t\tauthor,pub_time);\n //stats.updateStatistics(pt);\n //pt.showFeatures();\n String sentiment = \"?\";\n String URL = \"\";\n String t_followers = \"0\";\n String t_following = \"0\";\n String rt_count = \"0\";\n String reply_count = \"0\";\n String status_count = \"0\";\n if(ids[COL_INDECIES.SENTIMENT.ordinal()] != -1){\n \tsentiment = tweetList[ids[COL_INDECIES.SENTIMENT.ordinal()]];\n }\n if(ids[COL_INDECIES.URL.ordinal()] != -1){\n \tURL = tweetList[ids[COL_INDECIES.URL.ordinal()]];\n }\n if(ids[COL_INDECIES.T_FOLLOWERS.ordinal()] != -1){\n \tt_followers = tweetList[ids[COL_INDECIES.T_FOLLOWERS.ordinal()]];\n }\n if(ids[COL_INDECIES.T_FOLLOWING.ordinal()] != -1){\n \tt_following = tweetList[ids[COL_INDECIES.T_FOLLOWING.ordinal()]];\n }\n if(ids[COL_INDECIES.T_REPLY_COUNT.ordinal()] != -1){\n \treply_count = tweetList[ids[COL_INDECIES.T_REPLY_COUNT.ordinal()]];\n }\n if(ids[COL_INDECIES.T_RETWEETS.ordinal()] != -1){\n \trt_count = tweetList[ids[COL_INDECIES.T_RETWEETS.ordinal()]];\n }\n if(ids[COL_INDECIES.T_TWEETS.ordinal()] != -1){\n \tstatus_count = tweetList[ids[COL_INDECIES.T_TWEETS.ordinal()]];\n }\n cw.writeNext(this.getRowAsList(pt,sentiment,\n \t\tnew String[]{URL,t_followers,t_following,reply_count,rt_count,status_count}));\n \n }\n cr.close();\n cw.close();\n //stats.printStats(new PrintStream(new File(fileName+\".stats.tsv\")));\n\t\t} catch (Exception e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t\tSystem.err.println(\"Error occured while reading line: \"+lines_read);\n\t\t\tSystem.err.println(Arrays.toString(tweetList));\n\t\t\treturn 1;\n\t\t}\n\t return 0;\n\t}\n\t\n\tprivate int[] getColIds(String[] header){\n\t\tint[] ids = new int[this.colNames.length];\n\t\tfor(int i = 0; i < this.colNames.length; i++){\n\t\t\tint index = -1;\n\t\t\tif(this.colNames[i] != null && !this.colNames[i].equals(\"<Empty>\")){\n\t\t\t\tindex = Arrays.asList(header).indexOf(this.colNames[i]);\n\t\t\t\tif( index < 0){\n\t\t\t\t\tSystem.err.println(\"Didn't find column in search: \"+this.colNames[i]);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tSystem.err.println(\"Index of \"+this.colNames[i]+\" at: \"+index);\n\t\t\t}\n\t\t\tids[i] = index;\n\t\t}\n\t\treturn ids;\n\t}\n\t\n\t\n\tpublic String getRow(ParseTweet t){\n\t\t/*\n\t\t * Each row of format:\n\t\t * c_emo\tc_hash\tm_mention\turl\tc_url\ttweet_text\tc_mention\tparsed_text\tlength\tm_emo\tuser\tpublished_date\tc_quote\tm_hash\te/p/i\ts/ns/na\n\t\t */\n\t\tString row = \"\";\n\t\t\n\t\trow += t.c_emo+\"\\t\"+t.c_hash+\"\\t\"+t.m_mention\n\t\t\t\t+\"\\t\"+t.url+\"\\t\"+t.c_url+\"\\t\"+StringEscapeUtils.unescapeCsv(t.tweet_text)\n\t\t\t\t+\"\\t\"+t.c_mention+\"\\t\"+t.parsed_text+\"\\t\"+t.length\n\t\t\t\t+\"\\t\"+t.m_emo+\"\\t\"+t.user+\"\\t\"+t.published_date\n\t\t\t\t+\"\\t\"+t.c_quote+\"\\t\"+t.m_hash;\n\t\t\n\t\tfor(String key:POS_KEYSET){\n\t\t\trow += \"\\t\"+t.pf.posCounts.get(key);\n\t\t}\n\t\t\n\t\trow += \"\\t?\\t?\";\n\n\t\treturn row;\n\t}\n\t\n\tpublic String[] getRowAsList(ParseTweet t){\n\t\t/*\n\t\t * Each row of format:\n\t\t * c_emo\tc_hash\tm_mention\turl\tc_url\ttweet_text\tc_mention\tparsed_text\tlength\tm_emo\tuser\tpublished_date\tc_quote\tm_hash\te/p/i\ts/ns/na\n\t\t */\n\t\tArrayList<String> row = new ArrayList<String>();\n\t\t\n\t\tString[] row1 = {\n\t\t\t\tInteger.toString(t.c_emo),Integer.toString(t.c_hash),StringUtils.join(t.m_mention,\",\")\n\t\t\t\t,t.url,Integer.toString(t.c_url),t.tweet_text\n\t\t\t\t,Integer.toString(t.c_mention),t.parsed_text,Integer.toString(t.length)\n\t\t\t\t,StringUtils.join(t.m_emo, \",\"),t.user,t.published_date\n\t\t\t\t,Integer.toString(t.c_quote),StringUtils.join(t.m_hash, \",\")\n\t\t\t\t\n\t\t\t};\n\t\t\n\t\trow.addAll(Arrays.asList(row1));\n\t\tfor(String key:t.pf.posCounts.keySet()){\n\t\t\trow.add(t.pf.posCounts.get(key).toString());\n\t\t}\n\t\tfor(String key: DictionaryFeatures.getSentimentLabels()){\n\t\t\trow.add(t.to.getLexicalScores().get(key).toString());\n\t\t}\n\t\trow.addAll(Arrays.asList(new String[]{\"?\",\"?\"}));\n\n\t\treturn row.toArray(new String[row.size()]);\n\t}\n\t\n\tpublic String[] getRowAsList(ParseTweet t, String sentiment, String[] extras){\n\t\t/*\n\t\t * Each row of format:\n\t\t * c_emo\tc_hash\tm_mention\turl\tc_url\ttweet_text\tc_mention\tparsed_text\tlength\tm_emo\tuser\tpublished_date\tc_quote\tm_hash\te/p/i\ts/ns/na\n\t\t */\n\t\tString[] row = this.getRowAsList(t);\n\t\tint arr_size = row.length+1+extras.length+1; // Last one added for adding probability\n\t\tString[] newRow = new String[arr_size];\n\t\tfor (int i = 0; i < row.length; i++) {\n\t\t\tnewRow[i] = row[i];\n\t\t}\n\t\tnewRow[row.length] = sentiment;\n\t\tfor (int i = 0; i < extras.length; i++) {\n\t\t\tnewRow[row.length+1+i] = extras[i];\n\t\t}\n\t\tnewRow[row.length+1+extras.length] = \"-1.0\"; // Default probability\n\n\t\treturn newRow;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\t// TODO Auto-generated method stub\n\t\t/**\n\t\tReadTweetCorpus rtc = new ReadTweetCorpus(\"input/SupplementaryData.txt\",\"output/Supplementary_POS.tsv\",\n\t\t\t\tnew String[]{\"tweet_text\",\"user_screenname\",\"created_date\",null,\"tweet_url\",\n\t\t\t\t\"user_followers\",\"user_following\",null,\"retweet_count\",\"statuses_count\"});\n\t\t**/\n\t\t\n\t\t/**\n\t\t * \"c_emo\"\t\"c_hash\"\t\"m_mention\"\t\"url\"\t\"c_url\"\t\"tweet_text\"\t\"c_mention\"\t\"parsed_text\"\t\"length\"\t\"m_emo\"\t\"user\"\t\"published_date\"\t\"c_quote\"\t\"m_hash\"\t\"e/p/i\"\t\"s/ns/na\"\t\"sentiment\"\n\n\t\t */\n\t\t/*ReadTweetCorpus rtc = new ReadTweetCorpus(\"temp/All.tsv\",\"temp/All_POS.tsv\",\n\t\t\t\tnew String[]{\"tweet_text\",\"user\",\"published_date\",\"sentiment\",\"url\",\n\t\t\t\tnull,null,null,null,null});\n\t\trtc.writeData();*/\n\t\t/*ReadTweetCorpus rtc = new ReadTweetCorpus(\"E:\\\\Box\\\\Box Sync\\\\Research\\\\Jana\\\\InBev\\\\Sentiment\\\\data\\\\Full\\\\Sampled_3Way_Experiment\\\\input\\\\Deduplicated.txt\",\n\t\t\t\t\"E:\\\\Box\\\\Box Sync\\\\Research\\\\Jana\\\\InBev\\\\Sentiment\\\\data\\\\Full\\\\Sampled_3Way_Experiment\\\\output\\\\Deduplicated_LEX_QUE_POS.txt\",\n\t\t\t\tnew String[]{\"Snippet\",\"Author\",\"Date\",\"Sentiment\",\"Url\",\n\t\t\t\t\"Twitter Followers\",\"Twitter Following\",\"Twitter Reply Count\",\"Twitter Retweets\",\"Twitter Tweets\"},\n\t\t\"E:\\\\Box\\\\Box Sync\\\\Research\\\\Jana\\\\InBev\\\\Sentiment\\\\data\\\\Full\\\\All_data+superbowl\\\\output\\\\FinalLexicon\\\\FILTERED_LEXICON.txt\",\n\t\t\"E:\\\\Box\\\\Box Sync\\\\Research\\\\Jana\\\\InBev\\\\Sentiment\\\\data\\\\Full\\\\All_data+superbowl\\\\output\\\\QueryTerms.txt\");\n\t\trtc.writeData();*/\n\t\t\n\t\tReadTweetCorpus rtc = new ReadTweetCorpus(\"E:\\\\Box\\\\Box Sync\\\\Research\\\\Jana\\\\InBev\\\\Sentiment\\\\data\\\\Full\\\\All_data+superbowl\\\\input\\\\Deduplicated.txt\",\n\t\t\t\t\"E:\\\\Box\\\\Box Sync\\\\Research\\\\Jana\\\\InBev\\\\Sentiment\\\\data\\\\Full\\\\All_data+superbowl\\\\output\\\\NOPOS_LATEST\\\\Deduplicated_LEX_QUE.txt\",\n\t\t\t\tnew String[]{\"Snippet\",\"Author\",\"Date\",\"Sentiment\",\"Url\",\n\t\t\t\t\"Twitter Followers\",\"Twitter Following\",\"Twitter Reply Count\",\"Twitter Retweets\",\"Twitter Tweets\"},\n\t\t\"E:\\\\Box\\\\Box Sync\\\\Research\\\\Jana\\\\InBev\\\\Sentiment\\\\data\\\\Full\\\\All_data+superbowl\\\\output\\\\FinalLexicon\\\\FILTERED_LEXICON.txt\",\n\t\t\"E:\\\\Box\\\\Box Sync\\\\Research\\\\Jana\\\\InBev\\\\Sentiment\\\\data\\\\Full\\\\All_data+superbowl\\\\output\\\\QueryTerms.txt\");\n\t\trtc.writeData();\n\t\t\n\n\t}\n\n}",
"public static enum COL_INDECIES{MESSAGE,AUTHOR,TIME,SENTIMENT,URL,\n\tT_FOLLOWERS,T_FOLLOWING,T_REPLY_COUNT,T_RETWEETS,T_TWEETS};",
"public class Utils {\n\tpublic static enum OutDirIndex {FEATURES, ORIGINAL, LABELED, UPDATES, MODELS};\n\tpublic static final String[] outDirs = {\"Features\", \"original\", \"labled\", \"updates\", \"models\"};\n\t\n\tpublic static String getOutDir(OutDirIndex i){\n\t\treturn outDirs[i.ordinal()];\n\t}\n\tpublic Utils() {\n\t\t// TODO Auto-generated constructor stub\n\t}\n\t\n\tpublic static void createFolder(String dirName){\n\t\tFile theDir = new File(dirName);\n\n\t\t// if the directory does not exist, create it\n\t\tif (!theDir.exists()) {\n\t\t\tSystem.out.println(\"creating directory: \" + dirName);\n\t\t\tboolean result = false;\n\n\t\t\ttry {\n\t\t\t\ttheDir.mkdir();\n\t\t\t\tresult = true;\n\t\t\t} catch (SecurityException se) {\n\t\t\t\t// handle it\n\t\t\t\tSystem.err.println(\"Security Exception while creating dir\");\n\t\t\t\tSystem.err.println(se);\n\t\t\t}\n\t\t\tif (result) {\n\t\t\t\tSystem.out.println(\"DIR created\");\n\t\t\t}\n\t\t}\n\t}\n\n}",
"public class GUI extends Application {\n\t\n\tpublic static final String configFile = \"./data/config.properties\";\n\tpublic static final String configDefaultsFile = \"./data/config.defaults.properties\";\n\tpublic static final String licenseFile = \"./data/license.txt\";\n\tpublic GUIController controller;\n @Override\n public void start(Stage stage) throws Exception {\n \tstage.setTitle(\"SAIL (Sentiment Analysis and Incremental Learning)\");\n \tfinal FXMLLoader loader = new FXMLLoader(\n \t\t getClass().getResource(\n \t\t \"GUI.fxml\"\n \t\t )\n \t\t );\n \t\n Parent root = (Parent) loader.load();\n controller = loader.getController();\n controller.setStage(stage);\n Scene scene = new Scene(root);\n //\n /*scene.widthProperty().addListener(new ChangeListener<Number>() {\n @Override public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneWidth, Number newSceneWidth) {\n System.out.println(\"Width: \" + newSceneWidth);\n }\n });\n scene.heightProperty().addListener(new ChangeListener<Number>() {\n @Override public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneHeight, Number newSceneHeight) {\n System.out.println(\"Height: \" + newSceneHeight);\n }\n });*/\n //\n //Scene scene = new Scene(root, 790, 600);\n stage.setResizable(true);\n stage.setScene(scene);\n stage.show();\n \n \n }\n \n @Override\n public void stop() throws Exception {\n \t// TODO Auto-generated method stub\n \tcontroller.exit();\n \tsuper.stop();\n }\n\n /**\n * @param args the command line arguments\n */\n public static void main(String[] args) {\n \ttry {\n\t\t\tSystem.setOut(new PrintStream(\"log.stdout.txt\"));\n\t\t\tSystem.setErr(new PrintStream(\"log.stderr.txt\"));\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n \tSystem.out.println(\"This is the first output to the log.stdout.txt file\");\n \tSystem.err.println(\"This is the first output to the log.stderr.txt file\");\n launch(args);\n }\n \n}",
"public class Tweet {\t\n \n public static enum LABEL { positive, negative;\n public static LABEL getEnum(String s){\n if(positive.name().equals(s)){\n return positive;\n }else if(negative.name().equals(s)){\n return negative;\n }\n throw new IllegalArgumentException(\"No Enum specified for this string\");\n \t}\n }\n public static int SentimentIndex = 44;\n private StringProperty tweet;\n private StringProperty feature;\n private DoubleProperty probability;\n private int index;\n private String[] tweetList;\n private String originalLabel;\n private boolean changed;\n \n private double probability_val;\n \n// private StringProperty label;\n private StringProperty label;\n private HashMap<String, Integer> features = new HashMap<>();\n private ComboBoxTableCell priorityComboBox = new ComboBoxTableCell();\n \n public Tweet(String tweet, String label, int i, String[] tweetList) {\n this.tweet = new SimpleStringProperty(tweet);\n this.label = new SimpleStringProperty(label);\n this.feature = new SimpleStringProperty(getFeature());\n this.index = i;\n this.tweetList = tweetList;\n this.originalLabel = label;\n this.changed = false;\n this.probability_val = -1.0;\n }\n \n public Tweet(String tweet, String label, int i, String[] tweetList, double probability_val) {\n \tthis(tweet, label, i, tweetList);\n \tthis.probability_val = probability_val;\n \tthis.probability = new SimpleDoubleProperty(this.probability_val);\n }\n \n public String getFeature(){\n String t = \"\";\n for (String s : features.keySet()){\n t += s + \": \" + features.get(s) + \"\\n\";\n }\n return t;\n }\n \n public int getIndex(){\n \treturn this.index;\n }\n \n public String getLabel(){\n \treturn this.label.get();\n }\n \n public String[] getMeta(){\n \treturn this.tweetList;\n }\n \n public Double getProbability(){\n \treturn this.probability.get();\n }\n \n \n public String getTweet(){\n return this.tweet.get();\n }\n \n public boolean isChanged(){\n \treturn this.changed;\n }\n \n public void set(String newTweet){\n this.tweet = new SimpleStringProperty(newTweet);\n }\n \n public void setFeature(String key, Integer val){\n \tfeatures.put(key, val);\n }\n \n public void setLabel(LABEL lbl){\n \tthis.label.set(lbl.toString());\n \tthis.setSentiment(lbl.toString());\n }\n// \n// public void setLabel(String string){\n// \tthis.label.set(string);\n// }\n \n public void setSentiment(String sentiment){\n \tthis.tweetList[this.tweetList.length -8 ] = sentiment;\n \tif(!sentiment.equals(originalLabel)){\n \t\tthis.changed = true;\n \t\tSystem.out.println(\"Updated Sentiment to: \"+sentiment);\n \t} else {\n \t\tthis.changed = false;\n \t}\n \t\n\t}\n \n public String toString(){\n \treturn \"orginal index\" + this.getIndex() + \" \" + this.label.get();\n }\n \n}"
] | import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javafx.collections.ObservableList;
import org.apache.commons.io.FilenameUtils;
import sentinets.Prediction;
import sentinets.Prediction.MODELTYPE;
import sentinets.Prediction.outDirIndex;
import sentinets.ReadTweetCorpus;
import sentinets.ReadTweetCorpus.COL_INDECIES;
import sentinets.Utils;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
import com.sun.net.httpserver.HttpServer;
import frontend.GUI;
import frontend.Tweet; | }
if(defaultProperties.getRemoveList() != null){
this.setRemoveList(defaultProperties.getRemoveList());
}
Prediction.setModelParams(this.class_index, this.string_list, this.remove_list, this.customModelFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private List<String[]> originalData = new ArrayList<>();
public void addTweets(String fileName, ObservableList<Tweet> personData){
CSVReader cr;
try {
cr = new CSVReader(new FileReader(fileName), '\t');
headerRow = cr.readNext();
HashMap<String, Integer> headers = new HashMap<String, Integer>();
for(int i = 0; i < headerRow.length; i++){
headers.put(headerRow[i], i);
System.err.println("["+i+"]="+headerRow[i]);
}
HashMap<String, Integer> f_list = new HashMap<String, Integer>();
f_list.put("c_emo", headers.get("c_emo"));
f_list.put("c_hash", headers.get("c_hash"));
f_list.put("c_url", headers.get("c_url"));
f_list.put("c_mention", headers.get("c_mention"));
f_list.put("length", headers.get("length"));
int i = 0;
String[] tweetList;
while ((tweetList = cr.readNext())!= null){
Tweet t = new Tweet(tweetList[headers.get("tweet_text")], tweetList[headers.get("sentiment")],
i, tweetList, Double.parseDouble(tweetList[headers.get("prediction_prob")]));
originalData.add(tweetList);
for(String key: f_list.keySet()){
t.setFeature(key, Integer.parseInt(tweetList[f_list.get(key)]));
}
personData.add(t);
i++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void saveChanges(String outFolder, ObservableList<Tweet> personData, boolean predicted) {
CSVWriter writer;
try {
String updateFile = outFolder +"/"+Utils.getOutDir(Utils.OutDirIndex.UPDATES)+"/updates.txt";
System.out.println("Path: " + updateFile);
writer = new CSVWriter(new FileWriter(updateFile), '\t', '\"','\\');
writer.writeNext(headerRow);
for (Tweet t : personData) {
if(t.isChanged() && !predicted){
writer.writeNext(t.getMeta());
} else if (predicted){
writer.writeNext(t.getMeta());
}
}
writer.close();
} catch (Exception e){
e.printStackTrace();
}
}
public String updateModel(ArrayList<Double[]> metrics){
String updateFile = this.outputDir+"/"+Utils.getOutDir(Utils.OutDirIndex.UPDATES)+"/updates.txt";
String output = "";
output = obj.updateModel(updateFile, metrics);
return output;
}
public void listFilesForFolder(final File folder) {
files.clear();
for (final File fileEntry : folder.listFiles()) {
if(FilenameUtils.getExtension(fileEntry.getAbsolutePath()).equals("properties")){
System.out.println("Updating properties file.");
setConfigFile(fileEntry.getAbsolutePath());
customProps = true;
}
else if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
files.add(fileEntry.getPath());
System.out.println(fileEntry.getName());
}
}
}
public List<String> readHeader() throws Exception{
List<String> combos = new ArrayList<String>();
CSVReader cr = new CSVReader(new FileReader(files.get(0)), '\t');
String[] headers = cr.readNext();
for (String s : headers){
combos.add(s);
}
String[] carr = combos.toArray(new String[combos.size()]);
Arrays.sort(carr);
combos = new ArrayList<String>();
combos.addAll(Arrays.asList(carr));
combos.add("<Empty>");
cr.close();
return combos;
}
/**
*
* TODO - Move Features folder name to Utils along with all the other list of output folders and use it using the enum index.
* @param comboBoxes
* @param mt
* @param visualize
* @param predicted
*/ | public int processAfterLoadFile(ArrayList<String> comboBoxes, MODELTYPE mt, boolean visualize, boolean predicted){ | 1 |
Zerokyuuni/Ex-Aliquo | exaliquo/bridges/crossmod/ExtraTic_Mekanism.java | [
"public static Block getBlock(Info info)\n{\n\tBlock block = findBlock(info.mod, info.sname);\n\treturn (block != null) ? block : debugBlockInfo(info);\n}",
"public static int getIDs(Info info)\n{\n\tif (info.type == \"block\")\n\t{\n\t\tBlock id = findBlock(info.mod, info.sname);\n\t\treturn (id != null) ? id.blockID : debugIDInfo(info);\n\t}\n\telse\n\t{\n\t\tItem id = findItem(info.mod, info.sname);\n\t\treturn (id != null) ? id.itemID : debugIDInfo(info);\n\t}\n}",
"public static Item getItem(Info info)\n{\n\tItem item = findItem(info.mod, info.sname);\n\treturn (item != null) ? item : debugItemInfo(info);\n}",
"public class MoltenMetals\n{\n\tpublic static final int ingotCost = ModsLoaded.isTConLoaded ? TConstruct.ingotLiquidValue : 144;\n\tpublic static final int ingotCostSmeltery = ingotCost * (Configurations.isOre?2:1);\n\tpublic static final int dustCostGeneral = ingotCost / (Configurations.dustValue?4:6);\n\tpublic static final int dustCostSmeltery = dustCostGeneral * (Configurations.isOre?2:1);\n}",
"public class Registries\n{\n\tpublic static ExATab exatab;\n\tpublic static ExAOreTab oretab;\n\t\n\tprivate static String[] hammershape = { \" i \", \" si\", \"s \" };\n\tprivate static String[] crookshape = { \"ii\", \" i\", \" i\" };\n\tpublic static String[] oreType = { \"Gravel\",\"Sand\",\"Dust\" };\n\tprivate static String[] oreshape = { \"ii\", \"ii\" };\n\tpublic static Item hammerThaum;\n\tpublic static Item hammerInvar;\n\tpublic static Item hammerCopper;\n\tpublic static Item hammerTin;\n\tpublic static Item hammerSilver;\n\tpublic static Item hammerLead;\n\tpublic static Item hammerPlatinum;\n\tpublic static Item hammerNickel;\n\tpublic static Item hammerAluminum;\n\tpublic static Item crookReed;\n\tpublic static Item crookGold;\n\tpublic static Item crookHay;\n\tpublic static Item dragonEgg;\n\t\n\tpublic static Block blockEndEye;\n\tpublic static Block blockEndCake;\n\t\n\tpublic static Block cobaltOreBlock;\n\tpublic static Block arditeOreBlock;\n\tpublic static Block adamantineOreBlock;\n\tpublic static Block alduoriteOreBlock;\n\tpublic static Block astralsilverOreBlock;\n\tpublic static Block atlarusOreBlock;\n\tpublic static Block carmotOreBlock;\n\tpublic static Block ceruclaseOreBlock;\n\tpublic static Block deepironOreBlock;\n\tpublic static Block eximiteOreBlock;\n\tpublic static Block ignatiusOreBlock;\n\tpublic static Block infuscoliumOreBlock;\n\tpublic static Block kalendriteOreBlock;\n\tpublic static Block lemuriteOreBlock;\n\tpublic static Block manganeseOreBlock;\n\tpublic static Block meutoiteOreBlock;\n\tpublic static Block midasiumOreBlock;\n\tpublic static Block mithrilOreBlock;\n\tpublic static Block orichalcumOreBlock;\n\tpublic static Block oureclaseOreBlock;\n\tpublic static Block prometheumOreBlock;\n\tpublic static Block rubraciumOreBlock;\n\tpublic static Block sanguiniteOreBlock;\n\tpublic static Block shadowironOreBlock;\n\tpublic static Block vulcaniteOreBlock;\n\tpublic static Block vyroxeresOreBlock;\n\tpublic static Block zincOreBlock;\n\t\n\tpublic static Item cobaltOreItem;\n\tpublic static Item arditeOreItem;\n\tpublic static Item adamantineOreItem;\n\tpublic static Item alduoriteOreItem;\n\tpublic static Item astralsilverOreItem;\n\tpublic static Item atlarusOreItem;\n\tpublic static Item carmotOreItem;\n\tpublic static Item ceruclaseOreItem;\n\tpublic static Item deepironOreItem;\n\tpublic static Item eximiteOreItem;\n\tpublic static Item ignatiusOreItem;\n\tpublic static Item infuscoliumOreItem;\n\tpublic static Item kalendriteOreItem;\n\tpublic static Item lemuriteOreItem;\n\tpublic static Item manganeseOreItem;\n\tpublic static Item meutoiteOreItem;\n\tpublic static Item midasiumOreItem;\n\tpublic static Item mithrilOreItem;\n\tpublic static Item orichalcumOreItem;\n\tpublic static Item oureclaseOreItem;\n\tpublic static Item prometheumOreItem;\n\tpublic static Item rubraciumOreItem;\n\tpublic static Item sanguiniteOreItem;\n\tpublic static Item shadowironOreItem;\n\tpublic static Item vulcaniteOreItem;\n\tpublic static Item vyroxeresOreItem;\n\tpublic static Item zincOreItem;\n\t\n\tpublic static void registerItems()\n\t{\n\t\tif (ModsLoaded.isThaumcraftLoaded)\n\t\t{\n\t\t\thammerThaum = new ThaumiumHammer(Configurations.thaumHammer).setUnlocalizedName(\"ExAliquo.ThaumHammer\").registerItem().setCreativeTab(exatab);\n\t\t}\n\t\thammerInvar = new AliquoHammer(Configurations.invarHammer, \"invar\").registerItem();\n\t\thammerCopper = new AliquoHammer(Configurations.copperHammer, \"copper\").registerItem();\n\t\thammerTin = new AliquoHammer(Configurations.tinHammer, \"tin\").registerItem();\n\t\thammerSilver = new AliquoHammer(Configurations.silverHammer, \"silver\").registerItem();\n\t\thammerLead = new AliquoHammer(Configurations.leadHammer, \"lead\").registerItem();\n\t\thammerPlatinum = new AliquoHammer(Configurations.platinumHammer, \"platinum\").registerItem();\n\t\thammerNickel = new AliquoHammer(Configurations.nickelHammer, \"nickel\").registerItem();\n\t\thammerAluminum = new AliquoHammer(Configurations.aluminumHammer, \"aluminum\").registerItem();\n\t\t\n\t\tcrookReed = new ReedCrook(Configurations.reedCrook).setUnlocalizedName(\"ExAliquo.ReedCrook\").setCreativeTab(exatab);\n\t\tGameRegistry.registerItem(crookReed, \"ExAliquo.ReedCrook\");\n\t\tcrookGold = new GoldCrook(Configurations.goldCrook).setUnlocalizedName(\"ExAliquo.GoldCrook\").setCreativeTab(exatab);\n\t\tGameRegistry.registerItem(crookGold, \"ExAliquo.GoldCrook\");\n\t\tcrookHay = new HayCrook(Configurations.hayCrook).setUnlocalizedName(\"ExAliquo.HayCrook\").setCreativeTab(exatab);\n\t\tGameRegistry.registerItem(crookHay, \"ExAliquo.HayCrook\");\n\t\tdragonEgg = new DragonEgg(Configurations.dragonEgg).setUnlocalizedName(\"ExAliquo.DragonEgg\").setCreativeTab(exatab);\n\t\tGameRegistry.registerItem(dragonEgg, \"ExAliquo.DragonEgg\");\n\t\t\n\t\tregisterOreItems();\n\t}\n\t\n\tpublic static void registerBlocks()\n\t{\n\t\tblockEndEye = new BlockEndEye(Configurations.blockEndEye).setUnlocalizedName(\"EndEye\").setCreativeTab(exatab);\n\t\tGameRegistry.registerBlock(blockEndEye, \"ExAliquo.EndEye\");\n\t\tblockEndCake = new BlockEndCake(Configurations.blockEndCake).setUnlocalizedName(\"EndCake\").setCreativeTab(exatab);\n\t\tGameRegistry.registerBlock(blockEndCake, \"ExAliquo.EndCake\");\n\t\t\n\t\tOreDictionary.registerOre(\"blockEnder\", blockEndEye);\n\t\t\n\t\tregisterOres();\n\t}\n\t\n\tstatic void registerOres()\n\t{\n\t\tcobaltOreBlock = new AliquoOre(Configurations.cobaltOreBlock).setUnlocalizedName(\"Cobalt\");\n\t\tGameRegistry.registerBlock(cobaltOreBlock, ItemBlockOre.class, \"ExAliquo.CobaltOreBlock\");\n\t\tarditeOreBlock = new AliquoOre(Configurations.arditeOreBlock).setUnlocalizedName(\"Ardite\");\n\t\tGameRegistry.registerBlock(arditeOreBlock, ItemBlockOre.class, \"ExAliquo.ArditeOreBlock\");\n\t\t\n\t\tadamantineOreBlock = new AliquoOre(Configurations.adamantineOreBlock).setUnlocalizedName(\"Adamantine\");\n\t\tGameRegistry.registerBlock(adamantineOreBlock, ItemBlockOre.class, \"ExAliquo.AdamantineOreBlock\");\n\t\talduoriteOreBlock = new AliquoOre(Configurations.alduoriteOreBlock).setUnlocalizedName(\"Alduorite\");\n\t\tGameRegistry.registerBlock(alduoriteOreBlock, ItemBlockOre.class, \"ExAliquo.AlduoriteOreBlock\");\n\t\tastralsilverOreBlock = new AliquoOre(Configurations.astralsilverOreBlock).setUnlocalizedName(\"AstralSilver\");\n\t\tGameRegistry.registerBlock(astralsilverOreBlock, ItemBlockOre.class, \"ExAliquo.AstralSilverOreBlock\");\n\t\tatlarusOreBlock = new AliquoOre(Configurations.atlarusOreBlock).setUnlocalizedName(\"Atlarus\");\n\t\tGameRegistry.registerBlock(atlarusOreBlock, ItemBlockOre.class, \"ExAliquo.AtlarusOreBlock\");\n\t\tcarmotOreBlock = new AliquoOre(Configurations.carmotOreBlock).setUnlocalizedName(\"Carmot\");\n\t\tGameRegistry.registerBlock(carmotOreBlock, ItemBlockOre.class, \"ExAliquo.CarmotOreBlock\");\n\t\tceruclaseOreBlock = new AliquoOre(Configurations.ceruclaseOreBlock).setUnlocalizedName(\"Ceruclase\");\n\t\tGameRegistry.registerBlock(ceruclaseOreBlock, ItemBlockOre.class, \"ExAliquo.CeruclaseOreBlock\");\n\t\tdeepironOreBlock = new AliquoOre(Configurations.deepironOreBlock).setUnlocalizedName(\"DeepIron\");\n\t\tGameRegistry.registerBlock(deepironOreBlock, ItemBlockOre.class, \"ExAliquo.DeepIronOreBlock\");\n\t\teximiteOreBlock = new AliquoOre(Configurations.eximiteOreBlock).setUnlocalizedName(\"Eximite\");\n\t\tGameRegistry.registerBlock(eximiteOreBlock, ItemBlockOre.class, \"ExAliquo.EximiteOreBlock\");\n\t\tignatiusOreBlock = new AliquoOre(Configurations.ignatiusOreBlock).setUnlocalizedName(\"Ignatius\");\n\t\tGameRegistry.registerBlock(ignatiusOreBlock, ItemBlockOre.class, \"ExAliquo.IgnatiusOreBlock\");\n\t\tinfuscoliumOreBlock = new AliquoOre(Configurations.infuscoliumOreBlock).setUnlocalizedName(\"Infuscolium\");\n\t\tGameRegistry.registerBlock(infuscoliumOreBlock, ItemBlockOre.class, \"ExAliquo.InfuscoliumOreBlock\");\n\t\tkalendriteOreBlock = new AliquoOre(Configurations.kalendriteOreBlock).setUnlocalizedName(\"Kalendrite\");\n\t\tGameRegistry.registerBlock(kalendriteOreBlock, ItemBlockOre.class, \"ExAliquo.KalendriteOreBlock\");\n\t\tlemuriteOreBlock = new AliquoOre(Configurations.lemuriteOreBlock).setUnlocalizedName(\"Lemurite\");\n\t\tGameRegistry.registerBlock(lemuriteOreBlock, ItemBlockOre.class, \"ExAliquo.LemuriteOreBlock\");\n\t\tmanganeseOreBlock = new AliquoOre(Configurations.manganeseOreBlock).setUnlocalizedName(\"Manganese\");\n\t\tGameRegistry.registerBlock(manganeseOreBlock, ItemBlockOre.class, \"Exaliquo.ManganeseOreBlock\");\n\t\tmeutoiteOreBlock = new AliquoOre(Configurations.meutoiteOreBlock).setUnlocalizedName(\"Meutoite\");\n\t\tGameRegistry.registerBlock(meutoiteOreBlock, ItemBlockOre.class, \"ExAliquo.MeuroiteOreBlock\");\n\t\tmidasiumOreBlock = new AliquoOre(Configurations.midasiumOreBlock).setUnlocalizedName(\"Midasium\");\n\t\tGameRegistry.registerBlock(midasiumOreBlock, ItemBlockOre.class, \"ExAliquo.MidasiumOreBlock\");\n\t\tmithrilOreBlock = new AliquoOre(Configurations.mithrilOreBlock).setUnlocalizedName(\"Mithril\");\n\t\tGameRegistry.registerBlock(mithrilOreBlock, ItemBlockOre.class, \"ExAliquo.MithrilOreBlock\");\n\t\torichalcumOreBlock = new AliquoOre(Configurations.orichalcumOreBlock).setUnlocalizedName(\"Orichalcum\");\n\t\tGameRegistry.registerBlock(orichalcumOreBlock, ItemBlockOre.class, \"ExAliquo.OrichalcumOreBlock\");\n\t\toureclaseOreBlock = new AliquoOre(Configurations.oureclaseOreBlock).setUnlocalizedName(\"Oureclase\");\n\t\tGameRegistry.registerBlock(oureclaseOreBlock, ItemBlockOre.class, \"ExAliquo.OureclaseOreBlock\");\n\t\tprometheumOreBlock = new AliquoOre(Configurations.prometheumOreBlock).setUnlocalizedName(\"Prometheum\");\n\t\tGameRegistry.registerBlock(prometheumOreBlock, ItemBlockOre.class, \"ExAliquo.PromethiumOreBlock\");\n\t\trubraciumOreBlock = new AliquoOre(Configurations.rubraciumOreBlock).setUnlocalizedName(\"Rubracium\");\n\t\tGameRegistry.registerBlock(rubraciumOreBlock, ItemBlockOre.class, \"ExAliquo.RubraciumOreBlock\");\n\t\tsanguiniteOreBlock = new AliquoOre(Configurations.sanguiniteOreBlock).setUnlocalizedName(\"Sanguinite\");\n\t\tGameRegistry.registerBlock(sanguiniteOreBlock, ItemBlockOre.class, \"ExAliquo.SanguinuteOreBlock\");\n\t\tshadowironOreBlock = new AliquoOre(Configurations.shadowironOreBlock).setUnlocalizedName(\"ShadowIron\");\n\t\tGameRegistry.registerBlock(shadowironOreBlock, ItemBlockOre.class, \"ExAliquo.ShadowIronOreBlock\");\n\t\tvulcaniteOreBlock = new AliquoOre(Configurations.vulcaniteOreBlock).setUnlocalizedName(\"Vulcanite\");\n\t\tGameRegistry.registerBlock(vulcaniteOreBlock, ItemBlockOre.class, \"ExAliquo.VulcaniteOreBlock\");\n\t\tvyroxeresOreBlock = new AliquoOre(Configurations.vyroxeresOreBlock).setUnlocalizedName(\"Vyroxeres\");\n\t\tGameRegistry.registerBlock(vyroxeresOreBlock, ItemBlockOre.class, \"ExAliquo.VyroxeresOreBlock\");\n\t\tzincOreBlock = new AliquoOre(Configurations.zincOreBlock).setUnlocalizedName(\"Zinc\");\n\t\tGameRegistry.registerBlock(zincOreBlock, ItemBlockOre.class, \"ExAliquo.ZincOreBlock\");\n\t}\n\t\n\tstatic void registerOreItems()\n\t{\n\t\tcobaltOreItem = new AliquoItemOre(Configurations.cobaltOreItem).setUnlocalizedName(\"Cobalt\");\n\t\tGameRegistry.registerItem(cobaltOreItem, \"ExAliquo.OreCobaltItem\");\n\t\tarditeOreItem = new AliquoItemOre(Configurations.arditeOreItem).setUnlocalizedName(\"Ardite\");\n\t\tGameRegistry.registerItem(arditeOreItem, \"ExAliquo.OreArditeItem\");\n\t\t\n\t\tadamantineOreItem = new AliquoItemOre(Configurations.adamantineOreItem).setUnlocalizedName(\"Adamantine\");\n\t\tGameRegistry.registerItem(adamantineOreItem, \"ExAliquo.OreAdamantineItem\");\n\t\talduoriteOreItem = new AliquoItemOre(Configurations.alduoriteOreItem).setUnlocalizedName(\"Alduorite\");\n\t\tGameRegistry.registerItem(alduoriteOreItem, \"ExAliquo.OreAlduoriteItem\");\n\t\tastralsilverOreItem = new AliquoItemOre(Configurations.astralsilverOreItem).setUnlocalizedName(\"AstralSilver\");\n\t\tGameRegistry.registerItem(astralsilverOreItem, \"ExAliquo.OreAstralSilverItem\");\n\t\tatlarusOreItem = new AliquoItemOre(Configurations.atlarusOreItem).setUnlocalizedName(\"Atlarus\");\n\t\tGameRegistry.registerItem(atlarusOreItem, \"ExAliquo.OreAtlarusItem\");\n\t\tcarmotOreItem = new AliquoItemOre(Configurations.carmotOreItem).setUnlocalizedName(\"Carmot\");\n\t\tGameRegistry.registerItem(carmotOreItem, \"ExAliquo.CarmotOreItem\");\n\t\tceruclaseOreItem = new AliquoItemOre(Configurations.ceruclaseOreItem).setUnlocalizedName(\"Ceruclase\");\n\t\tGameRegistry.registerItem(ceruclaseOreItem, \"ExAliquo.CeruclaseOreItem\");\n\t\tdeepironOreItem = new AliquoItemOre(Configurations.deepironOreItem).setUnlocalizedName(\"DeepIron\");\n\t\tGameRegistry.registerItem(deepironOreItem, \"ExAliquo.DeepIronOreItem\");\n\t\teximiteOreItem = new AliquoItemOre(Configurations.eximiteOreItem).setUnlocalizedName(\"Eximite\");\n\t\tGameRegistry.registerItem(eximiteOreItem, \"ExAliquo.EximiteOreItem\");\n\t\tignatiusOreItem = new AliquoItemOre(Configurations.ignatiusOreItem).setUnlocalizedName(\"Ignatius\");\n\t\tGameRegistry.registerItem(ignatiusOreItem, \"ExAliquo.IgnatiusOreItem\");\n\t\tinfuscoliumOreItem = new AliquoItemOre(Configurations.infuscoliumOreItem).setUnlocalizedName(\"Infuscolium\");\n\t\tGameRegistry.registerItem(infuscoliumOreItem, \"ExAliquo.InfuscoliumOreItem\");\n\t\tkalendriteOreItem = new AliquoItemOre(Configurations.kalendriteOreItem).setUnlocalizedName(\"Kalendrite\");\n\t\tGameRegistry.registerItem(kalendriteOreItem, \"ExAliquo.KalendriteOreItem\");\n\t\tlemuriteOreItem = new AliquoItemOre(Configurations.lemuriteOreItem).setUnlocalizedName(\"Lemurite\");\n\t\tGameRegistry.registerItem(lemuriteOreItem, \"ExAliquo.LemuriteOreItem\");\n\t\tmanganeseOreItem = new AliquoItemOre(Configurations.manganeseOreItem).setUnlocalizedName(\"Manganese\");\n\t\tGameRegistry.registerItem(manganeseOreItem, \"Exaliquo.ManganeseOreItem\");\n\t\tmeutoiteOreItem = new AliquoItemOre(Configurations.meutoiteOreItem).setUnlocalizedName(\"Meuroite\");\n\t\tGameRegistry.registerItem(meutoiteOreItem, \"ExAliquo.MeuroiteOreItem\");\n\t\tmidasiumOreItem = new AliquoItemOre(Configurations.midasiumOreItem).setUnlocalizedName(\"Midasium\");\n\t\tGameRegistry.registerItem(midasiumOreItem, \"ExAliquo.MidasiumOreItem\");\n\t\tmithrilOreItem = new AliquoItemOre(Configurations.mithrilOreItem).setUnlocalizedName(\"Mithril\");\n\t\tGameRegistry.registerItem(mithrilOreItem, \"ExAliquo.MithrilOreItem\");\n\t\torichalcumOreItem = new AliquoItemOre(Configurations.orichalcumOreItem).setUnlocalizedName(\"Orichalcum\");\n\t\tGameRegistry.registerItem(orichalcumOreItem, \"ExAliquo.OrichalcumOreItem\");\n\t\toureclaseOreItem = new AliquoItemOre(Configurations.oureclaseOreItem).setUnlocalizedName(\"Oureclase\");\n\t\tGameRegistry.registerItem(oureclaseOreItem, \"ExAliquo.OureclaseOreItem\");\n\t\tprometheumOreItem = new AliquoItemOre(Configurations.prometheumOreItem).setUnlocalizedName(\"Prometheum\");\n\t\tGameRegistry.registerItem(prometheumOreItem, \"ExAliquo.PromethiumOreItem\");\n\t\trubraciumOreItem = new AliquoItemOre(Configurations.rubraciumOreItem).setUnlocalizedName(\"Rubracium\");\n\t\tGameRegistry.registerItem(rubraciumOreItem, \"ExAliquo.RubraciumOreItem\");\n\t\tsanguiniteOreItem = new AliquoItemOre(Configurations.sanguiniteOreItem).setUnlocalizedName(\"Sanguinite\");\n\t\tGameRegistry.registerItem(sanguiniteOreItem, \"ExAliquo.SanguinuteOreItem\");\n\t\tshadowironOreItem = new AliquoItemOre(Configurations.shadowironOreItem).setUnlocalizedName(\"ShadowIron\");\n\t\tGameRegistry.registerItem(shadowironOreItem, \"ExAliquo.ShadowIronOreItem\");\n\t\tvulcaniteOreItem = new AliquoItemOre(Configurations.vulcaniteOreItem).setUnlocalizedName(\"Vulcanite\");\n\t\tGameRegistry.registerItem(vulcaniteOreItem, \"ExAliquo.VulcaniteOreItem\");\n\t\tvyroxeresOreItem = new AliquoItemOre(Configurations.vyroxeresOreItem).setUnlocalizedName(\"Vyroxeres\");\n\t\tGameRegistry.registerItem(vyroxeresOreItem, \"ExAliquo.VyroxeresOreItem\");\n\t\tzincOreItem = new AliquoItemOre(Configurations.zincOreItem).setUnlocalizedName(\"Zinc\");\n\t\tGameRegistry.registerItem(zincOreItem, \"ExAliquo.ZincOreItem\");\n\t}\n\n\tpublic static void registerRecipes()\n\t{\n\t\tGameRegistry.addShapedRecipe(new ItemStack(crookReed), new Object[] { crookshape, 'i', Item.reed });\n\t\tGameRegistry.addShapedRecipe(new ItemStack(crookGold), new Object[] { crookshape, 'i', Item.ingotGold });\n\t\tGameRegistry.addShapedRecipe(new ItemStack(crookHay), new Object[] { \"wwi\", \"iwi\", \" w \", 'w', Item.wheat, 'i', Block.fenceIron });\n\t\tGameRegistry.addShapedRecipe(new ItemStack(Item.potion, 1, 0), new Object[] { \"ccc\", \"cbc\", \"ccc\", 'c', Block.cactus, 'b', Item.glassBottle });\n\t\tGameRegistry.addShapedRecipe(new ItemStack(blockEndEye), new Object[] { oreshape, 'i', Item.enderPearl});\n\t\tGameRegistry.addShapedRecipe(new ItemStack(blockEndCake), new Object[] { \"eee\", \"cnc\", \"eee\", 'e', blockEndEye, 'c', Item.cake, 'n', new ItemStack(Item.appleGold, 1, 1)});\n\t\t\n\t\tregisterOreCrafting();\n\t}\n\t\n\tstatic void registerOreCrafting()\n\t{\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(cobaltOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(cobaltOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(arditeOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(arditeOreItem, 1, i)});\n\t\t\t\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(adamantineOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(adamantineOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(alduoriteOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(alduoriteOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(astralsilverOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(astralsilverOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(atlarusOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(atlarusOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(carmotOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(carmotOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(ceruclaseOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(ceruclaseOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(deepironOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(deepironOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(eximiteOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(eximiteOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(ignatiusOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(ignatiusOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(infuscoliumOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(infuscoliumOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(kalendriteOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(kalendriteOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(lemuriteOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(lemuriteOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(manganeseOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(manganeseOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(meutoiteOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(meutoiteOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(midasiumOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(midasiumOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(mithrilOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(mithrilOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(orichalcumOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(orichalcumOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(oureclaseOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(oureclaseOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(prometheumOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(prometheumOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(rubraciumOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(adamantineOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(sanguiniteOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(rubraciumOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(shadowironOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(shadowironOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(vulcaniteOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(vulcaniteOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(vyroxeresOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(vyroxeresOreItem, 1, i)});\n\t\t\tGameRegistry.addShapedRecipe(new ItemStack(zincOreBlock, 1, i), new Object[] { oreshape, 'i', new ItemStack(zincOreItem, 1, i)});\n\t\t}\n\t}\n\t\n\tpublic static void postInitHammers() {\n\t\tfor (AliquoHammer hammer : AliquoHammer.registeredHammers()) {\n\t\t\tAliquoMaterial am = AliquoMaterial.get(hammer.material);\n\t\t\t\n\t\t\tEnumToolMaterial toolEnum = am.getToolEnumFromRecipe();\n\t\t\tif (toolEnum == null)\n\t\t\t{\n\t\t\t\ttoolEnum = am.getFallbackToolEnum();\n\t\t\t}\n\t\t\t\n\t\t\tGameRegistry.addRecipe(new ShapedOreRecipe(hammer, hammershape, 's', \"stickWood\", 'i', hammer.getIngotName()));\n\t\t\t\n\t\t\thammer.setToolMaterial(toolEnum);\n\t\t}\n\t}\n\n\tpublic static void registerNihiloOreDict()\n\t{\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tOreDictionary.registerOre(\"oreIron\", new ItemStack(getBlock(Info.ironore), 1, i));\n\t\t\tOreDictionary.registerOre(\"oreGold\", new ItemStack(getBlock(Info.goldore), 1, i));\n\t\t\tOreDictionary.registerOre(\"oreCopper\", new ItemStack(getBlock(Info.copperore), 1, i));\n\t\t\tOreDictionary.registerOre(\"oreTin\", new ItemStack(getBlock(Info.tinore), 1, i));\n\t\t\tOreDictionary.registerOre(\"oreSilver\", new ItemStack(getBlock(Info.silverore), 1, i));\n\t\t\tOreDictionary.registerOre(\"oreLead\", new ItemStack(getBlock(Info.leadore), 1, i));\n\t\t\tOreDictionary.registerOre(\"oreNickel\", new ItemStack(getBlock(Info.nickelore), 1, i));\n\t\t\tOreDictionary.registerOre(\"orePlatinum\", new ItemStack(getBlock(Info.platinumore), 1, i));\n\t\t\tOreDictionary.registerOre(\"oreAluminum\", new ItemStack(getBlock(Info.aluminumore), 1, i));\n\t\t\tOreDictionary.registerOre(\"oreAluminium\", new ItemStack(getBlock(Info.aluminumore), 1, i));\n\t\t}\n\t}\n}",
"public class Configurations {\n\n\tpublic static boolean isOre;\n\tpublic static boolean allowDustSmelting;\n\tpublic static boolean dustValue;\n\tpublic static boolean sieveOreBushes;\n\tpublic static boolean sieveEssenceBushes;\n\tpublic static int dualTools;\n\tpublic static boolean fortuneCrook;\n\tpublic static boolean fortuneHammer;\n\tpublic static boolean miniSmelting;\n\t\n\tpublic static boolean sieveRedwoods;\n\tpublic static boolean sieveHopseed;\n\tpublic static boolean sieveOverworldTrees;\n\tpublic static boolean allowTinkerBushCompost;\n\tpublic static boolean sieveNetherTrees;\n\tpublic static boolean sieveBerryBushes;\n\tpublic static boolean sieveDarkBerries;\n\t\n\tpublic static boolean hammerMoonstone;\n\tpublic static boolean sieveNovas;\n\n\tpublic static int silverwoodSwitch;\n\tpublic static boolean alternatewater;\n\tpublic static boolean runichax;\n\tpublic static boolean harderWands;\n\t\n\tpublic static boolean fishingOysters;\n\t\n\tpublic static boolean sacredohgodthewood;\n\t\n\tpublic static int thaumHammer;\n\tpublic static int invarHammer;\n\tpublic static int copperHammer;\n\tpublic static int tinHammer;\n\tpublic static int silverHammer;\n\tpublic static int leadHammer;\n\tpublic static int platinumHammer;\n\tpublic static int nickelHammer;\n\tpublic static int aluminumHammer;\n\tpublic static int reedCrook;\n\tpublic static int goldCrook;\n\tpublic static int hayCrook;\n\tpublic static int dragonEgg;\n\t\n\tpublic static boolean ninjaFeesh;\n\tpublic static boolean whenk;\n\t\n\tpublic static int blockEndEye;\n\tpublic static int blockEndCake;\n\t\n\tpublic static int cobaltOreBlock;\n\tpublic static int arditeOreBlock;\n\tpublic static int adamantineOreBlock;\n\tpublic static int alduoriteOreBlock;\n\tpublic static int astralsilverOreBlock;\n\tpublic static int atlarusOreBlock;\n\tpublic static int carmotOreBlock;\n\tpublic static int ceruclaseOreBlock;\n\tpublic static int deepironOreBlock;\n\tpublic static int eximiteOreBlock;\n\tpublic static int ignatiusOreBlock;\n\tpublic static int infuscoliumOreBlock;\n\tpublic static int kalendriteOreBlock;\n\tpublic static int lemuriteOreBlock;\n\tpublic static int manganeseOreBlock;\n\tpublic static int meutoiteOreBlock;\n\tpublic static int midasiumOreBlock;\n\tpublic static int mithrilOreBlock;\n\tpublic static int orichalcumOreBlock;\n\tpublic static int oureclaseOreBlock;\n\tpublic static int prometheumOreBlock;\n\tpublic static int rubraciumOreBlock;\n\tpublic static int sanguiniteOreBlock;\n\tpublic static int shadowironOreBlock;\n\tpublic static int vulcaniteOreBlock;\n\tpublic static int vyroxeresOreBlock;\n\tpublic static int zincOreBlock;\n\t\n\tpublic static int cobaltOreItem;\n\tpublic static int arditeOreItem;\n\tpublic static int adamantineOreItem;\n\tpublic static int alduoriteOreItem;\n\tpublic static int astralsilverOreItem;\n\tpublic static int atlarusOreItem;\n\tpublic static int carmotOreItem;\n\tpublic static int ceruclaseOreItem;\n\tpublic static int deepironOreItem;\n\tpublic static int eximiteOreItem;\n\tpublic static int ignatiusOreItem;\n\tpublic static int infuscoliumOreItem;\n\tpublic static int kalendriteOreItem;\n\tpublic static int lemuriteOreItem;\n\tpublic static int manganeseOreItem;\n\tpublic static int meutoiteOreItem;\n\tpublic static int midasiumOreItem;\n\tpublic static int mithrilOreItem;\n\tpublic static int orichalcumOreItem;\n\tpublic static int oureclaseOreItem;\n\tpublic static int prometheumOreItem;\n\tpublic static int rubraciumOreItem;\n\tpublic static int sanguiniteOreItem;\n\tpublic static int shadowironOreItem;\n\tpublic static int vulcaniteOreItem;\n\tpublic static int vyroxeresOreItem;\n\tpublic static int zincOreItem;\n\t\t\n\tpublic static void Load (File location)\n\t{\n\t\tFile file = new File(location + \"/exaliquo.cfg\");\n\t\t\n\t\ttry {\n\t\t\tfile.createNewFile();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\tConfiguration config = new Configuration(file);\n\t\tconfig.load();\n\t\t\n\t\tallowDustSmelting = config.get(\"TCon Tweaks\", \"Can Gravel/Sand/Dust items be smelted\", true).getBoolean(true);\n\t\tdustValue = config.get(\"TCon Tweaks\", \"Normal dust value in the smeltery\", true, \"Normal is 1/4 the block value. False means dusts are 1/6 the value\").getBoolean(true);\n\t\tsieveOreBushes = config.get(\"TCon Tweaks\", \"Can orebushes be obtained\", true).getBoolean(true);\n\t\tsieveEssenceBushes = config.get(\"TCon Tweaks\",\"Can essense bushes be obtained\", true).getBoolean(true);\n\t\tallowTinkerBushCompost = config.get(\"TCon Tweaks\", \"Can oreberry bushes be composted\", false).getBoolean(false);\n\t\tminiSmelting = config.get(\"TCon Tweaks\", \"Enable mini-smelteries\", false).getBoolean(false);\n\t\tdualTools = config.get(\"TCon Tweaks\", \"Modifier lock\", 0, \"0 is default (tool restrictions), 1 is dual-use tools unrestricted, 2 is fully unlock\").getInt(0);\n\t\tfortuneCrook = config.get(\"TCon Tweaks\", \"Fortune-Crooking Interaction\", false).getBoolean(false);\n\t\tfortuneHammer = config.get(\"TCon Tweaks\", \"Fortune-Hammering Interaction\", false).getBoolean(false);\n\t\t\n\t\tsieveRedwoods = config.get(\"Natura Tweaks\", \"Can redwood trees be obtained\", false, \"Redwoods eat every block going both up and down. Use at your own peril. Or enjoyment\").getBoolean(false);\n\t\tsieveHopseed = config.get(\"Natura Tweaks\", \"Can hopseed trees be obtained\", false).getBoolean(false);\n\t\tsieveOverworldTrees = config.get(\"Natura Tweaks\", \"Can natura trees be obtained\", true).getBoolean(true);\n\t\tsieveNetherTrees = config.get(\"Natura Tweaks\", \"Can nether trees be obtained\", true).getBoolean(true);\n\t\tsieveBerryBushes = config.get(\"Natura Tweaks\", \"Can berry bushes be obtained\", true).getBoolean(true);\n\t\tsieveDarkBerries = config.get(\"Natura Tweaks\", \"Can nether bushes be obtained\", true).getBoolean(true);\n\t\t\n\t\thammerMoonstone = config.get(\"ArsMagica Tweaks\", \"Can moonstone be obtained\", false).getBoolean(false);\n\t\tsieveNovas = config.get(\"ArsMagica Tweaks\", \"Can desert novas be obtained\", true).getBoolean(true);\n\t\t\n\t\tsilverwoodSwitch = config.get(\"Thaumcraft Tweaks\", \"Silverwood Setting\", 0, \"Set 0 for default, 1 for tweaked difficulty, and -1 to disable. See the forum post for difficulty changes\").getInt(0);\n\t\talternatewater = config.get(\"Thaumcraft Tweaks\", \"For tundra-less skyblocks\", false).getBoolean(false);\n\t\trunichax = config.get(\"Thaumcraft Tweaks\", \"Alternate Runics to prevent wall\", true, \"False to instead change how greatwoods are obtained\").getBoolean(false);\n\t\tharderWands = config.get(\"Thaumcraft Tweaks\", \"Do the primal aspect wand cores require a Greatwood wand core\", false).getBoolean(false);\n\t\t\n\t\tfishingOysters = config.get(\"Mariculture Tweaks\", \"Can Oysters be obtained via fishing\", true).getBoolean(true);\n\t\t\n\t\tsacredohgodthewood = config.get(\"MineFactory Reloaded Tweaks\",\"Can Sacred Rubber Trees be obtained\", false).getBoolean(false);\n\t\t\n\t\tthaumHammer = config.get(\"Ex Aliquo things\",\"Thaumium Hammer ID\", 20160).getInt(20160);\n\t\tinvarHammer = config.get(\"Ex Aliquo things\",\"Invar Hammer ID\", 20161).getInt(20161);\n\t\tcopperHammer = config.get(\"Ex Aliquo things\",\"Copper Hammer ID\", 20162).getInt(20162);\n\t\ttinHammer = config.get(\"Ex Aliquo things\",\"Tin Hammer ID\", 20163).getInt(20163);\n\t\tsilverHammer = config.get(\"Ex Aliquo things\",\"Silver Hammer ID\", 20164).getInt(20164);\n\t\tleadHammer = config.get(\"Ex Aliquo things\",\"Lead Hammer ID\", 20165).getInt(20165);\n\t\tplatinumHammer = config.get(\"Ex Aliquo things\",\"Platinum Hammer ID\", 20166).getInt(20166);\n\t\tnickelHammer = config.get(\"Ex Aliquo things\",\"Nickel Hammer ID\", 20167).getInt(20167);\n\t\taluminumHammer = config.get(\"Ex Aliquo things\",\"Aluminum Hammer ID\", 20168).getInt(20168);\n\t\treedCrook = config.get(\"Ex Aliquo things\",\"Reed Crook\", 20300).getInt(20300);\n\t\tgoldCrook = config.get(\"Ex Aliquo things\",\"Golden Crook\", 20301).getInt(20301);\n\t\thayCrook = config.get(\"Ex Aliquo things\",\"Hay Crook\", 20302).getInt(20302);\n\t\tdragonEgg = config.get(\"Ex Aliquo things\",\"Dragon Egg\", 20303).getInt(20303);\n\t\t\n\t\tblockEndEye = config.get(\"Ex Aliquo things\",\"EnderBlock\", 2298).getInt(2298);\n\t\tblockEndCake = config.get(\"Ex Aliquo things\",\"EnderCake\", 2299).getInt(2299);\n\t\t\n\t\tcobaltOreBlock = config.get(\"TCon Block IDs\", \"CobaltOre Block\", 2300).getInt(2300);\n\t\tarditeOreBlock = config.get(\"TCon Block IDs\", \"ArditeOre Block\", 2301).getInt(2301);\n\t\tadamantineOreBlock = config.get(\"Metallurgy Block IDs\",\"AdamantineOre Block\",2302).getInt(2302);\n\t\talduoriteOreBlock = config.get(\"Metallurgy Block IDs\",\"AlduoriteOre Block\",2303).getInt(2303);\n\t\tastralsilverOreBlock = config.get(\"Metallurgy Block IDs\",\"AstralSilverOre Block\",2304).getInt(2304);\n\t\tatlarusOreBlock = config.get(\"Metallurgy Block IDs\",\"AtlarusOre Block\",2305).getInt(2305);\n\t\tcarmotOreBlock = config.get(\"Metallurgy Block IDs\",\"CarmotOre Block\",2306).getInt(2306);\n\t\tceruclaseOreBlock = config.get(\"Metallurgy Block IDs\",\"CeruclaseOre Block\",2307).getInt(2307);\n\t\tdeepironOreBlock = config.get(\"Metallurgy Block IDs\",\"DeepIronOre Block\",2308).getInt(2308);\n\t\teximiteOreBlock = config.get(\"Metallurgy Block IDs\",\"EximiteOre Block\",2309).getInt(2309);\n\t\tignatiusOreBlock = config.get(\"Metallurgy Block IDs\",\"IgnatiusOre Block\",2310).getInt(2310);\n\t\tinfuscoliumOreBlock = config.get(\"Metallurgy Block IDs\",\"InfucoliumOre Block\",2311).getInt(2311);\n\t\tkalendriteOreBlock = config.get(\"Metallurgy Block IDs\",\"KalendriteOre Block\",2312).getInt(2312);\n\t\tlemuriteOreBlock = config.get(\"Metallurgy Block IDs\",\"LemuriteOre Block\",2313).getInt(2313);\n\t\tmanganeseOreBlock = config.get(\"Metallurgy Block IDs\",\"ManganeseOre Block\",2314).getInt(2314);\n\t\tmeutoiteOreBlock = config.get(\"Metallurgy Block IDs\",\"MeuroiteOre Block\",2315).getInt(2315);\n\t\tmidasiumOreBlock = config.get(\"Metallurgy Block IDs\",\"MidasiumOre Block\",2316).getInt(2316);\n\t\tmithrilOreBlock = config.get(\"Metallurgy Block IDs\",\"MithrilOre Block\",2317).getInt(2317);\n\t\torichalcumOreBlock = config.get(\"Metallurgy Block IDs\",\"OrichalcumOre Block\",2318).getInt(2318);\n\t\toureclaseOreBlock = config.get(\"Metallurgy Block IDs\",\"OureclaseOre Block\",2319).getInt(2319);\n\t\tprometheumOreBlock = config.get(\"Metallurgy Block IDs\",\"PromethiumOre Block\",2320).getInt(2320);\n\t\trubraciumOreBlock = config.get(\"Metallurgy Block IDs\",\"RubraciumOre Block\",2321).getInt(2321);\n\t\tsanguiniteOreBlock = config.get(\"Metallurgy Block IDs\",\"SanguiniteOre Block\",2322).getInt(2322);\n\t\tshadowironOreBlock = config.get(\"Metallurgy Block IDs\",\"ShadowIronOre Block\",2323).getInt(2323);\n\t\tvulcaniteOreBlock = config.get(\"Metallurgy Block IDs\",\"VulcaniteOre Block\",2324).getInt(2324);\n\t\tvyroxeresOreBlock = config.get(\"Metallurgy Block IDs\",\"VyroxeresOre Block\",2325).getInt(2325);\n\t\tzincOreBlock = config.get(\"Metallurgy Block IDs\",\"ZincOre Block\",2326).getInt(2326);\n\t\t\n\t\tcobaltOreItem = config.get(\"TCon Item IDs\", \"CobaltOre Item\", 20500).getInt(20500);\n\t\tarditeOreItem = config.get(\"TCon Item IDs\", \"ArditeOre Item\", 20501).getInt(20501);\n\t\tadamantineOreItem = config.get(\"Metallurgy Item IDs\",\"AdamantineOre Item\", 20502).getInt(20502);\n\t\talduoriteOreItem = config.get(\"Metallurgy Item IDs\",\"AlduoriteOre Item\", 20503).getInt(20503);\n\t\tastralsilverOreItem = config.get(\"Metallurgy Item IDs\",\"AstralSilverOre Item\", 20504).getInt(20504);\n\t\tatlarusOreItem = config.get(\"Metallurgy Item IDs\",\"AtlarusOre Item\", 20505).getInt(20505);\n\t\tcarmotOreItem = config.get(\"Metallurgy Item IDs\",\"CarmotOre Item\", 20506).getInt(20506);\n\t\tceruclaseOreItem = config.get(\"Metallurgy Item IDs\",\"CeruclaseOre Item\", 20507).getInt(20507);\n\t\tdeepironOreItem = config.get(\"Metallurgy Item IDs\",\"DeepIronOre Item\", 20508).getInt(20508);\n\t\teximiteOreItem = config.get(\"Metallurgy Item IDs\",\"EximiteOre Item\", 20509).getInt(20509);\n\t\tignatiusOreItem = config.get(\"Metallurgy Item IDs\",\"IgnatiusOre Item\", 20510).getInt(20510);\n\t\tinfuscoliumOreItem = config.get(\"Metallurgy Item IDs\",\"InfuscoliumOre Item\", 20511).getInt(20511);\n\t\tkalendriteOreItem = config.get(\"Metallurgy Item IDs\",\"KalendriteOre Item\", 20512).getInt(20512);\n\t\tlemuriteOreItem = config.get(\"Metallurgy Item IDs\",\"LemuriteOre Item\", 20513).getInt(20513);\n\t\tmanganeseOreItem = config.get(\"Metallurgy Item IDs\",\"ManganeseOre Item\", 20514).getInt(20514);\n\t\tmeutoiteOreItem = config.get(\"Metallurgy Item IDs\",\"MeuroiteOre Item\", 20515).getInt(20515);\n\t\tmidasiumOreItem = config.get(\"Metallurgy Item IDs\",\"MidasiumOre Item\", 20516).getInt(20516);\n\t\tmithrilOreItem = config.get(\"Metallurgy Item IDs\",\"MithrilOre Item\", 20517).getInt(20517);\n\t\torichalcumOreItem = config.get(\"Metallurgy Item IDs\",\"OrichalcumOre Item\", 20518).getInt(20518);\n\t\toureclaseOreItem = config.get(\"Metallurgy Item IDs\",\"OureclaseOre Item\", 20519).getInt(20519);\n\t\tprometheumOreItem = config.get(\"Metallurgy Item IDs\",\"PrometheumOre Item\", 20520).getInt(20520);\n\t\trubraciumOreItem = config.get(\"Metallurgy Item IDs\",\"RubraciumOre Item\", 20521).getInt(20521);\n\t\tsanguiniteOreItem = config.get(\"Metallurgy Item IDs\",\"SanguiniteOre Item\", 20522).getInt(20522);\n\t\tshadowironOreItem = config.get(\"Metallurgy Item IDs\",\"ShadowIronOre Item\", 20523).getInt(20523);\n\t\tvulcaniteOreItem = config.get(\"Metallurgy Item IDs\",\"VulcaniteOre Item\", 20524).getInt(20524);\n\t\tvyroxeresOreItem = config.get(\"Metallurgy Item IDs\",\"VyroxeresOre Item\", 20525).getInt(20525);\n\t\tzincOreItem = config.get(\"Metallurgy Item IDs\",\"ZincOre Item\", 20526).getInt(20526);\n\t\t\n\t\tninjaFeesh = config.get(\"Ex Aliquo multi-mod tweaks\",\"Hide Feesh from hammers\",true).getBoolean(true);\n\t\tisOre = config.get(\"Ex Aliquo multi-mod tweaks\", \"Are Gravel/Sand/Dust Ores actually ores\", true, \"False for counting as an ingot\").getBoolean(true);\n\t\twhenk = config.get(\"Ex Aliquo multi-mod tweaks\", \"Whenk :V\", true, \"Requires ninja-like feesh to do anything\").getBoolean(true);\n\t\t\n\t\tconfig.save();\n\t}\n}",
"public enum Info\n{\n\twoodbarrel(\"crowley.skyblock\",\"block\",\"barrel\"),\n\tstonebarrel(\"crowley.skyblock\",\"block\",\"barrel_stone\"),\n\tcrucible(\"crowley.skyblock\",\"block\",\"crucible\"),\n\tdust(\"crowley.skyblock\",\"block\",\"dust\"),\n\tsilkleaves(\"crowley.skyblock\",\"block\",\"infested_leaves\"),\n\tbeetrap(\"crowley.skyblock\",\"block\",\"bee_trap\"),\n\tscentedtrap(\"crowley.skyblock\",\"block\",\"bee_trap_treated\"),\n\twitchwater(\"crowley.skyblock\",\"block\",\"witchwater\"),\n\tironore(\"crowley.skyblock\",\"block\",\"iron_ore\"),\n\tgoldore(\"crowley.skyblock\",\"block\",\"gold_ore\"),\n\tcopperore(\"crowley.skyblock\",\"block\",\"copper_ore\"),\n\ttinore(\"crowley.skyblock\",\"block\",\"tin_ore\"),\n\tsilverore(\"crowley.skyblock\",\"block\",\"silver_ore\"),\n\tleadore(\"crowley.skyblock\",\"block\",\"lead_ore\"),\n\tnickelore(\"crowley.skyblock\",\"block\",\"nickel_ore\"),\n\tplatinumore(\"crowley.skyblock\",\"block\",\"platinum_ore\"),\n\tosmiumore(\"crowley.skyblock\",\"block\",\"osmium_ore\"),\n\taluminumore(\"crowley.skyblock\",\"block\",\"aluminum_ore\"),\n\tsilkworm(\"crowley.skyblock\",\"item\",\"silkworm\"),\n\tnomworm(\"crowley.skyblock\",\"item\",\"silkworm_cooked\"),\n\tspores(\"crowley.skyblock\",\"item\",\"spores\"),\n\tgrass(\"crowley.skyblock\",\"item\",\"seed_grass\"),\n\toakseed(\"crowley.skyblock\",\"item\",\"seed_oak\"),\n\tzebraseed(\"crowley.skyblock\",\"item\",\"seed_birch\"),\n\tspruceseed(\"crowley.skyblock\",\"item\",\"seed_spruce\"),\n\tjungleseed(\"crowley.skyblock\",\"item\",\"seed_jungle\"),\n\tcactusseed(\"crowley.skyblock\",\"item\",\"seed_cactus\"),\n\tcaneseed(\"crowley.skyblock\",\"item\",\"seed_sugar_cane\"),\n\tcarrotseed(\"crowley.skyblock\",\"item\",\"seed_carrot\"),\n\ttaterseed(\"crowley.skyblock\",\"item\",\"seed_potato\"),\n\trubberseed(\"crowley.skyblock\",\"item\",\"seed_rubber\"),\n\twitchbucket(\"crowley.skyblock\",\"item\",\"bucket_witchwater\"),\n\tmesh(\"crowley.skyblock\",\"item\",\"mesh\"),\n\tirongrav(\"crowley.skyblock\",\"item\",\"iron_broken\"),\n\tironsand(\"crowley.skyblock\",\"item\",\"iron_crushed\"),\n\tirondust(\"crowley.skyblock\",\"item\",\"iron_pulverized\"),\n\tgoldgrav(\"crowley.skyblock\",\"item\",\"gold_broken\"),\n\tgoldsand(\"crowley.skyblock\",\"item\",\"gold_crushed\"),\n\tgolddust(\"crowley.skyblock\",\"item\",\"gold_pulverized\"),\n\tcoppergrav(\"crowley.skyblock\",\"item\",\"copper_broken\"),\n\tcoppersand(\"crowley.skyblock\",\"item\",\"copper_crushed\"),\n\tcopperdust(\"crowley.skyblock\",\"item\",\"copper_pulverized\"),\n\ttingrav(\"crowley.skyblock\",\"item\",\"tin_broken\"),\n\ttinsand(\"crowley.skyblock\",\"item\",\"tin_crushed\"),\n\ttindust(\"crowley.skyblock\",\"item\",\"tin_pulverized\"),\n\tsilvergrav(\"crowley.skyblock\",\"item\",\"silver_broken\"),\n\tsilversand(\"crowley.skyblock\",\"item\",\"silver_crushed\"),\n\tsilverdust(\"crowley.skyblock\",\"item\",\"silver_pulverized\"),\n\tleadgrav(\"crowley.skyblock\",\"item\",\"lead_broken\"),\n\tleadsand(\"crowley.skyblock\",\"item\",\"lead_crushed\"),\n\tleaddust(\"crowley.skyblock\",\"item\",\"lead_pulverized\"),\n\tnickelgrav(\"crowley.skyblock\",\"item\",\"nickel_broken\"),\n\tnickelsand(\"crowley.skyblock\",\"item\",\"nickel_crushed\"),\n\tnickeldust(\"crowley.skyblock\",\"item\",\"nickel_pulverized\"),\n\tplatinumgrav(\"crowley.skyblock\",\"item\",\"platinum_broken\"),\n\tplatinumsand(\"crowley.skyblock\",\"item\",\"platinum_crushed\"),\n\tplatinumdust(\"crowley.skyblock\",\"item\",\"platinum_pulverized\"),\n\tosmiumgrav(\"crowley.skyblock\",\"item\",\"osmium_broken\"),\n\tosmiumsand(\"crowley.skyblock\",\"item\",\"osmium_crushed\"),\n\tosmiumdust(\"crowley.skyblock\",\"item\",\"osmium_pulverized\"),\n\taluminumgrav(\"crowley.skyblock\",\"item\",\"aluminum_broken\"),\n\taluminumsand(\"crowley.skyblock\",\"item\",\"aluminum_crushed\"),\n\taluminumdust(\"crowley.skyblock\",\"item\",\"aluminum_pulverized\"),\n\tstones(\"crowley.skyblock\",\"item\",\"stone\"),\n\tdiamondhammer(\"crowley.skyblock\",\"item\",\"hammer_diamond\"),\n\t\t\n\toreberrybush(\"TConstruct\",\"block\",\"ore.berries.one\"),\n\toreberrybush2(\"TConstruct\",\"block\",\"ore.berries.two\"),\n\thambone(\"TConstruct\",\"block\",\"MeatBlock\"),\n\tstorch(\"TConstruct\",\"block\",\"decoration.stonetorch\"),\n\tcraftedsoil(\"TConstruct\",\"block\",\"CraftedSoil\"),\n\tslimeleaves(\"TConstruct\",\"block\",\"slime.leaves\"),\n\tslimesapling(\"TConstruct\",\"block\",\"slime.sapling\"),\n\tmaterials(\"TConstruct\",\"item\",\"materials\"),\n\toreberry(\"TConstruct\",\"item\",\"oreBerries\"),\n\ttinkerfood(\"TConstruct\",\"item\",\"strangeFood\"),\n\t\t\n\tflora(\"Natura\",\"block\",\"florasapling\"),\n\tleaves(\"Natura\",\"block\",\"floraleaves\"),\n\traresap(\"Natura\",\"block\",\"Rare Sapling\"),\n\trareleaves(\"Natura\",\"block\",\"Rare Leaves\"),\n\tdarkleaves(\"Natura\",\"block\",\"Dark Leaves\"),\n\tmonochrome(\"Natura\",\"block\",\"floraleavesnocolor\"),\n\tgood(\"Natura\",\"block\",\"BerryBush\"),\n\tevil(\"Natura\",\"block\",\"NetherBerryBush\"),\n\tglowshroom(\"Natura\",\"block\",\"Glowshroom\"),\n\tthornvines(\"Natura\",\"block\",\"Thornvines\"),\n\tcactus(\"Natura\",\"block\",\"Saguaro\"),\n\tbluebell(\"Natura\",\"block\",\"Bluebells\"),\n\ttopiary(\"Natura\",\"block\",\"GrassBlock\"),\n\tnethersoil(\"Natura\",\"block\",\"soil.tainted\"),\n\tnethersand(\"Natura\",\"block\",\"heatsand\"),\n\tfruit(\"Natura\",\"item\",\"saguaro.fruit\"),\n\tgoodberry(\"Natura\",\"item\",\"berry\"),\n\tbadberry(\"Natura\",\"item\",\"berry.nether\"),\n\tpotash(\"Natura\",\"item\",\"Natura.netherfood\"),\n\tplants(\"Natura\",\"item\",\"barleyFood\"),\n\timpmeat(\"Natura\",\"item\",\"impmeat\"),\n\t\t\n\torchid(\"arsmagica2\",\"block\",\"blueOrchid\"),\n\tnova(\"arsmagica2\",\"block\",\"desertNova\"),\n\taum(\"arsmagica2\",\"block\",\"Aum\"),\n\twitchwood(\"arsmagica2\",\"block\",\"saplingWitchwood\"),\n\twitchleaves(\"arsmagica2\",\"block\",\"WitchwoodLeaves\"),\n\twakebloom(\"arsmagica2\",\"block\",\"WakeBloom\"),\n\ttarma(\"arsmagica2\",\"block\",\"TarmaRoot\"),\n\tessenceBlock(\"arsmagica2\",\"block\",\"liquidEssence\"),\n\tvtorch(\"arsmagica2\",\"block\",\"VinteumTorch\"),\n\tessenceBucket(\"arsmagica2\",\"item\",\"liquidEssenceBucket\"),\n\tmagicore(\"arsmagica2\",\"item\",\"itemOre\"),\n\tessences(\"arsmagica2\",\"item\",\"essence\"),\n\t\t\n\tthaumplants(\"Thaumcraft\",\"block\",\"blockCustomPlant\"),\n\tthaumleaves(\"Thaumcraft\",\"block\",\"blockMagicalLeaves\"),\n\tttorch(\"Thaumcraft\",\"block\",\"blockAiry\"),\n\tcandle(\"Thaumcraft\",\"block\",\"blockCandle\"),\n\tdevices(\"Thaumcraft\",\"block\",\"blockStoneDevice\"),\n\tcosmetics(\"Thaumcraft\",\"block\",\"blockCosmeticSolid\"),\n\tcluster(\"Thaumcraft\",\"block\",\"blockCrystal\"),\n\tmagicwood(\"Thaumcraft\",\"block\",\"blockMagicalLog\"),\n\tshard(\"Thaumcraft\",\"item\",\"ItemShard\"),\n\tresources(\"Thaumcraft\",\"item\",\"ItemResource\"),\n\tnuggets(\"Thaumcraft\",\"item\",\"ItemNugget\"),\n\tmanabean(\"Thaumcraft\",\"item\",\"ItemManaBean\"),\n\tnodejar(\"Thaumcraft\",\"item\",\"BlockJarNodeItem\"),\n\twands(\"Thaumcraft\",\"item\",\"WandRod\"),\n\t\t\n\tgcsappling(\"Growthcraft|Apples\",\"block\",\"grc.appleSapling\"),\n\tgcbamboo(\"Growthcraft|Bamboo\",\"block\",\"grc.bambooShoot\"),\n\tgcleaves(\"Growthcraft|Bamboo\",\"block\",\"grc.bambooLeaves\"),\n\tgcapple(\"Growthcraft|Apples\",\"item\",\"grc.appleSeeds\"),\n\tgcbee(\"Growthcraft|Bees\",\"item\",\"grc.bee\"),\n\tgcgrape(\"Growthcraft|Grapes\",\"item\",\"grc.grapes\"),\n\tgcgrapeseed(\"Growthcraft|Grapes\",\"item\",\"grc.grapeSeeds\"),\n\tgchops(\"Growthcraft|Hops\",\"item\",\"grc.hops\"),\n\tgchopseed(\"Growthcraft|Hops\",\"item\",\"grc.hopSeeds\"),\n\tgcrice(\"Growthcraft|Rice\",\"item\",\"grc.rice\"),\n\tgcriceball(\"Growthcraft|Rice\",\"item\",\"grc.riceBall\"),\n\t\t\n\tmariores(\"Mariculture\",\"block\",\"oreBlocks\"),\n\tmarioyster(\"Mariculture\",\"block\",\"oysterBlock\"),\n\tmaricoral(\"Mariculture\",\"item\",\"coral\"),\n\tmaribottle(\"Mariculture\",\"item\",\"liquidContainers\"),\n\t\t\n\thellfeesh(\"Minecraft\",\"block\",\"netherOresBlockHellfish\"),\n\t\t\n\trubbersapling(\"MineFactoryReloaded\",\"block\",\"tile.mfr.rubberwood.sapling\"),\n\trubberleaves(\"MineFactoryReloaded\",\"block\",\"tile.mfr.rubberwood.leaves\"),\n\t\t\n\tdartsapling(\"DartCraft\",\"block\",\"forceSapling\"),\n\tdartleaves(\"DartCraft\",\"block\",\"forceLeaves\"),\n\t\t\n\tliquidpyro(\"ThermalExpansion\",\"block\",\"FluidPyrotheum\"),\n\tliquidcold(\"ThermalExpansion\",\"block\",\"FluidCryotheum\");\n\t\t\n\tprivate final String mod;\n\tprivate final String type;\n\tprivate final String sname;\n\t\t\n\tprivate Info(String mod, String type, String sname)\n\t{\n\t\tthis.mod = mod;\n\t\tthis.type = type;\n\t\tthis.sname = sname;\n\t}\n\t\t\n\tprivate String mod() { return mod; }\n\tprivate String type() { return type; }\n\tprivate String sname() {return sname; }\n}"
] | import static exaliquo.data.ModIDs.getBlock;
import static exaliquo.data.ModIDs.getIDs;
import static exaliquo.data.ModIDs.getItem;
import static exaliquo.data.MoltenMetals.*;
import static net.minecraftforge.fluids.FluidRegistry.getFluid;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import tconstruct.library.crafting.Smeltery;
import exaliquo.Registries;
import exaliquo.data.Configurations;
import exaliquo.data.ModIDs.Info;
import exnihilo.registries.CrucibleRegistry; | package exaliquo.bridges.crossmod;
public class ExtraTic_Mekanism
{
protected static void SmeltMekanism()
{
for (int i = 0; i < 3; i++)
{ | Smeltery.addMelting(getBlock(Info.osmiumore), i, 550, new FluidStack(getFluid("molten.osmium"), ingotCostSmeltery)); | 0 |
Aurilux/Cybernetica | src/main/java/com/vivalux/cyb/item/implant/ImplantCyberneticArm.java | [
"@Mod(modid = CYBModInfo.MOD_ID,\n name = CYBModInfo.MOD_NAME,\n guiFactory = CYBModInfo.GUI_FACTORY,\n version = CYBModInfo.MOD_VERSION)\npublic class Cybernetica {\n\t@Instance(CYBModInfo.MOD_ID)\n\tpublic static Cybernetica instance;\n\n\t@SidedProxy(clientSide = CYBModInfo.CLIENT_PROXY, serverSide = CYBModInfo.SERVER_PROXY)\n\tpublic static CYBClientProxy proxy;\n\n /**\n * Run before anything else. Read your config, create blocks, items, etc\n */\n\t@EventHandler\n\tpublic void preInit(FMLPreInitializationEvent e) {\n //Config should be one of the first things you do\n FMLCommonHandler.instance().bus().register(new ConfigHandler(e.getSuggestedConfigurationFile()));\n\n //proxy.preInit();\n\n //Initialize mod-independent objects\n\t\tCYBBlocks.init();\n\t\tCYBItems.init();\n CYBAchievements.init();\n\n //PacketHandler.init();\n ChestGenHandler.init();\n\t}\n\n /**\n * Build whatever data structures you care about and register handlers, tile entities, renderers, and recipes\n */\n\t@EventHandler\n\tpublic void init(FMLInitializationEvent e) {\n //Register recipes here to ensure that all mod items and blocks, including those from other mods, are added\n CYBRecipes.init();\n\n proxy.init();\n\n //Minecraft Forge event handlers\n MinecraftForge.EVENT_BUS.register(new PlayerEventHandler());\n\n //FML event handlers\n FMLCommonHandler.instance().bus().register(new UpdateHandler());\n\n //Network handlers\n NetworkRegistry.INSTANCE.registerGuiHandler(Cybernetica.instance, new GuiHandler());\n\t}\n\n /**\n * Handle interaction with other mods, complete your setup based on this\n */\n\t@EventHandler\n\tpublic void postInit(FMLPostInitializationEvent e) {\n\n //proxy.postInit();\n\n //Inter-mod communications\n //Register the Waila data provider\n /*\n\t\tif (Loader.isModLoaded(\"Waila\")) {\n FMLInterModComms.sendMessage(\"Waila\", \"register\", \"\");\n }\n */\n\t}\n}",
"public abstract class Implant extends ItemArmor implements ISpecialArmor {\n /**\n * An enum with a set of bits that determine which implants a module can be applied to.\n * I could have just used a series of bit variables, but enums are a bit easier to manage.\n * This also replaces the 'armorType' uses inside this mod.\n *\n * Bit flags should be used more to determine settings such as text formatting options (Bold, Italic, etc), while\n * enums are best used to represent 'Types', such as what I've done here\n */\n public enum ImplantType {\n HEAD, TORSO, LEG, FOOT\n }\n\n /**\n * The ImplantType for this specific implant. Used to ensure modules get installed to the appropriate implant\n */\n private ImplantType implantType;\n\n //TODO remove this variable after the redesign\n private int moduleCapacity;\n\n\tpublic Implant(int renderIndex, ImplantType type, int capacity) {\n super(ArmorMaterial.IRON, renderIndex, type.ordinal());\n this.implantType = type;\n this.moduleCapacity = capacity;\n\t}\n\n @Override\n public int getItemStackLimit(ItemStack stack) {\n return 1;\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void registerIcons(IIconRegister reg) {\n String itemName = getUnlocalizedName().substring(getUnlocalizedName().lastIndexOf(\".\") + 1);\n this.itemIcon = reg.registerIcon(itemName);\n }\n\n @Override\n public String getUnlocalizedName() {\n return \"implant.\" + this.getCoreUnlocalizedName(super.getUnlocalizedName());\n }\n\n @Override\n public String getUnlocalizedName(ItemStack stack) {\n return \"implant.\" + this.getCoreUnlocalizedName(super.getUnlocalizedName());\n }\n\n /**\n * Trims the prefix identifier from the default getUnlocalizedName() (\"item.\") so we can add our own\n * @param unlocalizedName the unlocalized name\n * @return the trimmed string\n */\n protected String getCoreUnlocalizedName(String unlocalizedName) {\n return unlocalizedName.substring(unlocalizedName.indexOf(\".\") + 1);\n }\n\n /**\n * Adds text to the ItemStack's tooltip\n * @param stack the ItemStack of this item\n * @param player the player looking at the stack\n * @param list a list of strings to display in the tooltips. Each entry is it's own line\n * @param advancedTooltips if true displayed advanced information in the tooltip. Probably for debugging.\n */\n @Override\n public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean advancedTooltips) {\n if (stack.hasTagCompound()) {\n ItemStack module = ItemStack.loadItemStackFromNBT(stack.getTagCompound());\n String info = EnumChatFormatting.AQUA + StatCollector.translateToLocal(module.getItem().getUnlocalizedName() + \".name\");\n list.add(info);\n }\n else {\n String info = EnumChatFormatting.RED + StatCollector.translateToLocal(\"tooltip.module.none\");\n list.add(info);\n }\n }\n\n /**\n * Unlike normal armor items, the player cannot equip implants without using the integration table\n * @param stack the ItemStack containing an instance of this item\n * @param world the world the player is in\n * @param player the player that just right-clicked the ItemStack\n * @return the changed stack\n */\n\t@Override\n\tpublic ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {\n\t\treturn stack;\n\t}\n\n @Override\n public boolean getIsRepairable(ItemStack object, ItemStack resource) {\n return resource.getItem() == CYBItems.component && resource.getItemDamage() == 0 || super.getIsRepairable(object, resource);\n }\n\n /**\n * Unlike normal armor items, the player cannot enchant implants\n * @return an int describing how \"enchantable\" an item is\n */\n @Override\n public int getItemEnchantability() {\n return 0;\n }\n\n /**\n * Returns the number of modules this implant can have installed\n * TODO This will get removed in the next version\n * @return moduleCapacity\n */\n public int getModuleCapacity() {\n return this.moduleCapacity;\n }\n\n public ImplantType getImplantType() {\n return this.implantType;\n }\n\n /**\n * The ImplantType enum ordinal values corresponds to the respective armor slots. This is a helper method to get\n * that information\n * @return the ordinal value of the ImplantType\n */\n public int implantTypeAsArmor() {\n return this.getImplantType().ordinal();\n }\n\n /**\n * Performs actions determined by the implant every tick\n * @param world the world the player is in\n * @param player the player the armor is equipped to\n * @param armor the armor currently ticked\n */\n @Override\n public void onArmorTick(World world, EntityPlayer player, ItemStack armor) {\n if(armor.getItem() != this || !armor.hasTagCompound()) return;\n this.implantTick(world, player, armor);\n }\n\n /**\n * The update tick for this implant. This will be different for each implant and for each module it has installed.\n * I could technically just use 'onArmorTick', but I feel the name of this method gives better context\n * @param world the world the player is in\n * @param player the player the implant is equipped to\n * @param armor the armor currently ticked\n */\n protected abstract void implantTick(World world, EntityPlayer player, ItemStack armor);\n\n /**\n * Installs modules onto the implant by writing them to NBT\n * @param implant the implant the modules are getting installed on\n * @param module the array of modules to install\n */\n public static void installModule(ItemStack implant, ItemStack module) {\n //Verify that both ItemStacks are what they are supposed to be\n if (!(implant.getItem() instanceof Implant) && !(module.getItem() instanceof Module)) return;\n\n NBTTagCompound installedModules = new NBTTagCompound();\n module.writeToNBT(installedModules);\n implant.setTagCompound(installedModules);\n }\n\n /**\n * Checks to see if a specific module, given by its name, is installed\n * @param implant the inplant to check\n * @param moduleClass the class of the module to find\n * @return true if the module is installed, false otherwise\n */\n public static boolean hasInstalledModule(ItemStack implant, Class moduleClass) {\n for (ItemStack i : getInstalledModules(implant, ((Implant) implant.getItem()).getModuleCapacity())) {\n if (i != null && i.getItem().getClass().equals(moduleClass)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Gets all of the modules currently installed on an implant\n * @param implant the implant to get modules from\n * @param capacity the capacity of the implant\n * @return the array of installed modules\n */\n public static ItemStack[] getInstalledModules(ItemStack implant, int capacity) {\n ItemStack[] modules = new ItemStack[capacity];\n NBTTagCompound installedModules = implant.getTagCompound();\n for (int i = 0; i < modules.length; i++) {\n modules[i] = ItemStack.loadItemStackFromNBT(installedModules);\n }\n return modules;\n }\n}",
"public class ModelArmImplant extends ModelBiped\n{\n \n ModelRenderer SideTop;\n ModelRenderer SideBottom;\n ModelRenderer FrontTop;\n ModelRenderer FrontBottom;\n ModelRenderer BackTop;\n ModelRenderer BackBottom;\n ModelRenderer Augment1;\n ModelRenderer Augment2;\n ModelRenderer Augment3;\n ModelRenderer Finger1;\n ModelRenderer Finger1Bottom;\n ModelRenderer Finger2;\n ModelRenderer Finger2Bottom;\n ModelRenderer Finger3;\n ModelRenderer Finger3Bottom;\n ModelRenderer Top;\n ModelRenderer LeftTop;\n ModelRenderer LeftBottom;\n ModelRenderer Augment4;\n ModelRenderer Bottom;\n \n public ModelArmImplant()\n {\n textureWidth = 64;\n textureHeight = 64;\n \n int yOffset = -2;\n int xOffset = 5;\n \n SideTop = new ModelRenderer(this, 11, 29);\n SideTop.addBox(-9F+xOffset, 0F+yOffset, -2F, 1, 4, 4);\n SideTop.setRotationPoint(0F, 0F, 0F);\n SideTop.setTextureSize(64, 32);\n SideTop.mirror = true;\n setRotation(SideTop, 0F, 0F, 0F);\n \n SideBottom = new ModelRenderer(this, 11, 44);\n SideBottom.addBox(-9F+xOffset, 8F+yOffset, -2F, 1, 4, 4);\n SideBottom.setRotationPoint(0F, 0F, 0F);\n SideBottom.setTextureSize(64, 32);\n SideBottom.mirror = true;\n setRotation(SideBottom, 0F, 0F, 0F);\n \n FrontTop = new ModelRenderer(this, 0, 12);\n FrontTop.addBox(-8F+xOffset, 0F+yOffset, -3F, 4, 4, 1);\n FrontTop.setRotationPoint(0F, 0F, 0F);\n FrontTop.setTextureSize(64, 32);\n FrontTop.mirror = true;\n setRotation(FrontTop, 0F, 0F, 0F);\n \n FrontBottom = new ModelRenderer(this, 0, 23);\n FrontBottom.addBox(-8F+xOffset, 8F+yOffset, -3F, 4, 4, 1);\n FrontBottom.setRotationPoint(0F, 0F, 0F);\n FrontBottom.setTextureSize(64, 32);\n FrontBottom.mirror = true;\n setRotation(FrontBottom, 0F, 0F, 0F);\n \n BackTop = new ModelRenderer(this, 11, 12);\n BackTop.addBox(-8F+xOffset, 0F+yOffset, 2F, 4, 4, 1);\n BackTop.setRotationPoint(0F, 0F, 0F);\n BackTop.setTextureSize(64, 32);\n BackTop.mirror = true;\n setRotation(BackTop, 0F, 0F, 0F);\n \n BackBottom = new ModelRenderer(this, 11, 23);\n BackBottom.addBox(-8F+xOffset, 8F+yOffset, 2F, 4, 4, 1);\n BackBottom.setRotationPoint(0F, 0F, 0F);\n BackBottom.setTextureSize(64, 32);\n BackBottom.mirror = true;\n setRotation(BackBottom, 0F, 0F, 0F);\n \n Augment1 = new ModelRenderer(this, 2, 17);\n Augment1.addBox(-7F+xOffset, 4F+yOffset, -3F, 2, 5, 1);\n Augment1.setRotationPoint(0F, 0F, 0F);\n Augment1.setTextureSize(64, 32);\n Augment1.mirror = true;\n setRotation(Augment1, 0F, 0F, 0F);\n \n Augment2 = new ModelRenderer(this, 13, 37);\n Augment2.addBox(-9F+xOffset, 4F+yOffset, -1F, 1, 5, 2);\n Augment2.setRotationPoint(0F, 0F, 0F);\n Augment2.setTextureSize(64, 32);\n Augment2.mirror = true;\n setRotation(Augment2, 0F, 0F, 0F);\n \n Augment3 = new ModelRenderer(this, 13, 17);\n Augment3.addBox(-7F+xOffset, 4F+yOffset, 2F, 2, 5, 1);\n Augment3.setRotationPoint(0F, 0F, 0F);\n Augment3.setTextureSize(64, 32);\n Augment3.mirror = true;\n setRotation(Augment3, 0F, 0F, 0F);\n \n Finger1 = new ModelRenderer(this, 27, 0);\n Finger1.addBox(-8F+xOffset, 12F+yOffset, -2F, 1, 1, 1);\n Finger1.setRotationPoint(0F, 0F, 0F);\n Finger1.setTextureSize(64, 32);\n Finger1.mirror = true;\n setRotation(Finger1, 0.0174533F, 0F, 0F);\n \n Finger1Bottom = new ModelRenderer(this, 27, 2);\n Finger1Bottom.addBox(-11F+xOffset, 10F+yOffset, -2F, 1, 3, 1);\n Finger1Bottom.setRotationPoint(0F, 0F, 0F);\n Finger1Bottom.setTextureSize(64, 32);\n Finger1Bottom.mirror = true;\n setRotation(Finger1Bottom, 0F, 0F, -0.2602503F);\n \n Finger2 = new ModelRenderer(this, 22, 0);\n Finger2.addBox(-8F+xOffset, 12F+yOffset, 1F, 1, 1, 1);\n Finger2.setRotationPoint(0F, 0F, 0F);\n Finger2.setTextureSize(64, 32);\n Finger2.mirror = true;\n setRotation(Finger2, 0.0174533F, 0F, 0F);\n \n Finger2Bottom = new ModelRenderer(this, 22, 2);\n Finger2Bottom.addBox(-11F+xOffset, 10F+yOffset, 1F, 1, 3, 1);\n Finger2Bottom.setRotationPoint(0F, 0F, 0F);\n Finger2Bottom.setTextureSize(64, 32);\n Finger2Bottom.mirror = true;\n setRotation(Finger2Bottom, 0F, 0F, -0.2602503F);\n \n Finger3 = new ModelRenderer(this, 17, 0);\n Finger3.addBox(-5F+xOffset, 12F+yOffset, -1F, 1, 1, 1);\n Finger3.setRotationPoint(0F, 0F, 0F);\n Finger3.setTextureSize(64, 32);\n Finger3.mirror = true;\n setRotation(Finger3, 0.0174533F, 0F, 0F);\n \n Finger3Bottom = new ModelRenderer(this, 17, 2);\n Finger3Bottom.addBox(-2F+xOffset, 12F+yOffset, -1F, 1, 3, 1);\n Finger3Bottom.setRotationPoint(0F, 0F, 0F);\n Finger3Bottom.setTextureSize(64, 32);\n Finger3Bottom.mirror = true;\n setRotation(Finger3Bottom, 0F, 0F, 0.2633485F);\n \n Top = new ModelRenderer(this, 0, 0);\n Top.addBox(-8F+xOffset, -1F+yOffset, -2F, 4, 1, 4);\n Top.setRotationPoint(0F, 0F, 0F);\n Top.setTextureSize(64, 32);\n Top.mirror = true;\n setRotation(Top, 0F, 0F, 0F);\n \n LeftTop = new ModelRenderer(this, 0, 29);\n LeftTop.addBox(-4F+xOffset, 0F+yOffset, -2F, 1, 4, 4);\n LeftTop.setRotationPoint(0F, 0F, 0F);\n LeftTop.setTextureSize(64, 32);\n LeftTop.mirror = true;\n setRotation(LeftTop, 0F, 0F, 0F);\n \n LeftBottom = new ModelRenderer(this, 0, 44);\n LeftBottom.addBox(-4F+xOffset, 8F+yOffset, -2F, 1, 4, 4);\n LeftBottom.setRotationPoint(0F, 0F, 0F);\n LeftBottom.setTextureSize(64, 32);\n LeftBottom.mirror = true;\n setRotation(LeftBottom, 0F, 0F, 0F);\n \n Augment4 = new ModelRenderer(this, 2, 37);\n Augment4.addBox(-4F+xOffset, 4F+yOffset, -1F, 1, 5, 2);\n Augment4.setRotationPoint(0F, 0F, 0F);\n Augment4.setTextureSize(64, 32);\n Augment4.mirror = true;\n setRotation(Augment4, 0F, 0F, 0F);\n \n Bottom = new ModelRenderer(this, 0, 6);\n Bottom.addBox(-8F+xOffset, 11F, -2F, 4, 1, 4);\n Bottom.setRotationPoint(0F, 0F, 0F);\n Bottom.setTextureSize(64, 32);\n Bottom.mirror = true;\n setRotation(Bottom, 0F, 0F, 0F);\n \n this.bipedRightArm.addChild(SideTop);\n this.bipedRightArm.addChild(SideBottom);\n this.bipedRightArm.addChild(FrontTop);\n this.bipedRightArm.addChild(FrontBottom);\n this.bipedRightArm.addChild(BackTop);\n this.bipedRightArm.addChild(BackBottom);\n this.bipedRightArm.addChild(Augment1);\n this.bipedRightArm.addChild(Augment2);\n this.bipedRightArm.addChild(Augment3);\n this.bipedRightArm.addChild(Finger1);\n this.bipedRightArm.addChild(Finger1Bottom);\n this.bipedRightArm.addChild(Finger2);\n this.bipedRightArm.addChild(Finger2Bottom);\n this.bipedRightArm.addChild(Finger3);\n this.bipedRightArm.addChild(Finger3Bottom);\n this.bipedRightArm.addChild(Top);\n this.bipedRightArm.addChild(LeftTop);\n this.bipedRightArm.addChild(LeftBottom);\n this.bipedRightArm.addChild(Augment4);\n }\n \n public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5)\n {\n super.render(entity, f, f1, f2, f3, f4, f5);\n setRotationAngles(f, f1, f2, f3, f4, f5);\n /* \n SideTop.render(f5);\n SideBottom.render(f5);\n FrontTop.render(f5);\n FrontBottom.render(f5);\n BackTop.render(f5);\n BackBottom.render(f5);\n Augment1.render(f5);\n Augment2.render(f5);\n Augment3.render(f5);\n Finger3.render(f5);\n Finger3Bottom.render(f5);\n Finger2.render(f5);\n Finger2Bottom.render(f5);\n Finger3.render(f5);\n Finger3Bottom.render(f5);\n Top.render(f5);\n LeftTop.render(f5);\n LeftBottom.render(f5);\n Augment4.render(f5);\n Bottom.render(f5);\n */\n }\n \n private void setRotation(ModelRenderer model, float x, float y, float z)\n {\n model.rotateAngleX = x;\n model.rotateAngleY = y;\n model.rotateAngleZ = z;\n }\n \n public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5)\n {\n super.setRotationAngles(f, f1, f2, f3, f4, f5, null);\n }\n\n}",
"public class CYBItems {\n public static Item circuit, component, relay;\n public static Item implantEye, implantArm, implantLeg;\n public static Item moduleLexica, moduleActuator;\n public static Item moduleNightvision;\n public static Item moduleBlastResist, moduleProjectileResist, moduleFireResist, moduleArmorPlate;\n\n public static void init() {\n //Materials\n circuit = new Circuit(\"circuit\", \"Circuit\");\n //component = new Component(\"component\", \"Component\");\n //relay = new Relay(\"relay\", \"Relay\");\n\n //Implants\n implantEye = new ImplantCyberneticEye(\"eyeImplant\", \"CyberneticEye\", 1);\n implantArm = new ImplantCyberneticArm(\"armImplant\", \"CyberneticArm\", 1);\n //legImplant = new ImplantCyberneticLeg(\"legImplant\", \"Cybernetic Leg\", 0, 2);\n\n //Modules\n //moduleActuator = new ModuleActuator(\"moduleActuator\", \"Actuator Module\");\n moduleLexica = new ModuleLexica(\"moduleLexica\", \"LexicaCybernetica\");\n\n moduleNightvision = new ModuleNightvision(\"moduleNightvision\", \"NightVisionModule\");\n\n moduleBlastResist = new ModuleBlastResist(\"moduleBlastResist\", \"BlastResistanceModule\");\n moduleFireResist = new ModuleFireResist(\"moduleFireResist\", \"FireResistanceModule\");\n moduleProjectileResist = new ModuleProjectileResist(\"moduleProjectileResist\", \"ProjectileResistanceModule\");\n moduleArmorPlate = new ModuleArmorPlate(\"moduleArmorPlate\", \"ArmorPlateModule\");\n\n }\n\n\t//A helper method called by each item's constructor\n\tpublic static void setItem(Item item, String str, String str2) {\n\t\titem.setUnlocalizedName(str);\n\t\titem.setTextureName(str);\n\t\titem.setCreativeTab(CYBMisc.tab);\n\t\tGameRegistry.registerItem(item, str2, CYBModInfo.MOD_ID);\n\t}\n}",
"public class ModuleArmorPlate extends Module {\n public ModuleArmorPlate(String str, String str2) {\n CYBItems.setItem(this, str, str2);\n this.setCompatibles(EnumSet.allOf(ImplantType.class));\n }\n}",
"public class ModuleBlastResist extends Module {\n public ModuleBlastResist(String str, String str2) {\n CYBItems.setItem(this, str, str2);\n this.setCompatibles(EnumSet.allOf(Implant.ImplantType.class));\n }\n}",
"public class ModuleFireResist extends Module {\n public ModuleFireResist(String str, String str2) {\n CYBItems.setItem(this, str, str2);\n this.setCompatibles(EnumSet.allOf(ImplantType.class));\n }\n}",
"public class ModuleProjectileResist extends Module {\n public ModuleProjectileResist(String str, String str2) {\n CYBItems.setItem(this, str, str2);\n this.setCompatibles(EnumSet.allOf(ImplantType.class));\n }\n}",
"public class MiscUtils {\n /**\n * Helper method to get the texture path of the block/item\n * @param str the block's/item's unlocalized name\n * @return the texture path\n */\n public static String getTexturePath(String str) {\n return CYBModInfo.MOD_ID + \":\" + str;\n }\n}"
] | import com.vivalux.cyb.Cybernetica;
import com.vivalux.cyb.api.Implant;
import com.vivalux.cyb.client.model.ModelArmImplant;
import com.vivalux.cyb.init.CYBItems;
import com.vivalux.cyb.item.module.ModuleArmorPlate;
import com.vivalux.cyb.item.module.ModuleBlastResist;
import com.vivalux.cyb.item.module.ModuleFireResist;
import com.vivalux.cyb.item.module.ModuleProjectileResist;
import com.vivalux.cyb.util.MiscUtils;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World; | package com.vivalux.cyb.item.implant;
public class ImplantCyberneticArm extends Implant {
// this implant provides modules equipped to the arm
public ImplantCyberneticArm(String str, String str2, int renderIndex) {
super(renderIndex, ImplantType.TORSO, 1);
CYBItems.setItem(this, str, str2);
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister reg) {
this.itemIcon = reg.registerIcon(MiscUtils.getTexturePath(this.iconString));
}
@Override
protected void implantTick(World world, EntityPlayer player, ItemStack armor) {
}
@Override
@SideOnly(Side.CLIENT)
public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) {
if ((itemStack != null)) {
if (itemStack.getItem() instanceof ImplantCyberneticArm) {
ModelArmImplant model = (ModelArmImplant) Cybernetica.proxy.modelArm;
model.bipedRightArm.showModel = true;
model.isSneak = entityLiving.isSneaking();
model.isRiding = entityLiving.isRiding();
model.isChild = entityLiving.isChild();
model.heldItemRight = ((EntityPlayer) entityLiving).getCurrentArmor(0) != null ? 1 : 0;
return model;
}
}
return null;
}
@Override
public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) {
return "cybernetica:textures/armour/armImplant.png";
}
@Override
public ArmorProperties getProperties(EntityLivingBase player, ItemStack armor, DamageSource source, double damage, int slot) {
//Depending on modules, this could reduce damage from blast, fire, projectiles, etc
if(Implant.hasInstalledModule(armor, ModuleFireResist.class) && source.isFireDamage()) {
return new ArmorProperties(1, 1, MathHelper.floor_double(damage * .125D));
}
else if (Implant.hasInstalledModule(armor, ModuleBlastResist.class) && source.isExplosion()) {
return new ArmorProperties(1, 1, MathHelper.floor_double(damage * .125D));
}
else if (Implant.hasInstalledModule(armor, ModuleProjectileResist.class) && source.isProjectile()) {
return new ArmorProperties(1, 1, MathHelper.floor_double(damage * .125D));
}
return new ArmorProperties(0, 0, 0);
}
@Override
public int getArmorDisplay(EntityPlayer player, ItemStack armor, int slot) {
//Without the proper modules, this won't provide any armor protection | if (Implant.hasInstalledModule(armor, ModuleArmorPlate.class)) { | 4 |
metamolecular/mx | src/com/metamolecular/mx/test/QueryTest.java | [
"public interface BondMatcher\n{\n public boolean matches(Bond bond);\n}",
"public class DefaultAtomMatcher implements AtomMatcher\n{\n\n private String symbol;\n private int maximumNeighbors;\n\n public DefaultAtomMatcher()\n {\n symbol = null;\n maximumNeighbors = -1;\n }\n\n public DefaultAtomMatcher(Atom atom)\n {\n this();\n\n this.symbol = atom.getSymbol();\n }\n \n public DefaultAtomMatcher(Atom template, int blockedPositions)\n {\n this(template);\n \n this.maximumNeighbors = template.countNeighbors() + template.countVirtualHydrogens() - blockedPositions;\n }\n\n public boolean matches(Atom atom)\n {\n if (!matchSymbol(atom))\n {\n return false;\n }\n\n if (!matchMaximumNeighbors(atom))\n {\n return false;\n }\n \n return true;\n }\n\n public void setMaximumNeighbors(int maximum)\n {\n this.maximumNeighbors = maximum;\n }\n\n public void setSymbol(String symbol)\n {\n this.symbol = symbol;\n }\n\n private boolean matchSymbol(Atom atom)\n {\n if (symbol == null)\n {\n return true;\n }\n\n return symbol.equals(atom.getSymbol());\n }\n\n private boolean matchMaximumNeighbors(Atom atom)\n {\n if (maximumNeighbors == -1)\n {\n return true;\n }\n\n return atom.countNeighbors() <= maximumNeighbors;\n }\n}",
"public class DefaultBondMatcher implements BondMatcher\n{\n private int bondOrder;\n private int unsaturation;\n\n public DefaultBondMatcher()\n {\n this.bondOrder = -1;\n this.unsaturation = -1;\n }\n\n public DefaultBondMatcher(Bond bond)\n {\n this.bondOrder = bond.getType();\n this.unsaturation = getUnsaturation(bond);\n }\n\n public boolean matches(Bond bond)\n {\n if (bondOrder == bond.getType())\n {\n return true;\n }\n \n if (this.unsaturation == getUnsaturation(bond))\n {\n return true;\n }\n \n return false;\n }\n\n private int getUnsaturation(Bond bond)\n {\n return getUnsaturation(bond.getSource()) + getUnsaturation(bond.getTarget());\n }\n\n private int getUnsaturation(Atom atom)\n {\n return atom.getValence() - atom.countNeighbors();\n }\n}",
"public class DefaultQuery implements Query\n{\n private List<Node> nodes;\n private List<Edge> edges;\n\n public DefaultQuery()\n {\n nodes = new ArrayList();\n edges = new ArrayList();\n }\n\n public Iterable<Edge> edges()\n {\n return edges;\n }\n\n public Iterable<Node> nodes()\n {\n return nodes;\n }\n\n public Node getNode(int index)\n {\n return nodes.get(index);\n }\n\n public Edge getEdge(int index)\n {\n return edges.get(index);\n }\n\n public Edge getEdge(Node source, Node target)\n {\n if (source == target)\n {\n return null;\n }\n\n NodeImpl sourceImpl = (NodeImpl) source;\n\n for (Edge edge : sourceImpl.edges)\n {\n if (edge.getSource() == target || edge.getTarget() == target)\n {\n return edge;\n }\n }\n\n return null;\n }\n\n public Node addNode(AtomMatcher matcher)\n {\n NodeImpl node = new NodeImpl(matcher);\n\n nodes.add(node);\n\n return node;\n }\n\n public int countNodes()\n {\n return nodes.size();\n }\n\n public int countEdges()\n {\n return edges.size();\n }\n\n public Edge connect(Node source, Node target, BondMatcher matcher)\n {\n NodeImpl sourceImpl = (NodeImpl) source;\n NodeImpl targetImpl = (NodeImpl) target;\n EdgeImpl edge = new EdgeImpl(sourceImpl, targetImpl, matcher);\n\n sourceImpl.neighbors.add(targetImpl);\n targetImpl.neighbors.add(sourceImpl);\n\n sourceImpl.edges.add(edge);\n targetImpl.edges.add(edge);\n\n edges.add(edge);\n\n return edge;\n }\n\n private class NodeImpl implements Node\n {\n private List<Node> neighbors;\n private List<Edge> edges;\n private AtomMatcher matcher;\n\n private NodeImpl(AtomMatcher matcher)\n {\n edges = new ArrayList();\n neighbors = new ArrayList();\n this.matcher = matcher;\n }\n\n public int countNeighbors()\n {\n return neighbors.size();\n }\n\n public Iterable<Node> neighbors()\n {\n return neighbors;\n }\n\n public AtomMatcher getAtomMatcher()\n {\n return matcher;\n }\n }\n\n private class EdgeImpl implements Edge\n {\n private NodeImpl source;\n private NodeImpl target;\n private BondMatcher matcher;\n\n private EdgeImpl(NodeImpl source, NodeImpl target, BondMatcher matcher)\n {\n this.source = source;\n this.target = target;\n this.matcher = matcher;\n }\n\n public Node getSource()\n {\n return source;\n }\n\n public Node getTarget()\n {\n return target;\n }\n \n public BondMatcher getBondMatcher()\n {\n return matcher;\n }\n }\n}",
"public interface Edge\n{\n public Node getSource();\n \n public Node getTarget();\n \n public BondMatcher getBondMatcher();\n}",
"public interface Node\n{\n public int countNeighbors();\n \n public Iterable<Node> neighbors();\n \n public AtomMatcher getAtomMatcher();\n}"
] | import com.metamolecular.mx.query.Edge;
import com.metamolecular.mx.query.Node;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import com.metamolecular.mx.query.BondMatcher;
import com.metamolecular.mx.query.DefaultAtomMatcher;
import com.metamolecular.mx.query.DefaultBondMatcher;
import com.metamolecular.mx.query.DefaultQuery; | /*
* MX - Essential Cheminformatics
*
* Copyright (c) 2007-2009 Metamolecular, LLC
*
* http://metamolecular.com/mx
*
* 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.metamolecular.mx.test;
/**
* @author Richard L. Apodaca <rapodaca at metamolecular.com>
*/
public class QueryTest extends TestCase
{
private DefaultQuery query;
@Override
protected void setUp() throws Exception
{
query = new DefaultQuery();
}
public void testItShouldHaveOneNodeAfterAddingOne()
{
query.addNode(new DefaultAtomMatcher());
assertEquals(1, query.countNodes());
}
public void testItShouldReturnANodeHavingNoNeighborsAsFirst()
{
Node node = query.addNode(new DefaultAtomMatcher());
assertEquals(0, node.countNeighbors());
}
public void testItShouldReturnANodeWithCorrectAtomMatcherAfterAdding()
{
DefaultAtomMatcher matcher = new DefaultAtomMatcher();
Node node = query.addNode(matcher);
assertEquals(matcher, node.getAtomMatcher());
}
public void testItShouldUpdateNodeNeighborCountAfterConnectingTwoNodes()
{
Node node1 = query.addNode(new DefaultAtomMatcher());
Node node2 = query.addNode(new DefaultAtomMatcher());
| query.connect(node1, node2, new DefaultBondMatcher()); | 2 |
netmelody/ci-eye | src/main/java/org/netmelody/cieye/server/response/CiEyeResourceEngine.java | [
"public final class LandscapeObservation {\n\n private final List<TargetDetail> targets = new ArrayList<TargetDetail>();\n private final Set<Sponsor> dohGroup;\n \n public LandscapeObservation() {\n this(new TargetDetailGroup());\n }\n \n public LandscapeObservation(TargetDetailGroup targets) {\n this(newArrayList(targets.targets()), null);\n }\n \n private LandscapeObservation(Collection<TargetDetail> targets, Set<Sponsor> dohGroup) {\n this.targets.addAll(targets);\n this.dohGroup = (null == dohGroup) ? null : new HashSet<Sponsor>(dohGroup);\n }\n\n public LandscapeObservation add(TargetDetailGroup group) {\n if (null == group) {\n return this;\n }\n final LandscapeObservation result = new LandscapeObservation(targets, dohGroup);\n result.targets.addAll(newArrayList(group.targets()));\n return result;\n }\n\n public List<TargetDetail> targets() {\n return new ArrayList<TargetDetail>(targets);\n }\n \n public Set<Sponsor> dohGroup() {\n return (null == dohGroup) ? new HashSet<Sponsor>() : new HashSet<Sponsor>(dohGroup);\n }\n\n public LandscapeObservation withDoh(Set<Sponsor> dohGroup) {\n return new LandscapeObservation(this.targets, dohGroup);\n }\n\n public LandscapeObservation forSponsor(final Sponsor sponsor) {\n return new LandscapeObservation(filter(targets, onSponsor(sponsor)), dohGroup);\n }\n\n private Predicate<TargetDetail> onSponsor(final Sponsor sponsor) {\n return new Predicate<TargetDetail>() {\n @Override\n public boolean apply(TargetDetail input) {\n return input.sponsors().contains(sponsor);\n }\n };\n }\n\n}",
"public final class LandscapeListResponder implements CiEyeResponder {\n\n private final LandscapeFetcher landscapeFetcher;\n\n public LandscapeListResponder(LandscapeFetcher landscapeFetcher) {\n this.landscapeFetcher = landscapeFetcher;\n }\n\n @Override\n public CiEyeResponse respond(Request request) throws IOException {\n return CiEyeResponse.withJson(new JsonTranslator().toJson(landscapeFetcher.landscapes())).expiringInMillis(10000L);\n }\n}",
"public final class LandscapeObservationResponder implements CiEyeResponder {\r\n\r\n private final CiSpyIntermediary spyIntermediary;\r\n private final Landscape landscape;\r\n private final Prison prison;\r\n private final Function<LandscapeObservation, LandscapeObservation> converter;\r\n\r\n public LandscapeObservationResponder(Landscape landscape, CiSpyIntermediary spyIntermediary, Prison prison) {\r\n this(landscape, spyIntermediary, prison, Functions.<LandscapeObservation>identity());\r\n }\r\n\r\n public LandscapeObservationResponder(Landscape landscape, CiSpyIntermediary spyIntermediary, Prison prison, Function<LandscapeObservation, LandscapeObservation> converter) {\r\n this.landscape = landscape;\r\n this.spyIntermediary = spyIntermediary;\r\n this.prison = prison;\r\n this.converter = converter;\r\n }\r\n\r\n public CiEyeResponse respond(Request request) throws IOException {\r\n LandscapeObservation result = new LandscapeObservation();\r\n long timeToLiveMillis = Long.MAX_VALUE;\r\n for (Feature feature : landscape.features()) {\r\n final TargetGroupBriefing briefing = spyIntermediary.briefingOn(feature);\r\n result = result.add(briefing.status);\r\n timeToLiveMillis = min(timeToLiveMillis, briefing.millisecondsUntilNextUpdate);\r\n }\r\n\r\n if (prison.crimeReported(landscape)) {\r\n result = result.withDoh(prison.prisonersFor(landscape));\r\n }\r\n\r\n return CiEyeResponse.withJson(new JsonTranslator().toJson(converter.apply(result))).expiringInMillis(timeToLiveMillis);\r\n }\r\n}\r",
"public final class NotFoundResponder implements CiEyeResponder {\n\n private static final String CONTENT =\n \"<!DOCTYPE html>\" +\n \"<html>\" +\n \"<body>%s</body>\" +\n \"</html>\";\n\n private static final String BODY = \"Page Not Found. Try <a href=\\\"/\\\">starting from the top<a>\";\n private final String content;\n\n public NotFoundResponder() {\n this(BODY);\n }\n\n public NotFoundResponder(String body) {\n this.content = String.format(CONTENT, body);\n }\n\n @Override\n public CiEyeResponse respond(Request request) throws IOException {\n return CiEyeResponse.withHtml(content).withStatus(Status.NOT_FOUND);\n }\n}",
"public final class TargetNotationHandler implements CiEyeResponder {\n\n private static final Logbook LOG = LogKeeper.logbookFor(TargetNotationHandler.class);\n \n private final RequestOriginTracker tracker;\n private final Landscape landscape;\n private final CiSpyIntermediary spyIntermediary;\n\n public TargetNotationHandler(Landscape landscape, CiSpyIntermediary spyIntermediary, RequestOriginTracker tracker) {\n this.landscape = landscape;\n this.spyIntermediary = spyIntermediary;\n this.tracker = tracker;\n }\n\n private void makeNote(final TargetId targetId, final String note) {\n if (targetId.id() == null || targetId.id().isEmpty()) {\n return;\n }\n\n for (Feature feature : landscape.features()) {\n if (spyIntermediary.passNoteOn(feature, targetId, note)) {\n return;\n }\n LOG.error(\"Failed to handle request to note target \" + targetId.id());\n }\n }\n\n @Override\n public CiEyeResponse respond(Request request) throws IOException {\n try {\n final String targetId = request.getForm().get(\"id\");\n final String note = request.getForm().get(\"note\") + \" by \" + tracker.originOf(request);\n makeNote(new TargetId(targetId), note);\n } catch (Exception e) {\n LOG.error(\"Failed to handle request to note a build\", e);\n }\n return CiEyeResponse.withJson(\"\");\n }\n}"
] | import com.google.common.base.Function;
import org.netmelody.cieye.core.domain.LandscapeObservation;
import org.netmelody.cieye.core.domain.Sponsor;
import org.netmelody.cieye.server.CiEyeNewVersionChecker;
import org.netmelody.cieye.server.CiEyeServerInformationFetcher;
import org.netmelody.cieye.server.CiSpyIntermediary;
import org.netmelody.cieye.server.LandscapeFetcher;
import org.netmelody.cieye.server.PictureFetcher;
import org.netmelody.cieye.server.response.resource.CiEyeResource;
import org.netmelody.cieye.server.response.responder.CiEyeVersionResponder;
import org.netmelody.cieye.server.response.responder.DohHandler;
import org.netmelody.cieye.server.response.responder.FileResponder;
import org.netmelody.cieye.server.response.responder.LandscapeListResponder;
import org.netmelody.cieye.server.response.responder.LandscapeObservationResponder;
import org.netmelody.cieye.server.response.responder.NotFoundResponder;
import org.netmelody.cieye.server.response.responder.PictureResponder;
import org.netmelody.cieye.server.response.responder.RedirectResponder;
import org.netmelody.cieye.server.response.responder.SettingsLocationResponder;
import org.netmelody.cieye.server.response.responder.SponsorResponder;
import org.netmelody.cieye.server.response.responder.TargetNotationHandler;
import org.simpleframework.http.Address;
import org.simpleframework.http.resource.Resource;
import org.simpleframework.http.resource.ResourceEngine; | package org.netmelody.cieye.server.response;
public final class CiEyeResourceEngine implements ResourceEngine {
private final CiSpyIntermediary spyIntermediary;
private final LandscapeFetcher landscapeFetcher;
private final PictureFetcher pictureFetcher;
private final CiEyeServerInformationFetcher configurationFetcher;
private final CiEyeNewVersionChecker updateChecker;
private final RequestOriginTracker tracker;
private final Prison prison = new Prison();
public CiEyeResourceEngine(LandscapeFetcher landscapeFetcher, PictureFetcher pictureFetcher,
CiEyeServerInformationFetcher configurationFetcher,
RequestOriginTracker tracker, CiSpyIntermediary spyIntermediary,
CiEyeNewVersionChecker updateChecker) {
this.landscapeFetcher = landscapeFetcher;
this.pictureFetcher = pictureFetcher;
this.configurationFetcher = configurationFetcher;
this.tracker = tracker;
this.spyIntermediary = spyIntermediary;
this.updateChecker = updateChecker;
}
@Override
public Resource resolve(Address target) {
return new CiEyeResource(route(target));
}
private CiEyeResponder route(Address target) {
final String[] path = target.getPath().getSegments();
if (path.length == 0) {
return new FileResponder("/resources/welcome.html");
}
if (path.length == 1) {
if ("mugshotconfig.html".equals(path[0])) {
return new FileResponder("/resources/mugshotconfig.html");
}
if ("landscapelist.json".equals(path[0])) {
return new LandscapeListResponder(landscapeFetcher);
}
if ("settingslocation.json".equals(path[0])) {
return new SettingsLocationResponder(configurationFetcher);
}
if ("version.json".equals(path[0])) {
return new CiEyeVersionResponder(configurationFetcher, updateChecker);
}
if ("sponsor.json".equals(path[0])) {
return new SponsorResponder(tracker);
}
final String name = "/resources/" + path[0];
if (null != getClass().getResource(name)) {
return new FileResponder(name);
}
}
if (path.length == 2) {
if ("pictures".equals(path[0])) {
return new PictureResponder(pictureFetcher, path[1]);
}
if ("landscapes".equals(path[0])) {
if (!target.getPath().getPath().endsWith("/")) {
return new RedirectResponder(target.getPath().getPath() + "/");
}
return new FileResponder("/resources/cieye.html");
}
}
if (path.length == 3) {
if ("filteredlandscapes".equals(path[0])) {
Sponsor sponsor = tracker.sponsorWith(path[2]);
if (sponsor == null) {
return new NotFoundResponder("Cannot find user " + path[2]);
}
if (!target.getPath().getPath().endsWith("/")) {
return new RedirectResponder(target.getPath().getPath() + "/");
}
return new FileResponder("/resources/cieye.html");
}
if ("landscapes".equals(path[0]) && "landscapeobservation.json".equals(path[2])) {
return new LandscapeObservationResponder(landscapeFetcher.landscapeNamed(path[1]), spyIntermediary, prison);
}
if ("landscapes".equals(path[0]) && "addNote".equals(path[2])) { | return new TargetNotationHandler(landscapeFetcher.landscapeNamed(path[1]), spyIntermediary, tracker); | 4 |
iostackproject/SDGen | src/com/ibm/test/HelloWorldTest.java | [
"public class DatasetCharacterization implements Serializable, Cloneable{\n\n\tprivate static final long serialVersionUID = 1L;\n\n\t/*List of chunk characterization and deduplication ratio of this dataset*/\n\tprivate List<AbstractChunkCharacterization> chunkCharacterization = new ArrayList<>();\n\tprivate double deduplicationRatio = 0.0;\n\t\n\t/*Used to generate synthetic chunks in the same order that they appear in the file*/\n\tprivate transient volatile int circularIndex = 0;\n\t\n\t/*Tokens used to format the persistent form of this object*/\n\tprivate static final String chunkSeparator = \"?\";\n\tprivate static final String lineBreak = \"\\n\";\n\t\n\t/**\n\t * Persistently write the information of a {@link DatasetCharacterization}\n\t * object at disk.\n\t * \n\t * @param filePath\n\t */\n\tpublic void save(String filePath) {\n\t\tBufferedWriter fileOut;\n\t\ttry {\n\t\t\tfileOut = new BufferedWriter(new FileWriter(filePath));\n\t\t\t//Write the deduplication ratio\n\t\t\tfileOut.write(deduplicationRatio + lineBreak);\n\t\t\tfor (AbstractChunkCharacterization c: chunkCharacterization){\n\t\t\t\tc.save(fileOut);\n\t\t\t\tfileOut.write(chunkSeparator + lineBreak);\n\t\t\t}\n\t\t\tfileOut.close();\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\t/**\n\t * Load on this object the characterization stored in the file\n\t * passed by parameter.\n\t * \n\t * @param filePath\n\t */\n\tpublic void load(String filePath) {\n\t\tBufferedReader fileIn = null;\n\t\ttry {\n\t\t\tfileIn = new BufferedReader(new FileReader(filePath));\n\t\t\tString line = \"\";\n\t\t\t//Get the file deduplication ratio\n\t\t\tdeduplicationRatio = Double.valueOf(fileIn.readLine());\n\t\t\t//Load every chunk characterization object\n\t\t\tMotifChunkCharacterization chunk = new MotifChunkCharacterization();\n\t\t\tList<String> chunkInfo = new ArrayList<String>(); \n\t\t\twhile ((line = fileIn.readLine())!=null){\n\t\t\t\tif (line.startsWith(chunkSeparator)){\n\t\t\t\t\tchunk.load(chunkInfo);\n\t\t\t\t\tchunkCharacterization.add(chunk);\n\t\t\t\t\tchunk = new MotifChunkCharacterization();\n\t\t\t\t\tchunkInfo.clear();\n\t\t\t\t}else chunkInfo.add(line);\t\t\t\t\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\t/**\n\t * @return the chunkCharacterization\n\t */\n\tpublic List<AbstractChunkCharacterization> getChunkCharacterization() {\n\t\treturn chunkCharacterization;\n\t}\n\t/**\n\t * @param chunkCharacterization the chunkCharacterization to set\n\t */\n\tpublic void setChunkCharacterization(\n\t\t\tList<AbstractChunkCharacterization> chunkCharacterization) {\n\t\tthis.chunkCharacterization = chunkCharacterization;\n\t}\n\t/**\n\t * @return the deduplicationRatio\n\t */\n\tpublic double getDeduplicationRatio() {\n\t\treturn deduplicationRatio;\n\t}\n\t/**\n\t * @param deduplicationRatio the deduplicationRatio to set\n\t */\n\tpublic void setDeduplicationRatio(double deduplicationRatio) {\n\t\tthis.deduplicationRatio = deduplicationRatio;\n\t}\n\t\n\tpublic synchronized AbstractChunkCharacterization getNextChunkInCircularOrder() {\n\t\treturn chunkCharacterization.get(circularIndex++%chunkCharacterization.size());\n\t}\n\n\t@Override\n\tprotected DatasetCharacterization clone() throws CloneNotSupportedException {\n\t\tDatasetCharacterization clone = new DatasetCharacterization();\n\t\tList<AbstractChunkCharacterization> cloneChunkCharacterization = new ArrayList<>();\n\t\tclone.setDeduplicationRatio(deduplicationRatio);\n\t\tfor (AbstractChunkCharacterization chunk: chunkCharacterization)\n\t\t\tcloneChunkCharacterization.add(chunk.clone());\n\t\tclone.setChunkCharacterization(cloneChunkCharacterization);\n\t\treturn clone;\n\t}\n}",
"public class PropertiesStore {\n\t\n\t@PropertiesHolder(file=\"application.properties\", autoLoad=true)\n\tprivate static Properties appProperties;\n\n\tpublic static String getString(String propName) {\n\t\treturn getAppProperties().getProperty(propName);\n\t}\n\t\n\tpublic static int getInt(String propName) {\n\t\treturn Integer.valueOf(getAppProperties().getProperty(propName));\n\t}\n\t\n\tpublic static double getDouble(String propName) {\n\t\treturn Double.valueOf(getAppProperties().getProperty(propName));\n\t}\n\n\tpublic static boolean getBoolean(String propName) {\n\t\treturn Boolean.valueOf(getAppProperties().getProperty(propName));\n\t}\n\t\n\tpublic static String[] getStrings(String propName) {\n\t\treturn getAppProperties().getProperty(propName).split(\",\");\n\t}\n\t\n\tpublic static Properties getAppProperties() {\n\t\tif (appProperties==null){\n\t\t\ttry {\n\t\t\t\tPropertiesLoader.load();\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn appProperties;\n\t}\n\tprotected static void setAppProperties(Properties appProperties) {\n\t\tPropertiesStore.appProperties = appProperties;\n\t}\n}",
"public class PropertyNames {\n\t\n\tpublic static final String SAMPLING = \"SAMPLING\";\n\tpublic static final String SCAN_COMP_ALG = \"SCAN_COMP_ALG\";\n\tpublic static final String ACCURACY = \"ACCURACY\";\n\tpublic static final String CONFIDENCE = \"CONFIDENCE\";\n\tpublic static final String SCAN_CHUNK_SIZE = \"SCAN_CHUNK_SIZE\";\n\tpublic static final String DATA_GENERATION = \"DATA_GENERATION\";\n\tpublic static final String T_MIN = \"T_MIN\";\n\tpublic static final String T_MAX = \"T_MAX\";\n\tpublic static final String RABIN_WINDOW_SIZE = \"RABIN_WINDOW_SIZE\";\n\tpublic static final String GENERATION_CHUNK_SIZE = \"GENERATION_CHUNK_SIZE\";\n\tpublic static final String ENABLE_DEDUP = \"ENABLE_DEDUP\";\n\tpublic static final String CHUNK_SCANNERS = \"CHUNK_SCANNERS\";\n\tpublic static final String CHUNK_CHARACTERIZATION = \"CHUNK_CHARACTERIZATION\";\n\tpublic static final String TEST_COMPRESSORS = \"TEST_COMPRESSORS\";\n\t\n}",
"public class DataProducer {\n\t\n\tprivate static final String generationPath = \"com.ibm.generation.user.\";\n\t\n\t/*Data structures needed to generate synthetic data*/\n\tprivate DatasetCharacterization characterization;\n\tprivate FitnessProportionateSelection<AbstractChunkCharacterization> dedupSelector = null;\n\tprivate Set<Long> alreadyGeneratedChunk = new HashSet<Long>();\n\tprivate boolean enableDedupGeneration = PropertiesStore.getBoolean(PropertyNames.ENABLE_DEDUP);\n\t\n\t/*Data structures and field for the production process*/\n\tprivate static final int parallelsm = 4;\n\tprivate static final int pollDataTimeoutInSecs = 10;\n\tprivate BlockingQueue<byte[]> dataQueue = new ArrayBlockingQueue<byte[]>(parallelsm);\n\tprivate List<DataProducerTask> producers = new ArrayList<DataProducerTask>();\n\tprivate ExecutorService threadPool = Executors.newFixedThreadPool(parallelsm);\n\tprivate ByteBuffer currentChunk = ByteBuffer.allocate(\n\t\t\tPropertiesStore.getInt(PropertyNames.SCAN_CHUNK_SIZE));\n\t\n\tpublic DataProducer(DatasetCharacterization characterization) {\n\t\tthis.characterization = characterization;\n\t\tif (enableDedupGeneration) initializeDedupSelector();\n\t}\n\n\tpublic void startProducing () {\n\t\tfor (int i=0; i<parallelsm; i++){\n\t\t\tDataProducerTask producer = new DataProducerTask();\n\t\t\tproducers.add(producer);\n\t\t\tthreadPool.execute(producer);\n\t\t}\n\t\t//Initialize first chunk\n\t\ttry {\n\t\t\tcurrentChunk.put(dataQueue.poll(pollDataTimeoutInSecs, TimeUnit.SECONDS));\n\t\t} catch (InterruptedException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tcurrentChunk.position(0);\n\t}\n\t\n\tpublic void endProducing() {\n\t\tSystem.out.println(\"Finishing tasks...\");\n\t\tfor (DataProducerTask task: producers){\n\t\t\ttask.finish = true;\n\t\t}\n\t\tSystem.out.println(\"Clearing queue...\");\n\t\tdataQueue.clear();\t\t\n\t\tSystem.out.println(\"Tearing down pool...\");\n\t\tthreadPool.shutdown();\n\t\tcurrentChunk.clear();\n\t}\n\t/**\n\t * This method return a chunk of synthetic with the same size\n\t * as the characterization specifies.\n\t * \n\t * @return synthetic chunk\n\t */\n\tpublic byte[] getSyntheticData() {\n\t\ttry {\n\t\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\t\tout.write(currentChunk.array());\n\t\t\tcurrentChunk.rewind();\n\t\t\tcurrentChunk.put(dataQueue.poll(pollDataTimeoutInSecs, TimeUnit.SECONDS));\n\t\t\tcurrentChunk.position(0);\n\t\t\treturn out.toByteArray();\n\t\t} catch (InterruptedException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tSystem.err.println(\"No production of data!!\");\n\t\treturn null;\n\t}\n\t/**\n\t * This method produces an arbitrary amount of synthetic data.\n\t * Its use recommended when the size of writes is smaller that the\n\t * average chunk size in the characterization to avoid wasting\n\t * already generated synthetic content. \n\t * \n\t * @param size\n\t * @return synthetic data\n\t */\n\tpublic synchronized byte[] getSyntheticData(int size) {\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\tbyte[] smallWrite = new byte[Math.min(size, currentChunk.remaining())];\n\t\tcurrentChunk.get(smallWrite);\n\t\ttry {\n\t\t\tout.write(smallWrite);\n\t\t\t//Renew the current chunk\n\t\t\tif (!currentChunk.hasRemaining()){ \n\t\t\t\tcurrentChunk.rewind();\n\t\t\t\tcurrentChunk.put(dataQueue.poll(pollDataTimeoutInSecs, TimeUnit.SECONDS));\n\t\t\t\tcurrentChunk.position(0);\n\t\t\t}\n\t\t\t//If there is more data to create, just write more\n\t\t\twhile (out.size() < size)\t\t\n\t\t\t\tout.write(dataQueue.poll(pollDataTimeoutInSecs, TimeUnit.SECONDS));\n\t\t} catch (IOException | InterruptedException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn (out.size()!=size)? Arrays.copyOf(out.toByteArray(), size): out.toByteArray();\n\t}\n\n\tprivate void initializeDedupSelector() {\n\t\tMap<AbstractChunkCharacterization, Long> chunkAndDedupData = new HashMap<>();\n\t\tfor (AbstractChunkCharacterization chunk: characterization.getChunkCharacterization()){\n\t\t\tchunkAndDedupData.put(chunk, (long) chunk.getDeduplicatedData());\n\t\t}\n\t\tdedupSelector = new FitnessProportionateSelection<AbstractChunkCharacterization>(chunkAndDedupData);\n\t}\n\t\n\tprivate class DataProducerTask implements Runnable{\n\t\t\n\t\tboolean finish = false; \n\t\tprivate long deduplicatedData = 0;\n\t\tprivate AbstractDataGeneratorFactory generatorFactory;\n\t\t\n\t\tpublic DataProducerTask() {\n\t\t\ttry {\n\t\t\t\tString generator = PropertiesStore.getString(PropertyNames.DATA_GENERATION);\n\t\t\t\tgeneratorFactory = (AbstractDataGeneratorFactory) \n\t\t\t\t\tClass.forName(generationPath + generator + \"Factory\").newInstance();\n\t\t\t} catch (InstantiationException | IllegalAccessException\n\t\t\t\t\t| ClassNotFoundException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t} \n\t\t}\n\n\t\t@Override\n\t\tpublic void run() {\n\t\t\t/*Producer tasks will run until they are notified to end*/\n\t\t\tRandom random = new Random();\n\t\t\twhile (!finish) {\t\t\t\t\t\t\t\t\n\t\t\t\tAbstractChunkCharacterization chunk = null;\n\t\t\t\t//Decide whether to introduce a deduplicated block or not\n\t\t\t\tboolean deduplicatedChunk = enableDedupGeneration &&\n\t\t\t\t\t\t(random.nextDouble() < characterization.getDeduplicationRatio());\n\t\t\t\t//At the moment, we opt to generate data by doing a circular\n\t\t\t\t//walk over the chunk characterization\n\t\t\t\ttry {\n\t\t\t\t\tif (deduplicatedChunk) {\t\t\t\t\t\n\t\t\t\t\t\tchunk = dedupSelector.generateProportionalKeys();\n\t\t\t\t\t}else {\n\t\t\t\t\t\tchunk = characterization.getNextChunkInCircularOrder();\t\n\t\t\t\t\t\tif (!alreadyGeneratedChunk.contains(chunk.getSeed())){\n\t\t\t\t\t\t\talreadyGeneratedChunk.add(chunk.getSeed());\n\t\t\t\t\t\t\tdeduplicatedChunk = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t//Generate the synthetic data and wait until the queue is free again\n\t\t\t\t\tboolean result = dataQueue.offer(generateData(chunk, deduplicatedChunk), \n\t\t\t\t\t\t\t\t\tLong.MAX_VALUE, TimeUnit.SECONDS);\n\t\t\t\t\tif (!result) System.err.println(\"Problems inserting data in queue!\");\n\t\t\t\t} catch (InterruptedException | DataGenerationException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tSystem.out.println(\"PRODUCED DEDUPLICATED DATA: \" + deduplicatedData);\n\t\t\tSystem.out.println(\"Finishing producer task...\");\n\t\t}\n\t\t\n\t\tprivate byte[] generateData(AbstractChunkCharacterization chunk, boolean deduplicated) {\n\t\t\t//Instantiate the data generator with the appropriate information\n\t\t\tAbstractDataGenerator dataGenerator = generatorFactory.create();\n\t\t\t//Set the info to the data generator for building the synthetic chunk\n\t\t\tdataGenerator.initialize(chunk);\n\t\t\t//Discriminate between deduplicated block or not \n\t\t\treturn dataGenerator.generate(deduplicated);\n\t\t}\t\t\n\t}\n\t\n\t/**\n\t * @return the characterization\n\t */\n\tpublic DatasetCharacterization getCharacterization() {\n\t\treturn characterization;\n\t}\n\n\t/**\n\t * @param characterization the characterization to set\n\t */\n\tpublic void setCharacterization(DatasetCharacterization characterization) {\n\t\tthis.characterization = characterization;\n\t}\n}",
"public class CompressionTimeScanner extends AbstractScanner {\n\n\tprivate static final double ITERATIONS = 5;\n\tprivate FileWriter results = null;\n\tprivate List<AbstractChunkCharacterization> chunks = null;\t\n\t\n\tpublic CompressionTimeScanner(String outputFile, List<AbstractChunkCharacterization> chunks) {\n\t\ttry {\n\t\t\tresults = new FileWriter(outputFile);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tthis.chunks = chunks;\n\t}\n\t\n\t/**\n\t * @param string\n\t */\n\tpublic CompressionTimeScanner(String outputFile) {\n\t\ttry {\n\t\t\tresults = new FileWriter(outputFile);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic void fullScan(String fileName, int regionSize) {\t \n\t\ttry {\t\t\t\n\t\t\tFileInputStream is = new FileInputStream(new File(fileName));\n\t\t byte[] chunk = null;\n\t\t int bytesRead = 0;\n\t\t while (true) {\n\t\t \tif (chunks!=null && !chunks.isEmpty()) \n\t\t \t\tregionSize = chunks.remove(0).getSize();\n\t\t \tchunk = new byte[regionSize];\n\t\t \tbytesRead = is.read(chunk);\n\t\t \tif (bytesRead == -1) break;\n\t\t \tif (bytesRead < chunk.length) \n\t\t \t\tchunk = Arrays.copyOfRange(chunk, 0, bytesRead);\n\t\t \tif (bytesRead > 128) \n\t\t \t\tscan(chunk);\n\t\t }\n\t\t is.close();\n\t\t} catch (FileNotFoundException fileNotFoundException) {\n\t\t fileNotFoundException.printStackTrace();\n\t\t} catch (IOException ioException) {\n\t\t ioException.printStackTrace();\n\t\t}\n\t}\t\n\t\n\t@Override\n\tpublic void scan(byte[] toScan) {\n\t\tList<Double> times = new ArrayList<>();\n\t\t//Add ITERATION samples of compression times\t\t\n\t\tfor (int i=0; i < ITERATIONS; i++){\n\t\t\tList<Double> iterationTimes = TestUtils.calculateCompressionPerformance(toScan);\n\t\t\tif (times.isEmpty()){\n\t\t\t\ttimes.addAll(iterationTimes);\n\t\t\t}else{\n\t\t\t\tfor (int j=0; j < iterationTimes.size();j++)\n\t\t\t\t\ttimes.set(j, times.get(j)+iterationTimes.get(j));\n\t\t\t}\n\t\t}\n\t\t//Divide the accumulated results by ITERATIONS\n\t\tfor (int j=0; j < times.size();j++)\n\t\t\ttimes.set(j, times.get(j)/ITERATIONS);\n\t\tTestUtils.writeTestResults(times, results);\n\t}\n\n\t@Override\n\tpublic void finishScan() {\n\t\ttry {\n\t\t\tresults.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}",
"public class DataScanner extends AbstractScanner{\n\t\n\tprivate static final String scannersPackage = \"com.ibm.scan.user.\"; \n\tprivate static final String characterizationPackage = \"com.ibm.characterization.user.\"; \n\t\n\t/*Chunk granularity of the scan process*/\n\tprivate int chunkSize = PropertiesStore.getInt(PropertyNames.GENERATION_CHUNK_SIZE);\n\tprivate boolean enableDedupGeneration = PropertiesStore.getBoolean(PropertyNames.ENABLE_DEDUP);\n\t\t\t\n\t/*Scanners at chunk and dataset levels*/\n\tprivate List<Class<? extends AbstractChunkScanner>> chunkScannersClasses = \n\t\t\tnew ArrayList<Class<? extends AbstractChunkScanner>>();\n\tprivate Class<? extends AbstractChunkCharacterization> characterizationClass = null;\n\t\n\t/*Scanners and global dataset info*/\n\tprivate ContentBasedChunking globalDeduplicationScanner = new ContentBasedChunking();\n\t\n\tprivate final ForkJoinPool scannerWorkerPool = new ForkJoinPool();\n\t\n\t/*Scan information goes to these fields*/\n\tprivate List<AbstractChunkCharacterization> chunkCharacterization = new ArrayList<>();\n\tprivate double deduplicationRatio = 0.0;\n\t\n\t//For debug purposes\n\tprivate Histogram globalCompressionHistogram = new DoublesHistogram();\n\tprivate Histogram globalRepetitionLengthHistogram = new IntegersHistogram();\n\tprivate Histogram globalSymbolHistogram = new IntegersHistogram();\t\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic DataScanner() {\n\t\tString[] scanners = PropertiesStore.getStrings(PropertyNames.CHUNK_SCANNERS);\n\t\ttry {\n\t\t\tcharacterizationClass = (Class<? extends AbstractChunkCharacterization>) \n\t\t\t\tClass.forName(characterizationPackage + \n\t\t\t\t\tPropertiesStore.getString(PropertyNames.CHUNK_CHARACTERIZATION));\n\t\t\tfor (String scannerName: scanners){\n\t\t\t\tchunkScannersClasses.add((Class<? extends AbstractChunkScanner>) \n\t\t\t\t\tClass.forName(scannersPackage + scannerName));\n\t\t\t}\n\t\t} catch (ClassNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\t/**\n\t * This method takes as input a chunk of data of the original dataset\n\t * to scan. We exploit parallelism by scanning the data with different\n\t * scanners at the same time.\n\t * \n\t * @param data\n\t */\n\t@Override\n\tpublic void scan(byte[] data) {\t\t\n\t\t//Instantiate a new chunk characterization loaded from the configuration\n\t\tAbstractChunkCharacterization chunk = null;\n\t\ttry {\n\t\t\tchunk = (AbstractChunkCharacterization) characterizationClass.newInstance();\n\t\t} catch (InstantiationException | IllegalAccessException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t//Instantiate a list of chunk scanners\n\t\tList<AbstractChunkScanner> chunkScanners = initializeChunkScanners(data);\n\t\t//Execute chunk feature extracting in parallel\n\t\tfor (AbstractChunkScanner scanner: chunkScanners) \n\t\t\tscannerWorkerPool.execute(scanner);\n\t\t//Third, scan for deduplication if necessary\n\t\tif (enableDedupGeneration) \n\t\t\tglobalDeduplicationScanner.digest(data);\n\t\t//Wait for scan termination\n\t\tfor (AbstractChunkScanner scanner: chunkScanners) \n\t\t\tscanner.join();\n\t\t//Set the scan information into the characterization object\t\t\n\t\tfor (AbstractChunkScanner scanner: chunkScanners) \n\t\t\tscanner.setInfo(chunk);\t\t\n\t\tchunk.setSize(data.length);\t\n\t\t//For debug purposes\n\t\tglobalRepetitionLengthHistogram.mergeHistograms(\n\t\t\t\t((MotifChunkCharacterization)chunk).getRepetitionLengthHistogram());\n\t\t//Add chunk to characterization\n\t\tchunkCharacterization.add(chunk);\n\t}\n\t/**\n\t * This function instantiates fresh scanner objects and feeds them with a \n\t * data chunk to be scanned.\n\t * \n\t * @param data\n\t * @return scanners\n\t */\n\tprivate List<AbstractChunkScanner> initializeChunkScanners(byte[] data) {\n\t\tList<AbstractChunkScanner> chunkScanners = new ArrayList<AbstractChunkScanner>();\n\t\tfor (Class<? extends AbstractChunkScanner> scannerClass: chunkScannersClasses){\n\t\t\ttry {\n\t\t\t\tchunkScanners.add((AbstractChunkScanner) \n\t\t\t\t\tscannerClass.getConstructor(byte[].class).newInstance(data));\n\t\t\t} catch (InstantiationException | IllegalAccessException \n\t\t\t\t| IllegalArgumentException | InvocationTargetException | \n\t\t\t\tNoSuchMethodException | SecurityException e) {\n\t\t\t}\n\t\t}\n\t\treturn chunkScanners;\n\t}\n\n\t@Override\n\tpublic void finishScan() {\n\t\tscannerWorkerPool.shutdown();\n\t\tdeduplicationRatio = globalDeduplicationScanner.calculateDeduplicationRatio();\n\t\tsetDeduplicationInfoToChunks();\n\t\t//Delete memory objects related with this scan\n\t\tglobalDeduplicationScanner.reset();\n\t\tSystem.out.println(\"Number of characterization chunks: \" + \n\t\t\t\tchunkCharacterization.size());\n\t}\n\t\n\t/**\n\t * Create a {@link DatasetCharacterization} object representing the\n\t * data scanned.\n\t */\n\tpublic DatasetCharacterization buildCharacterization() {\n\t\tDatasetCharacterization characterization = new DatasetCharacterization();\t\t\n\t\tList<AbstractChunkCharacterization> cloneChunkCharacterization = new ArrayList<>();\n\t\tfor (AbstractChunkCharacterization chunk: chunkCharacterization){\n\t\t\ttry {\n\t\t\t\tcloneChunkCharacterization.add((AbstractChunkCharacterization) chunk.clone());\n\t\t\t} catch (CloneNotSupportedException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tcharacterization.setChunkCharacterization(cloneChunkCharacterization);\n\t\tcharacterization.setDeduplicationRatio(deduplicationRatio);\n\t\treturn characterization;\n\t}\n\t\n\tpublic DatasetCharacterization finishScanAndBuildCharacterization() {\n\t\tfinishScan();\n\t\treturn buildCharacterization();\n\t}\t\n\t\n\tprivate void setDeduplicationInfoToChunks() {\n\t\tIterator<Finger> breakpoints = globalDeduplicationScanner.getBreakpoints().iterator();\n\t\tdouble deduplicatedData = 0.0;\n\t\twhile (breakpoints.hasNext()){\n\t\t\tFinger finger = breakpoints.next();\n\t\t\tlong fingerRepetitions = globalDeduplicationScanner.getFingerprints().get(finger);\n\t\t\tif (fingerRepetitions > 1){\n\t\t\t\tint chunkIndex = (int) (finger.getPosition()/chunkSize);\n\t\t\t\tlong fingerDeduplication = finger.getLength()-(finger.getLength()/fingerRepetitions);\n\t\t\t\tdeduplicatedData += fingerDeduplication;\n\t\t\t\t//Set the position in relative terms\n\t\t\t\tchunkCharacterization.get(chunkIndex).incrementDeduplicatedData((int)fingerDeduplication);\n\t\t\t}\n\t\t}\t\t\n\t\tdeduplicationRatio = globalDeduplicationScanner.calculateDeduplicationRatio();\n\t\tSystem.out.println(\"Deduplicated data: \" + deduplicatedData/(1024.0*1024.0) + \"MB\" +\n\t\t\t\t\" (dedup ratio=\" + deduplicationRatio + \")\");\n\t}\n\t/**\n\t * @return the globalRepetitionLengthHistogram\n\t */\n\tpublic Histogram getGlobalRepetitionLengthHistogram() {\n\t\treturn globalRepetitionLengthHistogram;\n\t}\n\n\t/**\n\t * @param globalRepetitionLengthHistogram the globalRepetitionLengthHistogram to set\n\t */\n\tpublic void setGlobalRepetitionLengthHistogram(\n\t\t\tHistogram globalRepetitionLengthHistogram) {\n\t\tthis.globalRepetitionLengthHistogram = globalRepetitionLengthHistogram;\n\t}\n\n\t/**\n\t * @return the chunkCharacterization\n\t */\n\tpublic List<AbstractChunkCharacterization> getChunkCharacterization() {\n\t\treturn chunkCharacterization;\n\t}\n\n\t/**\n\t * @param chunkCharacterization the chunkCharacterization to set\n\t */\n\tpublic void setChunkCharacterization(\n\t\t\tList<AbstractChunkCharacterization> chunkCharacterization) {\n\t\tthis.chunkCharacterization = chunkCharacterization;\n\t}\n\n\t/**\n\t * @return the globalCompressionHistogram\n\t */\n\tpublic Histogram getGlobalCompressionHistogram() {\n\t\treturn globalCompressionHistogram;\n\t}\n\n\t/**\n\t * @param globalCompressionHistogram the globalCompressionHistogram to set\n\t */\n\tpublic void setGlobalCompressionHistogram(Histogram globalCompressionHistogram) {\n\t\tthis.globalCompressionHistogram = globalCompressionHistogram;\n\t}\n\n\t/**\n\t * @return the globalSymbolHistogram\n\t */\n\tpublic Histogram getGlobalSymbolHistogram() {\n\t\treturn globalSymbolHistogram;\n\t}\n\n\t/**\n\t * @param globalSymbolHistogram the globalSymbolHistogram to set\n\t */\n\tpublic void setGlobalSymbolHistogram(Histogram globalSymbolHistogram) {\n\t\tthis.globalSymbolHistogram = globalSymbolHistogram;\n\t}\t\n\t\n\tpublic double getDeduplicationRatio() {\n\t\treturn deduplicationRatio;\n\t}\n}",
"public class Utils {\n\t\n\tpublic static AbstractCompressionFactory compressorFactory = null;\n\n\tpublic static final String APPLICATION_PATH = \n\t\t\tSystem.getProperty(\"user.dir\") + File.separator;\n\t\n\tstatic {\n\t\t//Initialize the factory with the compression algorithm configured\n\t\ttry {\n\t\t\tcompressorFactory = (AbstractCompressionFactory) Class.forName(\n\t\t\t\t\tAbstractCompression.compressionPackagePath + \n\t\t\t\t\t\tPropertiesStore.getAppProperties().get(\n\t\t\t\t\t\t\tPropertyNames.SCAN_COMP_ALG) + \n\t\t\t\t\t\t\t\t\"CompressionFactory\").newInstance();\n\t\t} catch (InstantiationException | IllegalAccessException\n\t\t\t\t| ClassNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\t\t\n\t}\n\t\n\t/**\n\t * Return a new array from joining two arrays given by parameter.\n\t * @param firstArray\n\t * @param secondArray\n\t * @return\n\t */\n\tpublic static byte[] joinByteArrays(byte[] firstArray, byte[] secondArray){\n\t\tbyte[] jointArray = new byte[firstArray.length+secondArray.length];\n\t\tSystem.arraycopy(firstArray, 0, jointArray, 0, firstArray.length);\n\t\tSystem.arraycopy(secondArray, 0, jointArray, firstArray.length, secondArray.length);\n\t\treturn jointArray;\n\t}\n\t\n\t/**\n\t * Randomly shuffle elements within an array.\n\t * @param array\n\t */\n\tpublic static void shuffle(byte [] array) {\n shuffle(new Random(), array);\n }\n\t\n\t/**\n\t * Randomly shuffle elements within an array.\n\t * @param array\n\t */\n\tpublic static void shuffle(Random random, byte [] array) {\n int count = array.length;\n for (int i = count; i > 1; i--) {\n swap(array, i - 1, random.nextInt(i));\n }\n }\n\t\n\t/**\n\t * Get the size of a file.\n\t * @param fileName\n\t * @return\n\t */\n\tpublic static long getFileSize(String fileName) {\n\t\tFile file = new File(fileName);\n\t\treturn file.length();\n\t}\n\t\n\tpublic static String getApplicationPath() {\n\t\treturn System.getProperty(\"user.dir\") + File.separator;\n\t}\n\t/**\n\t * This function returns the compression ration of two files: the first one\n\t * the original (F_or) and the second one the compressed file (F_com). The \n\t * ratio is defined by F_or/F_com.\n\t * \n\t * @param originalFile\n\t * @param compressedFile\n\t * @return\n\t */\n\tpublic static double getCompressionRatio(String originalFile, String compressedFile){\n\t\tfloat lengthOriginal = (float) Utils.getFileSize(originalFile);\n\t\tfloat lengthCompressed = (float) Utils.getFileSize(compressedFile);\n\t\tif (lengthCompressed > 0.0)\n\t\t\treturn lengthOriginal/lengthCompressed;\n\t\treturn Double.MAX_VALUE;\n\t}\n\t\n\tpublic static void writeDataToFile(byte[] data, String fileName) {\n\t\t// Write random data to a file\n\t\tFileOutputStream fileOutputStream;\n\t\ttry {\n\t\t\tfileOutputStream = new FileOutputStream(new File(fileName));\n\t\t\tint from = 0, to = 0;\n\t\t\tint writeSize = 32*1024;\n\t\t\twhile (from < data.length){\n\t\t\t\tif ((to + writeSize) > data.length){\n\t\t\t\t\tto = data.length;\n\t\t\t\t}else to += writeSize;\n\t\t\t\tfileOutputStream.write(Arrays.copyOfRange(data, from, to));\n\t\t\t\tfrom += writeSize;\n\t\t\t}\n\t\t\tfileOutputStream.close();\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\tpublic static double getCompressionRatio(byte[] original, byte[] compressed) {\n\t\treturn ((double)original.length)/compressed.length;\n\t}\n\tpublic static double compressAndCompare(byte[] data){\n\t\t//Compress File\n\t\tAbstractCompression compressor = compressorFactory.create();\n\t\treturn compressAndCompare(compressor, data);\n\t}\n\t\n\tpublic static void deleteFile(String fileName) {\n\t\tFile file = new File(fileName);\n\t\tfile.delete();\n\t}\n\t\n\tpublic static File[] getDirectoryFiles(String path) {\n\t\tFile folder = new File(path);\n\t\treturn folder.listFiles(); \n\t}\n\t\n /**\n * Shovels all data from an input stream to an output stream.\n */\n public static void shovelInToOut(InputStream in, OutputStream out) throws IOException {\n byte[] buffer = new byte[1000];\n int len;\n while((len = in.read(buffer)) > 0) {\n out.write(buffer, 0, len);\n }\n }\n\t\n\t/**\n * Returns bits of Shanon entropy in a given array of bytes\n * \n * @param data\n * @return bits of entropy\n */\n\tpublic static double getShannonEntropy(byte[] data) {\n Map<Byte, Integer> occ = new HashMap<Byte, Integer>();\n \n for (int b = 0; b < data.length; ++b) {\n \tbyte currentByte = data[b];\n \tif (occ.containsKey(currentByte)) {\n \t\tocc.put(currentByte, occ.get(currentByte) + 1);\n \t} else {\n \t\tocc.put(currentByte, 1);\n \t}\n }\n \n double entropy = 0.0;\n for (Map.Entry<Byte, Integer> entry : occ.entrySet()) {\n \tdouble p = (double) entry.getValue() / data.length;\n \tentropy += p * log2(p);\n }\n return (entropy==0.0) ? 0.0 : -entropy;\n }\n\t\n\t/**\n\t * Save the serialized version of the object in a file.\n\t * \n\t * @param outputFileName\n\t */\n\tpublic static void serializeObject(Object object, String outputFileName){\n\t\ttry {\n\t\t\tFileOutputStream fileOut = new FileOutputStream(outputFileName);\n\t\t\tObjectOutputStream out = new ObjectOutputStream(fileOut);\n\t\t\tout.writeObject(object);\n\t\t\tout.close();\n\t\t\tfileOut.close();\n\t\t} catch (IOException exception) {\n\t\t\texception.printStackTrace();\n\t\t}\n\t}\n\t/**\n\t * Load the characterization from the serialized version stored in a file.\n\t * \n\t * @param inputFileName\n\t * @return\n\t */\n\tpublic static Object deserializeObject(String inputFileName) {\n\t\tObject toLoad = null;\n\t\ttry {\n\t\t\tFileInputStream fileIn = new FileInputStream(inputFileName);\n\t ObjectInputStream in = new ObjectInputStream(fileIn);\n\t toLoad = in.readObject();\n\t in.close();\n\t fileIn.close();\n\t\t}catch(IOException ioException) {\n\t ioException.printStackTrace();\n\t }catch(ClassNotFoundException classNotFoundException) {\n\t classNotFoundException.printStackTrace();\n\t }\n\t\treturn toLoad;\n\t}\n\n\tpublic static double getDeduplicationRatio(Map<Finger, Long> chunksAndRepetitions) {\n\t\tlong deduplicatedData = 0, allData = 0, uniqueChunks = 0, repeatedChunks = 0, allChunks = 0;\n\t\tfor (Finger fingerprint: chunksAndRepetitions.keySet()){\n\t\t\tlong count = chunksAndRepetitions.get(fingerprint);\n\t\t\tif (count > 1){\n\t\t\t\tdeduplicatedData+=(count-1)*fingerprint.getLength();\n\t\t\t\trepeatedChunks+=count-1;\n\t\t\t}\n\t\t\tuniqueChunks+=1;\n\t\t\tallData+=count*fingerprint.getLength();\n\t\t\tallChunks+=count;\n\t\t}\n\t\tdouble dedupRatio = ((double) deduplicatedData)/allData;\n\t\tSystem.out.println(\"Deduplication ratio: \" + dedupRatio);\n\t\tSystem.out.println(\"Unique chunks: \" + uniqueChunks);\n\t\tSystem.out.println(\"Repeated chunks: \" + repeatedChunks);\n\t\tSystem.out.println(\"Deduplicated data: \" + deduplicatedData);\n\t\tSystem.out.println(\"Total chunks: \" + allChunks);\n\t\tSystem.out.println(\"All data: \" + allData);\n\t\treturn dedupRatio;\n\t}\n\t\n\t/**\n\t * @param profilespath\n\t */\n\tpublic static void createDirectory(String directoryName) {\n\t\tFile theDir = new File(directoryName);\n\t\t// if the directory does not exist, create it\n\t\tif (!theDir.exists()) {\n\t\t\tSystem.out.println(\"creating directory: \" + directoryName);\n\t\t\ttheDir.mkdirs(); \n\t\t}\t\t\n\t}\n\t\n //\tPRIVATE FUNCTIONS --\n\t\n\tprivate static double log2(double a) {\n\t\treturn Math.log(a) / Math.log(2);\n\t}\n\t\n private static void swap(byte[] array, int i, int j) {\n byte temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n private static double compressAndCompare(AbstractCompression compressor, byte[] data) {\n \tbyte [] compressedData = compressor.compress(data);\n\t\treturn getCompressionRatio(data, compressedData);\n }\n\n //ACCESS METHODS --\n \n\t/**\n\t * @return the characterizationCompressorFactory\n\t */\n\tpublic static AbstractCompressionFactory getCharacterizationCompressorFactory() {\n\t\treturn compressorFactory;\n\t}\n\t/**\n\t * @param characterizationCompressorFactory the characterizationCompressorFactory to set\n\t */\n\tpublic static void setCharacterizationCompressorFactory(\n\t\t\tAbstractCompressionFactory characterizationCompressorFactory) {\n\t\tUtils.compressorFactory = characterizationCompressorFactory;\n\t}\n}"
] | import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.ibm.characterization.DatasetCharacterization;
import com.ibm.config.PropertiesStore;
import com.ibm.config.PropertyNames;
import com.ibm.generation.DataProducer;
import com.ibm.scan.CompressionTimeScanner;
import com.ibm.scan.DataScanner;
import com.ibm.utils.Utils; | package com.ibm.test;
public class HelloWorldTest {
private static String datasetPath = "path_to_your_dataset";
private static String originalDataset = datasetPath + "LargeCalgaryCorpus.tar";
private static String syntheticDataset = datasetPath + "syntheticDataset";
private static int chunkSize = PropertiesStore.getInt(PropertyNames.GENERATION_CHUNK_SIZE);
public static void main(String[] args) throws IOException {
//1) Scan a dataset. If the dataset is a collection of files, to run this test is better
//to pack them into a .tar fall to do a fair comparison with the synthetic file generated. | DataScanner scanner = new DataScanner(); | 5 |
michaelmarconi/oncue | oncue-tests/src/test/java/oncue/tests/base/DistributedActorSystemTest.java | [
"public abstract class AbstractAgent extends UntypedActor {\n\n\t// The scheduled heartbeat\n\tprivate Cancellable heartbeat;\n\n\t// Map jobs in progress to their workers\n\tprotected Map<String, Job> jobsInProgress = new HashMap<>();\n\n\tprotected LoggingAdapter log = Logging.getLogger(getContext().system(), this);\n\n\tfinal protected Settings settings = SettingsProvider.SettingsProvider\n\t\t\t.get(getContext().system());\n\n\t// A probe for testing\n\tprotected ActorRef testProbe;\n\n\t// The list of worker types this agent can spawn\n\tprivate final Set<String> workerTypes;\n\n\t// A scheduled request for new work\n\tprivate Cancellable workRequest;\n\n\t/**\n\t * An agent must be initialised with a list of worker types it is capable of spawning.\n\t * \n\t * @param workerTypes is a list of Strings that correspond with the classes of available worker\n\t * types.\n\t * \n\t * @throws MissingWorkerException thrown if a class representing a worker cannot be found\n\t */\n\tpublic AbstractAgent(Set<String> workerTypes) {\n\t\tfor(String workerType : workerTypes) {\n\t\t\tif (fetchWorkerClass(workerType.trim()) == null) {\n\t\t\t\tworkerTypes.remove(workerType);\n\t\t\t}\n\t\t}\n\t\tthis.workerTypes = workerTypes;\n\t}\n\n\t/**\n\t * Try to load the Class for the worker of type workerType.\n\t * \n\t * @param workerType\n\t * @return\n\t * @throws MissingWorkerException If the class cannot be instantiated or the class does not\n\t * extend AbstractWorker\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tprivate Class<? extends AbstractWorker> fetchWorkerClass(String workerType) {\n\t\ttry {\n\t\t\treturn (Class<? extends AbstractWorker>) Class.forName(workerType);\n\t\t} catch (ClassNotFoundException e) {\n\t\t\tlog.error(String.format(\"Cannot find a class for the worker type '%s'\", workerType));\n\t\t\treturn null;\n\t\t} catch (ClassCastException e) {\n\t\t\tthrow new IllegalStateException(String.format(\n\t\t\t\t\t\"The class for worker type '%s' doesn't extend the AbstractWorker base class\",\n\t\t\t\t\tworkerType), e);\n\t\t}\n\t}\n\n\t/**\n\t * @return a reference to the scheduler\n\t */\n\tprotected ActorRef getScheduler() {\n\t\ttry {\n\t\t\treturn getContext().actorFor(settings.SCHEDULER_PATH);\n\t\t} catch (NullPointerException e) {\n\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\"Could not get a reference to the Scheduler. Is the system shutting down?\", e);\n\t\t}\n\t}\n\n\t/**\n\t * @return the set of {@linkplain AbstractWorker} types this agent is capable of spawning.\n\t */\n\tpublic Set<String> getWorkerTypes() {\n\t\treturn workerTypes;\n\t}\n\n\tpublic void injectProbe(ActorRef testProbe) {\n\t\tthis.testProbe = testProbe;\n\t}\n\n\t@Override\n\tpublic void onReceive(Object message) {\n\n\t\tif (testProbe != null)\n\t\t\ttestProbe.forward(message, getContext());\n\n\t\tif (message.equals(SimpleMessage.AGENT_REGISTERED)) {\n\t\t\tlog.info(\"Registered with scheduler\");\n\t\t\trequestWork();\n\t\t}\n\n\t\telse if (message instanceof WorkResponse) {\n\t\t\tlog.debug(\"Agent {} got a response to my work request: {}\", getSelf().path().toString(),\n\t\t\t\t\tmessage);\n\t\t\tList<Job> jobs = ((WorkResponse) message).getJobs();\n\t\t\tCollections.sort(jobs, new JobComparator());\n\t\t\tfor (Job job : jobs) {\n\t\t\t\tspawnWorker(job);\n\t\t\t}\n\t\t}\n\n\t\telse if (message instanceof WorkAvailable) {\n\t\t\tWorkAvailable workAvailable = (WorkAvailable) message;\n\t\t\tlog.debug(\"Agent {} found work available for the following worker types: {}\",\n\t\t\t\t\tgetSelf().path().toString(), workAvailable.getWorkerTypes());\n\t\t\tfor (String workerTypeRequired : workAvailable.getWorkerTypes()) {\n\t\t\t\tif (workerTypes.contains(workerTypeRequired)) {\n\t\t\t\t\trequestWork();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\telse if (message instanceof JobProgress) {\n\t\t\tJob job = ((JobProgress) message).getJob();\n\t\t\tlog.debug(\"Worker reported progress of {} on {}\", job.getProgress(), job);\n\t\t\trecordProgress((JobProgress) message, getSender());\n\t\t}\n\n\t\telse {\n\t\t\tlog.error(\"Unrecognised message: {}\", message);\n\t\t\tunhandled(message);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void postStop() {\n\t\tsuper.postStop();\n\t\theartbeat.cancel();\n\t\tif (workRequest != null && !workRequest.isCancelled())\n\t\t\tworkRequest.cancel();\n\t\tlog.info(\"Shut down.\");\n\t}\n\n\t@Override\n\tpublic void preStart() {\n\t\tsuper.preStart();\n\t\tlog.info(\"{} is running with worker types: {}\", getClass().getSimpleName(),\n\t\t\t\tworkerTypes.toString());\n\t\tstartHeartbeat();\n\t}\n\n\t/*\n\t * Tell the agent to begin heartbeating back to the service.\n\t */\n\tpublic void startHeartbeat() {\n\t\tif (heartbeat != null) {\n\t\t\tstopHeartbeat();\n\t\t}\n\n\t\theartbeat = getContext().system().scheduler().schedule(Duration.Zero(),\n\t\t\t\tsettings.AGENT_HEARTBEAT_FREQUENCY, new Runnable() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tgetScheduler().tell(SimpleMessage.AGENT_HEARTBEAT, getSelf());\n\t\t\t\t\t}\n\t\t\t\t}, getContext().dispatcher());\n\t}\n\n\t/**\n\t * Stop the agent from heartbeating. Primarily for use with testing, this is a way to simulate\n\t * network disconnects.\n\t */\n\tpublic void stopHeartbeat() {\n\t\theartbeat.cancel();\n\t}\n\n\t/**\n\t * Note the progress against a job. If it is complete, remove it from the jobs in progress map.\n\t * \n\t * @param jobProgress is the {@linkplain JobProgress} made against a job\n\t * @param worker is the {@linkplain AbstractWorker} completing the job\n\t */\n\tprivate void recordProgress(JobProgress jobProgress, ActorRef worker) {\n\t\tgetScheduler().tell(jobProgress, getSelf());\n\t\tif (jobProgress.getJob().getProgress() == 1.0) {\n\t\t\tjobsInProgress.remove(worker.path().toString());\n\t\t\tscheduleWorkRequest();\n\t\t}\n\t}\n\n\t/**\n\t * Request work from the {@linkplain Scheduler}.\n\t */\n\tprotected abstract void requestWork();\n\n\t/**\n\t * Schedule a work request to take place to allow for a period of quiesence after job\n\t * completion.\n\t */\n\tprivate void scheduleWorkRequest() {\n\t\tif (workRequest != null && !workRequest.isCancelled())\n\t\t\tworkRequest.cancel();\n\n\t\tworkRequest = getContext().system().scheduler().scheduleOnce(Duration.Zero(),\n\t\t\t\tnew Runnable() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\trequestWork();\n\t\t\t\t\t}\n\t\t\t\t}, getContext().dispatcher());\n\t}\n\n\t/**\n\t * Spawn a new worker to complete a job.\n\t * \n\t * @param job is the job that a {@linkplain Worker} should complete.\n\t */\n\t@SuppressWarnings(\"serial\")\n\tprivate void spawnWorker(Job job) {\n\t\tfinal Class<? extends AbstractWorker> workerClass = fetchWorkerClass(job.getWorkerType());\n\n\t\tif (workerClass == null) {\n\t\t\tsendFailure(job, String.format(\"Could not find worker for job type %s\", workerClass));\n\t\t\treturn;\n\t\t}\n\n\t\t// The agent has connected to a scheduler and received a job. If this agent thinks that\n\t\t// it is already running that job then do nothing. This can happen during a network\n\t\t// partition where an agent reconnects and get scheduled the same job that it's already\n\t\t// processing.\n\t\tboolean jobInProgress = false;\n\t\tfor (Job activeJob : jobsInProgress.values()) {\n\t\t\tif (job.getId() == activeJob.getId()) {\n\t\t\t\tjobInProgress = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!jobInProgress) {\n\t\t\tActorRef worker = getContext().actorOf(new Props(new UntypedActorFactory() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic Actor create() throws Exception {\n\t\t\t\t\treturn workerClass.newInstance();\n\t\t\t\t}\n\t\t\t}), \"job-\" + job.getId());\n\t\t\tjobsInProgress.put(worker.path().toString(), job);\n\t\t\tworker.tell(job.clone(), getSelf());\n\t\t} else {\n\t\t\tlog.error(\"Job {} is already in progress. Ignoring scheduler response\", job.getId());\n\t\t}\n\t}\n\n\t/**\n\t * Extract the job failure reason and notify the scheduler that the job failed\n\t * \n\t * @param job\n\t */\n\tprivate void sendFailure(Job job, String message) {\n\t\tjob.setState(State.FAILED);\n\t\tjob.setErrorMessage(\"A worker failed due to \" + message);\n\t\tgetScheduler().tell(new JobFailed(job), getSelf());\n\t}\n\n\t/**\n\t * Allows handling of a worker death. Called when a worker that is owned by this agent has\n\t * thrown an exception.\n\t * \n\t * @param job The job that was in progress\n\t * @param error The Throwable from the worker\n\t */\n\tprotected void onWorkerDeath(Job job, Throwable error) {\n\t\t// Do nothing by default\n\t}\n\n\t/**\n\t * Supervise all workers for unexpected exceptions. When an exception is encountered, tell the\n\t * scheduler about it, stop the worker and remove it from the jobs in progress map.\n\t */\n\t@Override\n\tpublic SupervisorStrategy supervisorStrategy() {\n\t\treturn new OneForOneStrategy(0, Duration.Zero(), new Function<Throwable, Directive>() {\n\n\t\t\t@Override\n\t\t\tpublic Directive apply(Throwable error) {\n\t\t\t\tlog.error(error, \"The worker {} has died a horrible death!\", getSender());\n\t\t\t\tJob job = jobsInProgress.remove(getSender().path().toString());\n\t\t\t\tonWorkerDeath(job, error);\n\t\t\t\tsendFailure(job, error.toString());\n\t\t\t\treturn stop();\n\t\t\t}\n\t\t});\n\t}\n}",
"public class RedisBackingStore extends AbstractBackingStore {\n\n\t/**\n\t * An AutoCloseable wrapper that manages fetching a connection from the redis connection pool\n\t * and safely returning it when finished.\n\t * \n\t * This class proxies methods from Jedis for convenience.\n\t */\n\tpublic static class RedisConnection implements AutoCloseable {\n\n\t\t// A Redis connection pool\n\t\tprivate static JedisPool redisPool;\n\n\t\tprivate Jedis connection;\n\n\t\tpublic RedisConnection() {\n\t\t\tif (redisPool == null) {\n\t\t\t\tredisPool = new JedisPool(new JedisPoolConfig(), host, port,\n\t\t\t\t\t\tProtocol.DEFAULT_TIMEOUT, null);\n\t\t\t}\n\t\t\tthis.connection = redisPool.getResource();\n\t\t}\n\n\t\t@Override\n\t\tpublic void close() {\n\t\t\tthis.connection.close();\n\t\t}\n\n\t\tpublic Long incr(String key) {\n\t\t\treturn this.connection.incr(key);\n\t\t}\n\n\t\tpublic Transaction multi() {\n\t\t\treturn this.connection.multi();\n\t\t}\n\n\t\tpublic void lpush(String key, String value) {\n\t\t\tthis.connection.lpush(key, value);\n\t\t}\n\n\t\tpublic List<String> lrange(String key, int start, int end) {\n\t\t\treturn this.connection.lrange(key, start, end);\n\t\t}\n\n\t\tpublic String hget(String key, String field) {\n\t\t\treturn this.connection.hget(key, field);\n\t\t}\n\n\t\tpublic void hset(String key, String field, String value) {\n\t\t\tthis.connection.hset(key, field, value);\n\t\t}\n\n\t\tpublic void lrem(String key, int count, String value) {\n\t\t\tthis.connection.lrem(key, count, value);\n\t\t}\n\n\t\tpublic void del(String key) {\n\t\t\tthis.connection.del(key);\n\t\t}\n\n\t\tpublic Object rpoplpush(String srckey, String dstkey) {\n\t\t\treturn this.connection.rpoplpush(srckey, dstkey);\n\t\t}\n\n\t\t/**\n\t\t * Flush the entire redis database. This should only be used in tests.\n\t\t */\n\t\tpublic void flushDB() {\n\t\t\tthis.connection.flushDB();\n\t\t}\n\n\t\tpublic boolean exists(String key) {\n\t\t\treturn this.connection.exists(key);\n\t\t}\n\n\t\tpublic Long llen(String key) {\n\t\t\treturn this.connection.llen(key);\n\t\t}\n\n\t\tpublic List<String> brpop(int timeout, String key) {\n\t\t\treturn this.connection.brpop(timeout, key);\n\t\t}\n\t}\n\n\t// Redis host config key\n\tprivate static final String REDIS_HOST = \"oncue.scheduler.backing-store.redis.host\";\n\n\t// Redis port config key\n\tprivate static final String REDIS_PORT = \"oncue.scheduler.backing-store.redis.port\";\n\n\t// Redis port\n\tprivate static int port = Protocol.DEFAULT_PORT;\n\n\t// The jobs that have completed successfully\n\tpublic static final String COMPLETED_JOBS = \"oncue:jobs:complete\";\n\n\t// The jobs that have failed\n\tpublic static final String FAILED_JOBS = \"oncue:jobs:failed\";\n\n\t// Redis host\n\tprivate static String host = \"localhost\";\n\n\t// The total count of persisted jobs\n\tpublic static final String JOB_COUNT_KEY = \"oncue:job_count\";\n\n\t// The time the job was enqueued\n\tpublic static final String JOB_ENQUEUED_AT = \"job_enqueued_at\";\n\n\t// The time the job was started\n\tpublic static final String JOB_STARTED_AT = \"job_started_at\";\n\n\t// The time the job was completed\n\tpublic static final String JOB_COMPLETED_AT = \"job_completed_at\";\n\n\t// The message associated with a failed job\n\tpublic static final String JOB_ERROR_MESSAGE = \"job_failure_message\";\n\n\t// The ID of a job\n\tpublic static final String JOB_ID = \"job_id\";\n\n\t// The key to a particular job\n\tpublic static final String JOB_KEY = \"oncue:jobs:%s\";\n\n\t// The job parameters\n\tpublic static final String JOB_PARAMS = \"job_params\";\n\n\t// The progress against a job\n\tpublic static final String JOB_PROGRESS = \"job_progress\";\n\n\t// The job state\n\tpublic static final String JOB_STATE = \"job_state\";\n\n\t// The worker type assigned to a job\n\tpublic static final String JOB_WORKER_TYPE = \"job_worker_type\";\n\n\t// The re-run status of a job\n\tpublic static final String JOB_RERUN_STATUS = \"job_rerun_status\";\n\n\t/*\n\t * The queue of jobs that acts as an external interface; the scheduler component will watch this\n\t * queue for new jobs\n\t */\n\tpublic static final String NEW_JOBS = \"oncue:jobs:new\";\n\n\t// The scheduled jobs dispatched by the scheduler component\n\tpublic static final String SCHEDULED_JOBS = \"oncue:jobs:scheduled\";\n\n\t// The unscheduled jobs held by the scheduler\n\tpublic static final String UNSCHEDULED_JOBS = \"oncue:jobs:unscheduled\";\n\n\t/**\n\t * Create a new {@linkplain Job} and persist it in Redis\n\t * \n\t * @param workerType is the type of worker required to complete this job\n\t * \n\t * @param params is a map of job parameters\n\t * \n\t * @return a new {@linkplain Job}\n\t */\n\tpublic static Job createJob(String workerType, Map<String, String> params) {\n\t\ttry (RedisConnection redis = new RedisConnection()) {\n\t\t\t// Get the latest job ID\n\t\t\tLong jobId = redis.incr(RedisBackingStore.JOB_COUNT_KEY);\n\n\t\t\t// Create a new job\n\t\t\tJob job = new Job(jobId, workerType);\n\t\t\tif (params != null)\n\t\t\t\tjob.setParams(params);\n\n\t\t\t// Now, persist the job and release the connection\n\t\t\tpersistJob(job, RedisBackingStore.NEW_JOBS, redis);\n\t\t\treturn job;\n\t\t}\n\t}\n\n\t/**\n\t * Construct a job from a given Job ID\n\t * \n\t * @param id is the id of the job\n\t * @param redis is a connection to Redis\n\t * @return a {@linkplain Job} that represents the job hash in Redis\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static Job loadJob(long id, RedisConnection redis) {\n\t\tString jobKey = String.format(JOB_KEY, id);\n\t\tJob job;\n\n\t\ttry {\n\t\t\tDateTime enqueuedAt = DateTime.parse(redis.hget(jobKey, JOB_ENQUEUED_AT));\n\n\t\t\tDateTime startedAt = null;\n\t\t\tString startedAtRaw = redis.hget(jobKey, JOB_STARTED_AT);\n\t\t\tif (startedAtRaw != null)\n\t\t\t\tstartedAt = DateTime.parse(startedAtRaw);\n\n\t\t\tDateTime completedAt = null;\n\t\t\tString completedAtRaw = redis.hget(jobKey, JOB_COMPLETED_AT);\n\t\t\tif (completedAtRaw != null)\n\t\t\t\tcompletedAt = DateTime.parse(completedAtRaw);\n\n\t\t\tString workerType = redis.hget(jobKey, JOB_WORKER_TYPE);\n\t\t\tString state = redis.hget(jobKey, JOB_STATE);\n\t\t\tString progress = redis.hget(jobKey, JOB_PROGRESS);\n\t\t\tString params = redis.hget(jobKey, JOB_PARAMS);\n\t\t\tString errorMessage = redis.hget(jobKey, JOB_ERROR_MESSAGE);\n\t\t\tString rerunStatus = redis.hget(jobKey, JOB_RERUN_STATUS);\n\n\t\t\tjob = new Job(new Long(id), workerType);\n\t\t\tjob.setEnqueuedAt(enqueuedAt);\n\n\t\t\tif (startedAt != null)\n\t\t\t\tjob.setStartedAt(startedAt);\n\n\t\t\tif (completedAt != null)\n\t\t\t\tjob.setCompletedAt(completedAt);\n\n\t\t\tjob.setRerun(Boolean.parseBoolean(rerunStatus));\n\n\t\t\tif (params != null)\n\t\t\t\tjob.setParams((Map<String, String>) JSONValue.parse(params));\n\n\t\t\tif (state != null)\n\t\t\t\tjob.setState(State.valueOf(state.toUpperCase()));\n\n\t\t\tif (progress != null)\n\t\t\t\tjob.setProgress(new Double(progress));\n\n\t\t\tif (errorMessage != null)\n\t\t\t\tjob.setErrorMessage(errorMessage);\n\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(\n\t\t\t\t\tString.format(\"Could not load job with id %s from Redis\", id), e);\n\t\t}\n\n\t\treturn job;\n\t}\n\n\t/**\n\t * Persist a job as a hash in Redis\n\t * \n\t * @param job is the {@linkplain Job} to persist\n\t * @param queueName is the name of the queue to push the job onto\n\t * @param redis is a connection to Redis\n\t */\n\tpublic static void persistJob(Job job, String queueName, RedisConnection redis) {\n\t\t// Persist the job in a transaction\n\t\ttry (Transaction transaction = redis.multi()) {\n\n\t\t\t// Create a map describing the job\n\t\t\tString jobKey = String.format(JOB_KEY, job.getId());\n\t\t\ttransaction.hset(jobKey, JOB_ENQUEUED_AT, job.getEnqueuedAt().toString());\n\n\t\t\tif (job.getStartedAt() != null)\n\t\t\t\ttransaction.hset(jobKey, JOB_STARTED_AT, job.getStartedAt().toString());\n\n\t\t\tif (job.getCompletedAt() != null)\n\t\t\t\ttransaction.hset(jobKey, JOB_COMPLETED_AT, job.getCompletedAt().toString());\n\n\t\t\ttransaction.hset(jobKey, JOB_WORKER_TYPE, job.getWorkerType());\n\t\t\ttransaction.hset(jobKey, JOB_RERUN_STATUS, Boolean.toString(job.isRerun()));\n\n\t\t\tif (job.getParams() != null) {\n\t\t\t\tMap<String, String> params = null;\n\t\t\t\tswitch (job.getState()) {\n\t\t\t\tcase COMPLETE:\n\t\t\t\tcase FAILED:\n\t\t\t\t\tparams = job.getParams(false);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tparams = job.getParams();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ttransaction.hset(jobKey, JOB_PARAMS, JSONValue.toJSONString(params));\n\t\t\t}\n\n\t\t\tif (job.getState() != null)\n\t\t\t\ttransaction.hset(jobKey, JOB_STATE, job.getState().toString());\n\n\t\t\ttransaction.hset(jobKey, JOB_PROGRESS, String.valueOf(job.getProgress()));\n\n\t\t\tif (job.getErrorMessage() != null)\n\t\t\t\ttransaction.hset(jobKey, JOB_ERROR_MESSAGE, job.getErrorMessage());\n\n\t\t\t// Add the job to the specified queue\n\t\t\ttransaction.lpush(queueName, Long.toString(job.getId()));\n\n\t\t\t// Exec the transaction\n\t\t\ttransaction.exec();\n\t\t} catch (IOException e) {\n\t\t\t// Jedis' Transaction.close() method does not actually throw IOException, it just says\n\t\t\t// that it does. In fact it can only throw a JedisConnectionException, an instance of a\n\t\t\t// RuntimeException. Let's wrap this in a JedisException anyway to be sure.\n\t\t\tthrow new JedisException(e);\n\t\t}\n\t}\n\n\t// Logger\n\tprivate LoggingAdapter log;\n\n\tpublic RedisBackingStore(ActorSystem system, Settings settings) {\n\t\tsuper(system, settings);\n\n\t\t/*\n\t\t * Override Redis hostname and port from configuration\n\t\t */\n\t\tConfig config = system.settings().config();\n\t\tif (config.hasPath(REDIS_HOST)) {\n\t\t\thost = config.getString(REDIS_HOST);\n\t\t}\n\t\tif (config.hasPath(REDIS_PORT)) {\n\t\t\tport = config.getInt(REDIS_PORT);\n\t\t}\n\n\t\tlog = Logging.getLogger(system, this);\n\t\tlog.info(\"Backing store expects Redis at: host={}, port={}\", host, port);\n\t}\n\n\t@Override\n\tpublic void addScheduledJobs(List<Job> jobs) {\n\t\ttry (RedisConnection redis = new RedisConnection()) {\n\t\t\tfor (Job job : jobs) {\n\t\t\t\tredis.lpush(SCHEDULED_JOBS, Long.toString(job.getId()));\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void addUnscheduledJob(Job job) {\n\t\ttry (RedisConnection redis = new RedisConnection()) {\n\t\t\tpersistJob(job, UNSCHEDULED_JOBS, redis);\n\t\t}\n\t}\n\n\t@Override\n\tpublic List<Job> getCompletedJobs() {\n\t\tList<Job> jobs = new ArrayList<>();\n\n\t\ttry (RedisConnection redis = new RedisConnection()) {\n\t\t\tList<String> jobIDs = redis.lrange(COMPLETED_JOBS, 0, -1);\n\t\t\tfor (String jobID : jobIDs) {\n\t\t\t\tjobs.add(loadJob(new Long(jobID), redis));\n\t\t\t}\n\t\t}\n\t\treturn jobs;\n\t}\n\n\t@Override\n\tpublic List<Job> getFailedJobs() {\n\t\tList<Job> jobs = new ArrayList<>();\n\t\ttry (RedisConnection redis = new RedisConnection()) {\n\t\t\tList<String> jobIDs = redis.lrange(FAILED_JOBS, 0, -1);\n\t\t\tfor (String jobID : jobIDs) {\n\t\t\t\tjobs.add(loadJob(new Long(jobID), redis));\n\t\t\t}\n\t\t}\n\n\t\treturn jobs;\n\t}\n\n\t@Override\n\tpublic long getNextJobID() {\n\t\ttry (RedisConnection redis = new RedisConnection()) {\n\t\t\t// Increment and return the latest job ID\n\t\t\treturn redis.incr(RedisBackingStore.JOB_COUNT_KEY);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void persistJobFailure(Job job) {\n\t\ttry (RedisConnection redis = new RedisConnection()) {\n\t\t\tpersistJob(job, FAILED_JOBS, redis);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void persistJobProgress(Job job) {\n\t\ttry (RedisConnection redis = new RedisConnection()) {\n\t\t\tString jobKey = String.format(JOB_KEY, job.getId());\n\t\t\tredis.hset(jobKey, JOB_PROGRESS, String.valueOf(job.getProgress()));\n\t\t\tredis.hset(jobKey, JOB_STATE, job.getState().toString());\n\t\t\tif (job.getStartedAt() != null)\n\t\t\t\tredis.hset(jobKey, JOB_STARTED_AT, job.getStartedAt().toString());\n\n\t\t\tif (job.getState() == Job.State.COMPLETE) {\n\t\t\t\tif (job.getCompletedAt() != null)\n\t\t\t\t\tredis.hset(jobKey, JOB_COMPLETED_AT, job.getCompletedAt().toString());\n\t\t\t\tredis.lpush(COMPLETED_JOBS, Long.toString(job.getId()));\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void removeCompletedJobById(long jobId) {\n\t\ttry (RedisConnection redis = new RedisConnection()) {\n\t\t\tredis.lrem(COMPLETED_JOBS, 0, Long.toString(jobId));\n\t\t\tremoveJobById(jobId, redis);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void removeFailedJobById(long jobId) {\n\t\ttry (RedisConnection redis = new RedisConnection()) {\n\t\t\tredis.lrem(FAILED_JOBS, 0, Long.toString(jobId));\n\t\t\tremoveJobById(jobId, redis);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void removeScheduledJobById(long jobId) {\n\t\ttry (RedisConnection redis = new RedisConnection()) {\n\t\t\tredis.lrem(SCHEDULED_JOBS, 0, Long.toString(jobId));\n\t\t}\n\t}\n\n\t@Override\n\tpublic void removeUnscheduledJobById(long jobId) {\n\t\ttry (RedisConnection redis = new RedisConnection()) {\n\t\t\tredis.lrem(UNSCHEDULED_JOBS, 0, Long.toString(jobId));\n\t\t}\n\t}\n\n\tpublic void removeJobById(long jobId, RedisConnection redis) {\n\t\tredis.del(String.format(JOB_KEY, jobId));\n\t}\n\n\t/**\n\t * When restoring the jobs queue, we need to look for all the jobs that were on the scheduler\n\t * jobs queue in Redis, as well as the jobs that had been scheduled against agents, which we\n\t * assume are dead.\n\t */\n\t@Override\n\tpublic List<Job> restoreJobs() {\n\t\tList<Job> jobs = new ArrayList<>();\n\n\t\ttry (RedisConnection redis = new RedisConnection()) {\n\t\t\t// Pop all scheduled jobs back onto the unscheduled jobs queue\n\t\t\twhile (redis.rpoplpush(SCHEDULED_JOBS, UNSCHEDULED_JOBS) != null) {\n\t\t\t}\n\n\t\t\t// Get all the unscheduled jobs\n\t\t\tList<String> jobIDs = redis.lrange(UNSCHEDULED_JOBS, 0, -1);\n\t\t\tfor (String jobID : jobIDs) {\n\t\t\t\tjobs.add(loadJob(new Long(jobID), redis));\n\t\t\t}\n\t\t}\n\n\t\treturn jobs;\n\t}\n\n\t@Override\n\tpublic int cleanupJobs(boolean includeFailedJobs, Duration expirationAge) {\n\t\tint cleanedJobsCount = 0;\n\n\t\tfor (Job completedJob : getCompletedJobs()) {\n\t\t\tDateTime expirationThreshold = DateTime.now().minus(expirationAge.getMillis());\n\t\t\tboolean isExpired = completedJob.getCompletedAt()\n\t\t\t\t\t.isBefore(expirationThreshold.toInstant());\n\t\t\tif (isExpired) {\n\t\t\t\tremoveCompletedJobById(completedJob.getId());\n\t\t\t\tcleanedJobsCount++;\n\t\t\t}\n\t\t}\n\n\t\tif (!includeFailedJobs) {\n\t\t\treturn cleanedJobsCount;\n\t\t}\n\n\t\tfor (Job failedJob : getFailedJobs()) {\n\t\t\tif (failedJob.getCompletedAt() == null) {\n\t\t\t\tlog.error(\n\t\t\t\t\t\t\"Found a failed job with no completion time. Setting completion time to now and defering to next clean up. (\"\n\t\t\t\t\t\t\t\t+ failedJob.toString() + \")\");\n\t\t\t\tfailedJob.setCompletedAt(DateTime.now());\n\t\t\t\tpersistJobFailure(failedJob);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tDateTime expirationThreshold = DateTime.now().minus(expirationAge.getMillis());\n\t\t\tboolean isExpired = failedJob.getCompletedAt()\n\t\t\t\t\t.isBefore(expirationThreshold.toInstant());\n\t\t\tif (isExpired) {\n\t\t\t\tremoveFailedJobById(failedJob.getId());\n\t\t\t\tcleanedJobsCount++;\n\t\t\t}\n\t\t}\n\n\t\treturn cleanedJobsCount;\n\t}\n}",
"public static class RedisConnection implements AutoCloseable {\n\n\t// A Redis connection pool\n\tprivate static JedisPool redisPool;\n\n\tprivate Jedis connection;\n\n\tpublic RedisConnection() {\n\t\tif (redisPool == null) {\n\t\t\tredisPool = new JedisPool(new JedisPoolConfig(), host, port,\n\t\t\t\t\tProtocol.DEFAULT_TIMEOUT, null);\n\t\t}\n\t\tthis.connection = redisPool.getResource();\n\t}\n\n\t@Override\n\tpublic void close() {\n\t\tthis.connection.close();\n\t}\n\n\tpublic Long incr(String key) {\n\t\treturn this.connection.incr(key);\n\t}\n\n\tpublic Transaction multi() {\n\t\treturn this.connection.multi();\n\t}\n\n\tpublic void lpush(String key, String value) {\n\t\tthis.connection.lpush(key, value);\n\t}\n\n\tpublic List<String> lrange(String key, int start, int end) {\n\t\treturn this.connection.lrange(key, start, end);\n\t}\n\n\tpublic String hget(String key, String field) {\n\t\treturn this.connection.hget(key, field);\n\t}\n\n\tpublic void hset(String key, String field, String value) {\n\t\tthis.connection.hset(key, field, value);\n\t}\n\n\tpublic void lrem(String key, int count, String value) {\n\t\tthis.connection.lrem(key, count, value);\n\t}\n\n\tpublic void del(String key) {\n\t\tthis.connection.del(key);\n\t}\n\n\tpublic Object rpoplpush(String srckey, String dstkey) {\n\t\treturn this.connection.rpoplpush(srckey, dstkey);\n\t}\n\n\t/**\n\t * Flush the entire redis database. This should only be used in tests.\n\t */\n\tpublic void flushDB() {\n\t\tthis.connection.flushDB();\n\t}\n\n\tpublic boolean exists(String key) {\n\t\treturn this.connection.exists(key);\n\t}\n\n\tpublic Long llen(String key) {\n\t\treturn this.connection.llen(key);\n\t}\n\n\tpublic List<String> brpop(int timeout, String key) {\n\t\treturn this.connection.brpop(timeout, key);\n\t}\n}",
"public class Settings implements Extension {\n\n\tprivate static final String SCHEDULER_BACKING_STORE_PATH = \"scheduler.backing-store.class\";\n\tpublic final String SCHEDULER_NAME;\n\tpublic final String SCHEDULER_PATH;\n\tpublic final String SCHEDULER_CLASS;\n\tpublic String SCHEDULER_BACKING_STORE_CLASS;\n\tpublic final FiniteDuration SCHEDULER_TIMEOUT;\n\tpublic final FiniteDuration SCHEDULER_BROADCAST_JOBS_FREQUENCY;\n\tpublic final FiniteDuration SCHEDULER_BROADCAST_JOBS_QUIESCENCE_PERIOD;\n\tpublic final FiniteDuration SCHEDULER_MONITOR_AGENTS_FREQUENCY;\n\tpublic final FiniteDuration SCHEDULER_AGENT_HEARTBEAT_TIMEOUT;\n\n\tpublic final FiniteDuration TIMED_JOBS_RETRY_DELAY;\n\n\tpublic final String AGENT_NAME;\n\tpublic final String AGENT_PATH;\n\tpublic final String AGENT_CLASS;\n\tpublic final FiniteDuration AGENT_HEARTBEAT_FREQUENCY;\n\n\tpublic final List<Map<String, Object>> TIMED_JOBS_TIMETABLE;\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Settings(Config config) {\n\n\t\tConfig oncueConfig = config.getConfig(\"oncue\");\n\n\t\tSCHEDULER_NAME = oncueConfig.getString(\"scheduler.name\");\n\t\tSCHEDULER_PATH = oncueConfig.getString(\"scheduler.path\");\n\t\tSCHEDULER_CLASS = oncueConfig.getString(\"scheduler.class\");\n\t\tSCHEDULER_TIMEOUT = Duration\n\t\t\t\t.create(oncueConfig.getMilliseconds(\"scheduler.response-timeout\"), TimeUnit.MILLISECONDS);\n\n\t\tif(oncueConfig.hasPath(SCHEDULER_BACKING_STORE_PATH)) {\n\t\t\tSCHEDULER_BACKING_STORE_CLASS = oncueConfig.getString(SCHEDULER_BACKING_STORE_PATH);\n\t\t} else {\n\t\t\tSCHEDULER_BACKING_STORE_CLASS = null;\n\t\t}\n\n\t\tSCHEDULER_BROADCAST_JOBS_FREQUENCY = Duration.create(\n\t\t\t\toncueConfig.getMilliseconds(\"scheduler.broadcast-jobs-frequency\"), TimeUnit.MILLISECONDS);\n\n\t\tSCHEDULER_BROADCAST_JOBS_QUIESCENCE_PERIOD = Duration.create(\n\t\t\t\toncueConfig.getMilliseconds(\"scheduler.broadcast-jobs-quiescence-period\"), TimeUnit.MILLISECONDS);\n\n\t\tSCHEDULER_MONITOR_AGENTS_FREQUENCY = Duration.create(\n\t\t\t\toncueConfig.getMilliseconds(\"scheduler.monitor-agents-frequency\"), TimeUnit.MILLISECONDS);\n\n\t\tSCHEDULER_AGENT_HEARTBEAT_TIMEOUT = Duration.create(\n\t\t\t\toncueConfig.getMilliseconds(\"scheduler.agent-heartbeat-timeout\"), TimeUnit.MILLISECONDS);\n\n\t\tAGENT_NAME = oncueConfig.getString(\"agent.name\");\n\t\tAGENT_PATH = oncueConfig.getString(\"agent.path\");\n\t\tAGENT_CLASS = oncueConfig.getString(\"agent.class\");\n\t\tAGENT_HEARTBEAT_FREQUENCY = Duration.create(oncueConfig.getMilliseconds(\"agent.heartbeat-frequency\"),\n\t\t\t\tTimeUnit.MILLISECONDS);\n\n\t\tTIMED_JOBS_RETRY_DELAY = Duration.create(oncueConfig.getMilliseconds(\"timed-jobs.retry-delay\"),\n\t\t\t\tTimeUnit.MILLISECONDS);\n\n\t\t// Timed jobs are optional\n\t\tif (oncueConfig.hasPath(\"timed-jobs.timetable\")) {\n\t\t\tTIMED_JOBS_TIMETABLE = (ArrayList<Map<String, Object>>) oncueConfig.getAnyRef(\"timed-jobs.timetable\");\n\t\t} else {\n\t\t\tTIMED_JOBS_TIMETABLE = null;\n\t\t}\n\t}\n}",
"public class SettingsProvider extends AbstractExtensionId<Settings> implements ExtensionIdProvider {\n\tpublic final static SettingsProvider SettingsProvider = new SettingsProvider();\n\n\t@SuppressWarnings(\"static-access\")\n\tpublic SettingsProvider lookup() {\n\t\treturn SettingsProvider.SettingsProvider;\n\t}\n\n\tpublic Settings createExtension(ExtendedActorSystem system) {\n\t\treturn new Settings(system.settings().config());\n\t}\n}",
"public abstract class AbstractScheduler<WorkRequest extends AbstractWorkRequest> extends\n\t\tUntypedActor {\n\n\t// A periodic check for dead agents\n\tprivate Cancellable agentMonitor;\n\n\t// Map an agent to a deadline for deregistration\n\tprivate Map<String, Deadline> agents = new HashMap<>();\n\n\t// Map an agent to a the set of worker types it can process\n\tprivate Map<String, Set<String>> agentWorkers = new HashMap<>();\n\n\t// The persistent backing store\n\tprotected BackingStore backingStore;\n\n\t// A scheduled check for jobs to broadcast\n\tprivate Cancellable jobsBroadcast;\n\n\tprotected LoggingAdapter log = Logging.getLogger(getContext().system(), this);\n\n\t// A flag to indicate that jobs should not be scheduled temporarily\n\tprivate boolean paused = false;\n\n\t// The map of scheduled jobs\n\tprivate ScheduledJobs scheduledJobs;\n\n\tprotected Settings settings = SettingsProvider.SettingsProvider.get(getContext().system());\n\n\t// A probe for testing\n\tprivate ActorRef testProbe;\n\n\t// The queue of unscheduled jobs\n\tprotected UnscheduledJobs unscheduledJobs;\n\n\tpublic List<Job> getScheduledJobs() {\n\t\treturn scheduledJobs.getScheduledJobs();\n\t}\n\n\tpublic int getUnscheduledJobsCount() {\n\t\treturn unscheduledJobs.getSize();\n\t}\n\n\t/**\n\t * @param backingStore is an implementation of {@linkplain BackingStore}\n\t */\n\tpublic AbstractScheduler(Class<? extends BackingStore> backingStore) {\n\n\t\tif (backingStore == null)\n\t\t\tthrow new RuntimeException(\"A backing store implementation must be specified!\");\n\n\t\ttry {\n\t\t\tthis.backingStore = backingStore.getConstructor(ActorSystem.class, Settings.class)\n\t\t\t\t\t.newInstance(getContext().system(), settings);\n\t\t\tunscheduledJobs = new UnscheduledJobs(this.backingStore, log, getComparator());\n\t\t\tscheduledJobs = new ScheduledJobs(this.backingStore);\n\t\t\tlog.info(\"{} is running, backed by {}\", getClass().getSimpleName(),\n\t\t\t\t\tbackingStore.getSimpleName());\n\t\t} catch (InstantiationException | IllegalAccessException | IllegalArgumentException\n\t\t\t\t| InvocationTargetException | NoSuchMethodException | SecurityException e) {\n\t\t\tthrow new ActorInitializationException(getSelf(),\n\t\t\t\t\t\"Failed to create a backing store from class: \" + backingStore.getName(), e);\n\t\t}\n\t}\n\n\tprotected Comparator<Job> getComparator() {\n\t\treturn new JobComparator();\n\t}\n\n\t/**\n\t * While there are jobs in the queue, continue sending a \"Work available\" message to all\n\t * registered agents.\n\t */\n\tprivate void broadcastJobs() {\n\n\t\t/*\n\t\t * Don't broadcast jobs if there are no agents, no more jobs on the unscheduled queue or\n\t\t * scheduling is paused\n\t\t */\n\t\tif (agents.isEmpty() || unscheduledJobs.isEmpty() || paused)\n\t\t\treturn;\n\n\t\tlog.debug(\"Broadcasting jobs\");\n\n\t\tfor (String agent : agents.keySet()) {\n\t\t\tif (testProbe != null)\n\t\t\t\ttestProbe.tell(createWorkAvailable(), getSelf());\n\t\t\tgetContext().actorFor(agent).tell(createWorkAvailable(), getSelf());\n\t\t}\n\n\t\t// Tee-up another broadcast if necessary\n\t\tif (!unscheduledJobs.isEmpty()) {\n\n\t\t\t// Cancel any scheduled broadcast\n\t\t\tif (jobsBroadcast != null)\n\t\t\t\tjobsBroadcast.cancel();\n\n\t\t\tjobsBroadcast = getContext().system().scheduler()\n\t\t\t\t\t.scheduleOnce(settings.SCHEDULER_BROADCAST_JOBS_FREQUENCY, new Runnable() {\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\t\tgetSelf().tell(SimpleMessage.BROADCAST_JOBS, getSelf());\n\t\t\t\t\t\t}\n\t\t\t\t\t}, getContext().dispatcher());\n\t\t}\n\t}\n\n\t/**\n\t * Check to see that each agent has sent a heart beat by the deadline.\n\t */\n\tprivate void checkAgents() {\n\t\tfor (String agent : agents.keySet()) {\n\t\t\tDeadline deadline = agents.get(agent);\n\n\t\t\tif (deadline.isOverdue()) {\n\t\t\t\tlog.error(\"Found a dead agent: '{}'\", agent);\n\n\t\t\t\tif (testProbe != null)\n\t\t\t\t\ttestProbe.tell(SimpleMessage.AGENT_DEAD, getSelf());\n\n\t\t\t\tderegisterAgent(agent);\n\t\t\t\trebroadcastJobs(agent);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * When a job is finished or has failed, it must be removed from the scheduler's records.\n\t * \n\t * @param job is the {@linkplain Job} to clean up after\n\t */\n\tprivate void cleanupJob(Job job, String agent) {\n\t\tlog.debug(\"Cleaning up {} for agent {}\", job, agent);\n\t\tscheduledJobs.removeJobById(job.getId(), agent);\n\t}\n\n\t/**\n\t * Construct a message to advertise the type of work available.\n\t */\n\tprivate WorkAvailable createWorkAvailable() {\n\t\treturn new WorkAvailable(unscheduledJobs.getWorkerTypes());\n\t}\n\n\t/**\n\t * Delete an existing job\n\t * \n\t * @param job is the job to delete\n\t * @return the deleted job\n\t * @throws DeleteJobException if the job is currently running\n\t */\n\tprivate Job deleteJob(Job job) throws DeleteJobException {\n\t\tswitch (job.getState()) {\n\t\tcase RUNNING:\n\t\t\tthrow new DeleteJobException(\"This job cannot be deleted as it is currently running\");\n\t\tcase QUEUED:\n\t\t\tboolean removed = unscheduledJobs.removeJobById(job.getId());\n\t\t\tif (!removed)\n\t\t\t\tthrow new DeleteJobException(\n\t\t\t\t\t\t\"Failed to remove the job from the unscheduled jobs queue\");\n\t\t\tbreak;\n\t\tcase COMPLETE:\n\t\t\tbackingStore.removeCompletedJobById(job.getId());\n\t\t\tbreak;\n\t\tcase FAILED:\n\t\t\tbackingStore.removeFailedJobById(job.getId());\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new DeleteJobException(job.getState().toString()\n\t\t\t\t\t+ \" is an unrecognised job state\");\n\t\t}\n\t\tjob.setState(State.DELETED);\n\t\treturn job;\n\t}\n\n\t/**\n\t * De-register an agent\n\t */\n\tprivate void deregisterAgent(String url) {\n\t\tagents.remove(url);\n\t\tagentWorkers.remove(url);\n\n\t\t// Stop listening to remote events\n\t\tgetContext().system().eventStream().unsubscribe(getContext().actorFor(url));\n\n\t\t// Broadcast agent stopped event\n\t\tAgent agent = new Agent(url);\n\t\tgetContext().system().eventStream().publish(new AgentStoppedEvent(agent));\n\n\t}\n\n\t/**\n\t * Dispatch jobs to agents according to entries in the schedule. This method will also keep\n\t * record of the jobs scheduled to each agent, in case an agent dies.\n\t * \n\t * @param schedule is the {@linkplain Schedule} that maps agents to jobs\n\t */\n\tprotected void dispatchJobs(Schedule schedule) {\n\t\tvalidateSchedule(schedule);\n\t\tfor (Map.Entry<String, WorkResponse> entry : schedule.getEntries()) {\n\t\t\tActorRef agent = getContext().actorFor(entry.getKey());\n\t\t\tWorkResponse workResponse = entry.getValue();\n\n\t\t\t// Assign the jobs to the agent\n\t\t\tunscheduledJobs.removeJobs(workResponse.getJobs());\n\t\t\tscheduledJobs.addJobs(agent.path().toString(), workResponse.getJobs());\n\n\t\t\tlog.debug(\"Sending work response with {} jobs to agent {}\", workResponse.getJobs()\n\t\t\t\t\t.size(), agent.toString());\n\n\t\t\t// Tell the agent about the work\n\t\t\tagent.tell(workResponse, getSelf());\n\t\t}\n\t}\n\n\t/**\n\t * Enqueue a new job\n\t */\n\tprivate Job enqueueJob(EnqueueJob enqueueJob) {\n\t\tJob job = new Job(backingStore.getNextJobID(), enqueueJob.getWorkerType());\n\t\tMap<String, String> jobParams = enqueueJob.getParams();\n\t\tif (jobParams != null) {\n\t\t\tjob.getParams().putAll(jobParams);\n\t\t}\n\t\taugmentJob(job);\n\t\tunscheduledJobs.addJob(job);\n\t\tgetContext().system().eventStream().publish(new JobEnqueuedEvent(job));\n\t\tstartJobsBroadcast();\n\t\treturn job;\n\t}\n\n\t/**\n\t * This method can be overridden by a {@linkplain AbstractScheduler} implementation in order to\n\t * modify the Job object before it is persisted in the list of unscheduled jobs. This allows\n\t * scheduler-implementation-specific metadata to be attached to the job.\n\t * \n\t * @param job The job to modify\n\t */\n\tprotected void augmentJob(Job job) {\n\t\t// NOOP\n\t};\n\n\t/**\n\t * Look through all jobs to find an existing job\n\t * \n\t * @param id is the unique job identifier\n\t * @return the matching job\n\t * @throws JobNotFoundException\n\t */\n\tprivate Job findExistingJob(long id) throws JobNotFoundException {\n\t\tSet<Job> jobs = getAllJobs();\n\t\tfor (Job job : jobs) {\n\t\t\tif (job.getId() == id)\n\t\t\t\treturn job;\n\t\t}\n\t\tthrow new JobNotFoundException(\"Failed to find an existing job with ID \" + id);\n\t}\n\n\t/**\n\t * @return the set of all registered agents\n\t */\n\tprotected Set<String> getAgents() {\n\t\treturn agents.keySet();\n\t}\n\n\t/**\n\t * @return the map of agents to the worker types they can process\n\t */\n\tprotected Map<String, Set<String>> getAgentWorkers() {\n\t\treturn agentWorkers;\n\t}\n\n\t/**\n\t * @return the full set of unscheduled, scheduled, complete and failed jobs\n\t */\n\tprivate Set<Job> getAllJobs() {\n\t\tSet<Job> jobs = new HashSet<>();\n\t\tfor (Iterator<Job> iterator = unscheduledJobs.iterator(); iterator.hasNext();) {\n\t\t\tjobs.add(iterator.next());\n\t\t}\n\t\tjobs.addAll(scheduledJobs.getJobs());\n\t\tjobs.addAll(backingStore.getCompletedJobs());\n\t\tjobs.addAll(backingStore.getFailedJobs());\n\n\t\treturn jobs;\n\t}\n\n\t/**\n\t * Record the details of a failed job\n\t * \n\t * @param jobFailed contains both the failed job and the cause of failure\n\t */\n\tprivate void handleJobFailure(Job job, String agent) {\n\t\tif (backingStore != null)\n\t\t\tbackingStore.persistJobFailure(job);\n\n\t\tcleanupJob(job, agent);\n\n\t\tgetContext().system().eventStream().publish(new JobFailedEvent(job));\n\t}\n\n\t/**\n\t * Record any progress made against a job. If the job is complete, remove it from the jobs\n\t * scheduled against an agent.\n\t * \n\t * @param jobProgress describes the job and associated progress.\n\t */\n\tprivate void handleJobProgress(Job job, String agent) {\n\t\tif (backingStore != null)\n\t\t\tbackingStore.persistJobProgress(job);\n\n\t\tif (job.getProgress() == 1.0) {\n\t\t\tlog.debug(\"{} is complete.\", job);\n\t\t\tcleanupJob(job, agent);\n\t\t} else if (job.getState() != State.QUEUED)\n\t\t\tscheduledJobs.updateJob(job, agent);\n\n\t\tgetContext().system().eventStream().publish(new JobProgressEvent(job));\n\t}\n\n\t/**\n\t * Inject a probe into this actor for testing\n\t * \n\t * @param testProbe is a JavaTestKit probe\n\t */\n\tpublic void injectProbe(ActorRef testProbe) {\n\t\tthis.testProbe = testProbe;\n\t}\n\n\t/**\n\t * Set up a monitor that periodically checks for dead Agents\n\t */\n\tprivate void monitorAgents() {\n\t\tagentMonitor = getContext()\n\t\t\t\t.system()\n\t\t\t\t.scheduler()\n\t\t\t\t.schedule(settings.SCHEDULER_MONITOR_AGENTS_FREQUENCY,\n\t\t\t\t\t\tsettings.SCHEDULER_MONITOR_AGENTS_FREQUENCY, new Runnable() {\n\n\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\t\t\tgetSelf().tell(SimpleMessage.CHECK_AGENTS, getSelf());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}, getContext().dispatcher());\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic void onReceive(Object message) throws Exception {\n\n\t\tif (testProbe != null)\n\t\t\ttestProbe.forward(message, getContext());\n\n\t\tif (message.equals(SimpleMessage.AGENT_HEARTBEAT)) {\n\t\t\tlog.debug(\"Got a heartbeat from agent: '{}'\", getSender());\n\t\t\tregisterAgent(getSender().path().toString());\n\t\t}\n\n\t\telse if (message instanceof RemoteClientShutdown) {\n\t\t\tString system = ((RemoteClientShutdown) message).getRemoteAddress().system();\n\t\t\tif (\"oncue-agent\".equals(system)) {\n\t\t\t\tString agent = ((RemoteClientShutdown) message).getRemoteAddress().toString()\n\t\t\t\t\t\t+ settings.AGENT_PATH;\n\t\t\t\tlog.info(\"Agent '{}' has shut down\", agent);\n\t\t\t\tderegisterAgent(agent);\n\t\t\t\trebroadcastJobs(agent);\n\n\t\t\t\tif (testProbe != null)\n\t\t\t\t\ttestProbe.tell(SimpleMessage.AGENT_SHUTDOWN, getSelf());\n\t\t\t}\n\t\t}\n\n\t\telse if (message.equals(SimpleMessage.CHECK_AGENTS)) {\n\t\t\tlog.debug(\"Checking for dead agents...\");\n\t\t\tcheckAgents();\n\t\t}\n\n\t\telse if (message instanceof EnqueueJob) {\n\t\t\tlog.debug(\"Got a new job to enqueue: {}\", message);\n\t\t\tJob job = enqueueJob((EnqueueJob) message);\n\t\t\tgetSender().tell(job, getSelf());\n\t\t}\n\n\t\telse if (message instanceof RerunJob) {\n\t\t\tlog.debug(\"Got an existing job to re-run: {}\", message);\n\t\t\tJob job = findExistingJob(((RerunJob) message).getId());\n\t\t\tJob rerunJob = rerunJob(job);\n\t\t\tgetSender().tell(rerunJob, getSelf());\n\t\t}\n\n\t\telse if (message instanceof DeleteJob) {\n\t\t\tlog.debug(\"Got an existing job to delete: {}\", message);\n\t\t\tJob job = findExistingJob(((DeleteJob) message).getId());\n\t\t\tJob deleteJob;\n\t\t\ttry {\n\t\t\t\tdeleteJob = deleteJob(job);\n\t\t\t\tgetSender().tell(deleteJob, getSelf());\n\t\t\t} catch (DeleteJobException e) {\n\t\t\t\tlog.error(e, \"Failed to delete job {}\", job.getId());\n\t\t\t\tgetSender().tell(new Failure(e), getSelf());\n\t\t\t}\n\t\t}\n\n\t\telse if (message instanceof CleanupJobs) {\n\t\t\tlog.debug(\"Clean up jobs\");\n\t\t\tCleanupJobs cleanupJobs = (CleanupJobs) message;\n\t\t\tint numCleanedJobs = backingStore.cleanupJobs(cleanupJobs.isIncludeFailedJobs(),\n\t\t\t\t\tcleanupJobs.getExpirationAge());\n\t\t\tgetContext().system().eventStream().publish(new JobCleanupEvent());\n\t\t\tgetSender().tell(new Success(format(\"Removed %d jobs\", numCleanedJobs)), getSelf());\n\t\t}\n\n\t\telse if (message instanceof AbstractWorkRequest) {\n\t\t\tlog.debug(\"Got a work request from agent '{}': {}\", getSender().path().toString(),\n\t\t\t\t\tmessage);\n\t\t\tAbstractWorkRequest workRequest = (AbstractWorkRequest) message;\n\t\t\tagentWorkers.put(getSender().path().toString(), workRequest.getWorkerTypes());\n\t\t\tboolean workAvailable = unscheduledJobs.isWorkAvailable(workRequest.getWorkerTypes());\n\t\t\tif (!workAvailable || paused)\n\t\t\t\treplyWithNoWork(getSender());\n\t\t\telse {\n\t\t\t\tscheduleJobs((WorkRequest) workRequest);\n\t\t\t}\n\t\t}\n\n\t\telse if (message instanceof JobProgress) {\n\t\t\tJob job = ((JobProgress) message).getJob();\n\t\t\tlog.debug(\"Agent reported progress of {} on {}\", job.getProgress(), job);\n\t\t\thandleJobProgress(job, getSender().path().toString());\n\t\t}\n\n\t\telse if (message instanceof JobFailed) {\n\t\t\tJob job = ((JobFailed) message).getJob();\n\t\t\tlog.debug(\"Agent reported a failed job {} ({})\", job, job.getErrorMessage());\n\t\t\thandleJobFailure(job, getSender().path().toString());\n\t\t}\n\n\t\telse if (message == SimpleMessage.JOB_SUMMARY) {\n\t\t\tlog.debug(\"Received a request for a job summary from {}\", getSender());\n\t\t\treplyWithJobSummary();\n\t\t}\n\n\t\telse if (message == SimpleMessage.LIST_AGENTS) {\n\t\t\tlog.debug(\"Received a request for a the list of registered agents from {}\", getSender());\n\t\t\treplyWithAgentSummary();\n\t\t}\n\n\t\telse if (message.equals(SimpleMessage.BROADCAST_JOBS)) {\n\t\t\tlog.debug(\"Teeing up a job broadcast...\");\n\t\t\tbroadcastJobs();\n\t\t}\n\n\t\telse {\n\t\t\tlog.error(\"Unrecognised message: {}\", message);\n\t\t\tunhandled(message);\n\t\t}\n\t}\n\n\t/**\n\t * Pause job scheduling temporarily\n\t */\n\tpublic void pause() {\n\t\tpaused = true;\n\t}\n\n\t@Override\n\tpublic void postStop() {\n\t\tsuper.postStop();\n\n\t\tif (agentMonitor != null)\n\t\t\tagentMonitor.cancel();\n\t\tif (jobsBroadcast != null)\n\t\t\tjobsBroadcast.cancel();\n\n\t\tlog.info(\"Shut down.\");\n\t}\n\n\t@Override\n\tpublic void preStart() {\n\t\tmonitorAgents();\n\t\tsuper.preStart();\n\t}\n\n\t/**\n\t * In the case where an Agent has died or shutdown before completing the jobs assigned to it, we\n\t * need to re-broadcast the jobs so they are run by another agent.\n\t * \n\t * @param agent is the Agent to check for incomplete jobs\n\t */\n\tprivate void rebroadcastJobs(String agent) {\n\t\tif (!scheduledJobs.getJobs(agent).isEmpty()) {\n\n\t\t\t// Grab the list of jobs scheduled for this agent\n\t\t\tList<Job> agentJobs = new ArrayList<>();\n\t\t\tfor (Job scheduledJob : scheduledJobs.getJobs(agent)) {\n\t\t\t\tagentJobs.add(scheduledJob);\n\t\t\t}\n\n\t\t\tfor (Job job : agentJobs) {\n\n\t\t\t\t// Remove job from the agent\n\t\t\t\tscheduledJobs.removeJobById(job.getId(), agent);\n\n\t\t\t\t// Reset job state and progress\n\t\t\t\tjob.setState(State.QUEUED);\n\t\t\t\tjob.setProgress(0);\n\t\t\t\thandleJobProgress(job, agent);\n\n\t\t\t\t// Add jobs back onto the unscheduled queue\n\t\t\t\tunscheduledJobs.addJob(job);\n\t\t\t}\n\t\t}\n\t\tbroadcastJobs();\n\t}\n\n\t/**\n\t * Register the heartbeat of an agent, capturing the heartbeat time as a timestamp. If this is a\n\t * new Agent, return a message indicating that it has been registered.\n\t * \n\t * @param agent is the agent to register\n\t */\n\tprivate void registerAgent(String url) {\n\t\tif (!agents.containsKey(url)) {\n\t\t\tAgent agent = new Agent(url);\n\t\t\tgetContext().actorFor(url).tell(SimpleMessage.AGENT_REGISTERED, getSelf());\n\t\t\tgetContext().system().eventStream().subscribe(getSelf(), RemoteClientShutdown.class);\n\t\t\tgetContext().system().eventStream().publish(new AgentStartedEvent(agent));\n\t\t\tlog.info(\"Registered agent: {}\", url);\n\t\t}\n\n\t\tagents.put(url, settings.SCHEDULER_AGENT_HEARTBEAT_TIMEOUT.fromNow());\n\t}\n\n\t/**\n\t * Reply with the list of registered agents\n\t */\n\tprivate void replyWithAgentSummary() {\n\t\tList<Agent> agents = new ArrayList<>();\n\t\tfor (String url : this.agents.keySet()) {\n\t\t\tAgent agent = new oncue.common.messages.Agent(url);\n\t\t\tagents.add(agent);\n\t\t}\n\t\tgetSender().tell(new AgentSummary(agents), getSelf());\n\t}\n\n\t/**\n\t * Construct and reply with a job summary message\n\t */\n\tprivate void replyWithJobSummary() {\n\t\tgetSender().tell(new JobSummary(getAllJobs()), getSelf());\n\t}\n\n\t/**\n\t * Send a response to the requesting agent containing a {@linkplain WorkResponse} with no jobs.\n\t */\n\tprivate void replyWithNoWork(ActorRef agent) {\n\t\tagent.tell(new WorkResponse(), getSelf());\n\t}\n\n\t/**\n\t * Re-run an existing job\n\t * \n\t * @param job is the job to re-run\n\t */\n\tprivate Job rerunJob(Job job) {\n\t\tJob rerunJob = new Job(job.getId(), job.getWorkerType());\n\t\trerunJob.setParams(job.getParams());\n\t\trerunJob.setRerun(true);\n\n\t\t// TODO Find a way to make this transactional\n\t\tunscheduledJobs.addJob(rerunJob);\n\t\tif (job.getState() == Job.State.COMPLETE)\n\t\t\tbackingStore.removeCompletedJobById(job.getId());\n\t\telse if (job.getState() == Job.State.FAILED)\n\t\t\tbackingStore.removeFailedJobById(job.getId());\n\n\t\tgetContext().system().eventStream().publish(new JobEnqueuedEvent(job));\n\t\tstartJobsBroadcast();\n\t\treturn rerunJob;\n\t}\n\n\t/**\n\t * Create a schedule that maps agents to work responses. Once the schedule has been created, the\n\t * work should be dispatched by calling the <i>dispatchJobs</i> method.\n\t */\n\tprotected abstract void scheduleJobs(WorkRequest workRequest);\n\n\t/**\n\t * Schedule a jobs broadcast. Cancel any previously scheduled broadcast, to ensure quiescence in\n\t * the case where lots of new jobs arrive in a short time.\n\t */\n\tprivate void startJobsBroadcast() {\n\t\tif (jobsBroadcast != null && !jobsBroadcast.isCancelled())\n\t\t\tjobsBroadcast.cancel();\n\n\t\tjobsBroadcast = getContext().system().scheduler()\n\t\t\t\t.scheduleOnce(settings.SCHEDULER_BROADCAST_JOBS_QUIESCENCE_PERIOD, new Runnable() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tgetSelf().tell(SimpleMessage.BROADCAST_JOBS, getSelf());\n\t\t\t\t\t}\n\t\t\t\t}, getContext().dispatcher());\n\t}\n\n\t/**\n\t * Allow the scheduler to continue scheduling jobs.\n\t */\n\tpublic void unpause() {\n\t\tpaused = false;\n\t}\n\n\t/**\n\t * Ensure that the schedule produced by the scheduler is valid, e.g. ensure that no agent is\n\t * scheduled a job it does not have the worker to process.\n\t * \n\t * @param schedule is the {@linkplain Schedule} to validate\n\t */\n\tprivate void validateSchedule(Schedule schedule) {\n\t\tfor (Map.Entry<String, WorkResponse> entry : schedule.getEntries()) {\n\t\t\tString agent = entry.getKey();\n\t\t\tWorkResponse workResponse = entry.getValue();\n\t\t\tfor (Job job : workResponse.getJobs()) {\n\t\t\t\tboolean foundWorkerType = false;\n\t\t\t\tfor (String workerType : agentWorkers.get(agent)) {\n\t\t\t\t\tif (job.getWorkerType().equals(workerType)) {\n\t\t\t\t\t\tfoundWorkerType = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!foundWorkerType)\n\t\t\t\t\tthrow new ScheduleException(\"Agent \" + agent + \" was assigned \"\n\t\t\t\t\t\t\t+ job.toString()\n\t\t\t\t\t\t\t+ \", but does not have a worker capable of processing it!\");\n\t\t\t}\n\t\t}\n\t}\n\n}"
] | import oncue.backingstore.RedisBackingStore.RedisConnection;
import oncue.common.settings.Settings;
import oncue.common.settings.SettingsProvider;
import oncue.scheduler.AbstractScheduler;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import akka.actor.Actor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActorFactory;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import oncue.agent.AbstractAgent;
import oncue.backingstore.RedisBackingStore; | /*******************************************************************************
* Copyright 2013 Michael Marconi
*
* 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 oncue.tests.base;
public abstract class DistributedActorSystemTest {
protected Config serviceConfig;
protected ActorSystem serviceSystem;
protected Settings serviceSettings;
protected LoggingAdapter serviceLog;
protected Config agentConfig;
protected ActorSystem agentSystem;
protected Settings agentSettings;
protected LoggingAdapter agentLog;
/**
* Create an agent component, with a set of workers and an optional probe
*
* @param probe can be null
*/
@SuppressWarnings("serial")
public ActorRef createAgent(final Set<String> workers, final ActorRef probe) {
return agentSystem.actorOf(new Props(new UntypedActorFactory() {
@Override
public Actor create() throws Exception {
AbstractAgent agent = (AbstractAgent) Class.forName(agentSettings.AGENT_CLASS)
.getConstructor(Set.class).newInstance(workers);
if (probe != null)
agent.injectProbe(probe);
return agent;
}
}), agentSettings.AGENT_NAME);
}
/**
* Create a scheduler component, with an optional probe
*
* @param probe can be null
*/
@SuppressWarnings("serial")
public ActorRef createScheduler(final ActorRef probe) {
return serviceSystem.actorOf(new Props(new UntypedActorFactory() {
@Override
public Actor create() throws Exception {
Class<?> schedulerClass = Class.forName(serviceSettings.SCHEDULER_CLASS);
Class<?> backingStoreClass = null;
if (serviceSettings.SCHEDULER_BACKING_STORE_CLASS != null)
backingStoreClass = Class
.forName(serviceSettings.SCHEDULER_BACKING_STORE_CLASS);
@SuppressWarnings("rawtypes")
AbstractScheduler scheduler = (AbstractScheduler) schedulerClass
.getConstructor(Class.class).newInstance(backingStoreClass);
if (probe != null)
scheduler.injectProbe(probe);
return scheduler;
}
}), serviceSettings.SCHEDULER_NAME);
}
@Before
public void startActorSystems() {
/*
* Load configuration specific to this test and fall back to the reference configuration
*/
serviceConfig = ConfigFactory.load();
serviceConfig = ConfigFactory.load(getClass().getSimpleName() + "-Service")
.withFallback(serviceConfig);
agentConfig = ConfigFactory.load();
agentConfig = ConfigFactory.load(getClass().getSimpleName() + "-Agent")
.withFallback(agentConfig);
serviceSystem = ActorSystem.create("oncue-service", serviceConfig);
serviceSettings = SettingsProvider.SettingsProvider.get(serviceSystem);
serviceLog = Logging.getLogger(serviceSystem, this);
agentSystem = ActorSystem.create("oncue-agent", agentConfig);
agentSettings = SettingsProvider.SettingsProvider.get(agentSystem);
agentLog = Logging.getLogger(agentSystem, this);
}
@After
public void stopActorSystems() throws Exception {
serviceSystem.shutdown();
agentSystem.shutdown();
while (!serviceSystem.isTerminated() || !agentSystem.isTerminated()) {
serviceLog.info("Waiting for systems to shut down...");
Thread.sleep(500);
}
serviceLog.debug("Systems shut down");
}
@Before
@After
public void cleanRedis() { | try (RedisConnection redis = new RedisBackingStore.RedisConnection()) { | 2 |
noctarius/castmapr | src/main/java/com/noctarius/castmapr/core/IListNodeMapReduceTaskImpl.java | [
"public interface MapReduceTask<KeyIn, ValueIn, KeyOut, ValueOut>\n extends ExecutableMapReduceTask<KeyIn, ValueIn, KeyOut, ValueOut>\n{\n\n /**\n * Defines the mapper for this task. This method is not idempotent and is callable only one time. If called further\n * times an {@link IllegalStateException} is thrown telling you to not change the internal state.\n * \n * @param mapper The tasks mapper\n * @return The instance of this MapReduceTask with generics changed on usage\n */\n MapReduceTask<KeyOut, List<ValueOut>, KeyOut, ValueOut> mapper( Mapper<KeyIn, ValueIn, KeyOut, ValueOut> mapper );\n\n /**\n * Defines the reducer for this task. This method is not idempotent and is callable only one time. If called further\n * times an {@link IllegalStateException} is thrown telling you to not change the internal state.\n * \n * @param reducer The tasks reducer\n * @return The instance of this MapReduceTask with generics changed on usage\n */\n ReducingMapReduceTask<KeyOut, ValueOut, KeyOut, ValueOut> reducer( Reducer<KeyOut, ValueOut> reducer );\n\n /**\n * Defines keys to execute the mapper and a possibly defined reducer against. If keys are known before submitting\n * the task setting them can improve execution speed.\n * \n * @param keys The keys to be executed against\n * @return The instance of this MapReduceTask with generics changed on usage\n */\n MapReduceTask<KeyIn, ValueIn, KeyOut, ValueOut> onKeys( Iterable<KeyIn> keys );\n\n /**\n * Defines keys to execute the mapper and a possibly defined reducer against. If keys are known before submitting\n * the task setting them can improve execution speed.<br>\n * This method can be used in conjunction with {@link #keyPredicate(KeyPredicate)} to define a range of known and\n * evaluated keys.\n * \n * @param keys The keys to be executed against\n * @return The instance of this MapReduceTask with generics changed on usage\n */\n MapReduceTask<KeyIn, ValueIn, KeyOut, ValueOut> onKeys( KeyIn... keys );\n\n /**\n * Defines the {@link KeyPredicate} implementation to preselect keys the MapReduce task will be executed on.\n * Preselecting keys can speed up the job massively.<br>\n * This method can be used in conjunction with {@link #onKeys(Iterable)} or {@link #onKeys(Object...)} to define a\n * range of known and evaluated keys.\n * \n * @param predicate The predicate implementation to be used to evaluate keys\n * @return The instance of this MapReduceTask with generics changed on usage\n */\n MapReduceTask<KeyIn, ValueIn, KeyOut, ValueOut> keyPredicate( KeyPredicate<KeyIn> predicate );\n\n}",
"public class IListMapReduceOperation<KeyIn, ValueIn, KeyOut, ValueOut>\n extends AbstractMapReduceOperation<KeyIn, ValueIn, KeyOut, ValueOut>\n{\n\n public IListMapReduceOperation()\n {\n }\n\n public IListMapReduceOperation( String name, Mapper<KeyIn, ValueIn, KeyOut, ValueOut> mapper,\n Reducer<KeyOut, ValueOut> reducer )\n {\n super( name, mapper, reducer, null );\n }\n\n @Override\n public void run()\n throws Exception\n {\n CollectionService service = ( (NodeEngineImpl) getNodeEngine() ).getService( CollectionService.SERVICE_NAME );\n CollectionContainer container = getCollectionContainer( service );\n\n ProxyService proxyService = getNodeEngine().getProxyService();\n IList<ValueIn> list = getList( proxyService );\n\n int partitionId = getPartitionId();\n if ( mapper instanceof PartitionIdAware )\n {\n ( (PartitionIdAware) mapper ).setPartitionId( partitionId );\n }\n if ( mapper instanceof IListAware )\n {\n ( (IListAware) mapper ).setMultiMap( list );\n }\n\n Data dataKey = getNodeEngine().toData( name );\n CollectionWrapper collectionWrapper = container.getOrCreateCollectionWrapper( dataKey );\n Collection<CollectionRecord> collection = collectionWrapper.getCollection();\n\n CollectorImpl<KeyOut, ValueOut> collector = new CollectorImpl<KeyOut, ValueOut>();\n\n mapper.initialize( collector );\n for ( CollectionRecord record : collection )\n {\n ValueIn value = (ValueIn) getNodeEngine().toObject( record.getObject() );\n mapper.map( null, value, collector );\n }\n mapper.finalized( collector );\n\n if ( reducer != null )\n {\n if ( reducer instanceof PartitionIdAware )\n {\n ( (PartitionIdAware) reducer ).setPartitionId( partitionId );\n }\n if ( reducer instanceof IListAware )\n {\n ( (IListAware) reducer ).setMultiMap( list );\n }\n Map<KeyOut, ValueOut> reducedResults = new HashMap<KeyOut, ValueOut>( collector.emitted.keySet().size() );\n for ( Entry<KeyOut, List<ValueOut>> entry : collector.emitted.entrySet() )\n {\n reducedResults.put( entry.getKey(), reducer.reduce( entry.getKey(), entry.getValue().iterator() ) );\n }\n response = reducedResults;\n }\n else\n {\n response = collector.emitted;\n }\n }\n\n private IList<ValueIn> getList( ProxyService proxyService )\n {\n CollectionProxyId proxyId =\n new CollectionProxyId( ObjectListProxy.COLLECTION_LIST_NAME, name, CollectionProxyType.LIST );\n return (IList<ValueIn>) proxyService.getDistributedObject( CollectionService.SERVICE_NAME, proxyId );\n }\n\n private CollectionContainer getCollectionContainer( CollectionService collectionService )\n {\n CollectionProxyId proxyId =\n new CollectionProxyId( ObjectListProxy.COLLECTION_LIST_NAME, name, CollectionProxyType.LIST );\n return collectionService.getOrCreateCollectionContainer( getPartitionId(), proxyId );\n }\n}",
"public interface Collator<Key, Value, R>\n{\n\n /**\n * This method is called with the mapped and possibly reduced values from the MapReduce algorithm.\n * \n * @param reducedResults The mapped and possibly reduced intermediate results.\n * @return The collated result.\n */\n R collate( Map<Key, Value> reducedResults );\n\n}",
"public interface KeyPredicate<Key>\n{\n\n /**\n * This methods implementation contains the evaluation code whether to select a key or not.\n * \n * @param key The key to evaluate\n * @return true if the MapReduce task should be executed on this key otherwise false\n */\n boolean evaluate( Key key );\n\n}",
"public interface MapReduceCollatorListener<R>\n{\n\n /**\n * This method is called when a calculation of the {@link MapReduceTask} is finished.\n * \n * @param result The mapped, reduced and collated result.\n */\n void onCompletion( R result );\n\n}",
"public interface MapReduceListener<Key, Value>\n{\n\n /**\n * This method is called when a calculation of the {@link MapReduceTask} is finished.\n * \n * @param reducedResults The mapped and reduced results.\n */\n void onCompletion( Map<Key, Value> reducedResults );\n\n}",
"public interface Reducer<Key, Value>\n extends Serializable\n{\n\n /**\n * The reduce method is called either locally after of intermediate results are retrieved from mapping algorithms or\n * (if the Reducer implementation is distributable - see {@link Distributable} or {@link DistributableReducer}) on\n * the different cluster nodes.<br>\n * <b>Caution: For distributable {@link Reducer}s you need to pay attention that the reducer is executed multiple\n * times and only with intermediate results of one cluster node! This is totally ok for example for sum-algorithms\n * but can be a problem for other kinds!</b><br>\n * {@link Reducer} implementations are never distributed by default - they need to explicitly be marked using the\n * {@link Distributable} annotation or by implementing the {@link DistributableReducer} interface.\n * \n * @param key The reduced key\n * @param values The values corresponding to the reduced key\n * @return The reduced value\n */\n Value reduce( Key key, Iterator<Value> values );\n\n}"
] | import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.MapService;
import com.hazelcast.partition.PartitionService;
import com.hazelcast.spi.NodeEngine;
import com.hazelcast.spi.OperationService;
import com.hazelcast.spi.impl.BinaryOperationFactory;
import com.hazelcast.util.ExceptionUtil;
import com.noctarius.castmapr.MapReduceTask;
import com.noctarius.castmapr.core.operation.IListMapReduceOperation;
import com.noctarius.castmapr.spi.Collator;
import com.noctarius.castmapr.spi.KeyPredicate;
import com.noctarius.castmapr.spi.MapReduceCollatorListener;
import com.noctarius.castmapr.spi.MapReduceListener;
import com.noctarius.castmapr.spi.Reducer; | /*
* 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.noctarius.castmapr.core;
public class IListNodeMapReduceTaskImpl<KeyIn, ValueIn, KeyOut, ValueOut>
extends AbstractMapReduceTask<KeyIn, ValueIn, KeyOut, ValueOut>
{
private final NodeEngine nodeEngine;
public IListNodeMapReduceTaskImpl( String name, NodeEngine nodeEngine, HazelcastInstance hazelcastInstance )
{
super( name, hazelcastInstance );
this.nodeEngine = nodeEngine;
}
/**
* @throws UnsupportedOperationException IList MapReduce tasks do not support keys
*/
@Override | public MapReduceTask<KeyIn, ValueIn, KeyOut, ValueOut> onKeys( Iterable<KeyIn> keys ) | 0 |
loopfz/Lucki | src/shaft/poker/agent/handranges/weightedrange/weighttable/WeightTable.java | [
"public interface IWeightTable {\n \n public double getWeight(Card c1, Card c2);\n \n public void suspendSetWeight(Card c1, Card c2, double weight);\n public void setWeight(Card c1, Card c2, double weight);\n public void setWeight(Rank r1, Rank r2, double weight);\n \n public void initReweight();\n public void consolidate();\n}",
"public class Card implements Comparable<Card> {\n\n public enum Rank {\n DEUCE,\n THREE,\n FOUR,\n FIVE,\n SIX,\n SEVEN,\n EIGHT,\n NINE,\n TEN,\n JACK,\n QUEEN,\n KING,\n ACE\n }\n \n public enum Suit {\n CLUBS,\n SPADES,\n HEARTS,\n DIAMONDS\n }\n \n private final Rank _rank;\n private final Suit _suit;\n private static final List<Card> _values = new ArrayList<Card>(Rank.values().length * Suit.values().length) {\n {\n for (Suit suit : Suit.values()) {\n for (Rank rank : Rank.values()) {\n add(new Card(rank, suit));\n }\n }\n }\n };\n \n public Card(Rank rank, Suit suit) {\n _rank = rank;\n _suit = suit;\n }\n \n @Override\n public String toString() {\n return _rank.toString() + \" of \" + _suit.toString();\n }\n \n public Rank rank() {\n return _rank;\n }\n \n public Suit suit() {\n return _suit;\n }\n \n public static List<Card> values() {\n return _values;\n }\n \n @Override\n public int compareTo(Card o) {\n if (_rank.ordinal() > o._rank.ordinal()) {\n return 1;\n }\n else if (_rank.ordinal() < o._rank.ordinal()) {\n return -1;\n }\n return 0;\n }\n\n}",
"public class Card implements Comparable<Card> {\n\n public enum Rank {\n DEUCE,\n THREE,\n FOUR,\n FIVE,\n SIX,\n SEVEN,\n EIGHT,\n NINE,\n TEN,\n JACK,\n QUEEN,\n KING,\n ACE\n }\n \n public enum Suit {\n CLUBS,\n SPADES,\n HEARTS,\n DIAMONDS\n }\n \n private final Rank _rank;\n private final Suit _suit;\n private static final List<Card> _values = new ArrayList<Card>(Rank.values().length * Suit.values().length) {\n {\n for (Suit suit : Suit.values()) {\n for (Rank rank : Rank.values()) {\n add(new Card(rank, suit));\n }\n }\n }\n };\n \n public Card(Rank rank, Suit suit) {\n _rank = rank;\n _suit = suit;\n }\n \n @Override\n public String toString() {\n return _rank.toString() + \" of \" + _suit.toString();\n }\n \n public Rank rank() {\n return _rank;\n }\n \n public Suit suit() {\n return _suit;\n }\n \n public static List<Card> values() {\n return _values;\n }\n \n @Override\n public int compareTo(Card o) {\n if (_rank.ordinal() > o._rank.ordinal()) {\n return 1;\n }\n else if (_rank.ordinal() < o._rank.ordinal()) {\n return -1;\n }\n return 0;\n }\n\n}",
"public interface IGameEventListener {\n \n public void roundBegin(ITable table, Round r);\n public void roundEnd(ITable table, Round r);\n \n public void newHand(ITable table);\n \n public void newGame(ITable table, int stackSize, int sBlind, int bBlind, List<String> players);\n \n public void winHand(ITable table, IPlayerData data, int amount);\n \n}",
"public interface ITable {\n \n enum ActionType {\n FOLD,\n CALL,\n BET\n }\n \n enum Round {\n PREFLOP,\n FLOP,\n TURN,\n RIVER\n }\n \n public void runGame(int hands, int stackSize, int sBlind, int bBlind);\n \n public int numberBets();\n public int maxBets();\n public int numberCallers();\n public Round round();\n public int potSize();\n \n public int numberPlayers();\n public int numberActivePlayers();\n public int numberPlayersToAct();\n \n public int smallBlind();\n public int bigBlind();\n \n public List<Card> board();\n \n public String playerSmallBlind();\n public String playerBigBlind();\n public String playerDealer();\n \n public void registerListenerForPlayer(String id, IPlayerActionListener listener);\n public void registerPriorityListenerForPlayer(String id, IPlayerActionListener listener);\n public void registerListenAllPlayerEvents(IPlayerActionListener listener);\n public void registerEventListener(IGameEventListener listener);\n\n}",
"public interface ITable {\n \n enum ActionType {\n FOLD,\n CALL,\n BET\n }\n \n enum Round {\n PREFLOP,\n FLOP,\n TURN,\n RIVER\n }\n \n public void runGame(int hands, int stackSize, int sBlind, int bBlind);\n \n public int numberBets();\n public int maxBets();\n public int numberCallers();\n public Round round();\n public int potSize();\n \n public int numberPlayers();\n public int numberActivePlayers();\n public int numberPlayersToAct();\n \n public int smallBlind();\n public int bigBlind();\n \n public List<Card> board();\n \n public String playerSmallBlind();\n public String playerBigBlind();\n public String playerDealer();\n \n public void registerListenerForPlayer(String id, IPlayerActionListener listener);\n public void registerPriorityListenerForPlayer(String id, IPlayerActionListener listener);\n public void registerListenAllPlayerEvents(IPlayerActionListener listener);\n public void registerEventListener(IGameEventListener listener);\n\n}",
"public interface IPlayerData {\n \n public int amountToCall();\n public int betsToCall();\n public double potOdds(int potSize);\n public int moneyInPotForRound();\n public int totalMoneyInPot();\n public int stack();\n public int position();\n public String id();\n}"
] | import shaft.poker.game.ITable.*;
import shaft.poker.game.table.IPlayerData;
import java.util.ArrayList;
import java.util.List;
import shaft.poker.agent.handranges.weightedrange.IWeightTable;
import shaft.poker.game.Card;
import shaft.poker.game.Card.*;
import shaft.poker.game.table.IGameEventListener;
import shaft.poker.game.ITable; | /*
* The MIT License
*
* Copyright 2013 Thomas Schaffer <[email protected]>.
*
* 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 shaft.poker.agent.handranges.weightedrange.weighttable;
/**
*
* @author Thomas Schaffer <[email protected]>
*/
public class WeightTable implements IWeightTable, IGameEventListener {
// Dimensions: [Rank1][Suit1][Rank2][Suit2][Weight]
private double[][][][] _table1;
private double[][][][] _table2;
private double[][][][] _tableFrom;
private double[][][][] _tableTo;
List<WeightChange> _delayedChanges;
public WeightTable(ITable table) {
_table1 = new double[Rank.values().length][Suit.values().length][Rank.values().length][Suit.values().length];
_table2 = new double[Rank.values().length][Suit.values().length][Rank.values().length][Suit.values().length];
_delayedChanges = new ArrayList<>(100);
table.registerEventListener(this);
}
private void setWeight(Rank r1, Suit s1, Rank r2, Suit s2, double weight) {
_tableTo[r1.ordinal()][s1.ordinal()][r2.ordinal()][s2.ordinal()] = weight;
}
@Override
public double getWeight(Card c1, Card c2) {
return _tableFrom[c1.rank().ordinal()][c1.suit().ordinal()][c2.rank().ordinal()][c2.suit().ordinal()];
}
@Override
public void suspendSetWeight(Card c1, Card c2, double weight) {
_delayedChanges.add(new WeightChange(c1, c2, weight));
}
@Override
public void setWeight(Card c1, Card c2, double weight) {
setWeight(c1.rank(), c1.suit(), c2.rank(), c2.suit(), weight);
}
@Override
public void setWeight(Rank r1, Rank r2, double weight) {
for (Suit s1 : Suit.values()) {
for (Suit s2 : Suit.values()) {
if (r1 != r2 || s1 != s2) {
setWeight(r1, s1, r2, s2, weight);
}
}
}
}
@Override
public void initReweight() {
_tableFrom = _table1;
_tableTo = _table2;
}
@Override
public void consolidate() {
_tableFrom = _table2;
for (WeightChange change : _delayedChanges) {
setWeight(change.card1(), change.card2(), change.newWeight());
}
_delayedChanges.clear();
}
@Override
public void roundBegin(ITable table, Round r) {
if (r == Round.PREFLOP) {
for (double[][][] arr1 : _table1) {
for (double[][] arr2 : arr1) {
for (double[] arr3 : arr2) {
for (int i = 0; i < arr3.length; i++) {
arr3[i] = 1.0;
}
}
}
}
}
_tableFrom = _table1;
_tableTo = _table2;
}
@Override
public void roundEnd(ITable table, ITable.Round r) {
double[][][][] tmp = _table1;
_table1 = _table2;
_table2 = tmp;
}
@Override
public void newHand(ITable table) {
}
@Override
public void newGame(ITable table, int stackSize, int sBlind, int bBlind, List<String> players) {
}
@Override | public void winHand(ITable table, IPlayerData data, int amount) { | 6 |
scriptkitty/SNC | unikl/disco/calculator/gui/AddVertexDialog.java | [
"public class SNC {\r\n\r\n private final UndoRedoStack undoRedoStack;\r\n private static SNC singletonInstance;\r\n private final List<Network> networks;\r\n private final int currentNetworkPosition;\r\n\r\n private SNC() {\r\n networks = new ArrayList<>();\r\n undoRedoStack = new UndoRedoStack();\r\n networks.add(new Network()); // Create an initially empty Network\r\n currentNetworkPosition = 0;\r\n }\r\n\r\n /**\r\n * Returns the singleton instance, creates a new one if none exists\r\n *\r\n * @return\r\n */\r\n public static SNC getInstance() {\r\n if (singletonInstance == null) {\r\n singletonInstance = new SNC();\r\n }\r\n return singletonInstance;\r\n }\r\n\r\n /**\r\n * The main method of the program, used to start the GUI and initialize\r\n * everything\r\n *\r\n * @param args Command line arguments - not used at the moment\r\n * @throws InvocationTargetException\r\n * @throws InterruptedException\r\n * @throws ArrivalNotAvailableException\r\n * @throws BadInitializationException\r\n * @throws DeadlockException\r\n * @throws ThetaOutOfBoundException\r\n * @throws ParameterMismatchException\r\n * @throws ServerOverloadException\r\n */\r\n public static void main(String[] args) throws InvocationTargetException, InterruptedException,\r\n ArrivalNotAvailableException, BadInitializationException, DeadlockException, ThetaOutOfBoundException,\r\n ParameterMismatchException, ServerOverloadException {\r\n\r\n SNC snc = SNC.getInstance();\r\n final MainWindow main = new MainWindow();\r\n\r\n Runnable runnable = new Runnable() {\r\n @Override\r\n public void run() {\r\n main.createGUI();\r\n }\r\n };\r\n EventQueue.invokeLater(runnable);\r\n\r\n }\r\n\r\n /**\r\n * Registers a new {@link NetworkListener} on the current network\r\n *\r\n * @param listener The listener that should be added\r\n */\r\n public void registerNetworkListener(NetworkListener listener) {\r\n SNC.getInstance().getCurrentNetwork().addListener(listener);\r\n }\r\n\r\n /**\r\n * Reverts the effects of the last {@link Command}\r\n */\r\n public void undo() {\r\n undoRedoStack.undo();\r\n }\r\n\r\n /**\r\n * Redos the last {@link Command} that was un-done\r\n */\r\n public void redo() {\r\n undoRedoStack.redo();\r\n }\r\n\r\n /**\r\n * Executes the given {@link Command} and adds it to the\r\n * {@link UndoRedoStack} Throws NetworkActionException upon error.\r\n *\r\n * @param c The command to be invoked.\r\n */\r\n public void invokeCommand(Command c) {\r\n undoRedoStack.insertIntoStack(c);\r\n c.execute();\r\n }\r\n\r\n /**\r\n * Returns the currently accessed {@link Network}. Note that only one\r\n * network can be opened at a time, at the moment.\r\n *\r\n * @return The current network\r\n */\r\n public Network getCurrentNetwork() {\r\n return networks.get(currentNetworkPosition);\r\n }\r\n\r\n /**\r\n * Saves the currently accessed {@link Network} to the file specified by the\r\n * parameter.\r\n *\r\n * @param file The file to which the network should be saved.\r\n */\r\n public void saveNetwork(File file) {\r\n getCurrentNetwork().save(file);\r\n\r\n }\r\n\r\n /**\r\n * Load a {@link Network} from the file specified by the parameter. Since,\r\n * at the moment, only one network can be opened at a time, the currently\r\n * accessed network is overwritten. Throws a FileOperationException when an\r\n * error upon load occurs\r\n *\r\n * @param file The file in which the network is saved.\r\n */\r\n public void loadNetwork(File file) {\r\n Network nw = Network.load(file, true);\r\n networks.set(currentNetworkPosition, nw);\r\n }\r\n\r\n /**\r\n * Returns the {@link Network} with the corresponding ID, if it exists. If\r\n * not, an exception is thrown. At the moment the current network position\r\n * will be returned.\r\n *\r\n * @param id The ID of the desired network.\r\n * @return The current network\r\n */\r\n public Network getNetwork(int id) {\r\n return networks.get(currentNetworkPosition);\r\n }\r\n\r\n /**\r\n * This relays the command of calculating a symbolic (not optimized) bound\r\n * to the corresponding {@link AbstractAnalysis}-subclass. The result is\r\n * returned in arrival-representation.\r\n *\r\n * @param flow the <code>Flow</code> of interest.\r\n * @param vertex the <code>Vertex</code> of interest.\r\n * @param anaType the type of analysis used\r\n * @param boundtype the type of bound, which needs to be computed.\r\n * @param nw the <code>Network</code> to which the other parameters belong\r\n * @return the result of the analysis in arrival-representation.\r\n */\r\n public Arrival analyzeNetwork(Flow flow, Vertex vertex, AnalysisType anaType, AbstractAnalysis.Boundtype boundtype, Network nw) {\r\n\r\n //Preparations\r\n Arrival bound = null;\r\n File file = null;\r\n try {\r\n file = File.createTempFile(\"SNC\", \"txt\");\r\n } catch (IOException e) {\r\n throw new FileOperationException(\"Error while analyzing Network: \" + e.getMessage());\r\n }\r\n this.saveNetwork(file);\r\n Network nwCopy = Network.load(file, false);\r\n Analyzer analyzer = AnalysisFactory.getAnalyzer(anaType, nwCopy, nwCopy.getVertices(), nwCopy.getFlows(), flow.getID(), vertex.getID(), boundtype);\r\n try {\r\n bound = analyzer.analyze();\r\n } catch (ArrivalNotAvailableException | DeadlockException | BadInitializationException e) {\r\n throw new AnalysisException(e);\r\n }\r\n return bound;\r\n }\r\n\r\n /**\r\n * Computes an optimized bound for the desired {@link Flow} and\r\n * {@link Vertex}.\r\n *\r\n * @param flow The {@link Flow} of interest\r\n * @param vertex The {@link Vertex} of interest\r\n * @param thetaGran Specifies the optimization granularity of the\r\n * theta-parameter\r\n * @param hoelderGran Specifies the optimization granularity of the\r\n * hoelder-parameter\r\n * @param analysisType The desired analysis algorithm (see\r\n * {@link AnalysisType})\r\n * @param optAlgorithm The desired optimization algorithm (see\r\n * {@link OptimizationType})\r\n * @param boundType The desired {@link BoundType}\r\n * @param value Depending on the boundType parameter this is either: A\r\n * violation probability (in case of an inverse bound) or a bound value\r\n * (otherwise)\r\n * @param nw The network to which the <code>flow</code> and\r\n * <code>vertex</code> belong to\r\n * @return An optimal bound\r\n */\r\n public double optimizeSymbolicFunction(Flow flow, Vertex vertex, double thetaGran, double hoelderGran,\r\n AnalysisType analysisType, OptimizationType optAlgorithm, BoundType boundType, double value, Network nw) {\r\n\r\n double result = Double.NaN;\r\n double debugVal = Double.NaN;\r\n AbstractAnalysis.Boundtype analysisBound = convertBoundTypes(boundType);\r\n Arrival symbolicBound = analyzeNetwork(flow, vertex, analysisType, analysisBound, nw);\r\n\r\n //Backlog values are represented by negative values in the arrival representation\r\n if (boundType == BoundType.BACKLOG && value > 0) {\r\n value = -value;\r\n }\r\n\r\n Optimizable bound = BoundFactory.createBound(symbolicBound, boundType, value);\r\n Optimizer optimizer = OptimizationFactory.getOptimizer(bound, analysisBound, optAlgorithm);\r\n\r\n try {\r\n result = optimizer.minimize(thetaGran, hoelderGran);\r\n // Temporary Debug Test\r\n if (boundType == BoundType.BACKLOG || boundType == BoundType.DELAY) {\r\n debugVal = optimizer.Bound(symbolicBound, analysisBound, value, thetaGran, hoelderGran);\r\n } else {\r\n debugVal = optimizer.ReverseBound(symbolicBound, analysisBound, value, thetaGran, hoelderGran);\r\n }\r\n\r\n } catch (ThetaOutOfBoundException | ParameterMismatchException | ServerOverloadException e) {\r\n throw new AnalysisException(e);\r\n }\r\n // For debugging purposes\r\n if (result != debugVal) {\r\n throw new RuntimeException(\"[DEBUG] Optimization results do not match!\");\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Helper function to convert between AbstractAnalysis.BoundType and\r\n * BoundType\r\n *\r\n * @param boundType The BoundType that should be converted\r\n * @return An appropriate AbstractAnalysis.BoundType\r\n */\r\n AbstractAnalysis.Boundtype convertBoundTypes(BoundType boundType) {\r\n AbstractAnalysis.Boundtype targetBoundType = null;\r\n if (boundType == BoundType.BACKLOG || boundType == BoundType.INVERSE_BACKLOG) {\r\n targetBoundType = AbstractAnalysis.Boundtype.BACKLOG;\r\n } else if (boundType == BoundType.DELAY || boundType == BoundType.INVERSE_DELAY) {\r\n targetBoundType = AbstractAnalysis.Boundtype.DELAY;\r\n } else {\r\n throw new AnalysisException(\"No such boundtype\");\r\n }\r\n return targetBoundType;\r\n }\r\n\r\n // Temp:\r\n private void ConvolutionTest() {\r\n System.out.println(\"Convolution Test:\");\r\n Network nw = getCurrentNetwork();\r\n Command addV1 = new AddVertexCommand(\"V1\", -2.0, -1, SNC.getInstance());\r\n Command addV2 = new AddVertexCommand(\"V2\", -1.0, -1, SNC.getInstance());\r\n List<Integer> f1Route = new ArrayList<>();\r\n List<Integer> f1Prio = new ArrayList<>();\r\n f1Route.add(1);\r\n f1Route.add(2);\r\n f1Prio.add(1);\r\n f1Prio.add(1);\r\n Arrival arrival = new Arrival(new ConstantFunction(0), new ConstantFunction(0.5), nw);\r\n Command addF1 = new AddFlowCommand(\"F1\", arrival, f1Route, f1Prio, -1, SNC.getInstance());\r\n //Command convV1V2 = new ConvoluteVerticesCommand(1, 2, -1, SNC.getInstance());\r\n invokeCommand(addV1);\r\n invokeCommand(addV2);\r\n invokeCommand(addF1);\r\n //invokeCommand(convV1V2);\r\n\r\n Map<Integer, Vertex> vertices = nw.getVertices();\r\n Map<Integer, Flow> flows = nw.getFlows();\r\n System.out.println(\"Flows\");\r\n for (Entry<Integer, Flow> entry : flows.entrySet()) {\r\n System.out.print(entry.getValue().getAlias() + \": \" + entry.getValue().getVerticeIDs());\r\n }\r\n System.out.println(\"\\nVertices\");\r\n for (Entry<Integer, Vertex> entry : vertices.entrySet()) {\r\n System.out.print(entry.getKey() + \" \" + entry.getValue().getAlias() + \" \");\r\n }\r\n\r\n }\r\n}\r",
"public class AddVertexCommand implements Command {\n private final String alias;\n double rate;\n int networkID;\n SNC snc;\n boolean success;\n int vertexID;\n \n /**\n * Creates a new Command to add a vertex\n * @param alias The name of the vertex\n * @param rate The service rate the vertex offers (Because only constant rate\n * service is possible at the moment\n * @param networkID The network the vertex belongs to\n * @param snc The overall controller\n */\n public AddVertexCommand(String alias, double rate, int networkID, SNC snc) {\n this.alias = alias != null ? alias : \"\";\n this.rate = rate;\n this.networkID = networkID;\n this.snc = snc;\n this.success = false;\n this.vertexID = -1;\n }\n \n @Override\n public void execute() {\n\tNetwork nw = snc.getCurrentNetwork();\n try {\n vertexID = nw.addVertex(ServiceFactory.buildConstantRate(-rate), alias).getID();\n } catch (BadInitializationException ex) {\n throw new NetworkActionException(ex);\n }\n\t// Why is this?\n\tsnc.getCurrentNetwork().getVertex(vertexID).getService().getServicedependencies().clear();\n\n\tsuccess = true;\n }\n\n @Override\n public void undo() {\n if(success) {\n snc.getCurrentNetwork().removeVertex(vertexID);\n }\n }\n \n}",
"public interface Command {\n\n /**\n * The main function of the command, also used for redoing the command.\n */\n public void execute();\n\n /**\n * Used to undo the actions that were performed during execution of the command.\n */\n public void undo();\n}",
"public enum ServiceType {\n\n /**\n *\n */\n CONSTANT {\n @Override\n public String toString() {\n return \"Constant Rate Service\";\n }\n }\n}",
"public class NetworkActionException extends RuntimeException {\n public NetworkActionException(Exception e) {\n super(e);\n }\n \n public NetworkActionException(String message) {\n super(message);\n }\n}"
] | import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import unikl.disco.calculator.SNC;
import unikl.disco.calculator.commands.AddVertexCommand;
import unikl.disco.calculator.commands.Command;
import unikl.disco.calculator.symbolic_math.ServiceType;
import unikl.disco.misc.NetworkActionException; | /*
* (c) 2017 Michael A. Beck, Sebastian Henningsen
* disco | Distributed Computer Systems Lab
* University of Kaiserslautern, Germany
* All Rights Reserved.
*
* This software is work in progress and is released in the hope that it will
* be useful to the scientific community. It is provided "as is" without
* express or implied warranty, including but not limited to the correctness
* of the code or its suitability for any particular purpose.
*
* This software is provided under the MIT License, however, we would
* appreciate it if you contacted the respective authors prior to commercial use.
*
* If you find our software useful, we would appreciate if you mentioned it
* in any publication arising from the use of this software or acknowledge
* our work otherwise. We would also like to hear of any fixes or useful
*/
package unikl.disco.calculator.gui;
/**
* A dialog to get input from the user in order to add a vertex to a network.
* @author Sebastian Henningsen
* @author Michael Beck
*/
public class AddVertexDialog {
private final JPanel panel;
private final JLabel alias;
private final JLabel service;
private final JLabel rate;
private final JTextField aliasField;
private final JTextField rateField;
private final JComboBox<ServiceType> serviceTypes;
private final GridLayout layout;
/**
* Constructs the dialog and initializes all necessary fields.
*/
public AddVertexDialog() {
panel = new JPanel();
alias = new JLabel("Alias of the vertex: ");
service = new JLabel("Service Type: ");
rate = new JLabel("Rate: ");
aliasField = new JTextField();
rateField = new JTextField(10);
serviceTypes = new JComboBox<>(ServiceType.values());
panel.add(alias);
panel.add(aliasField);
panel.add(service);
panel.add(serviceTypes);
panel.add(rate);
panel.add(rateField);
layout = new GridLayout(0, 1);
panel.setLayout(layout);
}
/**
* Displays the dialog
*/
public void display() {
int result = JOptionPane.showConfirmDialog(null, panel, "Add Vertex",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
SNC snc = SNC.getInstance();
double serviceRate = Double.parseDouble(rateField.getText());
Command cmd = new AddVertexCommand(aliasField.getText(), serviceRate, -1, snc);
try {
snc.invokeCommand(cmd); | } catch(NetworkActionException e) { | 4 |
xiprox/WaniKani-for-Android | WaniKani/src/tr/xip/wanikani/content/notification/NotificationScheduler.java | [
"public abstract class WaniKaniApi {\n private static final String API_HOST = \"https://www.wanikani.com/api/user/\";\n\n private static WaniKaniService service;\n private static String API_KEY;\n\n static {\n init();\n }\n\n public static void init() {\n API_KEY = PrefManager.getApiKey();\n setupService();\n }\n\n private static void setupService() {\n OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();\n if (BuildConfig.DEBUG) {\n HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();\n httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);\n clientBuilder.addInterceptor(httpLoggingInterceptor);\n }\n\n Retrofit retrofit = new Retrofit.Builder()\n .client(clientBuilder.build())\n .addConverterFactory(GsonConverterFactory.create())\n .baseUrl(API_HOST)\n .build();\n\n service = retrofit.create(WaniKaniService.class);\n }\n\n public static Call<Request<User>> getUser() {\n return service.getUser(API_KEY);\n }\n\n public static Call<Request<User>> getUser(String apiKey) {\n return service.getUser(apiKey);\n }\n\n public static Call<Request<StudyQueue>> getStudyQueue() {\n return service.getStudyQueue(API_KEY);\n }\n\n public static Call<Request<LevelProgression>> getLevelProgression() {\n return service.getLevelProgression(API_KEY);\n }\n\n public static Call<Request<SRSDistribution>> getSRSDistribution() {\n return service.getSRSDistribution(API_KEY);\n }\n\n public static Call<Request<RecentUnlocksList>> getRecentUnlocksList(int limit) {\n return service.getRecentUnlocksList(API_KEY, limit);\n }\n\n public static Call<Request<CriticalItemsList>> getCriticalItemsList(int percentage) {\n return service.getCriticalItemsList(API_KEY, percentage);\n }\n\n public static Call<Request<RadicalsList>> getRadicalsList(String level) {\n return service.getRadicalsList(API_KEY, level);\n }\n\n public static Call<Request<KanjiList>> getKanjiList(String level) {\n return service.getKanjiList(API_KEY, level);\n }\n\n public static Call<Request<VocabularyList>> getVocabularyList(String level) {\n return service.getVocabularyList(API_KEY, level);\n }\n}",
"public abstract class ThroughDbCallback<T extends Request<B>, B extends Storable> implements Callback<T> {\n @Override\n public void onResponse(Call<T> call, Response<T> response) {\n T result = response.body();\n if (result == null) return;\n\n final User userInfo = result.user_information;\n final B requestedInfo = result.requested_information;\n\n if (result.error == null && (userInfo != null || requestedInfo != null)) {\n new Thread(new Runnable() {\n @Override\n public void run() {\n if (userInfo != null) {\n userInfo.save();\n }\n if (requestedInfo != null) {\n requestedInfo.save();\n }\n }\n }).start();\n }\n }\n\n @Override\n public void onFailure(Call<T> call, Throwable t) {\n RetrofitErrorHandler.handleError(t);\n }\n}",
"public class DatabaseManager {\n private static final String TAG = \"Database Manager\";\n\n private static SQLiteDatabase db;\n\n public static void init(Context context) {\n if (db == null) {\n db = DatabaseHelper.getInstance(context).getWritableDatabase();\n }\n }\n\n private static void addItem(BaseItem item) {\n ContentValues values = new ContentValues();\n values.put(ItemsTable.COLUMN_NAME_CHARACTER, item.getCharacter());\n values.put(ItemsTable.COLUMN_NAME_KANA, item.getKana());\n values.put(ItemsTable.COLUMN_NAME_MEANING, item.getMeaning());\n values.put(ItemsTable.COLUMN_NAME_IMAGE, item.getImage());\n values.put(ItemsTable.COLUMN_NAME_ONYOMI, item.getOnyomi());\n values.put(ItemsTable.COLUMN_NAME_KUNYOMI, item.getKunyomi());\n values.put(ItemsTable.COLUMN_NAME_IMPORTANT_READING, item.getImportantReading());\n values.put(ItemsTable.COLUMN_NAME_LEVEL, item.getLevel());\n values.put(ItemsTable.COLUMN_NAME_ITEM_TYPE, item.getType().toString());\n values.put(ItemsTable.COLUMN_NAME_SRS, item.getSrsLevel());\n values.put(ItemsTable.COLUMN_NAME_UNLOCKED_DATE, item.getUnlockDateInSeconds());\n values.put(ItemsTable.COLUMN_NAME_AVAILABLE_DATE, item.getAvailableDateInSeconds());\n values.put(ItemsTable.COLUMN_NAME_BURNED, item.isBurned() ? 1 : 0);\n values.put(ItemsTable.COLUMN_NAME_BURNED_DATE, item.getBurnedDateInSeconds());\n values.put(ItemsTable.COLUMN_NAME_MEANING_CORRECT, item.getMeaningCorrect());\n values.put(ItemsTable.COLUMN_NAME_MEANING_INCORRECT, item.getMeaningIncorrect());\n values.put(ItemsTable.COLUMN_NAME_MEANING_MAX_STREAK, item.getMeaningMaxStreak());\n values.put(ItemsTable.COLUMN_NAME_MEANING_CURRENT_STREAK, item.getMeaningCurrentStreak());\n values.put(ItemsTable.COLUMN_NAME_READING_CORRECT, item.getReadingCorrect());\n values.put(ItemsTable.COLUMN_NAME_READING_INCORRECT, item.getReadingIncorrect());\n values.put(ItemsTable.COLUMN_NAME_READING_MAX_STREAK, item.getReadingMaxStreak());\n values.put(ItemsTable.COLUMN_NAME_READING_CURRENT_STREAK, item.getReadingCurrentStreak());\n values.put(ItemsTable.COLUMN_NAME_MEANING_NOTE, item.getMeaningNote());\n values.put(ItemsTable.COLUMN_NAME_USER_SYNONYMS, item.getUserSynonymsAsString());\n values.put(ItemsTable.COLUMN_NAME_READING_NOTE, item.getReadingNote());\n\n db.insert(ItemsTable.TABLE_NAME, ItemsTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static void saveItems(List<BaseItem> list, BaseItem.ItemType type) {\n deleteAllItemsFromSameLevelAndType(list, type);\n\n for (BaseItem item : list)\n addItem(item);\n }\n\n public static ItemsList getItems(BaseItem.ItemType itemType, int[] levels) {\n ItemsList list = new ItemsList();\n\n for (int level : levels) {\n String whereClause = ItemsTable.COLUMN_NAME_ITEM_TYPE + \" = ?\" + \" AND \"\n + ItemsTable.COLUMN_NAME_LEVEL + \" = ?\";\n String[] whereArgs = {\n itemType.toString(),\n String.valueOf(level)\n };\n\n Cursor c = null;\n\n try {\n c = db.query(\n ItemsTable.TABLE_NAME,\n ItemsTable.COLUMNS,\n whereClause,\n whereArgs,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n do {\n BaseItem item = new BaseItem(\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_ID)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_CHARACTER)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_KANA)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_IMAGE)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_ONYOMI)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_KUNYOMI)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_IMPORTANT_READING)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_LEVEL)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_ITEM_TYPE)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_SRS)),\n c.getLong(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_UNLOCKED_DATE)),\n c.getLong(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_AVAILABLE_DATE)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_BURNED)) == 1,\n c.getLong(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_BURNED_DATE)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_CORRECT)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_INCORRECT)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_MAX_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_CURRENT_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_CORRECT)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_INCORRECT)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_MAX_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_CURRENT_STREAK)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_NOTE)),\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_USER_SYNONYMS)) != null\n ? c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_USER_SYNONYMS)).split(\",\")\n : null,\n c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_NOTE))\n );\n list.add(item);\n } while (c.moveToNext());\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n }\n\n return list.size() != 0 ? list : null;\n }\n\n private static void deleteAllItemsFromSameLevelAndType(List<BaseItem> list, BaseItem.ItemType type) {\n HashSet<Integer> levels = new HashSet();\n\n for (BaseItem item : list)\n levels.add(item.getLevel());\n\n for (Integer level : levels) {\n String whereClause = ItemsTable.COLUMN_NAME_LEVEL + \" = ?\" + \" AND \"\n + ItemsTable.COLUMN_NAME_ITEM_TYPE + \" = ?\";\n String[] whereArgs = {\n String.valueOf(level),\n type.toString()\n };\n\n db.delete(ItemsTable.TABLE_NAME, whereClause, whereArgs);\n }\n }\n\n private static void addRecentUnlock(UnlockItem item) {\n ContentValues values = new ContentValues();\n values.put(RecentUnlocksTable.COLUMN_NAME_CHARACTER, item.getCharacter());\n values.put(RecentUnlocksTable.COLUMN_NAME_KANA, item.getKana());\n values.put(RecentUnlocksTable.COLUMN_NAME_MEANING, item.getMeaning());\n values.put(RecentUnlocksTable.COLUMN_NAME_IMAGE, item.getImage());\n values.put(RecentUnlocksTable.COLUMN_NAME_ONYOMI, item.getOnyomi());\n values.put(RecentUnlocksTable.COLUMN_NAME_KUNYOMI, item.getKunyomi());\n values.put(RecentUnlocksTable.COLUMN_NAME_IMPORTANT_READING, item.getImportantReading());\n values.put(RecentUnlocksTable.COLUMN_NAME_LEVEL, item.getLevel());\n values.put(RecentUnlocksTable.COLUMN_NAME_ITEM_TYPE, item.getType().toString());\n values.put(RecentUnlocksTable.COLUMN_NAME_SRS, item.getSrsLevel());\n values.put(RecentUnlocksTable.COLUMN_NAME_UNLOCKED_DATE, item.getUnlockDateInSeconds());\n values.put(RecentUnlocksTable.COLUMN_NAME_AVAILABLE_DATE, item.getAvailableDateInSeconds());\n values.put(RecentUnlocksTable.COLUMN_NAME_BURNED, item.isBurned() ? 1 : 0);\n values.put(RecentUnlocksTable.COLUMN_NAME_BURNED_DATE, item.getBurnedDateInSeconds());\n values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_CORRECT, item.getMeaningCorrect());\n values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_INCORRECT, item.getMeaningIncorrect());\n values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_MAX_STREAK, item.getMeaningMaxStreak());\n values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_CURRENT_STREAK, item.getMeaningCurrentStreak());\n values.put(RecentUnlocksTable.COLUMN_NAME_READING_CORRECT, item.getReadingCorrect());\n values.put(RecentUnlocksTable.COLUMN_NAME_READING_INCORRECT, item.getReadingIncorrect());\n values.put(RecentUnlocksTable.COLUMN_NAME_READING_MAX_STREAK, item.getReadingMaxStreak());\n values.put(RecentUnlocksTable.COLUMN_NAME_READING_CURRENT_STREAK, item.getReadingCurrentStreak());\n values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_NOTE, item.getMeaningNote());\n values.put(RecentUnlocksTable.COLUMN_NAME_USER_SYNONYMS, item.getUserSynonymsAsString());\n values.put(RecentUnlocksTable.COLUMN_NAME_READING_NOTE, item.getReadingNote());\n\n db.insert(RecentUnlocksTable.TABLE_NAME, RecentUnlocksTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static void saveRecentUnlocks(List<UnlockItem> list) {\n deleteSameRecentUnlocks(list);\n\n for (UnlockItem item : list)\n addRecentUnlock(item);\n }\n\n public static RecentUnlocksList getRecentUnlocks(int limit) {\n RecentUnlocksList list = new RecentUnlocksList();\n\n Cursor c = null;\n\n try {\n c = db.query(\n RecentUnlocksTable.TABLE_NAME,\n RecentUnlocksTable.COLUMNS,\n null,\n null,\n null,\n null,\n null,\n String.valueOf(limit)\n );\n\n if (c != null && c.moveToFirst()) {\n do {\n UnlockItem item = new UnlockItem(\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_ID)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_CHARACTER)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_KANA)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_IMAGE)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_ONYOMI)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_KUNYOMI)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_IMPORTANT_READING)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_LEVEL)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_ITEM_TYPE)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_SRS)),\n c.getLong(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_UNLOCKED_DATE)),\n c.getLong(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_AVAILABLE_DATE)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_BURNED)) == 1,\n c.getLong(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_BURNED_DATE)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_CORRECT)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_INCORRECT)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_MAX_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_CURRENT_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_CORRECT)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_INCORRECT)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_MAX_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_CURRENT_STREAK)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_NOTE)),\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_USER_SYNONYMS)) != null\n ? c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_USER_SYNONYMS)).split(\",\")\n : null,\n c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_NOTE))\n );\n list.add(item);\n } while (c.moveToNext());\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n\n return list.size() != 0 ? list : null;\n }\n\n public static void deleteSameRecentUnlocks(List<UnlockItem> list) {\n for (UnlockItem item : list) {\n String whereClause = item.getImage() == null\n ? RecentUnlocksTable.COLUMN_NAME_CHARACTER + \" = ?\"\n : RecentUnlocksTable.COLUMN_NAME_IMAGE + \" = ?\";\n String[] whereArgs = {\n item.getImage() == null ? String.valueOf(item.getCharacter()) : item.getImage()\n };\n\n db.delete(RecentUnlocksTable.TABLE_NAME, whereClause, whereArgs);\n }\n }\n\n private static void addCriticalItem(CriticalItem item) {\n if (item == null) return; // WANIKANI API SMH\n\n ContentValues values = new ContentValues();\n values.put(CriticalItemsTable.COLUMN_NAME_CHARACTER, item.getCharacter());\n values.put(CriticalItemsTable.COLUMN_NAME_KANA, item.getKana());\n values.put(CriticalItemsTable.COLUMN_NAME_MEANING, item.getMeaning());\n values.put(CriticalItemsTable.COLUMN_NAME_IMAGE, item.getImage());\n values.put(CriticalItemsTable.COLUMN_NAME_ONYOMI, item.getOnyomi());\n values.put(CriticalItemsTable.COLUMN_NAME_KUNYOMI, item.getKunyomi());\n values.put(CriticalItemsTable.COLUMN_NAME_IMPORTANT_READING, item.getImportantReading());\n values.put(CriticalItemsTable.COLUMN_NAME_LEVEL, item.getLevel());\n values.put(CriticalItemsTable.COLUMN_NAME_ITEM_TYPE, item.getType().toString());\n values.put(CriticalItemsTable.COLUMN_NAME_SRS, item.getSrsLevel());\n values.put(CriticalItemsTable.COLUMN_NAME_UNLOCKED_DATE, item.getUnlockDateInSeconds());\n values.put(CriticalItemsTable.COLUMN_NAME_AVAILABLE_DATE, item.getAvailableDateInSeconds());\n values.put(CriticalItemsTable.COLUMN_NAME_BURNED, item.isBurned() ? 1 : 0);\n values.put(CriticalItemsTable.COLUMN_NAME_BURNED_DATE, item.getBurnedDateInSeconds());\n values.put(CriticalItemsTable.COLUMN_NAME_MEANING_CORRECT, item.getMeaningCorrect());\n values.put(CriticalItemsTable.COLUMN_NAME_MEANING_INCORRECT, item.getMeaningIncorrect());\n values.put(CriticalItemsTable.COLUMN_NAME_MEANING_MAX_STREAK, item.getMeaningMaxStreak());\n values.put(CriticalItemsTable.COLUMN_NAME_MEANING_CURRENT_STREAK, item.getMeaningCurrentStreak());\n values.put(CriticalItemsTable.COLUMN_NAME_READING_CORRECT, item.getReadingCorrect());\n values.put(CriticalItemsTable.COLUMN_NAME_READING_INCORRECT, item.getReadingIncorrect());\n values.put(CriticalItemsTable.COLUMN_NAME_READING_MAX_STREAK, item.getReadingMaxStreak());\n values.put(CriticalItemsTable.COLUMN_NAME_READING_CURRENT_STREAK, item.getReadingCurrentStreak());\n values.put(CriticalItemsTable.COLUMN_NAME_MEANING_NOTE, item.getMeaningNote());\n values.put(CriticalItemsTable.COLUMN_NAME_USER_SYNONYMS, item.getUserSynonymsAsString());\n values.put(CriticalItemsTable.COLUMN_NAME_READING_NOTE, item.getReadingNote());\n values.put(CriticalItemsTable.COLUMN_NAME_PERCENTAGE, item.getPercentage());\n\n db.insert(CriticalItemsTable.TABLE_NAME, CriticalItemsTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static void saveCriticalItems(CriticalItemsList list) {\n deleteSameCriticalItems(list);\n\n for (CriticalItem item : list)\n addCriticalItem(item);\n }\n\n public static CriticalItemsList getCriticalItems(int percentage) {\n CriticalItemsList list = new CriticalItemsList();\n\n String whereClause = CriticalItemsTable.COLUMN_NAME_PERCENTAGE + \" < ?\";\n String[] whereArgs = {\n String.valueOf(percentage)\n };\n\n Cursor c = null;\n\n try {\n c = db.query(\n CriticalItemsTable.TABLE_NAME,\n CriticalItemsTable.COLUMNS,\n whereClause,\n whereArgs,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n do {\n CriticalItem item = new CriticalItem(\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_ID)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_CHARACTER)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_KANA)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_IMAGE)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_ONYOMI)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_KUNYOMI)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_IMPORTANT_READING)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_LEVEL)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_ITEM_TYPE)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_SRS)),\n c.getLong(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_UNLOCKED_DATE)),\n c.getLong(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_AVAILABLE_DATE)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_BURNED)) == 1,\n c.getLong(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_BURNED_DATE)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_CORRECT)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_INCORRECT)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_MAX_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_CURRENT_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_CORRECT)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_INCORRECT)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_MAX_STREAK)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_CURRENT_STREAK)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_NOTE)),\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_USER_SYNONYMS)) != null\n ? c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_USER_SYNONYMS)).split(\",\")\n : null,\n c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_NOTE)),\n c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_PERCENTAGE))\n );\n list.add(item);\n } while (c.moveToNext());\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n\n return list;\n }\n\n private static void deleteSameCriticalItems(List<CriticalItem> list) {\n for (CriticalItem item : list) {\n if (item == null) continue;\n\n String whereClause = item.getImage() == null\n ? CriticalItemsTable.COLUMN_NAME_CHARACTER + \" = ?\"\n : CriticalItemsTable.COLUMN_NAME_IMAGE + \" = ?\";\n String[] whereArgs = {\n item.getImage() == null ? String.valueOf(item.getCharacter()) : item.getImage()\n };\n\n db.delete(CriticalItemsTable.TABLE_NAME, whereClause, whereArgs);\n }\n }\n\n public static void saveStudyQueue(StudyQueue queue) {\n deleteStudyQueue();\n\n ContentValues values = new ContentValues();\n values.put(StudyQueueTable.COLUMN_NAME_LESSONS_AVAILABLE, queue.lessons_available);\n values.put(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE, queue.reviews_available);\n values.put(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE_NEXT_HOUR, queue.reviews_available_next_hour);\n values.put(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE_NEXT_DAY, queue.reviews_available_next_day);\n values.put(StudyQueueTable.COLUMN_NAME_NEXT_REVIEW_DATE, queue.next_review_date);\n\n db.insert(StudyQueueTable.TABLE_NAME, StudyQueueTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static StudyQueue getStudyQueue() {\n Cursor c = null;\n\n try {\n c = db.query(\n StudyQueueTable.TABLE_NAME,\n StudyQueueTable.COLUMNS,\n null,\n null,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n return new StudyQueue(\n c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_ID)),\n c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_LESSONS_AVAILABLE)),\n c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE)),\n c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE_NEXT_HOUR)),\n c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE_NEXT_DAY)),\n c.getLong(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_NEXT_REVIEW_DATE))\n );\n } else {\n Log.e(TAG, \"No study queue found; returning null\");\n return null;\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n }\n\n public static void deleteStudyQueue() {\n db.delete(StudyQueueTable.TABLE_NAME, null, null);\n }\n\n public static void saveLevelProgression(LevelProgression progression) {\n deleteLevelProgression();\n\n ContentValues values = new ContentValues();\n values.put(LevelProgressionTable.COLUMN_NAME_RADICALS_PROGRESS, progression.radicals_progress);\n values.put(LevelProgressionTable.COLUMN_NAME_RADICALS_TOTAL, progression.radicals_total);\n values.put(LevelProgressionTable.COLUMN_NAME_REVIEWS_KANJI_PROGRESS, progression.kanji_progress);\n values.put(LevelProgressionTable.COLUMN_NAME_REVIEWS_KANJI_TOTAL, progression.kanji_total);\n\n db.insert(LevelProgressionTable.TABLE_NAME, LevelProgressionTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static LevelProgression getLevelProgression() {\n Cursor c = null;\n\n try {\n c = db.query(\n LevelProgressionTable.TABLE_NAME,\n LevelProgressionTable.COLUMNS,\n null,\n null,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n return new LevelProgression(\n c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_ID)),\n c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_RADICALS_PROGRESS)),\n c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_RADICALS_TOTAL)),\n c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_REVIEWS_KANJI_PROGRESS)),\n c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_REVIEWS_KANJI_TOTAL))\n );\n } else {\n Log.e(TAG, \"No study queue found; returning null\");\n return null;\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n }\n\n public static void deleteLevelProgression() {\n db.delete(SRSDistributionTable.TABLE_NAME, null, null);\n }\n\n public static void saveSrsDistribution(SRSDistribution distribution) {\n deleteSrsDistribution();\n\n ContentValues values = new ContentValues();\n values.put(SRSDistributionTable.COLUMN_NAME_APPRENTICE_RADICALS, distribution.apprentice.radicals);\n values.put(SRSDistributionTable.COLUMN_NAME_APPRENTICE_KANJI, distribution.apprentice.kanji);\n values.put(SRSDistributionTable.COLUMN_NAME_APPRENTICE_VOCABULARY, distribution.apprentice.vocabulary);\n values.put(SRSDistributionTable.COLUMN_NAME_GURU_RADICALS, distribution.guru.radicals);\n values.put(SRSDistributionTable.COLUMN_NAME_GURU_KANJI, distribution.guru.kanji);\n values.put(SRSDistributionTable.COLUMN_NAME_GURU_VOCABULARY, distribution.guru.vocabulary);\n values.put(SRSDistributionTable.COLUMN_NAME_MASTER_RADICALS, distribution.master.radicals);\n values.put(SRSDistributionTable.COLUMN_NAME_MASTER_KANJI, distribution.master.kanji);\n values.put(SRSDistributionTable.COLUMN_NAME_MASTER_VOCABULARY, distribution.master.vocabulary);\n values.put(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_RADICALS, distribution.enlighten.radicals);\n values.put(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_KANJI, distribution.enlighten.kanji);\n values.put(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_VOCABULARY, distribution.enlighten.vocabulary);\n values.put(SRSDistributionTable.COLUMN_NAME_BURNED_RADICALS, distribution.burned.radicals);\n values.put(SRSDistributionTable.COLUMN_NAME_BURNED_KANJI, distribution.burned.kanji);\n values.put(SRSDistributionTable.COLUMN_NAME_BURNED_VOCABULARY, distribution.burned.vocabulary);\n\n db.insert(SRSDistributionTable.TABLE_NAME, SRSDistributionTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static SRSDistribution getSrsDistribution() {\n Cursor c = null;\n\n try {\n c = db.query(\n SRSDistributionTable.TABLE_NAME,\n SRSDistributionTable.COLUMNS,\n null,\n null,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n return new SRSDistribution(\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_ID)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_APPRENTICE_RADICALS)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_APPRENTICE_KANJI)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_APPRENTICE_VOCABULARY)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_GURU_RADICALS)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_GURU_KANJI)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_GURU_VOCABULARY)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_MASTER_RADICALS)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_MASTER_KANJI)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_MASTER_VOCABULARY)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_RADICALS)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_KANJI)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_VOCABULARY)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_BURNED_RADICALS)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_BURNED_KANJI)),\n c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_BURNED_VOCABULARY))\n );\n } else {\n Log.e(TAG, \"No srs distribution found; returning null\");\n return null;\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n }\n\n public static void deleteSrsDistribution() {\n db.delete(SRSDistributionTable.TABLE_NAME, null, null);\n }\n\n private static void addUser(User user) {\n ContentValues values = new ContentValues();\n values.put(UsersTable.COLUMN_NAME_USERNAME, user.username);\n values.put(UsersTable.COLUMN_NAME_GRAVATAR, user.gravatar);\n values.put(UsersTable.COLUMN_NAME_LEVEL, user.level);\n values.put(UsersTable.COLUMN_NAME_TITLE, user.title);\n values.put(UsersTable.COLUMN_NAME_ABOUT, user.about);\n values.put(UsersTable.COLUMN_NAME_WEBSITE, user.website);\n values.put(UsersTable.COLUMN_NAME_TWITTER, user.twitter);\n values.put(UsersTable.COLUMN_NAME_TOPICS_COUNT, user.topics_count);\n values.put(UsersTable.COLUMN_NAME_POSTS_COUNT, user.posts_count);\n values.put(UsersTable.COLUMN_NAME_CREATION_DATE, user.creation_date);\n values.put(UsersTable.COLUMN_NAME_VACATION_DATE, user.vacation_date);\n db.insert(UsersTable.TABLE_NAME, UsersTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static void saveUser(User user) {\n deleteUsers();\n\n addUser(user);\n }\n\n public static User getUser() {\n Cursor c = null;\n\n try {\n c = db.query(\n UsersTable.TABLE_NAME,\n UsersTable.COLUMNS,\n null,\n null,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n return new User(\n c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_USERNAME)),\n c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_GRAVATAR)),\n c.getInt(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_LEVEL)),\n c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_TITLE)),\n c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_ABOUT)),\n c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_WEBSITE)),\n c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_TWITTER)),\n c.getInt(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_TOPICS_COUNT)),\n c.getInt(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_POSTS_COUNT)),\n c.getLong(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_CREATION_DATE)),\n c.getLong(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_VACATION_DATE))\n );\n } else {\n Log.e(TAG, \"No users found; returning null\");\n return null;\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n }\n\n public static void deleteUsers() {\n db.delete(UsersTable.TABLE_NAME, null, null);\n }\n\n public static void saveNotification(Notification item) {\n db.delete(\n NotificationsTable.TABLE_NAME,\n NotificationsTable.COLUMN_NAME_ID + \" = ?\",\n new String[]{String.valueOf(item.getId())}\n );\n\n ContentValues values = new ContentValues();\n values.put(NotificationsTable.COLUMN_NAME_ID, item.getId());\n values.put(NotificationsTable.COLUMN_NAME_TITLE, item.getTitle());\n values.put(NotificationsTable.COLUMN_NAME_SHORT_TEXT, item.getShortText());\n values.put(NotificationsTable.COLUMN_NAME_TEXT, item.getText());\n values.put(NotificationsTable.COLUMN_NAME_IMAGE, item.getImage());\n values.put(NotificationsTable.COLUMN_NAME_ACTION_URL, item.getActionUrl());\n values.put(NotificationsTable.COLUMN_NAME_READ, item.isRead() ? 1 : 0);\n values.put(NotificationsTable.COLUMN_NAME_ACTION_TEXT, item.getActionText());\n\n db.insert(NotificationsTable.TABLE_NAME, NotificationsTable.COLUMN_NAME_NULLABLE, values);\n }\n\n public static void saveNotifications(List<Notification> list) {\n deleteSameNotifications(list);\n\n for (Notification item : list)\n saveNotification(item);\n }\n\n public static List<Notification> getNotifications() {\n List<Notification> list = new ArrayList<>();\n\n String whereClause = NotificationsTable.COLUMN_NAME_READ + \" = ?\";\n String[] whereArgs = {\n \"0\"\n };\n\n Cursor c = null;\n\n try {\n c = db.query(\n NotificationsTable.TABLE_NAME,\n NotificationsTable.COLUMNS,\n whereClause,\n whereArgs,\n null,\n null,\n null\n );\n\n if (c != null && c.moveToFirst()) {\n do {\n Notification item = new Notification(\n c.getInt(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_ID)),\n c.getString(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_TITLE)),\n c.getString(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_SHORT_TEXT)),\n c.getString(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_TEXT)),\n c.getString(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_IMAGE)),\n c.getString(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_ACTION_URL)),\n c.getString(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_ACTION_TEXT)),\n c.getInt(c.getColumnIndexOrThrow(NotificationsTable.COLUMN_NAME_READ)) == 1\n );\n list.add(item);\n } while (c.moveToNext());\n }\n } finally {\n if (c != null) {\n c.close();\n }\n }\n\n return list;\n }\n\n private static void deleteSameNotifications(List<Notification> list) {\n for (Notification item : list) {\n String whereClause = NotificationsTable.COLUMN_NAME_ID + \" = ?\";\n String[] whereArgs = {\n String.valueOf(item.getId())\n };\n\n db.delete(NotificationsTable.TABLE_NAME, whereClause, whereArgs);\n }\n }\n}",
"public class Request<T> {\n public User user_information;\n public T requested_information;\n public Error error;\n}",
"public class StudyQueue implements Serializable, Storable {\n public int id;\n public int lessons_available;\n public int reviews_available;\n public int reviews_available_next_hour;\n public int reviews_available_next_day;\n public long next_review_date;\n\n public StudyQueue(int id, int lessons, int reviews, int reviewsNextHour, int reviewsNextDay, long nextReviewDate) {\n this.id = id;\n this.lessons_available = lessons;\n this.reviews_available = reviews;\n this.reviews_available_next_hour = reviewsNextHour;\n this.reviews_available_next_day = reviewsNextDay;\n this.next_review_date = nextReviewDate;\n }\n\n public long getNextReviewDateInMillis() {\n return next_review_date * 1000;\n }\n\n @Override\n public void save() {\n DatabaseManager.saveStudyQueue(this);\n }\n}"
] | import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import java.text.SimpleDateFormat;
import retrofit2.Call;
import retrofit2.Response;
import tr.xip.wanikani.client.WaniKaniApi;
import tr.xip.wanikani.client.task.callback.ThroughDbCallback;
import tr.xip.wanikani.database.DatabaseManager;
import tr.xip.wanikani.models.Request;
import tr.xip.wanikani.models.StudyQueue; | package tr.xip.wanikani.content.notification;
public class NotificationScheduler {
private Context context;
private NotificationPreferences prefs;
public NotificationScheduler(Context context) {
this.context = context;
prefs = new NotificationPreferences(context);
}
public void schedule() { | WaniKaniApi.getStudyQueue().enqueue(new ThroughDbCallback<Request<StudyQueue>, StudyQueue>() { | 0 |
jenshadlich/s3srv | src/main/java/de/jeha/s3srv/resources/S3OperationsFacade.java | [
"public class RequestContext {\n\n private final boolean pathStyle;\n private final String bucket;\n private final String key;\n\n private RequestContext(boolean pathStyle, String bucket, String key) {\n this.pathStyle = pathStyle;\n this.bucket = bucket;\n this.key = key;\n }\n\n public static RequestContext build(HttpServletRequest request) {\n final String requestUri = request.getRequestURI();\n final String hostHeader = request.getHeader(Headers.HOST);\n final boolean pathStyle = detectPathStyle(request);\n\n String bucket = null;\n String key = null;\n\n String[] parts = StringUtils.split(requestUri, \"/\", 2);\n if (pathStyle) {\n if (parts.length >= 1) {\n bucket = parts[0];\n }\n if (parts.length >= 2) {\n key = parts[1];\n }\n } else {\n bucket = StringUtils.substringBefore(hostHeader, \".\");\n if (parts.length >= 1) {\n key = parts[0];\n }\n }\n return new RequestContext(pathStyle, bucket, key);\n }\n\n private static boolean detectPathStyle(HttpServletRequest request) {\n final String serverName = request.getServerName();\n final String hostHeader = request.getHeader(Headers.HOST);\n\n return !(hostHeader.startsWith(serverName) && serverName.endsWith(\".localhost\"));\n }\n\n public boolean isPathStyle() {\n return pathStyle;\n }\n\n public String getBucket() {\n return bucket;\n }\n\n public String getKey() {\n return key;\n }\n\n @Override\n public String toString() {\n return \"S3Context{\" +\n \"pathStyle=\" + pathStyle +\n \", bucket='\" + bucket + '\\'' +\n \", key='\" + key + '\\'' +\n '}';\n }\n\n}",
"public class CreateObject extends AbstractOperation {\n\n private static final Logger LOG = LoggerFactory.getLogger(CreateObject.class);\n\n public CreateObject(StorageBackend storageBackend) {\n super(storageBackend);\n }\n\n /**\n * Create an object.\n *\n * @param request HTTP request\n * @param bucket bucket\n * @param key object key\n * @return response\n */\n public Response createObject(HttpServletRequest request,\n String bucket,\n String key) {\n LOG.info(\"createObject '{}/{}'\", bucket, key);\n final String resource = \"/\" + bucket + \"/\" + key;\n\n AuthorizationContext authorizationContext = checkAuthorization(request, resource);\n if (!authorizationContext.isUserValid()) {\n return createErrorResponse(ErrorCodes.INVALID_ACCESS_KEY_ID, resource, null);\n }\n if (!authorizationContext.isSignatureValid()) {\n return createErrorResponse(ErrorCodes.SIGNATURE_DOES_NOT_MATCH, resource, null);\n }\n if (!getStorageBackend().doesBucketExist(bucket)) {\n return createErrorResponse(ErrorCodes.NO_SUCH_BUCKET, resource, null);\n }\n if (!getStorageBackend().getBucket(bucket).isOwnedBy(authorizationContext.getUser())) {\n return createErrorResponse(ErrorCodes.ACCESS_DENIED, resource, null);\n }\n\n final String expectedMD5 = request.getHeader(Headers.CONTENT_MD5); // optional\n try {\n S3Object object = getStorageBackend().createObject(\n bucket,\n key,\n request.getInputStream(),\n request.getContentLength(),\n expectedMD5,\n request.getContentType());\n\n return Response.ok()\n .header(Headers.ETAG, object.getETag())\n .build();\n } catch (IOException e) {\n LOG.error(\"Unable to read input stream\", e);\n return createErrorResponse(ErrorCodes.INTERNAL_ERROR, \"/\" + bucket + \"/\" + key, null);\n } catch (BadDigestException e) {\n return createErrorResponse(ErrorCodes.BAD_DIGEST, \"/\" + bucket + \"/\" + key, null);\n }\n }\n\n}",
"public class DeleteObject extends AbstractOperation {\n\n private static final Logger LOG = LoggerFactory.getLogger(DeleteObject.class);\n\n public DeleteObject(StorageBackend storageBackend) {\n super(storageBackend);\n }\n\n /**\n * Delete an object.\n *\n * @param request HTTP request\n * @param bucket bucket\n * @param key object key\n * @return response\n */\n public Response deleteObject(HttpServletRequest request,\n String bucket,\n String key) {\n LOG.info(\"deleteObject '{}/{}'\", bucket, key);\n final String resource = \"/\" + bucket + \"/\" + key;\n\n AuthorizationContext authorizationContext = checkAuthorization(request, resource);\n if (!authorizationContext.isUserValid()) {\n return createErrorResponse(ErrorCodes.INVALID_ACCESS_KEY_ID, resource, null);\n }\n if (!authorizationContext.isSignatureValid()) {\n return createErrorResponse(ErrorCodes.SIGNATURE_DOES_NOT_MATCH, resource, null);\n }\n if (!getStorageBackend().doesBucketExist(bucket)) {\n return createErrorResponse(ErrorCodes.NO_SUCH_BUCKET, resource, null);\n }\n if (!getStorageBackend().getBucket(bucket).isOwnedBy(authorizationContext.getUser())) {\n return createErrorResponse(ErrorCodes.ACCESS_DENIED, resource, null);\n }\n if (!getStorageBackend().doesObjectExist(bucket, key)) {\n return Response.status(Response.Status.NOT_FOUND)\n .build();\n }\n\n getStorageBackend().deleteObject(bucket, key);\n\n return Response.noContent()\n .build();\n }\n\n}",
"public class ExistsObject extends AbstractOperation {\n\n private static final Logger LOG = LoggerFactory.getLogger(ExistsObject.class);\n\n public ExistsObject(StorageBackend storageBackend) {\n super(storageBackend);\n }\n\n /**\n * Check if an object exists.\n *\n * @param request HTTP request\n * @param bucket bucket\n * @param key object key\n * @return response\n */\n public Response doesObjectExist(HttpServletRequest request,\n String bucket,\n String key) {\n LOG.info(\"doesObjectExist '{}/{}'\", bucket, key);\n final String resource = \"/\" + bucket + \"/\" + key;\n\n AuthorizationContext authorizationContext = checkAuthorization(request, resource);\n if (!authorizationContext.isUserValid()) {\n return createErrorResponse(ErrorCodes.INVALID_ACCESS_KEY_ID, resource, null);\n }\n if (!authorizationContext.isSignatureValid()) {\n return createErrorResponse(ErrorCodes.SIGNATURE_DOES_NOT_MATCH, resource, null);\n }\n if (!getStorageBackend().doesBucketExist(bucket)) {\n return createErrorResponse(ErrorCodes.NO_SUCH_BUCKET, resource, null);\n }\n if (!getStorageBackend().getBucket(bucket).isOwnedBy(authorizationContext.getUser())) {\n return createErrorResponse(ErrorCodes.ACCESS_DENIED, resource, null);\n }\n if (getStorageBackend().doesObjectExist(bucket, key)) {\n S3Object object = getStorageBackend().getObject(bucket, key);\n\n return Response.ok()\n .type(object.getContentType())\n .header(Headers.LAST_MODIFIED, RFC822Date.format(object.getLastModified()))\n .header(Headers.ETAG, object.getETag())\n .header(Headers.CONTENT_LENGTH, Integer.toString(object.getSize()))\n .build();\n } else {\n return Response.status(Response.Status.NOT_FOUND)\n .build();\n }\n }\n\n}",
"public class GetObject extends AbstractOperation {\n\n private static final Logger LOG = LoggerFactory.getLogger(ExistsObject.class);\n\n public GetObject(StorageBackend storageBackend) {\n super(storageBackend);\n }\n\n /**\n * Retrieve an object.\n *\n * @param request HTTP request\n * @param bucket bucket\n * @param key object key\n * @return response\n */\n public Response getObject(HttpServletRequest request,\n String bucket,\n String key) {\n LOG.info(\"getObject '{}/{}'\", bucket, key);\n final String resource = \"/\" + bucket + \"/\" + key;\n\n AuthorizationContext authorizationContext = checkAuthorization(request, resource);\n if (!authorizationContext.isUserValid()) {\n return createErrorResponse(ErrorCodes.INVALID_ACCESS_KEY_ID, resource, null);\n }\n if (!authorizationContext.isSignatureValid()) {\n return createErrorResponse(ErrorCodes.SIGNATURE_DOES_NOT_MATCH, resource, null);\n }\n if (!getStorageBackend().doesBucketExist(bucket)) {\n return createErrorResponse(ErrorCodes.NO_SUCH_BUCKET, resource, null);\n }\n if (!getStorageBackend().getBucket(bucket).isOwnedBy(authorizationContext.getUser())) {\n return createErrorResponse(ErrorCodes.ACCESS_DENIED, resource, null);\n }\n if (getStorageBackend().doesObjectExist(bucket, key)) {\n S3Object object = getStorageBackend().getObject(bucket, key);\n\n return Response.ok(object.getInputStream())\n .type(object.getContentType())\n .header(Headers.ETAG, object.getETag())\n .header(Headers.CONTENT_LENGTH, Integer.toString(object.getSize()))\n .build();\n } else {\n return Response.status(Response.Status.NOT_FOUND)\n .build();\n }\n }\n\n}",
"public class ListBuckets extends AbstractOperation {\n\n private static final Logger LOG = LoggerFactory.getLogger(ListBuckets.class);\n\n public ListBuckets(StorageBackend storageBackend) {\n super(storageBackend);\n }\n\n /**\n * List the buckets of some user\n *\n * @param request HTTP request\n * @return response\n */\n public Response listBuckets(HttpServletRequest request) {\n LOG.info(\"listBuckets\");\n final String resource = \"/\";\n\n AuthorizationContext authorizationContext = checkAuthorization(request, resource);\n if (!authorizationContext.isUserValid()) {\n return createErrorResponse(ErrorCodes.INVALID_ACCESS_KEY_ID, resource, null);\n }\n if (!authorizationContext.isSignatureValid()) {\n return createErrorResponse(ErrorCodes.SIGNATURE_DOES_NOT_MATCH, resource, null);\n }\n\n List<ListAllMyBucketsResult.BucketsEntry> buckets = getStorageBackend()\n .listBuckets()\n .stream()\n .filter(bucket -> bucket.isOwnedBy(authorizationContext.getUser()))\n .map(bucket -> new ListAllMyBucketsResult.BucketsEntry(bucket.getName(), bucket.getCreationDate()))\n .collect(Collectors.toList());\n\n ListAllMyBucketsResult response =\n new ListAllMyBucketsResult(\n new Owner(\n authorizationContext.getUser().getId(),\n authorizationContext.getUser().getDisplayName()),\n buckets);\n\n try {\n return Response.ok(JaxbMarshaller.marshall(response), MediaType.APPLICATION_XML_TYPE)\n .build();\n } catch (Exception e) {\n LOG.error(\"Unable to create xml response body\", e);\n return createErrorResponse(ErrorCodes.INTERNAL_ERROR, \"/\", null);\n }\n }\n\n}",
"public interface StorageBackend extends HealthAware {\n\n List<S3Bucket> listBuckets();\n\n void createBucket(S3User user, String bucket);\n\n boolean doesBucketExist(String bucket);\n\n S3Bucket getBucket(String bucket);\n\n void deleteBucket(String bucket);\n\n S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength,\n String expectedMD5, String contentType)\n throws IOException, BadDigestException;\n\n boolean doesObjectExist(String bucket, String key);\n\n List<S3Object> listObjects(String bucket, int max);\n\n S3Object getObject(String bucket, String key);\n\n void deleteObject(String bucket, String key);\n\n /**\n * @todo maybe separate storage backends for data and account data\n */\n S3User getUserByAccessId(String accessKey);\n\n}"
] | import com.codahale.metrics.annotation.Timed;
import de.jeha.s3srv.common.s3.RequestContext;
import de.jeha.s3srv.operations.buckets.*;
import de.jeha.s3srv.operations.objects.CreateObject;
import de.jeha.s3srv.operations.objects.DeleteObject;
import de.jeha.s3srv.operations.objects.ExistsObject;
import de.jeha.s3srv.operations.objects.GetObject;
import de.jeha.s3srv.operations.service.ListBuckets;
import de.jeha.s3srv.storage.StorageBackend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response; | package de.jeha.s3srv.resources;
/**
* @author [email protected]
*/
@Path("/")
public class S3OperationsFacade {
private static final Logger LOG = LoggerFactory.getLogger(S3OperationsFacade.class);
private final StorageBackend storageBackend;
public S3OperationsFacade(StorageBackend storageBackend) {
this.storageBackend = storageBackend;
}
@HEAD
@Path("{subResources:.*}")
@Timed
public Response head(@Context HttpServletRequest request) {
LOG.info("head");
final RequestContext context = RequestContext.build(request);
LOG.info("{}", context);
if (context.getBucket() != null && context.getKey() != null) {
return new ExistsObject(storageBackend).doesObjectExist(request, context.getBucket(), context.getKey());
}
if (context.getBucket() != null) {
return new ExistsBucket(storageBackend).doesBucketExist(request, context.getBucket());
}
throw new UnsupportedOperationException("Not yet implemented!"); // TODO
}
@GET
@Path("{subResources:.*}")
@Timed
public Response get(@Context HttpServletRequest request) {
LOG.info("get");
final RequestContext context = RequestContext.build(request);
LOG.info("{}", context);
if (context.getBucket() != null && context.getKey() != null) {
return new GetObject(storageBackend).getObject(request, context.getBucket(), context.getKey());
}
if (context.getBucket() != null && "acl".equals(request.getQueryString())) {
return new GetBucketACL(storageBackend).getBucketACL(request, context.getBucket());
}
if (context.getBucket() != null) {
return new ListObjects(storageBackend).listObjects(request, context.getBucket());
}
return new ListBuckets(storageBackend).listBuckets(request);
}
@PUT
@Path("{subResources:.*}")
@Timed
public Response put(@Context HttpServletRequest request) {
LOG.info("put");
final RequestContext context = RequestContext.build(request);
LOG.info("{}", context);
if (context.getBucket() != null && context.getKey() != null) {
return new CreateObject(storageBackend).createObject(request, context.getBucket(), context.getKey());
}
if (context.getBucket() != null) {
return new CreateBucket(storageBackend).createBucket(request, context.getBucket());
}
throw new UnsupportedOperationException("Not yet implemented!"); // TODO
}
@POST
@Path("{subResources:.*}")
@Timed
public Response post(@Context HttpServletRequest request) {
LOG.info("post");
final RequestContext context = RequestContext.build(request);
LOG.info("{}", context);
throw new UnsupportedOperationException("Not yet implemented!"); // TODO
}
@DELETE
@Path("{subResources:.*}")
@Timed
public Response delete(@Context HttpServletRequest request) {
LOG.info("delete");
final RequestContext context = RequestContext.build(request);
LOG.info("{}", context);
if (context.getBucket() != null && context.getKey() != null) { | return new DeleteObject(storageBackend).deleteObject(request, context.getBucket(), context.getKey()); | 2 |
c-rack/cbor-java | src/test/java/co/nstant/in/cbor/decoder/CborDecoderTest.java | [
"public class CborBuilder extends AbstractBuilder<CborBuilder> {\n\n private final LinkedList<DataItem> dataItems = new LinkedList<>();\n\n public CborBuilder() {\n super(null);\n }\n\n public CborBuilder reset() {\n dataItems.clear();\n return this;\n }\n\n public List<DataItem> build() {\n return dataItems;\n }\n\n public CborBuilder add(DataItem dataItem) {\n dataItems.add(dataItem);\n return this;\n }\n\n public CborBuilder add(long value) {\n add(convert(value));\n return this;\n }\n\n public CborBuilder add(BigInteger value) {\n add(convert(value));\n return this;\n }\n\n public CborBuilder add(boolean value) {\n add(convert(value));\n return this;\n }\n\n public CborBuilder add(float value) {\n add(convert(value));\n return this;\n }\n\n public CborBuilder add(double value) {\n add(convert(value));\n return this;\n }\n\n public CborBuilder add(byte[] bytes) {\n add(convert(bytes));\n return this;\n }\n\n public ByteStringBuilder<CborBuilder> startByteString() {\n return startByteString(null);\n }\n\n public ByteStringBuilder<CborBuilder> startByteString(byte[] bytes) {\n add(new ByteString(bytes).setChunked(true));\n return new ByteStringBuilder<CborBuilder>(this);\n }\n\n public CborBuilder add(String string) {\n add(convert(string));\n return this;\n }\n\n public UnicodeStringBuilder<CborBuilder> startString() {\n return startString(null);\n }\n\n public UnicodeStringBuilder<CborBuilder> startString(String string) {\n add(new UnicodeString(string).setChunked(true));\n return new UnicodeStringBuilder<CborBuilder>(this);\n }\n\n public CborBuilder addTag(long value) {\n add(tag(value));\n return this;\n }\n\n public CborBuilder tagged(long value) {\n DataItem item = dataItems.peekLast();\n if (item == null) {\n throw new IllegalStateException(\"Can't add a tag before adding an item\");\n }\n item.getOuterTaggable().setTag(value);\n return this;\n }\n\n public ArrayBuilder<CborBuilder> startArray() {\n Array array = new Array();\n array.setChunked(true);\n add(array);\n return new ArrayBuilder<CborBuilder>(this, array);\n }\n\n public ArrayBuilder<CborBuilder> addArray() {\n Array array = new Array();\n add(array);\n return new ArrayBuilder<CborBuilder>(this, array);\n }\n\n public MapBuilder<CborBuilder> addMap() {\n Map map = new Map();\n add(map);\n return new MapBuilder<CborBuilder>(this, map);\n }\n\n public MapBuilder<CborBuilder> startMap() {\n Map map = new Map();\n map.setChunked(true);\n add(map);\n return new MapBuilder<CborBuilder>(this, map);\n }\n\n @Override\n protected void addChunk(DataItem dataItem) {\n add(dataItem);\n }\n\n}",
"public class CborDecoder {\n\n private final InputStream inputStream;\n private final UnsignedIntegerDecoder unsignedIntegerDecoder;\n private final NegativeIntegerDecoder negativeIntegerDecoder;\n private final ByteStringDecoder byteStringDecoder;\n private final UnicodeStringDecoder unicodeStringDecoder;\n private final ArrayDecoder arrayDecoder;\n private final MapDecoder mapDecoder;\n private final TagDecoder tagDecoder;\n private final SpecialDecoder specialDecoder;\n\n private boolean autoDecodeInfinitiveArrays = true;\n private boolean autoDecodeInfinitiveMaps = true;\n private boolean autoDecodeInfinitiveByteStrings = true;\n private boolean autoDecodeInfinitiveUnicodeStrings = true;\n private boolean autoDecodeRationalNumbers = true;\n private boolean autoDecodeLanguageTaggedStrings = true;\n private boolean rejectDuplicateKeys = false;\n\n /**\n * Initialize a new decoder which reads the binary encoded data from an\n * {@link OutputStream}.\n * \n * @param inputStream the {@link OutputStream} to read the data from\n */\n public CborDecoder(InputStream inputStream) {\n Objects.requireNonNull(inputStream);\n this.inputStream = inputStream;\n unsignedIntegerDecoder = new UnsignedIntegerDecoder(this, inputStream);\n negativeIntegerDecoder = new NegativeIntegerDecoder(this, inputStream);\n byteStringDecoder = new ByteStringDecoder(this, inputStream);\n unicodeStringDecoder = new UnicodeStringDecoder(this, inputStream);\n arrayDecoder = new ArrayDecoder(this, inputStream);\n mapDecoder = new MapDecoder(this, inputStream);\n tagDecoder = new TagDecoder(this, inputStream);\n specialDecoder = new SpecialDecoder(this, inputStream);\n }\n\n /**\n * Convenience method to decode a byte array directly.\n *\n * @param bytes the CBOR encoded data\n * @return a list of {@link DataItem}s\n * @throws CborException if decoding failed\n */\n public static List<DataItem> decode(byte[] bytes) throws CborException {\n return new CborDecoder(new ByteArrayInputStream(bytes)).decode();\n }\n\n /**\n * Decode the {@link InputStream} to a list of {@link DataItem}s.\n *\n * @return the list of {@link DataItem}s\n * @throws CborException if decoding failed\n */\n public List<DataItem> decode() throws CborException {\n List<DataItem> dataItems = new LinkedList<>();\n DataItem dataItem;\n while ((dataItem = decodeNext()) != null) {\n dataItems.add(dataItem);\n }\n return dataItems;\n }\n\n /**\n * Streaming decoding of an input stream. On each decoded DataItem, the callback\n * listener is invoked.\n *\n * @param dataItemListener the callback listener\n * @throws CborException if decoding failed\n */\n public void decode(DataItemListener dataItemListener) throws CborException {\n Objects.requireNonNull(dataItemListener);\n DataItem dataItem = decodeNext();\n while (dataItem != null) {\n dataItemListener.onDataItem(dataItem);\n dataItem = decodeNext();\n }\n }\n\n /**\n * Decodes exactly one DataItem from the input stream.\n *\n * @return a {@link DataItem} or null if end of stream has reached.\n * @throws CborException if decoding failed\n */\n public DataItem decodeNext() throws CborException {\n int symbol;\n try {\n symbol = inputStream.read();\n } catch (IOException ioException) {\n throw new CborException(ioException);\n }\n if (symbol == -1) {\n return null;\n }\n switch (MajorType.ofByte(symbol)) {\n case ARRAY:\n return arrayDecoder.decode(symbol);\n case BYTE_STRING:\n return byteStringDecoder.decode(symbol);\n case MAP:\n return mapDecoder.decode(symbol);\n case NEGATIVE_INTEGER:\n return negativeIntegerDecoder.decode(symbol);\n case UNICODE_STRING:\n return unicodeStringDecoder.decode(symbol);\n case UNSIGNED_INTEGER:\n return unsignedIntegerDecoder.decode(symbol);\n case SPECIAL:\n return specialDecoder.decode(symbol);\n case TAG:\n Tag tag = tagDecoder.decode(symbol);\n DataItem next = decodeNext();\n if (next == null) {\n throw new CborException(\"Unexpected end of stream: tag without following data item.\");\n } else {\n if (autoDecodeRationalNumbers && tag.getValue() == 30) {\n return decodeRationalNumber(next);\n } else if (autoDecodeLanguageTaggedStrings && tag.getValue() == 38) {\n return decodeLanguageTaggedString(next);\n } else {\n DataItem itemToTag = next;\n while (itemToTag.hasTag())\n itemToTag = itemToTag.getTag();\n itemToTag.setTag(tag);\n return next;\n }\n }\n case INVALID:\n default:\n throw new CborException(\"Not implemented major type \" + symbol);\n }\n }\n\n private DataItem decodeLanguageTaggedString(DataItem dataItem) throws CborException {\n if (!(dataItem instanceof Array)) {\n throw new CborException(\"Error decoding LanguageTaggedString: not an array\");\n }\n\n Array array = (Array) dataItem;\n\n if (array.getDataItems().size() != 2) {\n throw new CborException(\"Error decoding LanguageTaggedString: array size is not 2\");\n }\n\n DataItem languageDataItem = array.getDataItems().get(0);\n\n if (!(languageDataItem instanceof UnicodeString)) {\n throw new CborException(\"Error decoding LanguageTaggedString: first data item is not an UnicodeString\");\n }\n\n DataItem stringDataItem = array.getDataItems().get(1);\n\n if (!(stringDataItem instanceof UnicodeString)) {\n throw new CborException(\"Error decoding LanguageTaggedString: second data item is not an UnicodeString\");\n }\n\n UnicodeString language = (UnicodeString) languageDataItem;\n UnicodeString string = (UnicodeString) stringDataItem;\n\n return new LanguageTaggedString(language, string);\n }\n\n private DataItem decodeRationalNumber(DataItem dataItem) throws CborException {\n if (!(dataItem instanceof Array)) {\n throw new CborException(\"Error decoding RationalNumber: not an array\");\n }\n\n Array array = (Array) dataItem;\n\n if (array.getDataItems().size() != 2) {\n throw new CborException(\"Error decoding RationalNumber: array size is not 2\");\n }\n\n DataItem numeratorDataItem = array.getDataItems().get(0);\n\n if (!(numeratorDataItem instanceof Number)) {\n throw new CborException(\"Error decoding RationalNumber: first data item is not a number\");\n }\n\n DataItem denominatorDataItem = array.getDataItems().get(1);\n\n if (!(denominatorDataItem instanceof Number)) {\n throw new CborException(\"Error decoding RationalNumber: second data item is not a number\");\n }\n\n Number numerator = (Number) numeratorDataItem;\n Number denominator = (Number) denominatorDataItem;\n\n return new RationalNumber(numerator, denominator);\n }\n\n public boolean isAutoDecodeInfinitiveArrays() {\n return autoDecodeInfinitiveArrays;\n }\n\n public void setAutoDecodeInfinitiveArrays(boolean autoDecodeInfinitiveArrays) {\n this.autoDecodeInfinitiveArrays = autoDecodeInfinitiveArrays;\n }\n\n public boolean isAutoDecodeInfinitiveMaps() {\n return autoDecodeInfinitiveMaps;\n }\n\n public void setAutoDecodeInfinitiveMaps(boolean autoDecodeInfinitiveMaps) {\n this.autoDecodeInfinitiveMaps = autoDecodeInfinitiveMaps;\n }\n\n public boolean isAutoDecodeInfinitiveByteStrings() {\n return autoDecodeInfinitiveByteStrings;\n }\n\n public void setAutoDecodeInfinitiveByteStrings(boolean autoDecodeInfinitiveByteStrings) {\n this.autoDecodeInfinitiveByteStrings = autoDecodeInfinitiveByteStrings;\n }\n\n public boolean isAutoDecodeInfinitiveUnicodeStrings() {\n return autoDecodeInfinitiveUnicodeStrings;\n }\n\n public void setAutoDecodeInfinitiveUnicodeStrings(boolean autoDecodeInfinitiveUnicodeStrings) {\n this.autoDecodeInfinitiveUnicodeStrings = autoDecodeInfinitiveUnicodeStrings;\n }\n\n public boolean isAutoDecodeRationalNumbers() {\n return autoDecodeRationalNumbers;\n }\n\n public void setAutoDecodeRationalNumbers(boolean autoDecodeRationalNumbers) {\n this.autoDecodeRationalNumbers = autoDecodeRationalNumbers;\n }\n\n public boolean isAutoDecodeLanguageTaggedStrings() {\n return autoDecodeLanguageTaggedStrings;\n }\n\n public void setAutoDecodeLanguageTaggedStrings(boolean autoDecodeLanguageTaggedStrings) {\n this.autoDecodeLanguageTaggedStrings = autoDecodeLanguageTaggedStrings;\n }\n\n public boolean isRejectDuplicateKeys() {\n return rejectDuplicateKeys;\n }\n\n public void setRejectDuplicateKeys(boolean rejectDuplicateKeys) {\n this.rejectDuplicateKeys = rejectDuplicateKeys;\n }\n\n /**\n * Sets the given amount of bytes as maximum preallocation limit for arrays in\n * all decoders. This prevents OutOfMemory exceptions on malicious CBOR with\n * forged fixed length items. Note that items may exceed the given size when the\n * decoded data actually contains much data. This may be limited by using a\n * limiting stream.\n *\n * @param maxSize Maximum number of bytes to preallocate in array-based items.\n * Set to 0 to disable.\n */\n public void setMaxPreallocationSize(int maxSize) {\n unsignedIntegerDecoder.setMaxPreallocationSize(maxSize);\n negativeIntegerDecoder.setMaxPreallocationSize(maxSize);\n byteStringDecoder.setMaxPreallocationSize(maxSize);\n unicodeStringDecoder.setMaxPreallocationSize(maxSize);\n arrayDecoder.setMaxPreallocationSize(maxSize);\n mapDecoder.setMaxPreallocationSize(maxSize);\n tagDecoder.setMaxPreallocationSize(maxSize);\n specialDecoder.setMaxPreallocationSize(maxSize);\n }\n\n}",
"public class CborEncoder {\n\n private final UnsignedIntegerEncoder unsignedIntegerEncoder;\n private final NegativeIntegerEncoder negativeIntegerEncoder;\n private final ByteStringEncoder byteStringEncoder;\n private final UnicodeStringEncoder unicodeStringEncoder;\n private final ArrayEncoder arrayEncoder;\n private final MapEncoder mapEncoder;\n private final TagEncoder tagEncoder;\n private final SpecialEncoder specialEncoder;\n private boolean canonical = true;\n\n /**\n * Initialize a new encoder which writes the binary encoded data to an\n * {@link OutputStream}.\n * \n * @param outputStream the {@link OutputStream} to write the encoded data to\n */\n public CborEncoder(OutputStream outputStream) {\n Objects.requireNonNull(outputStream);\n unsignedIntegerEncoder = new UnsignedIntegerEncoder(this, outputStream);\n negativeIntegerEncoder = new NegativeIntegerEncoder(this, outputStream);\n byteStringEncoder = new ByteStringEncoder(this, outputStream);\n unicodeStringEncoder = new UnicodeStringEncoder(this, outputStream);\n arrayEncoder = new ArrayEncoder(this, outputStream);\n mapEncoder = new MapEncoder(this, outputStream);\n tagEncoder = new TagEncoder(this, outputStream);\n specialEncoder = new SpecialEncoder(this, outputStream);\n }\n\n /**\n * Encode a list of {@link DataItem}s, also known as a stream.\n *\n * @param dataItems a list of {@link DataItem}s\n * @throws CborException if the {@link DataItem}s could not be encoded or there\n * was an problem with the {@link OutputStream}.\n */\n public void encode(List<DataItem> dataItems) throws CborException {\n for (DataItem dataItem : dataItems) {\n encode(dataItem);\n }\n }\n\n /**\n * Encode a single {@link DataItem}.\n *\n * @param dataItem the {@link DataItem} to encode. If null, encoder encodes a\n * {@link SimpleValue} NULL value.\n * @throws CborException if {@link DataItem} could not be encoded or there was\n * an problem with the {@link OutputStream}.\n */\n public void encode(DataItem dataItem) throws CborException {\n if (dataItem == null) {\n dataItem = SimpleValue.NULL;\n }\n\n if (dataItem.hasTag()) {\n Tag tagDi = dataItem.getTag();\n encode(tagDi);\n }\n\n switch (dataItem.getMajorType()) {\n case UNSIGNED_INTEGER:\n unsignedIntegerEncoder.encode((UnsignedInteger) dataItem);\n break;\n case NEGATIVE_INTEGER:\n negativeIntegerEncoder.encode((NegativeInteger) dataItem);\n break;\n case BYTE_STRING:\n byteStringEncoder.encode((ByteString) dataItem);\n break;\n case UNICODE_STRING:\n unicodeStringEncoder.encode((UnicodeString) dataItem);\n break;\n case ARRAY:\n arrayEncoder.encode((Array) dataItem);\n break;\n case MAP:\n mapEncoder.encode((Map) dataItem);\n break;\n case SPECIAL:\n specialEncoder.encode((Special) dataItem);\n break;\n case TAG:\n tagEncoder.encode((Tag) dataItem);\n break;\n default:\n throw new CborException(\"Unknown major type\");\n }\n }\n\n public boolean isCanonical() {\n return canonical;\n }\n\n public CborEncoder nonCanonical() {\n canonical = false;\n return this;\n }\n\n}",
"public abstract class AbstractEncoder<T> {\n\n private final OutputStream outputStream;\n protected final CborEncoder encoder;\n\n public AbstractEncoder(CborEncoder encoder, OutputStream outputStream) {\n this.encoder = encoder;\n this.outputStream = outputStream;\n }\n\n public abstract void encode(T dataItem) throws CborException;\n\n protected void encodeTypeChunked(MajorType majorType) throws CborException {\n int symbol = majorType.getValue() << 5;\n symbol |= AdditionalInformation.INDEFINITE.getValue();\n try {\n outputStream.write(symbol);\n } catch (IOException ioException) {\n throw new CborException(ioException);\n }\n }\n\n protected void encodeTypeAndLength(MajorType majorType, long length) throws CborException {\n int symbol = majorType.getValue() << 5;\n if (length <= 23L) {\n write((byte) (symbol | length));\n } else if (length <= 255L) {\n symbol |= AdditionalInformation.ONE_BYTE.getValue();\n write((byte) symbol, (byte) length);\n } else if (length <= 65535L) {\n symbol |= AdditionalInformation.TWO_BYTES.getValue();\n write((byte) symbol, (byte) (length >> 8), (byte) (length & 0xFF));\n } else if (length <= 4294967295L) {\n symbol |= AdditionalInformation.FOUR_BYTES.getValue();\n write((byte) symbol, (byte) ((length >> 24) & 0xFF), (byte) ((length >> 16) & 0xFF),\n (byte) ((length >> 8) & 0xFF), (byte) (length & 0xFF));\n } else {\n symbol |= AdditionalInformation.EIGHT_BYTES.getValue();\n write((byte) symbol, (byte) ((length >> 56) & 0xFF), (byte) ((length >> 48) & 0xFF),\n (byte) ((length >> 40) & 0xFF), (byte) ((length >> 32) & 0xFF), (byte) ((length >> 24) & 0xFF),\n (byte) ((length >> 16) & 0xFF), (byte) ((length >> 8) & 0xFF), (byte) (length & 0xFF));\n }\n }\n\n protected void encodeTypeAndLength(MajorType majorType, BigInteger length) throws CborException {\n boolean negative = majorType == MajorType.NEGATIVE_INTEGER;\n int symbol = majorType.getValue() << 5;\n if (length.compareTo(BigInteger.valueOf(24)) == -1) {\n write(symbol | length.intValue());\n } else if (length.compareTo(BigInteger.valueOf(256)) == -1) {\n symbol |= AdditionalInformation.ONE_BYTE.getValue();\n write((byte) symbol, (byte) length.intValue());\n } else if (length.compareTo(BigInteger.valueOf(65536L)) == -1) {\n symbol |= AdditionalInformation.TWO_BYTES.getValue();\n long twoByteValue = length.longValue();\n write((byte) symbol, (byte) (twoByteValue >> 8), (byte) (twoByteValue & 0xFF));\n } else if (length.compareTo(BigInteger.valueOf(4294967296L)) == -1) {\n symbol |= AdditionalInformation.FOUR_BYTES.getValue();\n long fourByteValue = length.longValue();\n write((byte) symbol, (byte) ((fourByteValue >> 24) & 0xFF), (byte) ((fourByteValue >> 16) & 0xFF),\n (byte) ((fourByteValue >> 8) & 0xFF), (byte) (fourByteValue & 0xFF));\n } else if (length.compareTo(new BigInteger(\"18446744073709551616\")) == -1) {\n symbol |= AdditionalInformation.EIGHT_BYTES.getValue();\n BigInteger mask = BigInteger.valueOf(0xFF);\n write((byte) symbol, length.shiftRight(56).and(mask).byteValue(),\n length.shiftRight(48).and(mask).byteValue(), length.shiftRight(40).and(mask).byteValue(),\n length.shiftRight(32).and(mask).byteValue(), length.shiftRight(24).and(mask).byteValue(),\n length.shiftRight(16).and(mask).byteValue(), length.shiftRight(8).and(mask).byteValue(),\n length.and(mask).byteValue());\n } else {\n if (negative) {\n encoder.encode(new Tag(3));\n } else {\n encoder.encode(new Tag(2));\n }\n encoder.encode(new ByteString(length.toByteArray()));\n }\n }\n\n protected void write(int b) throws CborException {\n try {\n outputStream.write(b);\n } catch (IOException ioException) {\n throw new CborException(ioException);\n }\n }\n\n protected void write(byte... bytes) throws CborException {\n try {\n outputStream.write(bytes);\n } catch (IOException ioException) {\n throw new CborException(ioException);\n }\n }\n\n}",
"public class DataItem {\n\n private final MajorType majorType;\n private Tag tag;\n\n protected DataItem(MajorType majorType) {\n this.majorType = majorType;\n Objects.requireNonNull(majorType, \"majorType is null\");\n }\n\n public MajorType getMajorType() {\n return majorType;\n }\n\n public void setTag(long tag) {\n if (tag < 0) {\n throw new IllegalArgumentException(\"tag number must be 0 or greater\");\n }\n\n this.tag = new Tag(tag);\n }\n\n public void setTag(Tag tag) {\n Objects.requireNonNull(tag, \"tag is null\");\n this.tag = tag;\n }\n\n public void removeTag() {\n tag = null;\n }\n\n public Tag getTag() {\n return tag;\n }\n\n public boolean hasTag() {\n return tag != null;\n }\n\n @Override\n public boolean equals(Object object) {\n if (object instanceof DataItem) {\n DataItem other = (DataItem) object;\n if (tag != null) {\n return tag.equals(other.tag) && majorType == other.majorType;\n } else {\n return other.tag == null && majorType == other.majorType;\n }\n }\n\n return false;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(majorType, tag);\n }\n\n protected void assertTrue(boolean condition, String message) {\n if (!condition) {\n throw new IllegalArgumentException(message);\n }\n }\n\n public DataItem getOuterTaggable() {\n DataItem item = this;\n while (item.getTag() != null) {\n item = item.getTag();\n }\n return item;\n }\n}",
"public enum MajorType {\n\n INVALID(-1),\n\n /**\n * Major type 0: an unsigned integer. The 5-bit additional information is either\n * the integer itself (for additional information values 0 through 23), or the\n * length of additional data. Additional information 24 means the value is\n * represented in an additional uint8_t, 25 means a uint16_t, 26 means a\n * uint32_t, and 27 means a uint64_t. For example, the integer 10 is denoted as\n * the one byte 0b000_01010 (major type 0, additional information 10). The\n * integer 500 would be 0b000_11001 (major type 0, additional information 25)\n * followed by the two bytes 0x01f4, which is 500 in decimal.\n */\n UNSIGNED_INTEGER(0),\n\n /**\n * Major type 1: a negative integer. The encoding follows the rules for unsigned\n * integers (major type 0), except that the value is then -1 minus the encoded\n * unsigned integer. For example, the integer -500 would be 0b001_11001 (major\n * type 1, additional information 25) followed by the two bytes 0x01f3, which is\n * 499 in decimal.\n */\n NEGATIVE_INTEGER(1),\n\n /**\n * Major type 2: a byte string. The string's length in bytes is represented\n * following the rules for positive integers (major type 0). For example, a byte\n * string whose length is 5 would have an initial byte of 0b010_00101 (major\n * type 2, additional information 5 for the length), followed by 5 bytes of\n * binary content. A byte string whose length is 500 would have 3 initial bytes\n * of 0b010_11001 (major type 2, additional information 25 to indicate a\n * two-byte length) followed by the two bytes 0x01f4 for a length of 500,\n * followed by 500 bytes of binary content.\n */\n BYTE_STRING(2),\n\n /**\n * Major type 3: string of Unicode characters that is encoded as UTF-8\n * [RFC3629]. The format of this type is identical to that of byte strings\n * (major type 2), that is, as with major type 2, the length gives the number of\n * bytes. This type is provided for systems that need to interpret or display\n * human-readable text. In contrast to formats such as JSON, the Unicode\n * characters in this type are never escaped. Thus, a newline character (U+000A)\n * is always represented in a string as the byte 0x0a, and never as the bytes\n * 0x5c6e (the characters \"\\\" and \"n\") or as 0x5c7530303061 (the characters \"\\\",\n * \"u\", \"0\", \"0\", \"0\", and \"a\").\n */\n UNICODE_STRING(3),\n\n /**\n * Major type 4: an array of data items. Arrays are also called lists,\n * sequences, or tuples. The array's length follows the rules for byte strings\n * (major type 2), except that the length denotes the number of data items, not\n * the length in bytes that the array takes up. Items in an array do not need to\n * all be of the same type. For example, an array that contains 10 items of any\n * type would have an initial byte of 0b100_01010 (major type of 4, additional\n * information of 10 for the length) followed by the 10 remaining items.\n */\n ARRAY(4),\n\n /**\n * Major type 5: a map of pairs of data items. Maps are also called tables,\n * dictionaries, hashes, or objects (in JSON). A map is comprised of pairs of\n * data items, the even-numbered ones serving as keys and the following\n * odd-numbered ones serving as values for the key that comes immediately before\n * it. The map's length follows the rules for byte strings (major type 2),\n * except that the length denotes the number of pairs, not the length in bytes\n * that the map takes up. For example, a map that contains 9 pairs would have an\n * initial byte of 0b101_01001 (major type of 5, additional information of 9 for\n * the number of pairs) followed by the 18 remaining items. The first item is\n * the first key, the second item is the first value, the third item is the\n * second key, and so on.\n */\n MAP(5),\n\n /**\n * Major type 6: optional semantic tagging of other major types. See Section\n * 2.4.\n */\n TAG(6),\n\n /**\n * Major type 7: floating point numbers and simple data types that need no\n * content, as well as the \"break\" stop code. See Section 2.3.\n */\n SPECIAL(7);\n\n private final int value;\n\n private MajorType(int value) {\n this.value = value;\n }\n\n public int getValue() {\n return value;\n }\n\n public static MajorType ofByte(int b) {\n switch (b >> 5) {\n case 0:\n return UNSIGNED_INTEGER;\n case 1:\n return NEGATIVE_INTEGER;\n case 2:\n return BYTE_STRING;\n case 3:\n return UNICODE_STRING;\n case 4:\n return ARRAY;\n case 5:\n return MAP;\n case 6:\n return TAG;\n case 7:\n return SPECIAL;\n default:\n return INVALID;\n }\n }\n\n}",
"public class Tag extends DataItem {\n\n private final long value;\n\n public Tag(long value) {\n super(MajorType.TAG);\n this.value = value;\n }\n\n public long getValue() {\n return value;\n }\n\n @Override\n public boolean equals(Object object) {\n if (object instanceof Tag) {\n Tag other = (Tag) object;\n return super.equals(object) && value == other.value;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return super.hashCode() ^ Objects.hashCode(value);\n }\n\n @Override\n public String toString() {\n return \"Tag(\" + value + \")\";\n }\n\n}",
"public class UnsignedInteger extends Number {\n\n public UnsignedInteger(long value) {\n this(BigInteger.valueOf(value));\n assertTrue(value >= 0L, \"value \" + value + \" is not >= 0\");\n }\n\n public UnsignedInteger(BigInteger value) {\n super(MajorType.UNSIGNED_INTEGER, value);\n }\n\n}"
] | import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.junit.Test;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.encoder.AbstractEncoder;
import co.nstant.in.cbor.model.DataItem;
import co.nstant.in.cbor.model.MajorType;
import co.nstant.in.cbor.model.RationalNumber;
import co.nstant.in.cbor.model.Tag;
import co.nstant.in.cbor.model.UnsignedInteger; | public int read() throws IOException {
return (8 << 5); // invalid major type
}
});
cborDecoder.decodeNext();
}
@Test
public void shouldSetAutoDecodeInfinitiveMaps() {
InputStream inputStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
CborDecoder cborDecoder = new CborDecoder(inputStream);
assertTrue(cborDecoder.isAutoDecodeInfinitiveMaps());
cborDecoder.setAutoDecodeInfinitiveMaps(false);
assertFalse(cborDecoder.isAutoDecodeInfinitiveMaps());
}
@Test
public void shouldSetAutoDecodeRationalNumbers() {
InputStream inputStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
CborDecoder cborDecoder = new CborDecoder(inputStream);
assertTrue(cborDecoder.isAutoDecodeRationalNumbers());
cborDecoder.setAutoDecodeRationalNumbers(false);
assertFalse(cborDecoder.isAutoDecodeRationalNumbers());
}
@Test
public void shouldSetAutoDecodeLanguageTaggedStrings() {
InputStream inputStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
CborDecoder cborDecoder = new CborDecoder(inputStream);
assertTrue(cborDecoder.isAutoDecodeLanguageTaggedStrings());
cborDecoder.setAutoDecodeLanguageTaggedStrings(false);
assertFalse(cborDecoder.isAutoDecodeLanguageTaggedStrings());
}
@Test(expected = CborException.class)
public void shouldThrowOnRationalNumberDecode1() throws CborException {
List<DataItem> items = new CborBuilder().addTag(30).add(true).build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CborEncoder encoder = new CborEncoder(baos);
encoder.encode(items);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
CborDecoder decoder = new CborDecoder(bais);
decoder.decode();
}
@Test(expected = CborException.class)
public void shouldThrowOnRationalNumberDecode2() throws CborException {
List<DataItem> items = new CborBuilder().addTag(30).addArray().add(true).end().build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CborEncoder encoder = new CborEncoder(baos);
encoder.encode(items);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
CborDecoder decoder = new CborDecoder(bais);
decoder.decode();
}
@Test(expected = CborException.class)
public void shouldThrowOnRationalNumberDecode3() throws CborException {
List<DataItem> items = new CborBuilder().addTag(30).addArray().add(true).add(true).end().build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CborEncoder encoder = new CborEncoder(baos);
encoder.encode(items);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
CborDecoder decoder = new CborDecoder(bais);
decoder.decode();
}
@Test(expected = CborException.class)
public void shouldThrowOnRationalNumberDecode4() throws CborException {
List<DataItem> items = new CborBuilder().addTag(30).addArray().add(1).add(true).end().build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CborEncoder encoder = new CborEncoder(baos);
encoder.encode(items);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
CborDecoder decoder = new CborDecoder(bais);
decoder.decode();
}
@Test
public void shouldDecodeRationalNumber() throws CborException {
List<DataItem> items = new CborBuilder().addTag(30).addArray().add(1).add(2).end().build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CborEncoder encoder = new CborEncoder(baos);
encoder.encode(items);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
CborDecoder decoder = new CborDecoder(bais);
assertEquals(new RationalNumber(new UnsignedInteger(1), new UnsignedInteger(2)), decoder.decodeNext());
}
@Test
public void shouldDecodeTaggedTags() throws CborException {
DataItem decoded = CborDecoder.decode(new byte[] { (byte) 0xC1, (byte) 0xC2, 0x02 }).get(0);
Tag outer = new Tag(1);
Tag inner = new Tag(2);
UnsignedInteger expected = new UnsignedInteger(2);
inner.setTag(outer);
expected.setTag(inner);
assertEquals(expected, decoded);
}
@Test
public void shouldDecodeTaggedRationalNumber() throws CborException {
List<DataItem> items = new CborBuilder().addTag(1).addTag(30).addArray().add(1).add(2).end().build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CborEncoder encoder = new CborEncoder(baos);
encoder.encode(items);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
CborDecoder decoder = new CborDecoder(bais);
RationalNumber expected = new RationalNumber(new UnsignedInteger(1), new UnsignedInteger(2));
expected.getTag().setTag(new Tag(1));
assertEquals(expected, decoder.decodeNext());
}
@Test
public void shouldThrowOnItemWithForgedLength() throws CborException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream(); | AbstractEncoder<Long> maliciousEncoder = new AbstractEncoder<Long>(null, buffer) { | 3 |
luoyuan800/IPMIUtil4J | src/main/java/request/SensorRequest.java | [
"public class IPMIClient {\n\tprivate String IPMI_META_COMMAND = \"\";\n\tprivate String user;\n\tprivate String password;\n\tprivate String host;\n\tprivate CipherSuite cs;\n\tprivate boolean systemPowerUp;\n\tprivate Platform platform;\n\tpublic String getHost() {\n\t\treturn host;\n\t}\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\tpublic String getUser() {\n\t\treturn user;\n\t}\n\tpublic CipherSuite getCs() {\n\t\treturn cs;\n\t}\n\n\t/**\n\t * IPMIClient is representative as the target device which support IPMI\n\t * @param host The BMC network address( IPMI card IP)\n\t * @param user The IPMI user name config in the BMC\n\t * @param password The IPMI password config for the user\n\t * @param cs Cipher suite must support when doing initialize\n\t * @see param.CipherSuite\n\t * @param platform The project you want to run in which platform. It was very important.\n\t */\n\tpublic IPMIClient(String host, String user, String password, CipherSuite cs, Platform platform){\n\t\tthis.host = host;\n\t\tthis.password = password;\n\t\tthis.user = user;\n\t\tthis.cs = cs;\n\t\tIPMI_META_COMMAND = platform.getIPMI_META_COMMAND();\n\t\tthis.platform = platform;\n\t}\n\n\t/**\n\t * Verify if this IPMI device could reach by IPMI command.\n\t * @return true, IPMI is eable\n\t * \t\t false, IPMI command faile, maybe this device did not support IPMI or the BMC is down.\n\t */\n\tpublic boolean verify(){\n\t\tChassisStatusRequest request = new ChassisStatusRequest();\n\t\tChassisStatusRespond chassis = request.sendTo(this);\n\t\tsystemPowerUp = chassis.isPowerOn();\n\t\treturn chassis.isChassisStatusOk();\n\t}\n\n\t/**\n\t * Power up the system install in the target device\n\t * @return true, power up complete\n\t */\n\tpublic boolean powerUpSystem(){\n\t\tResetRequest request = new ResetRequest();\n\t\trequest.setPowerUpSystem(true);\n\t\tif(request.sendTo(this).hasRespond()){\n\t\t\tsystemPowerUp = true;\n\t\t\treturn true;\n\t\t}else{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Power down the system in target device chassis\n\t * @return If return true, the IPMIClient.powerUp will set as false\n\t */\n\tpublic boolean powerDownSystem(){\n\t\tResetRequest request = new ResetRequest();\n\t\trequest.setPowerDownSystem(true);\n\t\tif(request.sendTo(this).hasRespond()){\n\t\t\tsystemPowerUp = false;\n\t\t\treturn true;\n\t\t}else{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Power cycle the system in target device chassis\n\t * Will try to check if the system already power up,\n\t * if not, just power up system,\n\t * if yes, will do the restart.\n\t * @return If return true, the IPMIClient.powerUp will set as true\n\t */\n\tpublic boolean powerCycleSystem(){\n\t\tif(systemPowerUp) {\n\t\t\tResetRequest request = new ResetRequest();\n\t\t\trequest.setPowerCycleSystem(true);\n\t\t\treturn request.sendTo(this).hasRespond();\n\t\t}else{\n\t\t\tsystemPowerUp = powerUpSystem();\n\t\t\treturn systemPowerUp;\n\t\t}\n\t}\n\n\t/**\n\t * This command will different for different Platform\n\t * @see param.Platform\n\t * @return The ipmiutil command format for different platforms.\n\t */\n\tpublic String getIPMI_META_COMMAND() {\n\t\treturn IPMI_META_COMMAND;\n\t}\n\n\t/**\n\t * This is not a real time status of the target device system\n\t * If the powerUpSystem() or powerCycleSystem() have been called before, this status will set as true\n\t * @return\n\t * @see #powerUpSystem()\n\t * @see #powerCycleSystem()\n\t */\n\tpublic boolean isSystemPowerUp() {\n\t\treturn systemPowerUp;\n\t}\n\n\tpublic Platform getPlatform() {\n\t\treturn platform;\n\t}\n}",
"public class Command {\n\tpublic OutputResult exeCmd(String commandStr) {\n\t\tBufferedReader br = null;\n\t\tOutputResult out = new OutputResult();\n\t\ttry {\n\t\t\tProcess p = Runtime.getRuntime().exec(commandStr);\n\t\t\tbr = new BufferedReader(new InputStreamReader(p.getInputStream()));\n\t\t\tString line;\n\t\t\twhile ((line = br.readLine()) != null) {\n\t\t\t\tout.add(line.trim());\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t} finally{\n\t\t\tif (br != null)\n\t\t\t{\n\t\t\t\ttry {\n\t\t\t\t\tbr.close();\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\tpublic OutputResult exeCmdOnLinux(String cmd){\n\t\tString[] command = {\"/bin/sh\", \"-c\", cmd};\n\t\tOutputResult out = new OutputResult();\n\t\tBufferedReader br = null;\n\t\ttry {\n\t\t\tProcess p = Runtime.getRuntime().exec(command);\n\t\t\tbr = new BufferedReader(new InputStreamReader(p.getInputStream()));\n\t\t\tString line;\n\t\t\twhile ((line = br.readLine()) != null) {\n\t\t\t\tout.add(line.trim());\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t} finally{\n\t\t\tif (br != null)\n\t\t\t{\n\t\t\t\ttry {\n\t\t\t\t\tbr.close();\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tRuntime runtime = Runtime.getRuntime();\n\t\tProcess p = runtime.exec(\"ipmiutil-2.9.6-win64/ipmiutil fru -N 10.4.33.146 -U Administrator -P rdis2fun! -J 3\");\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));\n\t\tString line = null;\n\t\tStringBuilder sb = new StringBuilder();\n\t\twhile ((line = br.readLine()) != null) {\n\t\t\tsb.append(line + \"\\n\");\n\t\t}\n\t\tSystem.out.println(sb.toString());\n\t}\n}",
"public class OutputResult extends LinkedList<String>{\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 10L;\n\n\t@Override\n\tpublic String toString(){\n\t\tStringBuilder sb= new StringBuilder();\n\t\tfor(String s : this){\n\t\t\tsb.append(s).append(\"\\n\");\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\tpublic boolean isNotEmpty() {\n\t\treturn !isEmpty();\n\t}\n}",
"public class Sensor {\n private String description;\n private Double reading;\n private String unit;\n private SDRType type;\n private String id;\n private String status;\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public Double getReading() {\n return reading;\n }\n\n public void setReading(Double reading) {\n this.reading = reading;\n }\n\n public String getUnit() {\n return unit;\n }\n\n public void setUnit(String unit) {\n this.unit = unit;\n }\n\n public SDRType getType() {\n return type;\n }\n\n public void setType(SDRType type) {\n this.type = type;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n}",
"public enum SDRType {\n Full, Comp, FRU, IPMB, OEM;\n}",
"public class SensorRespond implements IPMIRespond {\n private List<Sensor> sensors;\n private boolean success;\n @Override\n public boolean hasRespond() {\n return success;\n }\n\n public synchronized void addSensor(Sensor sensor){\n if(sensors==null){\n sensors = new ArrayList<Sensor>();\n }\n sensors.add(sensor);\n }\n\n public void setSuccess(boolean success) {\n this.success = success;\n }\n}",
"public class StringUtils {\n\n public static boolean isNotEmpty(String str) {\n return str != null && !str.isEmpty() && str.trim().length() != 0;\n }\n}"
] | import client.IPMIClient;
import command.Command;
import command.OutputResult;
import model.Sensor;
import param.SDRType;
import respond.SensorRespond;
import utils.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | /*
* SensorRequest.java
* Date: 7/15/2015
* Time: 10:28 AM
*
* Copyright 2015 luoyuan.
* ALL RIGHTS RESERVED.
*/
package request;
public class SensorRequest extends AbstractRequest {
private Command command = new Command();
private static final Pattern sensorIDTypeReadingP = Pattern.compile("^([1234567890abcdef]+) SDR (\\w*) [1234567890abcdef].* snum .{2} (.*) *= .*(?<=[1234567890abcdef]{2}) (\\w+) +(-*\\d+\\.\\d+) (Volts|degrees C|RPM|Amps|Watts|unspecified)$"),
sensorIDTypeStatus = Pattern.compile("^([1234567890abcdef]+) SDR (\\w*) [1234567890abcdef].* snum .{2} (.*) *= .* (\\w*)$"),
sensorIDType = Pattern.compile("^([1234567890abcdef]+) SDR (\\w*).*"),
endP = Pattern.compile("sensor, completed successfully");
@Override
public String getCommandString() {
return "sensor";
}
@Override
public SensorRespond sendTo(IPMIClient client) { | OutputResult or = command.exeCmd(buildCommand(client)); | 2 |
feldim2425/OC-Minecarts | src/main/java/mods/ocminecart/common/component/ComputerCartController.java | [
"public class Settings {\n\t\n\tpublic static final String OC_ResLoc = \"opencomputers\"; // Resource domain for OpenComputers\n\tpublic static final String OC_Namespace = \"oc:\"; // Namespace for OpenComputers NBT Data\n\t\n\tpublic static float OC_SoundVolume;\n\tpublic static double OC_IC2PWR;\n\tpublic static double OC_SuckDelay;\n\tpublic static double OC_DropDelay;\n\t\n\tpublic static int ComputerCartBaseCost; //Config Value -> basecost\n\tpublic static int ComputerCartComplexityCost; //Config Value -> costmultiplier\n\tpublic static int ComputerCartEnergyCap; //Config Value -> energystore\n\tpublic static double ComputerCartEnergyUse; //Config Value -> energyuse\n\tpublic static int ComputerCartCreateEnergy; //Config Value -> newenergy\n\tpublic static double ComputerCartEngineUse; //Config Value -> engineuse\n\tpublic static double ComputerCartETrackLoad; //Config Value -> maxtrackcharge\n\tpublic static double ComputerCartETrackBuf; //Config Value -> maxtrackcharge\n\tpublic static double ComputerCartETrackLoss; //Config Value -> maxtrackcharge\n\t\n\tpublic static int NetRailPowerTransfer; //Config Value -> transferspeed\n\t\n\tpublic static double LinkingLinkDelay;\n\tpublic static double LinkingLinkCost;\n\tpublic static double LinkingUnlinkDelay;\n\tpublic static double LinkingUnlinkCost;\n\tpublic static int[] RemoteRange;\n\t\n\tpublic static boolean GeneralFixCartBox; //Config Value -> cartboxfix\n\t\n\t\n\tpublic static void init(){\n\t\tOCMinecart.config.load();\n\t\tconfComments();\n\t\tconfValues();\n\t\tconfOrder();\n\t\tOCMinecart.config.save();\n\t\t\n\t\tocValues();\n\t}\n\t\n\tprivate static void ocValues(){\t//Get the settings from OpenCOmputers\n\t\tOC_SoundVolume = li.cil.oc.Settings.get().soundVolume();\n\t\tOC_IC2PWR = li.cil.oc.Settings.get().ratioIndustrialCraft2();\n\t\tOC_SuckDelay = li.cil.oc.Settings.get().suckDelay();\n\t\tOC_DropDelay = li.cil.oc.Settings.get().dropDelay();\n\t}\n\t\n\tprivate static void confValues(){\n\t\t// computercart\n\t\tComputerCartBaseCost = OCMinecart.config.get(\"computercart\", \"basecost\", 50000 , \"Energy cost for a ComputerCart with Complexity 0 [default: 50000]\").getInt(50000);\n\t\tComputerCartComplexityCost = OCMinecart.config.get(\"computercart\", \"costmultiplier\", 10000 , \"Energy - Complexity multiplier [default: 10000]\").getInt(10000);\n\t\tComputerCartEnergyCap = OCMinecart.config.get(\"computercart\", \"energystore\", 20000 , \"Energy a Computer cart can store [default: 20000]\").getInt(20000);\n\t\tComputerCartEnergyUse = OCMinecart.config.get(\"computercart\", \"energyuse\", 0.25 , \"Energy a Computer cart consume every tick [default: 0.25]\").getDouble(0.25);\n\t\tComputerCartCreateEnergy= OCMinecart.config.get(\"computercart\", \"newenergy\", 20000 , \"Energy new a Computer cart has stored [default: 20000]\").getInt(20000);\n\t\tComputerCartEngineUse = OCMinecart.config.get(\"computercart\", \"engineuse\", 2 , \"Energy multiplier for the Engine. Speed times Value [default: 2]\").getDouble(2);\n\t\tComputerCartETrackBuf = OCMinecart.config.get(\"computercart\", \"trackchargebuffer\", 1000 , \"[Railcraft] Charge buffer for the computer cart (EU) [default: 1000]\").getDouble(1000);\n\t\tComputerCartETrackLoss = OCMinecart.config.get(\"computercart\", \"chargebufferloss\", 0.1 , \"[Railcraft] Charge buffer loss per tick (EU) [default: 0.1]\").getDouble(0.1);\n\t\tComputerCartETrackLoad = OCMinecart.config.get(\"computercart\", \"maxtrackcharge\", 16 , \"[Railcraft] Max. Energy a cart can take from the charge buffer per tick (EU) [default: 16]\").getDouble(16);\n\t\t\t\t\n\t\t// networkrail\n\t\tNetRailPowerTransfer= OCMinecart.config.get(\"networkrail\", \"transferspeed\",150 , \"Energy that a network rail can transfer per tick [default: 100]\").getInt(150);\n\t\t\n\t\t// general\n\t\tGeneralFixCartBox = OCMinecart.config.get(\"general\", \"cartboxfix\", true, \"Fix the computer cart bounding box if railcraft is installed [default:true]\").getBoolean(true);\n\t\t\n\t\t//upgrades\n\t\tLinkingLinkDelay= OCMinecart.config.get(\"upgrades\", \"linkingdelay\", 0.2 , \"Pause time when linking two carts with a Linking Upgrade (also when unsuccessful). in seconds [default: 0.5]\").getDouble(0.5);\n\t\tLinkingLinkCost= OCMinecart.config.get(\"upgrades\", \"linkingcost\", 0.5 , \"Energy the Linking Upgrade will take when linked successful [default: 0.5]\").getDouble(0.5);\n\t\tLinkingUnlinkDelay= OCMinecart.config.get(\"upgrades\", \"unlinkdelay\", 0.2 , \"Pause time when unlinklink two carts with a Linking Upgrade (also when unsuccessful). in seconds [default: 0.3]\").getDouble(0.3);\n\t\tLinkingLinkDelay= OCMinecart.config.get(\"upgrades\", \"unlinkcost\", 0.5 , \"Energy the Linking Upgrade will take when unlinked successful [default: 0.4]\").getDouble(0.4);\n\t\t\n\t\tRemoteRange = OCMinecart.config.get(\"upgrades\", \"remoterange\", new int[]{4,64,256}, \"Wireless range for the remote modules (Tier 1,2,3) [default: {4,64,256}]\").getIntList();\n\t}\n\t\n\tprivate static void confComments(){\n\t\tOCMinecart.config.addCustomCategoryComment(\"computercart\", \"Settings for the computer cart\\n\"\n\t\t\t\t+ \"[Railcraft] <= This settings are useless if Railcraft is not installed. \");\n\t\t\n\t\tOCMinecart.config.addCustomCategoryComment(\"networkrail\", \"Settings for the network rail\");\n\t\tOCMinecart.config.addCustomCategoryComment(\"general\", \"Some general settings for the mod\");\n\t\tOCMinecart.config.addCustomCategoryComment(\"upgrades\", \"Some general settings for upgrades\");\n\t}\n\t\n\tprivate static void confOrder(){\n\t\tArrayList<String> computercart = new ArrayList<String>();\n\t\tcomputercart.add(\"basecost\");\n\t\tcomputercart.add(\"costmultiplier\");\n\t\tcomputercart.add(\"newenergy\");\n\t\tcomputercart.add(\"energystore\");\n\t\tcomputercart.add(\"energyuse\");\n\t\tcomputercart.add(\"engineuse\");\n\t\tcomputercart.add(\"maxtrackcharge\");\n\t\tcomputercart.add(\"trackchargebuffer\");\n\t\tcomputercart.add(\"chargebufferloss\");\n\t\tOCMinecart.config.setCategoryPropertyOrder(\"computercart\", computercart);\n\t\t\n\t\tArrayList<String> upgrades = new ArrayList<String>();\n\t\tupgrades.add(\"remoterange\");\n\t\tupgrades.add(\"linkingdelay\");\n\t\tupgrades.add(\"linkingcost\");\n\t\tupgrades.add(\"unlinkdelay\");\n\t\tupgrades.add(\"unlinkcost\");\n\t\tOCMinecart.config.setCategoryPropertyOrder(\"upgrades\", upgrades);\n\t}\n}",
"public class ComputerCart extends AdvCart implements MachineHost, Analyzable, ISyncEntity, IComputerCart{\n\t\n\tprivate final boolean isServer = FMLCommonHandler.instance().getEffectiveSide().isServer();\n\t\n\tprivate int tier = -1;\t//The tier of the cart\n\tprivate Machine machine; //The machine object\n\tprivate boolean firstupdate = true; //true if the update() function gets called the first time\n\tprivate boolean chDim = false;\t//true if the cart changing the dimension (Portal, AE2 Storage,...)\n\tprivate boolean isRun = false; //true if the machine is turned on;\n\tprivate ComputerCartController controller = new ComputerCartController(this); //The computer cart component\n\tprivate double startEnergy = -1; //Only used when placing the cart. Start energy stored in the item\n\tprivate int invsize = 0; //The current inventory size depending on the Inventory Upgrades\n\tprivate boolean onrail = false; // Store onRail from last tick to send a Signal\n\tprivate int selSlot = 0; //The index of the current selected slot\n\tprivate int selTank = 1; //The index of the current selected tank\n\tprivate Player player; //OC's fake player\n\tprivate String name; //name of the cart\n\t\n\tprivate int cRailX = 0;\t// Position of the connected Network Rail\n\tprivate int cRailY = 0;\n\tprivate int cRailZ = 0;\n\tprivate int cRailDim = 0;\n\tprivate boolean cRailCon = false; //True if the card is connected to a network rail\n\tprivate Node cRailNode = null; // This node will not get saved in NBT because it should automatic disconnect after restart; \n\t\n\t\n\tpublic ComponetInventory compinv = new ComponetInventory(this){\n\n\t\t@Override\n\t\tpublic int getSizeInventory() {\n\t\t\t// 9 Upgrade Slots; 3 Container Slots; 8 Component Slots(CPU,Memory,...); 3 Provided Container Slots (the Container Slots in the GUI)\n\t\t\treturn 23; \n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected void onItemAdded(int slot, ItemStack stack){\n\t\t\tif(FMLCommonHandler.instance().getEffectiveSide().isServer()){\n\t\t\t\tsuper.onItemAdded(slot, stack);\n\t\t\t\t((ComputerCart) this.host).synchronizeComponentSlot(slot);\n\t\t\t}\n\t\t\t\n\t\t\tif(this.getSlotType(slot) == Slot.Floppy) Sound.play(this.host, \"floppy_insert\");\n\t\t\telse if(this.getSlotType(slot) == Slot.Upgrade && FMLCommonHandler.instance().getEffectiveSide().isServer()){\n\t\t\t\tItem drv = CustomDriver.driverFor(stack, this.host.getClass());\n\t\t\t\tif(drv instanceof Inventory){\n\t\t\t\t\t((ComputerCart)host).setInventorySpace(0);\n\t\t\t\t\t((ComputerCart)host).checkInventorySpace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected void onItemRemoved(int slot, ItemStack stack){\n\t\t\tsuper.onItemRemoved(slot, stack);\n\t\t\tif(FMLCommonHandler.instance().getEffectiveSide().isServer())\n\t\t\t\t((ComputerCart) this.host).synchronizeComponentSlot(slot);\n\t\t\t\n\t\t\tif(this.getSlotType(slot) == Slot.Floppy) Sound.play(this.host, \"floppy_eject\");\n\t\t\telse if(this.getSlotType(slot) == Slot.Upgrade && FMLCommonHandler.instance().getEffectiveSide().isServer()){\n\t\t\t\tItem drv = CustomDriver.driverFor(stack, this.host.getClass());\n\t\t\t\tif(drv instanceof Inventory){\n\t\t\t\t\t((ComputerCart)host).setInventorySpace(0);\n\t\t\t\t\t((ComputerCart)host).checkInventorySpace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void connectItemNode(Node node){\n\t\t\tsuper.connectItemNode(node);\n\t\t\tif(node!=null){\n\t\t\t\tif(node.host() instanceof TextBuffer){\n\t\t\t\t\tfor(int i=0;i<this.getSizeInventory();i+=1){\n\t\t\t\t\t\tif((this.getSlotComponent(i) instanceof Keyboard) && this.getSlotComponent(i).node()!=null)\n\t\t\t\t\t\t\tnode.connect(this.getSlotComponent(i).node());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(node.host() instanceof Keyboard){\n\t\t\t\t\tfor(int i=0;i<this.getSizeInventory();i+=1){\n\t\t\t\t\t\tif((this.getSlotComponent(i) instanceof TextBuffer) && this.getSlotComponent(i).node()!=null)\n\t\t\t\t\t\t\tnode.connect(this.getSlotComponent(i).node());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\t\n\tpublic ComputercartInventory maininv = new ComputercartInventory(this);\n\t\n\tpublic MultiTank tanks = new MultiTank(){\n\t\t@Override\n\t\tpublic int tankCount() {\n\t\t\treturn ComputerCart.this.tankcount();\n\t\t}\n\n\t\t@Override\n\t\tpublic IFluidTank getFluidTank(int index) {\n\t\t\treturn ComputerCart.this.getTank(index);\n\t\t}\n\t};\n\t\n\tpublic ComputerCart(World p_i1712_1_) {\n\t\tsuper(p_i1712_1_);\n\t}\n\n\tpublic ComputerCart(World w, double x, double y, double z, ComputerCartData data) {\n\t\tsuper(w,x,y,z);\n\t\tif(data==null){\n\t\t\tthis.setDead();\n\t\t\tdata=new ComputerCartData();\n\t\t}\n\t\tthis.tier=data.getTier();\n\t\tthis.startEnergy=data.getEnergy();\n\t\tthis.setEmblem(data.getEmblem());\n\t\t\n\t\tIterator<Entry<Integer, ItemStack>> list = data.getComponents().entrySet().iterator();\n\t\twhile(list.hasNext()){\n\t\t\tEntry<Integer, ItemStack> e = list.next();\n\t\t\tif(e.getKey() < this.compinv.getSizeInventory() && e.getValue() != null){\n\t\t\t\tcompinv.updateSlot(e.getKey(), e.getValue());\n\t\t\t}\n\t\t}\n\t\t\n\t\tthis.checkInventorySpace();\n\t}\n\t\n\t@Override\n\tprotected void entityInit(){\n\t\tsuper.entityInit();\n\t\t\n\t\tthis.dataWatcher.addObject(24, 0x0000FF);\n\t\t\n\t\tthis.machine = li.cil.oc.api.Machine.create(this);\n\t\tif(FMLCommonHandler.instance().getEffectiveSide().isServer()){\n\t\t\tthis.machine.setCostPerTick(Settings.ComputerCartEnergyUse);\n\t\t\t((Connector) this.machine.node()).setLocalBufferSize(Settings.ComputerCartEnergyCap);\n\t\t}\n\t\t\n\t}\n\t\n\t/*------NBT/Sync-Stuff-------*/\n\t@Override\n\tpublic void readEntityFromNBT(NBTTagCompound nbt){\n\t\tsuper.readEntityFromNBT(nbt);\n\t\t\n\t\tif(nbt.hasKey(\"components\")) this.compinv.readNBT((NBTTagList) nbt.getTag(\"components\"));\n\t\tif(nbt.hasKey(\"controller\")) this.controller.load(nbt.getCompoundTag(\"controller\"));\n\t\tif(nbt.hasKey(\"inventory\")) this.maininv.readFromNBT((NBTTagList) nbt.getTag(\"inventory\"));\n\t\tif(nbt.hasKey(\"netrail\")){\n\t\t\tNBTTagCompound netrail = nbt.getCompoundTag(\"netrail\");\n\t\t\tthis.cRailCon=true;\n\t\t\tthis.cRailX = netrail.getInteger(\"posX\");\n\t\t\tthis.cRailY = netrail.getInteger(\"posY\");\n\t\t\tthis.cRailZ = netrail.getInteger(\"posZ\");\n\t\t\tthis.cRailDim = netrail.getInteger(\"posDim\");\n\t\t}\n\t\tif(nbt.hasKey(\"settings\")){\n\t\t\tNBTTagCompound set = nbt.getCompoundTag(\"settings\");\n\t\t\tif(set.hasKey(\"lightcolor\")) this.setLightColor(set.getInteger(\"lightcolor\"));\n\t\t\tif(set.hasKey(\"selectedslot\")) this.selSlot = set.getInteger(\"selectedslot\");\n\t\t\tif(set.hasKey(\"selectedtank\")) this.selTank = set.getInteger(\"selectedtank\");\n\t\t\tif(set.hasKey(\"tier\")) this.tier = set.getInteger(\"tier\");\n\t\t}\n\t\t\n\t\t\n\t\tthis.machine.onHostChanged();\n\t\tif(nbt.hasKey(\"machine\"))this.machine.load(nbt.getCompoundTag(\"machine\"));\n\t\t\n\t\tthis.connectNetwork();\n\t\tthis.checkInventorySpace();\n\t}\n\t\n\t@Override\n\tpublic void writeEntityToNBT(NBTTagCompound nbt){\n\t\tif(!this.isServer) return;\n\t\t\n\t\tsuper.writeEntityToNBT(nbt);\n\t\t\n\t\tthis.compinv.saveComponents();\n\t\t\n\t\tnbt.setTag(\"components\", this.compinv.writeNTB());\n\t\tnbt.setTag(\"inventory\", this.maininv.writeToNBT());\n\t\t\n\t\t//Controller tag\n\t\tNBTTagCompound controller = new NBTTagCompound();\n\t\tthis.controller.save(controller);\n\t\tnbt.setTag(\"controller\", controller);\n\t\t\n\t\t//Data about the connected rail\n\t\tif(this.cRailCon){\n\t\t\tNBTTagCompound netrail = new NBTTagCompound();\n\t\t\tnetrail.setInteger(\"posX\", this.cRailX);\n\t\t\tnetrail.setInteger(\"posY\", this.cRailY);\n\t\t\tnetrail.setInteger(\"posZ\", this.cRailZ);\n\t\t\tnetrail.setInteger(\"posDim\", this.cRailDim);\n\t\t\tnbt.setTag(\"netrail\", netrail);\n\t\t}\n\t\telse if(nbt.hasKey(\"netrail\")) nbt.removeTag(\"netrail\");\n\t\t\n\t\t//Some additional values like light color, selected Slot, ...\n\t\tNBTTagCompound set = new NBTTagCompound();\n\t\tset.setInteger(\"lightcolor\", this.getLightColor());\n\t\tset.setInteger(\"selectedslot\",this.selSlot);\n\t\tset.setInteger(\"selectedtank\",this.selTank);\n\t\tset.setInteger(\"tier\", this.tier);\n\t\tnbt.setTag(\"settings\", set);\n\t\t\n\t\tNBTTagCompound machine = new NBTTagCompound();\n\t\tthis.machine.save(machine);\n\t\tnbt.setTag(\"machine\", machine);\n\t}\n\t\n\t@Override\n\tpublic void writeSyncData(NBTTagCompound nbt) {\n\t\tthis.compinv.saveComponents();\n\t\tnbt.setTag(\"components\", this.compinv.writeNTB());\n\t\tnbt.setBoolean(\"isRunning\", this.isRun);\n\t}\n\n\t@Override\n\tpublic void readSyncData(NBTTagCompound nbt) {\n\t\tthis.compinv.readNBT((NBTTagList) nbt.getTag(\"components\"));\n\t\tthis.isRun = nbt.getBoolean(\"isRunning\");\n\t\tthis.compinv.connectComponents();\n\t}\n\t\n\t/*--------------------*/\n\t\n\t/*------Interaction-------*/\n\t\n\tprotected void checkInventorySpace(){\n\t\tfor(int i=0;i<this.compinv.getSizeInventory();i+=1){\n\t\t\tif(this.compinv.getStackInSlot(i)!=null){\n\t\t\t\tItemStack stack = this.compinv.getStackInSlot(i);\n\t\t\t\tItem drv = CustomDriver.driverFor(stack, this.getClass());\n\t\t\t\tif(drv instanceof Inventory && this.invsize<this.maininv.getMaxSizeInventory()){\n\t\t\t\t\tthis.invsize = this.invsize+((Inventory)drv).inventoryCapacity(stack);\n\t\t\t\t\tif(this.invsize>this.maininv.getMaxSizeInventory()) this.invsize = this.maininv.getMaxSizeInventory();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tIterable<ItemStack> over = this.maininv.removeOverflowItems(this.invsize);\n\t\tItemUtil.dropItemList(over, this.worldObj, this.posX, this.posY, this.posZ, true);\n\t}\n\t\n\t@Override\n\tpublic void onUpdate(){\n\t\tsuper.onUpdate();\n\t\t//Only executed at the first function call\n\t\tif(this.firstupdate){\n\t\t\tthis.firstupdate=false;\n\t\t\t//Request a entity data sync\n\t\t\tif(this.worldObj.isRemote) ModNetwork.channel.sendToServer(new EntitySyncRequest(this));\n\t\t\telse{\n\t\t\t\tif(this.startEnergy > 0) ((Connector)this.machine.node()).changeBuffer(this.startEnergy); //Give start energy\n\t\t\t\tif(this.machine.node().network()==null){\n\t\t\t\t\tthis.connectNetwork(); //Connect all nodes (Components & Controller)\n\t\t\t\t}\n\n\t\t\t\tthis.onrail = this.onRail(); //Update onRail Value\n\t\t\t\tthis.player = new li.cil.oc.server.agent.Player(this); //Set the fake Player\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(!this.worldObj.isRemote){\n\t\t\t//Update the machine and the Components\n\t\t\tif(this.isRun){\n\t\t\t\tthis.machine.update();\n\t\t\t\tthis.compinv.updateComponents();\n\t\t\t}\n\t\t\t//Check if the machine state has changed.\n\t\t\tif(this.isRun != this.machine.isRunning()){\n\t\t\t\tthis.isRun=this.machine.isRunning();\n\t\t\t\tModNetwork.sendToNearPlayers(new UpdateRunning(this,this.isRun), this.posX, this.posY, this.posZ, this.worldObj);\n\t\t\t\tif(!this.isRun) this.setEngine(0);\n\t\t\t}\n\t\t\t//Consume energy for the Engine\n\t\t\tif(this.isEngineActive()){\n\t\t\t\tif(!((Connector)this.machine.node()).tryChangeBuffer(-1.0 * this.getEngine() * Settings.ComputerCartEngineUse))\n\t\t\t\t{\n\t\t\t\t\tthis.machine.signal(\"engine_failed\",this.getEngine());\n\t\t\t\t\tthis.setEngine(0);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Check if the cart is on a Track\n\t\t\tif(this.onrail != this.onRail())\n\t\t\t{\n\t\t\t\tthis.onrail = !this.onrail;\n\t\t\t\tthis.machine.signal(\"track_state\",this.onrail);\n\t\t\t}\n\t\t\t//Give the cart energy if it is a creative cart\n\t\t\tif(this.tier==3)((Connector)this.machine.node()).changeBuffer(Integer.MAX_VALUE);\n\t\t\t//Connect / Disconnect a network rail\n\t\t\tthis.checkRailConnection();\n\t\t}\n\t}\n\t\n\tprivate void connectNetwork(){\n\t\tAPI.network.joinNewNetwork(machine.node());\n\t\tthis.compinv.connectComponents();\n\t\tthis.machine.node().connect(this.controller.node());\n\t}\n\t\n\t@Override\n\tpublic void setDead(){\n\t\tsuper.setDead();\n\t\tif (!this.worldObj.isRemote && !this.chDim) {\n\t\t\tthis.machine.stop();\n\t\t\tthis.machine.node().remove();\n\t\t\tthis.controller.node().remove();\n\t\t\tthis.compinv.disconnectComponents();\n\t\t\tthis.compinv.saveComponents();\n\t\t\tthis.compinv.removeTagsForDrop();\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void killMinecart(DamageSource dms){\n\t\tsuper.killMinecart(dms);\n\t\tList<ItemStack> drop = new ArrayList<ItemStack>();\n\t\tfor(int i=20;i<23;i+=1){\n\t\t\tif(compinv.getStackInSlot(i)!=null) drop.add(compinv.getStackInSlot(i));\n\t\t}\n\t\tIterator<ItemStack> minv = this.maininv.removeOverflowItems(0).iterator();\n\t\twhile(minv.hasNext()) drop.add(minv.next());\n\t\tItemUtil.dropItemList(drop, this.worldObj, this.posX, this.posY, this.posZ,true);\n\t\tthis.setDamage(Float.MAX_VALUE); //Sometimes the cart stay alive this should fix it.\n\t}\n\t\n\t@Override\n\tpublic boolean interactFirst(EntityPlayer p){\n\t\tItemStack refMan = API.items.get(\"manual\").createItemStack(1);\n\t\tboolean openwiki = p.getHeldItem()!=null && p.isSneaking() && p.getHeldItem().getItem() == refMan.getItem() && p.getHeldItem().getItemDamage() == refMan.getItemDamage();\n\t\t\n\t\tif(Loader.isModLoaded(\"Railcraft\") && RailcraftUtils.isUsingChrowbar(p)) return true;\n\t\t\n\t\tif(this.worldObj.isRemote && openwiki){\n\t\t\tManual.navigate(OCMinecart.MODID+\"/%LANGUAGE%/item/cart.md\");\n\t\t\tManual.openFor(p);\n\t\t}\n\t\telse if(!this.worldObj.isRemote && !openwiki){\n\t\t\tp.openGui(OCMinecart.instance, 1, this.worldObj, this.getEntityId(), -10, 0);\n\t\t}\n\t\telse if(this.worldObj.isRemote && !openwiki){\n\t\t\tp.swingItem();\n\t\t}\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic Node[] onAnalyze(EntityPlayer player, int side, float hitX, float hitY, float hitZ) {\n\t\treturn new Node[]{this.machine.node()};\n\t}\n\t\n\tprivate void checkRailConnection(){\n\t\t//If the cart isn't connected check for a new connection\n\t\tif(!this.cRailCon && this.onRail() && (this.worldObj.getBlock(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.posY), MathHelper.floor_double(this.posZ)) instanceof INetRail)){\n\t\t\tint x = MathHelper.floor_double(this.posX);\n\t\t\tint y = MathHelper.floor_double(this.posY);\n\t\t\tint z = MathHelper.floor_double(this.posZ);\n\t\t\tINetRail netrail = (INetRail) this.worldObj.getBlock(x,y,z);\n\t\t\tif(netrail.isValid(this.worldObj, x, y, z, this) && netrail.getResponseEnvironment(this.worldObj, x, y, z) != null){\n\t\t\t\tthis.cRailX = MathHelper.floor_double(this.posX);\n\t\t\t\tthis.cRailY = MathHelper.floor_double(this.posY);\n\t\t\t\tthis.cRailZ = MathHelper.floor_double(this.posZ);\n\t\t\t\tthis.cRailDim = this.worldObj.provider.dimensionId;\n\t\t\t\tthis.cRailCon = true;\n\t\t\t}\n\t\t}\n\t\t//If the cart is connected to a rail check if the connection is still valid and connect or disconnect\n\t\tif(this.cRailCon){\n\t\t\tWorld w = DimensionManager.getWorld(this.cRailDim);\n\t\t\tif( w.getBlock(this.cRailX,this.cRailY,this.cRailZ) instanceof INetRail){\n\t\t\t\tINetRail netrail = (INetRail) w.getBlock(this.cRailX,this.cRailY,this.cRailZ);\n\t\t\t\t//Connect a new network Rail\n\t\t\t\tif(netrail.isValid(w, this.cRailX, this.cRailY, this.cRailZ, this) && netrail.getResponseEnvironment(w, this.cRailX, this.cRailY, this.cRailZ)!=null){\n\t\t\t\t\tNode railnode = netrail.getResponseEnvironment(w, this.cRailX, this.cRailY, this.cRailZ).node();\n\t\t\t\t\tif(!this.machine.node().canBeReachedFrom(railnode)){\n\t\t\t\t\t\tthis.machine.node().connect(railnode);\n\t\t\t\t\t\tthis.cRailNode = railnode;\n\t\t\t\t\t\tthis.machine.signal(\"network_rail\", true);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//Disconnect when the cart leaves a network rail\n\t\t\t\telse if(netrail.getResponseEnvironment(w, this.cRailX, this.cRailY, this.cRailZ)!=null){\n\t\t\t\t\tNode railnode = netrail.getResponseEnvironment(w, this.cRailX, this.cRailY, this.cRailZ).node();\n\t\t\t\t\tif(this.machine.node().canBeReachedFrom(railnode)){\n\t\t\t\t\t\tthis.machine.node().disconnect(railnode);\n\t\t\t\t\t\tthis.cRailCon=false;\n\t\t\t\t\t\tthis.cRailNode = null;\n\t\t\t\t\t\tthis.machine.signal(\"network_rail\", false);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Disconnect if the network rail is not there\n\t\t\telse{\n\t\t\t\tif(this.cRailNode!=null && this.machine.node().canBeReachedFrom(this.cRailNode)){\n\t\t\t\t\tthis.machine.node().disconnect(this.cRailNode);\n\t\t\t\t\tthis.cRailNode = null;\n\t\t\t\t\tthis.machine.signal(\"network_rail\", false);\n\t\t\t\t}\n\t\t\t\tthis.cRailCon=false;\n\t\t\t}\t\n\t\t}\n\t}\n\t\n\t/*------------------------*/\n\t\n\t/*-----Minecart/Entity-Stuff-------*/\n\t@Override\n\tpublic int getMinecartType() { return -1; }\n\n\tpublic static EntityMinecart create(World w, double x, double y, double z, ComputerCartData data) { return new ComputerCart(w, x, y, z, data); }\n\t\n\t@Override\n\tpublic ItemStack getCartItem(){\n\t\tItemStack stack = new ItemStack(ModItems.item_ComputerCart);\n\t\t\n\t\t\n\t\tMap<Integer,ItemStack> components = new HashMap<Integer,ItemStack>();\n\t\tfor(int i=0;i<20;i+=1){\n\t\t\tif(compinv.getStackInSlot(i)!=null)\n\t\t\t\tcomponents.put(i, compinv.getStackInSlot(i));\n\t\t}\n\t\t\n\t\tComputerCartData data = new ComputerCartData();\n\t\tdata.setEnergy(((Connector)this.machine().node()).localBuffer());\n\t\tdata.setTier(this.tier);\n\t\tdata.setComponents(components);\n\t\tItemComputerCart.setData(stack, data);\n\t\t\n\t\treturn stack;\n\t}\n\t\n\t@Override\n\tpublic void travelToDimension(int dim){\n\t\ttry{\n\t\t\tthis.chDim = true;\n\t\t\tsuper.travelToDimension(dim);\n\t\t}\n\t\tfinally{\n\t\t\tthis.chDim = false;\n\t\t\tthis.setDead();\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean hasCustomInventoryName(){ return true; } // Drop Item on Kill when Player is in Creative Mode\n\t@Override\n\tpublic ItemStack getPickedResult(MovingObjectPosition target){ return null; } \n\t\n\t/*----------------------------------*/\n\t\n\t/*--------MachineHost--------*/\n\t@Override\n\tpublic World world() {\n\t\treturn this.worldObj;\n\t}\n\n\t@Override\n\tpublic double xPosition() {\n\t\treturn this.posX;\n\t}\n\n\t@Override\n\tpublic double yPosition() {\n\t\treturn this.posY;\n\t}\n\n\t@Override\n\tpublic double zPosition() {\n\t\treturn this.posZ;\n\t}\n\n\t@Override\n\tpublic void markChanged() {}\n\n\t@Override\n\tpublic Machine machine() {\n\t\treturn this.machine;\n\t}\n\n\t@Override\n\tpublic Iterable<ItemStack> internalComponents() {\n\t\tArrayList<ItemStack> components = new ArrayList<ItemStack>();\n\t\tfor(int i=0;i<compinv.getSizeInventory();i+=1){\n\t\t\tif(compinv.getStackInSlot(i)!=null && this.compinv.isComponentSlot(i, compinv.getStackInSlot(i)))\n\t\t\t\tcomponents.add(compinv.getStackInSlot(i));\n\t\t}\n\t\treturn components;\n\t}\n\n\t@Override\n\tpublic int componentSlot(String address) {\n\t\tfor(int i=0;i<this.compinv.getSizeInventory();i+=1){\n\t\t\tManagedEnvironment env = this.compinv.getSlotComponent(i);\n\t\t\tif(env != null && env.node()!=null && env.node().address() == address) return i;\n\t\t}\n\t\treturn -1;\n\t}\n\n\t@Override\n\tpublic void onMachineConnect(Node node) {}\n\n\t@Override\n\tpublic void onMachineDisconnect(Node node) {}\n\n\t@Override\n\tpublic IInventory equipmentInventory() { return null; }\n\n\t@Override\n\tpublic IInventory mainInventory() {\n\t\treturn this.maininv;\n\t}\n\n\t@Override\n\tpublic MultiTank tank() {\n\t\treturn this.tanks;\n\t}\n\n\t@Override\n\tpublic int selectedSlot() {\n\t\treturn this.selSlot;\n\t}\n\n\t@Override\n\tpublic void setSelectedSlot(int index) {\n\t\tif(index<this.maininv.getSizeInventory())\n\t\t\tthis.selSlot=index;\n\t}\n\n\t@Override\n\tpublic int selectedTank() {\n\t\treturn this.selTank;\n\t}\n\n\t@Override\n\tpublic void setSelectedTank(int index) {\n\t\tif(index<=this.tank().tankCount())\n\t\t\tthis.selTank=index;\n\t}\n\n\t@Override\n\tpublic EntityPlayer player() {\n\t\tthis.player.updatePositionAndRotation(player, this.facing(), this.facing());\n\t\treturn this.player;\n\t}\n\n\t@Override\n\tpublic String name() {\n\t\treturn this.func_95999_t();\n\t}\n\n\t@Override\n\tpublic void setName(String name) {\n\t\tthis.setMinecartName(name);\n\t}\n\n\t@Override\n\tpublic String ownerName() {\n\t\treturn li.cil.oc.Settings.get().fakePlayerName();\n\t}\n\n\t@Override\n\tpublic UUID ownerUUID() {\n\t\treturn li.cil.oc.Settings.get().fakePlayerProfile().getId();\n\t}\n\n\t@Override\n\tpublic ForgeDirection facing() {\n\t\tForgeDirection res = RotationHelper.directionFromYaw(this.rotationYaw-90D); //Minecarts seem to look at the right side\n\t\treturn res;\n\t}\n\n\t@Override\n\tpublic ForgeDirection toGlobal(ForgeDirection value) {\n\t\treturn RotationHelper.calcGlobalDirection(value, this.facing());\n\t}\n\n\t@Override\n\tpublic ForgeDirection toLocal(ForgeDirection value) {\n\t\treturn RotationHelper.calcLocalDirection(value, this.facing());\n\t}\n\n\t@Override\n\tpublic Node node() {\n\t\treturn this.machine.node();\n\t}\n\n\t@Override\n\tpublic void onConnect(Node node) {}\n\n\t@Override\n\tpublic void onDisconnect(Node node) {}\n\n\t@Override\n\tpublic void onMessage(Message message) {}\n\n\t@Override\n\tpublic int tier() {\n\t\treturn this.tier;\n\t}\n\t/*-----------------------------*/\n\t\n\t/*-------Inventory--------*/\n\n\t@Override\n\tpublic int getSizeInventory() {\n\t\treturn this.maininv.getSizeInventory();\n\t}\n\n\t@Override\n\tpublic ItemStack getStackInSlot(int slot) {\n\t\treturn this.maininv.getStackInSlot(slot);\n\t}\n\n\t@Override\n\tpublic ItemStack decrStackSize(int slot, int number) {\n\t\treturn this.maininv.decrStackSize(slot, number);\n\t}\n\n\t@Override\n\tpublic ItemStack getStackInSlotOnClosing(int slot) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void setInventorySlotContents(int slot, ItemStack stack) {\n\t\tthis.maininv.setInventorySlotContents(slot, stack);\n\t}\n\n\t@Override\n\tpublic String getInventoryName() {\n\t\treturn \"inventory.\"+OCMinecart.MODID+\".computercart\";\n\t}\n\n\t@Override\n\tpublic int getInventoryStackLimit() {\n\t\treturn this.maininv.getInventoryStackLimit();\n\t}\n\n\t@Override\n\tpublic void markDirty() {}\n\n\t@Override\n\tpublic boolean isUseableByPlayer(EntityPlayer player) {\n\t\treturn player.getDistanceSqToEntity(this)<=64 && !this.isDead;\n\t}\n\n\t@Override\n\tpublic void openInventory() {}\n\t@Override\n\tpublic void closeInventory() {}\n\n\t@Override\n\tpublic boolean isItemValidForSlot(int slot, ItemStack stack) {\n\t\treturn this.maininv.isItemValidForSlot(slot, stack);\n\t}\n\t\n/*------Tanks-------*/\n\t\n\tpublic int tankcount(){\n\t\tint c = 0;\n\t\tfor(int i=0;i<this.compinv.getSizeInventory();i+=1){\n\t\t\tif(this.compinv.getSlotComponent(i) instanceof IFluidTank){\n\t\t\t\tc+=1;\n\t\t\t}\n\t\t}\n\t\treturn c;\n\t}\n\t\n\tpublic IFluidTank getTank(int index){\n\t\tint c = 0;\n\t\tfor(int i=0;i<this.compinv.getSizeInventory();i+=1){\n\t\t\tif(this.compinv.getSlotComponent(i) instanceof IFluidTank){\n\t\t\t\tc+=1;\n\t\t\t\tif(c==index) return (IFluidTank) this.compinv.getSlotComponent(i);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t@Override\n\tpublic int fill(ForgeDirection from, FluidStack resource, boolean doFill) {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean canFill(ForgeDirection from, Fluid fluid) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean canDrain(ForgeDirection from, Fluid fluid) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic FluidTankInfo[] getTankInfo(ForgeDirection from) {\n\t\treturn new FluidTankInfo[]{};\n\t}\n\t/*--------------------*/\n\n\t/*-----Component-Inv------*/\n\t@Override\n\tpublic int componentCount() {\n\t\tint count = 0;\n\t\tIterator<ManagedEnvironment> list=this.compinv.getComponents().iterator();\n\t\twhile(list.hasNext()){\n\t\t\tcount+=1;\n\t\t\tlist.next();\n\t\t}\n\t\treturn count;\n\t}\n\n\t@Override\n\tpublic Environment getComponentInSlot(int index) {\n\t\tif(index>=this.compinv.getSizeInventory()) return null;\n\t\treturn this.compinv.getSlotComponent(index);\n\t}\n\n\t@Override\n\tpublic void synchronizeComponentSlot(int slot) {\n\t\tif(!this.worldObj.isRemote)\n\t\t\tModNetwork.sendToNearPlayers(new ComputercartInventoryUpdate(this, slot, this.compinv.getStackInSlot(slot)), this.posX, this.posY, this.posZ, this.worldObj);\n\t}\n\t\n\t/*---------Railcraft---------*/\n\t\n\tpublic void lockdown(boolean lock){\n\t\tsuper.lockdown(lock);\n\t\tif(lock != this.isLocked())\n\t\t\tthis.machine.signal(\"cart_lockdown\", lock);\n\t}\n\n\t/*------Setters & Getters-----*/\n\tpublic ComponetInventory getCompinv() {\n\t\treturn this.compinv;\n\t}\n\t\n\tpublic void setRunning(boolean newVal) {\n\t\tif(this.worldObj.isRemote) this.isRun=newVal;\n\t\telse{\n\t\t\tif(newVal) this.machine.start();\n\t\t\telse this.machine.stop();\n\t\t}\n\t}\n\t\n\tpublic boolean getRunning() {\n\t\treturn this.isRun;\n\t}\n\n\tpublic double getCurEnergy() {\n\t\tif(!this.worldObj.isRemote) return ((Connector)this.machine.node()).globalBuffer();\n\t\treturn -1;\n\t}\n\t\n\tpublic double getMaxEnergy() {\n\t\tif(!this.worldObj.isRemote) return ((Connector)this.machine.node()).globalBufferSize();\n\t\treturn -1;\n\t}\n\t\n\tprotected void setInventorySpace(int invsize) { this.invsize = invsize; }\n\tpublic int getInventorySpace() { return this.invsize; }\n\t\n\tpublic boolean getBrakeState(){ return this.getBrake(); }\n\tpublic void setBrakeState(boolean state){ this.setBrake(state);}\n\t\n\tpublic double getEngineState(){ return this.getEngine(); }\n\tpublic void setEngineState(double speed){ this.setEngine(speed); }\n\t\n\tpublic int getLightColor(){ return this.dataWatcher.getWatchableObjectInt(24); }\n\tpublic void setLightColor(int color){ this.dataWatcher.updateObject(24, color);}\n\t\n\tpublic boolean hasNetRail(){ return this.cRailCon; }\n\n\t@Override\n\tprotected double addEnergy(double amount, boolean simulate) {\n\t\tConnector n = ((Connector)this.machine.node());\n\t\tdouble max = Math.min(n.globalBufferSize() - n.globalBuffer(), amount);\n\t\tif(!simulate){\n\t\t\tmax -= n.changeBuffer(max);\n\t\t}\n\t\treturn max;\n\t}\n}",
"public class InventoryUtil {\n\n\tpublic static int dropItemInventoryWorld(ItemStack stack, World world, int x, int y, int z, ForgeDirection access, int num){\n\t\tTileEntity entity = world.getTileEntity(x, y, z);\n\t\tif(entity instanceof IInventory){\n\t\t\treturn putInventory(stack, (IInventory) entity, num, access);\n\t\t}\n\t\treturn -1;\n\t}\n\t\n\tpublic static int suckItemInventoryWorld(IInventory target, int[] taccess, World world, int x, int y, int z, ForgeDirection access, int num){\n\t\treturn suckItemInventoryWorld(target, taccess, -1, world, x,y,z, access, num);\n\t}\n\t\n\tpublic static int suckItemInventoryWorld(IInventory target, int[] taccess, int tfirst, World world, int x, int y, int z, ForgeDirection access, int num){\n\t\tTileEntity entity = world.getTileEntity(x, y, z);\n\t\tint moved = 0;\n\t\tif(entity instanceof IInventory){\n\t\t\tfor(int i=0;i<taccess.length && moved<1;i+=1){\n\t\t\t\tItemStack filter = target.getStackInSlot(taccess[i]);\n\t\t\t\tint num2 =Math.min(num, spaceforItem(filter,target,taccess));\n\t\t\t\tItemStack mov = suckInventory(filter, (IInventory) entity, num2, access);\n\t\t\t\tif(mov!=null && mov.stackSize>0){\n\t\t\t\t\tmoved = mov.stackSize;\n\t\t\t\t\tint[] slots = sortAccessible(target, taccess, mov);\n\t\t\t\t\tif(tfirst >= 0) slots = prioritizeAccessible(slots, tfirst);\n\t\t\t\t\tputInventory(mov,target,64,ForgeDirection.UNKNOWN,slots);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn moved;\n\t\t}\n\t\treturn -1;\n\t}\n\t\n\tpublic static ItemStack suckInventory(ItemStack filter,IInventory inv, int maxnum, ForgeDirection access) {\n\t\tint[] slots = getAccessible(inv,access);\n\t\tItemStack pulled = null;\n\t\tfor(int i=0;i<inv.getSizeInventory() && maxnum>0;i+=1){\n\t\t\tItemStack slot = inv.getStackInSlot(slots[i]);\n\t\t\tif(slot != null && (filter==null || (filter!=null && filter.isItemEqual(slot)))){\n\t\t\t\tif(!(!(inv instanceof ISidedInventory) || ((inv instanceof ISidedInventory) && ((ISidedInventory)inv).canInsertItem(slots[i], slot, access.ordinal()))))\n\t\t\t\t\tcontinue;\n\t\t\t\tint stacksize = slot.stackSize;\n\t\t\t\tif(filter==null) filter = slot.copy();\n\t\t\t\tif(maxnum>=stacksize){\n\t\t\t\t\tItemStack stack = slot.copy();\n\t\t\t\t\tinv.setInventorySlotContents(slots[i], null);\n\t\t\t\t\tif(pulled == null) pulled = stack;\n\t\t\t\t\telse pulled = ItemUtil.sumItemStacks(stack, pulled, false);\n\t\t\t\t\tmaxnum-=stacksize;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tif(pulled == null) pulled = slot.splitStack(maxnum);\n\t\t\t\t\telse pulled = ItemUtil.sumItemStacks( slot.splitStack(maxnum), pulled, false);\n\t\t\t\t\tmaxnum = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn pulled;\n\t}\n\t\n\tpublic static int putInventory(ItemStack stack, IInventory inv, int maxnum, ForgeDirection access){\n\t\tint[] slots = getAccessible(inv,access);\n\t\tslots = sortAccessible(inv, slots, stack);\n\t\treturn putInventory(stack,inv,maxnum,access,slots);\n\t}\n\n\tpublic static int putInventory(ItemStack stack, IInventory inv, int maxnum, ForgeDirection access, int[] slots){\n\t\tint maxcount = maxnum;\n\t\tfor(int i=0;i<slots.length;i+=1){\n\t\t\tif(!(!(inv instanceof ISidedInventory) || ((inv instanceof ISidedInventory) && ((ISidedInventory)inv).canInsertItem(slots[i], stack, access.ordinal()))))\n\t\t\t\tcontinue;\n\t\t\tif(!inv.isItemValidForSlot(slots[i], stack)) continue;\n\t\t\tItemStack slot = inv.getStackInSlot(slots[i]);\n\t\t\tif(slot == null || (slot!=null && slot.isItemEqual(stack))){\n\t\t\t\tint stacksize = Math.min(stack.getMaxStackSize(), inv.getInventoryStackLimit());\n\t\t\t\tint tstack = Math.min(stacksize, maxcount);\n\t\t\t\ttstack = Math.min(tstack, stack.stackSize);\n\t\t\t\tif(tstack<1) continue;\n\t\t\t\tif(slot!=null){\n\t\t\t\t\ttstack = Math.min(tstack, stacksize - slot.stackSize);\n\t\t\t\t\tslot.stackSize+=tstack;\n\t\t\t\t\tstack.stackSize-=tstack;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tItemStack newstack = stack.copy();\n\t\t\t\t\tstack.stackSize-=tstack;\n\t\t\t\t\tnewstack.stackSize = tstack;\n\t\t\t\t\tinv.setInventorySlotContents(slots[i], newstack);\n\t\t\t\t}\n\t\t\t\tmaxcount-=tstack;\n\t\t\t}\n\t\t}\n\t\treturn maxnum-maxcount;\n\t}\n\t\n\tpublic static int[] sortAccessible(IInventory inv, int[] slots, ItemStack stack){\n\t\tint[] res = new int[slots.length];\n\t\tArrayList<Integer> sort = new ArrayList<Integer>();\n\t\tfor(int i=0;i<slots.length;i+=1){\t//Check all slots with matching Items\n\t\t\tItemStack slot = inv.getStackInSlot(slots[i]);\n\t\t\tif(slot!=null && slot.isItemEqual(stack))\n\t\t\t\tsort.add(slots[i]);\n\t\t}\n\t\tfor(int i=0;i<slots.length;i+=1){\t//Add all other slots\n\t\t\tif(!sort.contains(slots[i]))\n\t\t\t\tsort.add(slots[i]);\n\t\t}\n\t\tfor(int i=0;i<sort.size();i+=1){ //Convert the List to a Array\n\t\t\tif(i<res.length)\n\t\t\t\tres[i] = sort.get(i);\n\t\t}\n\t\treturn res;\n\t}\n\t\n\tpublic static int[] prioritizeAccessible(int[] slots, int slot){\n\t\tint[] res = new int[slots.length];\n\t\tArrayList<Integer> sort = new ArrayList<Integer>();\n\t\tfor(int i=0;i<slots.length;i+=1){\t//Check if slot is a accessible slot\n\t\t\tif(slots[i] == slot){\n\t\t\t\tfor(int j=i;j<slots.length;j+=1){\n\t\t\t\t\tsort.add(slots[j]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor(int i=0;i<slots.length;i+=1){\t//Add all other slots\n\t\t\tif(!sort.contains(slots[i]))\n\t\t\t\tsort.add(slots[i]);\n\t\t}\n\t\tfor(int i=0;i<sort.size();i+=1){ //Convert the List to a Array\n\t\t\tif(i<res.length)\n\t\t\t\tres[i] = sort.get(i);\n\t\t}\n\t\treturn res;\n\t}\n\t\n\tpublic static int[] getAccessible(IInventory inv, ForgeDirection access){\n\t\tif((inv instanceof ISidedInventory) && access != ForgeDirection.UNKNOWN) \n\t\t\treturn ((ISidedInventory)inv).getAccessibleSlotsFromSide(access.ordinal());\n\t\tint sides[] = new int[inv.getSizeInventory()];\n\t\tfor(int i=0;i<inv.getSizeInventory();i+=1){\n\t\t\tsides[i]=i;\n\t\t}\n\t\t\n\t\treturn sides;\n\t}\n\t\n\t/*\n\t * Takes all items from invA and returns the matching slots in invB\n\t */\n\tpublic static int spaceforItem(ItemStack stack, IInventory inv, int[] access){\n\t\tint space = 0;\n\t\tint maxstack = Math.min((stack==null) ? 64 : stack.getMaxStackSize(), inv.getInventoryStackLimit());\n\t\tfor(int i=0;i<access.length;i+=1){\n\t\t\tItemStack slot = inv.getStackInSlot(access[i]);\n\t\t\tif(slot==null)\n\t\t\t\tspace+=maxstack;\n\t\t\telse if(stack != null && slot.isItemEqual(stack)){\n\t\t\t\tspace+=Math.max(0, maxstack-slot.stackSize);\n\t\t\t}\n\t\t}\n\t\treturn space;\n\t}\n\t\n\t/*\n\t * Try inserting an item stack into a player inventory. If that fails, drop it into the world.\n\t * Copy from li.cil.oc.util.InventoryUtils Line 308\n\t */\n\tpublic static void addToPlayerInventory(ItemStack stack, EntityPlayer player) {\n\t\tif (stack != null) {\n\t\t\tif (player.inventory.addItemStackToInventory(stack)) {\n\t\t\t\tplayer.inventory.markDirty();\n\t\t\t\tif (player.openContainer != null) {\n\t\t\t\t\tplayer.openContainer.detectAndSendChanges();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (stack.stackSize > 0) {\n\t\t\t\tplayer.dropPlayerItemWithRandomChoice(stack, false);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\n}",
"public class ItemUtil {\n\tpublic static void dropItemList(Iterable<ItemStack> items, World world, double x, double y, double z, boolean motion){\n\t\tif(!world.isRemote){\n\t\t\tIterator<ItemStack> itemlist = items.iterator();\n\t\t\twhile(itemlist.hasNext()){\n\t\t\t\tItemStack stack = itemlist.next();\n\t\t\t\tif(stack.stackSize > 0){\n\t\t\t\t\tEntityItem entityitem = new EntityItem(world, x, y, z, stack);\n\t\t\t\t\tentityitem.delayBeforeCanPickup = 10;\n\t\t\t\t\tif(!motion){\n\t\t\t\t\t\tentityitem.motionX=0;\n\t\t\t\t\t\tentityitem.motionY=0;\n\t\t\t\t\t\tentityitem.motionZ=0;\n\t\t\t\t\t}\n\t\t\t\t\tworld.spawnEntityInWorld(entityitem);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void dropItem(ItemStack stack, World world, double x, double y, double z, boolean motion){\n\t\tif(stack.stackSize > 0){\n\t\t\tEntityItem entityitem = new EntityItem(world, x, y, z, stack);\n\t\t\tentityitem.delayBeforeCanPickup = 10;\n\t\t\tif(!motion){\n\t\t\t\tentityitem.motionX=0;\n\t\t\t\tentityitem.motionY=0;\n\t\t\t\tentityitem.motionZ=0;\n\t\t\t}\n\t\t\tworld.spawnEntityInWorld(entityitem);\n\t\t}\n\t}\n\t\n\tpublic static ItemStack suckItems(World world, int x, int y, int z, ItemStack filter, int num){\n\t\tif(!world.isRemote){\n\t\t\tArrayList<ItemStack> items = new ArrayList<ItemStack>();\n\t\t\tAxisAlignedBB box = AxisAlignedBB.getBoundingBox(1,1,1,16,16,16);\n\t\t\tbox.offset(x-1, y-1, z-1);\n\t\t\tList entls = world.getEntitiesWithinAABB(EntityItem.class, box);\n\t\t\tIterator entit = entls.iterator();\n\t\t\twhile(entit.hasNext()){\n\t\t\t\tEntity ent = (Entity) entit.next();\n\t\t\t\tif(!(ent instanceof EntityItem)) continue;\n\t\t\t\tItemStack stack = ((EntityItem)ent).getEntityItem();\n\t\t\t\tif(!(filter==null || (filter!=null && filter.isItemEqual(stack)))) continue;\n\t\t\t\tItemStack ret = stack.copy();\n\t\t\t\tret.stackSize = Math.min(ret.stackSize, num);\n\t\t\t\tstack.stackSize-=ret.stackSize;\n\t\t\t\tif(stack.stackSize<1)ent.setDead();\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic static boolean hasDroppedItems(World world, int x, int y, int z){\n\t\tif(!world.isRemote){\n\t\t\tArrayList<ItemStack> items = new ArrayList<ItemStack>();\n\t\t\tAxisAlignedBB box = AxisAlignedBB.getBoundingBox(1,1,1,16,16,16);\n\t\t\tbox.offset(x-1, y-1, z-1);\n\t\t\tList entls = world.getEntitiesWithinAABB(EntityItem.class, box);\n\t\t\treturn !entls.isEmpty();\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic static ItemStack sumItemStacks(ItemStack stackA, ItemStack stackB, boolean pull){\n\t\tItemStack res = null;\n\t\tif(stackA==null || stackB==null) return null;\n\t\tif(!stackA.isItemEqual(stackB)) return null;\n\t\tres = stackA.copy();\n\t\tint size = stackA.stackSize + stackB.stackSize;\n\t\tsize = Math.min(size, res.getMaxStackSize());\n\t\tres.stackSize = size;\n\t\tif(pull){\n\t\t\tif(size >= stackA.stackSize){\n\t\t\t\tsize-=stackA.stackSize;\n\t\t\t\tstackA.stackSize=0;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tstackA.stackSize-=size;\n\t\t\t\tsize=0;\n\t\t\t}\n\t\t\t\n\t\t\tif(size >= stackB.stackSize){\n\t\t\t\tsize-=stackB.stackSize;\n\t\t\t\tstackB.stackSize=0;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tstackB.stackSize-=size;\n\t\t\t\tsize=0;\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n}",
"public class TankUtil {\n\t\n\tpublic static IFluidHandler getFluidHandler(World w, int x, int y, int z){\n\t\tif(w.isRemote) return null;\n\t\tTileEntity entity = w.getTileEntity(x, y, z);\n\t\tif(entity == null || !(entity instanceof IFluidHandler)) return null;\t\t\n\t\treturn (IFluidHandler)entity;\n\t}\n\t\n\tpublic static int getSpaceForFluid(IFluidHandler tank, FluidStack stack, ForgeDirection side){\n\t\tFluidTankInfo[] inf = tank.getTankInfo(side);\n\t\tint space = 0;\n\t\tfor(int i=0;i<inf.length;i+=1){\n\t\t\tif(inf[i].fluid == null)\n\t\t\t\tspace += inf[i].capacity;\n\t\t\telse if(inf[i].fluid.isFluidEqual(stack))\n\t\t\t\tspace += inf[i].capacity - inf[i].fluid.amount;\n\t\t}\n\t\treturn space;\n\t}\n\t\n\tpublic static boolean hasFluid(IFluidHandler tank, FluidStack stack, ForgeDirection side){\n\t\tFluidTankInfo[] inf = tank.getTankInfo(side);\n\t\tfor(int i=0;i<inf.length;i+=1){\n\t\t\tif(inf[i].fluid.isFluidEqual(stack))\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n}"
] | import li.cil.oc.api.API;
import li.cil.oc.api.machine.Arguments;
import li.cil.oc.api.machine.Callback;
import li.cil.oc.api.machine.Context;
import li.cil.oc.api.network.*;
import mods.ocminecart.Settings;
import mods.ocminecart.common.minecart.ComputerCart;
import mods.ocminecart.common.util.InventoryUtil;
import mods.ocminecart.common.util.ItemUtil;
import mods.ocminecart.common.util.TankUtil;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidHandler;
import net.minecraftforge.fluids.IFluidTank;
import java.util.ArrayList; | package mods.ocminecart.common.component;
public class ComputerCartController implements ManagedEnvironment{
private Node node;
private ComputerCart cart;
public ComputerCartController(ComputerCart cart){
this.cart = cart;
node = API.network.newNode(this, Visibility.Neighbors).withComponent("computercart").create();
}
@Override
public Node node() {
return node;
}
@Override
public void onConnect(Node node) {
}
@Override
public void onDisconnect(Node node) {
}
@Override
public void onMessage(Message message) {}
@Override
public void load(NBTTagCompound nbt) {
if(nbt.hasKey("node")) ((Component)this.node).load(nbt.getCompoundTag("node"));
}
@Override
public void save(NBTTagCompound nbt) {
NBTTagCompound node = new NBTTagCompound();
((Component)this.node).save(node);
nbt.setTag("node", node);
}
@Override
public boolean canUpdate() {
return false;
}
@Override
public void update() {}
/*--------Component-Functions-Cart--------*/
@Callback(doc="function(set:boolean):boolen, string -- Enable/Disable the brake. String for errors")
public Object[] setBrake(Context context, Arguments arguments){
boolean state = arguments.checkBoolean(0);
if(this.cart.getSpeed() > this.cart.getMaxCartSpeedOnRail() && state){
return new Object[]{this.cart.getBrakeState(), "too fast"};
}
this.cart.setBrakeState(state);
return new Object[]{state, null};
}
@Callback(direct = true,doc="function():boolean -- Get the status of the brake.")
public Object[] getBrake(Context context, Arguments arguments){
return new Object[]{this.cart.getBrakeState()};
}
@Callback(direct = true,doc="function():number -- Get engine speed")
public Object[] getEngineSpeed(Context context, Arguments arguments){
return new Object[]{this.cart.getEngineState()};
}
@Callback(doc="function():number -- Get current speed of the cart. -1 if there is no rail")
public Object[] getCartSpeed(Context context, Arguments arguments){
double speed = -1;
if(this.cart.onRail()){
speed = this.cart.getSpeed();
}
return new Object[]{speed};
}
@Callback(doc="function(speed:number):number -- Set the engine speed.")
public Object[] setEngineSpeed(Context context, Arguments arguments){
double speed = Math.max(Math.min(arguments.checkDouble(0), this.cart.getMaxCartSpeedOnRail()), 0);
this.cart.setEngineState(speed);
return new Object[]{speed};
}
@Callback(doc="function():number -- Get the maximal cart speed")
public Object[] getMaxSpeed(Context context, Arguments arguments){
return new Object[]{this.cart.getMaxCartSpeedOnRail()};
}
@Callback(doc="function(color:number):number -- Set light color")
public Object[] setLightColor(Context context, Arguments arguments){
int color = arguments.checkInteger(0);
this.cart.setLightColor(color);
return new Object[]{color};
}
@Callback(direct = true,doc="function():number -- Get light color")
public Object[] getLightColor(Context context, Arguments arguments){
return new Object[]{this.cart.getLightColor()};
}
@Callback(doc="function() -- Rotate the cart")
public Object[] rotate(Context context, Arguments arguments){
float yaw = this.cart.rotationYaw + 180F;
if(yaw>180) yaw-=360F;
else if(yaw<-180) yaw+=360F;
this.cart.rotationYaw = yaw;
//OCMinecart.logger.info("Rotate: "+this.cart.rotationYaw+" + "+cart.facing().toString());
return new Object[]{};
}
@Callback(direct = true,doc="function():boolean -- Check if the cart is on a rail")
public Object[] onRail(Context context, Arguments arguments){
return new Object[]{this.cart.onRail()};
}
@Callback(direct = true,doc="function():boolean -- Check if the cart is connected to a network rail")
public Object[] hasNetworkRail(Context context, Arguments arguments){
return new Object[]{this.cart.hasNetRail()};
}
@Callback(direct = true,doc="function():boolean -- Check if the cart is locked on a track")
public Object[] isLocked(Context context, Arguments arguments){
return new Object[]{this.cart.isLocked()};
}
/*--------Component-Functions-Inventory--------*/
@Callback(doc = "function():number -- The size of this device's internal inventory.")
public Object[] inventorySize(Context context, Arguments arguments){
return new Object[]{this.cart.getInventorySpace()};
}
@Callback(doc = "function([slot:number]):number -- Get the currently selected slot; set the selected slot if specified.")
public Object[] select(Context context, Arguments args){
int slot = args.optInteger(0, 0);
if(slot > 0 && slot <= this.cart.maininv.getMaxSizeInventory()){
this.cart.setSelectedSlot(slot-1);
}
else if(args.count() > 0){
throw new IllegalArgumentException("invalid slot");
}
return new Object[]{this.cart.selectedSlot()+1};
}
@Callback(direct = true, doc = "function([slot:number]):number -- Get the number of items in the specified slot, otherwise in the selected slot.")
public Object[] count(Context context, Arguments args){
int slot = args.optInteger(0, -1);
int num = 0;
slot = (args.count() > 0) ? slot-1 : this.cart.selectedSlot();
if(slot >= 0 && slot < this.cart.getInventorySpace()){
if(this.cart.mainInventory().getStackInSlot(slot)!=null){
num = this.cart.mainInventory().getStackInSlot(slot).stackSize;
}
}
else{
if(args.count() < 1)
return new Object[]{ 0 , "no slot selected"};
throw new IllegalArgumentException("invalid slot");
}
return new Object[]{num};
}
@Callback(direct = true, doc = "function([slot:number]):number -- Get the remaining space in the specified slot, otherwise in the selected slot.")
public Object[] space(Context context, Arguments args){
int slot = args.optInteger(0, -1);
int num = 0;
slot = (args.count() > 0) ? slot-1 : this.cart.selectedSlot();
if(slot > 0 && slot <= this.cart.getInventorySpace()){
ItemStack stack = this.cart.mainInventory().getStackInSlot(slot-1);
if(stack!=null){
int maxStack = Math.min(this.cart.mainInventory().getInventoryStackLimit(), stack.getMaxStackSize());
num = maxStack-stack.stackSize;
}
else{
num = this.cart.mainInventory().getInventoryStackLimit();
}
}
else{
if(args.count() < 1)
return new Object[]{ 0 , "no slot selected"};
throw new IllegalArgumentException("invalid slot");
}
return new Object[]{num};
}
@Callback(doc = "function(otherSlot:number):boolean -- Compare the contents of the selected slot to the contents of the specified slot.")
public Object[] compareTo(Context context, Arguments args){
int slotA = args.checkInteger(0) - 1;
int slotB = this.cart.selectedSlot();
boolean result;
if(slotB>=0 && slotB<this.cart.mainInventory().getSizeInventory())
return new Object[]{ false , "no slot selected"};
if(slotA>=0 && slotA<this.cart.mainInventory().getSizeInventory()){
ItemStack stackA = this.cart.mainInventory().getStackInSlot(slotA);
ItemStack stackB = this.cart.mainInventory().getStackInSlot(slotB);
result = (stackA==null && stackB==null) ||
(stackA!=null && stackB!=null && stackA.isItemEqual(stackB));
return new Object[]{result};
}
throw new IllegalArgumentException("invalid slot");
}
@Callback(doc = "function(toSlot:number[, amount:number]):boolean -- Move up to the specified amount of items from the selected slot into the specified slot.")
public Object[] transferTo(Context context, Arguments args){
int tslot = args.checkInteger(0) - 1;
int number = args.optInteger(1, this.cart.mainInventory().getInventoryStackLimit());
if(!(tslot>=0 && tslot<this.cart.mainInventory().getSizeInventory()))
throw new IllegalArgumentException("invalid slot");
if(!(this.cart.selectedSlot()>=0 && this.cart.selectedSlot()<this.cart.mainInventory().getSizeInventory()))
return new Object[]{ false , "no slot selected"};
ItemStack stackT = this.cart.mainInventory().getStackInSlot(tslot);
ItemStack stackS = this.cart.mainInventory().getStackInSlot(this.cart.selectedSlot());
if(!(stackT==null || (stackS!=null && stackT!=null && stackT.isItemEqual(stackS))) || stackS == null)
return new Object[]{false};
int items = 0;
int maxStack = Math.min(this.cart.mainInventory().getInventoryStackLimit(), stackS.getMaxStackSize());
items = maxStack - ((stackT!=null) ? stackT.stackSize : 0);
items = Math.min(items, number);
if(items<=0) return new Object[]{false};
ItemStack dif = this.cart.mainInventory().decrStackSize(this.cart.selectedSlot(), items);
if(stackT!=null){
stackT.stackSize+=dif.stackSize;
}
else{
this.cart.mainInventory().setInventorySlotContents(tslot, dif);
}
return new Object[]{true};
}
/*--------Component-Functions-Tank--------*/
@Callback(doc = "function():number -- The number of tanks installed in the device.")
public Object[] tankCount(Context context, Arguments args){
return new Object[]{ this.cart.tankcount() };
}
@Callback(doc = "function([index:number]):number -- Select a tank and/or get the number of the currently selected tank.")
public Object[] selectTank(Context context, Arguments args){
int index = args.optInteger(0, 0);
if(index > 0 && index <=this.cart.tankcount())
this.cart.setSelectedTank(index);
else if(args.count() > 0)
throw new IllegalArgumentException("invalid tank index");
return new Object[]{this.cart.selectedTank()};
}
@Callback(direct = true, doc = "function([index:number]):number -- Get the fluid amount in the specified or selected tank.")
public Object[] tankLevel(Context context, Arguments args){
int index = args.optInteger(0, 0);
index = (args.count()>0) ? index : this.cart.selectedTank();
if(!(index>0 && index<=this.cart.tankcount())){
if(args.count()<1)
return new Object[]{ false ,"no tank selected" };
throw new IllegalArgumentException("invalid tank index");
}
return new Object[]{ this.cart.getTank(index).getFluidAmount() };
}
@Callback(direct = true, doc = "function([index:number]):number -- Get the remaining fluid capacity in the specified or selected tank.")
public Object[] tankSpace(Context context, Arguments args){
int index = args.optInteger(0, 0);
index = (args.count()>0) ? index : this.cart.selectedTank();
if(!(index>0 && index<=this.cart.tankcount())){
if(args.count()<1)
return new Object[]{ false ,"no tank selected" };
throw new IllegalArgumentException("invalid tank index");
}
IFluidTank tank = this.cart.getTank(index);
return new Object[]{ tank.getCapacity() - tank.getFluidAmount() };
}
@Callback(doc = "function(index:number):boolean -- Compares the fluids in the selected and the specified tank. Returns true if equal.")
public Object[] compareFluidTo(Context context, Arguments args){
int tankA = args.checkInteger(0);
int tankB = this.cart.selectedTank();
if(!(tankA>0 && tankA<=this.cart.tankcount()))
throw new IllegalArgumentException("invalid tank index");
if(!(tankB>0 && tankB<=this.cart.tankcount()))
return new Object[]{ false ,"no tank selected" };
FluidStack stackA = this.cart.getTank(tankA).getFluid();
FluidStack stackB = this.cart.getTank(tankB).getFluid();
boolean res = (stackA==null && stackB==null);
if(!res && stackA!=null && stackB!=null)
res = stackA.isFluidEqual(stackB);
return new Object[]{ res };
}
@Callback(doc = "function(index:number[, count:number=1000]):boolean -- Move the specified amount of fluid from the selected tank into the specified tank.")
public Object[] transferFluidTo(Context context, Arguments args){
int tankA = args.checkInteger(0);
int tankB = this.cart.selectedTank();
int count = args.optInteger(1, 1000);
if(!(tankA>0 && tankA<=this.cart.tankcount()))
throw new IllegalArgumentException("invalid tank index");
if(!(tankB>0 && tankB<=this.cart.tankcount()))
return new Object[]{ false ,"no tank selected" };
IFluidTank tankT = this.cart.getTank(tankA);
IFluidTank tankS = this.cart.getTank(tankB);
if(tankS.getFluid()==null || (tankT!=null && tankS.getFluid().isFluidEqual(tankT.getFluid())))
return new Object[]{ false };
FluidStack sim = tankS.drain(count, false); //Simulate the transfer to get the max. moveable amount.
int move = tankT.fill(sim, false);
if(move<=0) return new Object[]{ false };
FluidStack mv = tankS.drain(move, true);
int over = tankT.fill(mv, true);
over-=mv.amount;
if(over>0){ //Just in case we drained too much.
FluidStack ret = mv.copy();
ret.amount = over;
tankS.fill(ret, true);
}
return new Object[]{ true };
}
//--------World-Inventory----------//
@Callback(doc = "function(side:number[, count:number=64]):boolean -- Drops items from the selected slot towards the specified side.")
public Object[] drop(Context context, Arguments args){
int side = args.checkInteger(0);
int amount = args.optInteger(1,64);
if(side<0 || side > 5) throw new IllegalArgumentException("invalid side");
int sslot = this.cart.selectedSlot();
if(!(sslot>=0 && sslot<this.cart.mainInventory().getSizeInventory()))
return new Object[]{ false , "no slot selected"};
if(amount<1) return new Object[]{ false };
ForgeDirection dir = this.cart.toGlobal(ForgeDirection.getOrientation(side));
int x = (int)Math.floor(this.cart.xPosition())+dir.offsetX;
int y = (int)Math.floor(this.cart.yPosition())+dir.offsetY;
int z = (int)Math.floor(this.cart.zPosition())+dir.offsetZ;
ItemStack dstack = this.cart.mainInventory().getStackInSlot(sslot);
if(dstack == null) return new Object[]{ false };
if(!(this.cart.world().getTileEntity(x, y, z) instanceof IInventory)){
ArrayList<ItemStack> drop = new ArrayList<ItemStack>();
int mov = Math.min(dstack.stackSize, amount);
ItemStack dif = dstack.splitStack(mov);
if(dstack.stackSize < 1)
this.cart.mainInventory().setInventorySlotContents(sslot, null);
drop.add(dif);
ItemUtil.dropItemList(drop, this.cart.world(), x+0.5D, y+0.5D, z+0.5D, false);
context.pause(Settings.OC_DropDelay);
return new Object[]{ true };
}
else{ | int moved = InventoryUtil.dropItemInventoryWorld(dstack.copy(), this.cart.world(), x, y, z, dir.getOpposite(), amount); | 2 |
Wondersoft/olaper | src/main/java/org/olap/server/processor/functions/IdentifiedMember.java | [
"public class MetadataUtils {\n\n\n @SuppressWarnings(\"serial\")\n\tprivate static class MetadataElementNamedList<T extends MetadataElement> extends ArrayNamedListImpl<T> {\n \t\n \tpublic MetadataElementNamedList(List<T> list){\n \t\tfor(T t : list)\n \t\t\tadd(t);\n \t}\n \t\n public String getName(Object element) {\n \treturn ((MetadataElement)element).getName();\n }\n\n\n }\n \n @SuppressWarnings(\"serial\")\n\tprivate static class SchemaNamedList extends ArrayNamedListImpl<Schema> {\n \t\n \tpublic SchemaNamedList(List<Schema> list){\n \t\t\n \t\tfor(Schema t : list)\n \t\t\tadd(t);\n \t}\n \t\n public String getName(Object element) {\n \treturn ((Schema)element).getName();\n }\n\n\n }\n \n @SuppressWarnings(\"serial\")\n\tprivate static class CatalogNamedList extends ArrayNamedListImpl<Catalog> {\n \t\n \tpublic CatalogNamedList(List<Catalog> list){\n \t\t\n \t\tfor(Catalog t : list)\n \t\t\tadd(t);\n \t}\n \t\n public String getName(Object element) {\n \treturn ((Catalog)element).getName();\n }\n\n\n }\n \n @SuppressWarnings(\"serial\")\n\tprivate static class CellSetAxisMetaDataNamedList extends ArrayNamedListImpl<CellSetAxisMetaData> {\n \t\n \tpublic CellSetAxisMetaDataNamedList(List<CellSetAxis> list){\n \t\t\n \t\tfor(CellSetAxis t : list)\n \t\t\tadd(t.getAxisMetaData());\n \t}\n \t\n public String getName(Object element) {\n \treturn ((CellSetAxisMetaData)element).getAxisOrdinal().name();\n }\n\n\n }\n\n public static <T extends MetadataElement> NamedList<T> metadataNamedList(List<T> list){\n \treturn new MetadataElementNamedList<T>(list);\n }\n \n public static NamedList<CellSetAxisMetaData> cellSetNamedList(List<CellSetAxis> list){\n \treturn new CellSetAxisMetaDataNamedList(list);\n }\n\n public static <T extends MetadataElement> NamedList<T> singletoneNamedList(T instance){\n \treturn new MetadataElementNamedList<T>(Collections.singletonList(instance));\n }\n \n public static NamedList<Schema> singletoneNamedList(Schema instance){\n \treturn new SchemaNamedList(Collections.singletonList(instance));\n }\n \n public static NamedList<Catalog> catalogNamedList(List<Catalog> list){\n \treturn new CatalogNamedList(list);\n }\n \n \n\tpublic static Member lookupMember(Cube cube, List<IdentifierSegment> segmentList) {\n\t\t\n\t\tif(segmentList.size() < 3)\n\t\t\treturn null;\n\t\t\n\t\tDimension dim = cube.getDimensions().get(segmentList.get(0).getName());\n\t\tif(dim instanceof ServerDimension){\n\t\t\t\n\t\t\tHierarchy h = dim.getHierarchies().get(segmentList.get(1).getName());\n\t\t\tif(h!=null){\n\t\t\t\t\n\t\t\t\tLevel level = null;\n\t\t\t\tString memberName = null;\n\t\t\t\t\n\t\t\t\tif(segmentList.size()==3){\t\t\n\t\t\t\t\tlevel = h.hasAll() ? h.getLevels().get(1) : h.getLevels().get(0);\n\t\t\t\t\tmemberName = segmentList.get(2).getName();\n\t\t\t\t}else if(segmentList.size()==4){\n\t\t\t\t\tlevel = h.getLevels().get(segmentList.get(2).getName());\n\t\t\t\t\tmemberName = segmentList.get(3).getName();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(level!=null){\n\t\t\t\t\treturn new LevelMember(level, memberName, memberName, 0);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\treturn null;\n\t}\n\n\n\tpublic static Level lookupLevel(Cube cube, List<IdentifierSegment> segmentList) {\n\t\t\n\t\tif(segmentList.size() < 2)\n\t\t\treturn null;\n\t\t\n\t\tDimension dim = cube.getDimensions().get(segmentList.get(0).getName());\n\t\tif(dim instanceof ServerDimension){\n\t\t\t\n\t\t\tHierarchy h = dim.getHierarchies().get(segmentList.get(1).getName());\n\t\t\tif(h!=null && segmentList.size()==3 && h.getLevels().size()==1){\n\t\t\t\treturn h.getLevels().get(0);\n\t\t\t}else if(h!=null && segmentList.size()==4){\n\t\t\t\treturn h.getLevels().get(segmentList.get(2).getName());\n\t\t\t}\n\n\t\t\t\n\t\t}\n\n\t\treturn null;\n\t}\n\n}",
"public class ParseUtils {\n\n\tpublic static String[] identifierNames(IdentifierNode inode){\n\t\t\n\t\tString[] ids = new String[inode.getSegmentList().size()];\n\t\t\n\t\tfor(int i=0; i<inode.getSegmentList().size(); i++){\n\t\t\tNameSegment seg = (NameSegment) inode.getSegmentList().get(i);\n\t\t\tids[i] = seg.getName();\n\t\t}\n\t\t\n\t\treturn ids;\n\t}\n\t\n public static String toString(ParseTreeNode node) {\n StringWriter sw = new StringWriter();\n ParseTreeWriter parseTreeWriter = new ParseTreeWriter(sw);\n node.unparse(parseTreeWriter);\n return sw.toString();\n }\n\t\n public static SelectNode normalize(MdxParser parser, SelectNode selectNode){\n \t\n\t\tSelectNode acopy = selectNode.deepCopy();\n\t\tacopy.getWithList().clear();\n\t\tString resolvedMdx = ParseUtils.toString(acopy);\n\t\t\n\t\tList<ParseTreeNode> withList = selectNode.getWithList();\n\t\t\n\t\tfor(int i=withList.size()-1; i>=0; i--){\n\t\t\tParseTreeNode wnode = withList.get(i);\n\t\t\tif(wnode instanceof WithSetNode){\n\t\t\t\tWithSetNode wsn = (WithSetNode) wnode;\n\t\t\t\tString exprMdx = ParseUtils.toString(wsn.getExpression());\n\t\t\t\tString nameMdx = wsn.getIdentifier().toString();\n\t\t\t\tresolvedMdx = resolvedMdx.replace(nameMdx, exprMdx);\t\t\t\t\n\t\t\t}else if(wnode instanceof WithMemberNode){\n\t\t\t\tWithMemberNode wsn = (WithMemberNode) wnode;\n\t\t\t\tString exprMdx = ParseUtils.toString(wsn.getExpression());\n\t\t\t\tString nameMdx = wsn.getIdentifier().toString();\n\t\t\t\tresolvedMdx = resolvedMdx.replace(nameMdx, exprMdx);\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\t\n\t\treturn parser.parseSelect(resolvedMdx);\n }\n \n public static List<IdentifierNode> getAllIdentifiers(CallNode callNode){\n \treturn getAllIdentifiers(callNode, new ArrayList<IdentifierNode>());\n }\n \n private static List<IdentifierNode> getAllIdentifiers(CallNode callNode, List<IdentifierNode> list){\n \t\n \tfor(ParseTreeNode node : callNode.getArgList()){\n \t\t\n \t\tif(node instanceof CallNode){\n \t\t\tgetAllIdentifiers((CallNode) node, list);\n \t\t}else if(node instanceof IdentifierNode){\n \t\t\tif(!list.contains(node))\n \t\t\t\tlist.add((IdentifierNode) node);\n \t\t}\n \t\t\n \t}\n \t\n \treturn list;\n }\n \n}",
"public class LevelMember implements Member {\n\n\tpublic static final String NULL_MEMBER = \"#null\";\n\t\n\tprivate Level level;\n\tprivate String name, key;\n\tprivate int ordinal;\n\t\n\tpublic LevelMember(Level level, String name, int ordinal){\n\t\tString[] comps = name.split(\"///\",2);\n\t\tthis.level = level;\n\t\tthis.name = clearControls( (comps.length>1 && !comps[0].isEmpty()) ? comps[1] : comps[0]);\n\t\tthis.key = clearControls(comps[0]);\n\t\tthis.ordinal = ordinal;\n\t}\n\t\n\tpublic LevelMember(Level level, String key, String name, int ordinal) {\n\t\tthis.level = level;\n\t\tthis.name = clearControls(name);\n\t\tthis.key = clearControls(key);\n\t\tthis.ordinal = ordinal;\n\t}\n\n\tprivate static String clearControls(String s){\n\t\treturn s==null ? s : s.replaceAll(\"[\\\\p{C}\\\\[\\\\]]\", \"_\");\n\t}\n\t\n\t@Override\n\tpublic String getName() {\n\t\tif(name!=null && !name.equals(key)){\n\t\t\treturn key + \"///\" + name;\n\t\t}else if(key==null){\n\t\t\treturn NULL_MEMBER;\n\t\t}else\n\t\t\treturn key;\n\t}\n\n\t@Override\n\tpublic String getUniqueName() {\t\n\t\t\n\t\treturn level.getUniqueName() + \".[\" + getName() + \"]\";\n\t}\n\n\t@Override\n\tpublic String getCaption() {\n\t\treturn name==null ? NULL_MEMBER : name;\n\t}\n\n\t@Override\n\tpublic String getDescription() {\n\t\treturn name;\n\t}\n\n\t@Override\n\tpublic boolean isVisible() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic NamedList<? extends Member> getChildMembers() throws OlapException {\n\t\treturn Olap4jUtil.emptyNamedList();\n\t}\n\n\t@Override\n\tpublic int getChildMemberCount() throws OlapException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic Member getParentMember() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Level getLevel() {\n\t\treturn level;\n\t}\n\n\t@Override\n\tpublic Hierarchy getHierarchy() {\n\t\treturn level.getHierarchy();\n\t}\n\n\t@Override\n\tpublic Dimension getDimension() {\n\t\treturn level.getDimension();\n\t}\n\n\t@Override\n\tpublic Type getMemberType() {\n\t\treturn Type.REGULAR;\n\t}\n\n\t@Override\n\tpublic boolean isAll() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isChildOrEqualTo(Member member) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isCalculated() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int getSolveOrder() {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic ParseTreeNode getExpression() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic List<Member> getAncestorMembers() {\n\t\treturn Collections.emptyList();\n\t}\n\n\t@Override\n\tpublic boolean isCalculatedInQuery() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic Object getPropertyValue(Property property) throws OlapException {\n\t\tif(property==Property.StandardMemberProperty.$visible){\n\t\t\treturn new Boolean(isVisible());\n\t\t}else if(property==Property.StandardMemberProperty.CHILDREN_CARDINALITY){\n\t\t\treturn 0;\n\t\t}else if(property==Property.StandardCellProperty.DATATYPE){\n\t\t\treturn \"String\";\n\t\t}else if(property==Property.StandardMemberProperty.MEMBER_UNIQUE_NAME){\n\t\t\treturn getUniqueName();\n\t\t}else if(property==Property.StandardMemberProperty.MEMBER_CAPTION){\n\t\t\treturn getCaption();\n\t\t}else if(property==Property.StandardMemberProperty.LEVEL_UNIQUE_NAME){\n\t\t\treturn getLevel().getUniqueName();\n\t\t}else if(property==Property.StandardMemberProperty.LEVEL_NUMBER){\n\t\t\treturn getLevel().getDepth();\n\t\t}else{\n\t\t\treturn null;\n\t\t}\t}\n\n\t@Override\n\tpublic String getPropertyFormattedValue(Property property)\n\t\t\tthrows OlapException {\n\t\tObject obj = getPropertyValue(property);\n\t\treturn obj==null ? null : obj.toString();\n\t}\n\n\t@Override\n\tpublic void setProperty(Property property, Object value)\n\t\t\tthrows OlapException {\n\t}\n\n\t@Override\n\tpublic NamedList<Property> getProperties() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic int getOrdinal() {\n\t\treturn ordinal;\n\t}\n\n\t@Override\n\tpublic boolean isHidden() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int getDepth() {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic Member getDataMember() {\n\t\treturn null;\n\t}\n\n\tpublic String getKey() {\n\t\treturn key;\n\t}\n\n}",
"public class LevelMemberSet {\n\t\n\tprivate Level level;\n\t\n\tprivate ParseTreeNode node;\n\tprivate OlapOp function;\n\tprivate List<Member> members = new ArrayList<Member>();\n\tprivate Map<String, Member> map = new HashMap<String, Member>();\n\t\n\tprivate Sorter sorter;\n\tprivate int topLimit;\n\t\n\tpublic LevelMemberSet(Level level, ParseTreeNode node, OlapOp function) {\n\t\tthis.level = level;\n\t\tthis.node = node;\n\t\tthis.function = function;\n\t}\n\n\tpublic LevelMemberSet(Member member, ParseTreeNode node, OlapOp function) {\t\t\n\t\tthis.level = member.getLevel();\n\t\tthis.node = node;\n\t\tthis.function = function;\n\t\tmembers.add(member);\t\t\n\t}\n\n\tpublic LevelMemberSet(ParseTreeNode node, OlapOp function) {\n\t\tthis.node = node;\n\t\tthis.function = function;\n\t}\n\n\tpublic Level getLevel() {\n\t\treturn level;\n\t}\n\t\n\tpublic boolean isMeasure(){\n\t\treturn level.getDimension() instanceof ServerMeasureDimension;\n\t}\n\n\tpublic ParseTreeNode getNode() {\n\t\treturn node;\n\t}\n\n\tpublic List<Member> getMembers() {\n\t\treturn members;\n\t}\n\n\t\t\n\t@Override\n\tpublic String toString() {\n\t\tStringBuffer sb = new StringBuffer(level.getUniqueName());\n\t\t\n\t\tif(!members.isEmpty()){\n\t\t\tsb.append(\" with \").append(members.size()).append(\" member(s): [\");\n\t\t\tfor(Member m: members){\n\t\t\t\tif(m!=members.get(0))\n\t\t\t\t\tsb.append(\",\");\n\t\t\t\tsb.append(m.getName());\n\t\t\t}\n\t\t\tsb.append(\"]\");\n\t\t}\n\t\t\n\t\tsb.append(\" node: \");\n\t\tsb.append(ParseUtils.toString(node));\n\n\t\treturn sb.toString();\n\t}\n\n\tpublic OlapOp getFunction() {\n\t\treturn function;\n\t}\n\n\tpublic Member findMember(String key, String name) {\n\t\t\n\t\tMember m = map.get(key);\n\t\tif(m!=null)\n\t\t\treturn m;\n\t\t\n\t\tif(topLimit>0 && members.size()>=topLimit)\n\t\t\treturn null;\n\t\t\n\t\tLevelMember member = new LevelMember(level, key, name, members.size());\n\t\tmembers.add(member);\n\t\tmap.put(key, member);\n\t\t\n\t\treturn member;\n\t}\n\n\tpublic void setFunction(OlapOp function) {\n\t\tthis.function = function;\n\t}\n\n\tpublic Sorter getSorter() {\n\t\treturn sorter;\n\t}\n\n\tpublic void setSorter(Sorter sorter) {\n\t\tthis.sorter = sorter;\n\t}\n\n\tpublic int getTopLimit() {\n\t\treturn topLimit;\n\t}\n\n\tpublic void setTopLimit(int topLimit) {\n\t\tthis.topLimit = topLimit;\n\t}\n\t\n\t\n\t\n}",
"public class SetSubquery {\n\t\n\tprivate TableJoin join;\n\tprivate TableColumn column;\n\tprivate Set<String> values;\n\tprivate String from_value, to_value;\n\tprivate String having_expression;\n\t\n\t\n\tprivate SetSubquery except, exists;\n\t\n\t\n\t\n\tpublic SetSubquery(TableJoin join, TableColumn column, List<String> values) {\n\t\tthis.join = join;\n\t\tthis.column = column;\n\t\tthis.values = new HashSet<String>(values);\n\t}\n\n\t\n\tpublic SetSubquery(TableJoin join, TableColumn column, String from_value, String to_value) {\n\t\tthis.join = join;\n\t\tthis.column = column;\n\t\tthis.from_value = from_value;\n\t\tthis.to_value = to_value;\n\t\t\n\t}\n\n\n\tpublic SetSubquery(String havingExpressionString) {\n\t\tthis.having_expression = havingExpressionString;\n\t}\n\n\n\tpublic SetSubquery or(SetSubquery q) throws OlapException {\n\t\t\n\t\tif( q.column!=column )\n\t\t\tthrow new OlapException(\"Incompatible members in set \"+q.column.column+\" vs \"+column.column);\n\t\t\n\t\tif(values!=null && q.values!=null)\n\t\t\tvalues.addAll(q.values);\n\t\t\n\t\tif(q.from_value!=null)\n\t\t\tthis.from_value = q.from_value;\n\t\t\n\t\tif(q.to_value!=null)\n\t\t\tthis.to_value = q.to_value;\n\t\t\n\t\treturn this;\n\t}\n\n\tpublic SetSubquery except(SetSubquery query) {\n\t\tthis.except = query;\n\t\treturn this;\n\t}\n\t\n\tpublic SetSubquery exists(SetSubquery query) {\n\t\tthis.exists = query;\n\t\treturn this;\n\t}\n\n\n\tpublic Condition condition() {\n\t\t\n\t\tif((values==null || values.size()==0) && from_value==null && to_value==null){\n\t\t\tif(except==null)\n\t\t\t\treturn null;\n\t\t\telse\n\t\t\t\treturn new NotCondition(except.condition());\n\t\t}\n\t\t\t\n\t\tDimensionTable dim_table = join.getDimensionTable();\n\t\t\n\t\tSelectQuery dim_query = new SelectQuery().\n\t\t\t\taddFromTable(dim_table.getDbTable()).\n\t\t\t\taddColumns(dim_table.getDbKey());\n\t\t\n\t\tif(from_value!=null){\n\t\t\tdim_query = dim_query.addCondition(BinaryCondition.greaterThan(column.getDbColumn(), from_value, true));\n\t\t}\n\n\t\tif(to_value!=null){\n\t\t\tdim_query = dim_query.addCondition(BinaryCondition.lessThan(column.getDbColumn(), to_value, true));\n\t\t}\n\n\t\t\n\t\tif(values!=null && values.size()>0){\n\t\t\tif(values.size()==1){\n\t\t\t\tString value = values.iterator().next();\n\t\t\t\tif(LevelMember.NULL_MEMBER.equals(value))\n\t\t\t\t\tdim_query = dim_query.addCondition(UnaryCondition.isNull(column.getDbColumn()));\n\t\t\t\telse\t\t\n\t\t\t\t\tdim_query = dim_query.addCondition(BinaryCondition.equalTo(column.getDbColumn(), value));\n\t\t\t}else{ \n\t\t\t\t\n\t\t\t\tif(values.contains(LevelMember.NULL_MEMBER)){\n\t\t\t\t\tSet<String> values_without_null = new HashSet<String>(values);\n\t\t\t\t\tvalues_without_null.remove(LevelMember.NULL_MEMBER);\n\t\t\t\t\tdim_query = dim_query.addCondition(ComboCondition.or(\n\t\t\t\t\t\t\tUnaryCondition.isNull(column.getDbColumn()),\n\t\t\t\t\t\t\tnew InCondition(column.getDbColumn(), values_without_null)));\n\t\t\t\t}else{\n\t\t\t\t\tdim_query = dim_query.addCondition(new InCondition(column.getDbColumn(), values));\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tCondition myCondition = new InCondition(join.getForeign_key(), new Subquery(dim_query) );\n\t\t\n\t\tif(except!=null)\n\t\t\tmyCondition = ComboCondition.and(myCondition, new NotCondition(except.condition()) );\n\n\t\tif(exists!=null)\n\t\t\tmyCondition = ComboCondition.and(myCondition, exists.condition());\n\t\t\n\t\treturn myCondition;\n\t\t \n\t\t\n\t}\n\t\n\tpublic Condition havingCondition(){\n\t\t\n\t\tif(having_expression==null){\n\t\t\tif(except == null || except.having_expression==null)\n\t\t\t\treturn null;\n\t\t\telse\n\t\t\t\treturn new NotCondition(except.havingCondition());\n\t\t}\n\t\t\n\t\tCondition myCondition = new CustomCondition(having_expression);\n\t\t\n\t\tif(except!=null && except.having_expression!=null)\n\t\t\tmyCondition = ComboCondition.and(myCondition, new NotCondition(except.havingCondition()) );\n\t\t\n\t\tif(exists!=null && exists.having_expression!=null)\n\t\t\tmyCondition = ComboCondition.and(myCondition, exists.havingCondition() );\n\t\t\n\t\t\n\t\treturn myCondition;\n\t\t\n\t\t\n\t}\n\n\tpublic void setHaving_expression(String having_expression) {\n\t\tthis.having_expression = having_expression;\n\t}\n\n\n\tpublic boolean combined_with(SetSubquery query) {\n\t\treturn column.equals(query.column);\n\t}\n\n\n\n\n\n\n}",
"public class TableMapping {\n\t\n\tprivate static Log log = LogFactory.getLog(SqlConnector.class);\n\t\n\tpublic class MeasureMapping {\n\t\tpublic ServerMeasure measure;\n\t\tpublic TableMeasure column;\n\t\tpublic String alias;\n\t}\n\n\tpublic class LevelMapping {\n\t\tpublic TableJoin join;\n\t\tpublic DimensionTable table;\n\t\tpublic TableColumn name_column;\n\t\tpublic String name_alias;\n\t\t\n\t\tpublic TableColumn key_column;\n\t\tpublic String key_alias;\n\t\t\n\t\tpublic TableColumn order_column;\n\t}\n\t\t\n\tprivate AggregateTable aggregate;\n\t\n\tprivate List<MeasureMapping> measures = new ArrayList<MeasureMapping>();\n\t\n\tprivate Map<ServerMeasure, MeasureMapping> measures_mapping = new IdentityHashMap<ServerMeasure, MeasureMapping>();\n\tprivate Map<Level, LevelMapping> levels_mapping = new IdentityHashMap<Level, LevelMapping>();\t\n\t\n\tpublic TableMapping(AggregateTable t) {\n\t\tthis.aggregate = t;\n\t}\n\n\n\tpublic static TableMapping mapToDatabase(PhysicalSchema schema, List<ResultAxis> resultAxes, ResultAxis filterAxis) throws OlapException {\n\t\t\n\t\tSet<ServerMeasure> measures = new HashSet<ServerMeasure>();\n\t\tSet<ServerDimension> dimensions = new HashSet<ServerDimension>();\n\t\t\n\t\tfor(ResultAxis axis : resultAxes){\n\t\t\tmeasures.addAll(axis.collectAllUsedMeasures());\n\t\t\tdimensions.addAll(axis.collectAllUsedDimensions());\n\t\t}\n\n\t\tmeasures.addAll(filterAxis.collectAllUsedMeasures());\n\t\tdimensions.addAll(filterAxis.collectAllUsedDimensions());\n\n\t\tList<TableMapping> candidates = new ArrayList<TableMapping>();\n\t\t\n\t\tfor(AggregateTable t : schema.aggregates){\n\t\t\tTableMapping mapping = new TableMapping(t);\n\t\t\t\n\t\t\tboolean all_mapped = true;\n\t\t\tfor(ServerMeasure m : measures){\n\t\t\t\tif(mapping.map(m)==null){\n\t\t\t\t\tall_mapped = false;\n\t\t\t\t\tlog.info(\"Can not use \"+t.table + \" missing \"+m.getName()+\" mapping\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(all_mapped){\n\t\t\t\tfor(ServerDimension d : dimensions){\n\t\t\t\t\tif(mapping.map(d)==null){\n\t\t\t\t\t\tall_mapped = false;\n\t\t\t\t\t\tlog.info(\"Can not use \"+t.table + \" missing \"+d.getName()+\" mapping\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tif(all_mapped)\n\t\t\t\tcandidates.add(mapping);\n\t\t\t\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\tCollections.sort(candidates, new Comparator<TableMapping>(){\n\n\t\t\t@Override\n\t\t\tpublic int compare(TableMapping o1, TableMapping o2) {\n\t\t\t\tif(o1.scale() > o2.scale())\n\t\t\t\t\treturn 1;\n\t\t\t\telse if(o1.scale() < o2.scale())\n\t\t\t\t\treturn -1;\n\t\t\t\telse\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t\n\t\t});\n\t\t\n\t\tTableMapping mapping = candidates.get(0);\n\t\tlog.info(\"Using \"+ mapping.aggregate.table+\" aggregate table\");\n\t\t\n\t\tfor(ResultAxis axis : resultAxes){\n\t\t\tfor( LevelMemberSet layer : axis.getLayers() ){\n\t\t\t\tmapping.map(layer);\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor( LevelMemberSet layer : filterAxis.getLayers() ){\n\t\t\tmapping.map(layer);\n\t\t}\n\t\t\n\t\t\n\t\treturn mapping;\n\t}\n\t\n\n\n\tprivate void map(LevelMemberSet layer) throws OlapException {\n\t\t\n\t\tif(layer.isMeasure()){\n\t\t\t\n\t\t\tfor(Member m : layer.getMembers()){\n\t\t\t\tServerMeasure sm = (ServerMeasure) m;\n\t\t\t\tMeasureMapping mm = new MeasureMapping();\n\t\t\t\tmm.alias = \"m\"+(measures_mapping.size() + 1);\n\t\t\t\tmm.column = map(sm);\n\t\t\t\tmm.measure = sm;\n\t\t\t\tmeasures_mapping.put(sm, mm );\n\t\t\t\tmeasures.add(mm);\n\t\t\t}\n\t\t\t\n\t\t}else if(layer.getLevel() instanceof ServerLevel && !levels_mapping.containsKey(layer.getLevel())){\n\t\t\t\t\t\t\t\n\t\t\tLevelMapping lm = new LevelMapping();\n\t\t\tTableJoin join = map(layer.getLevel().getDimension());\n\n\t\t\tlm.join = join;\n\t\t\tlm.name_column = join.getDimensionTable().findColumnByAttribute(layer.getLevel().getName());\n\t\t\tif(lm.name_column==null)\n\t\t\t\tthrow new OlapException(\"Column for \"+layer.getLevel().getName()+\" not found in \"+join.getDimensionTable().table);\n\t\t\t\n\t\t\tlm.name_alias = \"d\"+(levels_mapping.size() + 1);\n\t\t\t\n\t\t\tif(lm.name_column.identified_by!=null){\n\t\t\t\tlm.key_column = join.getDimensionTable().findColumnByName(lm.name_column.identified_by);\n\t\t\t\tlm.key_alias = \"id\"+(levels_mapping.size() + 1);\n\t\t\t}else{\n\t\t\t\tlm.key_column = lm.name_column;\n\t\t\t\tlm.key_alias = lm.key_alias;\n\t\t\t}\n\t\t\t\n\t\t\tif(lm.name_column.sorted_by!=null){\n\t\t\t\tlm.order_column = join.getDimensionTable().findColumnByName(lm.name_column.sorted_by);\n\t\t\t}else{\n\t\t\t\tlm.order_column = lm.name_column;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tlevels_mapping.put(layer.getLevel(), lm);\n\t\t\t\n\t\t\t\n\t\t}\n\t\t\n\t}\n\n\n\tprivate TableJoin map(Dimension d) {\n\t\tfor(TableJoin join : aggregate.joins){\n\t\t\tif(join.dimension.equals(d.getUniqueName())){\n\t\t\t\treturn join;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\n\tprivate TableMeasure map(ServerMeasure m) {\n\t\t\n\t\tif(m instanceof LiteralMeasure){\n\t\t\tLiteralMeasure literal = (LiteralMeasure) m;\n\t\t\tTableMeasure literalMeasure = new TableMeasure();\n\t\t\tliteralMeasure.setExpression(\n\t\t\t\t\tliteral.isNumeric() ? \n\t\t\t\t\t\tnew NumberValueObject(literal.getLiteralValue()) : \n\t\t\t\t\t\tnew ValueObject(literal.getLiteralValue())\n\t\t\t\t\t\t);\n\t\t\treturn literalMeasure;\n\t\t}\n\t\t\n\t\tfor(TableMeasure measure : aggregate.measures){\n\t\t\tif(measure.measure.equals(m.getName())){\n\t\t\t\treturn measure;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic String getMeasureExpression(ServerMeasure measure, boolean useAliases){\n\t\tMeasureMapping mapping = getMapping(measure);\n\t\t\n\t\tif(mapping!=null)\n\t\t\treturn useAliases ? mapping.alias : mapping.column.getExpression().toString();\n\t\telse{\n\t\t\tTableMeasure tm = map(measure);\n\t\t\treturn tm.getExpression().toString();\n\t\t}\t\n\t}\n\n\n\tpublic int scale() {\t\t\n\t\treturn aggregate.joins.size();\n\t}\n\n\n\tpublic AggregateTable getAggregate() {\n\t\treturn aggregate;\n\t}\n\t\n\tpublic MeasureMapping getMapping(ServerMeasure measure){\n\t\treturn measures_mapping.get(measure);\n\t}\n\n\tpublic LevelMapping getMapping(Level level){\n\t\treturn levels_mapping.get(level);\n\t}\n\t\n\tpublic Set<TableMeasure> getMeasureColumns(){\n\t\treturn null;\t\t\n\t}\n\n\tpublic Set<TableColumn> getTableColumns(){\n\t\treturn null;\t\t\n\t}\n\n\tpublic Set<TableJoin> getTableJoins(){\n\t\treturn null;\t\t\n\t}\n\n\n\tpublic List<MeasureMapping> getMeasures() {\n\t\treturn measures;\n\t}\n}",
"public class LevelMapping {\n\tpublic TableJoin join;\n\tpublic DimensionTable table;\n\tpublic TableColumn name_column;\n\tpublic String name_alias;\n\t\t\n\tpublic TableColumn key_column;\n\tpublic String key_alias;\n\t\t\n\tpublic TableColumn order_column;\n}"
] | import java.util.Collections;
import java.util.List;
import org.olap.server.driver.util.MetadataUtils;
import org.olap.server.driver.util.ParseUtils;
import org.olap.server.processor.LevelMember;
import org.olap.server.processor.LevelMemberSet;
import org.olap.server.processor.sql.SetSubquery;
import org.olap.server.processor.sql.TableMapping;
import org.olap.server.processor.sql.TableMapping.LevelMapping;
import org.olap4j.OlapException;
import org.olap4j.mdx.IdentifierNode;
import org.olap4j.metadata.Cube;
import org.olap4j.metadata.Member; | package org.olap.server.processor.functions;
public class IdentifiedMember extends OlapMethod {
private Member cube_member;
public IdentifiedMember(IdentifierNode node, Cube cube) throws OlapException {
super(node, cube);
cube_member = cube.lookupMember(node.getSegmentList());
if(cube_member==null)
cube_member = MetadataUtils.lookupMember(cube, node.getSegmentList());
if(cube_member==null)
throw new OlapException("Member not found in cube: "+ParseUtils.toString(node));
}
@Override
public List<LevelMemberSet> memberSet() throws OlapException {
return Collections.singletonList(new LevelMemberSet(cube_member, node, this));
}
@Override
public SetSubquery query(TableMapping mapping, LevelMemberSet layer)
throws OlapException {
| if(! (cube_member instanceof LevelMember)) | 2 |
wseemann/RoMote | app/src/main/java/wseemann/media/romote/service/NotificationService.java | [
"public abstract class RequestCallback {\n public abstract void requestResult(RokuRequestTypes rokuRequestType, RequestTask.Result result);\n public abstract void onErrorResponse(RequestTask.Result result);\n}",
"public class RequestTask extends AsyncTask<RokuRequestTypes, Void, RequestTask.Result> {\n\n private RequestCallback mCallback;\n\n private JakuRequest request;\n private RokuRequestTypes rokuRequestType;\n\n public RequestTask(JakuRequest request, RequestCallback callback) {\n this.request = request;\n setCallback(callback);\n }\n\n void setCallback(RequestCallback callback) {\n mCallback = callback;\n }\n\n /**\n * Wrapper class that serves as a union of a result value and an exception. When the download\n * task has completed, either the result value or exception can be a non-null value.\n * This allows you to pass exceptions to the UI thread that were thrown during doInBackground().\n */\n public static class Result {\n public Object mResultValue;\n public Exception mException;\n public Result(Object resultValue) {\n mResultValue = resultValue;\n }\n public Result(Exception exception) {\n mException = exception;\n }\n }\n\n /**\n * Cancel background network operation if we do not have network connectivity.\n */\n @Override\n protected void onPreExecute() {\n\n }\n\n @Override\n protected RequestTask.Result doInBackground(RokuRequestTypes... requestTypes) {\n Result result = null;\n if (!isCancelled() && requestTypes != null && requestTypes.length > 0) {\n RokuRequestTypes requestType = requestTypes[0];\n try {\n if (requestType.equals(RokuRequestTypes.query_active_app)) {\n JakuResponse response = request.send();\n List<Channel> channels = (List<Channel>) response.getResponseData();\n result = new Result(channels);\n } else if (requestType.equals(RokuRequestTypes.query_device_info)) {\n JakuResponse response = request.send();\n Device device = Device.Companion.fromDevice((com.jaku.model.Device) response.getResponseData());\n result = new Result(device);\n } else if (requestType.equals(RokuRequestTypes.query_icon)) {\n JakuResponse response = request.send();\n byte [] data = ((ByteArrayOutputStream) response.getResponseData()).toByteArray();\n result = new Result(data);\n } else {\n request.send();\n }\n } catch(Exception e) {\n e.printStackTrace();\n result = new Result(e);\n }\n }\n return result;\n }\n\n /**\n * Updates the DownloadCallback with the result.\n */\n @Override\n protected void onPostExecute(Result result) {\n if (result != null && mCallback != null) {\n if (result.mException != null) {\n mCallback.onErrorResponse(result);\n } else if (result.mResultValue != null) {\n mCallback.requestResult(rokuRequestType, result);\n }\n }\n }\n\n /**\n * Override to add special behavior for cancelled AsyncTask.\n */\n @Override\n protected void onCancelled(Result result) {\n }\n}",
"public class CommandHelper {\n\n private CommandHelper() {\n\n }\n\n public static String getDeviceURL(Context context) {\n String url = \"\";\n\n try {\n Device device = PreferenceUtils.getConnectedDevice(context);\n\n url = device.getHost();\n } catch (Exception ex) {\n }\n\n return url;\n }\n\n public static String getIconURL(Context context, String channelId) {\n String url = \"\";\n\n try {\n Device device = PreferenceUtils.getConnectedDevice(context);\n\n url = device.getHost() + \"/query/icon/\" + channelId;\n } catch (Exception ex) {\n }\n\n return url;\n }\n\n public static String getDeviceInfoURL(Context context, String host) {\n String url = host;\n\n return url;\n }\n\n public static String getConnectedDeviceInfoURL(Context context, String host) {\n String url = \"\";\n\n try {\n Device device = PreferenceUtils.getConnectedDevice(context);\n\n url = device.getHost();\n } catch (Exception ex) {\n }\n\n return url;\n }\n}",
"public class Constants {\n\n private Constants() {\n\n }\n\n public enum WIFI_AP_STATE {\n WIFI_AP_STATE_DISABLING,\n WIFI_AP_STATE_DISABLED,\n WIFI_AP_STATE_ENABLING,\n WIFI_AP_STATE_ENABLED,\n WIFI_AP_STATE_FAILED\n }\n\n public static final String UPDATE_DEVICE_BROADCAST = \"wseemann.media.romote.UPDATE_DEVICE\";\n public static final String PAYPAL_DONATION_LINK = \"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=C4RNUUK83P3E2\";\n public static final String DISMISS_CONECTIVITY_DIALOG = \"wseemann.media.romote.DISMISS_CONECTIVITY_DIALOG\";\n public static final String PRIVATE_LISTENING_URL = \"https://github.com/wseemann/RoMote-PrivateListening/releases/tag/v1.0.18\";\n}",
"public class NotificationUtils {\n\n private NotificationUtils() {\n\n }\n\n public static Notification buildNotification(\n Context context,\n String title,\n String text,\n Bitmap bitmap,\n MediaSession.Token token) {\n\n String contentTitle = \"Roku\";\n String contentText = \"\";\n\n if (title != null) {\n contentTitle = title;\n }\n\n if (text != null) {\n contentText = text;\n }\n\n PendingIntent contentIntent = PendingIntent.getActivity(\n context,\n ((int) System.currentTimeMillis()),\n new Intent(context,MainActivity.class),\n PendingIntent.FLAG_UPDATE_CURRENT\n );\n\n Notification.MediaStyle style = new Notification.MediaStyle();\n style.setMediaSession(token);\n\n Notification.Builder builder = new Notification.Builder(context)\n .setContentTitle(contentTitle)\n .setContentText(contentText)\n .setContentIntent(contentIntent)\n .setWhen(0)\n .setSmallIcon(R.drawable.ic_notification_icon)\n .setPriority(Notification.PRIORITY_LOW);\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n builder.setChannelId(context.getString(R.string.app_name));\n }\n\n if (bitmap != null) {\n builder.setLargeIcon(bitmap);\n }\n\n builder.addAction(GenerateActionCompat(context, android.R.drawable.ic_media_rew, \"Previous\", 0, KeypressKeyValues.REV));\n builder.addAction(GenerateActionCompat(context, android.R.drawable.ic_media_pause, \"Pause\", 1, KeypressKeyValues.PLAY));\n builder.addAction(GenerateActionCompat(context, android.R.drawable.ic_media_ff, \"Next\", 2, KeypressKeyValues.FWD));\n\n style.setShowActionsInCompactView(0, 1, 2);\n //style.setShowCancelButton(true);\n\n builder.setStyle(style);\n\n return builder.build();\n }\n\n private static Notification.Action GenerateActionCompat(Context context, int icon, String title, int requestCode, KeypressKeyValues keypressKeyValue) {\n Intent intent = new Intent(context, CommandService.class);\n intent.putExtra(\"keypress\", keypressKeyValue);\n PendingIntent pendingIntent = PendingIntent.getService(context, requestCode, intent, 0);\n\n return new Notification.Action.Builder(icon, title, pendingIntent).build();\n }\n}",
"public class PreferenceUtils {\n\n private PreferenceUtils() {\n\n }\n\n public static void setConnectedDevice(Context context, String serialNumber) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n SharedPreferences.Editor editor = prefs.edit();\n editor.putString(\"serial_number\", serialNumber);\n editor.commit();\n }\n\n public static Device getConnectedDevice(Context context) throws Exception {\n Device device;\n\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String serialNumber = prefs.getString(\"serial_number\", null);\n\n device = DBUtils.getDevice(context, serialNumber);\n\n if (device == null) {\n throw new Exception(\"Device not connected\");\n }\n\n return device;\n }\n\n public static boolean shouldProvideHapticFeedback(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n return prefs.getBoolean(\"haptic_feedback_preference\", false);\n }\n}",
"public enum RokuRequestTypes {\n query_active_app(\"query/active-app\"),\n query_device_info(\"query/device-info\"),\n launch(\"launch\"),\n keypress(\"keypress\"),\n query_icon(\"query/icon\"),\n search(\"search/browse?\");\n\n private final String method;\n\n RokuRequestTypes(String method) {\n this.method = method;\n }\n\n public String getValue() {\n return method;\n }\n}"
] | import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadata;
import android.media.session.MediaSession;
import android.media.session.PlaybackState;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import com.jaku.core.JakuRequest;
import com.jaku.parser.AppsParser;
import com.jaku.parser.IconParser;
import com.jaku.request.QueryActiveAppRequest;
import com.jaku.request.QueryIconRequest;
import java.util.List;
import java.util.Random;
import com.jaku.model.Channel;
import wseemann.media.romote.R;
import wseemann.media.romote.model.Device;
import wseemann.media.romote.tasks.RequestCallback;
import wseemann.media.romote.tasks.RequestTask;
import wseemann.media.romote.utils.CommandHelper;
import wseemann.media.romote.utils.Constants;
import wseemann.media.romote.utils.NotificationUtils;
import wseemann.media.romote.utils.PreferenceUtils;
import wseemann.media.romote.utils.RokuRequestTypes; | package wseemann.media.romote.service;
/**
* Created by wseemann on 6/19/16.
*/
public class NotificationService extends Service {
public static final String TAG = NotificationService.class.getName();
public static final int NOTIFICATION = 100;
private NotificationManager mNM;
private Notification notification;
private Channel mChannel;
private Device mDevice;
private SharedPreferences mPreferences;
private MediaSession mediaSession;
private int mServiceStartId;
private boolean mServiceInUse = true;
private final Random mGenerator = new Random();
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public NotificationService getService() {
// Return this instance of LocalService so clients can call public methods
return NotificationService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
setUpMediaSession();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Constants.UPDATE_DEVICE_BROADCAST);
registerReceiver(mUpdateReceiver, intentFilter);
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(getString(R.string.app_name), getString(R.string.app_name), NotificationManager.IMPORTANCE_LOW);
channel.setDescription(TAG);
channel.enableLights(false);
channel.enableVibration(false);
mNM.createNotificationChannel(channel);
}
//startForeground(NotificationService.NOTIFICATION, notification);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean enableNotification = mPreferences.getBoolean("notification_checkbox_preference", false);
mPreferences.registerOnSharedPreferenceChangeListener(mPreferencesChangedListener);
try {
mDevice = PreferenceUtils.getConnectedDevice(this);
if (enableNotification && mDevice != null) {
notification = NotificationUtils.buildNotification(NotificationService.this, null, null, null, mediaSession.getSessionToken());
mNM.notify(NOTIFICATION, notification);
sendStatusCommand();
}
} catch (Exception ex) {
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Received start id " + startId + ": " + intent);
mServiceStartId = startId;
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mUpdateReceiver);
// Cancel the persistent notification.
mNM.cancel(NOTIFICATION);
mPreferences.unregisterOnSharedPreferenceChangeListener(mPreferencesChangedListener);
mediaSession.release();
}
@Override
public IBinder onBind(Intent intent) {
mServiceInUse = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mServiceInUse = true;
}
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
return true;
}
private void sendStatusCommand() {
String url = CommandHelper.getDeviceURL(this);
QueryActiveAppRequest queryActiveAppRequest = new QueryActiveAppRequest(url);
JakuRequest request = new JakuRequest(queryActiveAppRequest, new AppsParser());
| new RequestTask(request, new RequestCallback() { | 0 |
rkkr/simple-keyboard | app/src/main/java/rkr/simplekeyboard/inputmethod/latin/RichInputMethodManager.java | [
"public class PreferenceManagerCompat {\n public static Context getDeviceContext(Context context) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n return context.createDeviceProtectedStorageContext();\n }\n\n return context;\n }\n\n public static SharedPreferences getDeviceSharedPreferences(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(getDeviceContext(context));\n }\n}",
"public final class LocaleUtils {\n private LocaleUtils() {\n // Intentional empty constructor for utility class.\n }\n\n // Locale match level constants.\n // A higher level of match is guaranteed to have a higher numerical value.\n // Some room is left within constants to add match cases that may arise necessary\n // in the future, for example differentiating between the case where the countries\n // are both present and different, and the case where one of the locales does not\n // specify the countries. This difference is not needed now.\n\n private static final HashMap<String, Locale> sLocaleCache = new HashMap<>();\n\n /**\n * Creates a locale from a string specification.\n * @param localeString a string specification of a locale, in a format of \"ll_cc_variant\" where\n * \"ll\" is a language code, \"cc\" is a country code.\n */\n public static Locale constructLocaleFromString(final String localeString) {\n synchronized (sLocaleCache) {\n if (sLocaleCache.containsKey(localeString)) {\n return sLocaleCache.get(localeString);\n }\n final String[] elements = localeString.split(\"_\", 3);\n final Locale locale;\n if (elements.length == 1) {\n locale = new Locale(elements[0] /* language */);\n } else if (elements.length == 2) {\n locale = new Locale(elements[0] /* language */, elements[1] /* country */);\n } else { // localeParams.length == 3\n locale = new Locale(elements[0] /* language */, elements[1] /* country */,\n elements[2] /* variant */);\n }\n sLocaleCache.put(localeString, locale);\n return locale;\n }\n }\n\n /**\n * Creates a string specification for a locale.\n * @param locale the locale.\n * @return a string specification of a locale, in a format of \"ll_cc_variant\" where \"ll\" is a\n * language code, \"cc\" is a country code.\n */\n public static String getLocaleString(final Locale locale) {\n if (!TextUtils.isEmpty(locale.getVariant())) {\n return locale.getLanguage() + \"_\" + locale.getCountry() + \"_\" + locale.getVariant();\n }\n if (!TextUtils.isEmpty(locale.getCountry())) {\n return locale.getLanguage() + \"_\" + locale.getCountry();\n }\n return locale.getLanguage();\n }\n\n /**\n * Get the closest matching locale. This searches by:\n * 1. {@link Locale#equals(Object)}\n * 2. Language, Country, and Variant match\n * 3. Language and Country match\n * 4. Language matches\n * @param localeToMatch the locale to match.\n * @param options a collection of locales to find the best match.\n * @return the locale from the collection that is the best match for the specified locale or\n * null if nothing matches.\n */\n public static Locale findBestLocale(final Locale localeToMatch,\n final Collection<Locale> options) {\n // Find the best subtype based on a straightforward matching algorithm.\n // TODO: Use LocaleList#getFirstMatch() instead.\n for (final Locale locale : options) {\n if (locale.equals(localeToMatch)) {\n return locale;\n }\n }\n for (final Locale locale : options) {\n if (locale.getLanguage().equals(localeToMatch.getLanguage()) &&\n locale.getCountry().equals(localeToMatch.getCountry()) &&\n locale.getVariant().equals(localeToMatch.getVariant())) {\n return locale;\n }\n }\n for (final Locale locale : options) {\n if (locale.getLanguage().equals(localeToMatch.getLanguage()) &&\n locale.getCountry().equals(localeToMatch.getCountry())) {\n return locale;\n }\n }\n for (final Locale locale : options) {\n if (locale.getLanguage().equals(localeToMatch.getLanguage())) {\n return locale;\n }\n }\n return null;\n }\n\n /**\n * Get the list of locales enabled in the system.\n * @return the list of locales enabled in the system.\n */\n public static List<Locale> getSystemLocales() {\n ArrayList<Locale> locales = new ArrayList<>();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n LocaleList localeList = Resources.getSystem().getConfiguration().getLocales();\n for (int i = 0; i < localeList.size(); i++) {\n locales.add(localeList.get(i));\n }\n } else {\n locales.add(Resources.getSystem().getConfiguration().locale);\n }\n return locales;\n }\n\n /**\n * Comparator for {@link Locale} to order them alphabetically\n * first.\n */\n public static class LocaleComparator implements Comparator<Locale> {\n @Override\n public int compare(Locale a, Locale b) {\n if (a.equals(b)) {\n // ensure that this is consistent with equals\n return 0;\n }\n final String aDisplay =\n LocaleResourceUtils.getLocaleDisplayNameInSystemLocale(getLocaleString(a));\n final String bDisplay =\n LocaleResourceUtils.getLocaleDisplayNameInSystemLocale(getLocaleString(b));\n final int result = aDisplay.compareToIgnoreCase(bDisplay);\n if (result != 0) {\n return result;\n }\n // ensure that non-equal objects are distinguished to be consistent with equals\n return a.hashCode() > b.hashCode() ? 1 : -1;\n }\n }\n}",
"public final class Settings implements SharedPreferences.OnSharedPreferenceChangeListener {\n private static final String TAG = Settings.class.getSimpleName();\n // Settings screens\n public static final String SCREEN_THEME = \"screen_theme\";\n // In the same order as xml/prefs.xml\n public static final String PREF_AUTO_CAP = \"auto_cap\";\n public static final String PREF_VIBRATE_ON = \"vibrate_on\";\n public static final String PREF_SOUND_ON = \"sound_on\";\n public static final String PREF_POPUP_ON = \"popup_on\";\n public static final String PREF_HIDE_LANGUAGE_SWITCH_KEY = \"pref_hide_language_switch_key\";\n public static final String PREF_ENABLE_IME_SWITCH = \"pref_enable_ime_switch\";\n public static final String PREF_ENABLED_SUBTYPES = \"pref_enabled_subtypes\";\n public static final String PREF_VIBRATION_DURATION_SETTINGS = \"pref_vibration_duration_settings\";\n public static final String PREF_KEYPRESS_SOUND_VOLUME = \"pref_keypress_sound_volume\";\n public static final String PREF_KEY_LONGPRESS_TIMEOUT = \"pref_key_longpress_timeout\";\n public static final String PREF_KEYBOARD_HEIGHT = \"pref_keyboard_height\";\n public static final String PREF_KEYBOARD_COLOR = \"pref_keyboard_color\";\n public static final String PREF_HIDE_SPECIAL_CHARS = \"pref_hide_special_chars\";\n public static final String PREF_SHOW_NUMBER_ROW = \"pref_show_number_row\";\n public static final String PREF_SPACE_SWIPE = \"pref_space_swipe\";\n public static final String PREF_DELETE_SWIPE = \"pref_delete_swipe\";\n public static final String PREF_MATCHING_NAVBAR_COLOR = \"pref_matching_navbar_color\";\n\n private static final float UNDEFINED_PREFERENCE_VALUE_FLOAT = -1.0f;\n private static final int UNDEFINED_PREFERENCE_VALUE_INT = -1;\n\n private Resources mRes;\n private SharedPreferences mPrefs;\n private SettingsValues mSettingsValues;\n private final ReentrantLock mSettingsValuesLock = new ReentrantLock();\n\n private static final Settings sInstance = new Settings();\n\n public static Settings getInstance() {\n return sInstance;\n }\n\n public static void init(final Context context) {\n sInstance.onCreate(context);\n }\n\n private Settings() {\n // Intentional empty constructor for singleton.\n }\n\n private void onCreate(final Context context) {\n mRes = context.getResources();\n mPrefs = PreferenceManagerCompat.getDeviceSharedPreferences(context);\n mPrefs.registerOnSharedPreferenceChangeListener(this);\n }\n\n public void onDestroy() {\n mPrefs.unregisterOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {\n mSettingsValuesLock.lock();\n try {\n if (mSettingsValues == null) {\n // TODO: Introduce a static function to register this class and ensure that\n // loadSettings must be called before \"onSharedPreferenceChanged\" is called.\n Log.w(TAG, \"onSharedPreferenceChanged called before loadSettings.\");\n return;\n }\n loadSettings(mSettingsValues.mInputAttributes);\n } finally {\n mSettingsValuesLock.unlock();\n }\n }\n\n public void loadSettings(final InputAttributes inputAttributes) {\n mSettingsValues = new SettingsValues(mPrefs, mRes, inputAttributes);\n }\n\n // TODO: Remove this method and add proxy method to SettingsValues.\n public SettingsValues getCurrent() {\n return mSettingsValues;\n }\n\n\n // Accessed from the settings interface, hence public\n public static boolean readKeypressSoundEnabled(final SharedPreferences prefs,\n final Resources res) {\n return prefs.getBoolean(PREF_SOUND_ON,\n res.getBoolean(R.bool.config_default_sound_enabled));\n }\n\n public static boolean readVibrationEnabled(final SharedPreferences prefs,\n final Resources res) {\n final boolean hasVibrator = AudioAndHapticFeedbackManager.getInstance().hasVibrator();\n return hasVibrator && prefs.getBoolean(PREF_VIBRATE_ON,\n res.getBoolean(R.bool.config_default_vibration_enabled));\n }\n\n public static boolean readKeyPreviewPopupEnabled(final SharedPreferences prefs,\n final Resources res) {\n final boolean defaultKeyPreviewPopup = res.getBoolean(\n R.bool.config_default_key_preview_popup);\n return prefs.getBoolean(PREF_POPUP_ON, defaultKeyPreviewPopup);\n }\n\n public static boolean readShowLanguageSwitchKey(final SharedPreferences prefs) {\n return !prefs.getBoolean(PREF_HIDE_LANGUAGE_SWITCH_KEY, false);\n }\n\n public static boolean readEnableImeSwitch(final SharedPreferences prefs) {\n return prefs.getBoolean(PREF_ENABLE_IME_SWITCH, false);\n }\n\n public static boolean readHideSpecialChars(final SharedPreferences prefs) {\n return prefs.getBoolean(PREF_HIDE_SPECIAL_CHARS, false);\n }\n\n public static boolean readShowNumberRow(final SharedPreferences prefs) {\n return prefs.getBoolean(PREF_SHOW_NUMBER_ROW, false);\n }\n\n public static boolean readSpaceSwipeEnabled(final SharedPreferences prefs) {\n return prefs.getBoolean(PREF_SPACE_SWIPE, false);\n }\n\n public static boolean readDeleteSwipeEnabled(final SharedPreferences prefs) {\n return prefs.getBoolean(PREF_DELETE_SWIPE, false);\n }\n\n public static String readPrefSubtypes(final SharedPreferences prefs) {\n return prefs.getString(PREF_ENABLED_SUBTYPES, \"\");\n }\n\n public static void writePrefSubtypes(final SharedPreferences prefs, final String prefSubtypes) {\n prefs.edit().putString(PREF_ENABLED_SUBTYPES, prefSubtypes).apply();\n }\n\n public static float readKeypressSoundVolume(final SharedPreferences prefs,\n final Resources res) {\n final float volume = prefs.getFloat(\n PREF_KEYPRESS_SOUND_VOLUME, UNDEFINED_PREFERENCE_VALUE_FLOAT);\n return (volume != UNDEFINED_PREFERENCE_VALUE_FLOAT) ? volume\n : readDefaultKeypressSoundVolume(res);\n }\n\n // Default keypress sound volume for unknown devices.\n // The negative value means system default.\n private static final String DEFAULT_KEYPRESS_SOUND_VOLUME = Float.toString(-1.0f);\n\n public static float readDefaultKeypressSoundVolume(final Resources res) {\n return Float.parseFloat(ResourceUtils.getDeviceOverrideValue(res,\n R.array.keypress_volumes, DEFAULT_KEYPRESS_SOUND_VOLUME));\n }\n\n public static int readKeyLongpressTimeout(final SharedPreferences prefs,\n final Resources res) {\n final int milliseconds = prefs.getInt(\n PREF_KEY_LONGPRESS_TIMEOUT, UNDEFINED_PREFERENCE_VALUE_INT);\n return (milliseconds != UNDEFINED_PREFERENCE_VALUE_INT) ? milliseconds\n : readDefaultKeyLongpressTimeout(res);\n }\n\n public static int readDefaultKeyLongpressTimeout(final Resources res) {\n return res.getInteger(R.integer.config_default_longpress_key_timeout);\n }\n\n public static int readKeypressVibrationDuration(final SharedPreferences prefs,\n final Resources res) {\n final int milliseconds = prefs.getInt(\n PREF_VIBRATION_DURATION_SETTINGS, UNDEFINED_PREFERENCE_VALUE_INT);\n return (milliseconds != UNDEFINED_PREFERENCE_VALUE_INT) ? milliseconds\n : readDefaultKeypressVibrationDuration(res);\n }\n\n // Default keypress vibration duration for unknown devices.\n // The negative value means system default.\n private static final String DEFAULT_KEYPRESS_VIBRATION_DURATION = Integer.toString(-1);\n\n public static int readDefaultKeypressVibrationDuration(final Resources res) {\n return Integer.parseInt(ResourceUtils.getDeviceOverrideValue(res,\n R.array.keypress_vibration_durations, DEFAULT_KEYPRESS_VIBRATION_DURATION));\n }\n\n public static float readKeyboardHeight(final SharedPreferences prefs,\n final float defaultValue) {\n return prefs.getFloat(PREF_KEYBOARD_HEIGHT, defaultValue);\n }\n\n public static int readKeyboardDefaultColor(final Context context) {\n final int[] keyboardThemeColors = context.getResources().getIntArray(R.array.keyboard_theme_colors);\n final int[] keyboardThemeIds = context.getResources().getIntArray(R.array.keyboard_theme_ids);\n final int themeId = KeyboardTheme.getKeyboardTheme(context).mThemeId;\n for (int index = 0; index < keyboardThemeIds.length; index++) {\n if (themeId == keyboardThemeIds[index]) {\n return keyboardThemeColors[index];\n }\n }\n\n return Color.LTGRAY;\n }\n\n public static int readKeyboardColor(final SharedPreferences prefs, final Context context) {\n return prefs.getInt(PREF_KEYBOARD_COLOR, readKeyboardDefaultColor(context));\n }\n\n public static void removeKeyboardColor(final SharedPreferences prefs) {\n prefs.edit().remove(PREF_KEYBOARD_COLOR).apply();\n }\n\n public static boolean readUseFullscreenMode(final Resources res) {\n return res.getBoolean(R.bool.config_use_fullscreen_mode);\n }\n\n public static boolean readHasHardwareKeyboard(final Configuration conf) {\n // The standard way of finding out whether we have a hardware keyboard. This code is taken\n // from InputMethodService#onEvaluateInputShown, which canonically determines this.\n // In a nutshell, we have a keyboard if the configuration says the type of hardware keyboard\n // is NOKEYS and if it's not hidden (e.g. folded inside the device).\n return conf.keyboard != Configuration.KEYBOARD_NOKEYS\n && conf.hardKeyboardHidden != Configuration.HARDKEYBOARDHIDDEN_YES;\n }\n\n public static boolean readUseMatchingNavbarColor(final SharedPreferences prefs) {\n return prefs.getBoolean(PREF_MATCHING_NAVBAR_COLOR, false);\n }\n}",
"public final class SubtypePreferenceUtils {\n private static final String TAG = SubtypePreferenceUtils.class.getSimpleName();\n\n private SubtypePreferenceUtils() {\n // This utility class is not publicly instantiable.\n }\n\n private static final String LOCALE_AND_LAYOUT_SEPARATOR = \":\";\n private static final int INDEX_OF_LOCALE = 0;\n private static final int INDEX_OF_KEYBOARD_LAYOUT = 1;\n private static final int PREF_ELEMENTS_LENGTH = (INDEX_OF_KEYBOARD_LAYOUT + 1);\n private static final String PREF_SUBTYPE_SEPARATOR = \";\";\n\n private static String getPrefString(final Subtype subtype) {\n final String localeString = subtype.getLocale();\n final String keyboardLayoutSetName = subtype.getKeyboardLayoutSet();\n return localeString + LOCALE_AND_LAYOUT_SEPARATOR + keyboardLayoutSetName;\n }\n\n public static List<Subtype> createSubtypesFromPref(final String prefSubtypes,\n final Resources resources) {\n if (TextUtils.isEmpty(prefSubtypes)) {\n return new ArrayList<>();\n }\n final String[] prefSubtypeArray = prefSubtypes.split(PREF_SUBTYPE_SEPARATOR);\n final ArrayList<Subtype> subtypesList = new ArrayList<>(prefSubtypeArray.length);\n for (final String prefSubtype : prefSubtypeArray) {\n final String[] elements = prefSubtype.split(LOCALE_AND_LAYOUT_SEPARATOR);\n if (elements.length != PREF_ELEMENTS_LENGTH) {\n Log.w(TAG, \"Unknown subtype specified: \" + prefSubtype + \" in \"\n + prefSubtypes);\n continue;\n }\n final String localeString = elements[INDEX_OF_LOCALE];\n final String keyboardLayoutSetName = elements[INDEX_OF_KEYBOARD_LAYOUT];\n final Subtype subtype =\n SubtypeLocaleUtils.getSubtype(localeString, keyboardLayoutSetName, resources);\n if (subtype == null) {\n continue;\n }\n subtypesList.add(subtype);\n }\n return subtypesList;\n }\n\n public static String createPrefSubtypes(final List<Subtype> subtypes) {\n if (subtypes == null || subtypes.size() == 0) {\n return \"\";\n }\n final StringBuilder sb = new StringBuilder();\n for (final Subtype subtype : subtypes) {\n if (sb.length() > 0) {\n sb.append(PREF_SUBTYPE_SEPARATOR);\n }\n sb.append(getPrefString(subtype));\n }\n return sb.toString();\n }\n}",
"public final class DialogUtils {\n private DialogUtils() {\n // This utility class is not publicly instantiable.\n }\n\n public static Context getPlatformDialogThemeContext(final Context context) {\n // Because {@link AlertDialog.Builder.create()} doesn't honor the specified theme with\n // createThemeContextWrapper=false, the result dialog box has unneeded paddings around it.\n return new ContextThemeWrapper(context, R.style.platformDialogTheme);\n }\n}",
"public final class LocaleResourceUtils {\n // This reference class {@link R} must be located in the same package as LatinIME.java.\n private static final String RESOURCE_PACKAGE_NAME = R.class.getPackage().getName();\n\n private static volatile boolean sInitialized = false;\n private static final Object sInitializeLock = new Object();\n private static Resources sResources;\n // Exceptional locale whose name should be displayed in Locale.ROOT.\n private static final HashMap<String, Integer> sExceptionalLocaleDisplayedInRootLocale =\n new HashMap<>();\n // Exceptional locale to locale name resource id map.\n private static final HashMap<String, Integer> sExceptionalLocaleToNameIdsMap = new HashMap<>();\n private static final String LOCALE_NAME_RESOURCE_PREFIX =\n \"string/locale_name_\";\n private static final String LOCALE_NAME_RESOURCE_IN_ROOT_LOCALE_PREFIX =\n \"string/locale_name_in_root_locale_\";\n\n private LocaleResourceUtils() {\n // Intentional empty constructor for utility class.\n }\n\n // Note that this initialization method can be called multiple times.\n public static void init(final Context context) {\n synchronized (sInitializeLock) {\n if (sInitialized == false) {\n initLocked(context);\n sInitialized = true;\n }\n }\n }\n\n private static void initLocked(final Context context) {\n final Resources res = context.getResources();\n sResources = res;\n\n final String[] exceptionalLocaleInRootLocale = res.getStringArray(\n R.array.locale_displayed_in_root_locale);\n for (int i = 0; i < exceptionalLocaleInRootLocale.length; i++) {\n final String localeString = exceptionalLocaleInRootLocale[i];\n final String resourceName = LOCALE_NAME_RESOURCE_IN_ROOT_LOCALE_PREFIX + localeString;\n final int resId = res.getIdentifier(resourceName, null, RESOURCE_PACKAGE_NAME);\n sExceptionalLocaleDisplayedInRootLocale.put(localeString, resId);\n }\n\n final String[] exceptionalLocales = res.getStringArray(R.array.locale_exception_keys);\n for (int i = 0; i < exceptionalLocales.length; i++) {\n final String localeString = exceptionalLocales[i];\n final String resourceName = LOCALE_NAME_RESOURCE_PREFIX + localeString;\n final int resId = res.getIdentifier(resourceName, null, RESOURCE_PACKAGE_NAME);\n sExceptionalLocaleToNameIdsMap.put(localeString, resId);\n }\n }\n\n private static Locale getDisplayLocale(final String localeString) {\n if (sExceptionalLocaleDisplayedInRootLocale.containsKey(localeString)) {\n return Locale.ROOT;\n }\n return LocaleUtils.constructLocaleFromString(localeString);\n }\n\n /**\n * Get the full display name of the locale in the system's locale.\n * For example in an English system, en_US: \"English (US)\", fr_CA: \"French (Canada)\"\n * @param localeString the locale to display.\n * @return the full display name of the locale.\n */\n public static String getLocaleDisplayNameInSystemLocale(\n final String localeString) {\n final Locale displayLocale = sResources.getConfiguration().locale;\n return getLocaleDisplayNameInternal(localeString, displayLocale);\n }\n\n /**\n * Get the full display name of the locale in its locale.\n * For example, en_US: \"English (US)\", fr_CA: \"Français (Canada)\"\n * @param localeString the locale to display.\n * @return the full display name of the locale.\n */\n public static String getLocaleDisplayNameInLocale(final String localeString) {\n final Locale displayLocale = getDisplayLocale(localeString);\n return getLocaleDisplayNameInternal(localeString, displayLocale);\n }\n\n /**\n * Get the display name of the language in the system's locale.\n * For example in an English system, en_US: \"English\", fr_CA: \"French\"\n * @param localeString the locale to display.\n * @return the display name of the language.\n */\n public static String getLanguageDisplayNameInSystemLocale(\n final String localeString) {\n final Locale displayLocale = sResources.getConfiguration().locale;\n final String languageString;\n if (sExceptionalLocaleDisplayedInRootLocale.containsKey(localeString)) {\n languageString = localeString;\n } else {\n languageString = LocaleUtils.constructLocaleFromString(localeString).getLanguage();\n }\n return getLocaleDisplayNameInternal(languageString, displayLocale);\n }\n\n /**\n * Get the display name of the language in its locale.\n * For example, en_US: \"English\", fr_CA: \"Français\"\n * @param localeString the locale to display.\n * @return the display name of the language.\n */\n public static String getLanguageDisplayNameInLocale(final String localeString) {\n final Locale displayLocale = getDisplayLocale(localeString);\n final String languageString;\n if (sExceptionalLocaleDisplayedInRootLocale.containsKey(localeString)) {\n languageString = localeString;\n } else {\n languageString = LocaleUtils.constructLocaleFromString(localeString).getLanguage();\n }\n return getLocaleDisplayNameInternal(languageString, displayLocale);\n }\n\n private static String getLocaleDisplayNameInternal(final String localeString,\n final Locale displayLocale) {\n final Integer exceptionalNameResId;\n if (displayLocale.equals(Locale.ROOT)\n && sExceptionalLocaleDisplayedInRootLocale.containsKey(localeString)) {\n exceptionalNameResId = sExceptionalLocaleDisplayedInRootLocale.get(localeString);\n } else if (sExceptionalLocaleToNameIdsMap.containsKey(localeString)) {\n exceptionalNameResId = sExceptionalLocaleToNameIdsMap.get(localeString);\n } else {\n exceptionalNameResId = null;\n }\n\n final String displayName;\n if (exceptionalNameResId != null) {\n displayName = sResources.getString(exceptionalNameResId);\n } else {\n displayName = LocaleUtils.constructLocaleFromString(localeString)\n .getDisplayName(displayLocale);\n }\n return StringUtils.capitalizeFirstCodePoint(displayName, displayLocale);\n }\n}",
"public final class SubtypeLocaleUtils {\n\n private SubtypeLocaleUtils() {\n // This utility class is not publicly instantiable.\n }\n\n private static final String LOCALE_AFRIKAANS = \"af\";\n private static final String LOCALE_ARABIC = \"ar\";\n private static final String LOCALE_AZERBAIJANI_AZERBAIJAN = \"az_AZ\";\n private static final String LOCALE_BELARUSIAN_BELARUS = \"be_BY\";\n private static final String LOCALE_BULGARIAN = \"bg\";\n private static final String LOCALE_BENGALI_BANGLADESH = \"bn_BD\";\n private static final String LOCALE_BENGALI_INDIA = \"bn_IN\";\n private static final String LOCALE_CATALAN = \"ca\";\n private static final String LOCALE_CZECH = \"cs\";\n private static final String LOCALE_DANISH = \"da\";\n private static final String LOCALE_GERMAN = \"de\";\n private static final String LOCALE_GERMAN_SWITZERLAND = \"de_CH\";\n private static final String LOCALE_GREEK = \"el\";\n private static final String LOCALE_ENGLISH_INDIA = \"en_IN\";\n private static final String LOCALE_ENGLISH_GREAT_BRITAIN = \"en_GB\";\n private static final String LOCALE_ENGLISH_UNITED_STATES = \"en_US\";\n private static final String LOCALE_ESPERANTO = \"eo\";\n private static final String LOCALE_SPANISH = \"es\";\n private static final String LOCALE_SPANISH_UNITED_STATES = \"es_US\";\n private static final String LOCALE_SPANISH_LATIN_AMERICA = \"es_419\";\n private static final String LOCALE_ESTONIAN_ESTONIA = \"et_EE\";\n private static final String LOCALE_BASQUE_SPAIN = \"eu_ES\";\n private static final String LOCALE_PERSIAN = \"fa\";\n private static final String LOCALE_FINNISH = \"fi\";\n private static final String LOCALE_FRENCH = \"fr\";\n private static final String LOCALE_FRENCH_CANADA = \"fr_CA\";\n private static final String LOCALE_FRENCH_SWITZERLAND = \"fr_CH\";\n private static final String LOCALE_GALICIAN_SPAIN = \"gl_ES\";\n private static final String LOCALE_HINDI = \"hi\";\n private static final String LOCALE_CROATIAN = \"hr\";\n private static final String LOCALE_HUNGARIAN = \"hu\";\n private static final String LOCALE_ARMENIAN_ARMENIA = \"hy_AM\";\n // Java uses the deprecated \"in\" code instead of the standard \"id\" code for Indonesian.\n private static final String LOCALE_INDONESIAN = \"in\";\n private static final String LOCALE_ICELANDIC = \"is\";\n private static final String LOCALE_ITALIAN = \"it\";\n private static final String LOCALE_ITALIAN_SWITZERLAND = \"it_CH\";\n // Java uses the deprecated \"iw\" code instead of the standard \"he\" code for Hebrew.\n private static final String LOCALE_HEBREW = \"iw\";\n private static final String LOCALE_GEORGIAN_GEORGIA = \"ka_GE\";\n private static final String LOCALE_KAZAKH = \"kk\";\n private static final String LOCALE_KHMER_CAMBODIA = \"km_KH\";\n private static final String LOCALE_KANNADA_INDIA = \"kn_IN\";\n private static final String LOCALE_KYRGYZ = \"ky\";\n private static final String LOCALE_LAO_LAOS = \"lo_LA\";\n private static final String LOCALE_LITHUANIAN = \"lt\";\n private static final String LOCALE_LATVIAN = \"lv\";\n private static final String LOCALE_MACEDONIAN = \"mk\";\n private static final String LOCALE_MALAYALAM_INDIA = \"ml_IN\";\n private static final String LOCALE_MONGOLIAN_MONGOLIA = \"mn_MN\";\n private static final String LOCALE_MARATHI_INDIA = \"mr_IN\";\n private static final String LOCALE_MALAY_MALAYSIA = \"ms_MY\";\n private static final String LOCALE_NORWEGIAN_BOKMAL = \"nb\"; // Norwegian Bokmål\n private static final String LOCALE_NEPALI_NEPAL = \"ne_NP\";\n private static final String LOCALE_DUTCH = \"nl\";\n private static final String LOCALE_DUTCH_BELGIUM = \"nl_BE\";\n private static final String LOCALE_POLISH = \"pl\";\n private static final String LOCALE_PORTUGUESE_BRAZIL = \"pt_BR\";\n private static final String LOCALE_PORTUGUESE_PORTUGAL = \"pt_PT\";\n private static final String LOCALE_ROMANIAN = \"ro\";\n private static final String LOCALE_RUSSIAN = \"ru\";\n private static final String LOCALE_SLOVAK = \"sk\";\n private static final String LOCALE_SLOVENIAN = \"sl\";\n private static final String LOCALE_SERBIAN = \"sr\";\n private static final String LOCALE_SERBIAN_LATIN = \"sr_ZZ\";\n private static final String LOCALE_SWEDISH = \"sv\";\n private static final String LOCALE_SWAHILI = \"sw\";\n private static final String LOCALE_TAMIL_INDIA = \"ta_IN\";\n private static final String LOCALE_TAMIL_SINGAPORE = \"ta_SG\";\n private static final String LOCALE_TELUGU_INDIA = \"te_IN\";\n private static final String LOCALE_THAI = \"th\";\n private static final String LOCALE_TAGALOG = \"tl\";\n private static final String LOCALE_TURKISH = \"tr\";\n private static final String LOCALE_UKRAINIAN = \"uk\";\n private static final String LOCALE_URDU = \"ur\";\n private static final String LOCALE_UZBEK_UZBEKISTAN = \"uz_UZ\";\n private static final String LOCALE_VIETNAMESE = \"vi\";\n private static final String LOCALE_ZULU = \"zu\";\n\n private static final String[] sSupportedLocales = new String[] {\n LOCALE_ENGLISH_UNITED_STATES,\n LOCALE_ENGLISH_GREAT_BRITAIN,\n LOCALE_AFRIKAANS,\n LOCALE_ARABIC,\n LOCALE_AZERBAIJANI_AZERBAIJAN,\n LOCALE_BELARUSIAN_BELARUS,\n LOCALE_BULGARIAN,\n LOCALE_BENGALI_BANGLADESH,\n LOCALE_BENGALI_INDIA,\n LOCALE_CATALAN,\n LOCALE_CZECH,\n LOCALE_DANISH,\n LOCALE_GERMAN,\n LOCALE_GERMAN_SWITZERLAND,\n LOCALE_GREEK,\n LOCALE_ENGLISH_INDIA,\n LOCALE_ESPERANTO,\n LOCALE_SPANISH,\n LOCALE_SPANISH_UNITED_STATES,\n LOCALE_SPANISH_LATIN_AMERICA,\n LOCALE_ESTONIAN_ESTONIA,\n LOCALE_BASQUE_SPAIN,\n LOCALE_PERSIAN,\n LOCALE_FINNISH,\n LOCALE_FRENCH,\n LOCALE_FRENCH_CANADA,\n LOCALE_FRENCH_SWITZERLAND,\n LOCALE_GALICIAN_SPAIN,\n LOCALE_HINDI,\n LOCALE_CROATIAN,\n LOCALE_HUNGARIAN,\n LOCALE_ARMENIAN_ARMENIA,\n LOCALE_INDONESIAN,\n LOCALE_ICELANDIC,\n LOCALE_ITALIAN,\n LOCALE_ITALIAN_SWITZERLAND,\n LOCALE_HEBREW,\n LOCALE_GEORGIAN_GEORGIA,\n LOCALE_KAZAKH,\n LOCALE_KHMER_CAMBODIA,\n LOCALE_KANNADA_INDIA,\n LOCALE_KYRGYZ,\n LOCALE_LAO_LAOS,\n LOCALE_LITHUANIAN,\n LOCALE_LATVIAN,\n LOCALE_MACEDONIAN,\n LOCALE_MALAYALAM_INDIA,\n LOCALE_MONGOLIAN_MONGOLIA,\n LOCALE_MARATHI_INDIA,\n LOCALE_MALAY_MALAYSIA,\n LOCALE_NORWEGIAN_BOKMAL,\n LOCALE_NEPALI_NEPAL,\n LOCALE_DUTCH,\n LOCALE_DUTCH_BELGIUM,\n LOCALE_POLISH,\n LOCALE_PORTUGUESE_BRAZIL,\n LOCALE_PORTUGUESE_PORTUGAL,\n LOCALE_ROMANIAN,\n LOCALE_RUSSIAN,\n LOCALE_SLOVAK,\n LOCALE_SLOVENIAN,\n LOCALE_SERBIAN,\n LOCALE_SERBIAN_LATIN,\n LOCALE_SWEDISH,\n LOCALE_SWAHILI,\n LOCALE_TAMIL_INDIA,\n LOCALE_TAMIL_SINGAPORE,\n LOCALE_TELUGU_INDIA,\n LOCALE_THAI,\n LOCALE_TAGALOG,\n LOCALE_TURKISH,\n LOCALE_UKRAINIAN,\n LOCALE_URDU,\n LOCALE_UZBEK_UZBEKISTAN,\n LOCALE_VIETNAMESE,\n LOCALE_ZULU\n };\n\n /**\n * Get a list of all of the currently supported subtype locales.\n * @return a list of subtype strings in the format of \"ll_cc_variant\" where \"ll\" is a language\n * code, \"cc\" is a country code.\n */\n public static List<String> getSupportedLocales() {\n return Arrays.asList(sSupportedLocales);\n }\n\n public static final String LAYOUT_ARABIC = \"arabic\";\n public static final String LAYOUT_ARMENIAN_PHONETIC = \"armenian_phonetic\";\n public static final String LAYOUT_AZERTY = \"azerty\";\n public static final String LAYOUT_BENGALI = \"bengali\";\n public static final String LAYOUT_BENGALI_AKKHOR = \"bengali_akkhor\";\n public static final String LAYOUT_BULGARIAN = \"bulgarian\";\n public static final String LAYOUT_BULGARIAN_BDS = \"bulgarian_bds\";\n public static final String LAYOUT_EAST_SLAVIC = \"east_slavic\";\n public static final String LAYOUT_FARSI = \"farsi\";\n public static final String LAYOUT_GEORGIAN = \"georgian\";\n public static final String LAYOUT_GREEK = \"greek\";\n public static final String LAYOUT_HEBREW = \"hebrew\";\n public static final String LAYOUT_HINDI = \"hindi\";\n public static final String LAYOUT_HINDI_COMPACT = \"hindi_compact\";\n public static final String LAYOUT_KANNADA = \"kannada\";\n public static final String LAYOUT_KHMER = \"khmer\";\n public static final String LAYOUT_LAO = \"lao\";\n public static final String LAYOUT_MACEDONIAN = \"macedonian\";\n public static final String LAYOUT_MALAYALAM = \"malayalam\";\n public static final String LAYOUT_MARATHI = \"marathi\";\n public static final String LAYOUT_MONGOLIAN = \"mongolian\";\n public static final String LAYOUT_NEPALI_ROMANIZED = \"nepali_romanized\";\n public static final String LAYOUT_NEPALI_TRADITIONAL = \"nepali_traditional\";\n public static final String LAYOUT_NORDIC = \"nordic\";\n public static final String LAYOUT_QWERTY = \"qwerty\";\n public static final String LAYOUT_QWERTZ = \"qwertz\";\n public static final String LAYOUT_SERBIAN = \"serbian\";\n public static final String LAYOUT_SERBIAN_QWERTZ = \"serbian_qwertz\";\n public static final String LAYOUT_SPANISH = \"spanish\";\n public static final String LAYOUT_SWISS = \"swiss\";\n public static final String LAYOUT_TAMIL = \"tamil\";\n public static final String LAYOUT_TELUGU = \"telugu\";\n public static final String LAYOUT_THAI = \"thai\";\n public static final String LAYOUT_TURKISH_Q = \"turkish_q\";\n public static final String LAYOUT_TURKISH_F = \"turkish_f\";\n public static final String LAYOUT_URDU = \"urdu\";\n public static final String LAYOUT_UZBEK = \"uzbek\";\n\n /**\n * Get a list of all of the supported subtypes for a locale.\n * @param locale the locale string for the subtypes to look up.\n * @param resources the resources to use.\n * @return the list of subtypes for the specified locale.\n */\n public static List<Subtype> getSubtypes(final String locale, final Resources resources) {\n return new SubtypeBuilder(locale, true, resources).getSubtypes();\n }\n\n /**\n * Get the default subtype for a locale.\n * @param locale the locale string for the subtype to look up.\n * @param resources the resources to use.\n * @return the default subtype for the specified locale or null if the locale isn't supported.\n */\n public static Subtype getDefaultSubtype(final String locale, final Resources resources) {\n final List<Subtype> subtypes = new SubtypeBuilder(locale, true, resources).getSubtypes();\n return subtypes.size() == 0 ? null : subtypes.get(0);\n }\n\n /**\n * Get a subtype for a specific locale and keyboard layout.\n * @param locale the locale string for the subtype to look up.\n * @param layoutSet the keyboard layout set name for the subtype.\n * @param resources the resources to use.\n * @return the subtype for the specified locale and layout or null if it isn't supported.\n */\n public static Subtype getSubtype(final String locale, final String layoutSet,\n final Resources resources) {\n final List<Subtype> subtypes =\n new SubtypeBuilder(locale, layoutSet, resources).getSubtypes();\n return subtypes.size() == 0 ? null : subtypes.get(0);\n }\n\n /**\n * Get the list subtypes corresponding to the system's languages.\n * @param resources the resources to use.\n * @return the default list of subtypes based on the system's languages.\n */\n public static List<Subtype> getDefaultSubtypes(final Resources resources) {\n final ArrayList<Locale> supportedLocales = new ArrayList<>(sSupportedLocales.length);\n for (final String localeString : sSupportedLocales) {\n supportedLocales.add(LocaleUtils.constructLocaleFromString(localeString));\n }\n\n final List<Locale> systemLocales = LocaleUtils.getSystemLocales();\n\n final ArrayList<Subtype> subtypes = new ArrayList<>();\n final HashSet<Locale> addedLocales = new HashSet<>();\n for (final Locale systemLocale : systemLocales) {\n final Locale bestLocale = LocaleUtils.findBestLocale(systemLocale, supportedLocales);\n if (bestLocale != null && !addedLocales.contains(bestLocale)) {\n addedLocales.add(bestLocale);\n final String bestLocaleString = LocaleUtils.getLocaleString(bestLocale);\n subtypes.add(getDefaultSubtype(bestLocaleString, resources));\n }\n }\n if (subtypes.size() == 0) {\n // there needs to be at least one default subtype\n subtypes.add(getSubtypes(LOCALE_ENGLISH_UNITED_STATES, resources).get(0));\n }\n return subtypes;\n }\n\n /**\n * Utility for building the supported subtype objects. {@link #getSubtypes} sets up the full\n * list of available subtypes for a locale, but not all of the subtypes that it requests always\n * get returned. The parameters passed in the constructor limit what subtypes are actually built\n * and returned. This allows for a central location for indicating what subtypes are available\n * for each locale without always needing to build them all.\n */\n private static class SubtypeBuilder {\n private final Resources mResources;\n private final boolean mAllowMultiple;\n private final String mLocale;\n private final String mExpectedLayoutSet;\n private List<Subtype> mSubtypes;\n\n /**\n * Builder for single subtype with a specific locale and layout.\n * @param locale the locale string for the subtype to build.\n * @param layoutSet the keyboard layout set name for the subtype.\n * @param resources the resources to use.\n */\n public SubtypeBuilder(final String locale, final String layoutSet,\n final Resources resources) {\n mLocale = locale;\n mExpectedLayoutSet = layoutSet;\n mAllowMultiple = false;\n mResources = resources;\n }\n\n /**\n * Builder for one or all subtypes with a specific locale.\n * @param locale the locale string for the subtype to build.\n * @param all true to get all of the subtypes for the locale or false for just the default.\n * @param resources the resources to use.\n */\n public SubtypeBuilder(final String locale, final boolean all, final Resources resources) {\n mLocale = locale;\n mExpectedLayoutSet = null;\n mAllowMultiple = all;\n mResources = resources;\n }\n\n /**\n * Get the requested subtypes.\n * @return the list of subtypes that were built.\n */\n public List<Subtype> getSubtypes() {\n if (mSubtypes != null) {\n // in case this gets called again for some reason, the subtypes should only be built\n // once\n return mSubtypes;\n }\n mSubtypes = new ArrayList<>();\n // This should call to build all of the available for each supported locale. The private\n // helper functions will handle skipping building the subtypes that weren't requested.\n // The first subtype that is specified to be built here for each locale will be\n // considered the default.\n switch (mLocale) {\n case LOCALE_AFRIKAANS:\n case LOCALE_AZERBAIJANI_AZERBAIJAN:\n case LOCALE_ENGLISH_INDIA:\n case LOCALE_ENGLISH_GREAT_BRITAIN:\n case LOCALE_ENGLISH_UNITED_STATES:\n case LOCALE_FRENCH_CANADA:\n case LOCALE_INDONESIAN:\n case LOCALE_ICELANDIC:\n case LOCALE_ITALIAN:\n case LOCALE_LITHUANIAN:\n case LOCALE_LATVIAN:\n case LOCALE_MALAY_MALAYSIA:\n case LOCALE_DUTCH:\n case LOCALE_POLISH:\n case LOCALE_PORTUGUESE_BRAZIL:\n case LOCALE_PORTUGUESE_PORTUGAL:\n case LOCALE_ROMANIAN:\n case LOCALE_SLOVAK:\n case LOCALE_SWAHILI:\n case LOCALE_VIETNAMESE:\n case LOCALE_ZULU:\n addLayout(LAYOUT_QWERTY);\n addGenericLayouts();\n break;\n case LOCALE_CZECH:\n case LOCALE_GERMAN:\n case LOCALE_CROATIAN:\n case LOCALE_HUNGARIAN:\n case LOCALE_SLOVENIAN:\n addLayout(LAYOUT_QWERTZ);\n addGenericLayouts();\n break;\n case LOCALE_FRENCH:\n case LOCALE_DUTCH_BELGIUM:\n addLayout(LAYOUT_AZERTY);\n addGenericLayouts();\n break;\n case LOCALE_CATALAN:\n case LOCALE_SPANISH:\n case LOCALE_SPANISH_UNITED_STATES:\n case LOCALE_SPANISH_LATIN_AMERICA:\n case LOCALE_BASQUE_SPAIN:\n case LOCALE_GALICIAN_SPAIN:\n case LOCALE_TAGALOG:\n addLayout(LAYOUT_SPANISH);\n addGenericLayouts();\n break;\n case LOCALE_ESPERANTO:\n addLayout(LAYOUT_SPANISH);\n break;\n case LOCALE_DANISH:\n case LOCALE_ESTONIAN_ESTONIA:\n case LOCALE_FINNISH:\n case LOCALE_NORWEGIAN_BOKMAL:\n case LOCALE_SWEDISH:\n addLayout(LAYOUT_NORDIC);\n addGenericLayouts();\n break;\n case LOCALE_GERMAN_SWITZERLAND:\n case LOCALE_FRENCH_SWITZERLAND:\n case LOCALE_ITALIAN_SWITZERLAND:\n addLayout(LAYOUT_SWISS);\n addGenericLayouts();\n break;\n case LOCALE_TURKISH:\n addLayout(LAYOUT_QWERTY);\n addLayout(LAYOUT_TURKISH_Q, R.string.subtype_q);\n addLayout(LAYOUT_TURKISH_F, R.string.subtype_f);\n addGenericLayouts();\n break;\n case LOCALE_UZBEK_UZBEKISTAN:\n addLayout(LAYOUT_UZBEK);\n addGenericLayouts();\n break;\n case LOCALE_ARABIC:\n addLayout(LAYOUT_ARABIC);\n break;\n case LOCALE_BELARUSIAN_BELARUS:\n case LOCALE_KAZAKH:\n case LOCALE_KYRGYZ:\n case LOCALE_RUSSIAN:\n case LOCALE_UKRAINIAN:\n addLayout(LAYOUT_EAST_SLAVIC);\n break;\n case LOCALE_BULGARIAN:\n addLayout(LAYOUT_BULGARIAN);\n addLayout(LAYOUT_BULGARIAN_BDS, R.string.subtype_bds);\n break;\n case LOCALE_BENGALI_BANGLADESH:\n addLayout(LAYOUT_BENGALI_AKKHOR);\n break;\n case LOCALE_BENGALI_INDIA:\n addLayout(LAYOUT_BENGALI);\n break;\n case LOCALE_GREEK:\n addLayout(LAYOUT_GREEK);\n break;\n case LOCALE_PERSIAN:\n addLayout(LAYOUT_FARSI);\n break;\n case LOCALE_HINDI:\n addLayout(LAYOUT_HINDI);\n addLayout(LAYOUT_HINDI_COMPACT, R.string.subtype_compact);\n break;\n case LOCALE_ARMENIAN_ARMENIA:\n addLayout(LAYOUT_ARMENIAN_PHONETIC);\n break;\n case LOCALE_HEBREW:\n addLayout(LAYOUT_HEBREW);\n break;\n case LOCALE_GEORGIAN_GEORGIA:\n addLayout(LAYOUT_GEORGIAN);\n break;\n case LOCALE_KHMER_CAMBODIA:\n addLayout(LAYOUT_KHMER);\n break;\n case LOCALE_KANNADA_INDIA:\n addLayout(LAYOUT_KANNADA);\n break;\n case LOCALE_LAO_LAOS:\n addLayout(LAYOUT_LAO);\n break;\n case LOCALE_MACEDONIAN:\n addLayout(LAYOUT_MACEDONIAN);\n break;\n case LOCALE_MALAYALAM_INDIA:\n addLayout(LAYOUT_MALAYALAM);\n break;\n case LOCALE_MONGOLIAN_MONGOLIA:\n addLayout(LAYOUT_MONGOLIAN);\n break;\n case LOCALE_MARATHI_INDIA:\n addLayout(LAYOUT_MARATHI);\n break;\n case LOCALE_NEPALI_NEPAL:\n addLayout(LAYOUT_NEPALI_ROMANIZED);\n addLayout(LAYOUT_NEPALI_TRADITIONAL, R.string.subtype_traditional);\n break;\n case LOCALE_SERBIAN:\n addLayout(LAYOUT_SERBIAN);\n break;\n case LOCALE_SERBIAN_LATIN:\n addLayout(LAYOUT_SERBIAN_QWERTZ);\n addGenericLayouts();\n break;\n case LOCALE_TAMIL_INDIA:\n case LOCALE_TAMIL_SINGAPORE:\n addLayout(LAYOUT_TAMIL);\n break;\n case LOCALE_TELUGU_INDIA:\n addLayout(LAYOUT_TELUGU);\n break;\n case LOCALE_THAI:\n addLayout(LAYOUT_THAI);\n break;\n case LOCALE_URDU:\n addLayout(LAYOUT_URDU);\n break;\n }\n return mSubtypes;\n }\n\n /**\n * Check if the layout should skip being built based on the request from the constructor.\n * @param keyboardLayoutSet the layout set for the subtype to potentially build.\n * @return whether the subtype should be skipped.\n */\n private boolean shouldSkipLayout(final String keyboardLayoutSet) {\n if (mAllowMultiple) {\n return false;\n }\n if (mSubtypes.size() > 0) {\n return true;\n }\n if (mExpectedLayoutSet != null) {\n return !mExpectedLayoutSet.equals(keyboardLayoutSet);\n }\n return false;\n }\n\n /**\n * Add a single layout for the locale. This might not actually add the subtype to the list\n * depending on the original request.\n * @param keyboardLayoutSet the keyboard layout set name.\n */\n private void addLayout(final String keyboardLayoutSet) {\n if (shouldSkipLayout(keyboardLayoutSet)) {\n return;\n }\n\n // if this is a generic layout, use that corresponding layout name\n final String[] predefinedLayouts =\n mResources.getStringArray(R.array.predefined_layouts);\n final int predefinedLayoutIndex =\n Arrays.asList(predefinedLayouts).indexOf(keyboardLayoutSet);\n final String layoutNameStr;\n if (predefinedLayoutIndex >= 0) {\n final String[] predefinedLayoutDisplayNames = mResources.getStringArray(\n R.array.predefined_layout_display_names);\n layoutNameStr = predefinedLayoutDisplayNames[predefinedLayoutIndex];\n } else {\n layoutNameStr = null;\n }\n\n mSubtypes.add(\n new Subtype(mLocale, keyboardLayoutSet, layoutNameStr, false, mResources));\n }\n\n /**\n * Add a single layout for the locale. This might not actually add the subtype to the list\n * depending on the original request.\n * @param keyboardLayoutSet the keyboard layout set name.\n * @param layoutRes the resource ID to use for the display name of the keyboard layout. This\n * generally shouldn't include the name of the language.\n */\n private void addLayout(final String keyboardLayoutSet, final int layoutRes) {\n if (shouldSkipLayout(keyboardLayoutSet)) {\n return;\n }\n mSubtypes.add(\n new Subtype(mLocale, keyboardLayoutSet, layoutRes, true, mResources));\n }\n\n /**\n * Add the predefined layouts (eg: QWERTY, AZERTY, etc) for the locale. This might not\n * actually add all of the subtypes to the list depending on the original request.\n */\n private void addGenericLayouts() {\n if (mSubtypes.size() > 0 && !mAllowMultiple) {\n return;\n }\n final int initialSize = mSubtypes.size();\n final String[] predefinedKeyboardLayoutSets = mResources.getStringArray(\n R.array.predefined_layouts);\n final String[] predefinedKeyboardLayoutSetDisplayNames = mResources.getStringArray(\n R.array.predefined_layout_display_names);\n for (int i = 0; i < predefinedKeyboardLayoutSets.length; i++) {\n final String predefinedLayout = predefinedKeyboardLayoutSets[i];\n if (shouldSkipLayout(predefinedLayout)) {\n continue;\n }\n\n boolean alreadyExists = false;\n for (int subtypeIndex = 0; subtypeIndex < initialSize; subtypeIndex++) {\n final String layoutSet = mSubtypes.get(subtypeIndex).getKeyboardLayoutSet();\n if (layoutSet.equals(predefinedLayout)) {\n alreadyExists = true;\n break;\n }\n }\n if (alreadyExists) {\n continue;\n }\n\n mSubtypes.add(new Subtype(mLocale, predefinedLayout,\n predefinedKeyboardLayoutSetDisplayNames[i], true, mResources));\n }\n }\n }\n}"
] | import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.inputmethodservice.InputMethodService;
import android.os.Build;
import android.os.IBinder;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import android.view.inputmethod.InputMethodSubtype;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Executors;
import rkr.simplekeyboard.inputmethod.R;
import rkr.simplekeyboard.inputmethod.compat.PreferenceManagerCompat;
import rkr.simplekeyboard.inputmethod.latin.common.LocaleUtils;
import rkr.simplekeyboard.inputmethod.latin.settings.Settings;
import rkr.simplekeyboard.inputmethod.latin.utils.SubtypePreferenceUtils;
import rkr.simplekeyboard.inputmethod.latin.utils.DialogUtils;
import rkr.simplekeyboard.inputmethod.latin.utils.LocaleResourceUtils;
import rkr.simplekeyboard.inputmethod.latin.utils.SubtypeLocaleUtils; | * @param token supplies the identifying token given to an input method when it was started,
* which allows it to perform this operation on itself.
* @param onlyCurrentIme whether to only switch virtual subtypes or also switch to other input
* methods.
* @return whether the switch was successful.
*/
public boolean switchToNextInputMethod(final IBinder token, final boolean onlyCurrentIme) {
if (onlyCurrentIme) {
if (!hasMultipleEnabledSubtypes()) {
return false;
}
return mSubtypeList.switchToNextSubtype(true);
}
if (mSubtypeList.switchToNextSubtype(false)) {
return true;
}
// switch to a different IME
if (mImmService.switchToNextInputMethod(token, false)) {
return true;
}
if (hasMultipleEnabledSubtypes()) {
// the virtual subtype should have been reset to the first item to prepare for switching
// back to this IME, but we skipped notifying the change because we expected to switch
// to a different IME, but since that failed, we just need to notify the listener
mSubtypeList.notifySubtypeChanged();
return true;
}
return false;
}
/**
* Get the subtype that is currently in use.
* @return the current subtype.
*/
public Subtype getCurrentSubtype() {
return mSubtypeList.getCurrentSubtype();
}
/**
* Check if the IME should offer ways to switch to a next input method (eg: a globe key).
* @param binder supplies the identifying token given to an input method when it was started,
* which allows it to perform this operation on itself.
* @return whether the IME should offer ways to switch to a next input method.
*/
public boolean shouldOfferSwitchingToOtherInputMethods(final IBinder binder) {
// Use the default value instead on Jelly Bean MR2 and previous where
// {@link InputMethodManager#shouldOfferSwitchingToNextInputMethod} isn't yet available
// and on KitKat where the API is still just a stub to return true always.
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
return false;
}
return mImmService.shouldOfferSwitchingToNextInputMethod(binder);
}
/**
* Show a popup to pick the current subtype.
* @param context the context for this application.
* @param windowToken identifier for the window.
* @param inputMethodService the input method service for this IME.
* @return the dialog that was created.
*/
public AlertDialog showSubtypePicker(final Context context, final IBinder windowToken,
final InputMethodService inputMethodService) {
if (windowToken == null) {
return null;
}
final CharSequence title = context.getString(R.string.change_keyboard);
final List<SubtypeInfo> subtypeInfoList = getEnabledSubtypeInfoOfAllImes(context);
if (subtypeInfoList.size() < 2) {
// if there aren't multiple options, there is no reason to show the picker
return null;
}
final CharSequence[] items = new CharSequence[subtypeInfoList.size()];
final Subtype currentSubtype = getCurrentSubtype();
int currentSubtypeIndex = 0;
int i = 0;
for (final SubtypeInfo subtypeInfo : subtypeInfoList) {
if (subtypeInfo.virtualSubtype != null
&& subtypeInfo.virtualSubtype.equals(currentSubtype)) {
currentSubtypeIndex = i;
}
final SpannableString itemTitle;
final SpannableString itemSubtitle;
if (!TextUtils.isEmpty(subtypeInfo.subtypeName)) {
itemTitle = new SpannableString(subtypeInfo.subtypeName);
itemSubtitle = new SpannableString("\n" + subtypeInfo.imeName);
} else {
itemTitle = new SpannableString(subtypeInfo.imeName);
itemSubtitle = new SpannableString("");
}
itemTitle.setSpan(new RelativeSizeSpan(0.9f), 0,itemTitle.length(),
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
itemSubtitle.setSpan(new RelativeSizeSpan(0.85f), 0,itemSubtitle.length(),
Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
items[i++] = new SpannableStringBuilder().append(itemTitle).append(itemSubtitle);
}
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int position) {
di.dismiss();
int i = 0;
for (final SubtypeInfo subtypeInfo : subtypeInfoList) {
if (i == position) {
if (subtypeInfo.virtualSubtype != null) {
setCurrentSubtype(subtypeInfo.virtualSubtype);
} else {
switchToTargetIme(subtypeInfo.imiId, subtypeInfo.systemSubtype,
inputMethodService);
}
break;
}
i++;
}
}
};
final AlertDialog.Builder builder = new AlertDialog.Builder( | DialogUtils.getPlatformDialogThemeContext(context)); | 4 |
FlyingPumba/SoundBox | src/com/arcusapp/soundbox/adapter/SongsListActivityAdapter.java | [
"public class SoundBoxApplication extends Application {\n private static Context appContext;\n\n public static final String ACTION_MAIN_ACTIVITY = \"com.arcusapp.soundbox.action.MAIN_ACTIVITY\";\n public static final String ACTION_FOLDERS_ACTIVITY = \"com.arcusapp.soundbox.action.FOLDERS_ACTIVITY\";\n public static final String ACTION_SONGSLIST_ACTIVITY = \"com.arcusapp.soundbox.action.SONGSLIST_ACTIVITY\";\n public static final String ACTION_ABOUT_ACTIVITY = \"com.arcusapp.soundbox.action.ABOUT_ACTIVITY\";\n public static final String ACTION_MEDIA_PLAYER_SERVICE = \"com.arcusapp.soundbox.action.MEDIA_PLAYER_SERVICE\";\n\n private static List<File> sdCards;\n\n private static int mForegroundActivities = 0;\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n appContext = getApplicationContext();\n searchForSDCards();\n }\n\n public static Context getContext() {\n return appContext;\n }\n\n public static void notifyForegroundStateChanged(boolean inForeground) {\n int old = mForegroundActivities;\n if (inForeground) {\n mForegroundActivities++;\n } else {\n mForegroundActivities--;\n }\n\n if (old == 0 || mForegroundActivities == 0) {\n Intent intent = new Intent();\n intent.setAction(MediaPlayerService.CHANGE_FOREGROUND_STATE);\n intent.putExtra(MediaPlayerService.NOW_IN_FOREGROUND, mForegroundActivities == 0);\n appContext.startService(intent);\n }\n\n }\n\n public static List<File> getSDCards() {\n return sdCards;\n }\n\n public static List<File> getDefaultUserDirectoriesOptions() {\n List<File> defaultUserOptions = new ArrayList<File>();\n\n if(Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) {\n File musicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);\n defaultUserOptions.add(musicDirectory);\n }\n defaultUserOptions.addAll(sdCards);\n return defaultUserOptions;\n }\n\n private void searchForSDCards() {\n sdCards = new ArrayList<File>();\n File primarysdCard = Environment.getExternalStorageDirectory();\n String[] sdCardDirectories = DirectoryHelper.getStorageDirectories();\n String[] othersdCardDirectories = DirectoryHelper.getOtherStorageDirectories();\n\n sdCards.add(primarysdCard);\n for (String s : sdCardDirectories) {\n File directory = new File(s);\n if (!sdCards.contains(directory)) {\n sdCards.add(directory);\n }\n }\n for (String s : othersdCardDirectories) {\n File directory = new File(s);\n if (!sdCards.contains(directory)) {\n sdCards.add(directory);\n }\n }\n }\n}",
"public class MediaProvider {\n\n private OnlyDirsFilter myFilter;\n private File defaultDirectory;\n private Uri defaultDirectoryUri;\n\n private Cursor myCursor;\n\n public MediaProvider() {\n myFilter = new OnlyDirsFilter();\n\n defaultDirectory = SoundBoxApplication.getSDCards().get(0);\n defaultDirectoryUri = MediaStore.Audio.Media.getContentUriForPath(defaultDirectory.getPath());\n }\n\n /**\n * Returns the id of all the Songs in the MediaStore.\n * \n * @return list with the ids\n */\n public List<String> getAllSongs() {\n List<String> songs = new ArrayList<String>();\n\n String[] cursorProjection = new String[] { MediaStore.Audio.Media._ID };\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 \";\n String sortOrder = MediaStore.Audio.Media.TITLE;\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, cursorProjection, selection, null, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n songs.add(myCursor.getString(0));\n }\n\n myCursor.close();\n return songs;\n }\n\n /**\n * Returns the name ({@linkplain MediaStore.Audio.Artists.ARTIST}) of all the Artists in the MediaStore.\n * \n * @return list with the names\n */\n public List<String> getAllArtists() {\n List<String> artists = new ArrayList<String>();\n\n String[] projection = { \"DISTINCT \" + MediaStore.Audio.Artists.ARTIST };\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \" + MediaStore.Audio.Artists.ARTIST + \" not null \";\n String sortOrder = MediaStore.Audio.Artists.ARTIST;\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, projection, selection, null, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n artists.add(myCursor.getString(0));\n }\n myCursor.close();\n return artists;\n }\n\n /**\n * Returns the name ({@linkplain MediaStore.Audio.Albums.ALBUM}) of all the Albums of the specified Artist in the MediaStore.\n * \n * @param artist the name of the Artist ({@linkplain MediaStore.Audio.Artists.ARTIST})\n * @return list with the names\n */\n public List<String> getAlbumsFromArtist(String artist) {\n List<String> albums = new ArrayList<String>();\n\n String[] projection = { \"DISTINCT \" + MediaStore.Audio.Artists.Albums.ALBUM };\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \" + MediaStore.Audio.Artists.ARTIST + \" = ?\";\n String sortOrder = MediaStore.Audio.Artists.Albums.ALBUM;\n String[] selectionArgs = new String[] { artist };\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, projection, selection, selectionArgs, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n albums.add(myCursor.getString(0));\n }\n\n myCursor.close();\n return albums;\n }\n\n /**\n * Returns the id ({@linkplain MediaStore.Audio.Media._ID}) of all the Songs of the specified Artist in the MediaStore.\n * \n * @param artist the name of the Artist ({@linkplain MediaStore.Audio.Artists.ARTIST})\n * @return list with the ids\n */\n public List<String> getSongsFromArtist(String artist) {\n List<String> ids = new ArrayList<String>();\n\n String[] projection = { MediaStore.Audio.Media._ID };\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \" + MediaStore.Audio.Artists.ARTIST + \" = ?\";\n String sortOrder = MediaStore.Audio.Media.TITLE;\n String[] selectionArgs = new String[] { artist };\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, projection, selection, selectionArgs, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n ids.add(myCursor.getString(0));\n }\n\n myCursor.close();\n return ids;\n }\n\n /**\n * Returns the id ({@linkplain MediaStore.Audio.Media._ID}) of all the Songs of the specified Album in the MediaStore.\n * \n * @param album the name of the Album ({@linkplain MediaStore.Audio.Albums.ALBUM})\n * @return list with the ids\n */\n public List<String> getSongsFromAlbum(String album) {\n List<String> ids = new ArrayList<String>();\n\n String[] projection = { MediaStore.Audio.Media._ID };\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \" + MediaStore.Audio.Artists.Albums.ALBUM + \" = ?\";\n String sortOrder = MediaStore.Audio.Media.TITLE;\n String[] selectionArgs = new String[] { album };\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, projection, selection, selectionArgs, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n ids.add(myCursor.getString(0));\n }\n\n myCursor.close();\n return ids;\n }\n\n /**\n * Returns a list of PlaylistEntries for all the Playlists in the MediaStore.\n * \n * @return a list of PlaylistEntries. The value associated is the name of the Playlist ({@linkplain MediaStore.Audio.Playlists.NAME})\n */\n public List<PlaylistEntry> getAllPlayLists() {\n List<PlaylistEntry> playLists = new ArrayList<PlaylistEntry>();\n\n String[] projection = new String[] { MediaStore.Audio.Playlists._ID, MediaStore.Audio.Playlists.NAME };\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, projection, null, null, null);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n playLists.add(new PlaylistEntry(myCursor.getString(0),\n myCursor.getString(1)));\n }\n\n Collections.sort(playLists);\n\n myCursor.close();\n return playLists;\n }\n\n /**\n * Returns the id ({@linkplain MediaStore.Audio.Playlists.Members.AUDIO_ID}) of all the Songs of the specified Playlist in the MediaStore.\n * \n * @param playListID ({@linkplain MediaStore.Audio.Playlists._ID})\n * @return list with the ids\n */\n public List<String> getSongsFromPlaylist(String playListID) {\n List<String> ids = new ArrayList<String>();\n\n Uri specialUri = MediaStore.Audio.Playlists.Members.getContentUri(\"external\", Integer.parseInt(playListID));\n String[] projection = { MediaStore.Audio.Playlists.Members.AUDIO_ID, MediaStore.Audio.Playlists.Members.TITLE };\n String sortOrder = MediaStore.Audio.Playlists.Members.TITLE;\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), specialUri, projection, null, null, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n ids.add(myCursor.getString(0));\n }\n\n myCursor.close();\n return ids;\n }\n\n public Song getSongFromID(String songID) {\n Song song;\n List<String> values = new ArrayList<String>();\n\n String[] projection = { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE,\n MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.DATA };\n\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \" + MediaStore.Audio.Media._ID + \" = ?\";\n String[] selectionArgs = new String[] { songID };\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, projection, selection, selectionArgs, null);\n myCursor = cl.loadInBackground();\n\n try {\n myCursor.moveToNext();\n for (int i = 0; i < myCursor.getColumnCount(); i++)\n values.add(myCursor.getString(i));\n if (values.size() > 0) {\n song = new Song(values.get(0), values.get(1), values.get(2), values.get(3), values.get(4));\n } else {\n song = new Song();\n }\n } catch (Exception ignored) {\n song = new Song();\n }\n\n myCursor.close();\n return song;\n }\n\n /**\n * Returns a list of SongEntries for the specified Songs.\n * \n * @param songsID list of ids ({@linkplain MediaStore.Audio.Media._ID})\n * @param projection one key from {@linkplain MediaStore.Audio.Media} to associate on the SongEntry's value\n * @return a list of SongEntries\n */\n public List<SongEntry> getValueFromSongs(List<String> songsID, String projection) {\n List<SongEntry> songs = new ArrayList<SongEntry>();\n\n String[] ids = new String[songsID.size()];\n ids = songsID.toArray(ids);\n\n String[] cursorProjection = new String[] { MediaStore.Audio.Media._ID, projection, MediaStore.Audio.Media.DATA };\n\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \" + MediaStore.Audio.Media._ID + \" IN (\";\n for (int i = 0; i < songsID.size() - 1; i++)\n {\n selection += \"?, \";\n }\n selection += \"?)\";\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, cursorProjection, selection, ids, null);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n songs.add(new SongEntry(myCursor.getString(0), myCursor.getString(1)));\n }\n\n Collections.sort(songs);\n\n myCursor.close();\n return songs;\n }\n\n /**\n * Returns the sub directories of a given directory\n * \n * @param directory the parent folder ({@linkplain File})\n * @return list with the subdirs\n */\n public List<File> getSubDirsInAFolder(File directory) {\n List<File> dirs = new ArrayList<File>();\n\n // list the directories inside the folder\n File list[] = directory.listFiles(myFilter);\n\n if (list != null) {\n\n Collections.addAll(dirs, list);\n\n // sort the directories alphabetically\n Collections.sort(dirs, new SortFileName());\n }\n return dirs;\n }\n\n /**\n * Returns a list of SongEntries for the Songs in the specified directory.\n * \n * @param directory the directory in which to search\n * @param projection one key from {@linkplain MediaStore.Audio.Media} to associate on the SongEntry's value\n * @return a list of SongEntries\n */\n public List<SongEntry> getSongsInAFolder(File directory, String projection) {\n List<SongEntry> songs = new ArrayList<SongEntry>();\n String folder = directory.getPath();\n\n String[] cursorProjection = new String[] { MediaStore.Audio.Media._ID, projection };\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \"\n + \"SUBSTR(\" + MediaStore.Audio.Media.DATA + \",0 , LENGTH('\" + folder + \"')+1) = '\" + folder + \"' AND \"\n + \"SUBSTR(\" + MediaStore.Audio.Media.DATA + \",LENGTH('\" + folder + \"')+1, 200) LIKE '/%.mp3' AND \"\n + \"SUBSTR(\" + MediaStore.Audio.Media.DATA + \",LENGTH('\" + folder + \"')+1, 200) NOT LIKE '/%/%.mp3'\";\n\n String sortOrder = MediaStore.Audio.Media.TITLE;\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cursorProjection, selection, null, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n songs.add(new SongEntry(myCursor.getString(0), myCursor.getString(1)));\n }\n\n CursorLoader cl2 = new CursorLoader(SoundBoxApplication.getContext(), MediaStore.Audio.Media.INTERNAL_CONTENT_URI, cursorProjection, selection, null, sortOrder);\n myCursor = cl2.loadInBackground();\n\n while (myCursor.moveToNext()) {\n songs.add(new SongEntry(myCursor.getString(0), myCursor.getString(1)));\n }\n\n myCursor.close();\n return songs;\n }\n\n /**\n * Class to sort the files based on its names (alphabetically)\n */\n private class SortFileName implements Comparator<File> {\n @Override\n public int compare(File f1, File f2) {\n return f1.getName().compareTo(f2.getName());\n }\n }\n\n /**\n * Class to filter the Files that are not directories.\n */\n private class OnlyDirsFilter implements FileFilter {\n\n @Override\n public boolean accept(File pathname) {\n return pathname.isDirectory() && !isProtected(pathname);\n }\n\n private boolean isProtected(File path) {\n return (!path.canRead() && !path.canWrite());\n }\n\n }\n}",
"public class BundleExtra {\n public final static String CURRENT_ID = \"currentid\";\n public final static String SONGS_ID_LIST = \"songsidlist\";\n\n public class DefaultValues {\n public final static String DEFAULT_ID = \"-1\";\n }\n\n public static String getBundleString(Bundle b, String key, String def) {\n String value = b.getString(key);\n if(value == null) {\n value = def;\n }\n return value;\n }\n}",
"public class SongEntry extends MediaEntry {\n\n public SongEntry(String id, String value) {\n super(id, value);\n }\n}",
"public class MediaPlayerService extends Service implements OnCompletionListener {\n\n private static final String TAG = \"MediaPlayerService\";\n public static final String INCOMMING_CALL = \"com.arcusapp.soundbox.action.MEDIA_PLAYER_SERVICE.INCOMMING_CALL\";\n public static final String PLAY_NEW_SONGS = \"com.arcusapp.soundbox.action.MEDIA_PLAYER_SERVICE.PLAY_NEW_SONGS\";\n public static final String CHANGE_FOREGROUND_STATE = \"com.arcusapp.soundbox.player.MEDIA_PLAYER_SERVICE.CHANGE_FOREGROUND_STATE\";\n public static final String NOW_IN_FOREGROUND = \"now_in_foreground\";\n\n /**\n * Possible actions that can be called from the MediaPlayerNotification\n */\n public static final String TOGGLEPLAYPAUSE_ACTION = \"com.arcusapp.soundbox.action.MEDIA_PLAYER_SERVICE.TOGGLEPLAYPAUSE\";\n public static final String PREVIOUS_ACTION = \"com.arcusapp.soundbox.player.MEDIA_PLAYER_SERVICE.PRVIOUS\";\n public static final String NEXT_ACTION = \"com.arcusapp.soundbox.player.MEDIA_PLAYER_SERVICE.NEXT\";\n public static final String STOP_ACTION = \"com.arcusapp.soundbox.player.MEDIA_PLAYER_SERVICE.STOP\";\n\n /**\n * Idle time before stopping the foreground notfication (1 minute)\n */\n private static final int IDLE_DELAY = 60000;\n\n private BroadcastReceiver headsetReceiver;\n\n // private int currentSongPosition;\n private SongStack currentSongStack;\n private List<String> songsIDList;\n\n private RepeatState repeatState = RepeatState.Off;\n private RandomState randomState = RandomState.Off;\n\n private MediaPlayer mediaPlayer;\n private List<MediaPlayerServiceListener> currentListeners;\n private final IBinder mBinder = new MyBinder();\n\n private boolean isOnForeground = false;\n MediaPlayerNotification mNotification;\n\n /**\n * Alarm intent for removing the notification when nothing is playing\n * for some time\n */\n private AlarmManager mAlarmManager;\n private PendingIntent mShutdownIntent;\n private boolean mShutdownScheduled;\n\n /**\n * Used to know when the service is active\n */\n private boolean mServiceInUse = false;\n\n /**\n * Used to know if something should be playing or not\n */\n private boolean mIsSupposedToBePlaying = false;\n\n private int mServiceStartId = -1;\n\n // Called every time a client starts the service using startService\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n mServiceStartId = startId;\n\n if(intent != null) {\n handleCommandIntent(intent);\n }\n\n // Make sure the service will shut down on its own if it was\n // just started but not bound to and nothing is playing\n if(!isPlaying()) {\n Log.d(this.getClass().getName(), \"scheduleDelayedShutdown from onStartCommand\");\n scheduleDelayedShutdown();\n }\n\n // We want this service to continue running until it is explicitly stopped, so return sticky.\n return Service.START_STICKY;\n }\n\n private void handleCommandIntent(Intent intent) {\n String action = intent.getAction();\n\n // Check if this is an intent from the AudioBecomingNoisyHandler\n if(INCOMMING_CALL.equals(action)) {\n if (mediaPlayer != null) {\n if(mediaPlayer.isPlaying()) {\n mediaPlayer.pause();\n mIsSupposedToBePlaying = false;\n Log.d(this.getClass().getName(), \"scheduleDelayedShutdown from INCOMMING_CALL\");\n scheduleDelayedShutdown();\n fireListenersOnMediaPlayerStateChanged();\n }\n }\n } // Check if we have a request to play new songs\n else if(PLAY_NEW_SONGS.equals(action)) {\n Bundle bundle = intent.getExtras();\n String currentID = BundleExtra.getBundleString(bundle, BundleExtra.CURRENT_ID, BundleExtra.DefaultValues.DEFAULT_ID);\n List<String> songsID = bundle.getStringArrayList(BundleExtra.SONGS_ID_LIST);\n\n loadSongs(songsID, currentID);\n mediaPlayer.start();\n mIsSupposedToBePlaying = true;\n Log.d(this.getClass().getName(), \"cancelShutdown from PLAY_NEW_SONGS\");\n cancelShutdown();\n } // Check if the foreground state needs to be changed\n else if (CHANGE_FOREGROUND_STATE.equals(action)) {\n boolean nowInForeground = intent.getBooleanExtra(NOW_IN_FOREGROUND, false);\n if(nowInForeground) {\n // check if we are playing. In case we are not, stop the service\n if(isPlaying()) {\n Song currentSong = getCurrentSong();\n Notification notification = mNotification.getNotification(currentSong.getArtist(), currentSong.getAlbum(), currentSong.getTitle(), mIsSupposedToBePlaying);\n startForeground(MediaPlayerNotification.MEDIA_PLAYER_NOTIFICATION_ID, notification);\n isOnForeground = true;\n } else {\n Log.d(this.getClass().getName(), \"scheduleDelayedShutdown from CHANGE_FOREGROUND_STATE\");\n scheduleDelayedShutdown();\n }\n } else {\n stopForeground(true);\n isOnForeground = false;\n }\n }\n\n //Check if there is an action from the MediaPlayerNotification\n if(isOnForeground) {\n if(TOGGLEPLAYPAUSE_ACTION.equals(action)) {\n playAndPause();\n } else if(NEXT_ACTION.equals(action)) {\n playNextSong();\n } else if(PREVIOUS_ACTION.equals(action)) {\n playPreviousSong();\n } else if(STOP_ACTION.equals(action)) {\n stopForeground(true);\n if (!mServiceInUse) {\n stopSelf(mServiceStartId);\n }\n }\n }\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n // Called when the Service object is instantiated. Theoretically, only once.\n if (mediaPlayer == null) {\n mediaPlayer = new MediaPlayer();\n mediaPlayer.setOnCompletionListener(this);\n }\n if(currentListeners == null) {\n currentListeners = new ArrayList<MediaPlayerServiceListener>();\n }\n if(mNotification == null){\n mNotification = new MediaPlayerNotification();\n }\n\n // Start up the thread running the service. Note that we create a\n // separate thread because the service normally runs in the process's\n // main thread, which we don't want to block. We also make it\n // background priority so CPU-intensive work will not disrupt the UI.\n final HandlerThread thread = new HandlerThread(\"MusicPlayerHandler\",\n android.os.Process.THREAD_PRIORITY_BACKGROUND);\n thread.start();\n\n FetchLastPlayedSongs();\n\n if(headsetReceiver == null) {\n headsetReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n // state - 0 for unplugged, 1 for plugged.\n int state = intent.getIntExtra(\"state\", 0);\n if(state == 0) {\n if (mediaPlayer != null) {\n if(mediaPlayer.isPlaying()) {\n mediaPlayer.pause();\n mIsSupposedToBePlaying = false;\n fireListenersOnMediaPlayerStateChanged();\n }\n }\n }\n }\n };\n registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));\n }\n\n // Initialize the delayed shutdown intent\n final Intent shutdownIntent = new Intent(this, MediaPlayerService.class);\n shutdownIntent.setAction(STOP_ACTION);\n\n mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);\n mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0);\n\n // Listen for the idle state\n Log.d(this.getClass().getName(), \"scheduleDelayedShutdown from onCreate\");\n scheduleDelayedShutdown();\n }\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n\n // remove any pending alarms\n mAlarmManager.cancel(mShutdownIntent);\n\n // Release the player\n if (mediaPlayer != null) {\n mediaPlayer.stop();\n mIsSupposedToBePlaying = false;\n mediaPlayer.release();\n mediaPlayer = null;\n }\n\n //Unregister headset listener\n if(headsetReceiver != null) {\n unregisterReceiver(headsetReceiver);\n }\n }\n\n @Override\n public IBinder onBind(Intent arg0) {\n Log.d(this.getClass().getName(), \"cancelShutdown from onBind\");\n cancelShutdown();\n mServiceInUse = true;\n return mBinder;\n }\n\n @Override\n public boolean onUnbind(Intent arg0) {\n mServiceInUse = false;\n\n if (mIsSupposedToBePlaying ) {\n // Something is currently playing, or will be playing once\n // an in-progress action requesting audio focus ends, so don't stop\n // the service now.\n return true;\n\n // If there is a playlist but playback is paused, then wait a while\n // before stopping the service.\n } else if (currentSongStack!= null && currentSongStack.getCurrentSongsIDList().size() > 0) {\n Log.d(this.getClass().getName(), \"scheduleDelayedShutdown from onUnbid\");\n scheduleDelayedShutdown();\n return true;\n }\n stopSelf(mServiceStartId);\n return true;\n }\n\n @Override\n public void onRebind(final Intent intent) {\n Log.d(this.getClass().getName(), \"cancelShutdown from onRebind\");\n cancelShutdown();\n mServiceInUse = true;\n }\n\n public class MyBinder extends Binder {\n public MediaPlayerService getService() {\n return MediaPlayerService.this;\n }\n }\n\n public void registerListener(MediaPlayerServiceListener listener) {\n if(listener == null || currentListeners == null){\n stopSelf();\n return;\n }\n\n if(!currentListeners.contains(listener) ) {\n currentListeners.add(listener);\n }\n }\n \n public void unRegisterListener(MediaPlayerServiceListener listener) {\n if(listener == null || currentListeners == null){\n stopSelf();\n return;\n }\n currentListeners.remove(listener);\n }\n\n private void FetchLastPlayedSongs() {\n List<String> songsID = SoundBoxPreferences.LastSongs.getLastSongs();\n String lastSong = SoundBoxPreferences.LastPlayedSong.getLastPlayedSong();\n\n loadSongs(songsID, lastSong);\n }\n\n public void loadSongs(List<String> songsID, String currentSongID) {\n if (songsID.isEmpty()) {\n Log.d(TAG, \"No songs to play\");\n return;\n }\n this.songsIDList = new ArrayList<String>();\n this.songsIDList.addAll(songsID);\n\n int currentSongPosition;\n if (currentSongID.equals(BundleExtra.DefaultValues.DEFAULT_ID)) {\n currentSongPosition = 0;\n } else {\n currentSongPosition = this.songsIDList.indexOf(currentSongID);\n if(currentSongPosition == -1) {\n Log.d(TAG, \"The first song to play is not in the loaded songs\");\n return;\n }\n }\n\n // create the song stack\n currentSongStack = new SongStack(currentSongPosition, this.songsIDList, randomState);\n\n prepareMediaPlayer();\n }\n\n public Song getCurrentSong() {\n if (currentSongStack != null) {\n return currentSongStack.getCurrentSong();\n } else {\n return null;\n }\n }\n\n public boolean isPlaying() {\n return mIsSupposedToBePlaying;\n }\n\n public RandomState getRandomState() {\n return currentSongStack.getCurrentRandomState();\n }\n\n public RepeatState getRepeatState() {\n return repeatState;\n }\n\n public RandomState changeRandomState() {\n if (randomState == RandomState.Off) {\n randomState = RandomState.Shuffled;\n }\n else if (randomState == RandomState.Shuffled) {\n randomState = RandomState.Random;\n }\n else if (randomState == RandomState.Random) {\n randomState = RandomState.Off;\n }\n currentSongStack.setRandomState(randomState);\n fireListenersOnMediaPlayerStateChanged();\n return randomState;\n }\n\n public RepeatState changeRepeatState() {\n if (repeatState == RepeatState.Off) {\n repeatState = RepeatState.All;\n }\n else if (repeatState == RepeatState.All) {\n repeatState = RepeatState.One;\n }\n else if (repeatState == RepeatState.One) {\n repeatState = RepeatState.Off;\n }\n fireListenersOnMediaPlayerStateChanged();\n return repeatState;\n }\n\n public void seekTo(int position) {\n mediaPlayer.seekTo(position);\n }\n\n public int getCurrentPosition() {\n return mediaPlayer.getCurrentPosition();\n }\n\n public int getDuration() {\n return mediaPlayer.getDuration();\n }\n\n public void playAndPause() {\n if (!mediaPlayer.isPlaying()) {\n mediaPlayer.start();\n mIsSupposedToBePlaying = true;\n Log.d(this.getClass().getName(), \"cancelShutdown from playAndPause\");\n cancelShutdown();\n }\n else {\n mediaPlayer.pause();\n mIsSupposedToBePlaying = false;\n Log.d(this.getClass().getName(), \"scheduleDelayedShutdown from playAndPause\");\n scheduleDelayedShutdown();\n }\n fireListenersOnMediaPlayerStateChanged();\n }\n\n public void playNextSong() {\n try {\n currentSongStack.moveStackForward();\n // check if we started the playlist again\n if (currentSongStack.getCurrentSong().getID().equals(currentSongStack.getCurrentSongsIDList().get(0))) {\n if (repeatState == RepeatState.Off) {\n // prepare the first song of the list, but do not play it.\n mediaPlayer.stop();\n Song currentSong = currentSongStack.getCurrentSong();\n mediaPlayer.reset();\n mediaPlayer.setDataSource(currentSong.getFile().getPath());\n mediaPlayer.prepare();\n Log.d(this.getClass().getName(), \"scheduleDelayedShutdown from playNextSong\");\n scheduleDelayedShutdown();\n mIsSupposedToBePlaying = false;\n fireListenersOnMediaPlayerStateChanged();\n\n } else {\n playCurrentSong();\n }\n } else {\n playCurrentSong();\n }\n } catch (Exception e) {\n fireListenersOnErrorRaised(e);\n }\n }\n\n public void playPreviousSong() {\n try {\n currentSongStack.moveStackBackward();\n playCurrentSong();\n } catch (Exception e) {\n fireListenersOnErrorRaised(e);\n }\n }\n\n public List<String> getSongsIDList() {\n if (currentSongStack.getCurrentRandomState() == RandomState.Random) {\n return songsIDList;\n } else {\n return currentSongStack.getCurrentSongsIDList();\n }\n }\n\n @Override\n public void onCompletion(MediaPlayer arg0) {\n try {\n if (repeatState == RepeatState.One) {\n playCurrentSong();\n } else {\n playNextSong();\n fireListenersOnMediaPlayerStateChanged();\n }\n }\n catch (Exception ex) {\n fireListenersOnErrorRaised(ex);\n }\n }\n\n private void playCurrentSong() {\n prepareMediaPlayer();\n mediaPlayer.start();\n mIsSupposedToBePlaying = true;\n Log.d(this.getClass().getName(), \"cancelShutdown from playCurrentSong\");\n cancelShutdown();\n fireListenersOnMediaPlayerStateChanged();\n }\n\n private void prepareMediaPlayer() {\n try {\n if (mediaPlayer.isPlaying()) {\n mediaPlayer.stop();\n }\n // play the song\n Song currentSong = currentSongStack.getCurrentSong();\n SoundBoxPreferences.LastPlayedSong.setLastPlayedSong(currentSong.getID());\n\n mediaPlayer.reset();\n mediaPlayer.setDataSource(currentSong.getFile().getPath());\n mediaPlayer.prepare();\n\n fireListenersOnMediaPlayerStateChanged();\n } catch (Exception e) {\n fireListenersOnErrorRaised(e);\n }\n }\n \n private void fireListenersOnMediaPlayerStateChanged() {\n if(currentListeners != null){\n for (MediaPlayerServiceListener listener : currentListeners) {\n listener.onMediaPlayerStateChanged();\n }\n }\n // if we are playing on foreground, update the notification\n if(isOnForeground) {\n Song currentSong = getCurrentSong();\n mNotification.updateNotification(currentSong.getArtist(), currentSong.getAlbum(), currentSong.getTitle(), mIsSupposedToBePlaying);\n }\n }\n\n private void fireListenersOnErrorRaised(Exception ex) {\n if(currentListeners == null){\n stopSelf();\n return;\n }\n for (MediaPlayerServiceListener listener : currentListeners) {\n listener.onExceptionRaised(ex); \n }\n if(isOnForeground) {\n stopForeground(true);\n }\n }\n\n private void scheduleDelayedShutdown() {\n mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,\n SystemClock.elapsedRealtime() + IDLE_DELAY, mShutdownIntent);\n mShutdownScheduled = true;\n }\n\n private void cancelShutdown() {\n if (mShutdownScheduled) {\n mAlarmManager.cancel(mShutdownIntent);\n mShutdownScheduled = false;\n }\n }\n}",
"public class MediaEntryHelper<T extends MediaEntry> {\n public List<String> getValues(List<T> list) {\n List<String> values = new ArrayList<String>();\n for (MediaEntry me : list) {\n values.add(me.getValue());\n }\n\n return values;\n }\n\n public List<String> getIDs(List<T> list) {\n List<String> ids = new ArrayList<String>();\n for (MediaEntry me : list) {\n ids.add(me.getID());\n }\n\n return ids;\n }\n}"
] | import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.arcusapp.soundbox.R;
import com.arcusapp.soundbox.SoundBoxApplication;
import com.arcusapp.soundbox.data.MediaProvider;
import com.arcusapp.soundbox.model.BundleExtra;
import com.arcusapp.soundbox.model.SongEntry;
import com.arcusapp.soundbox.player.MediaPlayerService;
import com.arcusapp.soundbox.util.MediaEntryHelper;
import java.util.ArrayList;
import java.util.List; | /*
* SoundBox - Android Music Player
* Copyright (C) 2013 Iván Arcuschin Moreno
*
* This file is part of SoundBox.
*
* SoundBox 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 2 of the License, or
* (at your option) any later version.
*
* SoundBox 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 SoundBox. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arcusapp.soundbox.adapter;
public class SongsListActivityAdapter extends BaseAdapter {
private Activity mActivity;
private List<SongEntry> songs;
private MediaProvider mediaProvider;
private MediaEntryHelper<SongEntry> mediaEntryHelper;
private String projection = MediaStore.Audio.Media.TITLE;
private String focusedID;
private boolean hasHeader;
public SongsListActivityAdapter(Activity activity, String focusedID, List<String> songsID, boolean hasHeader) {
mActivity = activity;
mediaProvider = new MediaProvider();
mediaEntryHelper = new MediaEntryHelper<SongEntry>();
this.hasHeader = hasHeader;
List<SongEntry> temp_songs = mediaProvider.getValueFromSongs(songsID, projection);
songs = new ArrayList<SongEntry>();
// order them by the order given on the songsID
for (int i = 0; i < songsID.size(); i++) {
for (int j = 0; j < temp_songs.size(); j++) {
if (temp_songs.get(j).getID().equals(songsID.get(i))) {
songs.add(temp_songs.get(j));
temp_songs.remove(j);
break;
}
}
}
this.focusedID = focusedID;
}
public void onSongClick(int position) {
//start the playActivity
Intent playActivityIntent = new Intent();
playActivityIntent.setAction(SoundBoxApplication.ACTION_MAIN_ACTIVITY);
playActivityIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
mActivity.startActivity(playActivityIntent);
//call the service to play new songs | Intent serviceIntent = new Intent(MediaPlayerService.PLAY_NEW_SONGS, null, SoundBoxApplication.getContext(), MediaPlayerService.class); | 4 |
superzanti/ServerSync | src/main/java/com/superzanti/serversync/client/Server.java | [
"@Command(name = \"ServerSync\", mixinStandardHelpOptions = true, version = RefStrings.VERSION, description = \"A utility for synchronizing a server<->client style game.\")\npublic class ServerSync implements Callable<Integer> {\n\n /* AWT EVENT DISPATCHER THREAD */\n\n public static final String APPLICATION_TITLE = \"Serversync\";\n public static final String GET_SERVER_INFO = \"SERVER_INFO\";\n public static EServerMode MODE;\n\n public static ResourceBundle strings;\n\n public static Path rootDir = Paths.get(System.getProperty(\"user.dir\"));\n\n @SuppressWarnings(\"FieldMayBeFinal\") // These have special behavior, final breaks it\n @Option(names = {\"-r\", \"--root\"}, description = \"The root directory of the game, defaults to the current working directory.\")\n private String rootDirectory = System.getProperty(\"user.dir\");\n @SuppressWarnings(\"FieldMayBeFinal\")\n @Option(names = {\"-o\", \"--progress\", \"progress-only\"}, description = \"Only show progress indication. Ignored if '-s', '--server' is specified.\")\n private boolean modeProgressOnly = false;\n @SuppressWarnings(\"FieldMayBeFinal\")\n @Option(names = {\"-q\", \"--quiet\", \"silent\"}, description = \"Remove all GUI interaction. Ignored if '-s', '--server' is specified.\")\n private boolean modeQuiet = false;\n @SuppressWarnings(\"FieldMayBeFinal\")\n @Option(names = {\"-s\", \"--server\", \"server\"}, description = \"Run the program in server mode.\")\n private boolean modeServer = false;\n @Option(names = {\"-a\", \"--address\"}, description = \"The address of the server you wish to connect to.\")\n private String serverAddress;\n @SuppressWarnings(\"FieldMayBeFinal\")\n @Option(names = {\"-p\", \"--port\"}, description = \"The port the server is running on.\")\n private int serverPort = -1;\n @Option(names = {\"-i\", \"--ignore\"}, arity = \"1..*\", description = \"A glob pattern or series of patterns for files to ignore\")\n private String[] ignorePatterns;\n @Option(names = {\"-l\", \"--lang\"}, description = \"A language code to set the UI language e.g. zh_CN or en_US\")\n private String languageCode;\n\n public static void main(String[] args) {\n int exitCode = new CommandLine(new ServerSync()).execute(args);\n if (exitCode != 0) {\n System.exit(exitCode);\n }\n }\n\n @Override\n public Integer call() {\n ServerSync.rootDir = Paths.get(rootDirectory);\n if (modeServer) {\n runInServerMode();\n } else {\n runInClientMode();\n }\n return 0;\n }\n\n private void commonInit() {\n Logger.log(String.format(\"Root dir: %s\", ServerSync.rootDir.toAbsolutePath()));\n Logger.log(String.format(\"Running version: %s\", RefStrings.VERSION));\n Locale locale = SyncConfig.getConfig().LOCALE;\n if (languageCode != null) {\n String[] lParts = languageCode.split(\"[_-]\");\n locale = new Locale(lParts[0], lParts[1]);\n SyncConfig.getConfig().LOCALE = locale;\n }\n if (serverAddress != null) {\n SyncConfig.getConfig().SERVER_IP = serverAddress;\n }\n if (serverPort > 0) {\n SyncConfig.getConfig().SERVER_PORT = serverPort;\n }\n if (ignorePatterns != null) {\n SyncConfig.getConfig().FILE_IGNORE_LIST = Arrays.stream(ignorePatterns).map(s -> s.replace(\"/\", File.separator).replace(\"\\\\\", File.separator)).collect(Collectors.toList());\n }\n\n try {\n Logger.log(\"Loading language file: \" + locale);\n strings = ResourceBundle.getBundle(\"assets.serversync.lang.MessagesBundle\", locale);\n } catch (MissingResourceException e) {\n Logger.log(\"No language file available for: \" + locale + \", defaulting to en_US\");\n strings = ResourceBundle.getBundle(\"assets.serversync.lang.MessagesBundle\", new Locale(\"en\", \"US\"));\n }\n }\n\n private Thread runInServerMode() {\n ServerSync.MODE = EServerMode.SERVER;\n try {\n ConfigLoader.load(EConfigType.SERVER);\n } catch (IOException e) {\n Logger.error(\"Failed to load server config\");\n Logger.debug(e);\n }\n commonInit();\n\n Thread serverThread = new ServerSetup();\n serverThread.start();\n return serverThread;\n }\n\n private void runInClientMode() {\n ServerSync.MODE = EServerMode.CLIENT;\n if(modeQuiet||modeProgressOnly){\n //Disable the consoleHandler to fix automation hanging\n Logger.setSystemOutput(false);\n }\n SyncConfig config = SyncConfig.getConfig();\n try {\n ConfigLoader.load(EConfigType.CLIENT);\n } catch (IOException e) {\n Logger.error(\"Failed to load client config\");\n e.printStackTrace();\n }\n commonInit();\n\n ClientWorker worker = new ClientWorker();\n if (modeQuiet) {\n try {\n worker.setAddress(SyncConfig.getConfig().SERVER_IP);\n worker.setPort(SyncConfig.getConfig().SERVER_PORT);\n worker.connect();\n Then.onComplete(worker.fetchActions(), actionEntries -> Then.onComplete(worker.executeActions(actionEntries, unused -> {\n }), unused -> {\n worker.close();\n System.exit(0);\n }));\n } catch (Exception e) {\n e.printStackTrace();\n System.exit(1);\n }\n } else if (modeProgressOnly) {\n // TODO setup a progress only version of the GUI?\n try {\n worker.setAddress(SyncConfig.getConfig().SERVER_IP);\n worker.setPort(SyncConfig.getConfig().SERVER_PORT);\n worker.connect();\n Then.onComplete(worker.fetchActions(), actionEntries -> Then.onComplete(worker.executeActions(actionEntries, actionProgress -> {\n if (actionProgress.isComplete()) {\n System.out.printf(\"Updated: %s%n\", actionProgress.entry);\n }\n }), unused -> {\n worker.close();\n System.exit(0);\n }));\n } catch (Exception e) {\n e.printStackTrace();\n System.exit(1);\n }\n } else {\n new GUI_Launcher().start();\n }\n }\n}",
"public class ServerInfo implements Serializable {\n public final List<String> messages;\n public final int syncMode;\n\n public ServerInfo(List<String> messages, int syncMode) {\n this.messages = messages;\n this.syncMode = syncMode;\n }\n}",
"public class AutoClose {\n\n @SafeVarargs\n public static <T extends Closeable> boolean closeResource(T... res) {\n //TODO keep an eye on this for issues\n int errors = 0;\n\n for (T t : res) {\n try {\n if (t != null) {\n if (t instanceof Socket) {\n if (((Socket) t).isClosed()) {\n t.close();\n }\n }\n\n t.close();\n }\n } catch (IOException e) {\n System.out.println(\"Failed to close resource\");\n e.printStackTrace();\n }\n }\n\n return true;\n }\n\n}",
"public class Logger {\n public static LoggerInstance instance = null;\n private static final Object mutex = new Object();\n private static Handler uiHandler;\n\n // Probably a heinous implementation of debounce but whatever\n private static final long dbTimeMS = 2000L;\n private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor();\n private static ScheduledFuture<?> waitingFlush;\n\n public static String getContext() {\n return ServerSync.MODE == null ? \"undefined\" : ServerSync.MODE.toString();\n }\n\n public static LoggerInstance getInstance() {\n LoggerInstance result = instance;\n if (result == null) {\n //synchronized block to remove overhead\n synchronized (mutex) {\n result = instance;\n if (result == null) {\n // if instance is null, initialize\n instance = result = new LoggerInstance(getContext());\n }\n }\n }\n return result;\n }\n\n public static void instantiate(String context) {\n instance = new LoggerInstance(context);\n }\n\n public static synchronized void setSystemOutput(boolean output) {\n // enable/disable System.out logging\n getInstance().javaLogger.setUseParentHandlers(output);\n }\n\n public static synchronized void log(String s) {\n getInstance().log(s);\n }\n\n public static synchronized void error(String s) {\n getInstance().error(s);\n }\n\n public static synchronized void debug(String s) {\n getInstance().debug(s);\n }\n\n public static synchronized void debug(Exception e) {\n getInstance().debug(Arrays.toString(e.getStackTrace()));\n }\n\n public static synchronized void outputError(Object object) {\n getInstance().debug(\"Failed to write object (\" + object + \") to output stream\");\n }\n\n public static synchronized void attachUIHandler(Handler handler) {\n if (uiHandler != null) {\n uiHandler.close();\n getInstance().javaLogger.removeHandler(uiHandler);\n }\n uiHandler = handler;\n getInstance().javaLogger.addHandler(uiHandler);\n }\n\n public static synchronized void flush() {\n if (uiHandler != null) {\n if (waitingFlush == null || waitingFlush.isDone()) {\n waitingFlush = dbRunner.schedule(() -> {\n uiHandler.flush();\n }, dbTimeMS, TimeUnit.MILLISECONDS);\n }\n }\n }\n}",
"public enum EServerMessage {\n SYNC_FILES(\"SYNC_FILES\"),\n GET_SERVER_INFO(\"GET_SERVER_INFO\"),\n GET_MANAGED_DIRECTORIES(\"GET_MANAGED_DIRECTORIES\"),\n GET_NUMBER_OF_MANAGED_FILES(\"GET_NUMBER_OF_MANAGED_FILES\"),\n GET_MANIFEST(\"GET_MANIFEST\"),\n UPDATE_FILE(\"UPDATE_FILE\"),\n EXIT(\"EXIT\");\n\n final String name;\n\n EServerMessage(String name) {\n this.name = name;\n }\n\n @Override\n public String toString() {\n return String.format(\"%d.EServerMessage.%s\", ordinal(), name);\n }\n}"
] | import com.superzanti.serversync.ServerSync;
import com.superzanti.serversync.communication.response.ServerInfo;
import com.superzanti.serversync.util.AutoClose;
import com.superzanti.serversync.util.Logger;
import com.superzanti.serversync.util.enums.EServerMessage;
import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException; | package com.superzanti.serversync.client;
public class Server {
public ObjectOutputStream output;
public ObjectInputStream input;
public Socket clientSocket;
public ServerInfo info;
public OutputStream os;
public InputStream is;
protected final String address;
protected final int port;
Server(String address, int port) {
this.address = address;
this.port = port;
}
public static Server forClient(Client client) {
return new Server(client.serverAddress, client.serverPort);
}
public boolean connect() {
InetAddress host;
try {
host = InetAddress.getByName(address);
} catch (UnknownHostException e) {
Logger.error(ServerSync.strings.getString("connection_failed_host") + ": " + address);
return false;
}
Logger.debug(ServerSync.strings.getString("connection_attempt_server"));
clientSocket = new Socket();
Logger.log("< " + ServerSync.strings.getString("connection_message") + " >");
try {
clientSocket.setPerformancePreferences(0, 1, 2);
clientSocket.connect(new InetSocketAddress(host.getHostName(), port), 5000);
} catch (IOException e) {
Logger.error(ServerSync.strings.getString("connection_failed_server") + ": " + address + ":" + port);
AutoClose.closeResource(clientSocket);
return false;
}
Logger.debug(ServerSync.strings.getString("debug_IO_streams"));
try {
os = clientSocket.getOutputStream();
is = clientSocket.getInputStream();
output = new ObjectOutputStream(os);
input = new ObjectInputStream(is);
} catch (IOException e) {
Logger.debug(ServerSync.strings.getString("debug_IO_streams_failed"));
AutoClose.closeResource(clientSocket);
return false;
}
try {
output.writeUTF(ServerSync.GET_SERVER_INFO);
output.flush();
} catch (IOException e) {
Logger.outputError(ServerSync.GET_SERVER_INFO);
}
try {
info = (ServerInfo) input.readObject();
} catch (IOException | ClassNotFoundException e) {
Logger.error("Failed to read server information");
Logger.debug(e);
}
return true;
}
public void close() {
try {
// Output could be null if the server has never connected, i.e. the client used the wrong details
if (output != null) { | output.writeUTF(EServerMessage.EXIT.toString()); | 4 |
rapidpro/surveyor | app/src/main/java/io/rapidpro/surveyor/activity/OrgChooseActivity.java | [
"public class Logger {\n\n private static final String TAG = \"Surveyor\";\n\n public static void e(String message, Throwable t) {\n Log.e(TAG, message, t);\n }\n\n public static void w(String message) {\n Log.w(TAG, message);\n }\n\n public static void d(String message) {\n Log.d(TAG, message);\n }\n}",
"public class SurveyorApplication extends Application {\n\n /**\n * The singleton instance of this application\n */\n private static SurveyorApplication s_this;\n\n /**\n * Service for network operations\n */\n private TembaService tembaService = null;\n\n /**\n * Service for local org operations\n */\n private OrgService orgService = null;\n\n /**\n * Service for local submission operations\n */\n private SubmissionService submissionService = null;\n\n /**\n * Gets the singleton instance of this application\n *\n * @return the instance\n */\n public static SurveyorApplication get() {\n return s_this;\n }\n\n @Override\n public void onCreate() {\n Logger.d(\"Creating Surveyor application...\");\n\n super.onCreate();\n\n Logger.d(\"External storage dir=\" + Environment.getExternalStorageDirectory() + \" state=\" + Environment.getExternalStorageState() + \" emulated=\" + Environment.isExternalStorageEmulated());\n\n s_this = this;\n\n tembaService = new TembaService(getTembaHost());\n\n try {\n orgService = new OrgService(getOrgsDirectory());\n submissionService = new SubmissionService(getSubmissionsDirectory());\n } catch (IOException e) {\n Logger.e(\"Unable to create directory based services\", e);\n }\n }\n\n /**\n * Gets the name of the preferences file\n *\n * @return the name of the preferences\n */\n public String getPreferencesName() {\n return \"default\";\n }\n\n /**\n * Gets the shared preferences for this application\n *\n * @return the preferences\n */\n public SharedPreferences getPreferences() {\n return s_this.getSharedPreferences(getPreferencesName(), Context.MODE_PRIVATE);\n }\n\n /**\n * Saves a string shared preference for this application\n *\n * @param key the preference key\n * @param value the preference value\n */\n public void setPreference(String key, String value) {\n getPreferences().edit().putString(key, value).apply();\n }\n\n /**\n * Saves a string-set shared preference for this application\n *\n * @param key the preference key\n * @param values the preference value\n */\n public void setPreference(String key, Set<String> values) {\n getPreferences().edit().putStringSet(key, values).apply();\n }\n\n /**\n * Clears a shared preference for this application\n *\n * @param key the preference key\n */\n public void clearPreference(String key) {\n getPreferences().edit().remove(key).apply();\n }\n\n /**\n * Gets the base URL of the Temba instance we're connected to\n *\n * @return the base URL\n */\n public String getTembaHost() {\n String host = getPreferences().getString(SurveyorPreferences.HOST, getString(R.string.pref_default_host));\n\n // strip any trailing slash\n if (host.endsWith(\"/\")) {\n host = host.substring(0, host.length() - 1);\n }\n\n return host;\n }\n\n /**\n * Called when our host setting has changed\n */\n public void onTembaHostChanged() {\n String newHost = getTembaHost();\n\n Logger.d(\"Host changed to \" + newHost);\n\n clearPreference(SurveyorPreferences.AUTH_USERNAME);\n clearPreference(SurveyorPreferences.AUTH_ORGS);\n try {\n getSubmissionService().clearAll();\n } catch (IOException e) {\n Logger.e(\"Unable to clear submissions\", e);\n }\n\n tembaService = new TembaService(newHost);\n }\n\n /**\n * Returns the Temba API service\n *\n * @return the service\n */\n public TembaService getTembaService() {\n return tembaService;\n }\n\n /**\n * Returns the local orgs service\n *\n * @return the service\n */\n public OrgService getOrgService() {\n return orgService;\n }\n\n /**\n * Returns the local submissions service\n *\n * @return the service\n */\n public SubmissionService getSubmissionService() {\n return submissionService;\n }\n\n /**\n * Gets the directory for org configurations\n *\n * @return the directory\n */\n public File getOrgsDirectory() throws IOException {\n return SurveyUtils.mkdir(getFilesDir(), \"orgs\");\n }\n\n /**\n * Gets the directory for user collected data\n *\n * @return the directory\n */\n public File getUserDirectory() {\n return getExternalFilesDir(null);\n }\n\n /**\n * Gets the submissions storage directory\n *\n * @return the directory\n */\n protected File getSubmissionsDirectory() throws IOException {\n return SurveyUtils.mkdir(getUserDirectory(), \"submissions\");\n }\n\n /**\n * Gets the URI for the given file using our application's file provider\n *\n * @param file the file\n * @return the URI\n */\n public Uri getUriForFile(File file) {\n return FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + \".provider\", file);\n }\n\n /**\n * Generate dump of the Android log\n *\n * @return the URI of the dump file\n */\n public Uri generateLogDump() throws IOException {\n // log our build and device details\n Logger.d(\"Version: \" + BuildConfig.VERSION_NAME + \"; \" + BuildConfig.VERSION_CODE);\n Logger.d(\"OS: \" + System.getProperty(\"os.version\") + \" (API \" + Build.VERSION.SDK_INT + \")\");\n Logger.d(\"Model: \" + android.os.Build.MODEL + \" (\" + android.os.Build.DEVICE + \")\");\n\n // dump log to file and return URI\n File outputFile = new File(getUserDirectory(), \"bug-report.txt\");\n Runtime.getRuntime().exec(\"logcat -d -f \" + outputFile.getAbsolutePath() + \" \\\"Surveyor:* *:E\\\"\");\n return getUriForFile(outputFile);\n }\n}",
"public interface SurveyorIntent {\n String EXTRA_ORG_UUID = \"surveyor.extra.org_uuid\";\n String EXTRA_FLOW_UUID = \"surveyor.extra.flow_uuid\";\n\n String EXTRA_SUBMISSION_FILE = \"surveyor.extra.submission_file\";\n\n // where media files are to be stored\n String EXTRA_MEDIA_FILE = \"surveyor.extra.media_file\";\n\n String EXTRA_ERROR = \"surveyor.extra.error\";\n String EXTRA_CAMERA_DIRECTION = \"surveyor.extra.camera_direction\";\n}",
"public interface SurveyorPreferences {\n /**\n * Host we are connected to\n */\n String HOST = \"host\";\n\n /**\n * Username/email we are logged in as. If this is set, we are logged in\n */\n String AUTH_USERNAME = \"auth_username\";\n\n /**\n * Username/email we were previously logged in as - used to prepopulate login form\n */\n String PREV_USERNAME = \"prev_username\";\n\n /**\n * UUIDs of the orgs this user has access to\n */\n String AUTH_ORGS = \"auth_orgs\";\n}",
"public class Org {\n /**\n * Contains the JSON representation of this org\n */\n private static final String DETAILS_FILE = \"details.json\";\n\n /**\n * Contains a goflow assets file with this org's flows, groups, fields etc\n */\n private static final String ASSETS_FILE = \"assets.json\";\n\n /**\n * Contains summaries of each flow available in this org\n */\n private static final String FLOWS_FILE = \"flows.json\";\n\n private String token;\n\n private String name;\n\n @SerializedName(\"primary_language\")\n private String primaryLanguage;\n\n private String[] languages;\n\n private String timezone;\n\n private String country;\n\n @SerializedName(\"date_style\")\n private String dateStyle;\n\n private boolean anon;\n\n private String legacySubmissionsDirectory;\n\n private transient File directory;\n\n private transient List<Flow> flows;\n\n /**\n * Creates an new empty org\n *\n * @param directory the directory\n * @param token the API token\n * @return the org\n */\n public static Org create(File directory, String name, String token) throws IOException {\n directory.mkdirs();\n\n Org org = new Org();\n org.name = name;\n org.token = token;\n org.directory = directory;\n org.flows = new ArrayList<>();\n org.legacySubmissionsDirectory = null;\n\n FileUtils.writeStringToFile(new File(directory, DETAILS_FILE), \"{\\\"name\\\":\\\"\" + name + \"\\\",\\\"token\\\":\\\"\" + token + \"\\\"}\");\n FileUtils.writeStringToFile(new File(directory, FLOWS_FILE), \"[]\");\n return org;\n }\n\n /**\n * Loads an org from a directory\n *\n * @param directory the directory\n * @return the org\n */\n static Org load(File directory) throws IOException {\n if (!directory.exists() || !directory.isDirectory()) {\n throw new RuntimeException(directory.getPath() + \" is not a valid org directory\");\n }\n\n // read details.json\n String detailsJSON = FileUtils.readFileToString(new File(directory, DETAILS_FILE));\n Org org = JsonUtils.unmarshal(detailsJSON, Org.class);\n org.directory = directory;\n\n // read flows.json\n String flowsJson = FileUtils.readFileToString(new File(directory, FLOWS_FILE));\n\n TypeToken type = new TypeToken<List<Flow>>() {\n };\n org.flows = JsonUtils.unmarshal(flowsJson, type);\n return org;\n }\n\n /**\n * Gets the UUID of this org (i.e. the name of its directory)\n *\n * @return the UUID\n */\n public String getUuid() {\n return directory.getName();\n }\n\n /**\n * Gets the directory of this org\n *\n * @return the directory\n */\n public File getDirectory() {\n return directory;\n }\n\n /**\n * Gets the API token for this org\n *\n * @return the API token\n */\n public String getToken() {\n return token;\n }\n\n /**\n * Gets the name of this org\n *\n * @return the name\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets the country code of this org\n *\n * @return the country code\n */\n public String getCountry() {\n return country;\n }\n\n public String[] getLanguages() {\n return languages;\n }\n\n public String getTimezone() {\n return timezone;\n }\n\n public String getDateStyle() {\n return dateStyle;\n }\n\n public boolean isAnon() {\n return anon;\n }\n\n /**\n * Gets the directory of legacy submissions for this org (may be null)\n *\n * @return the directory\n */\n public String getLegacySubmissionsDirectory() {\n return legacySubmissionsDirectory;\n }\n\n public void setLegacySubmissionsDirectory(String legacySubmissionsDirectory) {\n this.legacySubmissionsDirectory = legacySubmissionsDirectory;\n }\n\n public List<Flow> getFlows() {\n return flows;\n }\n\n /**\n * Gets the flow with the given UUID\n *\n * @param uuid the flow UUID\n * @return the flow or null if no such flow exists\n */\n public Flow getFlow(String uuid) {\n for (Flow flow : flows) {\n if (flow.getUuid().equals(uuid)) {\n return flow;\n }\n }\n return null;\n }\n\n /**\n * Gets whether this org has downloaded assets\n *\n * @return true if org has assets\n */\n public boolean hasAssets() {\n return new File(directory, ASSETS_FILE).exists();\n }\n\n /**\n * Gets this org's downloaded assets\n *\n * @return the assets JSON\n */\n public String getAssets() throws IOException {\n return FileUtils.readFileToString(new File(directory, ASSETS_FILE));\n }\n\n /**\n * Refreshes this org from RapidPro\n */\n public void refresh(boolean includeAssets, RefreshProgress progress) throws TembaException, IOException {\n TembaService svc = SurveyorApplication.get().getTembaService();\n io.rapidpro.surveyor.net.responses.Org apiOrg = svc.getOrg(this.token);\n\n this.name = apiOrg.getName();\n this.languages = apiOrg.getLanguages();\n this.timezone = apiOrg.getTimezone();\n this.country = apiOrg.getCountry();\n this.dateStyle = apiOrg.getDateStyle();\n this.anon = apiOrg.isAnon();\n this.save();\n\n if (progress != null) {\n progress.reportProgress(10);\n }\n\n if (includeAssets) {\n refreshAssets(progress);\n }\n }\n\n public void save() throws IOException {\n // (re)write org fields to details.json\n String detailsJSON = JsonUtils.marshal(this);\n FileUtils.writeStringToFile(new File(directory, DETAILS_FILE), detailsJSON);\n }\n\n private void refreshAssets(RefreshProgress progress) throws TembaException, IOException {\n List<Field> fields = SurveyorApplication.get().getTembaService().getFields(getToken());\n\n progress.reportProgress(20);\n\n List<Group> groups = SurveyorApplication.get().getTembaService().getGroups(getToken());\n\n progress.reportProgress(30);\n\n List<io.rapidpro.surveyor.net.responses.Flow> flows = SurveyorApplication.get().getTembaService().getFlows(getToken());\n\n progress.reportProgress(40);\n\n List<RawJson> definitions = SurveyorApplication.get().getTembaService().getDefinitions(getToken(), flows);\n\n progress.reportProgress(60);\n\n List<Boundary> boundaries = SurveyorApplication.get().getTembaService().getBoundaries(getToken());\n\n progress.reportProgress(70);\n\n OrgAssets assets = OrgAssets.fromTemba(fields, groups, boundaries, definitions);\n String assetsJSON = JsonUtils.marshal(assets);\n\n FileUtils.writeStringToFile(new File(directory, ASSETS_FILE), assetsJSON);\n\n progress.reportProgress(80);\n\n // update the flow summaries\n this.flows.clear();\n this.flows.addAll(assets.getFlows());\n\n // and write that to flows.json as well\n String summariesJSON = JsonUtils.marshal(this.flows);\n FileUtils.writeStringToFile(new File(directory, FLOWS_FILE), summariesJSON);\n\n progress.reportProgress(100);\n\n Logger.d(\"Refreshed assets for org \" + getUuid() + \" (flows=\" + flows.size() + \", fields=\" + fields.size() + \", groups=\" + groups.size() + \")\");\n }\n\n public interface RefreshProgress {\n void reportProgress(int percent);\n }\n}",
"public class OrgListFragment extends Fragment implements AbsListView.OnItemClickListener {\n\n private Container container;\n private ListAdapter adapter;\n\n public OrgListFragment() {\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n List<Org> items = container.getListItems();\n\n adapter = new OrgListAdapter(getActivity(), R.layout.item_org, items);\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(R.layout.fragment_list, container, false);\n ListView m_listView = view.findViewById(android.R.id.list);\n m_listView.setAdapter(adapter);\n m_listView.setOnItemClickListener(this);\n return view;\n }\n\n @Override\n public void onAttach(Activity activity) {\n super.onAttach(activity);\n try {\n container = (Container) activity;\n } catch (ClassCastException e) {\n throw new ClassCastException(activity.toString() + \" must implement OrgListFragment.Container\");\n }\n }\n\n @Override\n public void onDetach() {\n super.onDetach();\n container = null;\n }\n\n @Override\n public void onItemClick(AdapterView<?> parent, View view, int position, long id) {\n container.onItemClick((Org) adapter.getItem(position));\n }\n\n /**\n * Container activity should implement this to be notified when an org is clicked\n */\n public interface Container {\n List<Org> getListItems();\n\n void onItemClick(Org org);\n }\n}"
] | import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import io.rapidpro.surveyor.Logger;
import io.rapidpro.surveyor.R;
import io.rapidpro.surveyor.SurveyorApplication;
import io.rapidpro.surveyor.SurveyorIntent;
import io.rapidpro.surveyor.SurveyorPreferences;
import io.rapidpro.surveyor.data.Org;
import io.rapidpro.surveyor.fragment.OrgListFragment; | package io.rapidpro.surveyor.activity;
/**
* Let's the user select one of the orgs they have access to
*/
public class OrgChooseActivity extends BaseActivity implements OrgListFragment.Container {
private List<Org> getOrgs() { | Set<String> orgUUIDs = SurveyorApplication.get().getPreferences().getStringSet(SurveyorPreferences.AUTH_ORGS, Collections.<String>emptySet()); | 1 |
CvvT/DexTamper | src/org/jf/dexlib2/immutable/ImmutableClassDef.java | [
"public interface Annotation extends BasicAnnotation, Comparable<Annotation> {\n /**\n * Gets the visibility of this annotation.\n *\n * This will be one of the AnnotationVisibility.* constants.\n *\n * @return The visibility of this annotation\n */\n int getVisibility();\n\n /**\n * Gets the type of this annotation.\n *\n * This will be the type descriptor of the class that defines this annotation.\n *\n * @return The type of this annotation\n */\n @Nonnull @Override String getType();\n\n /**\n * Gets a set of the name/value elements associated with this annotation.\n *\n * The elements in the returned set will be unique with respect to the element name.\n *\n * @return A set of AnnotationElements\n */\n @Nonnull @Override Set<? extends AnnotationElement> getElements();\n\n /**\n * Returns a hashcode for this Annotation.\n *\n * This hashCode is defined to be the following:\n *\n * <pre>\n * {@code\n * int hashCode = getVisibility();\n * hashCode = hashCode*31 + getType().hashCode();\n * hashCode = hashCode*31 + getElements().hashCode();\n * }</pre>\n *\n * @return The hash code value for this Annotation\n */\n @Override int hashCode();\n\n /**\n * Compares this Annotation to another Annotation for equality.\n *\n * This Annotation is equal to another Annotation if all of it's \"fields\" are equal. That is, if the return values\n * of getVisibility(), getType(), and getElements() are all equal.\n *\n * @param o The object to be compared for equality with this Annotation\n * @return true if the specified object is equal to this Annotation\n */\n @Override boolean equals(@Nullable Object o);\n\n /**\n * Compares this Annotation to another Annotation.\n *\n * The comparison is based on the value of getVisibility(), getType() and getElements(), in that order. When\n * comparing the set of elements, the comparison is done with the semantics of\n * org.jf.util.CollectionUtils.compareAsSet(), using the natural ordering of AnnotationElement.\n *\n * @param o The Annotation to compare with this Annotation\n * @return An integer representing the result of the comparison\n */\n @Override int compareTo(Annotation o);\n}",
"public interface ClassDef extends TypeReference, Annotatable {\n /**\n * Gets the class type.\n *\n * This will be a type descriptor per the dex file specification.\n *\n * @return The class type\n */\n @Override @Nonnull String getType();\n\n /**\n * Gets the access flags for this class.\n *\n * This will be a combination of the AccessFlags.* flags that are marked as compatible for use with a class.\n *\n * @return The access flags for this class\n */\n int getAccessFlags();\n\n /**\n * Gets the superclass of this class.\n *\n * This will only be null if this is the base java.lang.Object class.\n *\n * @return The superclass of this class\n */\n @Nullable String getSuperclass();\n\n /**\n * Gets a list of the interfaces that this class implements.\n *\n * @return A list of the interfaces that this class implements\n */\n @Nonnull List<String> getInterfaces();\n\n /**\n * Gets the name of the primary source file that this class is defined in, if available.\n *\n * This will be the default source file associated with all methods defined in this class. This can be overridden\n * for sections of an individual method with the SetSourceFile debug item.\n *\n * @return The name of the primary source file for this class, or null if not available\n */\n @Nullable String getSourceFile();\n\n /**\n * Gets a set of the annotations that are applied to this class.\n *\n * The annotations in the returned set are guaranteed to have unique types.\n *\n * @return A set of the annotations that are applied to this class\n */\n @Override @Nonnull Set<? extends Annotation> getAnnotations();\n\n /**\n * Gets the static fields that are defined by this class.\n *\n * The static fields that are returned must have no duplicates.\n *\n * @return The static fields that are defined by this class\n */\n @Nonnull Iterable<? extends Field> getStaticFields();\n\n /**\n * Gets the instance fields that are defined by this class.\n *\n * The instance fields that are returned must have no duplicates.\n *\n * @return The instance fields that are defined by this class\n */\n @Nonnull Iterable<? extends Field> getInstanceFields();\n\n /**\n * Gets all the fields that are defined by this class.\n *\n * This is a convenience method that combines getStaticFields() and getInstanceFields()\n *\n * The returned fields may be in any order. I.e. It's not safe to assume that all instance fields will come after\n * all static fields.\n *\n * Note that there typically should not be any duplicate fields between the two, but some versions of\n * dalvik inadvertently allow duplicate static/instance fields, and are supported here for completeness\n *\n * @return A set of the fields that are defined by this class\n */\n @Nonnull Iterable<? extends Field> getFields();\n\n /**\n * Gets the direct methods that are defined by this class.\n *\n * The direct methods that are returned must have no duplicates.\n *\n * @return The direct methods that are defined by this class.\n */\n @Nonnull Iterable<? extends Method> getDirectMethods();\n\n /**\n * Gets the virtual methods that are defined by this class.\n *\n * The virtual methods that are returned must have no duplicates.\n *\n * @return The virtual methods that are defined by this class.\n */\n @Nonnull Iterable<? extends Method> getVirtualMethods();\n\n /**\n * Gets all the methods that are defined by this class.\n *\n * This is a convenience method that combines getDirectMethods() and getVirtualMethods().\n *\n * The returned methods may be in any order. I.e. It's not safe to assume that all virtual methods will come after\n * all direct methods.\n *\n * Note that there typically should not be any duplicate methods between the two, but some versions of\n * dalvik inadvertently allow duplicate direct/virtual methods, and are supported here for completeness\n *\n * @return An iterable of the methods that are defined by this class.\n */\n @Nonnull Iterable<? extends Method> getMethods();\n}",
"public interface Field extends FieldReference, Member {\n /**\n * Gets the type of the class that defines this field.\n *\n * @return The type of the class that defines this field\n */\n @Override @Nonnull String getDefiningClass();\n\n /**\n * Gets the name of this field.\n *\n * @return The name of this field\n */\n @Override @Nonnull String getName();\n\n /**\n * Gets the type of this field.\n *\n * @return The type of this field\n */\n @Override @Nonnull String getType();\n\n /**\n * Gets the access flags for this field.\n *\n * This will be a combination of the AccessFlags.* flags that are marked as compatible for use with a field.\n *\n * @return The access flags for this field\n */\n @Override int getAccessFlags();\n\n /**\n * Gets the initial value for this field, if available.\n *\n * Only static field may have an initial value set, but are not required to have an initial value.\n *\n * @return The initial value for this field, or null if this field is not a static field, or if this static field\n * does not have an initial value.\n */\n @Nullable EncodedValue getInitialValue();\n\n /**\n * Gets a set of the annotations that are applied to this field.\n *\n * The annotations in the returned set are guaranteed to have unique types.\n *\n * @return A set of the annotations that are applied to this field\n */\n @Override @Nonnull Set<? extends Annotation> getAnnotations();\n}",
"public interface Method extends MethodReference, Member {\n /**\n * Gets the type of the class that defines this method.\n *\n * @return The type of the class that defines this method\n */\n @Override @Nonnull String getDefiningClass();\n\n /**\n * Gets the name of this method.\n *\n * @return The name of this method\n */\n @Override @Nonnull String getName();\n\n /**\n * Gets a list of the parameters of this method.\n *\n * As per the MethodReference interface, the MethodParameter objects contained in the returned list also act\n * as a simple reference to the type of the parameter. However, the MethodParameter object can also contain\n * additional information about the parameter.\n *\n * Note: In some implementations, the returned list is likely to *not* provide efficient random access.\n *\n * @return A list of MethodParameter objects, representing the parameters of this method.\n */\n @Nonnull List<? extends MethodParameter> getParameters();\n\n /**\n * Gets the return type of this method.\n *\n * @return The return type of this method.\n */\n @Override @Nonnull String getReturnType();\n\n /**\n * Gets the access flags for this method.\n *\n * This will be a combination of the AccessFlags.* flags that are marked as compatible for use with a method.\n *\n * @return The access flags for this method\n */\n @Override int getAccessFlags();\n\n /**\n * Gets a set of the annotations that are applied to this method.\n *\n * The annotations in the returned set are guaranteed to have unique types.\n *\n * @return A set of the annotations that are applied to this method\n */\n @Override @Nonnull Set<? extends Annotation> getAnnotations();\n\n /**\n * Gets a MethodImplementation object that defines the implementation of the method.\n *\n * If this is an abstract method in an abstract class, or an interface method in an interface definition, then the\n * method has no implementation, and this will return null.\n *\n * @return A MethodImplementation object defining the implementation of this method, or null if the method has no\n * implementation\n */\n @Nullable MethodImplementation getImplementation();\n}",
"public final class MethodUtil {\n private static int directMask = AccessFlags.STATIC.getValue() | AccessFlags.PRIVATE.getValue() |\n AccessFlags.CONSTRUCTOR.getValue();\n\n public static Predicate<Method> METHOD_IS_DIRECT = new Predicate<Method>() {\n @Override public boolean apply(@Nullable Method input) {\n return input != null && isDirect(input);\n }\n };\n\n public static Predicate<Method> METHOD_IS_VIRTUAL = new Predicate<Method>() {\n @Override public boolean apply(@Nullable Method input) {\n return input != null && !isDirect(input);\n }\n };\n\n public static boolean isDirect(@Nonnull Method method) {\n return (method.getAccessFlags() & directMask) != 0;\n }\n\n public static boolean isStatic(@Nonnull Method method) {\n return AccessFlags.STATIC.isSet(method.getAccessFlags());\n }\n\n public static boolean isConstructor(@Nonnull MethodReference methodReference) {\n return methodReference.getName().equals(\"<init>\");\n }\n\n public static boolean isPackagePrivate(@Nonnull Method method) {\n return (method.getAccessFlags() & (AccessFlags.PRIVATE.getValue() |\n AccessFlags.PROTECTED.getValue() |\n AccessFlags.PUBLIC.getValue())) == 0;\n }\n\n public static int getParameterRegisterCount(@Nonnull Method method) {\n return getParameterRegisterCount(method, MethodUtil.isStatic(method));\n }\n\n public static int getParameterRegisterCount(@Nonnull MethodReference methodRef, boolean isStatic) {\n return getParameterRegisterCount(methodRef.getParameterTypes(), isStatic);\n }\n\n public static int getParameterRegisterCount(@Nonnull Collection<? extends CharSequence> parameterTypes,\n boolean isStatic) {\n int regCount = 0;\n for (CharSequence paramType: parameterTypes) {\n int firstChar = paramType.charAt(0);\n if (firstChar == 'J' || firstChar == 'D') {\n regCount += 2;\n } else {\n regCount++;\n }\n }\n if (!isStatic) {\n regCount++;\n }\n return regCount;\n }\n\n private static char getShortyType(CharSequence type) {\n if (type.length() > 1) {\n return 'L';\n }\n return type.charAt(0);\n }\n\n public static String getShorty(Collection<? extends CharSequence> params, String returnType) {\n StringBuilder sb = new StringBuilder(params.size() + 1);\n sb.append(getShortyType(returnType));\n for (CharSequence typeRef: params) {\n sb.append(getShortyType(typeRef));\n }\n return sb.toString();\n }\n\n public static boolean methodSignaturesMatch(@Nonnull MethodReference a, @Nonnull MethodReference b) {\n return (a.getName().equals(b.getName()) &&\n a.getReturnType().equals(b.getReturnType()) &&\n CharSequenceUtils.listEquals(a.getParameterTypes(), b.getParameterTypes()));\n }\n\n private MethodUtil() {}\n}"
] | import com.google.common.collect.*;
import org.jf.dexlib2.base.reference.BaseTypeReference;
import org.jf.dexlib2.iface.Annotation;
import org.jf.dexlib2.iface.ClassDef;
import org.jf.dexlib2.iface.Field;
import org.jf.dexlib2.iface.Method;
import org.jf.dexlib2.util.FieldUtil;
import org.jf.dexlib2.util.MethodUtil;
import org.jf.util.ImmutableConverter;
import org.jf.util.ImmutableUtils;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import java.util.List; | /*
* Copyright 2012, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.immutable;
public class ImmutableClassDef extends BaseTypeReference implements ClassDef {
@Nonnull protected final String type;
protected final int accessFlags;
@Nullable protected final String superclass;
@Nonnull protected final ImmutableList<String> interfaces;
@Nullable protected final String sourceFile;
@Nonnull protected final ImmutableSet<? extends ImmutableAnnotation> annotations;
@Nonnull protected final ImmutableSortedSet<? extends ImmutableField> staticFields;
@Nonnull protected final ImmutableSortedSet<? extends ImmutableField> instanceFields;
@Nonnull protected final ImmutableSortedSet<? extends ImmutableMethod> directMethods;
@Nonnull protected final ImmutableSortedSet<? extends ImmutableMethod> virtualMethods;
public ImmutableClassDef(@Nonnull String type,
int accessFlags,
@Nullable String superclass,
@Nullable Collection<String> interfaces,
@Nullable String sourceFile,
@Nullable Collection<? extends Annotation> annotations,
@Nullable Iterable<? extends Field> fields,
@Nullable Iterable<? extends Method> methods) {
if (fields == null) {
fields = ImmutableList.of();
}
if (methods == null) {
methods = ImmutableList.of();
}
this.type = type;
this.accessFlags = accessFlags;
this.superclass = superclass;
this.interfaces = interfaces==null ? ImmutableList.<String>of() : ImmutableList.copyOf(interfaces);
this.sourceFile = sourceFile;
this.annotations = ImmutableAnnotation.immutableSetOf(annotations);
this.staticFields = ImmutableField.immutableSetOf(Iterables.filter(fields, FieldUtil.FIELD_IS_STATIC));
this.instanceFields = ImmutableField.immutableSetOf(Iterables.filter(fields, FieldUtil.FIELD_IS_INSTANCE)); | this.directMethods = ImmutableMethod.immutableSetOf(Iterables.filter(methods, MethodUtil.METHOD_IS_DIRECT)); | 4 |
be-hase/relumin | src/test/java/com/behase/relumin/e2e/ClusterApiTest.java | [
"@Slf4j\n@Configuration\n@EnableAutoConfiguration\n@EnableScheduling\n@EnableWebSecurity\n@ComponentScan\npublic class Application extends WebMvcConfigurerAdapter {\n private static final String CONFIG_LOCATION = \"config\";\n\n public static void main(String[] args) throws IOException {\n log.info(\"Starting Relumin...\");\n\n String configLocation = System.getProperty(CONFIG_LOCATION);\n checkArgument(configLocation != null, \"Specify config VM parameter.\");\n\n ReluminConfig config = ReluminConfig.create(configLocation);\n log.info(\"config : {}\", config);\n\n SpringApplication app = new SpringApplication(Application.class);\n app.setDefaultProperties(config.getProperties());\n app.run(args);\n }\n}",
"@Slf4j\n@Component\npublic class TestHelper {\n @Value(\"${test.redis.host}\")\n private String testRedisHost;\n\n public String getDataStoreJedis() {\n return testRedisHost + \":9000\";\n }\n\n public Set<String> getRedisClusterHostAndPorts() {\n return new JedisSupport().getHostAndPorts(Lists.newArrayList(testRedisHost + \":10000-10005\"));\n }\n\n public Set<String> getRedisStandAloneHostAndPorts() {\n return new JedisSupport().getHostAndPorts(Lists.newArrayList(testRedisHost + \":10010-10015\"));\n }\n\n public void resetAllRedis() {\n log.info(\"reset all redis.\");\n\n try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(getDataStoreJedis())) {\n try {\n jedis.flushAll();\n } catch (Exception e) {\n }\n }\n\n for (String hostAndPort : getRedisClusterHostAndPorts()) {\n try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(hostAndPort)) {\n try {\n jedis.flushAll();\n } catch (Exception e) {\n }\n try {\n jedis.clusterReset(JedisCluster.Reset.HARD);\n } catch (Exception e) {\n }\n } catch (Exception e) {\n }\n }\n\n for (String hostAndPort : getRedisStandAloneHostAndPorts()) {\n try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(hostAndPort)) {\n jedis.flushAll();\n } catch (Exception e) {\n }\n }\n }\n\n public void createBasicCluster(MockMvc mockMvc, String clusterName) throws Exception {\n MvcResult result;\n\n result = mockMvc.perform(\n get(\"/api/trib/create/params\")\n .param(\"replicas\", \"1\")\n .param(\"hostAndPorts\", testRedisHost + \":10000-10005\")\n ).andReturn();\n String body = result.getResponse().getContentAsString();\n\n mockMvc.perform(\n post(\"/api/trib/create/\" + clusterName)\n .param(\"params\", body)\n .header(HttpHeaders.CONTENT_TYPE, \"application/json\")\n );\n }\n\n public void createOnlyMasterCluster(MockMvc mockMvc, String clusterName) throws Exception {\n MvcResult result;\n\n result = mockMvc.perform(\n get(\"/api/trib/create/params\")\n .param(\"replicas\", \"0\")\n .param(\"hostAndPorts\", testRedisHost + \":10000-10002\")\n ).andReturn();\n String body = result.getResponse().getContentAsString();\n\n mockMvc.perform(\n post(\"/api/trib/create/\" + clusterName)\n .param(\"params\", body)\n .header(HttpHeaders.CONTENT_TYPE, \"application/json\")\n );\n }\n\n public Cluster getCluster(MockMvc mockMvc, String clusterName) throws Exception {\n MvcResult result = mockMvc.perform(\n get(\"/api/cluster/\" + clusterName)\n ).andReturn();\n return WebConfig.MAPPER.readValue(result.getResponse().getContentAsString(), Cluster.class);\n }\n}",
"@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Cluster {\n private String clusterName;\n private String status;\n private Map<String, String> info;\n private List<ClusterNode> nodes;\n private List<SlotInfo> slots;\n\n public ClusterNode getNodeByHostAndPort(String hostAndPort) {\n return nodes.stream()\n .filter(node -> StringUtils.equalsIgnoreCase(hostAndPort, node.getHostAndPort()))\n .findFirst()\n .orElse(null);\n }\n\n public ClusterNode getNodeByNodeId(String nodeId) {\n return nodes.stream()\n .filter(node -> StringUtils.equalsIgnoreCase(nodeId, node.getNodeId()))\n .findFirst()\n .orElse(null);\n }\n\n public String getStatus() {\n if (status != null) {\n return status;\n }\n\n String clusterState = info.get(\"cluster_state\");\n if (StringUtils.equalsIgnoreCase(clusterState, \"fail\")) {\n status = \"fail\";\n return status;\n }\n\n boolean existsFailNode = nodes.stream()\n .filter(node -> node.hasFlag(\"fail\"))\n .findAny()\n .isPresent();\n\n if (existsFailNode) {\n status = \"warn\";\n return status;\n }\n\n status = \"ok\";\n return status;\n }\n}",
"@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Notice {\n private NoticeMail mail = new NoticeMail();\n private NoticeHttp http = new NoticeHttp();\n private String invalidEndTime;\n private List<NoticeItem> items = Lists.newArrayList();\n}",
"@Slf4j\n@Component\n@Profile(value = \"!test\")\npublic class NodeScheduler {\n @Autowired\n private ClusterService clusterService;\n\n @Autowired\n private NodeService nodeService;\n\n @Autowired\n private JedisPool datastoreJedisPool;\n\n @Autowired\n private NotifyService notifyService;\n\n @Autowired\n private ObjectMapper mapper;\n\n @Autowired\n private FluentLogger fluentLogger;\n\n @Value(\"${scheduler.collectStaticsInfoMaxCount:\" + SchedulerConfig.DEFAULT_COLLECT_STATICS_INFO_MAX_COUNT +\n \"}\")\n private long collectStaticsInfoMaxCount;\n\n @Value(\"${scheduler.collectSlowLogMaxCount:\" + SchedulerConfig.DEFAULT_COLLECT_SLOW_LOG_MAX_COUNT +\n \"}\")\n private long collectSlowLogMaxCount;\n\n @Value(\"${redis.prefixKey}\")\n private String redisPrefixKey;\n\n @Value(\"${notice.mail.host}\")\n private String noticeMailHost;\n\n @Value(\"${notice.mail.port}\")\n private int noticeMailPort;\n\n @Value(\"${notice.mail.from}\")\n private String noticeMailFrom;\n\n @Value(\"${outputMetrics.fluentd.nodeTag}\")\n private String outputMetricsFluentdNodeTag;\n\n @Scheduled(fixedDelayString = \"${scheduler.collectStaticsInfoIntervalMillis:\"\n + SchedulerConfig.DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS + \"}\")\n public void collectStaticsInfo() throws ApiException, IOException {\n log.info(\"collectStaticsInfo call\");\n Set<String> clusterNames = clusterService.getClusters();\n clusterNames.parallelStream().forEach(clusterName -> {\n try {\n Notice notice = clusterService.getClusterNotice(clusterName);\n Cluster cluster = clusterService.getCluster(clusterName);\n List<ClusterNode> clusterNodes = cluster.getNodes();\n Map<ClusterNode, Map<String, String>> staticsInfos = Maps.newConcurrentMap();\n List<SlowLog> slowLogs = Collections.synchronizedList(Lists.newArrayList());\n\n // collect statics and slowLog\n clusterNodes.parallelStream().forEach(clusterNode -> {\n try {\n Map<String, String> staticsInfo = nodeService.getStaticsInfo(clusterNode);\n staticsInfos.put(clusterNode, staticsInfo);\n\n if (collectSlowLogMaxCount > 0) {\n slowLogs.addAll(nodeService.getSlowLog(clusterNode));\n }\n\n try (Jedis jedis = datastoreJedisPool.getResource()) {\n log.debug(\"Save staticsInfo to redis.\");\n String key = Constants.getNodeStaticsInfoRedisKey(redisPrefixKey, clusterName,\n clusterNode.getNodeId());\n jedis.lpush(key, mapper.writeValueAsString(staticsInfo));\n jedis.ltrim(key, 0, collectStaticsInfoMaxCount - 1);\n }\n } catch (Exception e) {\n log.error(\"collectStaticsInfo fail. clusterName={}, hostAndPort={}\", clusterName,\n clusterNode.getHostAndPort(), e);\n }\n });\n\n // sort slowLog, and save\n try {\n saveSlowLogs(slowLogs, clusterName);\n } catch (Exception e) {\n log.error(\"saveSlowLogs fail. clusterName={}\", clusterName, e);\n }\n\n // Output metrics\n try {\n outputMetrics(cluster, staticsInfos);\n } catch (Exception e) {\n log.error(\"outputMetrics fail. clusterName={}\", clusterName, e);\n }\n\n // Notice\n if (notice == null) {\n log.debug(\"No notice setting, so skip.\");\n } else {\n List<NoticeJob> noticeJobs = getNoticeJobs(notice, cluster, staticsInfos);\n if (!noticeJobs.isEmpty()) {\n log.info(\"NOTIFY !! {}\", noticeJobs);\n notifyService.notify(cluster, notice, noticeJobs);\n }\n }\n } catch (Exception e) {\n log.error(\"collectStaticsInfo fail. {}\", clusterName, e);\n }\n });\n log.info(\"collectStaticsInfo finish\");\n }\n\n void saveSlowLogs(List<SlowLog> slowLogs, String clusterName) {\n try (Jedis jedis = datastoreJedisPool.getResource()) {\n String key = Constants.getClusterSlowLogRedisKey(redisPrefixKey, clusterName);\n\n PagerData<SlowLog> mostRecentPd = clusterService.getClusterSlowLogHistory(clusterName, 0, 1);\n final long mostRecent = mostRecentPd.getData().isEmpty() ? 0L : mostRecentPd.getData().get(0).getTimeStamp();\n\n // filter by timestamp\n slowLogs = slowLogs.stream().filter(v -> v.getTimeStamp() > mostRecent).collect(Collectors.toList());\n\n if (slowLogs.size() == 0) {\n return;\n }\n\n // sort by timestamp\n slowLogs.sort((i, k) -> Long.compare(i.getTimeStamp(), k.getTimeStamp()));\n\n List<String> slowLogStrList = slowLogs.stream().map(v -> {\n try {\n return mapper.writeValueAsString(v);\n } catch (JsonProcessingException ignore) {\n return null;\n }\n }).filter(v -> v != null).collect(Collectors.toList());\n\n if (slowLogStrList.size() > 0) {\n jedis.lpush(key, slowLogStrList.toArray(new String[slowLogStrList.size()]));\n jedis.ltrim(key, 0, collectSlowLogMaxCount - 1);\n }\n }\n }\n\n void outputMetrics(Cluster cluster, Map<ClusterNode, Map<String, String>> staticsInfos) {\n if (fluentLogger != null) {\n // node metrics\n staticsInfos.forEach((clusterNode, statics) -> {\n Map<String, Object> staticsObj = Maps.newHashMap();\n statics.forEach((k, v) -> staticsObj.put(k, v));\n staticsObj.put(\"cluster_name\", cluster.getClusterName());\n staticsObj.put(\"node_id\", clusterNode.getNodeId());\n staticsObj.put(\"host_and_port\", clusterNode.getHostAndPort());\n log.debug(\"Logging on fluentd.\");\n fluentLogger.log(\n String.format(\"%s.%s\", outputMetricsFluentdNodeTag, clusterNode.getNodeId()),\n staticsObj);\n });\n }\n }\n\n List<NoticeJob> getNoticeJobs(Notice notice, Cluster cluster,\n Map<ClusterNode, Map<String, String>> staticsInfos) {\n List<NoticeJob> noticeJobs = Lists.newArrayList();\n\n if (isInInvalidEndTime(notice)) {\n // ignore\n return noticeJobs;\n }\n\n for (NoticeItem item : notice.getItems()) {\n switch (NoticeType.getNoticeType(item.getMetricsType())) {\n case CLUSTER_INFO:\n String targetClusterInfoVal;\n if (\"cluster_state\".equals(item.getMetricsName())) {\n targetClusterInfoVal = cluster.getStatus();\n } else {\n targetClusterInfoVal = cluster.getInfo().get(item.getMetricsName());\n }\n\n if (shouldNotify(item.getValueType(), item.getOperator(), targetClusterInfoVal, item.getValue())) {\n ResultValue result = new ResultValue(\"\", \"\", targetClusterInfoVal);\n noticeJobs.add(new NoticeJob(item, Lists.newArrayList(result)));\n }\n break;\n case NODE_INFO:\n List<ResultValue> resultValues = Lists.newArrayList();\n\n staticsInfos.forEach((node, staticsInfo) -> {\n String targetNodeInfoVal = staticsInfo.get(item.getMetricsName());\n\n if (shouldNotify(item.getValueType(), item.getOperator(), targetNodeInfoVal, item.getValue())) {\n resultValues.add(\n new ResultValue(node.getNodeId(), node.getHostAndPort(), targetNodeInfoVal));\n }\n });\n\n if (resultValues.size() > 0) {\n noticeJobs.add(new NoticeJob(item, resultValues));\n }\n break;\n default:\n break;\n }\n }\n\n return noticeJobs;\n }\n\n boolean isInInvalidEndTime(Notice notice) {\n if (StringUtils.isNotBlank(notice.getInvalidEndTime())) {\n try {\n Long time = Long.valueOf(notice.getInvalidEndTime());\n if (System.currentTimeMillis() < time) {\n log.info(\"NOW ignore notify. notice={}\", notice);\n return true;\n }\n } catch (Exception e) {\n }\n }\n\n return false;\n }\n\n boolean shouldNotify(String valueType, String operator, String value, String threshold) {\n if (value == null) {\n return false;\n }\n\n boolean isNotify = false;\n\n switch (NoticeValueType.getNoticeValueType(valueType)) {\n case STRING:\n switch (NoticeOperator.getNoticeOperator(operator)) {\n case EQ:\n isNotify = StringUtils.equalsIgnoreCase(value, threshold);\n break;\n case NE:\n isNotify = !StringUtils.equalsIgnoreCase(value, threshold);\n break;\n default:\n break;\n }\n break;\n case NUMBER:\n BigDecimal targetValNumber = new BigDecimal(value);\n int compareResult = targetValNumber.compareTo(new BigDecimal(threshold));\n switch (NoticeOperator.getNoticeOperator(operator)) {\n case EQ:\n isNotify = compareResult == 0;\n break;\n case NE:\n isNotify = compareResult != 0;\n break;\n case GT:\n isNotify = compareResult == 1;\n break;\n case GE:\n isNotify = compareResult == 1 || compareResult == 0;\n break;\n case LT:\n isNotify = compareResult == -1;\n break;\n case LE:\n isNotify = compareResult == -1 || compareResult == 0;\n break;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n return isNotify;\n }\n}"
] | import com.behase.relumin.Application;
import com.behase.relumin.TestHelper;
import com.behase.relumin.model.Cluster;
import com.behase.relumin.model.Notice;
import com.behase.relumin.scheduler.NodeScheduler;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.context.WebApplicationContext;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; | package com.behase.relumin.e2e;
/**
* Check integration of success behavior
*/
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest
public class ClusterApiTest {
@Value("${test.redis.host}")
private String testRedisHost;
@Autowired
private TestHelper testHelper;
@Autowired
private WebApplicationContext wac;
@Autowired
private ObjectMapper mapper;
@Autowired | private NodeScheduler nodeScheduler; | 4 |
pasqualesalza/elephant56 | elephant56/src/main/java/it/unisa/elephant56/core/generator/GridReducer.java | [
"public final class Constants {\r\n /**\r\n * The default lock file name.\r\n */\r\n public static final String LOCK_FILE_NAME =\r\n \"lock\";\r\n\r\n public static final long LOCK_TIME_TO_WAIT =\r\n 100L;\r\n\r\n /**\r\n * The meta-data property for Avro files.\r\n */\r\n public static final String AVRO_NUMBER_OF_RECORDS =\r\n \"number_of_records\";\r\n\r\n /**\r\n * The file extension for the avro files.\r\n */\r\n public static final String AVRO_FILE_EXTENSION =\r\n \"avro\";\r\n\r\n /**\r\n * The file extension for the jar files.\r\n */\r\n public static final String JAR_FILE_EXTENSION =\r\n \"jar\";\r\n\r\n /**\r\n * The format of island names.\r\n */\r\n public static final String ISLANDS_NAME_FORMAT =\r\n \"%05d\";\r\n\r\n /**\r\n * The format of generation name.\r\n */\r\n public static final String CONFIGURATION_GENERATION_NAME_FORMAT =\r\n \"elephant56.configuration.generation_name_format\";\r\n\r\n /**\r\n * The path of the folder where are the files representing the fact the termination condition has been satisfied at\r\n * least once.\r\n */\r\n public static final String CONFIGURATION_TERMINATION_FLAG_FILES_FOLDER_PATH =\r\n \"elephant56.configuration.termination_flag_files_folder.path\";\r\n\r\n /**\r\n * The file extension for the termination flag files.\r\n */\r\n public static final String TERMINATION_FLAG_FILE_EXTENSION =\r\n \"termination_flag\";\r\n\r\n /**\r\n * The path of the folder where the islands properties files are.\r\n */\r\n public static final String CONFIGURATION_ISLAND_PROPERTIES_FILES_FOLDER_PATH =\r\n \"elephant56.configuration.island_properties_files_folder.path\";\r\n\r\n /**\r\n * The file extension for the properties files.\r\n */\r\n public static final String PROPERTIES_FILES_EXTENSION =\r\n \"properties\";\r\n\r\n /**\r\n * The start generation number.\r\n */\r\n public static final String CONFIGURATION_START_GENERATION_NUMBER =\r\n \"elephant56.configuration.start_generation_number\";\r\n\r\n /**\r\n * The finish generation number.\r\n */\r\n public static final String CONFIGURATION_FINISH_GENERATION_NUMBER =\r\n \"elephant56.configuration.finish_generation_number\";\r\n\r\n /**\r\n * The number of individual for the initialisation operator.\r\n */\r\n public static final String CONFIGURATION_INITIALISATION_POPULATION_SIZE =\r\n \"elephant56.configuration.initialisation.population_size\";\r\n\r\n /**\r\n * The flag that indicates if the initialisation is active or not.\r\n */\r\n public static final String CONFIGURATION_INITIALISATION_ACTIVE =\r\n \"elephant56.configuration.initialisation.active\";\r\n\r\n /**\r\n * The flag that indicates if the survival selection is active or not.\r\n */\r\n public static final String CONFIGURATION_SURVIVAL_SELECTION_ACTIVE =\r\n \"elephant56.configuration.survival_selection.active\";\r\n\r\n /**\r\n * The flag that indicates if the elitism is active or not.\r\n */\r\n public static final String CONFIGURATION_ELITISM_ACTIVE =\r\n \"elephant56.configuration.elitism.active\";\r\n\r\n /**\r\n * The flag that indicates if the migration is active or not.\r\n */\r\n public static final String CONFIGURATION_MIGRATION_ACTIVE =\r\n \"elephant56.configuration.migration.active\";\r\n\r\n /**\r\n * The flag that indicates if the time reporter is active or not.\r\n */\r\n public static final String CONFIGURATION_TIME_REPORTER_ACTIVE =\r\n \"elephant56.configuration.reporter.time.active\";\r\n\r\n /**\r\n * The flag that indicates if the individual reporter is active or not.\r\n */\r\n public static final String CONFIGURATION_INDIVIDUAL_REPORTER_ACTIVE =\r\n \"elephant56.configuration.reporter.individual.active\";\r\n\r\n /**\r\n * The fitness value class configuration string.\r\n */\r\n public static final String CONFIGURATION_FITNESS_VALUE_CLASS =\r\n \"elephant56.configuration.fitness_value.class\";\r\n\r\n /**\r\n * The initialisation class configuration string.\r\n */\r\n public static final String CONFIGURATION_INITIALISATION_CLASS =\r\n \"elephant56.configuration.initialisation.class\";\r\n\r\n /**\r\n * The fitness evaluation class configuration string.\r\n */\r\n public static final String CONFIGURATION_FITNESS_EVALUATION_CLASS =\r\n \"elephant56.configuration.fitness_evaluation.class\";\r\n\r\n /**\r\n * The termination condition check class configuration string.\r\n */\r\n public static final String CONFIGURATION_TERMINATION_CONDITION_CHECK_CLASS =\r\n \"elephant56.configuration.termination_condition_check.class\";\r\n\r\n /**\r\n * The parents selection class configuration string.\r\n */\r\n public static final String CONFIGURATION_PARENTS_SELECTION_CLASS =\r\n \"elephant56.configuration.parents_selection.class\";\r\n\r\n /**\r\n * The crossover class configuration string.\r\n */\r\n public static final String CONFIGURATION_CROSSOVER_CLASS =\r\n \"elephant56.configuration.crossover.class\";\r\n\r\n /**\r\n * The mutation class configuration string.\r\n */\r\n public static final String CONFIGURATION_MUTATION_CLASS =\r\n \"elephant56.configuration.mutation.class\";\r\n\r\n /**\r\n * The survival selection class configuration string.\r\n */\r\n public static final String CONFIGURATION_SURVIVAL_SELECTION_CLASS =\r\n \"elephant56.configuration.survival_selection.class\";\r\n\r\n /**\r\n * The elitism class configuration string.\r\n */\r\n public static final String CONFIGURATION_ELITISM_CLASS =\r\n \"elephant56.configuration.elitism.class\";\r\n\r\n /**\r\n * The migration class configuration string.\r\n */\r\n public static final String CONFIGURATION_MIGRATION_CLASS =\r\n \"elephant56.configuration.migration.class\";\r\n\r\n /**\r\n * The flag that indicates if the generation is the last for the grid parallelisation model.\r\n */\r\n public static final String CONFIGURATION_GRID_PARALLELISATION_MODEL_IS_LAST_GENERATION =\r\n \"elephant56.configuration.grid_parallelisation_model.is_last_generation\";\r\n\r\n /**\r\n * The reports folder path.\r\n */\r\n public static final String CONFIGURATION_REPORTS_FOLDER_PATH =\r\n \"elephant56.configuration.reports_folder.path\";\r\n\r\n public static final String CONFIGURATION_GENERATIONS_BLOCK_NUMBER =\r\n \"elephant56.configuration.generations_block_number.long\";\r\n\r\n public static final String GENETIC_OPERATORS_TIME_REPORT_FILE_NAME_FORMAT =\r\n \"times-genetic_operators-i(\" + ISLANDS_NAME_FORMAT + \").csv\";\r\n\r\n public static final String GENERATIONS_BLOCK_TIME_REPORT_FILE_NAME_FORMAT =\r\n \"times-generations_block-i(\" + ISLANDS_NAME_FORMAT + \").csv\";\r\n\r\n public static final String GRID_GENERATIONS_BLOCK_TIME_REPORT_FILE_NAME_FORMAT =\r\n \"times-generations_block.csv\";\r\n\r\n public static final String MAPREDUCE_TIME_REPORT_FILE_NAME_FORMAT =\r\n \"times-mapreduce.csv\";\r\n\r\n public static final String MAPREDUCE_MAPPER_PARTIAL_TIME_REPORT_FILE_NAME_FORMAT =\r\n \"times-mapreduce-i(\" + ISLANDS_NAME_FORMAT + \").csv.m.part\";\r\n\r\n public static final String MAPREDUCE_REDUCER_PARTIAL_TIME_REPORT_FILE_NAME_FORMAT =\r\n \"times-mapreduce-i(\" + ISLANDS_NAME_FORMAT + \").csv.r.part\";\r\n\r\n public static final String INDIVIDUAL_REPORT_FILE_NAME_FORMAT =\r\n \"individuals-i(\" + ISLANDS_NAME_FORMAT + \").csv\";\r\n\r\n public static final String CONFIGURATION_POPULATION_NAME =\r\n \"population\";\r\n\r\n public static final String CONFIGURATION_SOLUTIONS_NAME =\r\n \"solutions\";\r\n\r\n public static final String CONFIGURATION_NONSOLUTIONS_NAME =\r\n \"nonsolutions\";\r\n\r\n /**\r\n * The default parents output folder name.\r\n */\r\n public static final String DEFAULT_PARENTS_OUTPUT_FOLDER_NAME =\r\n \"parents\";\r\n\r\n /**\r\n * The default offspring output folder name.\r\n */\r\n public static final String DEFAULT_OFFSPRING_OUTPUT_FOLDER_NAME =\r\n \"offspring\";\r\n\r\n /**\r\n * The default input folder name.\r\n */\r\n public static final String DEFAULT_INPUT_FOLDER_NAME =\r\n \"input\";\r\n\r\n /**\r\n * The default output folder name.\r\n */\r\n public static final String DEFAULT_OUTPUT_FOLDER_NAME =\r\n \"output\";\r\n\r\n /**\r\n * The default generations folder name.\r\n */\r\n public static final String DEFAULT_GENERATIONS_BLOCKS_FOLDER_NAME =\r\n \"generations_blocks\";\r\n\r\n /**\r\n * The default termination flag files folder name.\r\n */\r\n public static final String DEFAULT_TERMINATION_FLAG_FILES_FOLDER_NAME =\r\n \"termination_flags\";\r\n\r\n /**\r\n * The default solutions folder name.\r\n */\r\n public static final String DEFAULT_SOLUTIONS_FOLDER_NAME =\r\n \"solutions\";\r\n\r\n /**\r\n * The default reports folder name.\r\n */\r\n public static final String DEFAULT_REPORTS_FOLDER_NAME =\r\n \"reports\";\r\n\r\n /**\r\n * The default islands properties files folder name.\r\n */\r\n public static final String DEFAULT_ISLANDS_PROPERTIES_FILES_FOLDER_NAME =\r\n \"islands_properties\";\r\n\r\n private Constants() {\r\n throw new AssertionError();\r\n }\r\n}\r",
"public class IndividualWrapper<IndividualType extends Individual, FitnessValueType extends FitnessValue>\r\n implements Comparable<IndividualWrapper<IndividualType, FitnessValueType>>, Cloneable {\r\n\r\n private IndividualType individual;\r\n private FitnessValueType fitnessValue;\r\n private Boolean terminationConditionSatisfied;\r\n\r\n /**\r\n * Constructs an empty wrapper.\r\n */\r\n public IndividualWrapper() {\r\n this.individual = null;\r\n this.fitnessValue = null;\r\n this.terminationConditionSatisfied = null;\r\n }\r\n\r\n /**\r\n * Composes the Avro schema of the individual wrapper.\r\n *\r\n * @param individualClass the class of the individual\r\n * @param fitnessValueClass the class of the fitness value\r\n * @return the schema composed\r\n */\r\n public static final Schema getSchema(Class<?> individualClass, Class<?> fitnessValueClass) {\r\n // Makes the list of the fields.\r\n List<Field> fields = new ArrayList<Field>();\r\n\r\n // Retrieves the schemas of the classes with the reflect.\r\n Schema individualReflectSchema = ReflectData.AllowNull.get().getSchema(individualClass);\r\n Schema fitnessValueReflectSchema = ReflectData.AllowNull.get().getSchema(fitnessValueClass);\r\n\r\n // Composes the schemas with the possibility to set values to null.\r\n Schema individualSchema = Schema.createUnion(Arrays.asList(\r\n Schema.create(Schema.Type.NULL), individualReflectSchema));\r\n Schema fitnessValueSchema = Schema.createUnion(Arrays.asList(\r\n Schema.create(Schema.Type.NULL), fitnessValueReflectSchema));\r\n Schema terminationConditionSatisfiedSchema = Schema.createUnion(Arrays.asList(\r\n Schema.create(Schema.Type.NULL), Schema.create(Schema.Type.BOOLEAN)));\r\n\r\n // Adds the fields to the main schema.\r\n fields.add(new Field(\"individual\", individualSchema, null, null));\r\n fields.add(new Field(\"fitnessValue\", fitnessValueSchema, null, null));\r\n fields.add(new Field(\"terminationConditionSatisfied\", terminationConditionSatisfiedSchema, null, null));\r\n\r\n // Creates the main schema and returns it.\r\n Schema schema = Schema.createRecord(IndividualWrapper.class.getName(), null,\r\n IndividualWrapper.class.getPackage().getName(), false);\r\n schema.setFields(fields);\r\n\r\n return schema;\r\n }\r\n\r\n /**\r\n * Empties the individual field.\r\n */\r\n public final void emptyIndividual() {\r\n this.individual = null;\r\n }\r\n\r\n /**\r\n * Checks if the individual is set.\r\n *\r\n * @return \"true\" if it is set\r\n */\r\n public final boolean isIndividualSet() {\r\n return (this.individual != null);\r\n }\r\n\r\n /**\r\n * Returns the individual inside the wrapper.\r\n *\r\n * @return the individual\r\n */\r\n public final IndividualType getIndividual() {\r\n return this.individual;\r\n }\r\n\r\n /**\r\n * Sets the individual.\r\n *\r\n * @param individual the individual (\"null\" to empty)\r\n */\r\n public final void setIndividual(IndividualType individual) {\r\n this.individual = individual;\r\n }\r\n\r\n /**\r\n * Empties the fitness value field.\r\n */\r\n public final void emptyFitnessValue() {\r\n this.fitnessValue = null;\r\n }\r\n\r\n /**\r\n * Checks if the fitness value is set.\r\n *\r\n * @return \"true\" if it is set\r\n */\r\n public final boolean isFitnessValueSet() {\r\n return (this.fitnessValue != null);\r\n }\r\n\r\n /**\r\n * Returns the fitness value of the individual.\r\n */\r\n public final FitnessValueType getFitnessValue() {\r\n return this.fitnessValue;\r\n }\r\n\r\n /**\r\n * Sets the fitness value of the individual.\r\n *\r\n * @param fitnessValue the fitness value (\"null\" to empty)\r\n */\r\n public final void setFitnessValue(FitnessValueType fitnessValue) {\r\n this.fitnessValue = fitnessValue;\r\n }\r\n\r\n /**\r\n * Sets if the individual satisfies the termination condition or not.\r\n *\r\n * @param value \"true\" if it satisfies the termination condition (\"null\" to empty)\r\n */\r\n public final void setTerminationConditionSatisfied(Boolean value) {\r\n this.terminationConditionSatisfied = value;\r\n }\r\n\r\n /**\r\n * Empties the termination condition satisfied field. This means that the check has never been checked.\r\n */\r\n public final void emptyTerminationConditionSatisfied() {\r\n this.terminationConditionSatisfied = null;\r\n }\r\n\r\n /**\r\n * Checks if the individual satisfies the termination condition or not. If it returns the \"null\" value, it means\r\n * that is has not ever been checked.\r\n *\r\n * @return \"true\" if it satisfies the termination condition (\"null\" if never checked)\r\n */\r\n public final Boolean isTerminationConditionSatisfied() {\r\n return this.terminationConditionSatisfied;\r\n }\r\n\r\n /**\r\n * Checks if the termination condition satisfied flag is set.\r\n *\r\n * @return \"true\" if it is set\r\n */\r\n public final Boolean isTerminationConditionSatisfiedSet() {\r\n return (this.terminationConditionSatisfied != null);\r\n }\r\n\r\n /**\r\n * Returns the string representation of the wrapper.\r\n */\r\n @Override\r\n public final String toString() {\r\n return \"{individual: \" + this.individual + \", fitnessValue: \" + this.fitnessValue +\r\n \", terminationConditionSatisfied: \" + this.terminationConditionSatisfied + \"}\";\r\n }\r\n\r\n /**\r\n * Two individuals are equal only if all the fields are equal.\r\n */\r\n @SuppressWarnings(\"unchecked\")\r\n @Override\r\n public final boolean equals(Object object) {\r\n if (!(object instanceof IndividualWrapper))\r\n return false;\r\n\r\n IndividualWrapper<IndividualType, FitnessValueType> other =\r\n (IndividualWrapper<IndividualType, FitnessValueType>) object;\r\n\r\n return this.individual.equals(other.individual);\r\n }\r\n\r\n @Override\r\n public final int hashCode() {\r\n final int prime = 31;\r\n\r\n int result = 1;\r\n\r\n result = prime * result + ((this.fitnessValue == null) ? 0 : this.fitnessValue.hashCode());\r\n result = prime * result + ((this.individual == null) ? 0 : this.individual.hashCode());\r\n result = prime * result + ((this.terminationConditionSatisfied == null) ? 0\r\n : this.terminationConditionSatisfied.hashCode());\r\n\r\n return result;\r\n }\r\n\r\n\r\n /**\r\n * Compares by the fitness value.\r\n *\r\n * @param other the other individual wrapper to compare\r\n * @return a negative integer, zero, or a positive integer as this object is less than,\r\n * equal to, or greater than the specified object\r\n */\r\n @Override\r\n public int compareTo(IndividualWrapper<IndividualType, FitnessValueType> other) {\r\n if (this.fitnessValue == null)\r\n return 0;\r\n\r\n return this.fitnessValue.compareTo(other.getFitnessValue());\r\n }\r\n\r\n @SuppressWarnings(\"unchecked\")\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n IndividualType individualClone = (IndividualType) this.individual.clone();\r\n FitnessValueType fitnessValueClone = (this.fitnessValue != null)\r\n ? (FitnessValueType) this.fitnessValue.clone() : null;\r\n\r\n IndividualWrapper<IndividualType, FitnessValueType> clone =\r\n new IndividualWrapper<IndividualType, FitnessValueType>();\r\n clone.setIndividual(individualClone);\r\n clone.setFitnessValue(fitnessValueClone);\r\n clone.setTerminationConditionSatisfied(this.terminationConditionSatisfied);\r\n\r\n return clone;\r\n }\r\n}\r",
"public class Properties {\r\n /**\r\n * Reads the properties from a file.\r\n *\r\n * @param inputFilePath the path where to read the properties\r\n * @param fileSystem the filesystem\r\n * @return the read properties\r\n * @throws IOException\r\n */\r\n public static Properties readFromFile(Path inputFilePath, FileSystem fileSystem) throws IOException {\r\n FSDataInputStream fileInputStream = fileSystem.open(inputFilePath);\r\n\r\n Configuration configuration = new Configuration(false);\r\n configuration.readFields(fileInputStream);\r\n\r\n fileInputStream.close();\r\n\r\n Properties properties = new Properties(configuration);\r\n\r\n return properties;\r\n }\r\n\r\n private Configuration configuration;\r\n\r\n /**\r\n * Constructs the object.\r\n */\r\n public Properties() {\r\n this.configuration = new Configuration(false);\r\n }\r\n\r\n /**\r\n * Constructs the object specifying the configuration.\r\n *\r\n * @param configuration the configuration\r\n */\r\n public Properties(Configuration configuration) {\r\n this.configuration = configuration;\r\n }\r\n\r\n /**\r\n * Copies the properties into a Configuration object.\r\n *\r\n * @param configuration the destination\r\n */\r\n public void copyIntoConfiguration(Configuration configuration) {\r\n for (Map.Entry<String, String> entry : this.configuration)\r\n configuration.set(entry.getKey(), entry.getValue());\r\n }\r\n\r\n /**\r\n * Writes the properties into a file.\r\n *\r\n * @param outputFilePath the path where to write the properties\r\n * @param fileSystem the filesystem\r\n * @throws java.io.IOException\r\n */\r\n public void writeToFile(Path outputFilePath, FileSystem fileSystem) throws IOException {\r\n FSDataOutputStream fileOutputStream = fileSystem.create(outputFilePath, true);\r\n this.configuration.write(fileOutputStream);\r\n fileOutputStream.close();\r\n }\r\n\r\n /**\r\n * Checks if a property is set or not.\r\n *\r\n * @param name the name of the property\r\n * @return \"true\" if yes, \"false\" otherwise\r\n */\r\n public boolean isSet(String name) {\r\n return (this.configuration.get(name) != null);\r\n }\r\n\r\n /**\r\n * Get the value of the the \"name\" property as a String.\r\n *\r\n * @param name the name of the property\r\n * @param defaultValue the default value, if the property doesn't exist\r\n * @return the value of the property\r\n */\r\n public String getString(String name, String defaultValue) {\r\n return this.configuration.get(name, defaultValue);\r\n }\r\n\r\n /**\r\n * Get the value of the \"name\" property as a boolean.\r\n *\r\n * @param name the name of the property\r\n * @param defaultValue the default value, if the property doesn't exist\r\n * @return the value of the property\r\n */\r\n public boolean getBoolean(String name, boolean defaultValue) {\r\n return this.configuration.getBoolean(name, defaultValue);\r\n }\r\n\r\n /**\r\n * Get the value of the \"name\" property as a Class.\r\n *\r\n * @param name the name of the property\r\n * @param defaultValue the default value, if the property doesn't exist\r\n * @return the value of the property\r\n */\r\n public Class<?> getClass(String name, Class<?> defaultValue) {\r\n return this.configuration.getClass(name, defaultValue);\r\n }\r\n\r\n /**\r\n * Get the value of the \"name\" property as an Enum.\r\n *\r\n * @param name the name of the property\r\n * @param defaultValue the default value, if the property doesn't exist\r\n * @return the value of the property\r\n */\r\n public <T extends Enum<T>> T getEnum(String name, T defaultValue) {\r\n return this.configuration.getEnum(name, defaultValue);\r\n }\r\n\r\n /**\r\n * Get the value of the \"name\" property as a float.\r\n *\r\n * @param name the name of the property\r\n * @param defaultValue the default value, if the property doesn't exist\r\n * @return the value of the property\r\n */\r\n public float getFloat(String name, float defaultValue) {\r\n return this.configuration.getFloat(name, defaultValue);\r\n }\r\n\r\n /**\r\n * Get the value of the \"name\" property as an int.\r\n *\r\n * @param name the name of the property\r\n * @param defaultValue the default value, if the property doesn't exist\r\n * @return the value of the property\r\n */\r\n public int getInt(String name, int defaultValue) {\r\n return this.configuration.getInt(name, defaultValue);\r\n }\r\n\r\n /**\r\n * Get the value of the \"name\" property as an array of int values.\r\n *\r\n * @param name the name of the property\r\n * @return the value of the property\r\n */\r\n public int[] getInts(String name) {\r\n Collection<String> strings = this.configuration.getStringCollection(name);\r\n\r\n int[] result = new int[strings.size()];\r\n\r\n int i = 0;\r\n\r\n for (String string : strings) {\r\n result[i] = Integer.parseInt(string);\r\n i++;\r\n }\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Get the value of the \"name\" property as a long.\r\n *\r\n * @param name the name of the property\r\n * @param defaultValue the default value, if the property doesn't exist\r\n * @return the value of the property\r\n */\r\n public long getLong(String name, long defaultValue) {\r\n return this.configuration.getLong(name, defaultValue);\r\n }\r\n\r\n /**\r\n * Get the value of the \"name\" property as a double.\r\n *\r\n * @param name the name of the property\r\n * @param defaultValue the default value, if the property doesn't exist\r\n * @return the value of the property\r\n */\r\n public double getDouble(String name, double defaultValue) {\r\n String string = this.configuration.get(name);\r\n\r\n if (string == null)\r\n return defaultValue;\r\n\r\n return Double.parseDouble(string);\r\n }\r\n\r\n /**\r\n * Get the value of the \"name\" property as a collection of String.\r\n *\r\n * @param name the name of the property\r\n * @return the value of the property\r\n */\r\n public Collection<String> getStringCollection(String name) {\r\n return this.configuration.getStringCollection(name);\r\n }\r\n\r\n /**\r\n * Get the value of the \"name\" property as an array of String.\r\n *\r\n * @param name the name of the property\r\n * @return the value of the property\r\n */\r\n public String[] getStrings(String name) {\r\n return this.configuration.getStrings(name);\r\n }\r\n\r\n /**\r\n * Set the value of the the \"name\" property as a String.\r\n *\r\n * @param name the name of the property\r\n * @param value the value to set\r\n */\r\n public void setString(String name, String value) {\r\n this.configuration.set(name, value);\r\n }\r\n\r\n /**\r\n * Set the value of the \"name\" property as a boolean.\r\n *\r\n * @param name the name of the property\r\n * @param value the value to set\r\n */\r\n public void setBoolean(String name, boolean value) {\r\n this.configuration.setBoolean(name, value);\r\n }\r\n\r\n /**\r\n * Set the value of the \"name\" property as a Class.\r\n *\r\n * @param name the name of the property\r\n * @param value the value to set\r\n */\r\n public void setClass(String name, Class<?> value) {\r\n this.configuration.setClass(name, value, Object.class);\r\n }\r\n\r\n /**\r\n * Set the value of the \"name\" property as an Enum.\r\n *\r\n * @param name the name of the property\r\n * @param value the value to set\r\n */\r\n public <T extends Enum<T>> void setEnum(String name, T value) {\r\n this.configuration.setEnum(name, value);\r\n }\r\n\r\n /**\r\n * Set the value of the \"name\" property as a float.\r\n *\r\n * @param name the name of the property\r\n * @param value the value to set\r\n */\r\n public void setFloat(String name, float value) {\r\n this.configuration.setFloat(name, value);\r\n }\r\n\r\n /**\r\n * Set the value of the \"name\" property as an int.\r\n *\r\n * @param name the name of the property\r\n * @param value the value to set\r\n */\r\n public void setInt(String name, int value) {\r\n this.configuration.setInt(name, value);\r\n }\r\n\r\n /**\r\n * Set the value of the \"name\" property as an array of int values.\r\n *\r\n * @param name the name of the property\r\n * @param values the values to set\r\n */\r\n public void setInts(String name, int... values) {\r\n String[] stringValues = new String[values.length];\r\n\r\n for (int i = 0; i < values.length; i++)\r\n stringValues[i] = Integer.toString(values[i]);\r\n\r\n this.configuration.setStrings(name, stringValues);\r\n }\r\n\r\n /**\r\n * Set the value of the \"name\" property as a long.\r\n *\r\n * @param name the name of the property\r\n * @param value the value to set\r\n */\r\n public void setLong(String name, long value) {\r\n this.configuration.setLong(name, value);\r\n }\r\n\r\n /**\r\n * Set the value of the \"name\" property as a double.\r\n *\r\n * @param name the name of the property\r\n * @param value the value to set\r\n */\r\n public void setDouble(String name, double value) {\r\n this.configuration.set(name, Double.toString(value));\r\n }\r\n\r\n /**\r\n * Set the value of the \"name\" property as an array of String.\r\n *\r\n * @param name the name of the property\r\n * @param values the values to set\r\n */\r\n public void setStrings(String name, String... values) {\r\n this.configuration.setStrings(name, values);\r\n }\r\n}\r",
"public class IndividualReporter extends TimeReporter {\r\n /**\r\n * The header.\r\n */\r\n public static final String[] HEADER = {\r\n \"island_number\", \"generations_block_number\", \"generation_number\",\r\n \"individual\", \"fitness_value\", \"termination_condition_satisfied\"\r\n };\r\n\r\n public IndividualReporter(Path outputFilePath, FileSystem fileSystem) throws IOException {\r\n super(outputFilePath, fileSystem, HEADER);\r\n }\r\n\r\n public void writeIndividual(\r\n int islandNumber, long generationsBlockNumber, long generationNumber, Individual individual,\r\n FitnessValue fitnessValue, boolean terminationConditionSatisfied) {\r\n String[] line = {\r\n Integer.toString(islandNumber),\r\n Long.toString(generationsBlockNumber),\r\n Long.toString(generationNumber),\r\n individual.toString(),\r\n fitnessValue.toString(),\r\n Boolean.toString(terminationConditionSatisfied)\r\n };\r\n\r\n super.writeLine(line);\r\n }\r\n}\r",
"public class GeneticOperatorsTimeReporter extends TimeReporter {\r\n /**\r\n * The header.\r\n */\r\n public static final String[] HEADER = {\r\n \"island_number\", \"generations_block_number\", \"generation_number\", \"phase_type\",\r\n \"start_time\", \"finish_time\", \"total_time\", \"human_total_time\"\r\n };\r\n\r\n /**\r\n * The types of phases.\r\n */\r\n public static enum PhaseType {\r\n AVERAGE_INITIALISATION,\r\n TOTAL_INITIALISATION,\r\n MIN_FITNESS_EVALUATION,\r\n MAX_FITNESS_EVALUATION,\r\n AVERAGE_FITNESS_EVALUATION,\r\n TOTAL_FITNESS_EVALUATION,\r\n AVERAGE_INDIVIDUAL_TERMINATION_CONDITION_CHECK,\r\n TOTAL_INDIVIDUAL_TERMINATION_CONDITION_CHECK,\r\n TOTAL_ISLAND_TERMINATION_CONDITION_CHECK,\r\n TOTAL_GLOBAL_TERMINATION_CONDITION_CHECK,\r\n TOTAL_ELITISM,\r\n TOTAL_PARENTS_SELECTION,\r\n AVERAGE_CROSSOVER,\r\n TOTAL_CROSSOVER,\r\n AVERAGE_MUTATION,\r\n TOTAL_MUTATION,\r\n MIN_FITNESS_EVALUATION_DURING_SURVIVAL_SELECTION,\r\n MAX_FITNESS_EVALUATION_DURING_SURVIVAL_SELECTION,\r\n AVERAGE_FITNESS_EVALUATION_DURING_SURVIVAL_SELECTION,\r\n TOTAL_FITNESS_EVALUATION_DURING_SURVIVAL_SELECTION,\r\n TOTAL_SURVIVAL_SELECTION,\r\n TOTAL_MIGRATION\r\n }\r\n\r\n ;\r\n\r\n public GeneticOperatorsTimeReporter(Path outputFilePath, FileSystem fileSystem) throws IOException {\r\n super(outputFilePath, fileSystem, HEADER);\r\n }\r\n\r\n public void writeTime(\r\n int islandNumber, long generationsBlockNumber, long generationNumber, PhaseType phaseType, long startTime,\r\n long finishTime) {\r\n super.writeTime(islandNumber, generationsBlockNumber, generationNumber, phaseType.name(), startTime, finishTime);\r\n }\r\n}\r",
"public class MapReduceTimeReporter extends TimeReporter {\r\n /**\r\n * The header.\r\n */\r\n public static final String[] HEADER = {\r\n \"island_number\", \"generations_block_number\", \"generation_number\", \"phase_type\",\r\n \"start_time\", \"finish_time\", \"total_time\", \"human_total_time\"\r\n };\r\n\r\n /**\r\n * The types of phases.\r\n */\r\n public static enum PhaseType {\r\n MAPPER_INITIALISATION,\r\n MAPPER_COMPUTATION,\r\n MAPPER_FINALISATION,\r\n REDUCER_INITIALISATION,\r\n REDUCER_COMPUTATION,\r\n REDUCER_FINALISATION\r\n }\r\n\r\n ;\r\n\r\n public static final int ISLAND_NUMBER_PARTIAL_TIMES_HEADER_INDEX = 0;\r\n public static final int GENERATIONS_BLOCK_NUMBER_PARTIAL_TIMES_HEADER_INDEX = 1;\r\n public static final int PHASE_TYPE_PARTIAL_TIMES_HEADER_INDEX = 2;\r\n public static final int TYPE_PARTIAL_TIMES_HEADER_INDEX = 3;\r\n public static final int TIME_PARTIAL_TIMES_HEADER_INDEX = 4;\r\n\r\n public static class PartialTimeKey {\r\n /**\r\n * The types of partial time.\r\n */\r\n public static enum Type {\r\n START,\r\n FINISH\r\n }\r\n\r\n private int islandNumber;\r\n private long generationsBlockNumber;\r\n private PhaseType phaseType;\r\n private Type type;\r\n\r\n public PartialTimeKey(int islandNumber, long generationsBlockNumber, PhaseType phaseType, Type type) {\r\n this.islandNumber = islandNumber;\r\n this.generationsBlockNumber = generationsBlockNumber;\r\n this.phaseType = phaseType;\r\n this.type = type;\r\n }\r\n\r\n public PartialTimeKey getOpposite() {\r\n Type oppositeType = (this.type == Type.START) ? Type.FINISH : Type.START;\r\n PartialTimeKey opposite =\r\n new PartialTimeKey(this.islandNumber, this.generationsBlockNumber, this.phaseType, oppositeType);\r\n return opposite;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n int result = islandNumber;\r\n result = 31 * result + (int) (generationsBlockNumber ^ (generationsBlockNumber >>> 32));\r\n result = 31 * result + (phaseType != null ? phaseType.hashCode() : 0);\r\n result = 31 * result + (type != null ? type.hashCode() : 0);\r\n return result;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object o) {\r\n if (this == o) return true;\r\n if (o == null || getClass() != o.getClass()) return false;\r\n\r\n PartialTimeKey that = (PartialTimeKey) o;\r\n\r\n if (generationsBlockNumber != that.generationsBlockNumber) return false;\r\n if (islandNumber != that.islandNumber) return false;\r\n if (phaseType != that.phaseType) return false;\r\n if (type != that.type) return false;\r\n\r\n return true;\r\n }\r\n }\r\n\r\n private Map<PartialTimeKey, Long> partialTimesMap;\r\n\r\n public MapReduceTimeReporter(Path outputFilePath, FileSystem fileSystem) throws IOException {\r\n super(outputFilePath, fileSystem, HEADER);\r\n\r\n this.partialTimesMap = new HashMap<PartialTimeKey, Long>();\r\n }\r\n\r\n public void writeTime(\r\n int islandNumber, long generationsBlockNumber, PhaseType phaseType, long startTime, long finishTime) {\r\n super.writeTime(islandNumber, generationsBlockNumber, -1L, phaseType.name(), startTime, finishTime);\r\n }\r\n\r\n public void addPartialTime(int islandNumber, long generationsBlockNumber, PhaseType phaseType,\r\n PartialTimeKey.Type partialTimeType, long time) {\r\n PartialTimeKey partialTimeKey =\r\n new PartialTimeKey(islandNumber, generationsBlockNumber, phaseType, partialTimeType);\r\n\r\n this.partialTimesMap.put(partialTimeKey, time);\r\n }\r\n\r\n public void addPartialTimesFromFile(Path inputFilePath, FileSystem fileSystem) throws IOException {\r\n // Creates the reader.\r\n FSDataInputStream fileInputStream = fileSystem.open(inputFilePath);\r\n BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));\r\n CSVReader fileReader = new CSVReader(bufferedReader);\r\n\r\n // Iterates among the lines.\r\n List<String[]> lines = fileReader.readAll();\r\n for (String[] line : lines) {\r\n // Reads data.\r\n int islandNumber = Integer.parseInt(line[ISLAND_NUMBER_PARTIAL_TIMES_HEADER_INDEX]);\r\n long generationsBlockNumber = Long.parseLong(line[GENERATIONS_BLOCK_NUMBER_PARTIAL_TIMES_HEADER_INDEX]);\r\n PhaseType phaseType = PhaseType.valueOf(line[PHASE_TYPE_PARTIAL_TIMES_HEADER_INDEX]);\r\n PartialTimeKey.Type partialTimeType = PartialTimeKey.Type.valueOf(line[TYPE_PARTIAL_TIMES_HEADER_INDEX]);\r\n long time = Long.parseLong(line[TIME_PARTIAL_TIMES_HEADER_INDEX]);\r\n\r\n // Adds the time.\r\n this.addPartialTime(islandNumber, generationsBlockNumber, phaseType, partialTimeType, time);\r\n }\r\n }\r\n\r\n public void writePartialTimesToFile(Path outputFilePath, FileSystem fileSystem) throws IOException {\r\n // Creates the file and the writer.\r\n FSDataOutputStream fileOutputStream = fileSystem.create(outputFilePath, true);\r\n BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));\r\n CSVWriter fileWriter = new CSVWriter(bufferedWriter);\r\n\r\n // Writes partial times.\r\n for (Map.Entry<PartialTimeKey, Long> mapEntry : partialTimesMap.entrySet()) {\r\n PartialTimeKey partialTimeKey = mapEntry.getKey();\r\n long time = mapEntry.getValue();\r\n this.writeNextPartialTimeToFileWriter(partialTimeKey, time, fileWriter);\r\n }\r\n\r\n // Finalises the file.\r\n fileWriter.close();\r\n }\r\n\r\n private void writeNextPartialTimeToFileWriter(PartialTimeKey partialTimeKey, long time, CSVWriter fileWriter) {\r\n String[] line = {\r\n Integer.toString(partialTimeKey.islandNumber),\r\n Long.toString(partialTimeKey.generationsBlockNumber),\r\n partialTimeKey.phaseType.name(),\r\n partialTimeKey.type.name(),\r\n Long.toString(time)\r\n };\r\n\r\n fileWriter.writeNext(line);\r\n }\r\n\r\n public void joinPartialTimes(int islandNumber, long generationsBlockNumber) {\r\n for (PhaseType phaseType : PhaseType.values()) {\r\n PartialTimeKey startPartialTime =\r\n new PartialTimeKey(islandNumber, generationsBlockNumber, phaseType, PartialTimeKey.Type.START);\r\n PartialTimeKey finishPartialTime =\r\n new PartialTimeKey(islandNumber, generationsBlockNumber, phaseType, PartialTimeKey.Type.FINISH);\r\n\r\n if (this.partialTimesMap.containsKey(startPartialTime) &&\r\n this.partialTimesMap.containsKey(startPartialTime)) {\r\n long startTime = this.partialTimesMap.get(startPartialTime);\r\n long finishTime = this.partialTimesMap.get(finishPartialTime);\r\n writeTime(islandNumber, generationsBlockNumber, phaseType, startTime, finishTime);\r\n }\r\n }\r\n }\r\n}\r",
"public abstract class FitnessValue\r\n implements Comparable<FitnessValue> {\r\n\r\n public FitnessValue() {\r\n }\r\n\r\n /**\r\n * <p>\r\n * Compares the current fitness value with another. Pay attention to control\r\n * if the value is null.\r\n * </p>\r\n */\r\n @Override\r\n public abstract int compareTo(FitnessValue other);\r\n\r\n /**\r\n * <p>\r\n * Clones the fitness value.\r\n * </p>\r\n */\r\n @Override\r\n public abstract Object clone() throws CloneNotSupportedException;\r\n\r\n /**\r\n * <p>\r\n * Retrieves the unique hash code of the object.\r\n * </p>\r\n */\r\n @Override\r\n public abstract int hashCode();\r\n\r\n}",
"public abstract class Individual implements Cloneable {\r\n\r\n /**\r\n * <p>\r\n * Clones the fitness value.\r\n * </p>\r\n */\r\n @Override\r\n public abstract Object clone() throws CloneNotSupportedException;\r\n\r\n /**\r\n * <p>\r\n * Retrieves the unique hash code of the object.\r\n * </p>\r\n */\r\n @Override\r\n public abstract int hashCode();\r\n\r\n}"
] | import it.unisa.elephant56.core.Constants;
import it.unisa.elephant56.core.common.IndividualWrapper;
import it.unisa.elephant56.core.common.Properties;
import it.unisa.elephant56.core.reporter.individual.IndividualReporter;
import it.unisa.elephant56.core.reporter.time.GeneticOperatorsTimeReporter;
import it.unisa.elephant56.core.reporter.time.MapReduceTimeReporter;
import it.unisa.elephant56.user.common.FitnessValue;
import it.unisa.elephant56.user.common.Individual;
import it.unisa.elephant56.user.operators.*;
import org.apache.avro.mapred.AvroKey;
import org.apache.avro.mapreduce.AvroMultipleOutputs;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
| package it.unisa.elephant56.core.generator;
public class GridReducer
extends Reducer<AvroKey<IndividualWrapper<Individual, FitnessValue>>, IntWritable,
AvroKey<IndividualWrapper<Individual, FitnessValue>>, NullWritable> {
// GenerationsExecutor object.
private GridDistributedSecondaryGenerationsBlockExecutor generationsBlockExecutor;
// Configuration object.
private Configuration configuration;
// Configuration variables.
private boolean isTimeReporterActive;
private GeneticOperatorsTimeReporter geneticOperatorsTimeReporter;
private MapReduceTimeReporter mapreduceTimeReporter;
private Path mapreduceReducerPartialTimeReportFilePath;
private boolean isIndividualReporterActive;
| private IndividualReporter individualReporter;
| 3 |
shaunlebron/flex-fov | src/main/java/mod/render360/coretransform/classtransformers/GuiOptionsTransformer.java | [
"public class ClassName {\n\n private final String deobfuscatedName;\n private final String obfuscatedName;\n\n public ClassName(String deobfuscatedName, String obfuscatedName) {\n this.deobfuscatedName = deobfuscatedName;\n this.obfuscatedName = obfuscatedName;\n }\n\n public String getName() {\n return getName(CoreLoader.isObfuscated);\n }\n\n public String getName(boolean obfuscated) {\n if (obfuscated) {\n return obfuscatedName;\n } else {\n return deobfuscatedName;\n }\n }\n\n /**\n * See {@link org.objectweb.asm.Type#getInternalName Type.getInternalName()}\n */\n public String getInternalName() {\n return getInternalName(CoreLoader.isObfuscated);\n }\n\n /**\n * See {@link org.objectweb.asm.Type#getInternalName Type.getInternalName()}\n */\n public String getInternalName(boolean obfuscated) {\n if (obfuscated) {\n return obfuscatedName;\n } else {\n return deobfuscatedName.replace('.', '/');\n }\n }\n\n //TODO comment\n public String getNameAsDesc() {\n return \"L\" + getInternalName(CoreLoader.isObfuscated) + \";\";\n }\n\n //TODO comment\n public String getNameAsDesc(boolean obfuscated) {\n return \"L\" + getInternalName(obfuscated) + \";\";\n }\n\n public String all() {\n return deobfuscatedName + \" \" + obfuscatedName;\n }\n}",
"public class MethodName {\n\n private final String deobfuscatedName;\n private final String obfuscatedNameFull;\n private final String obfuscatedNameShort;\n private final String deobfuscatedDesc;\n private final String obfuscatedDesc;\n\n public MethodName(String deobfuscatedName, String obfuscatedNameFull, String obfuscatedNameShort,\n String deobfuscatedDesc, String obfuscatedDesc) {\n this.deobfuscatedName = deobfuscatedName;\n this.obfuscatedNameFull = obfuscatedNameFull;\n this.obfuscatedNameShort = obfuscatedNameShort;\n this.deobfuscatedDesc = deobfuscatedDesc;\n this.obfuscatedDesc = obfuscatedDesc;\n }\n\n public String getShortName() {\n return getShortName(CoreLoader.isObfuscated);\n }\n\n public String getShortName(boolean obfuscated) {\n if (obfuscated) {\n return obfuscatedNameShort;\n } else {\n return deobfuscatedName;\n }\n }\n\n public String getFullName() {\n return getFullName(CoreLoader.isObfuscated);\n }\n\n public String getFullName(boolean obfuscated) {\n if (obfuscated) {\n return obfuscatedNameFull;\n } else {\n return deobfuscatedName;\n }\n }\n\n public String getDesc() {\n return getDesc(CoreLoader.isObfuscated);\n }\n\n public String getDesc(boolean obfuscated) {\n if (obfuscated) {\n return obfuscatedDesc;\n } else {\n return deobfuscatedDesc;\n }\n }\n\n public String all() {\n return deobfuscatedName + deobfuscatedDesc + \" \" + obfuscatedNameShort + obfuscatedDesc + \" \" + obfuscatedNameFull;\n }\n}",
"public class Names {\n\n public static final ClassName EntityRenderer = new ClassName(\"net.minecraft.client.renderer.EntityRenderer\", \"bqc\");\n public static final MethodName EntityRenderer_getFOVModifier = new MethodName(\"getFOVModifier\", \"func_78481_a\", \"a\", \"(FZ)F\", \"(FZ)F\");\n public static final MethodName EntityRenderer_hurtCameraEffect = new MethodName(\"hurtCameraEffect\", \"func_78482_e\", \"d\", \"(F)V\", \"(F)V\");\n public static final MethodName EntityRenderer_orientCamera = new MethodName(\"orientCamera\", \"func_78467_g\", \"f\", \"(F)V\", \"(F)V\");\n public static final MethodName EntityRenderer_setupCameraTransform = new MethodName(\"setupCameraTransform\", \"func_78479_a\", \"a\", \"(FI)V\", \"(FI)V\");\n public static final MethodName EntityRenderer_updateCameraAndRender = new MethodName(\"updateCameraAndRender\", \"func_181560_a\", \"a\", \"(FJ)V\", \"(FJ)V\");\n public static final MethodName EntityRenderer_renderWorld = new MethodName(\"renderWorld\", \"func_78471_a\", \"b\", \"(FJ)V\", \"(FJ)V\");\n public static final MethodName EntityRenderer_renderWorldPass = new MethodName(\"renderWorldPass\", \"func_175068_a\", \"a\", \"(IFJ)V\", \"(IFJ)V\");\n public static final MethodName EntityRenderer_updateFogColor = new MethodName(\"updateFogColor\", \"func_78466_h\", \"h\", \"(F)V\", \"(F)V\");\n public static final MethodName EntityRenderer_drawNameplate = new MethodName(\"drawNameplate\", \"func_189692_a\", \"a\", \"(Lnet/minecraft/client/gui/FontRenderer;Ljava/lang/String;FFFIFFZZ)V\", \"(Lbfe;Ljava/lang/String;FFFIFFZZ)V\");\n public static final FieldName EntityRenderer_mc = new FieldName(\"mc\", \"field_78531_r\", \"h\", \"Lnet/minecraft/client/Minecraft;\", \"Lbeq;\");\n\n public static final FieldName GameSettings_saveOptions = new FieldName(\"saveOptions\", \"func_74303_b\", \"b\", \"()V\", \"()V\");\n\n public static final MethodName GlStateManager_loadIdentity = new MethodName(\"loadIdentity\", \"func_179096_D\", \"F\", \"()V\", \"()V\");\n\n public static final ClassName GuiButton = new ClassName(\"net.minecraft.client.gui.GuiButton\", \"bfk\");\n public static final FieldName GuiButton_id = new FieldName(\"id\", \"field_146127_k\", \"k\", \"I\", \"I\");\n\n public static final ClassName GuiOptions = new ClassName(\"net.minecraft.client.gui.GuiOptions\", \"bhg\");\n public static final MethodName GuiOptions_initGui = new MethodName(\"initGui\", \"func_73866_w_\", \"b\", \"()V\", \"()V\");\n public static final MethodName GuiOptions_actionPerformed = new MethodName(\"actionPerformed\", \"func_146284_a\", \"a\", \"(Lnet/minecraft/client/gui/GuiButton;)V\", \"(Lbfk;)V\");\n\n public static final ClassName GuiScreen = new ClassName(\"net.minecraft.client.gui.GuiScreen\", \"bhm\");\n public static final MethodName GuiScreen_drawWorldBackground = new MethodName(\"drawWorldBackground\", \"func_146270_b\", \"d_\", \"(I)V\", \"(I)V\");\n public static final MethodName GuiScreen_drawBackground = new MethodName(\"drawBackground\", \"func_146278_c\", \"c\", \"(I)V\", \"(I)V\");\n public static final FieldName GuiScreen_buttonList = new FieldName(\"buttonList\", \"field_146292_n\", \"n\", \"Ljava/util/List;\", \"Ljava/util/List;\");\n public static final FieldName GuiScreen_width = new FieldName(\"width\", \"field_146294_l\", \"l\", \"I\", \"I\");\n public static final FieldName GuiScreen_height = new FieldName(\"height\", \"field_146295_m\", \"m\", \"I\", \"I\");\n public static final FieldName GuiScreen_mc = new FieldName(\"mc\", \"field_146297_k\", \"j\", \"Lnet/minecraft/client/Minecraft;\", \"Lbeq;\");\n\n public static final ClassName LoadingScreenRenderer = new ClassName(\"net.minecraft.client.LoadingScreenRenderer\", \"bet\");\n public static final MethodName LoadingScreenRenderer_setLoadingProgress = new MethodName(\"setLoadingProgress\", \"func_73718_a\", \"a\", \"(I)V\", \"(I)V\");\n public static final FieldName LoadingScreenRenderer_mc = new FieldName(\"mc\", \"field_73725_b\", \"b\", \"Lnet/minecraft/client/Minecraft;\", \"Lbeq;\");\n public static final FieldName LoadingScreenRenderer_framebuffer = new FieldName(\"framebuffer\", \"field_146588_g\", \"g\", \"Lnet/minecraft/client/shader/Framebuffer;\", \"Lbqp;\");\n\n public static final ClassName Minecraft = new ClassName(\"net.minecraft.client.Minecraft\", \"beq\");\n public static final MethodName Minecraft_loadWorld = new MethodName(\"loadWorld\", \"func_71353_a\", \"a\", \"(Lnet/minecraft/client/multiplayer/WorldClient;Ljava/lang/String;)V\", \"(Lbno;Ljava/lang/String;)V\");\n public static final MethodName Minecraft_displayGuiScreen = new MethodName(\"displayGuiScreen\", \"func_147108_a\", \"a\", \"(Lnet/minecraft/client/gui/GuiScreen;)V\", \"(Lbhm;)V\");\n public static final FieldName Minecraft_currentScreen = new FieldName(\"currentScreen\", \"field_71462_r\", \"m\", \"Lnet/minecraft/client/gui/GuiScreen;\", \"Lbhm;\");\n public static final FieldName Minecraft_gameSettings = new FieldName(\"gameSettings\", \"field_71474_y\", \"u\", \"Lnet/minecraft/client/settings/GameSettings;\", \"Lbes;\");\n\n public static final ClassName Barrier = new ClassName(\"net.minecraft.client.particle.Barrier\", \"bnx\");\n public static final ClassName ParticleBreaking = new ClassName(\"net.minecraft.client.particle.ParticleBreaking\", \"bny\");\n public static final ClassName ParticleDigging = new ClassName(\"net.minecraft.client.particle.ParticleDigging\", \"bph\");\n public static final ClassName ParticleExplosionLarge = new ClassName(\"net.minecraft.client.particle.ParticleExplosionLarge\", \"bol\");\n public static final ClassName ParticleSweepAttack = new ClassName(\"net.minecraft.client.particle.ParticleSweepAttack\", \"bnw\");\n public static final ClassName Particle = new ClassName(\"net.minecraft.client.particle.Particle\", \"bos\");\n public static final MethodName Particle_renderParticle = new MethodName(\"renderParticle\", \"func_180434_a\", \"a\", \"(Lnet/minecraft/client/renderer/VertexBuffer;Lnet/minecraft/entity/Entity;FFFFFF)V\", \"(Lbpw;Lsm;FFFFFF)V\");\n\n}",
"public class CLTLog\n{\n\tpublic static final Logger logger = LogManager.getLogger(\"Render360-CLT\");\n\n\tpublic static void info(String s)\n\t{\n\t\tlogger.info(s);\n\t}\n\t\n\tpublic static <T> void info(T s) {\n\t\tlogger.info(s.toString());\n\t}\n}",
"@IFMLLoadingPlugin.MCVersion(\"1.11\")\[email protected](value = \"mod.render360.coretransform.\")\[email protected](CoreLoader.NAME)\[email protected](value = 999)\npublic class CoreLoader implements IFMLLoadingPlugin {\n\t\n\tpublic static final String NAME = \"Render 360\";\n\tpublic static boolean isObfuscated = false;\n\t\n\t@Override\n\tpublic String[] getASMTransformerClass() {\n\t\treturn new String[]{CoreTransformer.class.getName()};\n\t}\n\n\t@Override\n\tpublic String getModContainerClass() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic String getSetupClass() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void injectData(Map<String, Object> data) {\n\t\tisObfuscated = (Boolean) data.get(\"runtimeDeobfuscationEnabled\");\n\t}\n\n\t@Override\n\tpublic String getAccessTransformerClass() {\n\t\treturn null;\n\t}\n\n}",
"public class RenderUtil {\n\n\t/**Enables or disables 360 degree rendering.*/\n\tpublic static boolean render360 = true;\n\n\t/**The current render method.*/\n\tpublic static RenderMethod renderMethod = new Standard();\n\t/**The index of the current render method.*/\n\tpublic static int index = 0;\n\n\t/**Used to check if the screen was resized.*/\n\tprivate static int width = 0;\n\t/**Used to check if the screen was resized.*/\n\tprivate static int height = 0;\n\t/**Used for rendering multiple times*/ //TODO remove\n\tpublic static int partialWidth = 0;\n\tpublic static int partialHeight = 0;\n\n\tpublic static float rotation = 0;\n\n\t/**The 360 degree shader.*/\n\tprivate static Shader shader = null;\n\t/**The secondary framebuffer used to render the world in 360 degrees.*/\n\tprivate static Framebuffer framebuffer = null;\n\tprivate static int[] framebufferTextures = new int[6];\n\n\t/**Reload the framebuffer and shader.*/\n\tprivate static boolean forceReload = false;\n\n\t/**Reload the framebuffer and shader.*/\n\tpublic static void forceReload() {\n\t\tforceReload = true;\n\t}\n\n\t/**\n\t * Checks if shader exists before creating it.\n\t */\n\tprivate static void createShader() {\n\t\tif (shader == null) {\n\t\t\tshader = new Shader();\n\t\t\tshader.createShaderProgram(renderMethod);\n\t\t} else {\n\t\t\tCLTLog.info(\"Attemped to re-create existing shader\");\n\t\t}\n\t}\n\n\t/**\n\t * Checks to see if the shader exists before deleting it.\n\t */\n\tprivate static void deleteShader() {\n\t\tif (shader != null) {\n\t\t\tshader.deleteShaderProgram();\n\t\t\tshader = null;\n\t\t} else {\n\t\t\tCLTLog.info(\"Attemped to delete non-existent shader\");\n\t\t}\n\t}\n\n\t/**\n\t * Create or delete shader and secondary framebuffer.<br>\n\t * Called from asm modified code on world load and unload.\n\t * @param worldClient used to detect if the world is being loaded or unloaded.\n\t */\n\tpublic static void onWorldLoad(WorldClient worldClient) {\n\t\tif (worldClient != null) {\n\t\t\tif (framebuffer == null) {\n\t\t\t\t//The actual numbers don't matter, they are reset later.\n\t\t\t\tframebuffer = new Framebuffer((int)(Display.getHeight()*renderMethod.getQuality()),\n\t\t\t\t\t\t(int)(Display.getHeight()*renderMethod.getQuality()), true);\n\t\t\t\t//create 6 new textures\n\t\t\t\tfor (int i = 0; i < framebufferTextures.length; i++) {\n\t\t\t\t\tframebufferTextures[i] = TextureUtil.glGenTextures();\n\t\t\t\t\tGlStateManager.bindTexture(framebufferTextures[i]);\n\t\t\t\t\tGlStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8,\n\t\t\t\t\t\t\tframebuffer.framebufferTextureWidth, framebuffer.framebufferTextureHeight,\n\t\t\t\t\t\t\t0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, null);\n\t\t\t\t\tGlStateManager.bindTexture(framebufferTextures[i]);\n\t\t GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);\n\t\t GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);\n\t\t GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);\n\t\t GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);\n\t\t\t\t}\n\t\t\t\tGlStateManager.bindTexture(0);\n\t\t\t} else {\n\t\t\t\tCLTLog.info(\"Attempted to recreate existing framebuffer\");\n\t\t\t}\n\t\t\tcreateShader();\n\t\t} else {\n\t\t\tdeleteShader();\n\t\t\tif (framebuffer != null) {\n\t\t\t\t//delete textures\n\t\t\t\tfor (int i = 0; i < framebufferTextures.length; i++) {\n\t\t\t\t\tTextureUtil.deleteTexture(framebufferTextures[i]);\n\t\t\t\t\tframebufferTextures[i] = -1;\n\t\t\t\t}\n\t\t\t\tframebuffer.deleteFramebuffer();\n\t\t\t\tframebuffer = null;\n\t\t\t} else {\n\t\t\t\tCLTLog.info(\"Attempted to delete non-existant framebuffer\");\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Render the world. Called from asm modified code.\n\t * @param er\n\t * @param mc\n\t * @param partialTicks\n\t * @param finishTimeNano\n\t */\n\tpublic static void setupRenderWorld(EntityRenderer er, Minecraft mc, float partialTicks, long finishTimeNano) {\n\n\t\t//reload the framebuffer and shader\n\t\tif (forceReload || width != mc.displayWidth || height != mc.displayHeight) {\n\t\t\tforceReload = false;\n\t\t\twidth = mc.displayWidth;\n\t\t\theight = mc.displayHeight;\n\t\t\t//delete textures\n\t\t\tfor (int i = 0; i < framebufferTextures.length; i++) {\n\t\t\t\tTextureUtil.deleteTexture(framebufferTextures[i]);\n\t\t\t\tframebufferTextures[i] = -1;\n\t\t\t}\n\t\t\t//recreate framebuffer with the new size\n\t\t\tframebuffer.deleteFramebuffer();\n\t\t\t//height is listed twice for an aspect ratio of 1:1\n\t\t\tframebuffer = new Framebuffer((int)(height*renderMethod.getQuality()), (int)(height*renderMethod.getQuality()), true);\n\t\t\tdeleteShader();\n\t\t\tcreateShader();\n\t\t\t//create 6 new textures\n\t\t\tfor (int i = 0; i < framebufferTextures.length; i++) {\n\t\t\t\tframebufferTextures[i] = TextureUtil.glGenTextures();\n\t\t\t\tGlStateManager.bindTexture(framebufferTextures[i]);\n\t\t\t\tGlStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8,\n\t\t\t\t\t\tframebuffer.framebufferTextureWidth, framebuffer.framebufferTextureHeight,\n\t\t\t\t\t\t0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, null);\n\t\t\t\tGlStateManager.bindTexture(framebufferTextures[i]);\n\t\t\t\tGlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);\n\t GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);\n\t GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);\n\t GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);\n\t\t\t}\n\t\t\tGlStateManager.bindTexture(0);\n\t\t}\n\n\t\trenderMethod.renderWorld(er, mc, framebuffer, shader, framebufferTextures, partialTicks, finishTimeNano, width, height, renderMethod.getQuality());\n\t}\n\n\t/**\n\t * Called from asm modified code\n\t * {@link net.minecraft.client.renderer.EntityRenderer#setupCameraTransform(float, int) setupCameraTransform}\n\t */\n\tpublic static void rotateCamera() {\n\t\tif (renderMethod.coordFrame != null) {\n\t\t\tGlStateManager.multMatrix(renderMethod.coordFrame);\n\t\t}\n\t}\n\n\t/**\n\t * Called from asm modified code\n\t * {@link net.minecraft.client.renderer.EntityRenderer#setupCameraTransform(float, int) setupCameraTransform}\n\t */\n\tpublic static void rotatePlayer() {\n\t\t// to prevent bad culling, we have to do this after orientCamera\n\t\tEntity player = renderMethod.player;\n\t\tfloat deltaYaw = renderMethod.playerDeltaYaw;\n\t\tfloat deltaPitch = renderMethod.playerDeltaPitch;\n\t\tif (player != null) {\n\t\t\tplayer.rotationYaw += deltaYaw;\n\t\t\tplayer.prevRotationYaw += deltaYaw;\n\t\t\tplayer.rotationPitch += deltaPitch;\n\t\t\tplayer.prevRotationPitch += deltaPitch;\n\t\t}\n\t}\n\n\t/**\n\t * Called from asm modified code\n\t * {@link net.minecraft.client.renderer.EntityRenderer#updateCameraAndRender(float, long) updateCameraAndRender}\n\t */\n\tpublic static void renderGuiStart() {\n\t\tif (renderMethod.getResizeGui()) {\n\t\t\tMinecraft mc = Minecraft.getMinecraft();\n\t\t\tframebuffer.bindFramebuffer(false);\n\t\t\tGlStateManager.viewport(0, 0, (int) (mc.displayHeight*renderMethod.getQuality()), (int) (mc.displayHeight*renderMethod.getQuality()));\n\t\t\tOpenGlHelper.glFramebufferTexture2D(OpenGlHelper.GL_FRAMEBUFFER, OpenGlHelper.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, framebufferTextures[0], 0);\n\t\t\tGlStateManager.bindTexture(0);\n\t\t}\n\t}\n\n\t/**\n\t * Called from asm modified code\n\t * {@link net.minecraft.client.renderer.EntityRenderer#updateCameraAndRender(float, long) updateCameraAndRender}\n\t */\n\tpublic static void renderGuiEnd() {\n\t\tif (renderMethod.getResizeGui()) {\n\t\t\tMinecraft mc = Minecraft.getMinecraft();\n\t\t\tif (!Mouse.isGrabbed()) {\n\t\t\t\tGL20.glUseProgram(shader.getShaderProgram());\n\t\t\t\tint angleUniform = GL20.glGetUniformLocation(shader.getShaderProgram(), \"cursorPos\");\n\t\t\t\tGL20.glUniform2f(angleUniform, Mouse.getX()/(float)mc.displayWidth, Mouse.getY()/(float)mc.displayHeight);\n\t\t\t\tint cursorUniform = GL20.glGetUniformLocation(shader.getShaderProgram(), \"drawCursor\");\n\t\t\t\tGL20.glUniform1i(cursorUniform, 1);\n\t\t\t\tGL20.glUseProgram(0);\n\t\t\t} else {\n\t\t\t\tGL20.glUseProgram(shader.getShaderProgram());\n\t\t\t\tint cursorUniform = GL20.glGetUniformLocation(shader.getShaderProgram(), \"drawCursor\");\n\t\t\t\tGL20.glUniform1i(cursorUniform, 0);\n\t\t\t\tGL20.glUseProgram(0);\n\t\t\t}\n\t\t\tmc.getFramebuffer().bindFramebuffer(false);\n\t\t\tGlStateManager.viewport(0, 0, mc.displayWidth, mc.displayHeight);\n\t\t\t//if not in menu or inventory\n\t\t\tif (mc.currentScreen == null) {\n\t\t\t\trenderMethod.runShader(mc, shader, framebufferTextures);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Called from asm modified code\n\t * {@link net.minecraft.client.renderer.EntityRenderer#updateCameraAndRender(float, long) updateCameraAndRender}\n\t */\n\tpublic static void renderGuiStart2() {\n\t\tif (renderMethod.getResizeGui()) {\n\t\t\tMinecraft mc = Minecraft.getMinecraft();\n\t\t\tif (mc.theWorld != null) {\n\t\t\t\tframebuffer.bindFramebuffer(false);\n\t\t\t\tGlStateManager.viewport(0, 0, (int) (mc.displayHeight*renderMethod.getQuality()), (int) (mc.displayHeight*renderMethod.getQuality()));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Called from asm modified code\n\t * {@link net.minecraft.client.renderer.EntityRenderer#updateCameraAndRender(float, long) updateCameraAndRender}\n\t */\n\tpublic static void renderGuiEnd2() {\n\t\tif (renderMethod.getResizeGui()) {\n\t\t\tMinecraft mc = Minecraft.getMinecraft();\n\t\t\tif (mc.theWorld != null) {\n\t\t\t\tmc.getFramebuffer().bindFramebuffer(false);\n\t\t\t\tGlStateManager.viewport(0, 0, mc.displayWidth, mc.displayHeight);\n\t\t\t\trenderMethod.runShader(mc, shader, framebufferTextures);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Called from asm modified code\n\t * {@link net.minecraft.client.renderer.EntityRenderer#drawNameplate(float, long) drawNameplate}\n\t */\n\tpublic static float setViewerYaw(float x, float z) {\n\t\tfloat yaw = (float) -(Math.atan(x/z)*180/Math.PI);\n\t\tif (z < 0) {\n\t\t\tyaw += 180;\n\t\t}\n\t\treturn yaw;\n\t}\n\n\t/**\n\t * Called from asm modified code\n\t * {@link net.minecraft.client.renderer.EntityRenderer#drawNameplate(float, long) drawNameplate}\n\t */\n\tpublic static float setViewerPitch(float x, float y, float z) {\n\t\tfloat distance = (float) (Math.sqrt(x*x + z*z));\n\t\tfloat pitch = (float) -(Math.atan((y-Minecraft.getMinecraft().getRenderViewEntity().height)/distance)*180/Math.PI);\n\t\treturn pitch;\n\t}\n}",
"public class Render360Settings extends GuiScreen {\r\n\r\n\tprivate final GuiScreen parentGuiScreen;\r\n\tpublic static final String screenTitle = \"Render 360 Settings\";\r\n\t\r\n\t//Load options from file. Run only once.\r\n\t/*static {\r\n\t\tFile optionsFile = new File(\"optionsRender360.txt\");\r\n\t\ttry {\r\n\t\t\tList<String> options = Files.readAllLines(Paths.get(\"optionsRender360.txt\"));\r\n\t\t\t//TODO actually read\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}*/\r\n\r\n\tpublic Render360Settings(GuiScreen parentScreenIn)\r\n\t{\r\n\t\tthis.parentGuiScreen = parentScreenIn;\r\n\t}\r\n\r\n\t/**\r\n\t * Adds the buttons (and other controls) to the screen in question. Called when the GUI is displayed and when the\r\n\t * window resizes, the buttonList is cleared beforehand.\r\n\t */\r\n\t@Override\r\n\tpublic void initGui() {\r\n\t\tsuper.buttonList.add(new GuiButton(18100, super.width / 2 - 100, super.height / 6 - 12, 200, 20, \"Render Mode: \" + RenderUtil.renderMethod.getName()));\r\n\t\tRenderUtil.renderMethod.addButtonsToGui(buttonList, width, height);\r\n\t\tsuper.buttonList.add(new GuiButton(200, super.width / 2 - 100, super.height / 6 + 168, I18n.format(\"gui.done\", new Object[0])));\r\n\t}\r\n\r\n\t/**\r\n\t * Called by the controls from the buttonList when activated. (Mouse pressed for buttons)\r\n\t */\r\n\t@Override\r\n\tprotected void actionPerformed(GuiButton button) throws IOException\r\n\t{\r\n\t\tif (button.enabled)\r\n\t\t{\r\n\t\t\t//Render Mode\r\n\t\t\tif (button.id == 18100)\r\n\t\t\t{\r\n\t\t\t\tRenderUtil.index = RenderMethod.getNextIndex(RenderUtil.index);\r\n\t\t\t\tRenderUtil.renderMethod = RenderMethod.getRenderMethod(RenderUtil.index);\r\n\t\t\t\tRenderUtil.forceReload();\r\n\t\t\t\tbutton.displayString = \"Render Mode: \" + RenderUtil.renderMethod.getName();\r\n\t\t\t\t//update buttons\r\n\t\t\t\tthis.mc.displayGuiScreen(new Render360Settings(this.parentGuiScreen));\r\n\t\t\t}\r\n\t\t\t//Done\r\n\t\t\telse if (button.id == 200)\r\n\t\t\t{\r\n\t\t\t\tthis.mc.displayGuiScreen(this.parentGuiScreen);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tRenderUtil.renderMethod.onButtonPress(button);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Draws the screen and all the components in it.\r\n\t */\r\n\t@Override\r\n\tpublic void drawScreen(int mouseX, int mouseY, float partialTicks) {\r\n\t\tsuper.drawDefaultBackground();\r\n\t\tthis.drawCenteredString(super.fontRendererObj, this.screenTitle, this.width / 2, 15, 0xFFFFFF);\r\n\t\tsuper.drawScreen(mouseX, mouseY, partialTicks);\r\n\t}\r\n}\r"
] | import static org.objectweb.asm.Opcodes.*;
import mod.render360.coretransform.classtransformers.name.ClassName;
import mod.render360.coretransform.classtransformers.name.MethodName;
import mod.render360.coretransform.classtransformers.name.Names;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import mod.render360.coretransform.CLTLog;
import mod.render360.coretransform.CoreLoader;
import mod.render360.coretransform.RenderUtil;
import mod.render360.coretransform.gui.Render360Settings;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiCustomizeSkin;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiVideoSettings;
import net.minecraft.client.settings.GameSettings;
| package mod.render360.coretransform.classtransformers;
public class GuiOptionsTransformer extends ClassTransformer {
@Override
public ClassName getName() {
return Names.GuiOptions;
}
@Override
public MethodTransformer[] getMethodTransformers() {
MethodTransformer transformInitGui = new MethodTransformer() {
@Override
public MethodName getName() {
return Names.GuiOptions_initGui;
}
@Override
public void transform(ClassNode classNode, MethodNode method, boolean obfuscated) {
| CLTLog.info("Found method: " + method.name + " " + method.desc);
| 3 |
jskcse4/FreeTamilEBooks | src/com/jskaleel/fte/home/BooksHomeAdapter.java | [
"public class FTEApplication extends Application {\n\t\n\t public static final String TAG = FTEApplication.class.getSimpleName();\n\t\n\tprivate static FTEApplication mInstance;\n\tprivate static Context mAppContext;\n\n\tprivate RequestQueue mRequestQueue;\n\tprivate static ImageLoader mImageLoader;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\tmInstance = this;\n\n\t\tthis.setAppContext(getApplicationContext());\n\t}\n\n\tpublic static FTEApplication getInstance(){\n\t\treturn mInstance;\n\t}\n\n\tpublic static Context getAppContext() {\n\t\treturn mAppContext;\n\t}\n\n\tpublic void setAppContext(Context mAppContext) {\n\t\tFTEApplication.mAppContext = mAppContext;\n\t}\n\n\tpublic RequestQueue getRequestQueue(){\n\t\tif (mRequestQueue == null) {\n\t\t\tmRequestQueue = Volley.newRequestQueue(getApplicationContext());\n\t\t}\n\t\treturn this.mRequestQueue;\n\t}\n\n\tpublic ImageLoader getImageLoader(){\n\t\tgetRequestQueue();\n\t\tif (mImageLoader == null) {\n\t\t\tmImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());\n\t\t}\n\t\treturn FTEApplication.mImageLoader;\n\t}\n\n\tpublic <T> void addToRequestQueue(Request<T> req, String tag) {\n // set the default tag if tag is empty\n req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);\n getRequestQueue().add(req);\n }\n \n public <T> void addToRequestQueue(Request<T> req) {\n req.setTag(TAG);\n getRequestQueue().add(req);\n }\n \n public void cancelPendingRequests(Object tag) {\n if (mRequestQueue != null) {\n mRequestQueue.cancelAll(tag);\n }\n }\n\n}",
"public class FTEDevice extends Application {\r\n\t\r\n//\tpublic static boolean GTE_GB_9 \t\t= false;\r\n//\tpublic static boolean GTE_GB_10\t\t= false;\r\n\t\r\n\tpublic static boolean GTE_HC_11\t\t= false;\r\n//\tpublic static boolean GTE_HC_12\t\t= false;\r\n//\tpublic static boolean GTE_HC_13\t\t= false;\r\n\t\r\n//\tpublic static boolean GTE_ICS_14\t\t= false;\r\n//\tpublic static boolean GTE_ICS_15\t\t= false;\r\n\t\r\n//\tpublic static boolean GTE_JB_16\t\t= false;\r\n//\tpublic static boolean GTE_JB_17\t\t= false;\r\n//\tpublic static boolean GTE_JB_18\t\t= false;\r\n\r\n\t\r\n//\tpublic static boolean PRE_GB_9 \t\t= false;\r\n//\tpublic static boolean PRE_GB_10\t\t= false;\r\n\t\r\n\tpublic static boolean PRE_HC_11\t\t= false;\r\n//\tpublic static boolean PRE_HC_12\t\t= false;\r\n//\tpublic static boolean PRE_HC_13\t\t= false;\r\n\r\n\tprivate static AppPreference mUserPrefrence;\r\n\t\r\n//\tpublic static boolean PRE_ICS_14\t\t= false;\r\n//\tpublic static boolean PRE_ICS_15\t\t= false;\r\n\t\r\n//\tpublic static boolean PRE_JB_16\t\t= false;\r\n//\tpublic static boolean PRE_JB_17\t\t= false;\r\n//\tpublic static boolean PRE_JB_18\t\t= false;\r\n\t\r\n\tstatic {\r\n\t\tint version = Build.VERSION.SDK_INT;\r\n\t\t\r\n/*\t\t//2.3.3 to 2.3.7 api level 9 mr1 = 10\r\n\t\tif(version >= VERSION_CODES.GINGERBREAD)\r\n\t\t\tGTE_GB_9 = true;\r\n\t\telse \r\n\t\t\tPRE_GB_9 = true;\r\n\r\n\t\tif(version >= VERSION_CODES.GINGERBREAD_MR1)\r\n\t\t\tGTE_GB_10 = true;\r\n\t\telse \r\n\t\t\tPRE_GB_10 = true;*/\r\n\t\t\r\n\t\t//3.2 api level 11, mr1=12,mr2=13\r\n\t\tif(version >= VERSION_CODES.HONEYCOMB)\r\n\t\t\tGTE_HC_11 = true;\r\n\t\telse\r\n\t\t\tPRE_HC_11 = true;\r\n\t\t\r\n\t\t/*if(version >= VERSION_CODES.HONEYCOMB_MR1)\r\n\t\t\tGTE_HC_12 = true;\r\n\t\telse\r\n\t\t\tPRE_HC_12 = true;\r\n\r\n\t\tif(version >= VERSION_CODES.HONEYCOMB_MR2)\r\n\t\t\tGTE_HC_13 = true;\r\n\t\telse\r\n\t\t\tPRE_HC_13 = true;\r\n\t\r\n\t\t//4.0.3 to 4.0.4 api level 14, mr1=15\r\n\t\tif(version >= VERSION_CODES.ICE_CREAM_SANDWICH)\r\n\t\t\tGTE_ICS_14 = true;\r\n\t\telse\r\n\t\t\tPRE_ICS_14 = true;\r\n\t\t\r\n\t\tif(version >= VERSION_CODES.ICE_CREAM_SANDWICH_MR1)\r\n\t\t\tGTE_ICS_15 = true;\r\n\t\telse\r\n\t\t\tPRE_ICS_15 = true;\r\n\t\t\r\n\t\t//4.1.x ,4.2.x ,4.3.x api level 16, mr1 =17, mr2 =18\r\n\t\tif(version>= VERSION_CODES.JELLY_BEAN)\r\n\t\t\tGTE_JB_16 = true;\r\n\t\telse\r\n\t\t\tPRE_JB_16 = true;\r\n\t\t\r\n\t\tif(version>= VERSION_CODES.JELLY_BEAN_MR1)\r\n\t\t\tGTE_JB_17 = true;\r\n\t\telse\r\n\t\t\tPRE_JB_17 = true;\r\n\t\t\r\n\t\tif(version>= VERSION_CODES.JELLY_BEAN_MR2)\r\n\t\t\tGTE_JB_18 = true;\r\n\t\telse\r\n\t\t\tPRE_JB_18 = true;*/\r\n\t\t\r\n\t\t\r\n\t\t//4.4 Kitkat\r\n\t}\r\n\r\n\tpublic static int convertDpToPx(int dp,Context context)\r\n\t{\r\n\t\tfloat px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());\r\n\t\treturn (int)px;\r\n\t}\r\n\t\r\n\tpublic static AppPreference getUserPrefs(Context context){\r\n\t\tif(mUserPrefrence == null){\r\n\t\t\tmUserPrefrence = new AppPreference(context);\r\n\t\t}\r\n\r\n\t\treturn mUserPrefrence;\r\n\t}\r\n}\r",
"public class PrintLog {\n\n\tpublic static void debug(String TAG,String str) {\n\t\tif(str.length() > 4000) \n\t\t{\n\t\t\tLog.d(\"FTE\",TAG+\" ---> \" + str.substring(0, 4000));\n\t\t\tdebug(TAG,str.substring(4000));\n\t\t} else\n\t\t{\n\t\t\tLog.d(\"FTE\",TAG+ \" ---->\" +str);\n\t\t}\n\t}\n\tpublic static void error(String TAG,String str) {\n\t\tif(str.length() > 4000) \n\t\t{\n\t\t\tLog.e(\"FTE\",TAG +\" ---> \" + str.substring(0, 4000));\n\t\t\terror(TAG,str.substring(4000));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLog.e(\"FTE\",TAG+ \" ---->\" +str);\n\t\t}\n\t}\n\t\n}",
"public interface HomeItemListener {\r\n\tpublic void DownloadPressed(BooksHomeListItems singleItem);\r\n\tpublic void OpenPressed(BooksHomeListItems singleItem);\r\n}\r",
"public class OnListItemTouchListener implements OnTouchListener {\n\n @SuppressWarnings(\"deprecation\")\n\tprivate final GestureDetector gestureDetector = new GestureDetector(new GestureListener());\n\n float downX;\n boolean isMoveEnd;\n boolean isLongPressed;\n public boolean onTouch(final View view, final MotionEvent motionEvent) {\n \t\n \tif(motionEvent.getAction()==MotionEvent.ACTION_DOWN)\n\t\t{\n \t\tisLongPressed = false;\n \t\tdownX = motionEvent.getX();\n\t\t}\n\t\telse if(motionEvent.getAction()==MotionEvent.ACTION_MOVE)\n\t\t{\n\t\t\tif(isMoveEnd)\n\t\t\t\tdownX = motionEvent.getX();\n\t\t\tisMoveEnd = false;\n\t\t\tonMove(motionEvent.getX()-downX);\n\t\t}\n\t\telse if(motionEvent.getAction()==MotionEvent.ACTION_UP)\n\t\t{ \n\t\t\tisMoveEnd = true;\n\t\t\tif(!isLongPressed)\n\t\t\tonUp(motionEvent.getX()-downX,motionEvent.getX());\n\t\t}\n\t\telse if(motionEvent.getAction()==MotionEvent.ACTION_CANCEL)\n\t\t{ \n\t\t\tisMoveEnd = true;\n\t\t\tif(!isLongPressed)\n\t\t\tonCancel(motionEvent.getX()-downX);\n\t\t}\n \t\n return gestureDetector.onTouchEvent(motionEvent);\n }\n\n private final class GestureListener extends SimpleOnGestureListener \n {\n\n private static final int SWIPE_THRESHOLD = 100;\n private static final int SWIPE_VELOCITY_THRESHOLD = 100;\n\n @Override\n public boolean onDown(MotionEvent event) \n {\n return true;\n }\n\n \n \t\t@Override\n\t\tpublic boolean onSingleTapConfirmed(MotionEvent e) {\n\t\t\treturn super.onSingleTapConfirmed(e);\n\t\t}\n\n \t\t\n\n\t\t@Override\n\t\t\tpublic void onLongPress(MotionEvent e) {\n\t\t\t\tisLongPressed = true;\n\t\t\t\tsuper.onLongPress(e);\n\t\t\t\tonHover();\n\t\t\t}\n\n\n\t\t@Override\n public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {\n boolean result = false;\n try {\n float diffY = e2.getY() - e1.getY();\n float diffX = e2.getX() - e1.getX();\n if (Math.abs(diffX) > Math.abs(diffY)) {\n \t\n if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {\n if (diffX > 0) {\n onSwipeRight();\n } else {\n onSwipeLeft();\n }\n }\n } else {\n if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {\n if (diffY > 0) {\n onSwipeBottom();\n } else {\n onSwipeTop();\n }\n }\n }\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n return result;\n }\n }\n\n \n public void onMove(float difference) {\n }\n \n public void onUp(float difference,float touchUpX) {\n }\n \n public void onCancel(float difference) {\n }\n \n public void onSwipeRight() {\n }\n\n public void onSwipeLeft() {\n }\n\n public void onSwipeTop() {\n }\n\n \n public void onSwipeBottom() {\n }\n \n public void onHover(){\n }\n \n}"
] | import java.util.ArrayList;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.NetworkImageView;
import com.jskaleel.fte.R;
import com.jskaleel.fte.app.FTEApplication;
import com.jskaleel.fte.common.FTEDevice;
import com.jskaleel.fte.common.PrintLog;
import com.jskaleel.fte.listeners.HomeItemListener;
import com.jskaleel.fte.listeners.OnListItemTouchListener;
import com.nineoldandroids.animation.ObjectAnimator;
| package com.jskaleel.fte.home;
public class BooksHomeAdapter extends BaseAdapter implements OnScrollListener {
private Context context;
private ArrayList<BooksHomeListItems> bookListArray;
private ArrayList<BooksHomeListItems> searchListArray;
private FragmentHome fragmentHome;
private Typeface tf;
private boolean fastAnim,isAnim;
private int SwipeLength;
| private HomeItemListener homeItemListener;
| 3 |
blinkfox/zealot | src/main/java/com/blinkfox/zealot/core/concrete/ImportHandler.java | [
"public final class BuildSource {\n\n /** xml文件对应的命名空间. */\n private String nameSpace;\n\n /** SQL拼接信息. */\n private SqlInfo sqlInfo;\n\n /** XML节点. */\n private Node node;\n\n /** 参数对象上下文,一般为Bean或者Map. */\n private Object paramObj;\n\n /** 拼接SQL片段的前缀,如:and、or等. */\n private String prefix;\n\n /** 拼接SQL片段的后缀,如:> = <=等. */\n private String suffix;\n\n /**\n * 仅仅有sqlInfo的构造方法.\n * @param sqlInfo SQL拼接和参数对象\n */\n public BuildSource(SqlInfo sqlInfo) {\n super();\n this.sqlInfo = sqlInfo;\n resetPrefix();\n resetSuffix();\n }\n\n /**\n * 含SqlInfo、Node节点、参数上下文的构造方法.\n * @param nameSpace 命名空间\n * @param sqlInfo SQL拼接和参数对象\n * @param node 某查询zealot的dom4j的节点\n * @param paramObj 参数对象\n */\n public BuildSource(String nameSpace, SqlInfo sqlInfo, Node node, Object paramObj) {\n super();\n this.nameSpace = nameSpace;\n this.sqlInfo = sqlInfo;\n this.node = node;\n this.paramObj = paramObj;\n resetPrefix();\n resetSuffix();\n }\n\n /**\n * 重置前缀为默认值.\n * 为了防止SQL拼接时连在一起,默认前缀为一个空格的字符串,后缀为空字符串.\n */\n public void resetPrefix() {\n this.prefix = ZealotConst.ONE_SPACE;\n this.suffix = ZealotConst.EMPTY;\n }\n\n /**\n * 重置后缀为默认值.\n * 为了防止SQL拼接时连在一起,默认后缀为一个空格的字符串.\n */\n public void resetSuffix() {\n this.suffix = ZealotConst.ONE_SPACE;\n }\n\n /* --------------- 以下是 getter 和 setter 方法. ---------------- */\n\n /**\n * 获取nameSpace的getter方法.\n * @return nameSpace\n */\n public String getNameSpace() {\n return nameSpace;\n }\n\n /**\n * 获取sqlInfo的getter方法.\n * @return SqlInfo实例\n */\n public SqlInfo getSqlInfo() {\n return sqlInfo;\n }\n\n /**\n * 设置sqlInfo的setter方法.\n * @param sqlInfo SqlInfo实例\n * @return 当前BuildSource的实例\n */\n public BuildSource setSqlInfo(SqlInfo sqlInfo) {\n this.sqlInfo = sqlInfo;\n return this;\n }\n\n /**\n * 获取node的getter方法.\n * @return Node实例\n */\n public Node getNode() {\n return node;\n }\n\n /**\n * 设置node的setter方法.\n * @param node Node实例\n * @return 当前BuildSource的实例\n */\n public BuildSource setNode(Node node) {\n this.node = node;\n return this;\n }\n\n /**\n * 获取paramObj的getter方法.\n * @return paramObj对象\n */\n public Object getParamObj() {\n return paramObj;\n }\n\n /**\n * 获取前缀prefix的getter方法.\n * @return prefix对象\n */\n public String getPrefix() {\n return prefix;\n }\n\n /**\n * 设置prefix的setter方法.\n * @param prefix prefix对象\n * @return 当前BuildSource的实例\n */\n public BuildSource setPrefix(String prefix) {\n this.prefix = prefix;\n return this;\n }\n\n /**\n * 获取后缀suffix的getter方法.\n * @return suffix对象\n */\n public String getSuffix() {\n return suffix;\n }\n\n /**\n * 设置后缀suffix的setter方法.\n * @param suffix suffix对象\n * @return 当前BuildSource的实例\n */\n public BuildSource setSuffix(String suffix) {\n this.suffix = suffix;\n return this;\n }\n\n /**\n * 设置SQL片段需要解析的参数对象.\n * @param paramObj 参数对象\n * @return 当前BuildSource的实例\n */\n public BuildSource setParamObj(Object paramObj) {\n this.paramObj = paramObj;\n return this;\n }\n}",
"public class SqlInfo {\n\n /** 拼接sql的StringBuilder对象. */\n private StringBuilder join;\n\n /** sql语句对应的有序参数. */\n private List<Object> params;\n\n /** 最终生成的可用sql. */\n private String sql;\n\n /**\n * 全构造方法.\n * @param join 拼接sql的StringBuilder对象\n * @param params 有序的参数集合\n */\n private SqlInfo(StringBuilder join, List<Object> params) {\n super();\n this.join = join;\n this.params = params;\n }\n\n /**\n * 获取一个新的SqlInfo实例.\n * @return 返回SqlInfo实例\n */\n public static SqlInfo newInstance() {\n return new SqlInfo(new StringBuilder(\"\"), new ArrayList<Object>());\n }\n\n /**\n * 得到参数的对象数组.\n * @return 返回参数的对象数组\n */\n public Object[] getParamsArr() {\n return params == null ? new Object[]{} : this.params.toArray();\n }\n\n /**\n * 如果存在某子SQL字符串,则移除该子SQL字符串,常用于来消除'WHERE 1=1'或其他不需要的SQL字符串的场景.\n * 注意该方法不会移除其对应的参数,所以,这里只应该移除静态SQL字符串,不应该移除包含占位符的SQL.\n *\n * @param subSql 静态子SQL片段\n * @return SqlInfo实例\n */\n public SqlInfo removeIfExist(String subSql) {\n this.sql = subSql != null && sql.contains(subSql) ? sql.replaceAll(subSql, \"\") : sql;\n return this;\n }\n\n /* -------------- 以下是 getter 和 setter 方法 ------------- */\n\n public StringBuilder getJoin() {\n return join;\n }\n\n public SqlInfo setJoin(StringBuilder join) {\n this.join = join;\n return this;\n }\n\n public List<Object> getParams() {\n return params;\n }\n\n public SqlInfo setParams(List<Object> params) {\n this.params = params;\n return this;\n }\n\n public String getSql() {\n return sql;\n }\n\n public SqlInfo setSql(String sql) {\n this.sql = sql;\n return this;\n }\n\n}",
"public final class ZealotConst {\n\n /** 分隔符常量,SP是Separate的简称. */\n public static final String SP_AT = \"@@\"; // @@分隔符\n\n /** 逗号常量. */\n public static final String COMMA = \",\";\n\n /* 节点类型 */\n public static final String NODETYPE_TEXT = \"Text\"; // 文本节点\n public static final String NODETYPE_ELEMENT = \"Element\"; // 元素节点\n\n /* 自定义的zealot的元素节点类型. */\n // 等于\n public static final String EQUAL = \"equal\";\n public static final String AND_EQUAL = \"andEqual\";\n public static final String OR_EQUAL = \"orEqual\";\n // 不等于\n public static final String NOT_EQUAL = \"notEqual\";\n public static final String AND_NOT_EQUAL = \"andNotEqual\";\n public static final String OR_NOT_EQUAL = \"orNotEqual\";\n // 大于\n public static final String MORE = \"moreThan\";\n public static final String AND_MORE = \"andMoreThan\";\n public static final String OR_MORE = \"orMoreThan\";\n // 小于\n public static final String LESS = \"lessThan\";\n public static final String AND_LESS = \"andLessThan\";\n public static final String OR_LESS = \"orLessThan\";\n // 大于等于\n public static final String MORE_EQUAL = \"moreEqual\";\n public static final String AND_MORE_EQUAL = \"andMoreEqual\";\n public static final String OR_MORE_EQUAL = \"orMoreEqual\";\n // 小于等于\n public static final String LESS_EQUAL = \"lessEqual\";\n public static final String AND_LESS_EQUAL = \"andLessEqual\";\n public static final String OR_LESS_EQUAL = \"orLessEqual\";\n // \"like\"模糊\n public static final String LIKE = \"like\";\n public static final String AND_LIKE = \"andLike\";\n public static final String OR_LIKE = \"orLike\";\n // \"not like\"模糊\n public static final String NOT_LIKE = \"notLike\";\n public static final String AND_NOT_LIKE = \"andNotLike\";\n public static final String OR_NOT_LIKE = \"orNotLike\";\n // \"between\"区间\n public static final String BETWEEN = \"between\";\n public static final String AND_BETWEEN = \"andBetween\";\n public static final String OR_BETWEEN = \"orBetween\";\n // \"in\"范围\n public static final String IN = \"in\";\n public static final String AND_IN = \"andIn\";\n public static final String OR_IN = \"orIn\";\n // \"not in\"范围\n public static final String NOT_IN = \"notIn\";\n public static final String AND_NOT_IN = \"andNotIn\";\n public static final String OR_NOT_IN = \"orNotIn\";\n // \"is null\"判空\n public static final String IS_NULL = \"isNull\";\n public static final String AND_IS_NULL = \"andIsNull\";\n public static final String OR_IS_NULL = \"orIsNull\";\n // \"is not null\"判不为空\n public static final String IS_NOT_NULL = \"isNotNull\";\n public static final String AND_IS_NOT_NULL = \"andIsNotNull\";\n public static final String OR_IS_NOT_NULL = \"orIsNotNull\";\n // \"text\"文本\n public static final String TEXT = \"text\";\n // \"import\"导入文本\n public static final String IMPORT = \"import\";\n // \"choose\"多条件选择\n public static final String CHOOSE = \"choose\";\n\n /* 节点相关的类型 */\n public static final String ZEALOT_TAG = \"zealots/zealot\";\n public static final String ATTR_NAMESPACE = \"attribute::nameSpace\";\n public static final String ATTR_CHILD = \"child::node()\";\n public static final String ATTR_ID = \"attribute::id\";\n public static final String ATTR_MATCH = \"attribute::match\";\n public static final String ATTR_FIELD = \"attribute::field\";\n public static final String ATTR_VALUE = \"attribute::value\";\n public static final String ATTR_PATTERN = \"attribute::pattern\";\n public static final String ATTR_START = \"attribute::start\";\n public static final String ATTR_ENT = \"attribute::end\";\n public static final String ATTR_NAME_SPACE = \"attribute::namespace\";\n public static final String ATTR_ZEALOT_ID = \"attribute::zealotid\";\n public static final String ATTR_WHEN = \"attribute::when\";\n public static final String ATTR_THEN = \"attribute::then\";\n public static final String ATTR_ELSE = \"attribute::else\";\n\n /* sql中前缀常量 */\n public static final String EMPTY = \"\";\n public static final String ONE_SPACE = \" \";\n public static final String AND_PREFIX = \" AND \";\n public static final String OR_PREFIX = \" OR \";\n\n /* sql中的后缀常量 */\n public static final String EQUAL_SUFFIX = \" = ? \";\n public static final String GT_SUFFIX = \" > ? \";\n public static final String LT_SUFFIX = \" < ? \";\n public static final String GTE_SUFFIX = \" >= ? \";\n public static final String LTE_SUFFIX = \" <= ? \";\n public static final String NOT_EQUAL_SUFFIX = \" <> ? \";\n public static final String LIKE_KEY = \" LIKE \";\n public static final String NOT_LIKE_KEY = \" NOT LIKE \";\n public static final String BT_AND_SUFFIX = \" BETWEEN ? AND ? \";\n public static final String IN_SUFFIX = \" IN \";\n public static final String NOT_IN_SUFFIX = \" NOT IN \";\n public static final String IS_NULL_SUFFIX = \" IS NULL \";\n public static final String IS_NOT_NULL_SUFFIX = \" IS NOT NULL \";\n\n /* 集合类型的常量,0表示单个对象,1表示普通数组,2表示Java集合 */\n public static final int OBJTYPE_ARRAY = 1;\n public static final int OBJTYPE_COLLECTION = 2;\n\n /**\n * 私有构造方法.\n */\n private ZealotConst() {\n super();\n }\n\n}",
"public interface IConditHandler {\n\n /**\n * 构建sqlInfo信息.\n * @param source 构建所需的资源对象\n * @return 返回SqlInfo对象\n */\n SqlInfo buildSqlInfo(BuildSource source);\n\n}",
"public final class Zealot {\n \n /** nsAtZealotId参数拆分成数组后的长度. */\n private static final int LEN = 2;\n\n /**\n * 私有构造方法.\n */\n private Zealot() {\n super();\n }\n\n /**\n * 通过传入zealot xml文件对应的命名空间及zealot节点的ID的结合体,来简单快速的生成和获取sqlInfo信息(无参的SQL).\n *\n * @param nsAtZealotId xml命名空间nameSpace+@@+zealotId的值.如:\"student@@queryStudentById\"\n * @return 返回SqlInfo对象\n */\n public static SqlInfo getSqlInfoSimply(String nsAtZealotId) {\n return getSqlInfoSimply(nsAtZealotId, null);\n }\n\n /**\n * 通过传入zealot xml文件对应的命名空间、zealot节点的ID以及参数对象(一般是JavaBean或者Map)的结合体,来简单快速的生成和获取sqlInfo信息(有参的SQL).\n *\n * @param nsAtZealotId xml命名空间nameSpace+@@+zealotId的值.如:\"student@@queryStudentById\"\n * @param paramObj 参数对象(一般是JavaBean对象或者Map)\n * @return 返回SqlInfo对象\n */\n public static SqlInfo getSqlInfoSimply(String nsAtZealotId, Object paramObj) {\n String[] arr = nsAtZealotId.split(ZealotConst.SP_AT);\n if (arr.length != LEN) {\n throw new ValidFailException(\"nsAtZealotId参数的值必须是xml文件中的 nameSpace + '@@' + zealotId 节点的值,\"\n + \"如:'student@@queryStudentById'.其中student为nameSpace, queryStudentById为XML文件中SQL的zealotId.\");\n }\n return getSqlInfo(arr[0], arr[1], paramObj);\n }\n\n /**\n * 通过传入zealot xml文件对应的命名空间和zealot节点的ID来生成和获取sqlInfo信息(无参的SQL).\n *\n * @param nameSpace xml命名空间\n * @param zealotId xml中的zealotId\n * @return 返回SqlInfo对象\n */\n public static SqlInfo getSqlInfo(String nameSpace, String zealotId) {\n return getSqlInfo(nameSpace, zealotId, null);\n }\n\n /**\n * 通过传入zealot xml文件对应的命名空间、zealot节点的ID以及参数对象(一般是JavaBean或者Map)来生成和获取sqlInfo信息(有参的SQL).\n *\n * @param nameSpace xml命名空间\n * @param zealotId xml中的zealotId\n * @param paramObj 参数对象(一般是JavaBean对象或者Map)\n * @return 返回SqlInfo对象\n */\n public static SqlInfo getSqlInfo(String nameSpace, String zealotId, Object paramObj) {\n if (StringHelper.isBlank(nameSpace) || StringHelper.isBlank(zealotId)) {\n throw new ValidFailException(\"请输入有效的nameSpace或者zealotId的值!\");\n }\n\n // 获取nameSpace文档中的指定sql的zealotId的节点对应的Node节点,如果是debug模式,则实时获取;否则从缓存中获取.\n Node zealotNode = NormalConfig.getInstance().isDebug() ? XmlNodeHelper.getNodeBySpaceAndId(nameSpace, zealotId)\n : AbstractZealotConfig.getZealots().get(StringHelper.concat(nameSpace, ZealotConst.SP_AT, zealotId));\n if (zealotNode == null) {\n throw new NodeNotFoundException(\"未找到nameSpace为:\" + nameSpace + \",zealotId为:\" + zealotId + \"的节点!\");\n }\n\n // 生成新的SqlInfo信息并打印出来.\n SqlInfo sqlInfo = buildNewSqlInfo(nameSpace, zealotNode, paramObj);\n SqlInfoPrinter.newInstance().printZealotSqlInfo(sqlInfo, true, nameSpace, zealotId);\n return sqlInfo;\n }\n\n /**\n * 构建完整的SqlInfo对象.\n *\n * @param nameSpace xml命名空间\n * @param sqlInfo SqlInfo对象\n * @param node dom4j对象节点\n * @param paramObj 参数对象\n * @return 返回SqlInfo对象\n */\n @SuppressWarnings(\"unchecked\")\n public static SqlInfo buildSqlInfo(String nameSpace, SqlInfo sqlInfo, Node node, Object paramObj) {\n // 获取所有子节点,并分别将其使用StringBuilder拼接起来\n List<Node> nodes = node.selectNodes(ZealotConst.ATTR_CHILD);\n for (Node n: nodes) {\n if (ZealotConst.NODETYPE_TEXT.equals(n.getNodeTypeName())) {\n // 如果子节点node 是文本节点,则直接获取其文本\n sqlInfo.getJoin().append(n.getText());\n } else if (ZealotConst.NODETYPE_ELEMENT.equals(n.getNodeTypeName())) {\n // 如果子节点node 是元素节点,则再判断其是什么元素,动态判断条件和参数\n ConditContext.buildSqlInfo(new BuildSource(nameSpace, sqlInfo, n, paramObj), n.getName());\n }\n }\n\n return buildFinalSql(sqlInfo, paramObj);\n }\n\n /**\n * 构建新的、完整的SqlInfo对象.\n *\n * @param nameSpace xml命名空间\n * @param node dom4j对象节点\n * @param paramObj 参数对象\n * @return 返回SqlInfo对象\n */\n private static SqlInfo buildNewSqlInfo(String nameSpace, Node node, Object paramObj) {\n return buildSqlInfo(nameSpace, SqlInfo.newInstance(), node, paramObj);\n }\n\n /**\n * 根据标签拼接的SQL信息来生成最终的SQL.\n *\n * @param sqlInfo sql及参数信息\n * @param paramObj 参数对象信息\n * @return 返回SqlInfo对象\n */\n private static SqlInfo buildFinalSql(SqlInfo sqlInfo, Object paramObj) {\n // 得到生成的SQL,如果有MVEL的模板表达式,则执行计算出该表达式来生成最终的SQL\n String sql = sqlInfo.getJoin().toString();\n sql = ParseHelper.parseTemplate(sql, paramObj);\n return sqlInfo.setSql(StringHelper.replaceBlank(sql));\n }\n\n}",
"public final class ParseHelper {\n\n private static final Log log = Log.get(ParseHelper.class);\n\n /**\n * 私有构造方法.\n */\n private ParseHelper() {\n super();\n }\n\n /**\n * 通过MVEL来解析表达式的值,如果出错不抛出异常.\n * @param exp 待解析表达式\n * @param paramObj 参数对象\n * @return 返回解析后的值\n */\n public static Object parseExpress(String exp, Object paramObj) {\n try {\n return MVEL.eval(exp, paramObj);\n } catch (Exception e) {\n log.error(\"解析表达式出错,表达式为:\" + exp, e);\n return null;\n }\n }\n\n /**\n * 通过MVEL来解析表达式的值,如果出错则抛出异常.\n * @param exp 待解析表达式\n * @param paramObj 参数对象\n * @return 返回解析后的值\n */\n public static Object parseExpressWithException(String exp, Object paramObj) {\n Object obj;\n try {\n obj = MVEL.eval(exp, paramObj);\n } catch (Exception e) {\n throw new ParseExpressionException(\"解析Mvel表达式异常,解析出错的表达式为:\" + exp, e);\n }\n return obj;\n }\n\n /**\n * 通过MVEL来解析模板的值.\n * @param template 待解析表达式\n * @param paramObj 参数对象\n * @return 返回解析后的结果\n */\n public static String parseTemplate(String template, Object paramObj) {\n String output;\n try {\n output = (String) TemplateRuntime.eval(template, paramObj);\n } catch (Exception e) {\n throw new ParseExpressionException(\"解析Mvel模板异常,解析出错的模板为:\" + template, e);\n }\n return output;\n }\n\n /**\n * 判断Zealot标签中`match`中的表达式是否匹配通过.\n * @param match match表达式\n * @param paramObj 参数上下文对象\n * @return 布尔值\n */\n public static boolean isMatch(String match, Object paramObj) {\n return StringHelper.isBlank(match) || isTrue(match, paramObj);\n }\n\n /**\n * 判断Zealot标签中`match`中的表达式是否`不`匹配通过.\n * @param match match表达式\n * @param paramObj 参数上下文对象\n * @return 布尔值\n */\n public static boolean isNotMatch(String match, Object paramObj) {\n return !isMatch(match, paramObj);\n }\n\n /**\n * 判断Zealot标签中`match`中的表达式是否匹配通过.\n * @param exp 表达式\n * @param paramObj 参数上下文对象\n * @return 布尔值\n */\n public static boolean isTrue(String exp, Object paramObj) {\n return Boolean.TRUE.equals(ParseHelper.parseExpressWithException(exp, paramObj));\n }\n\n}",
"public final class StringHelper {\n \n /** 替换空格、换行符、制表符等为一个空格的预编译正则表达式模式. */\n private static final Pattern BLANK_PATTERN = Pattern.compile(\"\\\\|\\t|\\r|\\n\");\n\n /** XML文件扩展名. */\n private static final String XML_EXT = \".xml\";\n\n /** Java文件扩展名. */\n private static final String JAVA_EXT = \".java\";\n\n /** Java编译后的class文件扩展名. */\n private static final String CLASS_EXT = \".class\";\n\n /**\n * 私有的构造方法.\n */\n private StringHelper() {\n super();\n }\n\n /**\n * 将字符串中的“空格(包括换行、回车、制表符)”等转成空格来处理,最后去掉所有多余空格.\n * @param str 待判断字符串\n * @return 替换后的字符串\n */\n public static String replaceBlank(String str) {\n Matcher m = BLANK_PATTERN.matcher(str);\n return m.replaceAll(\"\").replaceAll(\"\\\\s{2,}\", \" \").trim();\n }\n\n /**\n * 判断是否为空字符串,包括空格也算.\n * @param str 待判断字符串\n * @return 是否的布尔结果\n */\n public static boolean isBlank(String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return true;\n }\n\n // 遍历每个空格是否有非空格元素\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * 判断字符串是否为空.\n * @param str 待判断字符串\n * @return 是否的布尔结果\n */\n public static boolean isNotBlank(String str) {\n return !isBlank(str);\n }\n\n /**\n * 快速连接参数中的字符串.\n * @param strs 各字符串参数\n * @return 连接后的字符串\n */\n public static String concat(String ... strs) {\n StringBuilder sb = new StringBuilder(\"\");\n for (String str: strs) {\n sb.append(str);\n }\n return sb.toString();\n }\n\n /**\n * 判断文件全路径是否是已某扩展名结尾的文件.\n *\n * @param filePath 文件全路径名\n * @param ext 文件扩展名\n * @return 布尔值\n */\n private static boolean isExtFile(String filePath, String ext) {\n return filePath != null && filePath.endsWith(ext);\n }\n\n /**\n * 根据给定的文件路径判断文件是否是XML文件.\n * @param filePath 文件路径\n * @return 布尔值\n */\n public static boolean isXmlFile(String filePath) {\n return isExtFile(filePath, XML_EXT);\n }\n\n /**\n * 根据给定的文件路径判断文件是否是.java文件.\n * @param filePath 文件路径\n * @return 布尔值\n */\n public static boolean isJavaFile(String filePath) {\n return isExtFile(filePath, JAVA_EXT);\n }\n\n /**\n * 根据给定的文件路径判断文件是否是.class文件.\n * @param filePath 文件路径\n * @return 布尔值\n */\n public static boolean isClassFile(String filePath) {\n return isExtFile(filePath, CLASS_EXT);\n }\n\n}",
"public final class XmlNodeHelper {\n\n private static final Log log = Log.get(ZealotConfigManager.class);\n \n /** zealot xml文件中的根节点名称. */\n private static final String ROOT_NAME = \"zealots\";\n\n /**\n * 私有构造方法.\n */\n private XmlNodeHelper() {\n super();\n }\n\n /**\n * 读取xml文件为dom4j的Docment文档.\n * @param xmlPath 定位xml文件的路径,如:com/blinkfox/test.xml\n * @return 返回dom4j文档\n */\n public static Document getDocument(String xmlPath) {\n try {\n InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlPath);\n return new SAXReader().read(is);\n } catch (Exception e) {\n throw new XmlParseException(\"读取或解析xml文件失败,xmlPath是:\" + xmlPath, e);\n }\n }\n\n /**\n * 根据xml文件的nameSpace及zealot节点id值获取对应的第一个dom4j节点.\n * @param nameSpace xml文件对应命名空间\n * @param zealotId ZealotId\n * @return dom4j的Node节点\n */\n public static Node getNodeBySpaceAndId(String nameSpace, String zealotId) {\n String filePath = XmlContext.INSTANCE.getXmlPathMap().get(nameSpace);\n Document doc = XmlNodeHelper.getDocument(filePath);\n return doc == null ? null : XmlNodeHelper.getZealotNodeById(doc, zealotId);\n }\n\n /**\n * 根据xml文件的路径判断该xml文件是否是zealot xml文件(简单判断是否有'zealots'根节点即可),如果是则返回nameSpace.\n * @param xmlPath xml路径\n * @return 该xml文件的zealot命名空间nameSpace\n */\n public static String getZealotXmlNameSpace(String xmlPath) {\n Document doc;\n try {\n InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlPath);\n doc = new SAXReader().read(is);\n } catch (Exception expected) {\n // 由于只是判断该文件是否能被正确解析,并不进行正式的解析,所有这里就不抛出和记录异常了.\n log.warn(\"解析路径为:'\" + xmlPath + \"'的xml文件出错,请检查其正确性\");\n return null;\n }\n\n // 获取XML文件的根节点,判断其根节点是否为'zealots',如果是则获取其属性nameSpace的值.\n Node root = doc.getRootElement();\n if (root != null && ROOT_NAME.equals(root.getName())) {\n String nameSpace = getNodeText(root.selectSingleNode(ZealotConst.ATTR_NAMESPACE));\n if (StringHelper.isBlank(nameSpace)) {\n log.warn(\"zealot xml文件:'\" + xmlPath + \"'的根节点nameSpace命名空间属性为配置,请配置,否则将被忽略!\");\n return null;\n }\n return nameSpace;\n }\n\n return null;\n }\n\n /**\n * 根据xml文件docment中的zealot节点id值获取对应的第一个节点.\n * <p>使用xPath语法获取第一个符合条件的节点.</p>\n * @param doc docment文档\n * @param id zealotId\n * @return dom4j的Node节点\n */\n public static Node getZealotNodeById(Document doc, String id) {\n return doc.selectSingleNode(\"/zealots/zealot[@id='\" + id + \"']\");\n }\n\n /**\n * 获取xml节点的文本值,如果对象是空的,则转为空字符串.\n * @param node dom4j节点\n * @return 返回节点文本值\n */\n public static String getNodeText(Node node) {\n return node == null ? \"\" : node.getText();\n }\n\n /**\n * 获取节点文本.\n * @param node dom4j节点\n * @param attrName 节点属性\n * @return 返回节点文本值\n */\n public static String getNodeAttrText(Node node, String attrName) {\n Node fieldNode = node.selectSingleNode(attrName);\n return XmlNodeHelper.getNodeText(fieldNode);\n }\n\n /**\n * 检查和获取节点文本,会检查节点是否为空,如果节点为空,则抛出异常.\n * @param node dom4j节点\n * @param nodeName 节点名称\n * @return 返回节点文本值\n */\n public static String getAndCheckNodeText(Node node, String nodeName) {\n /* 判断必填的参数是否为空 */\n Node fieldNode = node.selectSingleNode(nodeName);\n String fieldText = XmlNodeHelper.getNodeText(fieldNode);\n if (StringHelper.isBlank(fieldText)) {\n throw new FieldEmptyException(\"填写的字段值是空的\");\n }\n return fieldText;\n }\n\n /**\n * 检查和获取开始和结束文本的内容,返回一个数组,会检查两个节点是否为空,如果都为空,则抛出异常.\n * @param node dom4j节点\n * @return 返回开始和结束文本的二元数组\n */\n public static String[] getBothCheckNodeText(Node node) {\n Node startNode = node.selectSingleNode(ZealotConst.ATTR_START);\n Node endNode = node.selectSingleNode(ZealotConst.ATTR_ENT);\n String startText = XmlNodeHelper.getNodeText(startNode);\n String endText = XmlNodeHelper.getNodeText(endNode);\n if (StringHelper.isBlank(startText) && StringHelper.isBlank(endText)) {\n throw new FieldEmptyException(\"填写的开始和结束字段值是空的\");\n }\n return new String[] {startText, endText};\n }\n\n}"
] | import com.blinkfox.zealot.bean.BuildSource;
import com.blinkfox.zealot.bean.SqlInfo;
import com.blinkfox.zealot.consts.ZealotConst;
import com.blinkfox.zealot.core.IConditHandler;
import com.blinkfox.zealot.core.Zealot;
import com.blinkfox.zealot.helpers.ParseHelper;
import com.blinkfox.zealot.helpers.StringHelper;
import com.blinkfox.zealot.helpers.XmlNodeHelper;
import org.dom4j.Node; | package com.blinkfox.zealot.core.concrete;
/**
* 引用import标签对应的动态sql生成处理器的实现类.
* <p>引用标签的主要内容:`[import match="" namespace="" zealotid="" value="" /]`</p>
* @author blinkfox on 2017/8/15.
*/
public class ImportHandler implements IConditHandler {
/**
* 构建import标签的sqlInfo信息.
* @param source 构建所需的资源对象
* @return 返回SqlInfo对象
*/
@Override
public SqlInfo buildSqlInfo(BuildSource source) {
// 判断是否生成,如果不匹配则不生成SQL片段.
String matchText = XmlNodeHelper.getNodeAttrText(source.getNode(), ZealotConst.ATTR_MATCH);
if (ParseHelper.isNotMatch(matchText, source.getParamObj())) {
return source.getSqlInfo();
}
// 获取命名空间的文本值.
String nameSpaceText = XmlNodeHelper.getNodeAttrText(source.getNode(), ZealotConst.ATTR_NAME_SPACE); | String nameSpace = StringHelper.isNotBlank(nameSpaceText) ? nameSpaceText : source.getNameSpace(); | 6 |
cobaltdev/pipeline | src/main/java/com/cobalt/bamboo/plugin/pipeline/servlet/MainPage.java | [
"public interface CacheManager {\n\t\n\t/**\n\t * Put WallBoardData for all plans into the cache. All of existing data (if any)\n\t * will be replaced.\n\t */\n\tpublic void putAllWallBoardData();\n\t\n\t/**\n\t * Update the WallBoardData in the cache for the given plan. If the plan already\n\t * exists in the cache, the associated WallBoardData will be replaced. If the plan\n\t * doesn't exist in the cache yet, a new plan will be created with it's new WallBoardData.\n\t * \n\t * @param planKey of the plan to update in the cache\n\t */\n\t/**\n\t * Update the WallBoardData in the cache for the given plan. If the plan already\n\t * exists in the cache, the associated WallBoardData will be replaced. If the plan\n\t * doesn't exist in the cache yet, a new plan will be created with it's new WallBoardData.\n\t * \n\t * @param planKey of the plan to update in the cache\n\t * @param updateUptimeGrade A boolean to indicate whether to update the UptimeGrade in the cache\n\t */\n\tpublic void updateWallBoardDataForPlan(String planKey, boolean updateUptimeGrade);\n\t\n\t/**\n\t * Get WallBoardData for all of the plans.\n\t * \n\t * @return a list of WallBoardData representing all plans.\n\t */\n\tpublic List<WallBoardData> getAllWallBoardData();\n\t\n\t/**\n\t * Clear everything in the cache.\n\t */\n\tpublic void clearCache();\n}",
"public interface MainManager {\n\t\n\t/**\n\t * Get all the results needed for displaying the CDPipeline table.\n\t * \n\t * @return a list of CDResults, where each CDResult represents one row.\n\t * See CDResults for more details.\n\t */\n\tpublic List<CDResult> getCDResults();\n\t\n\t/**\n\t * Get the result needed for displaying the CDPipeline table for the plan\n\t * specified by the given playkey.\n\t * @param planKey of the plan to look for\n\t * @return the CDResult of the given plan. Return null if no plan can be\n\t * found for the given plankey.\n\t */\n\tpublic CDResult getCDResultForPlan(String planKey);\n\t\n\t/**\n\t * Get a list of Changes since the last pipeline completion for the plan \n\t * specified by the given plankey.\n\t * \n\t * @param planKey of the plan to look for\n\t * @return the list of changes since last pipeline completion for the given plan.\n\t * List may be empty if there are no changes. Return null if no plan can\n\t * be found from the given plankey.\n\t */\n\tpublic List<Change> getChangeListForPlan(String planKey);\n\t\n\t/**\n\t * Get a CDPerformance for the plan specified by the given plankey.\n\t * If no plan found or no build in the plan, return null.\n\t * @param planKey planKey of the plan to look for\n\t * @return the continuous delivery performance statistics for the given plan.\n\t * Return null if no plan can be found for the given plankey or no build\n\t * in the plan.\n\t */\n\tpublic CDPerformance getPerformanceStatsForPlan(String planKey);\n\t\n\t/**\n\t * Get a UptimeGrade for the plan specified by the given planKey.\n\t * If no plan found or no build in the plan, return null.\n\t * \n\t * @param planKey planKey of the plan to look for\n\t * @return the UptimeGrade, representing the uptime percentage, of the plan.\n\t * Return null if no plan can be found for the given plankey or no build\n\t * in the plan.\n\t */\n\tpublic UptimeGrade getUptimeGradeForPlan(String planKey);\n\t\n\t/**\n\t * Get all TopLevelPlans directly from Bamboo.\n\t * @return a List of TopLevelPlan\n\t */\n\tpublic List<TopLevelPlan> getAllPlans();\n}",
"public class WallBoardData {\n\tpublic String planKey;\n\tpublic CDResult cdresult;\n\tpublic UptimeGrade uptimeGrade;\n\t\n\tpublic WallBoardData(String planKey, CDResult cdresult, UptimeGrade uptimeGrade) {\n\t\tthis.planKey = planKey;\n\t\tthis.cdresult = cdresult;\n\t\tthis.uptimeGrade = uptimeGrade;\n\t}\n}",
"public class CDPerformance {\n\tprivate int totalBuild;\n\tprivate int totalSuccess;\n\tprivate int numChanges;\n\tprivate List<CompletionStats> completions;\n\tprivate double totalDays;\n\t\n\t/**\n\t * Construct a CDPerformance with given information\n\t * Throw IllegalArgumentException if totalBuild < totalSuccess or startDate\n\t * after lastCompletionDate\n\t * @param totalBuild total number of builds of this plan\n\t * @param totalSuccess total number of successes of this plan\n\t * @param numChanges total number of changes before the most recent completion\n\t * @param startDate completed date of the first build\n\t * @param lastCompletionDate completed date of the most recent completion\n\t * @param completions all completions within this plan\n\t */\n\tpublic CDPerformance(int totalBuild, int totalSuccess, int numChanges, Date startDate, Date lastCompletionDate,\n\t\t\t\t\t\tList<CompletionStats> completions){\n\t\tif(totalBuild < totalSuccess){\n\t\t\tthrow new IllegalArgumentException(\"Total successes should not be greater than total builds\");\n\t\t}\n\t\tthis.totalBuild = totalBuild;\n\t\tthis.totalSuccess = totalSuccess;\n\t\tthis.numChanges = numChanges;\n\t\tthis.completions = new ArrayList<CompletionStats>(completions);\n\t\tif(startDate != null && lastCompletionDate != null){\n\t\t\tif(lastCompletionDate.compareTo(startDate) < 0){\n\t\t\t\tthrow new IllegalArgumentException(\"Last completion date should not be before start date\");\n\t\t\t}\n\t\t\tthis.totalDays = (lastCompletionDate.getTime() - startDate.getTime()) * 1.0 / (1000 * 60 * 60 * 24);\n\t\t}else{\n\t\t\ttotalDays = -1;\n\t\t}\n\t\t\n\t}\n\t\n\t/**\n\t * Return success percentage calculated by total successes / total builds, \n\t * rounded to 2 decimal places\n\t * If no build, return 0.\n\t * @return success percentage of this performance statistics, return 0 when\n\t * there's no build\n\t */\n\tpublic double getSuccessPercentage(){\n\t\tif (totalBuild <= 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tdouble percent = totalSuccess * 1.0 / totalBuild;\n\t\treturn Math.round(percent * 100.0) / 100.0;\t\n\t}\n\t\n\t/**\n\t * Return average changes from the creation of this plan to the recent completion,\n\t * calculated by total changes / total completions,\n\t * rounded to 2 decimal places\n\t * If there's no completions, return -1\n\t * @return average changes between completions\n\t */\n\tpublic double getAverageChanges() {\n\t\tif (completions.size() > 0) {\n\t\t\treturn numChanges * 1.0 / completions.size();\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic double getSuccessPercentageFormatted(){\n\t\tif (totalBuild <= 0) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn totalSuccess * 1.0 / totalBuild;\n\t}\n\t\n\t/**\n\t * Return average frequency of completion from the creation of this plan to the\n\t * recent completion in days, calculated by total days / total completions,\n\t * rounded to 2 decimal places\n\t * If there's no completions, return -1\n\t * @return average days between completions\n\t */\n\tpublic double getAverageFrequency() {\n\t\tif (completions.size() > 0) {\n\t\t\treturn totalDays * 1.0 / completions.size();\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t/**\n\t * Return all completions of this performance statistics\n\t * @return list of completions of this performance statistics\n\t */\n\tpublic List<CompletionStats> getCompletions() {\n\t\treturn Collections.unmodifiableList(completions);\n\t}\n\t\n}",
"public class Change {\n\tprivate String authorFullName;\n\tprivate String authorPictureUrl;\n\tprivate int buildNumber;\n\tprivate String comment;\n\tprivate Date date;\n\tprivate Set<String> files;\n\tprivate String revisionId;\n\t\n\t/**\n\t * Construct a Change object\n\t * @param author\t\t\tthe name of the contributor\n\t * @param authorPictureUrl\tthe link to the contributor's profile page\n\t * @param buildNumber\t\tthe build number\n\t * @param comment\t\t\tthe comment on the change\n\t * @param date\t\t\t\tthe date of the change\n\t * @param files\t\t\t\tthe files associated with the change\n\t * @param revisionNumber\tthe revision number of the change\n\t */\n\tpublic Change(String authorFullName, String authorPictureUrl, int buildNumber, String comment,\n\t\t\t\t\tDate date, Set<String> files, String revisionId) {\n this.authorFullName = authorFullName;\n\t\tthis.authorPictureUrl = authorPictureUrl;\n\t\tthis.buildNumber = buildNumber;\n\t\tthis.comment = comment;\n\t\tthis.date = date;\n\t\tthis.files = files;\n\t\tthis.revisionId = revisionId;\n\t}\n\n\t/**\n\t * Get the full name of the contributor\n\t * @return the full name of the contributor\n\t */\n\tpublic String getAuthorFullName() {\n\t\treturn authorFullName;\t\n\t}\n\t\n\t/**\n\t * Get the link to the contributor's profile page\n\t * @return the link to the contributor's profile page\n\t */\n\tpublic String getAuthorPictureUrl() {\n\t\treturn authorPictureUrl;\n\t}\n\t\n\t/**\n\t * Get the build number\n\t * @return the build number\n\t */\n\tpublic int getBuildNumber() {\n\t\treturn buildNumber;\n\t}\n\t\n\t/**\n\t * Get the comment on the change\n\t * @return the comment on the change\n\t */\n\tpublic String getComment() {\n\t\treturn comment;\n\t}\n\t\n\t/**\n\t * Get the date of the change\n\t * @return the date of the change\n\t */\n\tpublic Date getDate() {\n\t\treturn new Date(date.getTime());\n\t}\n\t\n\t/**\n\t * Get the time elapsed since the change:\n\t * - \"XYZ\" minute/hour/day/month/year ago if the change was made within the same hour/day/month/year/...\n\t * - \"Just now\" if the change was made within the same minute\n\t */\n\tpublic String getTimeElapsed() {\n\t\tDate today = new Date();\n\t\tint minuteDiff = today.getMinutes() - date.getMinutes();\n\t\tint hourDiff = today.getHours() - date.getHours();\n\t\tint dayDiff = today.getDate() - date.getDate();\n\t\tint monthDiff = today.getMonth() - date.getMonth();\n\t\tint yearDiff = today.getYear() - date.getYear();\n\t\t\t\n\t\tif (yearDiff == 0 && monthDiff == 0 && dayDiff == 0 && hourDiff == 0 && minuteDiff == 0) {\n\t\t\treturn \"Just now\";\n\t\t} else if (yearDiff == 0 && monthDiff == 0 && dayDiff == 0 && hourDiff == 0) {\n\t\t\treturn String.format(\"%d minute%s ago\", minuteDiff, minuteDiff > 1 ? \"s\" : \"\");\n\t\t} else if (yearDiff == 0 && monthDiff == 0 && dayDiff == 0) {\n\t\t\treturn String.format(\"%d hour%s ago\", hourDiff, hourDiff > 1 ? \"s\" : \"\");\n\t\t} else if (yearDiff == 0 && monthDiff == 0) {\n\t\t\treturn String.format(\"%d day%s ago\", dayDiff, dayDiff > 1 ? \"s\" : \"\");\n\t\t} else if (yearDiff == 0) {\n\t\t\treturn String.format(\"%d month%s ago\", monthDiff, monthDiff > 1 ? \"s\" : \"\");\n\t\t} else {\n\t\t\treturn String.format(\"%d year%s ago\", yearDiff, yearDiff > 1 ? \"s\" : \"\");\n\t\t}\n\t}\n\t\n\t/**\n\t * Get the files associated with the change\n\t * @return \tthe files associated with the change\n\t */\n\tpublic Set<String> getFiles() {\n\t\treturn files;\n\t}\n\t\n\t/**\n\t * Get the revision number of the change\n\t * @return the revision number of the change\n\t */\n\tpublic String getRevisionNumber() {\n\t\treturn revisionId;\n\t}\n}"
] | import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.atlassian.sal.api.auth.LoginUriProvider;
import com.atlassian.sal.api.user.UserManager;
import com.atlassian.templaterenderer.TemplateRenderer;
import com.cobalt.bamboo.plugin.pipeline.Controllers.CacheManager;
import com.cobalt.bamboo.plugin.pipeline.Controllers.MainManager;
import com.cobalt.bamboo.plugin.pipeline.cache.WallBoardData;
import com.cobalt.bamboo.plugin.pipeline.cdperformance.CDPerformance;
import com.cobalt.bamboo.plugin.pipeline.changelist.Change; | package com.cobalt.bamboo.plugin.pipeline.servlet;
public class MainPage extends HttpServlet{
private static final Logger log = LoggerFactory.getLogger(MainPage.class);
private final UserManager userManager;
private final LoginUriProvider loginUriProvider;
private final TemplateRenderer renderer;
private final CacheManager cacheManager;
private final MainManager mainManager;
public MainPage(UserManager userManager, LoginUriProvider loginUriProvider, TemplateRenderer renderer,
CacheManager cacheManager, MainManager mainManager)
{
this.userManager = userManager;
this.loginUriProvider = loginUriProvider;
this.renderer = renderer;
this.cacheManager = cacheManager;
this.mainManager = mainManager;
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// Redirect the user if user is not admin
String username = userManager.getRemoteUsername(request);
if (username == null)
{
redirectToLogin(request, response);
return;
}
String query = request.getParameter("data");
if (query == null) { // TODO
// Normal case: normal table page
response.setContentType("text/html;charset=utf-8");
renderer.render("cdpipeline.vm", response.getWriter());
} else if (query.equalsIgnoreCase("all")) {
// Special Case: JSON request
ObjectWriter writer = (new ObjectMapper()).writer().withDefaultPrettyPrinter();
List<WallBoardData> resultList = cacheManager.getAllWallBoardData();
String json = writer.writeValueAsString(resultList);
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
} else if (query.equalsIgnoreCase("changes") && request.getParameter("plankey") != null){ | List<Change> changeList = mainManager.getChangeListForPlan(request.getParameter("plankey")); | 4 |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/queries/QueryJ10RxStreamsWithAkkaStreams.java | [
"public class Credentials {\n\n public final String username;\n public final String password;\n\n public Credentials(final String username, final String password) {\n this.username = username;\n this.password = password;\n }\n}",
"public class Order {\n\n private static final String ID = \"_id\";\n private static final String USERNAME = \"first\";\n private static final String AMOUNT = \"amount\";\n\n public final int id;\n public final String username;\n public final int amount;\n\n public Order(final int id, final String username, final int amount) {\n this.id = id;\n this.username = username;\n this.amount = amount;\n }\n\n public Order(final Document doc) {\n this(doc.getInteger(ID), doc.getString(USERNAME), doc.getInteger(AMOUNT));\n }\n\n @Override\n public String toString() {\n return \"Order{\" +\n ID + \"=\" + id +\n \", \" + USERNAME + \"='\" + username + '\\'' +\n \", \" + AMOUNT + \"=\" + (amount/100.0) +\n '}';\n }\n\n public void print() {\n System.out.print(this);\n }\n\n public void println() {\n System.out.println(this);\n }\n\n public Document toDocument() {\n return new Document(ID, id).append(USERNAME, username).append(AMOUNT, amount);\n }\n}",
"@SuppressWarnings(\"WeakerAccess\")\npublic class Result {\n\n public final String username;\n public final int orderCount;\n public final int totalAmount;\n public final int avgAmount;\n\n public Result(final String username, final int orderCount, final int totalAmount, final int avgAmount) {\n this.username = username;\n this.orderCount = orderCount;\n this.totalAmount = totalAmount;\n this.avgAmount = avgAmount;\n }\n\n public Result(final String username, final int orderCount, final int totalAmount) {\n this(username, orderCount, totalAmount, average(totalAmount, orderCount));\n }\n\n public Result(final String username, final List<Order> orders) {\n this(username, orders.size(), totalAmountOf(orders));\n }\n\n @Override\n public String toString() {\n return \"Result{\" +\n \"first='\" + username + '\\'' +\n \", orderCount=\" + orderCount +\n \", totalAmount=\" + totalAmount +\n \", avgAmount=\" + avgAmount +\n '}';\n }\n\n public void display() {\n System.out.println(\"--------------------------------------------\");\n System.out.println(\"eCommerce Statistics of User \\\"\" + username + \"\\\":\");\n System.out.println(\"\\tNo of Orders: \" + orderCount);\n System.out.println(\"\\tTotal Amount: \" + totalAmount/100.0 + \" $\");\n System.out.println(\"\\tAverage Amount: \" + avgAmount/100.0 + \" $\");\n System.out.println(\"--------------------------------------------\\n\");\n }\n}",
"public class User {\n\n private static final String ID = \"_id\";\n private static final String NAME = \"name\";\n private static final String PASSWORD = \"password\";\n\n public final String name;\n public final String password;\n\n public User(final String name, final String password) {\n this.name = name;\n this.password = password;\n }\n\n public User(Document doc) {\n this(doc.getString(ID), doc.getString(PASSWORD));\n }\n\n @Override\n public String toString() {\n return \"User{\" +\n NAME + \"='\" + name + '\\'' +\n \", \" + PASSWORD + \"='\" + password + '\\'' +\n '}';\n }\n\n public void print() {\n System.out.print(this);\n }\n\n public void println() {\n System.out.println(this);\n }\n\n public Document toDocument() {\n return new Document(ID, name).append(PASSWORD, password);\n }\n}",
"public interface Constants {\n\n int MAX_ORDERS_PER_USER = 10;\n\n String MONGODB_URI = \"mongodb://localhost:27017\";\n String SHOP_DB_NAME = \"shop\";\n String USERS_COLLECTION_NAME = \"users\";\n String ORDERS_COLLECTION_NAME = \"orders\";\n\n String HOMER = \"homer\";\n String MARGE = \"marge\";\n String BART = \"bart\";\n String LISA = \"lisa\";\n String MAGGIE = \"maggie\";\n\n String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};\n}",
"public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {\n\n if (!optUser.isPresent()) { // replaces if (user != null)\n throw new RuntimeException(new IllegalAccessException(\"User unknown: \" + credentials.username));\n }\n final User user = optUser.get();\n return checkUserLoggedIn(user, credentials);\n}"
] | import akka.Done;
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.stream.ActorMaterializer;
import akka.stream.javadsl.Source;
import com.mongodb.rx.client.MongoClient;
import com.mongodb.rx.client.MongoClients;
import com.mongodb.rx.client.MongoCollection;
import com.mongodb.rx.client.MongoDatabase;
import org.bson.Document;
import org.reactivestreams.Publisher;
import rx.Observable;
import rx.Single;
import shopJava.model.Credentials;
import shopJava.model.Order;
import shopJava.model.Result;
import shopJava.model.User;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static rx.RxReactiveStreams.toPublisher;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.checkUserLoggedIn; | package shopJava.queries;
@SuppressWarnings("Convert2MethodRef")
public class QueryJ10RxStreamsWithAkkaStreams {
public static void main(String[] args) throws Exception {
new QueryJ10RxStreamsWithAkkaStreams();
}
private final DAO dao = new DAO();
private class DAO {
private final MongoCollection<Document> usersCollection;
private final MongoCollection<Document> ordersCollection;
DAO() {
final MongoClient client = MongoClients.create(MONGODB_URI);
final MongoDatabase db = client.getDatabase(SHOP_DB_NAME);
this.usersCollection = db.getCollection(USERS_COLLECTION_NAME);
this.ordersCollection = db.getCollection(ORDERS_COLLECTION_NAME);
}
private Single<User> _findUserByName(final String name) {
return usersCollection
.find(eq("_id", name))
.first()
.toSingle()
.map(doc -> new User(doc));
}
private Observable<Order> _findOrdersByUsername(final String username) {
return ordersCollection
.find(eq("username", username))
.toObservable()
.map(doc -> new Order(doc));
}
Publisher<User> findUserByName(final String name) {
return toPublisher(_findUserByName(name).toObservable());
}
Publisher<List<Order>> findOrdersByUsername(final String username) {
return toPublisher(_findOrdersByUsername(username).toList());
}
} // end DAO
private Source<String, NotUsed> logIn(final Credentials credentials) {
return Source.fromPublisher(dao.findUserByName(credentials.username)) | .map(user -> checkUserLoggedIn(user, credentials)) | 5 |
calibre2opds/calibre2opds | OpdsOutput/src/main/java/com/gmail/dpierron/calibre/opds/TagTreeSubCatalog.java | [
"public class Book extends GenericDataObject {\r\n private final static Logger logger = LogManager.getLogger(Book.class);\r\n\r\n private File bookFolder;\r\n private final String id;\r\n private final String uuid;\r\n private String title;\r\n private String titleSort;\r\n private final String path;\r\n private String comment;\r\n private String summary;\r\n private Integer summaryMaxLength;\r\n private final Float serieIndex;\r\n private final Date timestamp;\r\n private final Date modified;\r\n private final Date publicationDate;\r\n private final String isbn;\r\n private List<Author> authors;\r\n private String listOfAuthors;\r\n private String authorSort;\r\n private Publisher publisher;\r\n private Series series;\r\n private List<Tag> tags;\r\n private List<EBookFile> files;\r\n private EBookFile preferredFile;\r\n private EBookFile epubFile;\r\n private String epubFileName;\r\n private long latestFileModifiedDate = -1;\r\n private final BookRating rating;\r\n private List<Language> bookLanguages = new LinkedList<Language>();\r\n private List<CustomColumnValue> customColumnValues;\r\n private static Date ZERO;\r\n private static final Pattern tag_br = Pattern.compile(\"\\\\<br\\\\>\", Pattern.CASE_INSENSITIVE);\r\n protected Book copyOfBook; // If a book is copied then this points to the original\r\n\r\n // Flags\r\n // NOTE: Using byte plus bit settings is more memory efficient than using boolean types\r\n private final static byte FLAG_ALL_CLEAR = 0;\r\n private final static byte FLAG_DONE = 0x01; // Set when the Book full details have been generated\r\n private final static byte FLAG_REFERENCED = 0x02; // Set if book full details must be generated as referenced\r\n private final static byte FLAG_FILES_SORTED = 0x04;\r\n private final static byte FLAG_EPUBFILE_COMPUTED = 0x08;\r\n private final static byte FLAG_PREFERREDFILECOMPUTED = 0x10;\r\n private final static byte FLAG_CHANGED = 0x20;\r\n private final static byte FLAG_FLAGGED = 0x40;\r\n private byte flags = FLAG_ALL_CLEAR;\r\n\r\n static {\r\n Calendar c = Calendar.getInstance();\r\n c.setTimeInMillis(0);\r\n ZERO = c.getTime();\r\n }\r\n\r\n // CONSTRUCTORS\r\n\r\n public Book(String id,\r\n String uuid,\r\n String title,\r\n String title_sort,\r\n String path,\r\n Float serieIndex,\r\n Date timestamp,\r\n Date modified,\r\n Date publicationDate,\r\n String isbn,\r\n String authorSort,\r\n BookRating rating) {\r\n super();\r\n copyOfBook = null;\r\n this.id = id;\r\n this.uuid = uuid;\r\n\r\n if (title != null) {\r\n // Do some (possibly unnecessary) tidyong of title\r\n title = title.trim();\r\n this.title = title.substring(0, 1).toUpperCase() + title.substring(1);\r\n // title_sort is normally set by Calibre autoamtically, but it can be cleared\r\n // by users and may not be set by older versions of Calibre. In these\r\n // cases we fall back to using the (mandatory) title field and issue a warning\r\n if (Helper.isNullOrEmpty(title_sort)) {\r\n logger.warn(\"Title_Sort not set - using Title for book '\" + this.title + \"'\"); Helper.statsWarnings++;\r\n this.titleSort = DataModel.getNoiseword(getFirstBookLanguage()).removeLeadingNoiseWords(this.title);\r\n } else {\r\n this.titleSort = title_sort;\r\n }\r\n // Small memory optimisation to re-use title object if possible\r\n // TODO check if unecessary if Java does this automatically?\r\n if (this.title.equalsIgnoreCase(this.titleSort)) {\r\n this.titleSort = this.title;\r\n }\r\n }\r\n\r\n this.path = path;\r\n this.serieIndex = serieIndex;\r\n this.timestamp = timestamp;\r\n this.modified = modified;\r\n this.publicationDate = publicationDate;\r\n this.tags = new LinkedList<Tag>();\r\n this.files = new LinkedList<EBookFile>();\r\n this.authors = new LinkedList<Author>();\r\n this.isbn = isbn;\r\n this.authorSort = authorSort;\r\n this.rating = rating;\r\n\r\n }\r\n\r\n // METHODS and PROPERTIES implementing Abstract ones from Base class)\r\n\r\n /**\r\n * Method that gets the name for this 'data' type\r\n *\r\n * @return\r\n */\r\n public String getColumnName () {\r\n return \"book\";\r\n }\r\n\r\n public ColumType getColumnType() {\r\n return ColumType.COLUMN_BOOK;\r\n }\r\n\r\n public String getDisplayName() {\r\n return (copyOfBook == null) ? title : copyOfBook.getDisplayName();\r\n }\r\n\r\n public String getSortName() {\r\n return (copyOfBook == null) ? titleSort : copyOfBook.getSortName();\r\n }\r\n\r\n public String getTextToDisplay() {\r\n return DataModel.displayTitleSort ? getSortName() : getDisplayName() ;\r\n }\r\n\r\n public String getTextToSort() {\r\n return DataModel.librarySortTitle ? getDisplayName() : getSortName();\r\n }\r\n\r\n // METHODS and PROPERTIES\r\n\r\n /**\r\n * Helper routine to set flags bits state\r\n */\r\n private void setFlags (boolean b, int f) {\r\n if (b == true)\r\n flags |= f; // Set flag bits\r\n else\r\n flags &= ~f; // Clear flag bits;\r\n }\r\n\r\n /**\r\n * Helper routine to check if specified kags set\r\n * @param f\r\n * @return\r\n */\r\n private boolean isFlags( int f) {\r\n return ((flags & f) == f);\r\n }\r\n\r\n\r\n public String getId() {\r\n return (copyOfBook == null) ? id : copyOfBook.getId();\r\n }\r\n\r\n public String getUuid() {\r\n return (copyOfBook == null) ? uuid : copyOfBook.getUuid();\r\n }\r\n\r\n /**\r\n * Return the first listed language for a book\r\n * (this is on the assumption it is the most important one)\r\n * @return\r\n */\r\n public Language getFirstBookLanguage() {\r\n if (copyOfBook != null) return copyOfBook.getFirstBookLanguage();\r\n List<Language> languages = getBookLanguages();\r\n if ((languages == null) || (languages.size() == 0))\r\n return null;\r\n else\r\n return languages.get(0);\r\n }\r\n\r\n /**\r\n * Get all the languages for a book.\r\n * Most of the time there will only be one, but Ca;ibre\r\n * allows for multpiple languages on the same book.\r\n * @return\r\n */\r\n public List<Language> getBookLanguages() {\r\n return (copyOfBook == null) ? bookLanguages : copyOfBook.getBookLanguages();\r\n }\r\n\r\n /**\r\n * Add a language to the book.\r\n *\r\n * @param bookLanguage\r\n */\r\n public void addBookLanguage(Language bookLanguage) {\r\n assert copyOfBook == null; // Never expect this to be used on a copy of the book!\r\n if (getBookLanguages() == null) {\r\n bookLanguages = new LinkedList<Language>();\r\n }\r\n if (!bookLanguages.contains(bookLanguage)) {\r\n bookLanguages.add(bookLanguage);\r\n }\r\n }\r\n\r\n public String getIsbn() {\r\n return (copyOfBook == null) ? (isbn == null ? \"\" : isbn) : copyOfBook.getIsbn();\r\n }\r\n\r\n public String getPath() {\r\n return (copyOfBook == null) ? path : copyOfBook.getPath();\r\n }\r\n\r\n public String getComment() {\r\n return (copyOfBook == null) ? comment : copyOfBook.getComment();\r\n }\r\n\r\n /**\r\n * Remove leading text from the given XHTNL string. This is\r\n * used to remove words such as SUMMARY that we add ourselves\r\n * in the catalog. It is also used to remove other common\r\n * expressions from the Summary to try and leave text that is more\r\n * useful as a summary.\r\n *\r\n * Special processing requirements:\r\n * - Any leading HTML tags or spaces are ignored\r\n * - Any trailing ':' or spaces are removed\r\n * - If after removing the desired text there are\r\n * HTML tags that were purely surrounding the text\r\n * that has been removed, they are also removed.\r\n * @param text Text that is being worked on\r\n * @param leadingText String to be checked for (case ignored)\r\n * @return Result of removing text, or null if input was null\r\n */\r\n private String removeLeadingText (String text, String leadingText) {\r\n // Check for fast exit conditions\r\n if (Helper.isNullOrEmpty(text) || Helper.isNullOrEmpty(leadingText) )\r\n return text;\r\n int textLength = text.length();\r\n int leadingLength = leadingText.length();\r\n\r\n int cutStart = 0; // Start scanning from beginning of string\r\n int cutStartMax = textLength - leadingLength - 1 ;\r\n\r\n // skip over leading tags and spaces\r\n boolean scanning = true;\r\n while (scanning) {\r\n // Give up no room left to match text\r\n if (cutStart > cutStartMax)\r\n return text;\r\n // Look for special characters\r\n switch (text.charAt(cutStart)) {\r\n case ' ':\r\n cutStart++;\r\n break;\r\n case '<':\r\n // Look for end of tag\r\n int tagEnd = text.indexOf('>',cutStart);\r\n // If not found then give up But should this really occur)\r\n if (tagEnd == -1)\r\n return text;\r\n else\r\n cutStart = tagEnd + 1;\r\n break;\r\n default:\r\n scanning = false;\r\n break;\r\n }\r\n }\r\n\r\n // Exit if text does not match\r\n if (! text.substring(cutStart).toUpperCase(Locale.ENGLISH).startsWith(leadingText.toUpperCase(Locale.ENGLISH)))\r\n return text;\r\n // Set end of text to remove\r\n int cutEnd = cutStart + leadingLength;\r\n\r\n // After removing leading text, now remove any tags that are now empty of content\r\n // TODO - complete the logic here. Currently does not remove such empty tags\r\n scanning=true;\r\n while (scanning) {\r\n if (cutEnd >= textLength) {\r\n scanning = false;\r\n }\r\n else {\r\n switch (text.charAt(cutEnd)) {\r\n case ' ':\r\n case ':':\r\n cutEnd++;\r\n break;\r\n case '<':\r\n if (text.charAt(cutEnd+1) != '/'){\r\n // Handle case of BR tag following removed text\r\n if (text.substring(cutEnd).toUpperCase().startsWith(\"<BR\")) {\r\n int tagEnd = text.indexOf('>', cutEnd+1);\r\n if (tagEnd != -1) {\r\n cutEnd = tagEnd + 1;\r\n break;\r\n }\r\n }\r\n scanning = false;\r\n break;\r\n }\r\n else {\r\n int tagEnd = text.indexOf('>');\r\n if (tagEnd == -1) {\r\n scanning = false;\r\n break;\r\n }\r\n else {\r\n cutEnd = tagEnd + 1;\r\n }\r\n }\r\n break;\r\n default:\r\n scanning = false;\r\n break;\r\n } // End of switch\r\n }\r\n } // End of while\r\n\r\n if (cutStart > 0)\r\n return (text.substring(0, cutStart) + text.substring(cutEnd)).trim();\r\n else\r\n return text.substring(cutEnd).trim();\r\n }\r\n\r\n /**\r\n * Sets the comment value\r\n * If it starts with 'SUMMARY' then this is removed as superfluous\r\n * NOTE. Comments are allowed to contain (X)HTML) tags\r\n * @param value the new comment\r\n */\r\n public void setComment(String value) {\r\n assert copyOfBook == null; // Never expect this to be used on a copy\r\n summary = null;\r\n summaryMaxLength = -1;\r\n if (Helper.isNotNullOrEmpty(value)) {\r\n if (value.startsWith(\"<\")) {\r\n if (value.contains(\"<\\\\br\") || value.contains(\"<\\\\BR\")) {\r\n int dummy = 1;\r\n }\r\n // Remove newlines from HTML as they are meangless in that context\r\n value = value.replaceAll(\"\\\\n\",\"\");\r\n // Remove any empty paragraphs.\r\n value= value.replaceAll(\"<p></p>\",\"\");\r\n }\r\n comment = removeLeadingText(value, \"SUMMARY\");\r\n comment = removeLeadingText(comment, \"PRODUCT DESCRIPTION\");\r\n // The following log entry can be useful if trying to debug character encoding issues\r\n // logger.info(\"Book \" + id + \", setComment (Hex): \" + Database.stringToHex(comment));\r\n \r\n if (comment != null && comment.matches(\"(?i)<br>\")) {\r\n logger.warn(\"<br> tag in comment changed to <br /> for Book: Id=\" + id + \" Title=\" + title); Helper.statsWarnings++;\r\n comment.replaceAll(\"(?i)<br>\", \"<br />\");\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Get the book summary\r\n * This starts with any series information, and then as much of the book comment as\r\n * will fit in the space allowed.\r\n *\r\n * Special processing Requirements\r\n * - The word 'SUMMARY' is removed as superfluous at the start of the comment text\r\n * - The words 'PRODUCT DESCRIPTION' are removed as superfluous at the start of the comment text\r\n * - The calculated value is stored for later re-use (which is very likely to happen).\r\n * NOTE. Summary must be pure text (no (X)HTML tags) for OPDS compatibility\r\n * @param maxLength Maximum length of text allowed in summary\r\n * @return The value of the calculated summary field\r\n */\r\n public String getSummary(int maxLength) {\r\n if (copyOfBook != null) return copyOfBook.getSummary(maxLength);\r\n if (summary == null || maxLength != summaryMaxLength) {\r\n summary = \"\";\r\n summaryMaxLength = maxLength;\r\n // Check for series info to include\r\n if (Helper.isNotNullOrEmpty(getSeries())) {\r\n float seriesIndexFloat = getSerieIndex();\r\n if (seriesIndexFloat == 0 ) {\r\n // We do not add the index when it is zero\r\n summary += getSeries().getDisplayName() + \": \";\r\n } else {\r\n int seriesIndexInt = (int) seriesIndexFloat;\r\n String seriesIndexText;\r\n // For the commonest case of integers we want to truncate off the fractional part\r\n if (seriesIndexFloat == (float) seriesIndexInt)\r\n seriesIndexText = String.format(\"%d\", seriesIndexInt);\r\n else {\r\n // For fractions we want only 2 decimal places to match calibre\r\n seriesIndexText = String.format(\"%.2f\", seriesIndexFloat);\r\n }\r\n summary += getSeries().getDisplayName() + \" [\" + seriesIndexText + \"]: \";\r\n }\r\n if (maxLength != -1) {\r\n summary = Helper.shorten(summary, maxLength);\r\n }\r\n }\r\n // See if still space for comment info\r\n // allow for special case of -1 which means no limit.\r\n if (maxLength == -1 || (maxLength > (summary.length() + 3))) {\r\n String noHtml = Helper.removeHtmlElements(getComment());\r\n if (noHtml != null) {\r\n noHtml = removeLeadingText(noHtml, \"SUMMARY\");\r\n noHtml = removeLeadingText(noHtml, \"PRODUCT DESCRIPTION\");\r\n if (maxLength == -1 ) {\r\n summary += noHtml;\r\n } else {\r\n summary += Helper.shorten(noHtml, maxLength - summary.length());\r\n }\r\n }\r\n }\r\n }\r\n return summary;\r\n }\r\n\r\n /**&\r\n * Get the series index.\r\n * It is thought that Calibre always sets this but it is better to play safe!\r\n * @return\r\n */\r\n public Float getSerieIndex() {\r\n if (copyOfBook != null) return copyOfBook.getSerieIndex();\r\n if (Helper.isNotNullOrEmpty(serieIndex)) {\r\n return serieIndex;\r\n }\r\n // We never expect to get here!\r\n logger.warn(\"Unexpected null/empty Series Index for book \" + getDisplayName() + \"(\" + getId() + \")\"); Helper.statsWarnings++;\r\n return (float)1.0;\r\n }\r\n\r\n public Date getTimestamp() {\r\n if (copyOfBook != null) return copyOfBook.getTimestamp();\r\n // ITIMPI: Return 'now' if timestamp not set - would 0 be better?\r\n if (timestamp == null) {\r\n logger.warn(\"Date/Time Added not set for book '\" + title + \"'\"); Helper.statsWarnings++;\r\n return new Date();\r\n }\r\n return timestamp;\r\n }\r\n\r\n public Date getModified() {\r\n if (copyOfBook != null) return copyOfBook.getModified();\r\n // ITIMPI: Return 'now' if modified not set - would 0 be better?\r\n if (modified == null) {\r\n logger.warn(\"Date/Time Modified not set for book '\" + title + \"'\"); Helper.statsWarnings++;\r\n return new Date();\r\n }\r\n return modified;\r\n }\r\n\r\n public Date getPublicationDate() {\r\n if (copyOfBook != null) return copyOfBook.getPublicationDate();\r\n if (publicationDate == null) {\r\n logger.warn(\"Publication Date not set for book '\" + title + \"'\"); Helper.statsWarnings++;\r\n return ZERO;\r\n }\r\n return (publicationDate);\r\n }\r\n\r\n public boolean hasAuthor() {\r\n return Helper.isNotNullOrEmpty(getAuthors());\r\n }\r\n\r\n public boolean hasSingleAuthor() {\r\n if (copyOfBook != null) return copyOfBook.hasSingleAuthor();\r\n return (Helper.isNotNullOrEmpty(authors) && authors.size() == 1);\r\n }\r\n\r\n public List<Author> getAuthors() {\r\n if (copyOfBook != null) return copyOfBook.getAuthors();\r\n assert authors != null && authors.size() > 0;\r\n return authors;\r\n }\r\n\r\n /**\r\n * Create a comma separated list of authors\r\n * @return\r\n */\r\n public String getListOfAuthors() {\r\n if (copyOfBook != null) return copyOfBook.getListOfAuthors();\r\n if (listOfAuthors == null)\r\n listOfAuthors = Helper.concatenateList(\" & \", getAuthors(), \"getDisplayName\");\r\n return listOfAuthors;\r\n }\r\n\r\n public Author getMainAuthor() {\r\n if (copyOfBook != null) return copyOfBook.getMainAuthor();\r\n if (getAuthors() == null || getAuthors().size() == 0)\r\n return null;\r\n return getAuthors().get(0);\r\n }\r\n\r\n public String getAuthorSort() {\r\n return (copyOfBook == null) ? authorSort : copyOfBook.getAuthorSort();\r\n }\r\n\r\n public Publisher getPublisher() {\r\n return (copyOfBook == null) ? publisher : copyOfBook.getPublisher();\r\n }\r\n\r\n public void setPublisher(Publisher publisher) {\r\n assert copyOfBook == null; // Do not expect this on a copy\r\n this.publisher = publisher;\r\n }\r\n\r\n public Series getSeries() {\r\n return (copyOfBook == null) ? series : copyOfBook.getSeries();\r\n }\r\n\r\n public void setSeries(Series value) {\r\n assert copyOfBook == null; // Do not expect this on a copy\r\n this.series = value;\r\n }\r\n\r\n /**\r\n * Note that the list of tags for a books can be different\r\n * in the master and in any copies of the book object\r\n *\r\n * @return\r\n */\r\n public List<Tag> getTags() {\r\n return tags;\r\n }\r\n\r\n /**\r\n * Get the list of eBook files associated with this book.\r\n * @return\r\n */\r\n public List<EBookFile> getFiles() {\r\n if (copyOfBook != null) return copyOfBook.getFiles();\r\n if (! isFlags(FLAG_FILES_SORTED)) {\r\n if (files != null && files.size() > 1) {\r\n Collections.sort(files, new Comparator<EBookFile>() {\r\n public int compare(EBookFile o1, EBookFile o2) {\r\n if (o1 == null) {\r\n if (o2 == null)\r\n return 0;\r\n else\r\n return 1;\r\n }\r\n if (o2 == null) {\r\n return -1;\r\n }\r\n // Now allow for empty format entries\r\n if (o1.getFormat() == null) {\r\n if (o2.getFormat() == null)\r\n return 0;\r\n else\r\n return 1;\r\n }\r\n if (o2.getFormat() == null) {\r\n return -1;\r\n }\r\n return Helper.checkedCompare(o1.getFormat().toString(), o2.getFormat().toString());\r\n }\r\n });\r\n }\r\n setFlags(true, FLAG_FILES_SORTED);;\r\n }\r\n return files;\r\n }\r\n\r\n public void removeFile(EBookFile file) {\r\n assert copyOfBook == null; // Do not expect this on a copy\r\n files.remove(file);\r\n epubFile = null;\r\n preferredFile = null;\r\n latestFileModifiedDate = -1;\r\n setFlags(false,FLAG_EPUBFILE_COMPUTED + FLAG_PREFERREDFILECOMPUTED + FLAG_FILES_SORTED);\r\n }\r\n\r\n /**\r\n *\r\n * @param file\r\n */\r\n public void addFile(EBookFile file) {\r\n assert copyOfBook == null; // Fo not expect this on a copy\r\n files.add(file);\r\n epubFile = null;\r\n preferredFile = null;\r\n latestFileModifiedDate = -1;\r\n setFlags(false,FLAG_EPUBFILE_COMPUTED + FLAG_PREFERREDFILECOMPUTED + FLAG_FILES_SORTED);\r\n }\r\n\r\n public EBookFile getPreferredFile() {\r\n if (copyOfBook != null) return copyOfBook.getPreferredFile();\r\n if (! isFlags(FLAG_PREFERREDFILECOMPUTED)) {\r\n for (EBookFile file : getFiles()) {\r\n if (preferredFile == null || file.getFormat().getPriority() > preferredFile.getFormat().getPriority())\r\n preferredFile = file;\r\n }\r\n setFlags(true, FLAG_PREFERREDFILECOMPUTED);\r\n }\r\n return preferredFile;\r\n }\r\n\r\n /**\r\n * @param author\r\n */\r\n public void addAuthor(Author author) {\r\n assert copyOfBook == null; // Do not expect this on a copy\r\n listOfAuthors = null; // Force display list to be recalculated\r\n if (authors == null)\r\n authors = new LinkedList<Author>();\r\n if (!authors.contains(author))\r\n authors.add(author);\r\n }\r\n\r\n public String toString() {\r\n return getId() + \" - \" + getDisplayName();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == null)\r\n return false;\r\n if (obj instanceof Book) {\r\n return (Helper.checkedCompare(((Book) obj).getId(), getId()) == 0);\r\n } else\r\n return super.equals(obj);\r\n }\r\n\r\n public String toDetailedString() {\r\n return getId() + \" - \" + getMainAuthor().getDisplayName() + \" - \" + getDisplayName() + \" - \" + Helper.concatenateList(getTags()) + \" - \" + getPath();\r\n }\r\n\r\n public File getBookFolder() {\r\n if (copyOfBook != null) return copyOfBook.getBookFolder();\r\n if (bookFolder == null) {\r\n File calibreLibraryFolder = Configuration.instance().getDatabaseFolder();\r\n bookFolder = new File(calibreLibraryFolder, getPath());\r\n }\r\n return bookFolder;\r\n }\r\n\r\n public String getEpubFilename() {\r\n if (copyOfBook != null) return copyOfBook.getEpubFilename();\r\n if (! isFlags(FLAG_EPUBFILE_COMPUTED)) {\r\n getEpubFile();\r\n }\r\n return epubFileName;\r\n }\r\n\r\n public EBookFile getEpubFile() {\r\n if (copyOfBook != null) return copyOfBook.getEpubFile();\r\n if (!isFlags(FLAG_EPUBFILE_COMPUTED)) {\r\n epubFile = null;\r\n epubFileName = null;\r\n for (EBookFile file : getFiles()) {\r\n if (file.getFormat() == EBookFormat.EPUB) {\r\n epubFile = file;\r\n epubFileName = epubFile.getName() + epubFile.getExtension();\r\n }\r\n }\r\n setFlags(true, FLAG_EPUBFILE_COMPUTED);\r\n }\r\n return epubFile;\r\n }\r\n\r\n public boolean doesEpubFileExist() {\r\n if (copyOfBook != null) return copyOfBook.doesEpubFileExist();\r\n EBookFile file = getEpubFile();\r\n if (file == null)\r\n return false;\r\n File f = file.getFile();\r\n return (f != null && f.exists());\r\n }\r\n\r\n public long getLatestFileModifiedDate() {\r\n if (copyOfBook != null) return copyOfBook.getLatestFileModifiedDate();\r\n if (latestFileModifiedDate == -1) {\r\n latestFileModifiedDate = 0;\r\n for (EBookFile file : getFiles()) {\r\n File f = file.getFile();\r\n if (f.exists()) {\r\n long m = f.lastModified();\r\n if (m > latestFileModifiedDate)\r\n latestFileModifiedDate = m;\r\n }\r\n }\r\n }\r\n return latestFileModifiedDate;\r\n }\r\n\r\n public BookRating getRating() {\r\n if (copyOfBook != null) return copyOfBook.getRating();\r\n return rating;\r\n }\r\n\r\n /**\r\n * Make a copy of the book object.\r\n *\r\n * The copy has some special behavior in that most properties a@e read\r\n * from the original, but the tags one is still private.\r\n *\r\n * NOTE: Can pass as null values that are always read from parent!\r\n * Not sure if this reduces RAM usage or not!\r\n *\r\n * @return Book object that is the copy\r\n */\r\n public Book copy() {\r\n Book result = new Book(\r\n null,\r\n null,\r\n null,\r\n null,\r\n null,\r\n null,timestamp,modified,publicationDate,isbn,authorSort,rating);\r\n\r\n // The tags aassciated with this entry may be changed, so we make\r\n // a copy of the ones currently associated\r\n result.tags = new LinkedList<Tag>(this.getTags());\r\n\r\n // Indicate this is a copy by setting a reference to the parent\r\n // This is used to read/set variables that must be in parent.\r\n result.copyOfBook = (this.copyOfBook == null) ? this : this.copyOfBook;\r\n return result;\r\n }\r\n\r\n public boolean isFlagged() {\r\n if (copyOfBook != null) return copyOfBook.isFlagged();\r\n return isFlags(FLAG_FLAGGED);\r\n }\r\n\r\n public void setFlagged() {\r\n if (copyOfBook != null) {\r\n copyOfBook.setFlagged();\r\n return;\r\n }\r\n setFlags(true, FLAG_FLAGGED);\r\n }\r\n\r\n public void clearFlagged() {\r\n if (copyOfBook != null) {\r\n copyOfBook.clearFlagged();\r\n return;\r\n }\r\n setFlags(false, FLAG_FLAGGED);\r\n }\r\n\r\n /**\r\n * Return whether we believe book has been changed since last run\r\n * @return\r\n */\r\n public boolean isChanged() {\r\n if (copyOfBook != null) return copyOfBook.isChanged();\r\n return isFlags(FLAG_CHANGED);\r\n }\r\n\r\n /**\r\n * Set the changed status to be true\r\n * (default is false, -so should only need to set to true.\r\n * If neccesary could change to pass in required state).\r\n */\r\n public void setChanged() {\r\n if (copyOfBook != null) {\r\n copyOfBook.setChanged();\r\n return;\r\n }\r\n setFlags(true, FLAG_CHANGED);\r\n }\r\n\r\n public List<CustomColumnValue> getCustomColumnValues() {\r\n return customColumnValues;\r\n }\r\n\r\n public void setCustomColumnValues (List <CustomColumnValue> values) {\r\n assert copyOfBook == null:\r\n customColumnValues = values;\r\n }\r\n\r\n public CustomColumnValue getCustomColumnValue (String name) {\r\n assert false : \"getCustomColumnValue() not yet ready for use\";\r\n return null;\r\n }\r\n\r\n public void setCustomColumnValue (String name, String value) {\r\n assert false : \"setCustomColumnValue() not yet ready for use\";\r\n }\r\n\r\n public void setDone() {\r\n if (copyOfBook != null) {\r\n copyOfBook.setDone();\r\n return;\r\n }\r\n setFlags(true, FLAG_DONE);\r\n }\r\n\r\n public boolean isDone() {\r\n if (copyOfBook != null) return copyOfBook.isDone();\r\n return isFlags(FLAG_DONE);\r\n }\r\n\r\n /**\r\n * Set referenced flag.\r\n */\r\n public void setReferenced() {\r\n if (copyOfBook != null) {\r\n copyOfBook.setReferenced();\r\n return;\r\n }\r\n setFlags(true, FLAG_REFERENCED);\r\n }\r\n\r\n /**\r\n * Get referenced flag\r\n *\r\n * @return\r\n */\r\n public boolean isReferenced() {\r\n if (copyOfBook != null) return copyOfBook.isReferenced();\r\n return isFlags(FLAG_REFERENCED);\r\n }\r\n}\r",
"public class Tag extends GenericDataObject implements SplitableByLetter, Comparable<Tag> {\r\n private final String id;\r\n private final String name;\r\n private String[] partsOfTag;\r\n // Flags\r\n // NOTE: Using byte plus bit settings is more memory efficient than using boolean types\r\n private final static byte FLAG_ALL_CLEAR = 0;\r\n private final static byte FLAG_DONE = 0x01;\r\n private final static byte FLAG_REFERENCED = 0x02;\r\n private byte flags = FLAG_ALL_CLEAR;\r\n\r\n // CONSTRUCTOR\r\n\r\n public Tag(String id, String name) {\r\n super();\r\n this.id = id;\r\n this.name = name;\r\n }\r\n\r\n // METHODS and PROPERTIES implementing Abstract ones from Base class)\r\n\r\n public ColumType getColumnType() {\r\n return ColumType.COLUMN_TAGS;\r\n }\r\n public String getColumnName() {\r\n return \"tags\";\r\n }\r\n public String getDisplayName() {\r\n return name;\r\n }\r\n public String getSortName() {\r\n return name;\r\n }\r\n public String getTextToSort() {\r\n return name;\r\n }\r\n public String getTextToDisplay() {\r\n return name;\r\n }\r\n\r\n // METHODS and PROPERTIES\r\n\r\n public String getId() {\r\n return id;\r\n }\r\n\r\n\r\n\r\n public String toString() {\r\n return getTextToSort();\r\n }\r\n\r\n\r\n public String[] getPartsOfTag(String splitTagsOn) {\r\n if (partsOfTag == null) {\r\n List<String> parts = Helper.tokenize(getTextToSort(), splitTagsOn);\r\n partsOfTag = new String[parts.size()];\r\n int[] partsOfTagHash = new int[partsOfTag.length];\r\n for (int i = 0; i < parts.size(); i++) {\r\n String part = parts.get(i);\r\n partsOfTag[i] = part;\r\n partsOfTagHash[i] = (part == null ? -1 : part.hashCode());\r\n }\r\n }\r\n return partsOfTag;\r\n }\r\n\r\n public int compareTo(Tag o) {\r\n if (o == null)\r\n return 1;\r\n return Helper.trueStringCompare(getId(), o.getId());\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == null)\r\n return false;\r\n if (obj instanceof Tag) {\r\n return (Helper.checkedCompare(((Tag) obj).getId(), getId()) == 0);\r\n } else\r\n return super.equals(obj);\r\n }\r\n\r\n public void setDone() {\r\n flags |= FLAG_DONE;\r\n }\r\n public boolean isDone () {\r\n return ((flags & FLAG_DONE) != 0);\r\n }\r\n\r\n public void setReferenced() {\r\n flags |= FLAG_REFERENCED;\r\n }\r\n public boolean isReferenced () {\r\n return ((flags & FLAG_REFERENCED) != 0);\r\n }\r\n}\r",
"public class TrookSpecificSearchDatabaseManager {\r\n\r\n private static final int MIN_KEYWORD_LEN = 3;\r\n\r\n private static File databaseFile = null;\r\n private static Connection connection = null;\r\n private static Map<String, Long> keywords = new HashMap<String, Long>();\r\n private static List<Book> storedBooks = new LinkedList<Book>();\r\n private static List<Author> storedAuthors = new LinkedList<Author>();\r\n private static List<Series> storedSeries = new LinkedList<Series>();\r\n private static List<Tag> storedTags = new LinkedList<Tag>();\r\n private static long keywordCounter = 0;\r\n private static long resultCounter = 0;\r\n\r\n private static final Logger logger = LogManager.getLogger(TrookSpecificSearchDatabaseManager.class);\r\n\r\n public static void setDatabaseFile(File dbFile) {\r\n databaseFile = dbFile;\r\n }\r\n\r\n public static File getDatabaseFile() {\r\n return databaseFile;\r\n }\r\n\r\n public static Connection getConnection() {\r\n if (connection == null) {\r\n initConnection();\r\n }\r\n return connection;\r\n }\r\n\r\n public static void closeConnection() {\r\n if (connection != null) {\r\n try {\r\n connection.close();\r\n } catch (SQLException e) {\r\n // Ignore any exception\r\n }\r\n }\r\n }\r\n\r\n public static boolean databaseExists() {\r\n if (databaseFile == null)\r\n return false;\r\n if (!databaseFile.exists())\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n private static void initConnection() {\r\n try {\r\n Class.forName(\"org.sqlite.JDBC\");\r\n if (databaseFile == null)\r\n return;\r\n if (databaseExists())\r\n databaseFile.delete();\r\n String url = databaseFile.toURI().getPath();\r\n connection = DriverManager.getConnection(\"jdbc:sqlite:\" + url);\r\n Statement stat = connection.createStatement();\r\n // drop the indexes\r\n stat.executeUpdate(\"DROP INDEX IF EXISTS KEYWORDS_RESULTS_RELATION_INDEX_ON_RESULTS;\");\r\n stat.executeUpdate(\"DROP INDEX IF EXISTS KEYWORDS_RESULTS_RELATION_INDEX_ON_KEYWORD;\");\r\n stat.executeUpdate(\"DROP INDEX IF EXISTS RESULTS_INDEX;\");\r\n stat.executeUpdate(\"DROP INDEX IF EXISTS KEYWORDS_INDEX;\");\r\n // drop the tables\r\n stat.executeUpdate(\"DROP TABLE IF EXISTS keywords_results_relation\");\r\n stat.executeUpdate(\"DROP TABLE IF EXISTS results\");\r\n stat.executeUpdate(\"DROP TABLE IF EXISTS keywords\");\r\n // create the tables\r\n stat.executeUpdate(\"CREATE TABLE keywords (keyword_id INTEGER PRIMARY KEY, keyword_value TEXT);\");\r\n stat.executeUpdate(\"CREATE TABLE results (result_id INTEGER PRIMARY KEY, result_type TEXT, result_entry TEXT);\");\r\n stat.executeUpdate(\"CREATE TABLE keywords_results_relation (keyword_id INTEGER, result_id INTEGER);\");\r\n // create the indexes\r\n stat.executeUpdate(\"CREATE UNIQUE INDEX KEYWORDS_INDEX ON keywords(keyword_id ASC);\");\r\n stat.executeUpdate(\"CREATE UNIQUE INDEX RESULTS_INDEX ON results(result_id ASC);\");\r\n stat.executeUpdate(\"CREATE INDEX KEYWORDS_RESULTS_RELATION_INDEX_ON_KEYWORD ON keywords_results_relation(keyword_id ASC);\");\r\n stat.executeUpdate(\"CREATE INDEX KEYWORDS_RESULTS_RELATION_INDEX_ON_RESULTS ON keywords_results_relation(result_id ASC);\");\r\n } catch (ClassNotFoundException e) {\r\n logger.error(e); Helper.statsErrors++;\r\n } catch (SQLException e) {\r\n logger.error(e); Helper.statsErrors++;\r\n }\r\n }\r\n\r\n\r\n\r\n private static long addResult(String opdsEntry, ResultType type) throws SQLException {\r\n PreparedStatement ps = getConnection().prepareStatement(\"INSERT INTO results(result_id, result_type, result_entry) values (?, ?, ?);\");\r\n ps.setLong(1, ++resultCounter);\r\n ps.setString(2, type.name().toUpperCase(Locale.ENGLISH));\r\n ps.setString(3, opdsEntry);\r\n ps.execute();\r\n return resultCounter;\r\n }\r\n\r\n private static long addKeyword(String keyword) throws SQLException {\r\n // check if keyword already exist (we test in memory to be quicker)\r\n if (keywords.containsKey(keyword))\r\n return keywords.get(keyword);\r\n else {\r\n PreparedStatement ps = getConnection().prepareStatement(\"INSERT INTO keywords(keyword_id, keyword_value) values (?, ?);\");\r\n ps.setLong(1, ++keywordCounter);\r\n ps.setString(2, keyword);\r\n ps.execute();\r\n keywords.put(keyword, keywordCounter);\r\n }\r\n return keywordCounter;\r\n }\r\n\r\n private static void addKeywordResultRelation(long keywordId, long resultId) throws SQLException {\r\n PreparedStatement ps = getConnection().prepareStatement(\"INSERT INTO keywords_results_relation(keyword_id, result_id) values (?, ?);\");\r\n ps.setLong(1, keywordId);\r\n ps.setLong(2, resultId);\r\n ps.execute();\r\n }\r\n\r\n private static List<String> keywordize(String pKeywordString) {\r\n List<String> keywords = new LinkedList<String>();\r\n List<String> result = new LinkedList<String>();\r\n String keywordString = pKeywordString.toUpperCase(Locale.ENGLISH);\r\n StringBuffer currentKeyword = null;\r\n for (int pos = 0; pos < keywordString.length(); pos++) {\r\n char c = keywordString.charAt(pos);\r\n if (!Character.isLetterOrDigit(c)) {\r\n // skip and break keywords at non letter or digits\r\n if (currentKeyword != null) {\r\n // process current keyword\r\n keywords.add(currentKeyword.toString());\r\n currentKeyword = null;\r\n }\r\n continue;\r\n }\r\n if (currentKeyword == null)\r\n currentKeyword = new StringBuffer();\r\n currentKeyword.append(c);\r\n }\r\n\r\n // process the last keyword\r\n if (currentKeyword != null) {\r\n keywords.add(currentKeyword.toString());\r\n currentKeyword = null;\r\n }\r\n\r\n // make packages with keywords, in increasing size\r\n for (int size = 1; size <= keywords.size(); size++) {\r\n int pos = 0;\r\n while (pos + size <= keywords.size()) {\r\n StringBuffer keywordPackage = new StringBuffer();\r\n for (int i = pos; i < pos + size; i++) {\r\n keywordPackage.append(keywords.get(i));\r\n keywordPackage.append(' ');\r\n }\r\n String s = keywordPackage.toString();\r\n result.add(s.substring(0, s.length() - 1));\r\n pos++;\r\n }\r\n }\r\n\r\n // add the \"whole string\" keyword\r\n result.add(keywordString);\r\n\r\n return result;\r\n }\r\n\r\n public static void addEntry(String opdsEntry, ResultType type, String... keywordStrings) throws SQLException {\r\n // add the result\r\n long resultId = addResult(opdsEntry, type);\r\n\r\n for (String keywordString : keywordStrings) {\r\n // process the keyword string\r\n List<String> keywords = keywordize(keywordString);\r\n for (String keyword : keywords) {\r\n if (keyword.length() >= MIN_KEYWORD_LEN) {\r\n long keywordId = addKeyword(keyword);\r\n addKeywordResultRelation(keywordId, resultId);\r\n }\r\n }\r\n }\r\n }\r\n\r\n private static void addEntryToTrookSearchDatabase(Element entry, ResultType type, String... keywords) {\r\n try {\r\n StringWriter sw = new StringWriter();\r\n JDOMManager.getCompactXML().output(entry, sw);\r\n String opdsEntry = sw.getBuffer().toString();\r\n addEntry(opdsEntry, type, keywords);\r\n } catch (IOException e) {\r\n logger.warn(e.getMessage()); Helper.statsWarnings++;\r\n } catch (SQLException e) {\r\n logger.warn(e.getMessage()); Helper.statsWarnings++;\r\n }\r\n }\r\n\r\n public static void addAuthor(Author item, Element entry) {\r\n if (ConfigurationManager.getCurrentProfile().getDeviceMode() == DeviceMode.Nook) {\r\n if (!storedAuthors.contains(item)) {\r\n logger.debug(\"adding result for \" + item);\r\n String keywords = item.getDisplayName();\r\n addEntryToTrookSearchDatabase(entry, ResultType.AUTHOR, keywords);\r\n storedAuthors.add(item);\r\n }\r\n }\r\n }\r\n\r\n public static void addSeries(Series item, Element entry) {\r\n if (ConfigurationManager.getCurrentProfile().getDeviceMode() == DeviceMode.Nook) {\r\n if (!storedSeries.contains(item)) {\r\n logger.debug(\"adding result for \" + item);\r\n String keywords = item.getDisplayName();\r\n // TODO do this after Doug has added support for noise words filtering in series \r\n // String noNoise = item.getTitleForSort(ConfigurationManager.getCurrentProfile().getBookLanguageTag());\r\n addEntryToTrookSearchDatabase(entry, ResultType.SERIES, keywords);\r\n storedSeries.add(item);\r\n }\r\n }\r\n }\r\n\r\n public static void addTag(Tag item, Element entry) {\r\n if (ConfigurationManager.getCurrentProfile().getDeviceMode() == DeviceMode.Nook) {\r\n if (!storedTags.contains(item)) {\r\n logger.debug(\"adding result for \" + item);\r\n String keywords = item.getTextToSort();\r\n addEntryToTrookSearchDatabase(entry, ResultType.TAG, keywords);\r\n storedTags.add(item);\r\n }\r\n }\r\n }\r\n\r\n public static void addBook(Book item, Element entry) {\r\n if (ConfigurationManager.getCurrentProfile().getDeviceMode() == DeviceMode.Nook) {\r\n if (!storedBooks.contains(item)) {\r\n logger.debug(\"adding result for \" + item);\r\n String keywords = item.getDisplayName();\r\n String noNoise = item.getSortName();\r\n addEntryToTrookSearchDatabase(entry, ResultType.BOOK, keywords, noNoise);\r\n storedBooks.add(item);\r\n }\r\n }\r\n }\r\n}\r",
"public class Helper {\r\n\r\n private final static Logger logger = LogManager.getLogger(Helper.class);\r\n private static final String DEFAULT_PREFIX = \"com.gmail.dpierron.\";\r\n static final int DEFAULT_STACK_DEPTH = 5;\r\n\r\n /**\r\n * checked s1.equals(s2)\r\n */\r\n public static final boolean stringEquals(String s1, String s2) {\r\n return objectEquals(s1, s2);\r\n }\r\n\r\n /**\r\n * checked s1.equals(s2)\r\n */\r\n public static final boolean objectEquals(Object o1, Object o2) {\r\n if (o1 == null || o2 == null)\r\n return (o1 == null && o2 == null);\r\n\r\n return o1.equals(o2);\r\n }\r\n\r\n public static String newId() {\r\n String result = new VMID().toString();\r\n result = result.replace('0', 'G');\r\n result = result.replace('1', 'H');\r\n result = result.replace('2', 'I');\r\n result = result.replace('3', 'J');\r\n result = result.replace('4', 'K');\r\n result = result.replace('5', 'L');\r\n result = result.replace('6', 'M');\r\n result = result.replace('7', 'N');\r\n result = result.replace('8', 'O');\r\n result = result.replace('9', 'P');\r\n result = result.replaceAll(\"-\", \"\");\r\n result = result.replaceAll(\":\", \"\");\r\n return result;\r\n }\r\n\r\n public static void logStack(Logger logger) {\r\n logStack(logger, 2, DEFAULT_STACK_DEPTH, DEFAULT_PREFIX);\r\n }\r\n\r\n public static void logStack(Logger logger, int maxDepth) {\r\n logStack(logger, 2, maxDepth, DEFAULT_PREFIX);\r\n }\r\n\r\n public static void logStack(Logger logger, int skip, int maxDepth) {\r\n logStack(logger, skip + 2, maxDepth, DEFAULT_PREFIX);\r\n }\r\n\r\n public static void logStack(Logger logger, int skip, int maxDepth, String removePrefix) {\r\n Exception e = new RuntimeException();\r\n e.fillInStackTrace();\r\n StackTraceElement[] calls = e.getStackTrace();\r\n for (int i = skip; i < maxDepth + skip; i++) {\r\n if (i >= calls.length)\r\n break;\r\n StackTraceElement call = e.getStackTrace()[i];\r\n String msg = call.toString();\r\n if (removePrefix != null) {\r\n int pos = msg.indexOf(removePrefix);\r\n if (pos > -1)\r\n msg = msg.substring(pos + removePrefix.length());\r\n }\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"Stack trace [\" + (i - skip) + \"] -> \" + msg);\r\n }\r\n }\r\n\r\n public static String concatenateList(Collection toConcatenate) {\r\n return concatenateList(null, toConcatenate, (String[]) null);\r\n }\r\n\r\n public static String concatenateList(String separator, Collection toConcatenate) {\r\n return concatenateList(separator, toConcatenate, (String[]) null);\r\n }\r\n\r\n public static String concatenateList(Collection toConcatenate, String... methodName) {\r\n return concatenateList(null, toConcatenate, methodName);\r\n }\r\n\r\n public static String concatenateList(String separator, Collection toConcatenate, String... methodName) {\r\n try {\r\n if (toConcatenate == null || toConcatenate.size() == 0)\r\n return \"\";\r\n StringBuffer lines = new StringBuffer();\r\n String theSeparator = (separator == null ? \", \" : separator);\r\n for (Object o : toConcatenate) {\r\n Object result = o;\r\n if (methodName == null) {\r\n result = o.toString();\r\n } else {\r\n for (String theMethodName : methodName) {\r\n Method method = null;\r\n try {\r\n method = result.getClass().getMethod(theMethodName);\r\n } catch (SecurityException e) {\r\n logger.warn(e.getMessage(), e); Helper.statsWarnings++;\r\n } catch (NoSuchMethodException e) {\r\n logger.warn(e.getMessage(), e); Helper.statsWarnings++;\r\n }\r\n\r\n if (method != null)\r\n try {\r\n result = method.invoke(result);\r\n } catch (IllegalArgumentException e) {\r\n logger.warn(e.getMessage(), e); Helper.statsWarnings++;\r\n } catch (IllegalAccessException e) {\r\n logger.warn(e.getMessage(), e); Helper.statsWarnings++;\r\n } catch (InvocationTargetException e) {\r\n logger.warn(e.getMessage(), e); Helper.statsWarnings++;\r\n }\r\n }\r\n }\r\n\r\n lines.append(result);\r\n lines.append(theSeparator);\r\n }\r\n String sLines = lines.length() >= theSeparator.length() ? lines.substring(0, lines.length() - theSeparator.length()) : \"\";\r\n return sLines;\r\n } catch (Exception e) {\r\n return \"\";\r\n }\r\n }\r\n\r\n public static Collection transformList(Collection toTransform, String... methodName) {\r\n List transformed = new LinkedList();\r\n try {\r\n if (toTransform == null || toTransform.size() == 0)\r\n return toTransform;\r\n for (Object o : toTransform) {\r\n Object result = o;\r\n if (methodName == null) {\r\n result = o.toString();\r\n } else {\r\n for (String theMethodName : methodName) {\r\n Method method;\r\n method = result.getClass().getMethod(theMethodName);\r\n result = method.invoke(result);\r\n }\r\n }\r\n transformed.add(result);\r\n }\r\n return transformed;\r\n } catch (Exception e) {\r\n return transformed;\r\n }\r\n }\r\n\r\n public static List<String> tokenize(String text, String delim) {\r\n return tokenize(text, delim, false);\r\n }\r\n\r\n public static List<String> tokenize(String text, String delim, boolean trim) {\r\n List<String> result = new LinkedList<String>();\r\n if (isNotNullOrEmpty(text)) {\r\n // Note: Do not use replaceall as this uses regular expressions for the 'delim'\r\n // parameter which can ahve unexpected side effects if special characters used.\r\n // String s = text.replaceAll(delim, \"�\");\r\n String s = text.replace(delim, \"�\");\r\n String[] tokens = s.split(\"�\");\r\n for (String token : tokens) {\r\n if (trim)\r\n token = token.trim();\r\n result.add(token);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n public static String deTokenize(Collection<String> list, String delim) {\r\n if (list.size() > 0) {\r\n StringBuffer sb = new StringBuffer();\r\n for (String text : list) {\r\n if (sb.length() > 0)\r\n sb.append(delim);\r\n sb.append(text);\r\n }\r\n return sb.toString();\r\n } else\r\n return \"\";\r\n }\r\n\r\n public static String leftPad(String s, char paddingCharacter, int length) {\r\n if (s.length() >= length)\r\n return s;\r\n StringBuffer sb = new StringBuffer();\r\n for (int i = s.length(); i < length; i++) {\r\n sb.append(paddingCharacter);\r\n }\r\n sb.append(s);\r\n return sb.toString();\r\n }\r\n\r\n public static String pad(String s, char paddingCharacter, int length) {\r\n if (s.length() >= length)\r\n return s;\r\n StringBuffer sb = new StringBuffer(s);\r\n for (int i = s.length(); i < length; i++) {\r\n sb.append(paddingCharacter);\r\n }\r\n return sb.toString();\r\n }\r\n\r\n /**\r\n * @return the last numeric component of string s (that is, the part of the\r\n * string to the right of the last non-numeric character)\r\n */\r\n public static String getLastNumericComponent(String s) {\r\n int i = s.length() - 1;\r\n while ((i >= 0) && (Character.isDigit(s.charAt(i))))\r\n i--;\r\n if (i < 0)\r\n return s;\r\n if (i == s.length() - 1 && !Character.isDigit(s.charAt(i)))\r\n return null;\r\n return (s.substring(i + 1));\r\n }\r\n\r\n /**\r\n * @return the right part of string s, after the first occurence of string\r\n * toSubstract, or the whole string s if it does not contain\r\n * toSubstract\r\n */\r\n public static String substractString(String s, String toSubstract) {\r\n if (isNullOrEmpty(s))\r\n return s;\r\n if (isNullOrEmpty(toSubstract))\r\n return s;\r\n if (!s.startsWith(toSubstract))\r\n return s;\r\n return s.substring(toSubstract.length());\r\n }\r\n\r\n public static boolean trueBooleanEquals(Object o1, Object o2) {\r\n return trueBoolean(o1) == trueBoolean(o2);\r\n }\r\n\r\n public static boolean trueBoolean(Object o) {\r\n if (o == null)\r\n return false;\r\n if (o instanceof Boolean)\r\n return ((Boolean) o).booleanValue();\r\n else\r\n return new Boolean(o.toString()).booleanValue();\r\n }\r\n\r\n public static Integer parseInteger(String s) {\r\n if (isNullOrEmpty(s))\r\n return null;\r\n try {\r\n int i = Integer.parseInt(s);\r\n return new Integer(i);\r\n } catch (NumberFormatException e) {\r\n return null;\r\n }\r\n }\r\n\r\n public static boolean trueStringEquals(Object o1, Object o2) {\r\n return trueString(o1).equals(trueString(o2));\r\n }\r\n\r\n public static int trueStringCompare(Object o1, Object o2) {\r\n return trueString(o1).compareTo(trueString(o2));\r\n }\r\n\r\n public static String trueString(Object o) {\r\n if (o == null)\r\n return \"\";\r\n else\r\n return o.toString();\r\n }\r\n\r\n public static Object[] arrayThis(Object[] theArray, Object... objects) {\r\n ArrayList result = listThis(objects);\r\n return result.toArray(theArray);\r\n }\r\n\r\n public static ArrayList listThis(Object... objects) {\r\n return listThis(false, objects);\r\n }\r\n\r\n public static ArrayList listThis(boolean duplicates, Object... objects) {\r\n ArrayList result = new ArrayList();\r\n if (objects != null)\r\n for (Object object : objects) {\r\n if (object == null)\r\n continue;\r\n if (object instanceof List) {\r\n List list = (List) object;\r\n if (duplicates) {\r\n result.addAll(list);\r\n } else {\r\n if (list != null)\r\n for (Object item : list) {\r\n if (item == null)\r\n continue;\r\n if (!result.contains(item))\r\n result.add(item);\r\n }\r\n }\r\n } else {\r\n result.add(object);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * This method takes a string and wraps it to a line length of no more than\r\n * wrap_length. If prepend is not null, each resulting line will be prefixed\r\n * with the prepend string. In that case, resultant line length will be no\r\n * more than wrap_length + prepend.length()\r\n */\r\n\r\n public static String wrap(String inString, int wrap_length, String prepend) {\r\n char[] charAry;\r\n\r\n int p, p2, offset = 0, marker;\r\n\r\n StringBuffer result = new StringBuffer();\r\n\r\n /* -- */\r\n\r\n if (inString == null) {\r\n return null;\r\n }\r\n\r\n if (wrap_length < 0) {\r\n throw new IllegalArgumentException(\"bad params\");\r\n }\r\n\r\n if (prepend != null) {\r\n result.append(prepend);\r\n }\r\n\r\n charAry = inString.toCharArray();\r\n\r\n p = marker = 0;\r\n\r\n // each time through the loop, p starts out pointing to the same char as\r\n // marker\r\n\r\n while (marker < charAry.length) {\r\n while (p < charAry.length && (charAry[p] != '\\n') && ((p - marker) < wrap_length)) {\r\n p++;\r\n }\r\n\r\n if (p == charAry.length) {\r\n result.append(inString.substring(marker, p));\r\n return result.toString();\r\n }\r\n\r\n if (charAry[p] == '\\n') {\r\n /*\r\n * We've got a newline. This newline is bound to have terminated the\r\n * while loop above. Step p back one character so that the isspace(*p)\r\n * check below will detect that it hit the \\n, and will do the right\r\n * thing.\r\n */\r\n\r\n result.append(inString.substring(marker, p + 1));\r\n\r\n if (prepend != null) {\r\n result.append(prepend);\r\n }\r\n\r\n p = marker = p + 1;\r\n\r\n continue;\r\n }\r\n\r\n p2 = p - 1;\r\n\r\n /*\r\n * We've either hit the end of the string, or we've gotten past the\r\n * wrap_length. Back p2 up to the last space before the wrap_length, if\r\n * there is such a space. Note that if the next character in the string\r\n * (the character immediately after the break point) is a space, we don't\r\n * need to back up at all. We'll just print up to our current location, do\r\n * the newline, and skip to the next line.\r\n */\r\n\r\n if (p < charAry.length) {\r\n if (isspace(charAry[p])) {\r\n offset = 1; /*\r\n * the next character is white space. We'll want to skip\r\n * that.\r\n */\r\n } else {\r\n /* back p2 up to the last white space before the break point */\r\n\r\n while ((p2 > marker) && !isspace(charAry[p2])) {\r\n p2--;\r\n }\r\n\r\n offset = 0;\r\n }\r\n }\r\n\r\n /*\r\n * If the line was completely filled (no place to break), we'll just copy\r\n * the whole line out and force a break.\r\n */\r\n\r\n if (p2 == marker) {\r\n p2 = p - 1;\r\n }\r\n\r\n if (!isspace(charAry[p2])) {\r\n /*\r\n * If weren't were able to back up to a space, copy out the whole line,\r\n * including the break character (in this case, we'll be making the\r\n * string one character longer by inserting a newline).\r\n */\r\n\r\n result.append(inString.substring(marker, p2 + 1));\r\n } else {\r\n /*\r\n * The break character is whitespace. We'll copy out the characters up\r\n * to but not including the break character, which we will effectively\r\n * replace with a newline.\r\n */\r\n\r\n result.append(inString.substring(marker, p2));\r\n }\r\n\r\n /* If we have not reached the end of the string, newline */\r\n\r\n if (p < charAry.length) {\r\n result.append(\"\\n\");\r\n\r\n if (prepend != null) {\r\n result.append(prepend);\r\n }\r\n }\r\n\r\n p = marker = p2 + 1 + offset;\r\n }\r\n\r\n return result.toString();\r\n }\r\n\r\n public static String wrap(String inString, int wrap_length) {\r\n return wrap(inString, wrap_length, null);\r\n }\r\n\r\n public static String wrap(String inString) {\r\n return wrap(inString, 150, null);\r\n }\r\n\r\n public static boolean isspace(char c) {\r\n return (c == '\\n' || c == ' ' || c == '\\t');\r\n }\r\n\r\n /**\r\n * checks whether the object o is contained in the collection c\r\n *\r\n * @param comparator if not null, used to determine if two items are the same\r\n */\r\n public static boolean contains(Collection c, Object o, Comparator comparator) {\r\n if (comparator == null) {\r\n // simply check if 'c' contains the pointer 'o'\r\n return c.contains(o);\r\n } else {\r\n // look into 'c' for occurence of 'o'\r\n for (Object o2 : c) {\r\n if (comparator.compare(o, o2) == 0) { // the objects match\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Computes the intersection between two collections\r\n *\r\n * @param c1 the first collection\r\n * @param c2 the second (obviously) collection\r\n */\r\n public static Collection intersect(Collection c1, Collection c2) {\r\n return intersect(c1, c2, null);\r\n }\r\n\r\n /**\r\n * Computes the intersection between two collections\r\n *\r\n * @param c1 the first collection\r\n * @param c2 the second (obviously) collection\r\n * @param comparator is used to determine if two items are the same\r\n */\r\n public static Collection intersect(Collection c1, Collection c2, Comparator comparator) {\r\n\r\n Collection result = new LinkedList();\r\n\r\n if (c1 == null || c2 == null || c1.size() == 0 || c2.size() == 0)\r\n return result;\r\n\r\n /*\r\n * This algorithm is shamelessly stolen from Collections.disjoint() ...\r\n * \r\n * We're going to iterate through c1 and test for inclusion in c2. If c1 is\r\n * a Set and c2 isn't, swap the collections. Otherwise, place the shorter\r\n * collection in c1. Hopefully this heuristic will minimize the cost of the\r\n * operation.\r\n */\r\n Collection left = c1;\r\n Collection right = c2;\r\n if ((left instanceof Set) && !(right instanceof Set) || (left.size() > right.size())) {\r\n\r\n left = c2;\r\n right = c1;\r\n }\r\n\r\n for (Object l : left) {\r\n if (contains(right, l, comparator))\r\n result.add(l);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns true if the object specified is nor null nor empty (e.g., an empty\r\n * string, or an empty collection)\r\n *\r\n * @param object the object to check\r\n * @return true if the text specified is nor null nor empty, false otherwise\r\n */\r\n public final static boolean isNotNullOrEmpty(Object object) {\r\n return !(isNullOrEmpty(object));\r\n }\r\n\r\n /**\r\n * Returns true if the object specified is nor null nor empty (e.g., an empty\r\n * string, or an empty collection, or in this case a zero-valued number)\r\n *\r\n * @param object the object to check\r\n * @return true if the text specified is null or empty, false otherwise\r\n */\r\n public final static boolean isNotNullOrEmptyOrZero(Object object) {\r\n return !(isNullOrEmpty(object, true));\r\n }\r\n\r\n /**\r\n * Returns true if the object specified is null or empty (e.g., an empty\r\n * string, or an empty collection)\r\n *\r\n * @param object the object to check\r\n * @return true if the text specified is null or empty, false otherwise\r\n */\r\n public final static boolean isNullOrEmpty(Object object) {\r\n return (isNullOrEmpty(object, false));\r\n }\r\n\r\n /**\r\n * Returns true if the object specified is null or empty (e.g., an empty\r\n * string, or an empty collection, or in this case a zero-valued number)\r\n *\r\n * @param object the object to check\r\n * @return true if the text specified is null or empty, false otherwise\r\n */\r\n public final static boolean isNullOrEmptyOrZero(Object object) {\r\n return (isNullOrEmpty(object, true));\r\n }\r\n\r\n private final static boolean isNullOrEmpty(Object object, boolean zeroEqualsEmpty) {\r\n if (object == null)\r\n return true;\r\n if (object instanceof Collection)\r\n return ((Collection) object).size() == 0;\r\n else if (object instanceof Map)\r\n return ((Map) object).size() == 0;\r\n else if (object.getClass().isArray())\r\n return ((Object[]) object).length == 0;\r\n else if (object instanceof Number && zeroEqualsEmpty)\r\n return ((Number) object).longValue() == 0;\r\n else\r\n return object.toString().length() == 0;\r\n }\r\n\r\n /**\r\n * Returns the list of files corresponding to the extension, in the currentDir\r\n * and below\r\n */\r\n public static List<File> recursivelyGetFiles(final String extension, File currentDir) {\r\n List<File> result = new LinkedList<File>();\r\n recursivelyGetFiles(extension, currentDir, result);\r\n return result;\r\n }\r\n\r\n private static void recursivelyGetFiles(final String extension, File currentDir, List<File> filesList) {\r\n String[] files = currentDir.list(new FilenameFilter() {\r\n\r\n public boolean accept(File dir, String name) {\r\n File f = new File(dir, name);\r\n return f.isDirectory() || name.endsWith(extension);\r\n }\r\n\r\n });\r\n\r\n for (String filename : files) {\r\n File f = new File(currentDir, filename);\r\n if (f.isDirectory())\r\n recursivelyGetFiles(extension, f, filesList);\r\n else\r\n filesList.add(f);\r\n }\r\n }\r\n\r\n /**\r\n * forces a string into a specific encoding\r\n */\r\n public static String forceCharset(String text, String charset) {\r\n String result = text;\r\n try {\r\n result = new String(text.getBytes(charset));\r\n } catch (UnsupportedEncodingException e) {\r\n logger.error(e.getMessage(), e); Helper.statsErrors++;\r\n }\r\n return result;\r\n }\r\n\r\n public static Object getDelegateOrNull(Object source) {\r\n return getDelegateOrNull(source, false);\r\n }\r\n\r\n public static Object getDelegateOrNull(Object source, boolean digDeep) {\r\n if (source == null)\r\n return null;\r\n Object result = source;\r\n try {\r\n Method method = source.getClass().getMethod(\"getDelegate\", (Class[]) null);\r\n if (method != null)\r\n result = method.invoke(source, (Object[]) null);\r\n } catch (SecurityException e) {\r\n // let's return the source object\r\n } catch (NoSuchMethodException e) {\r\n // let's return the source object\r\n } catch (IllegalArgumentException e) {\r\n // let's return the source object\r\n } catch (IllegalAccessException e) {\r\n // let's return the source object\r\n } catch (InvocationTargetException e) {\r\n // let's return the source object\r\n }\r\n if (digDeep && (result != source))\r\n return getDelegateOrNull(result, digDeep);\r\n else\r\n return result;\r\n }\r\n\r\n public static List filter(List source, List unwantedKeys, String method) {\r\n if (isNullOrEmpty(unwantedKeys))\r\n return source;\r\n if (isNullOrEmpty(source))\r\n return source;\r\n List result = new LinkedList();\r\n for (Object object : source) {\r\n if (object == null)\r\n continue;\r\n Object key = null;\r\n try {\r\n Method keyGetter = object.getClass().getMethod(method, (Class[]) null);\r\n if (keyGetter != null)\r\n key = keyGetter.invoke(object, (Object[]) null);\r\n } catch (SecurityException e) {\r\n // key stays null\r\n } catch (NoSuchMethodException e) {\r\n // key stays null\r\n } catch (IllegalArgumentException e) {\r\n // key stays null\r\n } catch (IllegalAccessException e) {\r\n // key stays null\r\n } catch (InvocationTargetException e) {\r\n // key stays null\r\n }\r\n if (key == null)\r\n key = object.toString();\r\n if (key != null && !unwantedKeys.contains(key))\r\n result.add(object);\r\n }\r\n return result;\r\n }\r\n\r\n public static List filter(List source, List<Class> unwantedClasses) {\r\n if (isNullOrEmpty(unwantedClasses))\r\n return source;\r\n if (isNullOrEmpty(source))\r\n return source;\r\n List result = new LinkedList();\r\n for (Object object : source) {\r\n if (object == null)\r\n continue;\r\n if (!unwantedClasses.contains(object.getClass()))\r\n result.add(object);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Fetch the entire contents of a text stream, and return it in a String.\r\n * This style of implementation does not throw Exceptions to the caller.\r\n */\r\n public static String readTextFile(InputStream is) {\r\n //...checks on aFile are elided\r\n StringBuilder contents = new StringBuilder();\r\n\r\n try {\r\n //use buffering, reading one line at a time\r\n //FileReader always assumes default encoding is OK!\r\n BufferedReader input = new BufferedReader(new InputStreamReader(is));\r\n try {\r\n String line = null; //not declared within while loop\r\n /*\r\n * readLine is a bit quirky :\r\n * it returns the content of a line MINUS the newline.\r\n * it returns null only for the END of the stream.\r\n * it returns an empty String if two newlines appear in a row.\r\n */\r\n while ((line = input.readLine()) != null) {\r\n contents.append(line);\r\n contents.append(System.getProperty(\"line.separator\"));\r\n }\r\n } finally {\r\n input.close();\r\n }\r\n } catch (IOException ex) {\r\n ex.printStackTrace();\r\n }\r\n\r\n return contents.toString();\r\n }\r\n\r\n public static String readTextFile(String fullPathFilename) throws IOException {\r\n return readTextFile(new FileInputStream(fullPathFilename));\r\n }\r\n\r\n public static File putBytesIntoFile(byte[] bytes, File file) throws IOException {\r\n FileOutputStream out = new FileOutputStream(file);\r\n try {\r\n out.write(bytes);\r\n } finally {\r\n out.close();\r\n }\r\n return file;\r\n }\r\n\r\n public static File getFileFromBytes(byte[] bytes) throws IOException {\r\n String prefix = new VMID().toString();\r\n return getFileFromBytes(bytes, prefix);\r\n }\r\n\r\n public static File getFileFromBytes(byte[] bytes, String prefix) throws IOException {\r\n File f = File.createTempFile(prefix, null);\r\n return putBytesIntoFile(bytes, f);\r\n }\r\n\r\n public static byte[] getBytesFromFile(File file) throws IOException {\r\n InputStream is = new FileInputStream(file);\r\n\r\n // Get the size of the file\r\n long length = file.length();\r\n\r\n // You cannot create an array using a long type.\r\n // It needs to be an int type.\r\n // Before converting to an int type, check\r\n // to ensure that file is not larger than Integer.MAX_VALUE.\r\n if (length > Integer.MAX_VALUE) {\r\n // File is too large\r\n }\r\n\r\n // Create the byte array to hold the data\r\n byte[] bytes = new byte[(int) length];\r\n\r\n // Read in the bytes\r\n int offset = 0;\r\n int numRead = 0;\r\n while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {\r\n offset += numRead;\r\n }\r\n\r\n // Ensure all the bytes have been read in\r\n if (offset < bytes.length) {\r\n throw new IOException(\"Could not completely read file \" + file.getName());\r\n }\r\n\r\n // Close the input stream and return bytes\r\n is.close();\r\n return bytes;\r\n }\r\n\r\n public static String nowAs14CharString() {\r\n final DateFormat format = new SimpleDateFormat(\"yyyyMMddHHmmss\");\r\n return format.format(new Date());\r\n }\r\n\r\n public static String removeLeadingZeroes(String value) {\r\n return removeLeadingChars(value, '0');\r\n }\r\n\r\n public static String removeLeadingChars(String value, char charToRemove) {\r\n if (Helper.isNotNullOrEmpty(value)) {\r\n String regex = \"^\" + charToRemove + \"*\";\r\n return value.replaceAll(regex, \"\");\r\n }\r\n return value;\r\n }\r\n\r\n public static String makeString(String baseString, int number) {\r\n if (Helper.isNotNullOrEmpty(baseString) && (number > 0)) {\r\n StringBuffer sb = new StringBuffer();\r\n for (int i = 0; i < number; i++)\r\n sb.append(baseString);\r\n return sb.toString();\r\n }\r\n return \"\";\r\n }\r\n\r\n /**\r\n * Convert the stack trace into a string suitable for logging\r\n * @param t\r\n * @return\r\n */\r\n public static String getStackTrace(Throwable t) {\r\n StringBuilder sb = new StringBuilder(\"\");\r\n if (t != null) {\r\n for (StackTraceElement element : t.getStackTrace()) {\r\n sb.append(element.toString() + '\\n');\r\n }\r\n }\r\n return sb.toString();\r\n }\r\n\r\n public static Stack<Throwable> unwrap(Throwable t) {\r\n Stack<Throwable> result = new Stack<Throwable>();\r\n while (t != null) {\r\n result.add(t);\r\n t = t.getCause();\r\n }\r\n return result;\r\n }\r\n\r\n public static class ListCopier<T> {\r\n public List<T> copyList(List<T> original, int pMaxSize) {\r\n if (original == null)\r\n return null;\r\n int maxSize = pMaxSize;\r\n if (maxSize < 0)\r\n maxSize = original.size();\r\n if (original.size() <= maxSize)\r\n return new LinkedList<T>(original);\r\n List<T> result = new LinkedList<T>();\r\n for (int i = 0; i < maxSize; i++) {\r\n result.add(original.get(i));\r\n }\r\n return result;\r\n }\r\n }\r\n\r\n\r\n public static String shorten(String s, int maxSize) {\r\n if (isNullOrEmpty(s) || maxSize < 2)\r\n return s;\r\n if (s.length() > maxSize)\r\n return s.substring(0, maxSize) + \"...\";\r\n else\r\n return s;\r\n }\r\n\r\n\r\n // ITIMPI: It appears this routine is no longer used!\r\n // the logic has been subsumed into Catalog.merge()\r\n /*\r\n public static void copy(File src, File dst, boolean checkDates) throws IOException {\r\n if (src == null || dst == null) return;\r\n\r\n if (!src.exists()) return;\r\n\r\n if (src.isDirectory()) {\r\n\r\n if (!dst.exists()) dst.mkdirs();\r\n else if (!dst.isDirectory()) return;\r\n } else {\r\n\r\n boolean copy = false;\r\n if (!dst.exists()) {\r\n // ITIMPI: Is there a reason this is not logged via logger()?\r\n System.out.println(\"creating dirs \" + dst.getPath());\r\n dst.mkdirs();\r\n copy = true;\r\n }\r\n copy = copy || (!checkDates || (src.lastModified() > dst.lastModified()));\r\n if (copy) {\r\n InputStream in = new FileInputStream(src);\r\n copy(in, dst);\r\n }\r\n }\r\n }\r\n */\r\n\r\n public static void copy(File src, File dst) throws IOException {\r\n InputStream in = null;\r\n try {\r\n in = new FileInputStream(src);\r\n Helper.copy(in, dst);\r\n } finally {\r\n if (in != null)\r\n in.close();\r\n }\r\n\r\n }\r\n\r\n public static void copy(InputStream in, File dst) throws IOException {\r\n if (!dst.exists()) {\r\n if (dst.getName().endsWith(\"_Page\"))\r\n assert true;\r\n dst.getParentFile().mkdirs();\r\n }\r\n OutputStream out = null;\r\n try {\r\n out = new FileOutputStream(dst);\r\n\r\n copy(in, out);\r\n\r\n } finally {\r\n if (out != null)\r\n out.close();\r\n }\r\n }\r\n\r\n public static void copy(InputStream in, OutputStream out) throws IOException {\r\n try {\r\n // Transfer bytes from in to out\r\n byte[] buf = new byte[1024];\r\n int len;\r\n while ((len = in.read(buf)) > 0) {\r\n out.write(buf, 0, len);\r\n }\r\n } finally {\r\n if (out != null)\r\n out.close();\r\n }\r\n }\r\n\r\n private final static String[] FilesToKeep = new String[] { \".htaccess\", \"index.html\" };\r\n\r\n /**\r\n * Delete the given folder/files.\r\n *\r\n * You can specifiy whether the file should not be deleted if it is on\r\n * the list of those to keep, or should be deleted unconditionally\r\n *\r\n * @param path File to delete\r\n * @param check Specify whether to be kept if on reserved list\r\n */\r\n\r\n static public void delete (File path, boolean check) {\r\n\r\n if (path.exists()) {\r\n // Allow for list of Delete file xceptions (#c2o-112)\r\n if (check) {\r\n for (String f : FilesToKeep) {\r\n if (path.getName().toLowerCase().endsWith(f)) {\r\n if (logger.isTraceEnabled())\r\n logger.trace(\"File not deleted (on exception list): \" + path);\r\n return;\r\n }\r\n }\r\n }\r\n if (path.isDirectory()) {\r\n File[] files = path.listFiles();\r\n if (files != null)\r\n for (int i = 0; i < files.length; i++) {\r\n delete(files[i], check);\r\n }\r\n }\r\n path.delete();\r\n }\r\n }\r\n\r\n /**\r\n * Given a path, get a count of the contained folders and files\r\n * @param path\r\n * @return\r\n */\r\n static public long count(File path) {\r\n int result = 0;\r\n if (path.exists()) {\r\n if (path.isDirectory()) {\r\n File[] files = path.listFiles();\r\n if (files != null)\r\n for (int i = 0; i < files.length; i++) {\r\n result += count(files[i]);\r\n }\r\n }\r\n result++;\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Routine to carry out comparisons using the object type's\r\n * compareTo methods. Allows for either option to be passed\r\n * in a null.\r\n * NOTE: This uses the object's compareTo for method, so for\r\n * string objects this is a strict comparison that does\r\n * not take into account locale differences. If you want\r\n * locale to be considerd then use the collator methods.\r\n * @param o1\r\n * @param o2\r\n * @return\r\n */\r\n public static int checkedCompare(Comparable o1, Comparable o2) {\r\n if (o1 == null) {\r\n if (o2 == null)\r\n return 0;\r\n else\r\n return 1;\r\n } else if (o2 == null) {\r\n if (o1 == null)\r\n return 0;\r\n else\r\n return -1;\r\n }\r\n return o1.compareTo(o2);\r\n }\r\n\r\n /**\r\n * A checked string comparison that allows for null parameters\r\n * but ignores case differences.\r\n * @param s1\r\n * @param s2\r\n * @return\r\n */\r\n public static int checkedCompareIgnorCase (String s1, String s2) {\r\n if (s1 == null) {\r\n if (s2 == null)\r\n return 0;\r\n else\r\n return 1;\r\n } else if (s2 == null) {\r\n if (s1 == null)\r\n return 0;\r\n else\r\n return -1;\r\n }\r\n return s1.toUpperCase().compareTo(s2.toUpperCase());\r\n }\r\n\r\n /**\r\n * A checked string compare that uses the collator methods\r\n * that take into account local. This method uses the\r\n * default locale.\r\n * @param s1\r\n * @param s2\r\n * @return\r\n */\r\n public static int checkedCollatorCompare (String s1, String s2, Collator collator) {\r\n if (s1 == null) {\r\n if (s2 == null)\r\n return 0;\r\n else\r\n return 1;\r\n } else if (s2 == null) {\r\n if (s1 == null)\r\n return 0;\r\n else\r\n return -1;\r\n }\r\n return collator.compare(s1, s2);\r\n }\r\n public static int checkedCollatorCompareIgnoreCase (String s1, String s2, Collator collator) {\r\n return checkedCollatorCompare(s1.toUpperCase(), s2.toUpperCase(), collator);\r\n }\r\n\r\n /**\r\n * A checked string compare that uses the collator methods\r\n * that take into account local. This method uses the\r\n * default locale.\r\n * @param s1\r\n * @param s2\r\n * @return\r\n */\r\n public static int checkedCollatorCompare (String s1, String s2) {\r\n final Collator collator = Collator.getInstance();\r\n return checkedCollatorCompare(s1, s2, collator);\r\n }\r\n /**\r\n * A checked string compare that uses the collator methods\r\n * that take into account local. This method uses the\r\n * default locale.\r\n * @param s1 First string to compare\r\n * @param s2 Second string to compare\r\n * @return\r\n */\r\n public static int checkedCollatorCompareIgnoreCase (String s1, String s2) {\r\n return checkedCollatorCompare(s1.toUpperCase(), s2.toUpperCase());\r\n }\r\n\r\n public static int checkedCollatorCompare (String s1, String s2, Locale locale) {\r\n return checkedCollatorCompare(s1, s2, Collator.getInstance(locale));\r\n }\r\n public static int checkedCollatorCompareIgnoreCase (String s1, String s2, Locale locale) {\r\n return checkedCollatorCompare(s1.toUpperCase(), s2.toUpperCase(), locale);\r\n }\r\n\r\n public static ArrayList<File> listFilesIn(File dir) {\r\n ArrayList<File> result = new ArrayList<File>();\r\n if (dir != null && dir.isDirectory()) {\r\n String[] children = dir.list();\r\n if (children != null) {\r\n for (String childName : children) {\r\n File child = new File(dir, childName);\r\n if (child.isDirectory()) {\r\n result.addAll(listFilesIn(child));\r\n }\r\n result.add(child);\r\n }\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n public static String toTitleCase(String s) {\r\n if (Helper.isNullOrEmpty(s))\r\n return s;\r\n\r\n StringBuffer sb = new StringBuffer(s.length());\r\n sb.append(Character.toUpperCase(s.charAt(0)));\r\n sb.append(s.substring(1));\r\n return sb.toString();\r\n }\r\n\r\n /**\r\n * Code to remove HTML tags from an HTML string\r\n *\r\n * TODO: Consider whether this can be better implemented\r\n * TODO: using FOM and the InnterText metthod?\r\n *\r\n * TODO: Might want to consider replacing </p> tags with CR/LF?\r\n * @param s\r\n * @return\r\n */\r\n public static String removeHtmlElements(String s) {\r\n // process possible HTML tags\r\n StringBuffer sb = new StringBuffer();\r\n if (s != null) {\r\n boolean skipping = false;\r\n for (int i = 0; i < s.length(); i++) {\r\n char c = s.charAt(i);\r\n if (!skipping) {\r\n if (c == '<')\r\n skipping = true;\r\n else\r\n sb.append(c);\r\n } else {\r\n if (c == '>')\r\n skipping = false;\r\n }\r\n }\r\n } else {\r\n return \"\";\r\n }\r\n return sb.toString();\r\n }\r\n\r\n public static String stringToHex(String base) {\r\n StringBuffer buffer = new StringBuffer();\r\n int intValue;\r\n for (int x = 0; x < base.length(); x++) {\r\n int cursor = 0;\r\n intValue = base.charAt(x);\r\n String binaryChar = new String(Integer.toBinaryString(base.charAt(x)));\r\n for (int i = 0; i < binaryChar.length(); i++) {\r\n if (binaryChar.charAt(i) == '1') {\r\n cursor += 1;\r\n }\r\n }\r\n if ((cursor % 2) > 0) {\r\n intValue += 128;\r\n }\r\n buffer.append(Integer.toHexString(intValue) + \" \");\r\n }\r\n return buffer.toString();\r\n }\r\n\r\n public static String convertToHex(String s) {\r\n if (isNullOrEmpty(s)) return \"\";\r\n StringBuffer sb = new StringBuffer();\r\n for (int pos=0;pos<s.length();pos++) {\r\n int codepoint = s.codePointAt(pos);\r\n sb.append(Integer.toHexString(codepoint));\r\n }\r\n return sb.toString();\r\n }\r\n\r\n /**\r\n * This function is the 'worker' one for handling derived names\r\n * for split-by-letter or split by page number.\r\n *\r\n * Any characters that are not alpha-numeric or the split character are hex encoded\r\n * to make the results safe to use in a URN or filename.\r\n *\r\n * As an optimisation to try and keep values start, it assumed that if the end of the\r\n * string passed in as the base corresponds to the start of the new encoded splitText\r\n * then it is only necessay to extend the name to make it unique by the difference.\r\n *\r\n * @param baseString The base string fromt he previous level\r\n * @param splitText The text for this split level\r\n * @param splitSeparator The seperator to be used between levels\r\n * @return The link to this level for parent\r\n */\r\n public static String getSplitString (String baseString, String splitText, String splitSeparator) {\r\n StringBuffer encodedSplitText = new StringBuffer();\r\n encodedSplitText.append(splitSeparator);\r\n\r\n // Get the encoded form of the splitText\r\n // TODO ITIMPI: Need to check why this encoding is needed!\r\n for (int x= 0; x < splitText.length(); x++) {\r\n char c = splitText.charAt(x);\r\n if (Character.isLetterOrDigit(c)) {\r\n // Alphanumerics are passed through unchanged\r\n encodedSplitText.append(c);\r\n } else {\r\n // Other characters are hex encoded\r\n encodedSplitText.append(Integer.toHexString(c));\r\n }\r\n }\r\n // Now see if we only we need to extend the basename or add a new section\r\n int pos = baseString.lastIndexOf(splitSeparator);\r\n if (pos > 0) {\r\n // Get the amount we want to check\r\n String checkPart = baseString.substring(pos);\r\n if (encodedSplitText.toString().length() != checkPart.length()\r\n && encodedSplitText.toString().startsWith(checkPart)) {\r\n baseString = baseString.substring(0,pos);\r\n }\r\n }\r\n return baseString + encodedSplitText.toString();\r\n }\r\n\r\n /*\r\n * Convert a parameter option 'glob' that contains ? and * wildcards to a regex\r\n *\r\n * Adapted from routine found via google search\r\n */\r\n public static String convertGlobToRegEx(String line) {\r\n line = line.trim();\r\n int strLen = line.length();\r\n StringBuilder sb = new StringBuilder(strLen);\r\n // Remove beginning and ending * globs because they're useless\r\n // TODO: ITMPI This does not seem to be true - not sure why code was originally here!\r\n /*\r\n if (line.startsWith(\"*\"))\r\n {\r\n line = line.substring(1);\r\n strLen--;\r\n }\r\n if (line.endsWith(\"*\"))\r\n {\r\n line = line.substring(0, strLen-1);\r\n strLen--;\r\n }\r\n */\r\n boolean escaping = false;\r\n int inCurlies = 0;\r\n for (char currentChar : line.toCharArray())\r\n {\r\n switch (currentChar)\r\n {\r\n // Wild car characters\r\n case '*':\r\n if (escaping)\r\n sb.append(\"\\\\*\");\r\n else\r\n sb.append(\".+\");\r\n escaping = false;\r\n break;\r\n case '?':\r\n if (escaping)\r\n sb.append(\"\\\\?\");\r\n else\r\n sb.append('.');\r\n escaping = false;\r\n break;\r\n // Characters needing special treatment\r\n case '.':\r\n case '(':\r\n case ')':\r\n case '+':\r\n case '|':\r\n case '^':\r\n case '$':\r\n case '@':\r\n case '%':\r\n // TODO ITIMPI: Following added as special cases below seem not relevant\r\n case '[':\r\n case ']':\r\n case '\\\\':\r\n case '{':\r\n case '}':\r\n case ',':\r\n sb.append('\\\\');\r\n sb.append(currentChar);\r\n escaping = false;\r\n break;\r\n/*\r\n case '\\\\':\r\n if (escaping)\r\n {\r\n sb.append(\"\\\\\\\\\");\r\n escaping = false;\r\n }\r\n else\r\n escaping = true;\r\n break;\r\n case '{':\r\n if (escaping)\r\n {\r\n sb.append(\"\\\\{\");\r\n }\r\n else\r\n {\r\n sb.append('(');\r\n inCurlies++;\r\n }\r\n escaping = false;\r\n break;\r\n case '}':\r\n if (inCurlies > 0 && !escaping)\r\n {\r\n sb.append(')');\r\n inCurlies--;\r\n }\r\n else if (escaping)\r\n sb.append(\"\\\\}\");\r\n else\r\n sb.append(\"}\");\r\n escaping = false;\r\n break;\r\n case ',':\r\n if (inCurlies > 0 && !escaping)\r\n {\r\n sb.append('|');\r\n }\r\n else if (escaping)\r\n sb.append(\"\\\\,\");\r\n else\r\n sb.append(\",\");\r\n break;\r\n*/\r\n // characters that can just be passed through unchanged\r\n default:\r\n escaping = false;\r\n sb.append(currentChar);\r\n }\r\n }\r\n return sb.toString();\r\n }\r\n\r\n // All possible locales\r\n private final static Locale[] availableLocales = Locale.getAvailableLocales();\r\n // Saved subset that we have actually used for faster searching\r\n // (can have duplicates under different length keys)\r\n private static HashMap<String,Locale> usedLocales = new HashMap<String, Locale>();\r\n /**\r\n * Get the local that corresponds to the provided language string\r\n * The following assumptions are made about the supplied parameter:\r\n * - If it is 2 characters in length then it is assumed to be the ISO2 value\r\n * - If it is 3 characters in length then it is assumed to be the ISO3 value\r\n * - If it is 4+ characters then it is assumed to be the Display Language text\r\n * If no match can be found then the English Locale is always returned\r\n * TODO: Perhaps we should consider returning null if no match found?\r\n *\r\n * @param lang\r\n * @return Locale\r\n */\r\n public static Locale getLocaleFromLanguageString(String lang) {\r\n if (usedLocales.containsKey(lang)) {\r\n return usedLocales.get(lang);\r\n }\r\n if (lang != null && lang.length() > 1) {\r\n for (Locale l : availableLocales) {\r\n switch (lang.length()) {\r\n // Note te case of a 2 character lang needs special treatment - see Locale code for getLangugage\r\n case 2: String s = l.toString();\r\n String ll = l.getLanguage();\r\n if (s.length() < 2 || s.length() > 2) break; // Ignore entries that are not 2 characters\r\n if (! s.equalsIgnoreCase(lang)) break;\r\n usedLocales.put(lang,l);\r\n return l;\r\n case 3: if (! l.getISO3Language().equalsIgnoreCase(lang)) break;\r\n usedLocales.put(lang,l);\r\n return l;\r\n default: if (! l.getDisplayLanguage().equalsIgnoreCase(lang)) break;\r\n usedLocales.put(lang,l);\r\n return l;\r\n }\r\n }\r\n }\r\n logger.warn(\"Program Error: Unable to find locale for '\" + lang + \"'\"); Helper.statsWarnings++;\r\n return null;\r\n }\r\n /**\r\n * Convert a pseudo=html string to plain text\r\n *\r\n * We sometimes use a form of Pseudo-HTML is strings that are to be\r\n * displayed in the GUI. These can be identifed by the fact that they\r\n * start with <HTML> andd contain <BR> where end-of-line is wanted.\r\n */\r\n public static String getTextFromPseudoHtmlText (String htmltext) {\r\n String text;\r\n if (! htmltext.toUpperCase().startsWith(\"<HTML>\")) {\r\n text = htmltext;\r\n } else {\r\n text = htmltext.substring(\"<HTML>\".length()).toUpperCase().replace(\"<br>\", \"\\r\\n\");\r\n }\r\n return text;\r\n }\r\n\r\n private static File installDirectory;\r\n\r\n /**\r\n *\r\n * @return\r\n */\r\n public static File getInstallDirectory() {\r\n if (installDirectory == null) {\r\n URL mySource = Helper.class.getProtectionDomain().getCodeSource().getLocation();\r\n File sourceFile = new File(mySource.getPath());\r\n installDirectory = sourceFile.getParentFile();\r\n }\r\n return installDirectory;\r\n }\r\n\r\n // Some Stats to accumulate\r\n // NOTE. We make them public to avoid needing getters\r\n public static long statsXmlChanged; // Count of files where we realise during generation that XML unchanged\r\n public static long statsXmlDiscarded; // count of XML files generated and then discarded as not needed for final catalog\r\n public static long statsHtmlChanged; // Count of files where HTML not generated as XML unchanged.\r\n public static long statsXmlUnchanged; // Count of files where we realise during generation that XML unchanged\r\n public static long statsHtmlUnchanged; // Count of files where HTML not generated as XML unchanged.\r\n public static long statsCopyExistHits; // Count of Files that are copied because target does not exist\r\n public static long statsCopyLengthHits; // Count of files that are copied because lengths differ\r\n public static long statsCopyDateMisses; // Count of files that are not copied because source older\r\n public static long statsCopyCrcHits; // Count of files that are copied because CRC different\r\n public static long statsCopyCrcMisses; // Count of files copied because CRC same\r\n public static long statsCopyToSelf; // Count of cases where copy to self requested\r\n public static long statsCopyUnchanged; // Count of cases where copy skipped because file was not even generated\r\n public static long statsCopyDeleted; // Count of files/folders deleted during copy process\r\n public static long statsBookUnchanged; // We detected that the book was unchanged since last run\r\n public static long statsBookChanged; // We detected that the book was changed since last run\r\n public static long statsCoverUnchanged; // We detected that the cover was unchanged since last run\r\n public static long statsCoverChanged; // We detected that the cover was changed since last run\r\n public static long statsWarnings; // Number of warning messages logged in a catalog run\r\n public static long statsErrors; // Number of error messages logged in a catalog run\r\n\r\n public static void resetStats() {\r\n statsXmlChanged\r\n = statsXmlDiscarded\r\n = statsHtmlChanged\r\n = statsXmlUnchanged\r\n = statsHtmlUnchanged\r\n = statsCopyExistHits\r\n = statsCopyLengthHits\r\n = statsCopyCrcHits\r\n = statsCopyCrcMisses\r\n = statsCopyDateMisses\r\n = statsCopyUnchanged\r\n = statsBookUnchanged\r\n = statsBookChanged\r\n = statsCoverUnchanged\r\n = statsCoverChanged\r\n = statsWarnings\r\n = statsErrors\r\n = 0;\r\n }\r\n}\r",
"public class TreeNode {\r\n private Object data;\r\n private String id;\r\n private TreeNode parent;\r\n private List<TreeNode> children;\r\n\r\n public TreeNode(String id) {\r\n this(id, null);\r\n }\r\n\r\n public TreeNode(String id, Object data) {\r\n super();\r\n this.data = data;\r\n this.id = id;\r\n }\r\n\r\n public Object getData() {\r\n return data;\r\n }\r\n\r\n public void setData(Object data) {\r\n this.data = data;\r\n }\r\n\r\n public boolean isRoot() {\r\n return this instanceof RootTreeNode;\r\n }\r\n\r\n public TreeNode getParent() {\r\n return parent;\r\n }\r\n\r\n public void setParent(TreeNode parent) {\r\n this.parent = parent;\r\n }\r\n\r\n public List<TreeNode> getChildren() {\r\n if (children == null)\r\n children = new LinkedList<TreeNode>();\r\n return children;\r\n }\r\n\r\n public void setChildren(List<TreeNode> newChildren) {\r\n this.children = newChildren;\r\n }\r\n\r\n public TreeNode getChildWithId(String id) {\r\n for (TreeNode childNode : getChildren()) {\r\n if (childNode.getId().equals(id))\r\n return childNode;\r\n }\r\n return null;\r\n }\r\n\r\n public void addChild(TreeNode child) {\r\n if (child == null)\r\n return;\r\n getChildren().add(child);\r\n child.setParent(this);\r\n }\r\n\r\n public String getId() {\r\n return id;\r\n }\r\n\r\n public void setId(String value) {\r\n this.id = value;\r\n }\r\n\r\n public String getIdToRoot() {\r\n return getIdToRoot(\"_\");\r\n }\r\n\r\n public String getIdToRoot(String separator) {\r\n List<String> ids = new LinkedList<String>();\r\n TreeNode node = this;\r\n while (node.getParent() != null) {\r\n ids.add(node.getId());\r\n node = node.getParent();\r\n }\r\n Collections.reverse(ids);\r\n return Helper.concatenateList(separator, ids);\r\n }\r\n\r\n public String getGuid() {\r\n String guid = getIdToRoot();\r\n StringBuffer sb = new StringBuffer();\r\n for (int i = 0; i < guid.length(); i++) {\r\n char c = guid.charAt(i);\r\n if (Character.isLetterOrDigit(c))\r\n sb.append(c);\r\n else\r\n sb.append('_');\r\n }\r\n return sb.toString();\r\n }\r\n\r\n public String toString() {\r\n String base = getIdToRoot(\"/\");\r\n if (getData() == null)\r\n return base;\r\n else\r\n return base + \" (\" + getData() + \")\";\r\n }\r\n}\r"
] | import com.gmail.dpierron.calibre.configuration.Icons;
import com.gmail.dpierron.calibre.datamodel.Book;
import com.gmail.dpierron.calibre.datamodel.Tag;
import com.gmail.dpierron.tools.i18n.Localization;
import com.gmail.dpierron.calibre.trook.TrookSpecificSearchDatabaseManager;
import com.gmail.dpierron.tools.Helper;
import com.gmail.dpierron.tools.RootTreeNode;
import com.gmail.dpierron.tools.TreeNode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
| package com.gmail.dpierron.calibre.opds;
/**
* Class for defining a new tree set of levels based on a tag,
* with tags possibly split by a defined character. This is
* a way f implementing what are known as hierarchical tags
* in Calibre.
*/
public class TagTreeSubCatalog extends TagsSubCatalog {
private final static Logger logger = LogManager.getLogger(TagTreeSubCatalog.class);
// CONSTRUCTOR(S)
public TagTreeSubCatalog(List<Object> stuffToFilterOut, List<Book> books) {
super(stuffToFilterOut, books);
setCatalogType(Constants.TAGTREE_TYPE);
}
public TagTreeSubCatalog(List<Book> books) {
super(books);
setCatalogType(Constants.TAGTREE_TYPE);
}
// METHODS
/**
* Generate a tag tree for the current level
*
* The actual tag associated with a node is stored
* as data information
*
* @param pBreadcrumbs
* @return
* @throws IOException
*/
@Override
Element getCatalog(Breadcrumbs pBreadcrumbs, boolean inSubDir) throws IOException {
Element result;
if (logger.isDebugEnabled()) logger.debug("getCatalog: pBreadcrumbs=" + pBreadcrumbs.toString() + ", inSubDir=" + inSubDir);
String splitTagsOn = currentProfile.getSplitTagsOn();
assert Helper.isNotNullOrEmpty(splitTagsOn);
TreeNode root = new RootTreeNode();
// Work through the tags creating the tree
if (logger.isTraceEnabled()) logger.trace("generate initial tree");
for (Tag tag : getTags()) {
String[] partsOfTag = tag.getPartsOfTag(splitTagsOn);
TreeNode currentPositionInTree = root;
for (int i = 0; i < partsOfTag.length; i++) {
String partOfTag = partsOfTag[i];
TreeNode nextPositionInTree = currentPositionInTree.getChildWithId(partOfTag);
if (nextPositionInTree == null) {
nextPositionInTree = new TreeNode(partOfTag);
currentPositionInTree.addChild(nextPositionInTree);
currentPositionInTree = nextPositionInTree;
} else
currentPositionInTree = nextPositionInTree;
}
// Mark the tag this node uses
currentPositionInTree.setData(tag);
}
// browse the tree, removing unneeded levels (single childs up to the leafs)
if (logger.isTraceEnabled()) logger.trace("remove unneeded levels");
removeUnNeededLevelsInTree(root, null);
// Now get the resulting page set
result = getLevelOfTreeNode(pBreadcrumbs, root);
if (logger.isDebugEnabled()) logger.debug("getCatalog: exit (pBreadcrumbs=" + pBreadcrumbs.toString() + ")");
return result;
}
/**
* Trim un-needed nodes from the tree.
*
* We assume that any node that only has a single
* child can effectively have the child collapsed
* into the parent node. This will stop us generating
* a series of pages that only have a single entry.
*
* NOTE: It is written as a free-standing routine so it cn be called recursively.
*
* @param node
* @param removedParent
* @return
*/
private TreeNode removeUnNeededLevelsInTree(TreeNode node, TreeNode removedParent) {
// if (logger.isTraceEnabled()) logger.trace("removeUnNeededLevel: node=" + node + ", removedParent=" + removedParent);
if (removedParent != null) {
node.setId(removedParent.getId() + currentProfile.getSplitTagsOn() + node.getId());
}
if (node.getData() != null) {
// this is a leaf
return node;
}
List<TreeNode> newChildren = new LinkedList<TreeNode>();
for (TreeNode childNode : node.getChildren()) {
if (childNode.getData() == null && childNode.getChildren().size() <= 1) {
if (childNode.getChildren().size() == 0) {
// useless node
// TODO: ITIMPI: Feel there should be something done here if this condition can really ever occur
int dummy = 1; // TODO See if we really ever get here!
} else {
// useless level so remove it
TreeNode newChild = removeUnNeededLevelsInTree(childNode.getChildren().get(0), childNode);
if (newChild != null) {
newChild.setParent(node);
newChildren.add(newChild);
}
}
} else {
newChildren.add(removeUnNeededLevelsInTree(childNode, null));
}
}
node.setChildren(newChildren);
return node;
}
/**
* Initial entry point to creating a tree list of tags
*
* @param pBreadcrumbs
* @param level
* @return
* @throws IOException
*/
private Element getLevelOfTreeNode(Breadcrumbs pBreadcrumbs, TreeNode level) throws IOException {
if (logger.isDebugEnabled()) logger.debug("getLevelOfTreeNode: pBreadcrumbs=" + pBreadcrumbs + ", level=" + level);
Element result;
if (Helper.isNullOrEmpty(level.getChildren())) {
Tag tag = (Tag) level.getData();
if (tag == null) {
if (logger.isDebugEnabled()) logger.debug("getLevelOfTreeNode: Exinull (Appears to be an empty level!)");
return null;
}
// it's a leaf, consisting of a single tag : make a list of books
if (logger.isTraceEnabled()) logger.trace("getLevelOfTreeNode: it's a leaf, consisting of a single tag : make a list of books");
String urn = Constants.INITIAL_URN_PREFIX + getCatalogType()+ level.getGuid();
result = getDetailedEntry(pBreadcrumbs, tag, urn, level.getId());
| TrookSpecificSearchDatabaseManager.addTag(tag, result);
| 2 |
ketayao/fensy | src/main/java/com/ketayao/fensy/mvc/DispatcherFilter.java | [
"public class DBManager {\n\n private final static Logger log = LoggerFactory\n .getLogger(DBManager.class);\n private final static ThreadLocal<Connection> conns = new ThreadLocal<Connection>();\n private static DataSource dataSource;\n private static boolean showSql = false;\n public static String prefixTableName = \"\";\n\n static {\n initDataSource(null);\n }\n\n public static DataSource getDataSource() {\n return dataSource;\n }\n\n /**\n * 初始化连接池\n * @param props\n * @param show_sql\n */\n private final static void initDataSource(Properties dbProperties) {\n try {\n if (dbProperties == null) {\n dbProperties = new Properties();\n dbProperties.load(DBManager.class\n .getResourceAsStream(\"/\" + Constants.FENSY_CONFIG_FILE));\n }\n\n Properties props = new Properties();\n for (Object key : dbProperties.keySet()) {\n String skey = (String) key;\n\n if (skey.startsWith(\"jdbc.\")) {\n String name = skey.substring(5);\n props.put(name, dbProperties.getProperty(skey));\n if (\"showSql\".equalsIgnoreCase(name)) {\n showSql = \"true\".equalsIgnoreCase(dbProperties.getProperty(skey));\n } else if (\"prefixTableName\".equalsIgnoreCase(name)) {\n prefixTableName = dbProperties.getProperty(skey);\n }\n }\n }\n\n dataSource = (DataSource) Class.forName(props.getProperty(\"dataSource\")).newInstance();\n if (dataSource.getClass().getName().indexOf(\"c3p0\") > 0) {\n // Disable JMX in C3P0\n System.setProperty(\"com.mchange.v2.c3p0.management.ManagementCoordinator\",\n \"com.mchange.v2.c3p0.management.NullManagementCoordinator\");\n }\n log.info(\"Using DataSource : \" + dataSource.getClass().getName());\n BeanUtils.populate(dataSource, props);// 将props的值注入dataSource属性。\n\n Connection conn = getConnection();\n DatabaseMetaData mdm = conn.getMetaData();\n log.info(\"Connected to \" + mdm.getDatabaseProductName() + \" \"\n + mdm.getDatabaseProductVersion());\n closeConnection();\n } catch (Exception e) {\n throw new DBException(e);\n }\n }\n\n /**\n * 断开连接池\n */\n public final static void closeDataSource() {\n try {\n dataSource.getClass().getMethod(\"close\").invoke(dataSource);\n } catch (NoSuchMethodException e) {\n } catch (Exception e) {\n log.error(\"Unabled to destroy DataSource!!! \", e);\n }\n }\n\n /**\n * 获取连接\n * @return\n * @throws SQLException\n */\n public final static Connection getConnection() throws SQLException {\n Connection conn = conns.get();\n if (conn == null || conn.isClosed()) {\n conn = dataSource.getConnection();\n conns.set(conn);\n }\n\n return (showSql && !Proxy.isProxyClass(conn.getClass())) ? new DebugConnection(conn)\n .getConnection() : conn;\n }\n\n /**\n * 关闭连接\n */\n public final static void closeConnection() {\n Connection conn = conns.get();\n try {\n if (conn != null && !conn.isClosed()) {\n conn.setAutoCommit(true);\n conn.close();\n }\n } catch (SQLException e) {\n log.error(\"Unabled to close connection!!! \", e);\n }\n conns.remove();\n }\n\n /**\n * 用于跟踪执行的SQL语句\n */\n static class DebugConnection implements InvocationHandler {\n\n private final static Logger log = LoggerFactory.getLogger(DebugConnection.class);\n\n private Connection conn = null;\n\n public DebugConnection(Connection conn) {\n this.conn = conn;\n }\n\n /**\n * Returns the conn.\n * @return Connection\n */\n public Connection getConnection() {\n return (Connection) Proxy.newProxyInstance(conn.getClass().getClassLoader(), conn\n .getClass().getInterfaces(), this);\n }\n\n public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {\n try {\n String method = m.getName();\n if (\"prepareStatement\".equals(method) || \"createStatement\".equals(method))\n log.info(\"[SQL] >>> \" + args[0]);\n return m.invoke(conn, args);\n } catch (InvocationTargetException e) {\n throw e.getTargetException();\n }\n }\n\n }\n\n}",
"public class NotFoundTemplateException extends FensyException {\n\n\t/** 描述 */\n\tprivate static final long serialVersionUID = 4297542590778361854L;\n\n\t/** \n\t * \n\t */ \n\tpublic NotFoundTemplateException() {\n\t\tsuper();\n\t}\n\n\t/** \n\t * @param message\n\t * @param cause \n\t */ \n\tpublic NotFoundTemplateException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\t/** \n\t * @param message \n\t */ \n\tpublic NotFoundTemplateException(String message) {\n\t\tsuper(message);\n\t}\n\n\t/** \n\t * @param cause \n\t */ \n\tpublic NotFoundTemplateException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n\t\n\t/** \n\t * @param cause \n\t */ \n\tpublic static NotFoundTemplateException build(String path, List<View> viewList) {\n\t\tStringBuilder msg = new StringBuilder();\n\t\tmsg.append(\"Not found template:\" + path + \", ext is\");\n\t\tfor (View fensyView : viewList) {\n\t\t\tmsg.append(\" \" + fensyView.getExt());\n\t\t}\n\t\tmsg.append(\".\");\n\t\t\n\t\treturn new NotFoundTemplateException(msg.toString());\n\t}\n\t\n}",
"public interface Interceptor {\n\n\tpublic boolean preHandle(WebContext rc, Object handler)\n\t\tthrows Exception;\n\n\tpublic void postHandle(WebContext rc, Object handler, Object result)\n\t\t\tthrows Exception;\n\n\tpublic void afterCompletion(WebContext rc, Object handler, Exception ex)\n\t\t\tthrows Exception;\n}",
"public abstract class ClassUtils {\n\n /**\n * 扫描给定包的所有类\n * \n * @param packageName\n * 包名\n * @param recursive\n * 是否递归子包\n * @return\n */\n public static Collection<String> getClassNames(String packageName, boolean recursive) {\n String packagePath = packageName.replace('.', File.separatorChar);\n URL url = ClassUtils.class.getClassLoader().getResource(packagePath);\n\n String path = null;\n try {\n path = URLDecoder.decode(url.getPath(), \"utf-8\");// 处理空格等特殊字符\n } catch (UnsupportedEncodingException e) {\n }\n\n Collection<File> files = FileUtils.listFiles(new File(path), new String[] { \"class\" },\n recursive);\n Collection<String> classNames = new HashSet<String>();\n for (File file : files) {\n String name = StringUtils.substringAfterLast(file.getPath(), packagePath);\n classNames.add(packageName + StringUtils\n .substringBeforeLast(name.replace(File.separatorChar, '.'), \".class\"));\n }\n\n return classNames;\n }\n}",
"public class Exceptions {\n\n\t/**\n\t * 将CheckedException转换为UncheckedException.\n\t */\n\tpublic static RuntimeException unchecked(Exception e) {\n\t\tif (e instanceof RuntimeException) {\n\t\t\treturn (RuntimeException) e;\n\t\t} else {\n\t\t\treturn new RuntimeException(e);\n\t\t}\n\t}\n\n\t/**\n\t * 将ErrorStack转化为String.\n\t */\n\tpublic static String getStackTraceAsString(Exception e) {\n\t\tStringWriter stringWriter = new StringWriter();\n\t\te.printStackTrace(new PrintWriter(stringWriter));\n\t\treturn stringWriter.toString();\n\t}\n\n\t/**\n\t * 判断异常是否由某些底层的异常引起.\n\t */\n\tpublic static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {\n\t\tThrowable cause = ex;\n\t\twhile (cause != null) {\n\t\t\tfor (Class<? extends Exception> causeClass : causeExceptionClasses) {\n\t\t\t\tif (causeClass.isInstance(cause)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcause = cause.getCause();\n\t\t}\n\t\treturn false;\n\t}\n}",
"public class NumberUtils {\n\n /** Reusable Long constant for zero. */\n public static final Long LONG_ZERO = Long.valueOf(0L);\n /** Reusable Long constant for one. */\n public static final Long LONG_ONE = Long.valueOf(1L);\n /** Reusable Long constant for minus one. */\n public static final Long LONG_MINUS_ONE = Long.valueOf(-1L);\n /** Reusable Integer constant for zero. */\n public static final Integer INTEGER_ZERO = Integer.valueOf(0);\n /** Reusable Integer constant for one. */\n public static final Integer INTEGER_ONE = Integer.valueOf(1);\n /** Reusable Integer constant for minus one. */\n public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1);\n /** Reusable Short constant for zero. */\n public static final Short SHORT_ZERO = Short.valueOf((short) 0);\n /** Reusable Short constant for one. */\n public static final Short SHORT_ONE = Short.valueOf((short) 1);\n /** Reusable Short constant for minus one. */\n public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1);\n /** Reusable Byte constant for zero. */\n public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0);\n /** Reusable Byte constant for one. */\n public static final Byte BYTE_ONE = Byte.valueOf((byte) 1);\n /** Reusable Byte constant for minus one. */\n public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1);\n /** Reusable Double constant for zero. */\n public static final Double DOUBLE_ZERO = Double.valueOf(0.0d);\n /** Reusable Double constant for one. */\n public static final Double DOUBLE_ONE = Double.valueOf(1.0d);\n /** Reusable Double constant for minus one. */\n public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d);\n /** Reusable Float constant for zero. */\n public static final Float FLOAT_ZERO = Float.valueOf(0.0f);\n /** Reusable Float constant for one. */\n public static final Float FLOAT_ONE = Float.valueOf(1.0f);\n /** Reusable Float constant for minus one. */\n public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f);\n\n /**\n * <p><code>NumberUtils</code> instances should NOT be constructed in standard programming.\n * Instead, the class should be used as <code>NumberUtils.toInt(\"6\");</code>.</p>\n *\n * <p>This constructor is public to permit tools that require a JavaBean instance\n * to operate.</p>\n */\n public NumberUtils() {\n super();\n }\n\n //-----------------------------------------------------------------------\n /**\n * <p>Convert a <code>String</code> to an <code>int</code>, returning\n * <code>zero</code> if the conversion fails.</p>\n *\n * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>\n *\n * <pre>\n * NumberUtils.toInt(null) = 0\n * NumberUtils.toInt(\"\") = 0\n * NumberUtils.toInt(\"1\") = 1\n * </pre>\n *\n * @param str the string to convert, may be null\n * @return the int represented by the string, or <code>zero</code> if\n * conversion fails\n * @since 2.1\n */\n public static int toInt(String str) {\n return toInt(str, 0);\n }\n\n /**\n * <p>Convert a <code>String</code> to an <code>int</code>, returning a\n * default value if the conversion fails.</p>\n *\n * <p>If the string is <code>null</code>, the default value is returned.</p>\n *\n * <pre>\n * NumberUtils.toInt(null, 1) = 1\n * NumberUtils.toInt(\"\", 1) = 1\n * NumberUtils.toInt(\"1\", 0) = 1\n * </pre>\n *\n * @param str the string to convert, may be null\n * @param defaultValue the default value\n * @return the int represented by the string, or the default if conversion fails\n * @since 2.1\n */\n public static int toInt(String str, int defaultValue) {\n if (str == null) {\n return defaultValue;\n }\n try {\n return Integer.parseInt(str);\n } catch (NumberFormatException nfe) {\n return defaultValue;\n }\n }\n\n /**\n * <p>Convert a <code>String</code> to a <code>long</code>, returning\n * <code>zero</code> if the conversion fails.</p>\n *\n * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>\n *\n * <pre>\n * NumberUtils.toLong(null) = 0L\n * NumberUtils.toLong(\"\") = 0L\n * NumberUtils.toLong(\"1\") = 1L\n * </pre>\n *\n * @param str the string to convert, may be null\n * @return the long represented by the string, or <code>0</code> if\n * conversion fails\n * @since 2.1\n */\n public static long toLong(String str) {\n return toLong(str, 0L);\n }\n\n /**\n * <p>Convert a <code>String</code> to a <code>long</code>, returning a\n * default value if the conversion fails.</p>\n *\n * <p>If the string is <code>null</code>, the default value is returned.</p>\n *\n * <pre>\n * NumberUtils.toLong(null, 1L) = 1L\n * NumberUtils.toLong(\"\", 1L) = 1L\n * NumberUtils.toLong(\"1\", 0L) = 1L\n * </pre>\n *\n * @param str the string to convert, may be null\n * @param defaultValue the default value\n * @return the long represented by the string, or the default if conversion fails\n * @since 2.1\n */\n public static long toLong(String str, long defaultValue) {\n if (str == null) {\n return defaultValue;\n }\n try {\n return Long.parseLong(str);\n } catch (NumberFormatException nfe) {\n return defaultValue;\n }\n }\n\n /**\n * <p>Convert a <code>String</code> to a <code>float</code>, returning\n * <code>0.0f</code> if the conversion fails.</p>\n *\n * <p>If the string <code>str</code> is <code>null</code>,\n * <code>0.0f</code> is returned.</p>\n *\n * <pre>\n * NumberUtils.toFloat(null) = 0.0f\n * NumberUtils.toFloat(\"\") = 0.0f\n * NumberUtils.toFloat(\"1.5\") = 1.5f\n * </pre>\n *\n * @param str the string to convert, may be <code>null</code>\n * @return the float represented by the string, or <code>0.0f</code>\n * if conversion fails\n * @since 2.1\n */\n public static float toFloat(String str) {\n return toFloat(str, 0.0f);\n }\n\n /**\n * <p>Convert a <code>String</code> to a <code>float</code>, returning a\n * default value if the conversion fails.</p>\n *\n * <p>If the string <code>str</code> is <code>null</code>, the default\n * value is returned.</p>\n *\n * <pre>\n * NumberUtils.toFloat(null, 1.1f) = 1.0f\n * NumberUtils.toFloat(\"\", 1.1f) = 1.1f\n * NumberUtils.toFloat(\"1.5\", 0.0f) = 1.5f\n * </pre>\n *\n * @param str the string to convert, may be <code>null</code>\n * @param defaultValue the default value\n * @return the float represented by the string, or defaultValue\n * if conversion fails\n * @since 2.1\n */\n public static float toFloat(String str, float defaultValue) {\n if (str == null) {\n return defaultValue;\n }\n try {\n return Float.parseFloat(str);\n } catch (NumberFormatException nfe) {\n return defaultValue;\n }\n }\n\n /**\n * <p>Convert a <code>String</code> to a <code>double</code>, returning\n * <code>0.0d</code> if the conversion fails.</p>\n *\n * <p>If the string <code>str</code> is <code>null</code>,\n * <code>0.0d</code> is returned.</p>\n *\n * <pre>\n * NumberUtils.toDouble(null) = 0.0d\n * NumberUtils.toDouble(\"\") = 0.0d\n * NumberUtils.toDouble(\"1.5\") = 1.5d\n * </pre>\n *\n * @param str the string to convert, may be <code>null</code>\n * @return the double represented by the string, or <code>0.0d</code>\n * if conversion fails\n * @since 2.1\n */\n public static double toDouble(String str) {\n return toDouble(str, 0.0d);\n }\n\n /**\n * <p>Convert a <code>String</code> to a <code>double</code>, returning a\n * default value if the conversion fails.</p>\n *\n * <p>If the string <code>str</code> is <code>null</code>, the default\n * value is returned.</p>\n *\n * <pre>\n * NumberUtils.toDouble(null, 1.1d) = 1.1d\n * NumberUtils.toDouble(\"\", 1.1d) = 1.1d\n * NumberUtils.toDouble(\"1.5\", 0.0d) = 1.5d\n * </pre>\n *\n * @param str the string to convert, may be <code>null</code>\n * @param defaultValue the default value\n * @return the double represented by the string, or defaultValue\n * if conversion fails\n * @since 2.1\n */\n public static double toDouble(String str, double defaultValue) {\n if (str == null) {\n return defaultValue;\n }\n try {\n return Double.parseDouble(str);\n } catch (NumberFormatException nfe) {\n return defaultValue;\n }\n }\n\n //-----------------------------------------------------------------------\n /**\n * <p>Convert a <code>String</code> to a <code>byte</code>, returning\n * <code>zero</code> if the conversion fails.</p>\n *\n * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>\n *\n * <pre>\n * NumberUtils.toByte(null) = 0\n * NumberUtils.toByte(\"\") = 0\n * NumberUtils.toByte(\"1\") = 1\n * </pre>\n *\n * @param str the string to convert, may be null\n * @return the byte represented by the string, or <code>zero</code> if\n * conversion fails\n * @since 2.5\n */\n public static byte toByte(String str) {\n return toByte(str, (byte) 0);\n }\n\n /**\n * <p>Convert a <code>String</code> to a <code>byte</code>, returning a\n * default value if the conversion fails.</p>\n *\n * <p>If the string is <code>null</code>, the default value is returned.</p>\n *\n * <pre>\n * NumberUtils.toByte(null, 1) = 1\n * NumberUtils.toByte(\"\", 1) = 1\n * NumberUtils.toByte(\"1\", 0) = 1\n * </pre>\n *\n * @param str the string to convert, may be null\n * @param defaultValue the default value\n * @return the byte represented by the string, or the default if conversion fails\n * @since 2.5\n */\n public static byte toByte(String str, byte defaultValue) {\n if (str == null) {\n return defaultValue;\n }\n try {\n return Byte.parseByte(str);\n } catch (NumberFormatException nfe) {\n return defaultValue;\n }\n }\n\n /**\n * <p>Convert a <code>String</code> to a <code>short</code>, returning\n * <code>zero</code> if the conversion fails.</p>\n *\n * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>\n *\n * <pre>\n * NumberUtils.toShort(null) = 0\n * NumberUtils.toShort(\"\") = 0\n * NumberUtils.toShort(\"1\") = 1\n * </pre>\n *\n * @param str the string to convert, may be null\n * @return the short represented by the string, or <code>zero</code> if\n * conversion fails\n * @since 2.5\n */\n public static short toShort(String str) {\n return toShort(str, (short) 0);\n }\n\n /**\n * <p>Convert a <code>String</code> to an <code>short</code>, returning a\n * default value if the conversion fails.</p>\n *\n * <p>If the string is <code>null</code>, the default value is returned.</p>\n *\n * <pre>\n * NumberUtils.toShort(null, 1) = 1\n * NumberUtils.toShort(\"\", 1) = 1\n * NumberUtils.toShort(\"1\", 0) = 1\n * </pre>\n *\n * @param str the string to convert, may be null\n * @param defaultValue the default value\n * @return the short represented by the string, or the default if conversion fails\n * @since 2.5\n */\n public static short toShort(String str, short defaultValue) {\n if (str == null) {\n return defaultValue;\n }\n try {\n return Short.parseShort(str);\n } catch (NumberFormatException nfe) {\n return defaultValue;\n }\n }\n\n //-----------------------------------------------------------------------\n // must handle Long, Float, Integer, Float, Short,\n // BigDecimal, BigInteger and Byte\n // useful methods:\n // Byte.decode(String)\n // Byte.valueOf(String,int radix)\n // Byte.valueOf(String)\n // Double.valueOf(String)\n // Float.valueOf(String)\n // Float.valueOf(String)\n // Integer.valueOf(String,int radix)\n // Integer.valueOf(String)\n // Integer.decode(String)\n // Integer.getInteger(String)\n // Integer.getInteger(String,int val)\n // Integer.getInteger(String,Integer val)\n // Integer.valueOf(String)\n // Double.valueOf(String)\n // new Byte(String)\n // Long.valueOf(String)\n // Long.getLong(String)\n // Long.getLong(String,int)\n // Long.getLong(String,Integer)\n // Long.valueOf(String,int)\n // Long.valueOf(String)\n // Short.valueOf(String)\n // Short.decode(String)\n // Short.valueOf(String,int)\n // Short.valueOf(String)\n // new BigDecimal(String)\n // new BigInteger(String)\n // new BigInteger(String,int radix)\n // Possible inputs:\n // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd\n // plus minus everything. Prolly more. A lot are not separable.\n\n /**\n * <p>Turns a string value into a java.lang.Number.</p>\n *\n * <p>First, the value is examined for a type qualifier on the end\n * (<code>'f','F','d','D','l','L'</code>). If it is found, it starts \n * trying to create successively larger types from the type specified\n * until one is found that can represent the value.</p>\n *\n * <p>If a type specifier is not found, it will check for a decimal point\n * and then try successively larger types from <code>Integer</code> to\n * <code>BigInteger</code> and from <code>Float</code> to\n * <code>BigDecimal</code>.</p>\n *\n * <p>If the string starts with <code>0x</code> or <code>-0x</code> (lower or upper case), it\n * will be interpreted as a hexadecimal integer. Values with leading\n * <code>0</code>'s will not be interpreted as octal.</p>\n *\n * <p>Returns <code>null</code> if the string is <code>null</code>.</p>\n *\n * <p>This method does not trim the input string, i.e., strings with leading\n * or trailing spaces will generate NumberFormatExceptions.</p>\n *\n * @param str String containing a number, may be null\n * @return Number created from the string (or null if the input is null)\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Number createNumber(String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n }\n if (str.startsWith(\"--\")) {\n // this is protection for poorness in java.lang.BigDecimal.\n // it accepts this as a legal value, but it does not appear \n // to be in specification of class. OS X Java parses it to \n // a wrong value.\n return null;\n }\n if (str.startsWith(\"0x\") || str.startsWith(\"-0x\") || str.startsWith(\"0X\")\n || str.startsWith(\"-0X\")) {\n return createInteger(str);\n }\n char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = str.indexOf('.');\n int expPos = str.indexOf('e') + str.indexOf('E') + 1;\n\n if (decPos > -1) {\n\n if (expPos > -1) {\n if (expPos < decPos || expPos > str.length()) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n } else {\n if (expPos > -1) {\n if (expPos > str.length()) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar) && lastChar != '.') {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n //Requesting a specific type..\n String numeric = str.substring(0, str.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l':\n case 'L':\n if (dec == null && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1))\n || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) { // NOPMD\n // Too big for a long\n }\n return createBigInteger(numeric);\n\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f':\n case 'F':\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n //If it's too big for a float or the float value = 0 and the string\n //has non-zeros in it, then float does not have the precision we want\n return f;\n }\n\n } catch (NumberFormatException nfe) { // NOPMD\n // ignore the bad number\n }\n //$FALL-THROUGH$\n case 'd':\n case 'D':\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) { // NOPMD\n // ignore the bad number\n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) { // NOPMD\n // ignore the bad number\n }\n //$FALL-THROUGH$\n default:\n throw new NumberFormatException(str + \" is not a valid number.\");\n\n }\n } else {\n //User doesn't have a preference on the return type, so let's start\n //small and go from there...\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n //Must be an int,long,bigint\n try {\n return createInteger(str);\n } catch (NumberFormatException nfe) { // NOPMD\n // ignore the bad number\n }\n try {\n return createLong(str);\n } catch (NumberFormatException nfe) { // NOPMD\n // ignore the bad number\n }\n return createBigInteger(str);\n\n } else {\n //Must be a float,double,BigDec\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) { // NOPMD\n // ignore the bad number\n }\n try {\n Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) { // NOPMD\n // ignore the bad number\n }\n\n return createBigDecimal(str);\n\n }\n }\n }\n\n /**\n * <p>Utility method for {@link #createNumber(java.lang.String)}.</p>\n *\n * <p>Returns <code>true</code> if s is <code>null</code>.</p>\n * \n * @param str the String to check\n * @return if it is all zeros or <code>null</code>\n */\n private static boolean isAllZeros(String str) {\n if (str == null) {\n return true;\n }\n for (int i = str.length() - 1; i >= 0; i--) {\n if (str.charAt(i) != '0') {\n return false;\n }\n }\n return str.length() > 0;\n }\n\n //-----------------------------------------------------------------------\n /**\n * <p>Convert a <code>String</code> to a <code>Float</code>.</p>\n *\n * <p>Returns <code>null</code> if the string is <code>null</code>.</p>\n * \n * @param str a <code>String</code> to convert, may be null\n * @return converted <code>Float</code>\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Float createFloat(String str) {\n if (str == null) {\n return null;\n }\n return Float.valueOf(str);\n }\n\n /**\n * <p>Convert a <code>String</code> to a <code>Double</code>.</p>\n * \n * <p>Returns <code>null</code> if the string is <code>null</code>.</p>\n *\n * @param str a <code>String</code> to convert, may be null\n * @return converted <code>Double</code>\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Double createDouble(String str) {\n if (str == null) {\n return null;\n }\n return Double.valueOf(str);\n }\n\n /**\n * <p>Convert a <code>String</code> to a <code>Integer</code>, handling\n * hex and octal notations.</p>\n *\n * <p>Returns <code>null</code> if the string is <code>null</code>.</p>\n * \n * @param str a <code>String</code> to convert, may be null\n * @return converted <code>Integer</code>\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Integer createInteger(String str) {\n if (str == null) {\n return null;\n }\n // decode() handles 0xAABD and 0777 (hex and octal) as well.\n return Integer.decode(str);\n }\n\n /**\n * <p>Convert a <code>String</code> to a <code>Long</code>; \n * since 3.1 it handles hex and octal notations.</p>\n * \n * <p>Returns <code>null</code> if the string is <code>null</code>.</p>\n *\n * @param str a <code>String</code> to convert, may be null\n * @return converted <code>Long</code>\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Long createLong(String str) {\n if (str == null) {\n return null;\n }\n return Long.decode(str);\n }\n\n /**\n * <p>Convert a <code>String</code> to a <code>BigInteger</code>.</p>\n *\n * <p>Returns <code>null</code> if the string is <code>null</code>.</p>\n * \n * @param str a <code>String</code> to convert, may be null\n * @return converted <code>BigInteger</code>\n * @throws NumberFormatException if the value cannot be converted\n */\n public static BigInteger createBigInteger(String str) {\n if (str == null) {\n return null;\n }\n return new BigInteger(str);\n }\n\n /**\n * <p>Convert a <code>String</code> to a <code>BigDecimal</code>.</p>\n * \n * <p>Returns <code>null</code> if the string is <code>null</code>.</p>\n *\n * @param str a <code>String</code> to convert, may be null\n * @return converted <code>BigDecimal</code>\n * @throws NumberFormatException if the value cannot be converted\n */\n public static BigDecimal createBigDecimal(String str) {\n if (str == null) {\n return null;\n }\n // handle JDK1.3.1 bug where \"\" throws IndexOutOfBoundsException\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n }\n return new BigDecimal(str);\n }\n\n // Min in array\n //--------------------------------------------------------------------\n /**\n * <p>Returns the minimum value in an array.</p>\n * \n * @param array an array, must not be null or empty\n * @return the minimum value in the array\n * @throws IllegalArgumentException if <code>array</code> is <code>null</code>\n * @throws IllegalArgumentException if <code>array</code> is empty\n */\n public static long min(long[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array cannot be empty.\");\n }\n\n // Finds and returns min\n long min = array[0];\n for (int i = 1; i < array.length; i++) {\n if (array[i] < min) {\n min = array[i];\n }\n }\n\n return min;\n }\n\n /**\n * <p>Returns the minimum value in an array.</p>\n * \n * @param array an array, must not be null or empty\n * @return the minimum value in the array\n * @throws IllegalArgumentException if <code>array</code> is <code>null</code>\n * @throws IllegalArgumentException if <code>array</code> is empty\n */\n public static int min(int[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array cannot be empty.\");\n }\n\n // Finds and returns min\n int min = array[0];\n for (int j = 1; j < array.length; j++) {\n if (array[j] < min) {\n min = array[j];\n }\n }\n\n return min;\n }\n\n /**\n * <p>Returns the minimum value in an array.</p>\n * \n * @param array an array, must not be null or empty\n * @return the minimum value in the array\n * @throws IllegalArgumentException if <code>array</code> is <code>null</code>\n * @throws IllegalArgumentException if <code>array</code> is empty\n */\n public static short min(short[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array cannot be empty.\");\n }\n\n // Finds and returns min\n short min = array[0];\n for (int i = 1; i < array.length; i++) {\n if (array[i] < min) {\n min = array[i];\n }\n }\n\n return min;\n }\n\n /**\n * <p>Returns the minimum value in an array.</p>\n * \n * @param array an array, must not be null or empty\n * @return the minimum value in the array\n * @throws IllegalArgumentException if <code>array</code> is <code>null</code>\n * @throws IllegalArgumentException if <code>array</code> is empty\n */\n public static byte min(byte[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array cannot be empty.\");\n }\n\n // Finds and returns min\n byte min = array[0];\n for (int i = 1; i < array.length; i++) {\n if (array[i] < min) {\n min = array[i];\n }\n }\n\n return min;\n }\n\n /**\n * <p>Returns the minimum value in an array.</p>\n * \n * @param array an array, must not be null or empty\n * @return the minimum value in the array\n * @throws IllegalArgumentException if <code>array</code> is <code>null</code>\n * @throws IllegalArgumentException if <code>array</code> is empty\n * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently\n */\n public static double min(double[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array cannot be empty.\");\n }\n\n // Finds and returns min\n double min = array[0];\n for (int i = 1; i < array.length; i++) {\n if (Double.isNaN(array[i])) {\n return Double.NaN;\n }\n if (array[i] < min) {\n min = array[i];\n }\n }\n\n return min;\n }\n\n /**\n * <p>Returns the minimum value in an array.</p>\n * \n * @param array an array, must not be null or empty\n * @return the minimum value in the array\n * @throws IllegalArgumentException if <code>array</code> is <code>null</code>\n * @throws IllegalArgumentException if <code>array</code> is empty\n * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently\n */\n public static float min(float[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array cannot be empty.\");\n }\n\n // Finds and returns min\n float min = array[0];\n for (int i = 1; i < array.length; i++) {\n if (Float.isNaN(array[i])) {\n return Float.NaN;\n }\n if (array[i] < min) {\n min = array[i];\n }\n }\n\n return min;\n }\n\n // Max in array\n //--------------------------------------------------------------------\n /**\n * <p>Returns the maximum value in an array.</p>\n * \n * @param array an array, must not be null or empty\n * @return the minimum value in the array\n * @throws IllegalArgumentException if <code>array</code> is <code>null</code>\n * @throws IllegalArgumentException if <code>array</code> is empty\n */\n public static long max(long[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array cannot be empty.\");\n }\n\n // Finds and returns max\n long max = array[0];\n for (int j = 1; j < array.length; j++) {\n if (array[j] > max) {\n max = array[j];\n }\n }\n\n return max;\n }\n\n /**\n * <p>Returns the maximum value in an array.</p>\n * \n * @param array an array, must not be null or empty\n * @return the minimum value in the array\n * @throws IllegalArgumentException if <code>array</code> is <code>null</code>\n * @throws IllegalArgumentException if <code>array</code> is empty\n */\n public static int max(int[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array cannot be empty.\");\n }\n\n // Finds and returns max\n int max = array[0];\n for (int j = 1; j < array.length; j++) {\n if (array[j] > max) {\n max = array[j];\n }\n }\n\n return max;\n }\n\n /**\n * <p>Returns the maximum value in an array.</p>\n * \n * @param array an array, must not be null or empty\n * @return the minimum value in the array\n * @throws IllegalArgumentException if <code>array</code> is <code>null</code>\n * @throws IllegalArgumentException if <code>array</code> is empty\n */\n public static short max(short[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array cannot be empty.\");\n }\n\n // Finds and returns max\n short max = array[0];\n for (int i = 1; i < array.length; i++) {\n if (array[i] > max) {\n max = array[i];\n }\n }\n\n return max;\n }\n\n /**\n * <p>Returns the maximum value in an array.</p>\n * \n * @param array an array, must not be null or empty\n * @return the minimum value in the array\n * @throws IllegalArgumentException if <code>array</code> is <code>null</code>\n * @throws IllegalArgumentException if <code>array</code> is empty\n */\n public static byte max(byte[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array cannot be empty.\");\n }\n\n // Finds and returns max\n byte max = array[0];\n for (int i = 1; i < array.length; i++) {\n if (array[i] > max) {\n max = array[i];\n }\n }\n\n return max;\n }\n\n /**\n * <p>Returns the maximum value in an array.</p>\n * \n * @param array an array, must not be null or empty\n * @return the minimum value in the array\n * @throws IllegalArgumentException if <code>array</code> is <code>null</code>\n * @throws IllegalArgumentException if <code>array</code> is empty\n * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently\n */\n public static double max(double[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array cannot be empty.\");\n }\n\n // Finds and returns max\n double max = array[0];\n for (int j = 1; j < array.length; j++) {\n if (Double.isNaN(array[j])) {\n return Double.NaN;\n }\n if (array[j] > max) {\n max = array[j];\n }\n }\n\n return max;\n }\n\n /**\n * <p>Returns the maximum value in an array.</p>\n * \n * @param array an array, must not be null or empty\n * @return the minimum value in the array\n * @throws IllegalArgumentException if <code>array</code> is <code>null</code>\n * @throws IllegalArgumentException if <code>array</code> is empty\n * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently\n */\n public static float max(float[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array cannot be empty.\");\n }\n\n // Finds and returns max\n float max = array[0];\n for (int j = 1; j < array.length; j++) {\n if (Float.isNaN(array[j])) {\n return Float.NaN;\n }\n if (array[j] > max) {\n max = array[j];\n }\n }\n\n return max;\n }\n\n // 3 param min\n //-----------------------------------------------------------------------\n /**\n * <p>Gets the minimum of three <code>long</code> values.</p>\n * \n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the smallest of the values\n */\n public static long min(long a, long b, long c) {\n if (b < a) {\n a = b;\n }\n if (c < a) {\n a = c;\n }\n return a;\n }\n\n /**\n * <p>Gets the minimum of three <code>int</code> values.</p>\n * \n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the smallest of the values\n */\n public static int min(int a, int b, int c) {\n if (b < a) {\n a = b;\n }\n if (c < a) {\n a = c;\n }\n return a;\n }\n\n /**\n * <p>Gets the minimum of three <code>short</code> values.</p>\n * \n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the smallest of the values\n */\n public static short min(short a, short b, short c) {\n if (b < a) {\n a = b;\n }\n if (c < a) {\n a = c;\n }\n return a;\n }\n\n /**\n * <p>Gets the minimum of three <code>byte</code> values.</p>\n * \n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the smallest of the values\n */\n public static byte min(byte a, byte b, byte c) {\n if (b < a) {\n a = b;\n }\n if (c < a) {\n a = c;\n }\n return a;\n }\n\n /**\n * <p>Gets the minimum of three <code>double</code> values.</p>\n * \n * <p>If any value is <code>NaN</code>, <code>NaN</code> is\n * returned. Infinity is handled.</p>\n * \n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the smallest of the values\n * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently\n */\n public static double min(double a, double b, double c) {\n return Math.min(Math.min(a, b), c);\n }\n\n /**\n * <p>Gets the minimum of three <code>float</code> values.</p>\n * \n * <p>If any value is <code>NaN</code>, <code>NaN</code> is\n * returned. Infinity is handled.</p>\n *\n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the smallest of the values\n * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently\n */\n public static float min(float a, float b, float c) {\n return Math.min(Math.min(a, b), c);\n }\n\n // 3 param max\n //-----------------------------------------------------------------------\n /**\n * <p>Gets the maximum of three <code>long</code> values.</p>\n * \n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the largest of the values\n */\n public static long max(long a, long b, long c) {\n if (b > a) {\n a = b;\n }\n if (c > a) {\n a = c;\n }\n return a;\n }\n\n /**\n * <p>Gets the maximum of three <code>int</code> values.</p>\n * \n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the largest of the values\n */\n public static int max(int a, int b, int c) {\n if (b > a) {\n a = b;\n }\n if (c > a) {\n a = c;\n }\n return a;\n }\n\n /**\n * <p>Gets the maximum of three <code>short</code> values.</p>\n * \n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the largest of the values\n */\n public static short max(short a, short b, short c) {\n if (b > a) {\n a = b;\n }\n if (c > a) {\n a = c;\n }\n return a;\n }\n\n /**\n * <p>Gets the maximum of three <code>byte</code> values.</p>\n * \n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the largest of the values\n */\n public static byte max(byte a, byte b, byte c) {\n if (b > a) {\n a = b;\n }\n if (c > a) {\n a = c;\n }\n return a;\n }\n\n /**\n * <p>Gets the maximum of three <code>double</code> values.</p>\n * \n * <p>If any value is <code>NaN</code>, <code>NaN</code> is\n * returned. Infinity is handled.</p>\n *\n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the largest of the values\n * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently\n */\n public static double max(double a, double b, double c) {\n return Math.max(Math.max(a, b), c);\n }\n\n /**\n * <p>Gets the maximum of three <code>float</code> values.</p>\n * \n * <p>If any value is <code>NaN</code>, <code>NaN</code> is\n * returned. Infinity is handled.</p>\n *\n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the largest of the values\n * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently\n */\n public static float max(float a, float b, float c) {\n return Math.max(Math.max(a, b), c);\n }\n\n //-----------------------------------------------------------------------\n /**\n * <p>Checks whether the <code>String</code> contains only\n * digit characters.</p>\n *\n * <p><code>Null</code> and empty String will return\n * <code>false</code>.</p>\n *\n * @param str the <code>String</code> to check\n * @return <code>true</code> if str contains only Unicode numeric\n */\n public static boolean isDigits(String str) {\n if (StringUtils.isEmpty(str)) {\n return false;\n }\n for (int i = 0; i < str.length(); i++) {\n if (!Character.isDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * <p>Checks whether the String a valid Java number.</p>\n *\n * <p>Valid numbers include hexadecimal marked with the <code>0x</code>\n * qualifier, scientific notation and numbers marked with a type\n * qualifier (e.g. 123L).</p>\n *\n * <p><code>Null</code> and empty String will return\n * <code>false</code>.</p>\n *\n * @param str the <code>String</code> to check\n * @return <code>true</code> if the string is a correctly formatted number\n */\n public static boolean isNumber(String str) {\n if (StringUtils.isEmpty(str)) {\n return false;\n }\n char[] chars = str.toCharArray();\n int sz = chars.length;\n boolean hasExp = false;\n boolean hasDecPoint = false;\n boolean allowSigns = false;\n boolean foundDigit = false;\n // deal with any possible sign up front\n int start = (chars[0] == '-') ? 1 : 0;\n if (sz > start + 1 && chars[start] == '0' && chars[start + 1] == 'x') {\n int i = start + 2;\n if (i == sz) {\n return false; // str == \"0x\"\n }\n // checking hex (it can't be anything else)\n for (; i < chars.length; i++) {\n if ((chars[i] < '0' || chars[i] > '9') && (chars[i] < 'a' || chars[i] > 'f')\n && (chars[i] < 'A' || chars[i] > 'F')) {\n return false;\n }\n }\n return true;\n }\n sz--; // don't want to loop to the last char, check it afterwords\n // for type qualifiers\n int i = start;\n // loop to the next to last char or to the last char if we need another digit to\n // make a valid number (e.g. chars[0..5] = \"1234E\")\n while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {\n if (chars[i] >= '0' && chars[i] <= '9') {\n foundDigit = true;\n allowSigns = false;\n\n } else if (chars[i] == '.') {\n if (hasDecPoint || hasExp) {\n // two decimal points or dec in exponent \n return false;\n }\n hasDecPoint = true;\n } else if (chars[i] == 'e' || chars[i] == 'E') {\n // we've already taken care of hex.\n if (hasExp) {\n // two E's\n return false;\n }\n if (!foundDigit) {\n return false;\n }\n hasExp = true;\n allowSigns = true;\n } else if (chars[i] == '+' || chars[i] == '-') {\n if (!allowSigns) {\n return false;\n }\n allowSigns = false;\n foundDigit = false; // we need a digit after the E\n } else {\n return false;\n }\n i++;\n }\n if (i < chars.length) {\n if (chars[i] >= '0' && chars[i] <= '9') {\n // no type qualifier, OK\n return true;\n }\n if (chars[i] == 'e' || chars[i] == 'E') {\n // can't have an E at the last byte\n return false;\n }\n if (chars[i] == '.') {\n if (hasDecPoint || hasExp) {\n // two decimal points or dec in exponent\n return false;\n }\n // single trailing decimal point after non-exponent is ok\n return foundDigit;\n }\n if (!allowSigns\n && (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F')) {\n return foundDigit;\n }\n if (chars[i] == 'l' || chars[i] == 'L') {\n // not allowing L with an exponent or decimal point\n return foundDigit && !hasExp && !hasDecPoint;\n }\n // last character is illegal\n return false;\n }\n // allowSigns is true iff the val ends in 'E'\n // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass\n return !allowSigns && foundDigit;\n }\n\n}",
"public class PropertiesUtils {\n\n private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);\n\n /**\n * 加载属性文件\n * @param propsPath\n * @return\n */\n public static Properties load(String propsPath) {\n Properties props = new Properties();\n InputStream is = null;\n try {\n String suffix = \".properties\";\n if (propsPath.lastIndexOf(suffix) == -1) {\n propsPath += suffix;\n }\n is = PropertiesUtils.class.getClassLoader().getResourceAsStream(propsPath);\n if (is != null) {\n props.load(is);\n }\n } catch (IOException e) {\n logger.error(\"加载属性文件出错!propsPath:\" + propsPath, e);\n throw new RuntimeException(e);\n } finally {\n try {\n if (is != null) {\n is.close();\n }\n } catch (IOException e) {\n logger.error(\"释放资源出错!\", e);\n }\n }\n return props;\n }\n\n /**\n * 加载属性文件,并转为 Map\n * @param propsPath\n * @return\n */\n public static Map<String, String> loadToMap(String propsPath) {\n Map<String, String> map = new HashMap<String, String>();\n Properties props = load(propsPath);\n for (String key : props.stringPropertyNames()) {\n map.put(key, props.getProperty(key));\n }\n return map;\n }\n\n /**\n * 获取字符型属性\n * @param props\n * @param key\n * @return\n */\n public static String getString(Properties props, String key) {\n return props.getProperty(key) != null ? props.getProperty(key) : \"\";\n }\n\n /**\n * 获取数值型属性\n * @param props\n * @param key\n * @return\n */\n public static int getNumber(Properties props, String key) {\n return NumberUtils.toInt(props.getProperty(key), 0);\n }\n\n /**\n * 获取布尔型属性\n * @param props\n * @param key\n * @return\n */\n public static boolean getBoolean(Properties props, String key) {\n return Boolean.parseBoolean(props.getProperty(key));\n }\n}",
"public class StringUtils {\n /**\n * Represents a failed index search.\n * @since 2.1\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n * The empty String {@code \"\"}.\n * @since 2.0\n */\n public static final String EMPTY = \"\";\n\n public static boolean equals(CharSequence cs1, CharSequence cs2) {\n return cs1 == null ? cs2 == null : cs1.equals(cs2);\n }\n\n /**\n * Tests if this string ends with the specified suffix.\n *\n * @param src String to test\n * @param subS suffix\n *\n * @return <code>true</code> if the character sequence represented by the argument is\n * a suffix of the character sequence represented by this object;\n * <code>false</code> otherwise.\n */\n public static boolean endsWithIgnoreCase(String src, String subS) {\n if (src == null || subS == null) {\n return src == subS;\n }\n\n String sub = subS.toLowerCase();\n int sublen = sub.length();\n int j = 0;\n int i = src.length() - sublen;\n if (i < 0) {\n return false;\n }\n while (j < sublen) {\n char source = Character.toLowerCase(src.charAt(i));\n if (sub.charAt(j) != source) {\n return false;\n }\n j++;\n i++;\n }\n return true;\n }\n\n /**\n * <p>Checks if a CharSequence is whitespace, empty (\"\") or null.</p>\n *\n * <pre>\n * StringUtils.isBlank(null) = true\n * StringUtils.isBlank(\"\") = true\n * StringUtils.isBlank(\" \") = true\n * StringUtils.isBlank(\"bob\") = false\n * StringUtils.isBlank(\" bob \") = false\n * </pre>\n *\n * @param cs the CharSequence to check, may be null\n * @return {@code true} if the CharSequence is null, empty or whitespace\n * @since 2.0\n * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)\n */\n public static boolean isBlank(final CharSequence cs) {\n int strLen;\n if (cs == null || (strLen = cs.length()) == 0) {\n return true;\n }\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(cs.charAt(i)) == false) {\n return false;\n }\n }\n return true;\n }\n\n public static String[] split(final String str) {\n return split(str, null, -1);\n }\n\n /**\n * <p>Splits the provided text into an array, separators specified.\n * This is an alternative to using StringTokenizer.</p>\n *\n * <p>The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.</p>\n *\n * <p>A {@code null} input String returns {@code null}.\n * A {@code null} separatorChars splits on whitespace.</p>\n *\n * <pre>\n * StringUtils.split(null, *) = null\n * StringUtils.split(\"\", *) = []\n * StringUtils.split(\"abc def\", null) = [\"abc\", \"def\"]\n * StringUtils.split(\"abc def\", \" \") = [\"abc\", \"def\"]\n * StringUtils.split(\"abc def\", \" \") = [\"abc\", \"def\"]\n * StringUtils.split(\"ab:cd:ef\", \":\") = [\"ab\", \"cd\", \"ef\"]\n * </pre>\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * {@code null} splits on whitespace\n * @return an array of parsed Strings, {@code null} if null String input\n */\n public static String[] split(final String str, final String separatorChars) {\n return splitWorker(str, separatorChars, -1, false);\n }\n\n public static String[] split(final String str, final String separatorChars, final int max) {\n return splitWorker(str, separatorChars, max, false);\n }\n\n /**\n * <p>Splits the provided text into an array, separator specified.\n * This is an alternative to using StringTokenizer.</p>\n *\n * <p>The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.</p>\n *\n * <p>A {@code null} input String returns {@code null}.</p>\n *\n * <pre>\n * StringUtils.split(null, *) = null\n * StringUtils.split(\"\", *) = []\n * StringUtils.split(\"a.b.c\", '.') = [\"a\", \"b\", \"c\"]\n * StringUtils.split(\"a..b.c\", '.') = [\"a\", \"b\", \"c\"]\n * StringUtils.split(\"a:b:c\", '.') = [\"a:b:c\"]\n * StringUtils.split(\"a b c\", ' ') = [\"a\", \"b\", \"c\"]\n * </pre>\n *\n * @param str the String to parse, may be null\n * @param separatorChar the character used as the delimiter\n * @return an array of parsed Strings, {@code null} if null String input\n * @since 2.0\n */\n public static String[] split(final String str, final char separatorChar) {\n return splitWorker(str, separatorChar, false);\n }\n\n /**\n * Performs the logic for the {@code split} and\n * {@code splitPreserveAllTokens} methods that do not return a\n * maximum array length.\n *\n * @param str the String to parse, may be {@code null}\n * @param separatorChar the separate character\n * @param preserveAllTokens if {@code true}, adjacent separators are\n * treated as empty token separators; if {@code false}, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, {@code null} if null String input\n */\n private static String[] splitWorker(final String str, final char separatorChar,\n final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n\n if (str == null) {\n return null;\n }\n final int len = str.length();\n if (len == 0) {\n return new String[0];\n }\n final List<String> list = new ArrayList<String>();\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n while (i < len) {\n if (str.charAt(i) == separatorChar) {\n if (match || preserveAllTokens) {\n list.add(str.substring(start, i));\n match = false;\n lastMatch = true;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[list.size()]);\n }\n\n private static String[] splitWorker(final String str, final String separatorChars,\n final int max, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n // Direct code is quicker than StringTokenizer.\n // Also, StringTokenizer uses isSpace() not isWhitespace()\n\n if (str == null) {\n return null;\n }\n final int len = str.length();\n if (len == 0) {\n return new String[0];\n }\n final List<String> list = new ArrayList<String>();\n int sizePlus1 = 1;\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n if (separatorChars == null) {\n // Null separator means use whitespace\n while (i < len) {\n if (Character.isWhitespace(str.charAt(i))) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else if (separatorChars.length() == 1) {\n // Optimise 1 character case\n final char sep = separatorChars.charAt(0);\n while (i < len) {\n if (str.charAt(i) == sep) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else {\n // standard case\n while (i < len) {\n if (separatorChars.indexOf(str.charAt(i)) >= 0) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * <p>Checks if a CharSequence is not empty (\"\"), not null and not whitespace only.</p>\n *\n * <pre>\n * StringUtils.isNotBlank(null) = false\n * StringUtils.isNotBlank(\"\") = false\n * StringUtils.isNotBlank(\" \") = false\n * StringUtils.isNotBlank(\"bob\") = true\n * StringUtils.isNotBlank(\" bob \") = true\n * </pre>\n *\n * @param cs the CharSequence to check, may be null\n * @return {@code true} if the CharSequence is\n * not empty and not null and not whitespace\n * @since 2.0\n * @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence)\n */\n public static boolean isNotBlank(final CharSequence cs) {\n return !isBlank(cs);\n }\n\n public static boolean isEmpty(final CharSequence cs) {\n return cs == null || cs.length() == 0;\n }\n\n /**\n * <p>Gets the substring after the first occurrence of a separator.\n * The separator is not returned.</p>\n *\n * <p>A {@code null} string input will return {@code null}.\n * An empty (\"\") string input will return the empty string.\n * A {@code null} separator will return the empty string if the\n * input string is not {@code null}.</p>\n *\n * <p>If nothing is found, the empty string is returned.</p>\n *\n * <pre>\n * StringUtils.substringAfter(null, *) = null\n * StringUtils.substringAfter(\"\", *) = \"\"\n * StringUtils.substringAfter(*, null) = \"\"\n * StringUtils.substringAfter(\"abc\", \"a\") = \"bc\"\n * StringUtils.substringAfter(\"abcba\", \"b\") = \"cba\"\n * StringUtils.substringAfter(\"abc\", \"c\") = \"\"\n * StringUtils.substringAfter(\"abc\", \"d\") = \"\"\n * StringUtils.substringAfter(\"abc\", \"\") = \"abc\"\n * </pre>\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring after the first occurrence of the separator,\n * {@code null} if null String input\n * @since 2.0\n */\n public static String substringAfter(final String str, final String separator) {\n if (isEmpty(str)) {\n return str;\n }\n if (separator == null) {\n return EMPTY;\n }\n final int pos = str.indexOf(separator);\n if (pos == INDEX_NOT_FOUND) {\n return EMPTY;\n }\n return str.substring(pos + separator.length());\n }\n\n /**\n * <p>Gets the substring before the last occurrence of a separator.\n * The separator is not returned.</p>\n *\n * <p>A {@code null} string input will return {@code null}.\n * An empty (\"\") string input will return the empty string.\n * An empty or {@code null} separator will return the input string.</p>\n *\n * <p>If nothing is found, the string input is returned.</p>\n *\n * <pre>\n * StringUtils.substringBeforeLast(null, *) = null\n * StringUtils.substringBeforeLast(\"\", *) = \"\"\n * StringUtils.substringBeforeLast(\"abcba\", \"b\") = \"abc\"\n * StringUtils.substringBeforeLast(\"abc\", \"c\") = \"ab\"\n * StringUtils.substringBeforeLast(\"a\", \"a\") = \"\"\n * StringUtils.substringBeforeLast(\"a\", \"z\") = \"a\"\n * StringUtils.substringBeforeLast(\"a\", null) = \"a\"\n * StringUtils.substringBeforeLast(\"a\", \"\") = \"a\"\n * </pre>\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring before the last occurrence of the separator,\n * {@code null} if null String input\n * @since 2.0\n */\n public static String substringBeforeLast(final String str, final String separator) {\n if (isEmpty(str) || isEmpty(separator)) {\n return str;\n }\n final int pos = str.lastIndexOf(separator);\n if (pos == INDEX_NOT_FOUND) {\n return str;\n }\n return str.substring(0, pos);\n }\n\n /**\n * <p>Gets the substring before the first occurrence of a separator.\n * The separator is not returned.</p>\n *\n * <p>A {@code null} string input will return {@code null}.\n * An empty (\"\") string input will return the empty string.\n * A {@code null} separator will return the input string.</p>\n *\n * <p>If nothing is found, the string input is returned.</p>\n *\n * <pre>\n * StringUtils.substringBefore(null, *) = null\n * StringUtils.substringBefore(\"\", *) = \"\"\n * StringUtils.substringBefore(\"abc\", \"a\") = \"\"\n * StringUtils.substringBefore(\"abcba\", \"b\") = \"a\"\n * StringUtils.substringBefore(\"abc\", \"c\") = \"ab\"\n * StringUtils.substringBefore(\"abc\", \"d\") = \"abc\"\n * StringUtils.substringBefore(\"abc\", \"\") = \"\"\n * StringUtils.substringBefore(\"abc\", null) = \"abc\"\n * </pre>\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring before the first occurrence of the separator,\n * {@code null} if null String input\n * @since 2.0\n */\n public static String substringBefore(final String str, final String separator) {\n if (isEmpty(str) || separator == null) {\n return str;\n }\n if (separator.isEmpty()) {\n return EMPTY;\n }\n final int pos = str.indexOf(separator);\n if (pos == INDEX_NOT_FOUND) {\n return str;\n }\n return str.substring(0, pos);\n }\n\n /**\n * Finds first occurrence of a substring in the given source but within limited range [start, end).\n * It is fastest possible code, but still original <code>String.indexOf(String, int)</code>\n * is much faster (since it uses char[] value directly) and should be used when no range is needed.\n *\n * @param src source string for examination\n * @param sub substring to find\n * @param startIndex starting index\n * @param endIndex ending index\n * @return index of founded substring or -1 if substring not found\n */\n public static int indexOf(String src, String sub, int startIndex, int endIndex) {\n if (startIndex < 0) {\n startIndex = 0;\n }\n int srclen = src.length();\n if (endIndex > srclen) {\n endIndex = srclen;\n }\n int sublen = sub.length();\n if (sublen == 0) {\n return startIndex > srclen ? srclen : startIndex;\n }\n\n int total = endIndex - sublen + 1;\n char c = sub.charAt(0);\n mainloop: for (int i = startIndex; i < total; i++) {\n if (src.charAt(i) != c) {\n continue;\n }\n int j = 1;\n int k = i + 1;\n while (j < sublen) {\n if (sub.charAt(j) != src.charAt(k)) {\n continue mainloop;\n }\n j++;\n k++;\n }\n return i;\n }\n return -1;\n }\n\n /**\n * Finds the first occurrence of a character in the given source but within limited range (start, end].\n */\n public static int indexOf(String src, char c, int startIndex, int endIndex) {\n if (startIndex < 0) {\n startIndex = 0;\n }\n int srclen = src.length();\n if (endIndex > srclen) {\n endIndex = srclen;\n }\n for (int i = startIndex; i < endIndex; i++) {\n if (src.charAt(i) == c) {\n return i;\n }\n }\n return -1;\n }\n\n public static String substringAfterLast(final String str, final String separator) {\n if (isEmpty(str)) {\n return str;\n }\n if (isEmpty(separator)) {\n return EMPTY;\n }\n final int pos = str.lastIndexOf(separator);\n if (pos == INDEX_NOT_FOUND || pos == str.length() - separator.length()) {\n return EMPTY;\n }\n return str.substring(pos + separator.length());\n }\n\n /**\n * <p>Checks if the CharSequence contains only Unicode digits.\n * A decimal point is not a Unicode digit and returns false.</p>\n *\n * <p>{@code null} will return {@code false}.\n * An empty CharSequence (length()=0) will return {@code false}.</p>\n *\n * <p>Note that the method does not allow for a leading sign, either positive or negative.\n * Also, if a String passes the numeric test, it may still generate a NumberFormatException\n * when parsed by Integer.parseInt or Long.parseLong, e.g. if the value is outside the range\n * for int or long respectively.</p>\n *\n * <pre>\n * StringUtils.isNumeric(null) = false\n * StringUtils.isNumeric(\"\") = false\n * StringUtils.isNumeric(\" \") = false\n * StringUtils.isNumeric(\"123\") = true\n * StringUtils.isNumeric(\"\\u0967\\u0968\\u0969\") = true\n * StringUtils.isNumeric(\"12 3\") = false\n * StringUtils.isNumeric(\"ab2c\") = false\n * StringUtils.isNumeric(\"12-3\") = false\n * StringUtils.isNumeric(\"12.3\") = false\n * StringUtils.isNumeric(\"-123\") = false\n * StringUtils.isNumeric(\"+123\") = false\n * </pre>\n *\n * @param cs the CharSequence to check, may be null\n * @return {@code true} if only contains digits, and is non-null\n * @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence)\n * @since 3.0 Changed \"\" to return false and not true\n */\n public static boolean isNumeric(final CharSequence cs) {\n if (isEmpty(cs)) {\n return false;\n }\n final int sz = cs.length();\n for (int i = 0; i < sz; i++) {\n if (Character.isDigit(cs.charAt(i)) == false) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * <p>Checks if the CharSequence contains only lowercase characters.</p>\n *\n * <p>{@code null} will return {@code false}.\n * An empty CharSequence (length()=0) will return {@code false}.</p>\n *\n * <pre>\n * StringUtils.isAllLowerCase(null) = false\n * StringUtils.isAllLowerCase(\"\") = false\n * StringUtils.isAllLowerCase(\" \") = false\n * StringUtils.isAllLowerCase(\"abc\") = true\n * StringUtils.isAllLowerCase(\"abC\") = false\n * StringUtils.isAllLowerCase(\"ab c\") = false\n * StringUtils.isAllLowerCase(\"ab1c\") = false\n * StringUtils.isAllLowerCase(\"ab/c\") = false\n * </pre>\n *\n * @param cs the CharSequence to check, may be null\n * @return {@code true} if only contains lowercase characters, and is non-null\n * @since 2.5\n * @since 3.0 Changed signature from isAllLowerCase(String) to isAllLowerCase(CharSequence)\n */\n public static boolean isAllLowerCase(final CharSequence cs) {\n if (cs == null || isEmpty(cs)) {\n return false;\n }\n final int sz = cs.length();\n for (int i = 0; i < sz; i++) {\n if (Character.isLowerCase(cs.charAt(i)) == false) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * <p>Checks if the CharSequence contains only uppercase characters.</p>\n *\n * <p>{@code null} will return {@code false}.\n * An empty String (length()=0) will return {@code false}.</p>\n *\n * <pre>\n * StringUtils.isAllUpperCase(null) = false\n * StringUtils.isAllUpperCase(\"\") = false\n * StringUtils.isAllUpperCase(\" \") = false\n * StringUtils.isAllUpperCase(\"ABC\") = true\n * StringUtils.isAllUpperCase(\"aBC\") = false\n * StringUtils.isAllUpperCase(\"A C\") = false\n * StringUtils.isAllUpperCase(\"A1C\") = false\n * StringUtils.isAllUpperCase(\"A/C\") = false\n * </pre>\n *\n * @param cs the CharSequence to check, may be null\n * @return {@code true} if only contains uppercase characters, and is non-null\n * @since 2.5\n * @since 3.0 Changed signature from isAllUpperCase(String) to isAllUpperCase(CharSequence)\n */\n public static boolean isAllUpperCase(final CharSequence cs) {\n if (cs == null || isEmpty(cs)) {\n return false;\n }\n final int sz = cs.length();\n for (int i = 0; i < sz; i++) {\n if (Character.isUpperCase(cs.charAt(i)) == false) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * <p>Joins the elements of the provided {@code Iterator} into\n * a single String containing the provided elements.</p>\n *\n * <p>No delimiter is added before or after the list.\n * A {@code null} separator is the same as an empty String (\"\").</p>\n *\n * <p>See the examples here: {@link #join(Object[],String)}. </p>\n *\n * @param iterator the {@code Iterator} of values to join together, may be null\n * @param separator the separator character to use, null treated as \"\"\n * @return the joined String, {@code null} if null iterator input\n */\n public static String join(final Iterator<?> iterator, final String separator) {\n\n // handle null, zero and one elements before building a buffer\n if (iterator == null) {\n return null;\n }\n if (!iterator.hasNext()) {\n return EMPTY;\n }\n final Object first = iterator.next();\n if (!iterator.hasNext()) {\n return first == null ? \"\" : first.toString();\n }\n\n // two or more elements\n final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small\n if (first != null) {\n buf.append(first);\n }\n\n while (iterator.hasNext()) {\n if (separator != null) {\n buf.append(separator);\n }\n final Object obj = iterator.next();\n if (obj != null) {\n buf.append(obj);\n }\n }\n return buf.toString();\n }\n\n /**\n * <p>Joins the elements of the provided {@code Iterator} into\n * a single String containing the provided elements.</p>\n *\n * <p>No delimiter is added before or after the list. Null objects or empty\n * strings within the iteration are represented by empty strings.</p>\n *\n * <p>See the examples here: {@link #join(Object[],char)}. </p>\n *\n * @param iterator the {@code Iterator} of values to join together, may be null\n * @param separator the separator character to use\n * @return the joined String, {@code null} if null iterator input\n * @since 2.0\n */\n public static String join(final Iterator<?> iterator, final char separator) {\n\n // handle null, zero and one elements before building a buffer\n if (iterator == null) {\n return null;\n }\n if (!iterator.hasNext()) {\n return EMPTY;\n }\n final Object first = iterator.next();\n if (!iterator.hasNext()) {\n return first == null ? \"\" : first.toString();\n }\n\n // two or more elements\n final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small\n if (first != null) {\n buf.append(first);\n }\n\n while (iterator.hasNext()) {\n buf.append(separator);\n final Object obj = iterator.next();\n if (obj != null) {\n buf.append(obj);\n }\n }\n\n return buf.toString();\n }\n\n /**\n * \n * @param kvs\n * @param separator\n * @return\n */\n public static String join(List<String> kvs, char separator) {\n if (kvs == null) {\n return null;\n }\n return join(kvs.iterator(), separator);\n }\n}"
] | import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ketayao.fensy.Constants;
import com.ketayao.fensy.db.DBManager;
import com.ketayao.fensy.exception.ActionException;
import com.ketayao.fensy.exception.NotFoundTemplateException;
import com.ketayao.fensy.handler.ExceptionHandler;
import com.ketayao.fensy.handler.SimpleExceptionHandler;
import com.ketayao.fensy.mvc.interceptor.Interceptor;
import com.ketayao.fensy.mvc.view.View;
import com.ketayao.fensy.mvc.view.ViewMap;
import com.ketayao.fensy.util.ClassUtils;
import com.ketayao.fensy.util.Exceptions;
import com.ketayao.fensy.util.NumberUtils;
import com.ketayao.fensy.util.PropertiesUtils;
import com.ketayao.fensy.util.StringUtils; | /**
* <pre>
* Copyright: Copyright(C) 2011-2012, ketayao.com
* Date: 2013年8月13日
* Author: <a href="mailto:[email protected]">ketayao</a>
* Description:
*
* </pre>
**/
package com.ketayao.fensy.mvc;
/**
*
* @author <a href="mailto:[email protected]">ketayao</a>
* @since 2013年8月13日 上午11:48:42
*/
public class DispatcherFilter implements Filter {
private final static Logger log = LoggerFactory
.getLogger(DispatcherFilter.class);
private ServletContext context;
private ExceptionHandler exceptionHandler = new SimpleExceptionHandler();
private Map<String, Interceptor> interceptors = new LinkedHashMap<String, Interceptor>();
private final static String VIEW_INDEX = "/"
+ Constants.ACTION_DEFAULT_METHOD;
private final static Map<String, PathView> templates = new HashMap<String, PathView>();
private final static HashMap<String, Object> actions = new HashMap<String, Object>();
private final static HashMap<String, Method> methods = new HashMap<String, Method>();
// 忽略的URI
private List<String> ignoreURIs = new ArrayList<String>();
// 忽略的后缀
private List<String> ignoreExts = new ArrayList<String>();
// 视图类型
private List<View> viewList = new ArrayList<View>();
/**
* 视图路径=模板根路径+域名模板路径+视图名称
*/
// 其他子域名模板路径
private HashMap<String, String> domainTemplatePathes = new HashMap<String, String>();
// 域名
private String rootDomain = Constants.ACTION_ROOT_DOMAIN;
private String rootDomainTemplatePath = Constants.DEFAULT_DOMAIN_TEMPLATE_PATH;
// 模板根路径
private String templatePath = Constants.DEFAULT_TEMPLATE_PATH;
private String defaultTemplatePath;
@Override
public void init(FilterConfig cfg) throws ServletException {
this.context = cfg.getServletContext();
Map<String, String> config = PropertiesUtils.loadToMap(Constants.FENSY_CONFIG_FILE);
// 设置上传文件尺寸
String tmpSzie = config.get(Constants.FENSY_UPLOAD_FILE_MAX_SIZE);
if (NumberUtils.isNumber(tmpSzie)) {
WebContext.setMaxSize(NumberUtils.toInt(tmpSzie));
}
// 模板存放路径
String tmp = config.get(Constants.FENSY_TEMPLATE_PATH);
if (StringUtils.isNotBlank(tmp)) {
if (tmp.endsWith("/")) {
tmp = tmp.substring(0, tmp.length() - 1);
}
templatePath = tmp;
}
// 主域名,必须指定
tmp = config.get(Constants.FENSY_ROOT_DOMAIN);
if (StringUtils.isNotBlank(tmp))
rootDomain = tmp;
tmp = config.get(Constants.FENSY_ROOT_DOMAIN_TEMPLATE_PATH);
if (StringUtils.isNotBlank(tmp))
rootDomainTemplatePath = tmp;
// 二级域名和对应页面模板路径
tmp = config.get(Constants.FENSY_OTHER_DOMAIN_AND_TEMPLATE_PATH);
if (StringUtils.isNotBlank(tmp)) {
String[] domainAndPath = tmp.split(",");
for (String dp : domainAndPath) {
String[] arr = dp.split(":");
domainTemplatePathes.put(arr[0], templatePath + arr[1]);
}
}
defaultTemplatePath = templatePath + rootDomainTemplatePath;
// 某些URL前缀不予处理(例如 /img/**)
String ignores = config.get(Constants.FENSY_IGNORE_URI);
if (StringUtils.isBlank(ignores)) {
ignores = Constants.ACTION_IGNORE_URI;
}
ignoreURIs.addAll(Arrays.asList(StringUtils.split(ignores, ",")));
// 某些URL扩展名不予处理(例如 *.jpg)
ignores = config.get(Constants.FENSY_IGNORE_EXT);
if (StringUtils.isBlank(ignores)) {
ignores = Constants.ACTION_IGNORE_EXT;
}
for (String ig : StringUtils.split(ignores, ',')) {
ignoreExts.add('.' + ig.trim());
}
// 按顺序创建view
String views = config.get(Constants.FENSY_VIEW);
if (StringUtils.isNotBlank(views)) {
for (String v : StringUtils.split(views, ',')) {
View view = ViewMap.getView(v.toLowerCase());
// 从内置的viewMap中查找
if (view != null) {
viewList.add(view);
continue;
}
try {
viewList.add((View) Class.forName(v).newInstance());
} catch (Exception e) { | log.error("视图对象创建出错:" + view, Exceptions.getStackTraceAsString(e)); | 4 |
tmorcinek/android-codegenerator-library | src/test/java/com/morcinek/android/codegenerator/BActivityCodeGeneratorTest.java | [
"public class TemplateCodeGenerator {\n\n private BuildersCollection buildersCollection;\n\n private ResourceProvidersFactory resourceProvidersFactory;\n\n private TemplateManager templateManager;\n\n public TemplateCodeGenerator(String templateName, ResourceProvidersFactory resourceProvidersFactory, TemplatesProvider templatesProvider) {\n this.resourceProvidersFactory = resourceProvidersFactory;\n this.buildersCollection = new BuildersCollection(templatesProvider);\n this.templateManager = new TemplateManager(templatesProvider.provideTemplateForName(templateName));\n }\n\n public String generateCode(List<Resource> resources, String fileName) {\n buildersCollection.registerCodeBuilders(getResourceProviders(resources), fileName);\n\n Map<String, CodeBuilder> builderMap = buildersCollection.getBuilderMap();\n for (String key : builderMap.keySet()) {\n templateManager.addTemplateValue(key, builderMap.get(key).builtString());\n }\n\n return templateManager.getResult();\n }\n\n private List<ResourceProvider> getResourceProviders(List<Resource> resources) {\n List<ResourceProvider> resourceProviders = Lists.newArrayList();\n for (Resource resource : resources) {\n resourceProviders.add(resourceProvidersFactory.createResourceProvider(resource));\n }\n return resourceProviders;\n }\n}",
"public class BActivityResourceProvidersFactory implements ResourceProvidersFactory {\n\n @Override\n public ResourceProvider createResourceProvider(Resource resource) {\n if (isApplicable(resource, \"Button\", \"ImageButton\")) {\n return new BButtonProvider(resource);\n } else if (isApplicable(resource, \"List\")) {\n return new BListProvider(resource);\n }\n return new BDefaultProvider(resource);\n }\n\n private boolean isApplicable(Resource resource, String... resourcesNames) {\n return Lists.newArrayList(resourcesNames).contains(resource.getResourceType().getFullName());\n }\n}",
"public class ResourceTemplatesProvider implements TemplatesProvider {\n\n @Override\n public String provideTemplateForName(String templateName) {\n URL url = Resources.getResource(templateName);\n try {\n return Resources.toString(url, Charset.defaultCharset());\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n}",
"public interface TemplatesProvider {\n\n String provideTemplateForName(String templateName);\n}",
"public class XMLResourceExtractor implements ResourceExtractor {\n\n private StringExtractor<ResourceId> resourceIdExtractor;\n\n private StringExtractor<ResourceType> resourceTypeExtractor;\n\n public static XMLResourceExtractor createResourceExtractor() {\n return new XMLResourceExtractor(new ResourceIdExtractor(), new ResourceTypeExtractor());\n }\n\n protected XMLResourceExtractor(StringExtractor<ResourceId> resourceIdExtractor, StringExtractor<ResourceType> resourceTypeExtractor) {\n this.resourceIdExtractor = resourceIdExtractor;\n this.resourceTypeExtractor = resourceTypeExtractor;\n }\n\n @Override\n public List<Resource> extractResourceObjectsFromStream(InputStream inputStream) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {\n List<Resource> resources = new ArrayList<Resource>();\n NodeList nodeList = extractWidgetNodesWithId(inputStream);\n for (int i = 0; i < nodeList.getLength(); i++) {\n resources.add(getResourceObject(nodeList.item(i)));\n }\n return resources;\n }\n\n private Resource getResourceObject(Node node) {\n ResourceId resourceId = resourceIdExtractor.extractFromString(getIdAttributeValue(node));\n ResourceType resourceType = resourceTypeExtractor.extractFromString(node.getNodeName());\n return new Resource(resourceId, resourceType);\n }\n\n private String getIdAttributeValue(Node node) {\n return node.getAttributes().getNamedItem(\"android:id\").getNodeValue();\n }\n\n private NodeList extractWidgetNodesWithId(InputStream inputStream) throws ParserConfigurationException, SAXException,\n IOException, XPathExpressionException {\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n // factory.setNamespaceAware(true); // never forget this!\n DocumentBuilder builder = factory.newDocumentBuilder();\n Document doc = builder.parse(inputStream);\n XPathFactory pathFactory = XPathFactory.newInstance();\n XPath xPath = pathFactory.newXPath();\n XPathExpression expression = xPath.compile(\"//*[@id]\");\n return (NodeList) expression.evaluate(doc, XPathConstants.NODESET);\n }\n}",
"public class FileNameExtractor implements StringExtractor<String> {\n\n @Override\n public String extractFromString(String filePath) {\n return new File(filePath).getName().replaceFirst(\".xml\", \"\");\n }\n}",
"public class InputStreamProvider {\n\n public InputStream getStreamFromResource(String name) {\n return getClass().getResourceAsStream(\"/\" + name);\n }\n}"
] | import com.morcinek.android.codegenerator.codegeneration.TemplateCodeGenerator;
import com.morcinek.android.codegenerator.codegeneration.providers.factories.BActivityResourceProvidersFactory;
import com.morcinek.android.codegenerator.codegeneration.templates.ResourceTemplatesProvider;
import com.morcinek.android.codegenerator.codegeneration.templates.TemplatesProvider;
import com.morcinek.android.codegenerator.extractor.XMLResourceExtractor;
import com.morcinek.android.codegenerator.extractor.string.FileNameExtractor;
import com.morcinek.android.codegenerator.util.InputStreamProvider;
import org.fest.assertions.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException; | package com.morcinek.android.codegenerator;
public class BActivityCodeGeneratorTest {
private CodeGenerator codeGenerator;
private InputStreamProvider inputStreamProvider = new InputStreamProvider();
private TemplatesProvider templatesProvider = new ResourceTemplatesProvider();
@Before
public void setUp() throws Exception { | codeGenerator = new CodeGenerator(XMLResourceExtractor.createResourceExtractor(), new FileNameExtractor(), new TemplateCodeGenerator("BActivity_template", new BActivityResourceProvidersFactory(), new ResourceTemplatesProvider())); | 4 |
damingerdai/web-qq | src/main/java/org/aming/web/qq/contorller/UserController.java | [
"public class User extends AbstractUserDetails implements UserDetails {\n\n private static final long serialVersionUID = -5509256807259591938L;\n\n private String id;\n private String username;\n private String password;\n private String email;\n\n public String getId() {\n return id;\n }\n\n public User setId(String id) {\n this.id = id;\n return this;\n }\n\n @Override\n public String getUsername() {\n return username;\n }\n\n public User setUsername(String username) {\n this.username = username;\n return this;\n }\n\n @Override\n public String getPassword() {\n return password;\n }\n\n public User setPassword(String password) {\n this.password = password;\n return this;\n }\n\n public String getEmail() {\n return email;\n }\n\n public User setEmail(String email) {\n this.email = email;\n return this;\n }\n\n public User(String id, String username, String password, String email) {\n super();\n this.id = id;\n this.username = username;\n this.password = password;\n this.email = email;\n }\n\n public User(String username, String password) {\n super();\n this.id = IdGen.uuid();\n this.username = username;\n this.password = password;\n }\n\n public User(UserDetails userDetails){\n this(userDetails.getUsername(),userDetails.getPassword());\n }\n\n public User() {\n super();\n this.id = IdGen.uuid();\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this);\n }\n\n @Override\n public int hashCode() {\n return this.username.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if(obj == null){\n return false;\n }\n if(obj == this){\n return true;\n }\n if(obj instanceof User){\n if(obj instanceof UserDetails){\n UserDetails userDetails = (UserDetails)obj;\n if(this.getUsername().equals(userDetails.getUsername())){\n return true;\n }\n }else{\n User user = (User)obj;\n if(this.getUsername().equals(user.getUsername())){\n return true;\n }\n }\n }\n return false;\n }\n}",
"public class Logger {\n\n /**\n * 默认的日志记录器\n */\n private org.slf4j.Logger logger;\n\n /**\n * 初始化\n *\n * @param logger\n */\n public Logger(org.slf4j.Logger logger) {\n this.logger = logger;\n }\n\n /**\n * 如果默认的日志管理器支持追踪信息<br/>\n * 则追踪信息\n *\n * @param msg 信息\n */\n public void trace(String msg) {\n if (logger.isTraceEnabled()) {\n logger.trace(msg);\n }\n }\n\n /**\n * 如果默认的日志管理器支持追踪信息<br/>\n * 则追踪信息\n *\n * @param msg 信息\n */\n public void trace(Supplier<String> msg){\n if (logger.isTraceEnabled()) {\n logger.trace(msg.get());\n }\n }\n\n /**\n * 如果默认的日志管理器支持追踪信息<br/>\n * 则追踪信息\n *\n * @param msg 信息\n * @param obj 占位符信息\n */\n public void trace(String msg, Object... obj) {\n if (logger.isTraceEnabled()) {\n logger.trace(msg, obj);\n }\n }\n\n\n /**\n * 如果默认的日志管理器支持追踪信息<br/>\n * 则追踪信息\n *\n * @param msg 信息\n * @param cause 异常\n */\n public void trace(String msg, Throwable cause) {\n if (logger.isTraceEnabled()) {\n logger.trace(msg, cause);\n }\n }\n\n /**\n * 如果默认的日志管理器支持调试信息<br/>\n * 则调试信息\n *\n * @param msg\n */\n public void debug(String msg) {\n if (logger.isDebugEnabled()) {\n logger.debug(msg);\n }\n }\n\n /**\n * 如果默认的日志管理器支持调试信息<br/>\n * 则调试信息\n *\n * @param msg\n */\n public void debug(Supplier<String> msg){\n if (logger.isDebugEnabled()) {\n logger.debug(msg.get());\n }\n }\n\n /**\n * 如果默认的日志管理器支持调试信息<br/>\n * 则调试信息\n *\n * @param msg\n * @param obj\n */\n public void debug(String msg, Object... obj) {\n if (logger.isDebugEnabled()) {\n logger.debug(msg, obj);\n }\n }\n\n /**\n * 如果默认的日志管理器支持调试信息<br/>\n * 则调试信息\n *\n * @param msg\n * @param cause\n */\n public void debug(String msg, Throwable cause) {\n if (logger.isDebugEnabled()) {\n logger.debug(msg, cause);\n }\n }\n\n /**\n * 如果默认的日志管理器支持警告信息<br/>\n * 则警告信息\n *\n * @param msg\n */\n public void warn(String msg) {\n if (logger.isWarnEnabled()) {\n logger.warn(msg);\n }\n }\n\n /**\n * 如果默认的日志管理器支持警告信息<br/>\n * 则警告信息\n *\n * @param msg\n */\n public void warn(Supplier<String> msg){\n if (logger.isWarnEnabled()) {\n logger.warn(msg.get());\n }\n }\n\n /**\n * 如果默认的日志管理器支持警告信息<br/>\n * 则警告信息\n *\n * @param msg\n * @param obj\n */\n public void warn(String msg, Object... obj) {\n if (logger.isWarnEnabled()) {\n logger.warn(msg, obj);\n }\n }\n\n /**\n * 如果默认的日志管理器支持警告信息<br/>\n * 则警告信息\n *\n * @param msg\n * @param cause\n */\n public void warn(String msg, Throwable cause) {\n if (logger.isWarnEnabled()) {\n logger.warn(msg, cause);\n }\n }\n\n /**\n * 如果默认的日志管理器支持报错信息<br/>\n * 则报错信息\n *\n * @param msg\n */\n public void error(String msg) {\n if (logger.isErrorEnabled()) {\n logger.error(msg);\n }\n }\n\n /**\n * 如果默认的日志管理器支持报错信息<br/>\n * 则报错信息\n *\n * @param msg\n */\n public void error(Supplier<String> msg){\n if (logger.isErrorEnabled()) {\n\n }\n }\n\n /**\n * 如果默认的日志管理器支持报错信息<br/>\n * 则报错信息\n *\n * @param msg\n * @param obj\n */\n public void error(String msg, Object... obj) {\n if (logger.isErrorEnabled()) {\n logger.error(msg, obj);\n }\n }\n\n /**\n * 如果默认的日志管理器支持报错信息<br/>\n * 则报错信息\n *\n * @param msg\n * @param cause\n */\n public void error(String msg, Throwable cause) {\n if (logger.isErrorEnabled()) {\n logger.error(msg, cause);\n }\n }\n\n @Override\n public String toString(){\n return ToStringBuilder.reflectionToString(this);\n }\n}",
"public class LoggerManager {\n\n private static Map<String,Logger> encache = Maps.newHashMap();\n\n public static Logger getLogger(Class<?> loggerClassName){\n return getLogger(loggerClassName.getName());\n }\n\n public static Logger getLogger(String loggerName){\n if(isNonExistLogger(loggerName)){\n newLogger(loggerName);\n }\n return encache.get(loggerName);\n }\n\n private static void newLogger(String loggerName){\n encache.put(loggerName,new Logger(LoggerFactory.getLogger(loggerName)));\n }\n\n private static boolean isExistLogger(String loggerName){\n return encache.containsKey(loggerName);\n }\n\n private static boolean isNonExistLogger(String loggerName){\n return !isExistLogger(loggerName);\n }\n}",
"public class CommonResponse implements Serializable {\n\n private static final long serialVersionUID = 7980325592134636957L;\n\n private static final boolean DEFAULT_SUCCESS_FLAG = true;\n\n private boolean success;\n private Object data;\n private WebQQException error;\n\n @Deprecated\n public static CommonResponse getCommonResponse(boolean success,Object data){\n return new CommonResponse(success,data);\n }\n\n public static CommonResponse getSuccessCommonResponse(Object data){\n return new CommonResponse(true,data);\n }\n\n public static WebQQException getErrorCommonResponse(Throwable error) {\n if(error instanceof WebQQException){\n return (WebQQException)error;\n } else if (error instanceof WebQQServiceException) {\n return new WebQQException(5001,error.getMessage());\n } else {\n return new WebQQException();\n }\n }\n\n public static WebQQException getErrorCommonResponse(int code, String message) {\n return new WebQQException(code,message);\n }\n\n public boolean isSuccess() {\n return success;\n }\n\n public void setSuccess(boolean success) {\n this.success = success;\n }\n\n public Object getData() {\n return data;\n }\n\n public void setData(Object data) {\n this.data = data;\n }\n\n public WebQQException getError() {\n return error;\n }\n\n public void setError(WebQQException error){\n this.error = error;\n }\n\n public CommonResponse() {\n super();\n this.success = DEFAULT_SUCCESS_FLAG;\n }\n\n public CommonResponse(boolean success, Object data) {\n super();\n this.success = success;\n this.data = data;\n }\n\n public CommonResponse(boolean success,WebQQException error){\n super();\n this.success = success;\n this.error = error;\n }\n}",
"public interface UserService extends UserDetailsService {\n\n List<User> getFriendsByUsername(String username) throws WebQQServiceException;\n\n UserDetails getCurrentUser() throws WebQQServiceException;\n\n List<User> getFriendsForCurrentUser() throws WebQQServiceException;\n\n Set<User> findMoreUser(@Nonnull String condition) throws WebQQServiceException;\n\n void addRelationship(User friend) throws WebQQServiceException;\n\n boolean addUser(User user) throws WebQQServiceException;\n\n User getUserInfo(@Nullable String username) throws WebQQServiceException;\n}"
] | import org.aming.web.qq.domain.User;
import org.aming.web.qq.logger.Logger;
import org.aming.web.qq.logger.LoggerManager;
import org.aming.web.qq.response.CommonResponse;
import org.aming.web.qq.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*; | package org.aming.web.qq.contorller;
/**
* @author daming
* @version 2017/10/2.
*/
@RestController
@RequestMapping("/webqq")
public class UserController {
| private static final Logger logger = LoggerManager.getLogger(UserController.class); | 1 |
Nanopublication/nanopub-java | src/main/java/org/nanopub/Run.java | [
"public class MakeIndex {\n\n\[email protected](description = \"input-nanopub-files\")\n\tprivate List<File> inputFiles = new ArrayList<File>();\n\n\[email protected](names = \"-fs\", description = \"Add index nanopubs from input files \" +\n\t\t\t\"as sub-indexes (instead of elements); has no effect if input file is plain-text list of URIs\")\n\tprivate boolean useSubindexes = false;\n\n\[email protected](names = \"-e\", description = \"Add given URIs as elements \" +\n\t\t\t\"(in addition to the ones from the input files)\")\n\tprivate List<String> elements = new ArrayList<>();\n\n\[email protected](names = \"-s\", description = \"Add given URIs as sub-indexes \" +\n\t\t\t\"(in addition to the ones from the input files, if given)\")\n\tprivate List<String> subindexes = new ArrayList<>();\n\n\[email protected](names = \"-x\", description = \"Set given URI as superseded index\")\n\tprivate String supersededIndex;\n\n\[email protected](names = \"-o\", description = \"Output file\")\n\tprivate File outputFile = new File(\"index.trig\");\n\n\[email protected](names = \"-u\", description = \"Base URI for index nanopubs\")\n\tprivate String baseUri = \"http://purl.org/nanopub/temp/index/\";\n\n\[email protected](names = \"-t\", description = \"Title of index\")\n\tprivate String iTitle;\n\n\[email protected](names = \"-d\", description = \"Description of index\")\n\tprivate String iDesc;\n\n\[email protected](names = \"-c\", description = \"Creator of index\")\n\tprivate List<String> iCreators = new ArrayList<>();\n\n\[email protected](names = \"-l\", description = \"License URI\")\n\tprivate String licenseUri;\n\n\[email protected](names = \"-a\", description = \"'See also' resources\")\n\tprivate List<String> seeAlso = new ArrayList<>();\n\n\[email protected](names = \"-p\", description = \"Make plain (non-trusty) index nanopublications\")\n\tprivate boolean plainNanopub;\n\n//\[email protected](names = \"--sig\", description = \"Path and file name of key files\")\n//\tprivate boolean useSignature;\n//\n//\[email protected](names = \"--sig-key-file\", description = \"Path and file name of key files\")\n//\tprivate String keyFilename;\n//\n//\[email protected](names = \"--sig-algorithm\", description = \"Signature algorithm: either RSA or DSA\")\n//\tprivate SignatureAlgorithm algorithm;\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tNanopubImpl.ensureLoaded();\n\t\tMakeIndex obj = new MakeIndex();\n\t\tJCommander jc = new JCommander(obj);\n\t\ttry {\n\t\t\tjc.parse(args);\n\t\t} catch (ParameterException ex) {\n\t\t\tjc.usage();\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tif (obj.inputFiles.isEmpty() && obj.elements.isEmpty() && obj.subindexes.isEmpty() && obj.supersededIndex == null) {\n\t\t\tjc.usage();\n\t\t\tSystem.exit(1);\n\t\t}\n\t\ttry {\n\t\t\tobj.run();\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tSystem.exit(1);\n\t\t}\n\t}\n\n\tprivate SimpleIndexCreator indexCreator;\n\tprivate OutputStreamWriter writer;\n\tprivate RDFFormat outFormat;\n\tprivate int count;\n//\tprivate KeyPair key;\n\n\tprivate MakeIndex() {\n\t}\n\n\tprivate void init() throws IOException {\n\t\tcount = 0;\n\t\toutFormat = Rio.getParserFormatForFileName(outputFile.getName()).orElse(RDFFormat.TRIG);\n\t\tif (outputFile.getName().endsWith(\".gz\")) {\n\t\t\twriter = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outputFile)), Charset.forName(\"UTF-8\"));\n\t\t} else {\n\t\t\twriter = new OutputStreamWriter(new FileOutputStream(outputFile), Charset.forName(\"UTF-8\"));\n\t\t}\n\n\t\tindexCreator = new SimpleIndexCreator(!plainNanopub) {\n\n\t\t\t@Override\n\t\t\tpublic void handleIncompleteIndex(NanopubIndex npi) {\n\t\t\t\ttry {\n\t\t\t\t\twriter.write(NanopubUtils.writeToString(npi, outFormat) + \"\\n\\n\");\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void handleCompleteIndex(NanopubIndex npi) {\n\t\t\t\tSystem.out.println(\"Index URI: \" + npi.getUri());\n\t\t\t\ttry {\n\t\t\t\t\twriter.write(NanopubUtils.writeToString(npi, outFormat) + \"\\n\\n\");\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t}\n\t\t\t}\n\n\t\t};\n\n\t\tindexCreator.setBaseUri(baseUri);\n\t\tif (iTitle != null) {\n\t\t\tindexCreator.setTitle(iTitle);\n\t\t}\n\t\tif (iDesc != null) {\n\t\t\tindexCreator.setDescription(iDesc);\n\t\t}\n\t\tfor (String creator : iCreators) {\n\t\t\tindexCreator.addCreator(creator);\n\t\t}\n\t\tif (licenseUri != null) {\n\t\t\tindexCreator.setLicense(SimpleValueFactory.getInstance().createIRI(licenseUri));\n\t\t}\n\t\tfor (String sa : seeAlso) {\n\t\t\tindexCreator.addSeeAlsoUri(SimpleValueFactory.getInstance().createIRI(sa));\n\t\t}\n\t}\n\n\tprivate void run() throws Exception {\n\t\tinit();\n\n//\t\tif (useSignature) {\n//\t\t\tif (algorithm == null) {\n//\t\t\t\tif (keyFilename == null) {\n//\t\t\t\t\tkeyFilename = \"~/.nanopub/id_rsa\";\n//\t\t\t\t\talgorithm = SignatureAlgorithm.RSA;\n//\t\t\t\t} else if (keyFilename.endsWith(\"_rsa\")) {\n//\t\t\t\t\talgorithm = SignatureAlgorithm.RSA;\n//\t\t\t\t} else if (keyFilename.endsWith(\"_dsa\")) {\n//\t\t\t\t\talgorithm = SignatureAlgorithm.DSA;\n//\t\t\t\t} else {\n//\t\t\t\t\t// Assuming RSA if not other information is available\n//\t\t\t\t\talgorithm = SignatureAlgorithm.RSA;\n//\t\t\t\t}\n//\t\t\t} else if (keyFilename == null) {\n//\t\t\t\tkeyFilename = \"~/.nanopub/id_\" + algorithm.name().toLowerCase();\n//\t\t\t}\n//\t\t\tkey = SignNanopub.loadKey(keyFilename, algorithm);\n//\t\t}\n\n\t\tfor (File f : inputFiles) {\n\t\t\tif (f.getName().endsWith(\".txt\")) {\n\t\t\t\tBufferedReader br = null;\n\t\t\t\ttry {\n\t\t\t\t\tbr = new BufferedReader(new FileReader(f));\n\t\t\t\t String line;\n\t\t\t\t while ((line = br.readLine()) != null) {\n\t\t\t\t \tline = line.trim();\n\t\t\t\t \tif (line.isEmpty()) continue;\n\t\t\t\t \t// To allow for other content in the file, ignore everything after the first blank space:\n\t\t\t\t \tif (line.contains(\" \")) line = line.substring(0, line.indexOf(\" \"));\n\t\t\t\t \tindexCreator.addElement(SimpleValueFactory.getInstance().createIRI(line));\n\t\t\t\t }\n\t\t\t\t} finally {\n\t\t\t\t\tif (br != null) br.close();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tRDFFormat format = Rio.getParserFormatForFileName(f.getName()).orElse(RDFFormat.TRIG);\n\t\t\t\tMultiNanopubRdfHandler.process(format, f, new NanopubHandler() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void handleNanopub(Nanopub np) {\n\t\t\t\t\t\tif (useSubindexes && IndexUtils.isIndex(np)) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tindexCreator.addSubIndex(IndexUtils.castToIndex(np));\n\t\t\t\t\t\t\t} catch (MalformedNanopubException ex) {\n\t\t\t\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindexCreator.addElement(np);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t\tif (count % 100 == 0) {\n\t\t\t\t\t\t\tSystem.err.print(count + \" nanopubs...\\r\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tfor (String e : elements) {\n\t\t\tindexCreator.addElement(SimpleValueFactory.getInstance().createIRI(e));\n\t\t}\n\t\tfor (String s : subindexes) {\n\t\t\tindexCreator.addSubIndex(SimpleValueFactory.getInstance().createIRI(s));\n\t\t}\n\t\tif (supersededIndex != null) {\n\t\t\tindexCreator.setSupersededIndex(SimpleValueFactory.getInstance().createIRI(supersededIndex));\n\t\t}\n\t\tindexCreator.finalizeNanopub();\n\t\twriter.close();\n\t}\n\n}",
"public class MakeKeys {\n\n\[email protected](names = \"-f\", description = \"Path and file name prefix of key files\")\n\tprivate String pathAndFilenamePrefix = \"~/.nanopub/id\";\n\n\[email protected](names = \"-a\", description = \"Signature algorithm: either RSA or DSA\")\n\tprivate SignatureAlgorithm algorithm = SignatureAlgorithm.DSA;\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tNanopubImpl.ensureLoaded();\n\t\tMakeKeys obj = new MakeKeys();\n\t\tJCommander jc = new JCommander(obj);\n\t\ttry {\n\t\t\tjc.parse(args);\n\t\t} catch (ParameterException ex) {\n\t\t\tjc.usage();\n\t\t\tSystem.exit(1);\n\t\t}\n\t\ttry {\n\t\t\tobj.run();\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tSystem.exit(1);\n\t\t}\n\t}\n\n\tprivate MakeKeys() {\n\t}\n\n\tprivate void run() throws IOException {\n\t\tmake(pathAndFilenamePrefix, algorithm);\n\t}\n\n\tpublic static void make(String pathAndFilenamePrefix, SignatureAlgorithm algorithm) throws IOException {\n\n\t\t// Preparation:\n\t\tString pathAndFilename = SignatureUtils.getFullFilePath(pathAndFilenamePrefix) + \"_\" + algorithm.name().toLowerCase();\n\t\tFile publicKeyFile = new File(pathAndFilename + \".pub\");\n\t\tif (publicKeyFile.exists()) {\n\t\t\tthrow new FileAlreadyExistsException(\"Key file already exists: \" + publicKeyFile);\n\t\t}\n\t\tFile privateKeyFile = new File(pathAndFilename);\n\t\tif (privateKeyFile.exists()) {\n\t\t\tthrow new FileAlreadyExistsException(\"Key file already exists: \" + privateKeyFile);\n\t\t}\n\t\tFile parentDir = privateKeyFile.getParentFile();\n\t\tif (parentDir != null) parentDir.mkdir();\n\t\tpublicKeyFile.createNewFile();\n\t\tpublicKeyFile.setReadable(true, false);\n\t\tpublicKeyFile.setWritable(false, false);\n\t\tpublicKeyFile.setWritable(true, true);\n\t\tprivateKeyFile.createNewFile();\n\t\tprivateKeyFile.setReadable(false, false);\n\t\tprivateKeyFile.setReadable(true, true);\n\t\tprivateKeyFile.setWritable(false, false);\n\t\tprivateKeyFile.setWritable(true, true);\n\n\t\t// Creating and writing keys\n\t\tKeyPairGenerator keyPairGenerator;\n\t\tSecureRandom random;\n\t\ttry {\n\t\t\tkeyPairGenerator = KeyPairGenerator.getInstance(algorithm.name());\n\t\t\trandom = SecureRandom.getInstance(\"SHA1PRNG\");\n\t\t} catch (GeneralSecurityException ex) {\n\t\t\tthrow new RuntimeException(ex);\n\t\t}\n\t\tkeyPairGenerator.initialize(1024, random);\n\t\tKeyPair keyPair = keyPairGenerator.genKeyPair();\n\n\t\tFileOutputStream outPublic = new FileOutputStream(publicKeyFile);\n\t\toutPublic.write(DatatypeConverter.printBase64Binary(keyPair.getPublic().getEncoded()).getBytes());\n\t\toutPublic.close();\n\t\tFileOutputStream outPrivate = new FileOutputStream(privateKeyFile);\n\t\toutPrivate.write(DatatypeConverter.printBase64Binary(keyPair.getPrivate().getEncoded()).getBytes());\n\t\toutPrivate.close();\n\t}\n\n}",
"public class SignNanopub {\n\n\[email protected](description = \"input-nanopub-files\", required = true)\n\tprivate List<File> inputNanopubFiles = new ArrayList<File>();\n\n\[email protected](names = \"-o\", description = \"Output file\")\n\tprivate File singleOutputFile;\n\n\[email protected](names = \"-k\", description = \"Path and file name of key files\")\n\tprivate String keyFilename;\n\n\[email protected](names = \"-a\", description = \"Signature algorithm: either RSA or DSA\")\n\tprivate SignatureAlgorithm algorithm;\n\n\[email protected](names = \"-v\", description = \"Verbose\")\n\tprivate boolean verbose = false;\n\n\[email protected](names = \"-r\", description = \"Resolve cross-nanopub references\")\n\tprivate boolean resolveCrossRefs = false;\n\n\[email protected](names = \"-R\", description = \"Resolve cross-nanopub references based on prefixes\")\n\tprivate boolean resolveCrossRefsPrefixBased = false;\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tNanopubImpl.ensureLoaded();\n\t\tSignNanopub obj = new SignNanopub();\n\t\tJCommander jc = new JCommander(obj);\n\t\ttry {\n\t\t\tjc.parse(args);\n\t\t} catch (ParameterException ex) {\n\t\t\tjc.usage();\n\t\t\tSystem.exit(1);\n\t\t}\n\t\ttry {\n\t\t\tobj.run();\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tSystem.exit(1);\n\t\t}\n\t}\n\n\tprivate KeyPair key;\n\n\tprivate SignNanopub() {\n\t}\n\n\tprivate void run() throws Exception {\n\t\tif (algorithm == null) {\n\t\t\tif (keyFilename == null) {\n\t\t\t\tkeyFilename = \"~/.nanopub/id_rsa\";\n\t\t\t\talgorithm = SignatureAlgorithm.RSA;\n\t\t\t} else if (keyFilename.endsWith(\"_rsa\")) {\n\t\t\t\talgorithm = SignatureAlgorithm.RSA;\n\t\t\t} else if (keyFilename.endsWith(\"_dsa\")) {\n\t\t\t\talgorithm = SignatureAlgorithm.DSA;\n\t\t\t} else {\n\t\t\t\t// Assuming RSA if not other information is available\n\t\t\t\talgorithm = SignatureAlgorithm.RSA;\n\t\t\t}\n\t\t} else if (keyFilename == null) {\n\t\t\tkeyFilename = \"~/.nanopub/id_\" + algorithm.name().toLowerCase();\n\t\t}\n\t\tkey = loadKey(keyFilename, algorithm);\n\t\tfinal TransformContext c = new TransformContext(algorithm, key, null, resolveCrossRefs, resolveCrossRefsPrefixBased);\n\n\t\tfinal OutputStream singleOut;\n\t\tif (singleOutputFile != null) {\n\t\t\tif (singleOutputFile.getName().matches(\".*\\\\.(gz|gzip)\")) {\n\t\t\t\tsingleOut = new GZIPOutputStream(new FileOutputStream(singleOutputFile));\n\t\t\t} else {\n\t\t\t\tsingleOut = new FileOutputStream(singleOutputFile);\n\t\t\t}\n\t\t} else {\n\t\t\tsingleOut = null;\n\t\t}\n\n\t\tfor (File inputFile : inputNanopubFiles) {\n\t\t\tFile outputFile;\n\t\t\tfinal OutputStream out;\n\t\t\tif (singleOutputFile == null) {\n\t\t\t\toutputFile = new File(inputFile.getParent(), \"signed.\" + inputFile.getName());\n\t\t\t\tif (inputFile.getName().matches(\".*\\\\.(gz|gzip)\")) {\n\t\t\t\t\tout = new GZIPOutputStream(new FileOutputStream(outputFile));\n\t\t\t\t} else {\n\t\t\t\t\tout = new FileOutputStream(outputFile);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toutputFile = singleOutputFile;\n\t\t\t\tout = singleOut;\n\t\t\t}\n\t\t\tfinal RDFFormat inFormat = new TrustyUriResource(inputFile).getFormat(RDFFormat.TRIG);\n\t\t\tfinal RDFFormat outFormat = new TrustyUriResource(outputFile).getFormat(RDFFormat.TRIG);\n\t\t\tMultiNanopubRdfHandler.process(inFormat, inputFile, new NanopubHandler() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void handleNanopub(Nanopub np) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnp = writeAsSignedTrustyNanopub(np, outFormat, c, out);\n\t\t\t\t\t\tif (verbose) {\n\t\t\t\t\t\t\tSystem.out.println(\"Nanopub URI: \" + np.getUri());\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (RDFHandlerException ex) {\n\t\t\t\t\t\tex.printStackTrace();\n\t\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t\t} catch (TrustyUriException ex) {\n\t\t\t\t\t\tex.printStackTrace();\n\t\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t\t} catch (InvalidKeyException ex) {\n\t\t\t\t\t\tex.printStackTrace();\n\t\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t\t} catch (SignatureException ex) {\n\t\t\t\t\t\tex.printStackTrace();\n\t\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t});\n\t\t\tout.close();\n\t\t}\n\t}\n\n\tpublic static Nanopub signAndTransform(Nanopub nanopub, TransformContext c)\n\t\t\tthrows TrustyUriException, InvalidKeyException, SignatureException {\n\t\tif (SignatureUtils.seemsToHaveSignature(nanopub)) {\n\t\t\tthrow new SignatureException(\"Seems to have signature before signing: \" + nanopub.getUri());\n\t\t}\n\t\tif (nanopub instanceof NanopubWithNs) {\n\t\t\t((NanopubWithNs) nanopub).removeUnusedPrefixes();\n\t\t}\n\t\ttry {\n\t\t\treturn SignatureUtils.createSignedNanopub(nanopub, c);\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tthrow new RuntimeException(ex);\n\t\t}\n\t}\n\n\tpublic static void signAndTransformMultiNanopub(final RDFFormat format, File file, TransformContext c, OutputStream out)\n\t\t\tthrows IOException, RDFParseException, RDFHandlerException, MalformedNanopubException {\n\t\tInputStream in = new FileInputStream(file);\n\t\tsignAndTransformMultiNanopub(format, in, c, out);\n\t}\n\n\tpublic static void signAndTransformMultiNanopub(final RDFFormat format, InputStream in, final TransformContext c, final OutputStream out)\n\t\t\tthrows IOException, RDFParseException, RDFHandlerException, MalformedNanopubException {\n\t\tMultiNanopubRdfHandler.process(format, in, new NanopubHandler() {\n\n\t\t\t@Override\n\t\t\tpublic void handleNanopub(Nanopub np) {\n\t\t\t\ttry {\n\t\t\t\t\twriteAsSignedTrustyNanopub(np, format, c, out);\n\t\t\t\t} catch (RDFHandlerException ex) {\n\t\t\t\t\tex.printStackTrace();\n\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t} catch (TrustyUriException ex) {\n\t\t\t\t\tex.printStackTrace();\n\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t} catch (InvalidKeyException ex) {\n\t\t\t\t\tex.printStackTrace();\n\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t} catch (SignatureException ex) {\n\t\t\t\t\tex.printStackTrace();\n\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t}\n\t\t\t}\n\n\t\t});\n\t\tout.close();\n\t}\n\n\tpublic static Nanopub writeAsSignedTrustyNanopub(Nanopub np, RDFFormat format, TransformContext c, OutputStream out)\n\t\t\tthrows RDFHandlerException, TrustyUriException, InvalidKeyException, SignatureException {\n\t\tnp = signAndTransform(np, c);\n\t\tRDFWriter w = Rio.createWriter(format, new OutputStreamWriter(out, Charset.forName(\"UTF-8\")));\n\t\tNanopubUtils.propagateToHandler(np, w);\n\t\treturn np;\n\t}\n\n\tpublic static KeyPair loadKey(String keyFilename, SignatureAlgorithm algorithm) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {\n\t\tkeyFilename = SignatureUtils.getFullFilePath(keyFilename);\n\t\tKeyFactory kf = KeyFactory.getInstance(algorithm.name());\n\t\tbyte[] privateKeyBytes = DatatypeConverter.parseBase64Binary(IOUtils.toString(new FileInputStream(keyFilename), \"UTF-8\"));\n\t\tKeySpec privateSpec = new PKCS8EncodedKeySpec(privateKeyBytes);\n\t\tPrivateKey privateKey = kf.generatePrivate(privateSpec);\n\t\tbyte[] publicKeyBytes = DatatypeConverter.parseBase64Binary(IOUtils.toString(new FileInputStream(keyFilename + \".pub\"), \"UTF-8\"));\n\t\tKeySpec publicSpec = new X509EncodedKeySpec(publicKeyBytes);\n\t\tPublicKey publicKey = kf.generatePublic(publicSpec);\n\t\treturn new KeyPair(publicKey, privateKey);\n\t}\n\n}",
"public class GetNanopub {\n\n\[email protected](description = \"nanopub-uris-or-artifact-codes\", required = true)\n\tprivate List<String> nanopubIds;\n\n\[email protected](names = \"-f\", description = \"Format of the nanopub: trig, nq, trix, trig.gz, ...\")\n\tprivate String format;\n\n\[email protected](names = \"-o\", description = \"Output file\")\n\tprivate File outputFile;\n\n\[email protected](names = \"-e\", description = \"Write error messages from fetching nanopubs into this file (ignored otherwise)\")\n\tprivate File errorFile;\n\n\[email protected](names = \"-i\", description = \"Retrieve the index for the given index nanopub\")\n\tprivate boolean getIndex;\n\n\[email protected](names = \"-c\", description = \"Retrieve the content of the given index\")\n\tprivate boolean getIndexContent;\n\n\[email protected](names = \"--mongodb-host\", description = \"Directly contact single MongoDB instance instead of the network (e.g. 'localhost')\")\n\tprivate String mongoDbHost;\n\n\[email protected](names = \"--mongodb-port\", description = \"MongoDB port\")\n\tprivate int mongoDbPort = 27017;\n\n\[email protected](names = \"--mongodb-dbname\", description = \"MongoDB database name\")\n\tprivate String mongoDbName = \"nanopub-server\";\n\n\[email protected](names = \"--mongodb-user\", description = \"MongoDB user name\")\n\tprivate String mongoDbUsername;\n\n\[email protected](names = \"--mongodb-pw\", description = \"MongoDB password\")\n\tprivate String mongoDbPassword;\n\n\[email protected](names = \"-r\", description = \"Show a report in the end\")\n\tprivate boolean showReport;\n\n\[email protected](names = \"-l\", description = \"Use a local server, e.g. http://localhost:7880/\")\n\tprivate String localServer;\n\n\[email protected](names = \"--simulate-unreliable-connection\",\n\t\t\tdescription = \"Simulate an unreliable connection for testing purposes\")\n\tprivate boolean simUnrelConn;\n\n\tpublic static void main(String[] args) {\n\t\tNanopubImpl.ensureLoaded();\n\t\tGetNanopub obj = new GetNanopub();\n\t\tJCommander jc = new JCommander(obj);\n\t\ttry {\n\t\t\tjc.parse(args);\n\t\t} catch (ParameterException ex) {\n\t\t\tjc.usage();\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tsimulateUnreliableConnection = obj.simUnrelConn;\n\t\ttry {\n\t\t\tobj.run();\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tSystem.exit(1);\n\t\t}\n\t}\n\n\tprivate static boolean simulateUnreliableConnection = false;\n\n\tpublic static Nanopub get(String uriOrArtifactCode) {\n\t\tServerIterator serverIterator = new ServerIterator();\n\t\tString ac = getArtifactCode(uriOrArtifactCode);\n\t\tif (!ac.startsWith(RdfModule.MODULE_ID)) {\n\t\t\tthrow new IllegalArgumentException(\"Not a trusty URI of type RA\");\n\t\t}\n\t\twhile (serverIterator.hasNext()) {\n\t\t\tServerInfo serverInfo = serverIterator.next();\n\t\t\ttry {\n\t\t\t\tNanopub np = get(ac, serverInfo);\n\t\t\t\tif (np != null) {\n\t\t\t\t\treturn np;\n\t\t\t\t}\n\t\t\t} catch (IOException ex) {\n\t\t\t\t// ignore\n\t\t\t} catch (RDF4JException ex) {\n\t\t\t\t// ignore\n\t\t\t} catch (MalformedNanopubException ex) {\n\t\t\t\t// ignore\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static Nanopub get(String uriOrArtifactCode, NanopubDb db) {\n\t\tString ac = getArtifactCode(uriOrArtifactCode);\n\t\tif (!ac.startsWith(RdfModule.MODULE_ID)) {\n\t\t\tthrow new IllegalArgumentException(\"Not a trusty URI of type RA\");\n\t\t}\n\t\treturn db.getNanopub(ac);\n\t}\n\n\tpublic static Nanopub get(String artifactCode, ServerInfo serverInfo)\n\t\t\tthrows IOException, RDF4JException, MalformedNanopubException {\n\t\treturn get(artifactCode, serverInfo.getPublicUrl());\n\t}\n\n\tpublic static Nanopub get(String artifactCode, String serverUrl)\n\t\t\tthrows IOException, RDF4JException, MalformedNanopubException {\n\t\tRequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000)\n\t\t\t\t.setConnectionRequestTimeout(100).setSocketTimeout(1000)\n\t\t\t\t.setCookieSpec(CookieSpecs.STANDARD).build();\n\t\tHttpClient c = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();\n\t\treturn get(artifactCode, serverUrl, c);\n\t}\n\n\tpublic static Nanopub get(String artifactCode, String serverUrl, HttpClient httpClient)\n\t\t\tthrows IOException, RDF4JException, MalformedNanopubException {\n\t\tHttpGet get = new HttpGet(serverUrl + artifactCode);\n\t\tget.setHeader(\"Accept\", \"application/trig\");\n\t\tInputStream in = null;\n\t\ttry {\n\t\t\tHttpResponse resp = httpClient.execute(get);\n\t\t\tif (!wasSuccessful(resp)) {\n\t\t\t\tEntityUtils.consumeQuietly(resp.getEntity());\n\t\t\t\tthrow new IOException(resp.getStatusLine().toString());\n\t\t\t}\n\t\t\tin = resp.getEntity().getContent();\n\t\t\tif (simulateUnreliableConnection) {\n\t\t\t\tin = new UnreliableInputStream(in);\n\t\t\t}\n\t\t\tNanopub nanopub = new NanopubImpl(in, RDFFormat.TRIG);\n\t\t\tif (!TrustyNanopubUtils.isValidTrustyNanopub(nanopub)) {\n\t\t\t\tthrow new MalformedNanopubException(\"Nanopub is not trusty\");\n\t\t\t}\n\t\t\treturn nanopub;\n\t\t} finally {\n\t\t\tif (in != null) in.close();\n\t\t}\n\t}\n\n\tpublic static String getArtifactCode(String uriOrArtifactCode) {\n\t\tif (uriOrArtifactCode.indexOf(\":\") > 0) {\n\t\t\tIRI uri = SimpleValueFactory.getInstance().createIRI(uriOrArtifactCode);\n\t\t\tif (!TrustyUriUtils.isPotentialTrustyUri(uri)) {\n\t\t\t\tthrow new IllegalArgumentException(\"Not a well-formed trusty URI\");\n\t\t\t}\n\t\t\treturn TrustyUriUtils.getArtifactCode(uri.toString());\n\t\t} else {\n\t\t\tif (!TrustyUriUtils.isPotentialArtifactCode(uriOrArtifactCode)) {\n\t\t\t\tthrow new IllegalArgumentException(\"Not a well-formed artifact code\");\n\t\t\t}\n\t\t\treturn uriOrArtifactCode;\n\t\t}\n\t}\n\n\tprivate OutputStream outputStream = System.out;\n\tprivate PrintStream errorStream = null;\n\tprivate int count;\n\tprivate List<Exception> exceptions;\n\tprivate NanopubDb db = null;\n\n\tprivate RDFFormat rdfFormat;\n\n\tpublic GetNanopub() {\n\t}\n\n\tprivate void run() throws IOException, RDFHandlerException, MalformedNanopubException {\n\t\tif (showReport) {\n\t\t\texceptions = new ArrayList<>();\n\t\t}\n\t\tif (outputFile == null) {\n\t\t\tif (format == null) {\n\t\t\t\tformat = \"trig\";\n\t\t\t}\n\t\t\trdfFormat = Rio.getParserFormatForFileName(\"file.\" + format).orElse(RDFFormat.TRIG);\n\t\t} else {\n\t\t\trdfFormat = Rio.getParserFormatForFileName(outputFile.getName()).orElse(RDFFormat.TRIG);\n\t\t\tif (outputFile.getName().endsWith(\".gz\")) {\n\t\t\t\toutputStream = new GZIPOutputStream(new FileOutputStream(outputFile));\n\t\t\t} else {\n\t\t\t\toutputStream = new FileOutputStream(outputFile);\n\t\t\t}\n\t\t}\n\t\tif (errorFile != null) {\n\t\t\terrorStream = new PrintStream(errorFile);\n\t\t}\n\t\tif (mongoDbHost != null) {\n\t\t\tdb = new NanopubDb(mongoDbHost, mongoDbPort, mongoDbName, mongoDbUsername, mongoDbPassword);\n\t\t}\n\t\tFetchIndex fetchIndex = null;\n\t\tfor (String nanopubId : nanopubIds) {\n\t\t\tif (getIndex || getIndexContent) {\n\t\t\t\tif (db == null) {\n\t\t\t\t\tfetchIndex = new FetchIndex(nanopubId, outputStream, rdfFormat, getIndex, getIndexContent, localServer);\n\t\t\t\t} else {\n\t\t\t\t\tfetchIndex = new FetchIndexFromDb(nanopubId, db, outputStream, rdfFormat, getIndex, getIndexContent);\n\t\t\t\t}\n\t\t\t\tfetchIndex.setProgressListener(new FetchIndex.Listener() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void progress(int count) {\n\t\t\t\t\t\tSystem.err.print(count + \" nanopubs...\\r\");\n\t\t\t\t\t}\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void exceptionHappened(Exception ex, String serverUrl, String artifactCode) {\n\t\t\t\t\t\tif (showReport) {\n\t\t\t\t\t\t\texceptions.add(ex);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (errorStream != null) {\n\t\t\t\t\t\t\tString exString = ex.toString().replaceAll(\"\\\\n\", \"\\\\\\\\n\");\n\t\t\t\t\t\t\terrorStream.println(serverUrl + \" \" + artifactCode + \" \" + exString);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t});\n\t\t\t\tfetchIndex.run();\n\t\t\t\tcount = fetchIndex.getNanopubCount();\n\t\t\t} else {\n\t\t\t\tNanopub np;\n\t\t\t\tif (db == null) {\n\t\t\t\t\tnp = get(nanopubId);\n\t\t\t\t} else {\n\t\t\t\t\tnp = get(nanopubId, db);\n\t\t\t\t}\n\t\t\t\toutputNanopub(nanopubId, np);\n\t\t\t}\n\t\t}\n\t\tif (outputStream != System.out) {\n\t\t\toutputStream.close();\n\t\t\tSystem.err.println(count + \" nanopubs retrieved and saved in \" + outputFile);\n\t\t}\n\t\tif (errorStream != null) {\n\t\t\terrorStream.close();\n\t\t}\n\t\tif (showReport && fetchIndex != null) {\n\t\t\tSystem.err.println(\"Number of retries: \" + exceptions.size());\n\t\t\tSystem.err.println(\"Used servers:\");\n\t\t\tList<ServerInfo> usedServers = fetchIndex.getServers();\n\t\t\tfinal FetchIndex fi = fetchIndex;\n\t\t\tCollections.sort(usedServers, new Comparator<ServerInfo>() {\n\t\t\t\t@Override\n\t\t\t\tpublic int compare(ServerInfo o1, ServerInfo o2) {\n\t\t\t\t\treturn fi.getServerUsage(o2) - fi.getServerUsage(o1);\n\t\t\t\t}\n\t\t\t});\n\t\t\tint usedServerCount = 0;\n\t\t\tfor (ServerInfo si : usedServers) {\n\t\t\t\tif (fetchIndex.getServerUsage(si) > 0) usedServerCount++;\n\t\t\t\tSystem.err.format(\"%8d %s%n\", fetchIndex.getServerUsage(si), si.getPublicUrl());\n\t\t\t}\n\t\t\tSystem.err.format(\"Number of servers used: \" + usedServerCount);\n\t\t}\n\t}\n\n\tprivate void outputNanopub(String nanopubId, Nanopub np) throws IOException, RDFHandlerException {\n\t\tif (np == null) {\n\t\t\tSystem.err.println(\"NOT FOUND: \" + nanopubId);\n\t\t\treturn;\n\t\t}\n\t\tcount++;\n\t\tif (outputStream == System.out) {\n\t\t\tNanopubUtils.writeToStream(np, System.out, rdfFormat);\n\t\t\tSystem.out.print(\"\\n\\n\");\n\t\t} else {\n\t\t\tNanopubUtils.writeToStream(np, outputStream, rdfFormat);\n\t\t\tif (count % 100 == 0) {\n\t\t\t\tSystem.err.print(count + \" nanopubs...\\r\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static boolean wasSuccessful(HttpResponse resp) {\n\t\tint c = resp.getStatusLine().getStatusCode();\n\t\treturn c >= 200 && c < 300;\n\t}\n\n}",
"public class GetServerInfo {\n\n\[email protected](description = \"server-urls\", required = true)\n\tprivate List<String> serverUrls;\n\n\tpublic static void main(String[] args) {\n\t\tNanopubImpl.ensureLoaded();\n\t\tGetServerInfo obj = new GetServerInfo();\n\t\tJCommander jc = new JCommander(obj);\n\t\ttry {\n\t\t\tjc.parse(args);\n\t\t} catch (ParameterException ex) {\n\t\t\tjc.usage();\n\t\t\tSystem.exit(1);\n\t\t}\n\t\ttry {\n\t\t\tobj.run();\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tSystem.exit(1);\n\t\t}\n\t}\n\n\tprivate void run() throws ServerInfoException, IOException {\n\t\tfor (String url : serverUrls) {\n\t\t\tServerInfo si = ServerInfo.load(url);\n\t\t\tSystem.out.println(\"Server URL: \" + si.getPublicUrl());\n\t\t\tSystem.out.println(\"Protocol version: \" + si.getProtocolVersion());\n\t\t\tSystem.out.println(\"Description: \" + si.getDescription());\n\t\t\tString ad = si.getAdmin();\n\t\t\tSystem.out.println(\"Admin: \" + (ad == null || ad.isEmpty() ? \"(unknown)\" : ad));\n\t\t\tSystem.out.println(\"Journal ID: \" + si.getJournalId());\n\t\t\tSystem.out.println(\"Page size: \" + si.getPageSize());\n\t\t\tSystem.out.println(\"Post peers: \" + (si.isPostPeersEnabled() ? \"enabled\" : \"disabled\"));\n\t\t\tSystem.out.println(\"Post nanopubs: \" + (si.isPostNanopubsEnabled() ? \"enabled\" : \"disabled\"));\n\t\t\tSystem.out.println(\"Nanopub count: \" + (si.getNextNanopubNo()-1));\n\t\t\tSystem.out.println(\"Max nanopubs: \" + (si.getMaxNanopubs() == null ? \"unrestricted\" : si.getMaxNanopubs()));\n\t\t\tSystem.out.println(\"Max triples/nanopub: \" + (si.getMaxNanopubTriples() == null ? \"unrestricted\" : si.getMaxNanopubTriples()));\n\t\t\tSystem.out.println(\"Max bytes/nanopub: \" + (si.getMaxNanopubBytes() == null ? \"unrestricted\" : si.getMaxNanopubBytes()));\n\t\t\tSystem.out.println(\"URI pattern: \" + (si.getUriPattern() == null ? \"(everything)\" : si.getUriPattern()));\n\t\t\tSystem.out.println(\"Hash pattern: \" + (si.getHashPattern() == null ? \"(everything)\" : si.getHashPattern()));\n\t\t\tSystem.out.println();\n\t\t}\n\t}\n\n}",
"public class NanopubStatus {\n\n\[email protected](description = \"nanopub-uri-or-artifact-code\", required = true)\n\tprivate List<String> nanopubIds;\n\n\[email protected](names = \"-v\", description = \"Verbose\")\n\tprivate boolean verbose = false;\n\n\[email protected](names = \"-r\", description = \"Recursive (check entire content of index)\")\n\tprivate boolean recursive = false;\n\n\[email protected](names = \"-a\", description = \"Check all servers (do not stop after the first successful one)\")\n\tprivate boolean checkAllServers = false;\n\n\tpublic static void main(String[] args) {\n\t\tNanopubImpl.ensureLoaded();\n\t\tNanopubStatus obj = new NanopubStatus();\n\t\tJCommander jc = new JCommander(obj);\n\t\ttry {\n\t\t\tjc.parse(args);\n\t\t} catch (ParameterException ex) {\n\t\t\tjc.usage();\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tif (obj.nanopubIds.size() != 1) {\n\t\t\tSystem.err.println(\"ERROR: Exactly one main argument needed\");\n\t\t\tjc.usage();\n\t\t\tSystem.exit(1);\n\t\t}\n\t\ttry {\n\t\t\tobj.run();\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tSystem.exit(1);\n\t\t}\n\t}\n\n\tprivate static String getArtifactCode(String uriOrArtifactCode) {\n\t\tif (uriOrArtifactCode.indexOf(\":\") > 0) {\n\t\t\tIRI uri = SimpleValueFactory.getInstance().createIRI(uriOrArtifactCode);\n\t\t\tif (!TrustyUriUtils.isPotentialTrustyUri(uri)) {\n\t\t\t\tthrow new IllegalArgumentException(\"Not a well-formed trusty URI\");\n\t\t\t}\n\t\t\treturn TrustyUriUtils.getArtifactCode(uri.toString());\n\t\t} else {\n\t\t\tif (!TrustyUriUtils.isPotentialArtifactCode(uriOrArtifactCode)) {\n\t\t\t\tthrow new IllegalArgumentException(\"Not a well-formed artifact code\");\n\t\t\t}\n\t\t\treturn uriOrArtifactCode;\n\t\t}\n\t}\n\n\tprivate int contentNpCount, indexNpCount;\n\tprivate int minCount = -1;\n\n\tpublic NanopubStatus() {\n\t}\n\n\tprivate void run() throws IOException, RDFHandlerException {\n\t\tcheckNanopub(nanopubIds.get(0), recursive);\n\t\tif (recursive) {\n\t\t\tSystem.out.print(indexNpCount + \" index nanopub\" + (indexNpCount!=1?\"s\":\"\") + \"; \");\n\t\t\tSystem.out.println(contentNpCount + \" content nanopub\" + (contentNpCount!=1?\"s\":\"\"));\n\t\t\tif (checkAllServers) {\n\t\t\t\tSystem.out.println(\"Each found on at least \" + minCount + \" nanopub server\" + (minCount!=1?\"s\":\"\") + \".\");\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void checkNanopub(String nanopubId, boolean checkIndexContent) {\n\t\tString ac = getArtifactCode(nanopubId);\n\t\tif (!ac.startsWith(RdfModule.MODULE_ID)) {\n\t\t\tSystem.err.println(\"ERROR. Not a trusty URI of type RA: \" + nanopubId);\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tint count = 0;\n\t\tServerIterator serverIterator = new ServerIterator();\n\t\tNanopub nanopub = null;\n\t\twhile (serverIterator.hasNext()) {\n\t\t\tServerInfo serverInfo = serverIterator.next();\n\t\t\tString serverUrl = serverInfo.getPublicUrl();\n\t\t\ttry {\n\t\t\t\tNanopub np = GetNanopub.get(ac, serverUrl);\n\t\t\t\tif (np != null) {\n\t\t\t\t\tif (checkIndexContent && !IndexUtils.isIndex(np)) {\n\t\t\t\t\t\tSystem.err.println(\"ERROR. Not an index: \" + nanopubId);\n\t\t\t\t\t\tSystem.exit(1);\n\t\t\t\t\t}\n\t\t\t\t\tif (nanopub == null) nanopub = np;\n\t\t\t\t\tif (!recursive || verbose) {\n\t\t\t\t\t\tSystem.out.println(\"URL: \" + serverUrl + ac);\n\t\t\t\t\t}\n\t\t\t\t\tif (checkAllServers) {\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (FileNotFoundException ex) {\n\t\t\t\tif (verbose && !recursive) {\n\t\t\t\t\tSystem.out.println(\"NOT FOUND ON: \" + serverUrl);\n\t\t\t\t}\n\t\t\t} catch (IOException ex) {\n\t\t\t\tif (verbose && !recursive) {\n\t\t\t\t\tSystem.out.println(\"CONNECTION ERROR: \" + serverUrl);\n\t\t\t\t}\n\t\t\t} catch (RDF4JException ex) {\n\t\t\t\tif (verbose && !recursive) {\n\t\t\t\t\tSystem.out.println(\"VALIDATION ERROR: \" + serverUrl);\n\t\t\t\t}\n\t\t\t} catch (MalformedNanopubException ex) {\n\t\t\t\tif (verbose && !recursive) {\n\t\t\t\t\tSystem.out.println(\"VALIDATION ERROR: \" + serverUrl);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (checkAllServers) {\n\t\t\tString text = \"Found on \" + count + \" nanopub server\" + (count!=1?\"s\":\"\");\n\t\t\tif (!recursive) {\n\t\t\t\tSystem.out.println(text + \".\");\n\t\t\t} else if (verbose) {\n\t\t\t\tSystem.out.println(text + \": \" + ac);\n\t\t\t}\n\t\t\tif (minCount < 0 || minCount > count) {\n\t\t\t\tminCount = count;\n\t\t\t}\n\t\t}\n\t\tif (nanopub != null) {\n\t\t\tif (checkIndexContent) {\n\t\t\t\tindexNpCount++;\n\t\t\t\tNanopubIndex npi = null;\n\t\t\t\ttry {\n\t\t\t\t\tnpi = IndexUtils.castToIndex(nanopub);\n\t\t\t\t} catch (MalformedNanopubException ex) {\n\t\t\t\t\tex.printStackTrace();\n\t\t\t\t\tSystem.exit(1);\n\t\t\t\t}\n\t\t\t\tfor (IRI elementUri : npi.getElements()) {\n\t\t\t\t\tcheckNanopub(elementUri.toString(), false);\n\t\t\t\t}\n\t\t\t\tfor (IRI subIndexUri : npi.getSubIndexes()) {\n\t\t\t\t\tcheckNanopub(subIndexUri.toString(), true);\n\t\t\t\t}\n\t\t\t\tif (npi.getAppendedIndex() != null) {\n\t\t\t\t\tcheckNanopub(npi.getAppendedIndex().toString(), true);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcontentNpCount++;\n\t\t\t}\n\t\t}\n\t\tif ((indexNpCount+contentNpCount) % 100 == 0) {\n\t\t\tSystem.err.print((indexNpCount+contentNpCount) + \" nanopubs...\\r\");\n\t\t}\n\t}\n\n}",
"public class PublishNanopub {\n\n\[email protected](description = \"nanopubs\", required = true)\n\tprivate List<String> nanopubs = new ArrayList<String>();\n\n\[email protected](names = \"-v\", description = \"Verbose\")\n\tprivate boolean verbose = false;\n\n\[email protected](names = \"-u\", description = \"Use the given nanopub server URLs\")\n\tprivate List<String> serverUrls;\n\n\[email protected](names = \"-s\", description = \"Get nanopubs to be published from given SPARQL endpoint\")\n\tprivate String sparqlEndpointUrl;\n\n\tpublic static void main(String[] args) {\n\t\tNanopubImpl.ensureLoaded();\n\t\tPublishNanopub obj = new PublishNanopub();\n\t\tJCommander jc = new JCommander(obj);\n\t\ttry {\n\t\t\tjc.parse(args);\n\t\t} catch (ParameterException ex) {\n\t\t\tjc.usage();\n\t\t\tSystem.exit(1);\n\t\t}\n\t\ttry {\n\t\t\tobj.run();\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tSystem.exit(1);\n\t\t}\n\t}\n\n\tpublic static void publish(Nanopub nanopub) throws IOException {\n\t\tnew PublishNanopub().publishNanopub(nanopub);\n\t}\n\n\tprivate ServerIterator serverIterator = null;\n\tprivate ServerInfo serverInfo = null;\n\tprivate Map<String,Integer> usedServers = new HashMap<>();\n\tprivate int count;\n\tprivate boolean failed;\n\tprivate SPARQLRepository sparqlRepo;\n\tprivate String artifactCode;\n\n\tpublic PublishNanopub() {\n\t}\n\n\tprivate void run() throws IOException {\n\t\tfailed = false;\n\t\tfor (String s : nanopubs) {\n\t\t\tcount = 0;\n\t\t\ttry {\n\t\t\t\tif (sparqlEndpointUrl != null) {\n\t\t\t\t\tif (sparqlRepo == null) {\n\t\t\t\t\t\tsparqlRepo = new SPARQLRepository(sparqlEndpointUrl);\n\t\t\t\t\t\tsparqlRepo.initialize();\n\t\t\t\t\t}\n\t\t\t\t\tprocessNanopub(new NanopubImpl(sparqlRepo, SimpleValueFactory.getInstance().createIRI(s)));\n\t\t\t\t} else {\n\t\t\t\t\tif (verbose) {\n\t\t\t\t\t\tSystem.out.println(\"Reading file: \" + s);\n\t\t\t\t\t}\n\t\t\t\t\tMultiNanopubRdfHandler.process(new File(s), new NanopubHandler() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void handleNanopub(Nanopub np) {\n\t\t\t\t\t\t\tif (failed) return;\n\t\t\t\t\t\t\tprocessNanopub(np);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tif (count == 0) {\n\t\t\t\t\t\tSystem.out.println(\"NO NANOPUB FOUND: \" + s);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (RDF4JException ex) {\n\t\t\t\tSystem.out.println(\"RDF ERROR: \" + s);\n\t\t\t\tex.printStackTrace(System.err);\n\t\t\t\tbreak;\n\t\t\t} catch (MalformedNanopubException ex) {\n\t\t\t\tSystem.out.println(\"INVALID NANOPUB: \" + s);\n\t\t\t\tex.printStackTrace(System.err);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (failed) {\n\t\t\t\tSystem.out.println(\"FAILED TO PUBLISH NANOPUBS\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tfor (String s : usedServers.keySet()) {\n\t\t\tint c = usedServers.get(s);\n\t\t\tSystem.out.println(c + \" nanopub\" + (c==1?\"\":\"s\") + \" published at \" + s);\n\t\t}\n\t\tif (sparqlRepo != null) {\n\t\t\ttry {\n\t\t\t\tsparqlRepo.shutDown();\n\t\t\t} catch (RepositoryException ex) {\n\t\t\t\tex.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void processNanopub(Nanopub nanopub) {\n\t\tcount++;\n\t\tif (count % 100 == 0) {\n\t\t\tSystem.err.print(count + \" nanopubs...\\r\");\n\t\t}\n\t\ttry {\n\t\t\tpublishNanopub(nanopub);\n\t\t} catch (IOException ex) {\n\t\t\tif (verbose) {\n\t\t\t\tSystem.err.println(ex.getClass().getName() + \": \" + ex.getMessage());\n\t\t\t\tSystem.err.println(\"---\");\n\t\t\t}\n\t\t\tfailed = true;\n\t\t}\n\t}\n\n\tpublic void publishNanopub(Nanopub nanopub) throws IOException {\n\t\tif (serverInfo == null) {\n\t\t\tif (serverUrls == null || serverUrls.isEmpty()) {\n\t\t\t\tserverIterator = new ServerIterator();\n\t\t\t} else {\n\t\t\t\tserverIterator = new ServerIterator(serverUrls);\n\t\t\t}\n\t\t\tserverInfo = serverIterator.next();\n\t\t}\n\t\tartifactCode = TrustyUriUtils.getArtifactCode(nanopub.getUri().toString());\n\t\tif (verbose) {\n\t\t\tSystem.out.println(\"---\");\n\t\t\tSystem.out.println(\"Trying to publish nanopub: \" + artifactCode);\n\t\t}\n\t\tif (NanopubServerUtils.isProtectedNanopub(nanopub)) {\n\t\t\tthrow new RuntimeException(\"Can't publish protected nanopublication: \" + artifactCode);\n\t\t}\n\t\twhile (serverInfo != null) {\n\t\t\tString serverUrl = serverInfo.getPublicUrl();\n\t\t\tif (!serverInfo.isPostNanopubsEnabled()) {\n\t\t\t\tserverInfo = serverIterator.next();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!serverInfo.getNanopubSurfacePattern().matchesUri(nanopub.getUri().stringValue())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (verbose) {\n\t\t\t\tSystem.out.println(\"Trying server: \" + serverUrl);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tHttpPost post = new HttpPost(serverUrl);\n\t\t\t\tString nanopubString = NanopubUtils.writeToString(nanopub, RDFFormat.TRIG);\n\t\t\t\tpost.setEntity(new StringEntity(nanopubString, \"UTF-8\"));\n\t\t\t\tpost.setHeader(\"Content-Type\", RDFFormat.TRIG.getDefaultMIMEType());\n\t\t\t\tRequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();\n\t\t\t\tHttpResponse response = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build().execute(post);\n\t\t\t\tint code = response.getStatusLine().getStatusCode();\n\t\t\t\tif (code >= 200 && code < 300) {\n\t\t\t\t\tif (usedServers.containsKey(serverUrl)) {\n\t\t\t\t\t\tusedServers.put(serverUrl, usedServers.get(serverUrl) + 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tusedServers.put(serverUrl, 1);\n\t\t\t\t\t}\n\t\t\t\t\tif (verbose) {\n\t\t\t\t\t\tSystem.out.println(\"Published: \" + artifactCode);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tif (verbose) {\n\t\t\t\t\t\tSystem.out.println(\"Response: \" + code + \" \" + response.getStatusLine().getReasonPhrase());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (IOException ex) {\n\t\t\t\tif (verbose) {\n\t\t\t\t\tSystem.out.println(ex.getClass().getName() + \": \" + ex.getMessage());\n\t\t\t\t}\n\t\t\t} catch (RDF4JException ex) {\n\t\t\t\tif (verbose) {\n\t\t\t\t\tSystem.out.println(ex.getClass().getName() + \": \" + ex.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t\tserverInfo = serverIterator.next();\n\t\t}\n\t\tserverInfo = null;\n\t\tthrow new RuntimeException(\"Failed to publish the nanopub\");\n\t}\n\n\tpublic ServerInfo getUsedServer() {\n\t\treturn serverInfo;\n\t}\n\n\tpublic String getPublishedNanopubUrl() {\n\t\tif (serverInfo == null || artifactCode == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn serverInfo.getPublicUrl() + artifactCode;\n\t}\n\n}",
"public class FixTrustyNanopub {\n\n\[email protected](description = \"input-nanopubs\", required = true)\n\tprivate List<File> inputNanopubs = new ArrayList<File>();\n\n\[email protected](names = \"-v\", description = \"Verbose\")\n\tprivate boolean verbose = false;\n\n\tpublic static void main(String[] args) {\n\t\tNanopubImpl.ensureLoaded();\n\t\tFixTrustyNanopub obj = new FixTrustyNanopub();\n\t\tJCommander jc = new JCommander(obj);\n\t\ttry {\n\t\t\tjc.parse(args);\n\t\t} catch (ParameterException ex) {\n\t\t\tjc.usage();\n\t\t\tSystem.exit(1);\n\t\t}\n\t\ttry {\n\t\t\tobj.run();\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tSystem.exit(1);\n\t\t}\n\t}\n\n\tprivate int count;\n\n\tprivate void run() throws IOException, RDFParseException, RDFHandlerException,\n\t\t\tMalformedNanopubException, TrustyUriException {\n\t\tfor (File inputFile : inputNanopubs) {\n\t\t\tFile outFile = new File(inputFile.getParent(), \"fixed.\" + inputFile.getName());\n\t\t\tfinal OutputStream out;\n\t\t\tif (inputFile.getName().matches(\".*\\\\.(gz|gzip)\")) {\n\t\t\t\tout = new GZIPOutputStream(new FileOutputStream(outFile));\n\t\t\t} else {\n\t\t\t\tout = new FileOutputStream(outFile);\n\t\t\t}\n\t\t\tfinal RDFFormat format = new TrustyUriResource(inputFile).getFormat(RDFFormat.TRIG);\n\t\t\tMultiNanopubRdfHandler.process(format, inputFile, new NanopubHandler() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void handleNanopub(Nanopub np) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnp = writeAsFixedNanopub(np, format, out);\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t\tif (verbose) {\n\t\t\t\t\t\t\tSystem.out.println(\"Nanopub URI: \" + np.getUri());\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (count % 100 == 0) {\n\t\t\t\t\t\t\t\tSystem.err.print(count + \" nanopubs...\\r\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (RDFHandlerException ex) {\n\t\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t\t} catch (TrustyUriException ex) {\n\t\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t});\n\t\t\tout.close();\n\t\t}\n\t}\n\n\tpublic static Nanopub fix(Nanopub nanopub) throws TrustyUriException {\n\t\tNanopub np;\n\t\tif (nanopub instanceof NanopubWithNs) {\n\t\t\t((NanopubWithNs) nanopub).removeUnusedPrefixes();\n\t\t}\n\t\ttry {\n\t\t\tRdfFileContent r = new RdfFileContent(RDFFormat.TRIG);\n\t\t\tNanopubUtils.propagateToHandler(nanopub, r);\n\t\t\tNanopubRdfHandler h = new NanopubRdfHandler();\n\t\t\tif (!TrustyUriUtils.isPotentialTrustyUri(nanopub.getUri())) {\n\t\t\t\tthrow new TrustyUriException(\"Not a (broken) trusty URI: \" + nanopub.getUri());\n\t\t\t}\n\t\t\tString oldArtifactCode = TrustyUriUtils.getArtifactCode(nanopub.getUri().toString());\n\t\t\tRdfUtils.fixTrustyRdf(r, oldArtifactCode, h);\n\t\t\tnp = h.getNanopub();\n\t\t} catch (RDFHandlerException ex) {\n\t\t\tthrow new TrustyUriException(ex);\n\t\t} catch (MalformedNanopubException ex) {\n\t\t\tthrow new TrustyUriException(ex);\n\t\t}\n\t\treturn np;\n\t}\n\n\tpublic static void transformMultiNanopub(final RDFFormat format, File file, final OutputStream out)\n\t\t\tthrows IOException, RDFParseException, RDFHandlerException, MalformedNanopubException {\n\t\tInputStream in = new FileInputStream(file);\n\t\ttransformMultiNanopub(format, in, out);\n\t}\n\n\tpublic static void transformMultiNanopub(final RDFFormat format, InputStream in, final OutputStream out)\n\t\t\tthrows IOException, RDFParseException, RDFHandlerException, MalformedNanopubException {\n\t\tMultiNanopubRdfHandler.process(format, in, new NanopubHandler() {\n\n\t\t\t@Override\n\t\t\tpublic void handleNanopub(Nanopub np) {\n\t\t\t\ttry {\n\t\t\t\t\twriteAsFixedNanopub(np, format, out);\n\t\t\t\t} catch (RDFHandlerException ex) {\n\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t} catch (TrustyUriException ex) {\n\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t}\n\t\t\t}\n\n\t\t});\n\t\tout.close();\n\t}\n\n\tpublic static Nanopub writeAsFixedNanopub(Nanopub np, RDFFormat format, OutputStream out)\n\t\t\tthrows RDFHandlerException, TrustyUriException {\n\t\tnp = FixTrustyNanopub.fix(np);\n\t\tRDFWriter w = Rio.createWriter(format, new OutputStreamWriter(out, Charset.forName(\"UTF-8\")));\n\t\tNanopubUtils.propagateToHandler(np, w);\n\t\treturn np;\n\t}\n\n}",
"public class MakeTrustyNanopub {\n\n\[email protected](description = \"input-nanopub-files\", required = true)\n\tprivate List<File> inputNanopubsFiles = new ArrayList<File>();\n\n\[email protected](names = \"-o\", description = \"Output file\")\n\tprivate File singleOutputFile;\n\n\[email protected](names = \"-r\", description = \"Resolve cross-nanopub references\")\n\tprivate boolean resolveCrossRefs = false;\n\n\[email protected](names = \"-R\", description = \"Resolve cross-nanopub references based on prefixes\")\n\tprivate boolean resolveCrossRefsPrefixBased = false;\n\n\[email protected](names = \"-v\", description = \"Verbose\")\n\tprivate boolean verbose = false;\n\n\tpublic static void main(String[] args) {\n\t\tNanopubImpl.ensureLoaded();\n\t\tMakeTrustyNanopub obj = new MakeTrustyNanopub();\n\t\tJCommander jc = new JCommander(obj);\n\t\ttry {\n\t\t\tjc.parse(args);\n\t\t} catch (ParameterException ex) {\n\t\t\tjc.usage();\n\t\t\tSystem.exit(1);\n\t\t}\n\t\ttry {\n\t\t\tobj.run();\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tSystem.exit(1);\n\t\t}\n\t}\n\n\tprivate void run() throws IOException, RDFParseException, RDFHandlerException,\n\t\t\tMalformedNanopubException, TrustyUriException {\n\t\tfinal Map<Resource,IRI> tempRefMap;\n\t\tfinal Map<String,String> tempPrefixMap;\n\t\tif (resolveCrossRefsPrefixBased) {\n\t\t\ttempPrefixMap = new HashMap<>();\n\t\t\ttempRefMap = new HashMap<>();\n\t\t} else if (resolveCrossRefs) {\n\t\t\ttempPrefixMap = null;\n\t\t\ttempRefMap = new HashMap<>();\n\t\t} else {\n\t\t\ttempPrefixMap = null;\n\t\t\ttempRefMap = null;\n\t\t}\n\t\tfinal OutputStream singleOut;\n\t\tif (singleOutputFile != null) {\n\t\t\tif (singleOutputFile.getName().matches(\".*\\\\.(gz|gzip)\")) {\n\t\t\t\tsingleOut = new GZIPOutputStream(new FileOutputStream(singleOutputFile));\n\t\t\t} else {\n\t\t\t\tsingleOut = new FileOutputStream(singleOutputFile);\n\t\t\t}\n\t\t} else {\n\t\t\tsingleOut = null;\n\t\t}\n\t\tfor (File inputFile : inputNanopubsFiles) {\n\t\t\tFile outputFile;\n\t\t\tfinal OutputStream out;\n\t\t\tif (singleOutputFile == null) {\n\t\t\t\toutputFile = new File(inputFile.getParent(), \"trusty.\" + inputFile.getName());\n\t\t\t\tif (inputFile.getName().matches(\".*\\\\.(gz|gzip)\")) {\n\t\t\t\t\tout = new GZIPOutputStream(new FileOutputStream(outputFile));\n\t\t\t\t} else {\n\t\t\t\t\tout = new FileOutputStream(outputFile);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toutputFile = singleOutputFile;\n\t\t\t\tout = singleOut;\n\t\t\t}\n\t\t\tfinal RDFFormat inFormat = new TrustyUriResource(inputFile).getFormat(RDFFormat.TRIG);\n\t\t\tfinal RDFFormat outFormat = new TrustyUriResource(outputFile).getFormat(RDFFormat.TRIG);\n\t\t\tMultiNanopubRdfHandler.process(inFormat, inputFile, new NanopubHandler() {\n\t\n\t\t\t\t@Override\n\t\t\t\tpublic void handleNanopub(Nanopub np) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnp = writeAsTrustyNanopub(np, outFormat, out, tempRefMap, tempPrefixMap);\n\t\t\t\t\t\tif (verbose) {\n\t\t\t\t\t\t\tSystem.out.println(\"Nanopub URI: \" + np.getUri());\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (RDFHandlerException | TrustyUriException ex) {\n\t\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\n\t\t\t});\n\t\t\tif (singleOutputFile == null) {\n\t\t\t\tout.close();\n\t\t\t}\n\t\t}\n\t\tif (singleOutputFile != null) {\n\t\t\tsingleOut.close();\n\t\t}\n\t}\n\n\tpublic static Nanopub transform(Nanopub nanopub) throws TrustyUriException {\n\t\treturn transform(nanopub, null, null);\n\t}\n\n\tpublic static Nanopub transform(Nanopub nanopub, Map<Resource,IRI> tempRefMap, Map<String,String> tempPrefixMap) throws TrustyUriException {\n\t\tString u = nanopub.getUri().stringValue();\n\t\tif (!nanopub.getHeadUri().stringValue().startsWith(u) ||\n\t\t\t\t!nanopub.getAssertionUri().stringValue().startsWith(u) ||\n\t\t\t\t!nanopub.getProvenanceUri().stringValue().startsWith(u) ||\n\t\t\t\t!nanopub.getPubinfoUri().stringValue().startsWith(u)) {\n\t\t\tthrow new TrustyUriException(\"Graph URIs need have the nanopub URI as prefix: \" + u + \"...\");\n\t\t}\n\t\tNanopub np;\n\t\ttry {\n\t\t\tRdfFileContent r = new RdfFileContent(RDFFormat.TRIG);\n\t\t\tString npUri;\n\t\t\tMap<Resource,IRI> tempUriReplacerMap = null;\n\t\t\tif (TempUriReplacer.hasTempUri(nanopub)) {\n\t\t\t\tnpUri = TempUriReplacer.normUri;\n\t\t\t\ttempUriReplacerMap = new HashMap<>();\n\t\t\t\tNanopubUtils.propagateToHandler(nanopub, new TempUriReplacer(nanopub, r, tempUriReplacerMap));\n\t\t\t} else {\n\t\t\t\tnpUri = nanopub.getUri().toString();\n\t\t\t\tNanopubUtils.propagateToHandler(nanopub, r);\n\t\t\t}\n\t\t\tif (tempRefMap != null || tempPrefixMap != null) {\n\t\t\t\tif (tempRefMap == null) {\n\t\t\t\t\ttempRefMap = new HashMap<>();\n\t\t\t\t}\n\t\t\t\tmergeTransformMaps(tempRefMap, tempUriReplacerMap);\n\t\t\t\tRdfFileContent r2 = new RdfFileContent(RDFFormat.TRIG);\n\t\t\t\tr.propagate(new CrossRefResolver(tempRefMap, tempPrefixMap, r2));\n\t\t\t\tr = r2;\n\t\t\t}\n\t\t\tNanopubRdfHandler h = new NanopubRdfHandler();\n\t\t\tMap<Resource,IRI> transformMap = TransformRdf.transformAndGetMap(r, h, npUri);\n\t\t\tnp = h.getNanopub();\n\t\t\tmergeTransformMaps(tempRefMap, transformMap);\n\t\t\tmergePrefixTransformMaps(tempPrefixMap, transformMap);\n\t\t} catch (RDFHandlerException ex) {\n\t\t\tthrow new TrustyUriException(ex);\n\t\t} catch (MalformedNanopubException ex) {\n\t\t\tthrow new TrustyUriException(ex);\n\t\t}\n\t\tif (np instanceof NanopubWithNs) {\n\t\t\t((NanopubWithNs) np).removeUnusedPrefixes();\n\t\t}\n\t\treturn np;\n\t}\n\n\tpublic static void transformMultiNanopub(final RDFFormat format, File file, final OutputStream out)\n\t\t\tthrows IOException, RDFParseException, RDFHandlerException, MalformedNanopubException {\n\t\ttransformMultiNanopub(format, file, out, false);\n\t}\n\n\tpublic static void transformMultiNanopub(final RDFFormat format, File file, final OutputStream out, boolean resolveCrossRefs)\n\t\t\tthrows IOException, RDFParseException, RDFHandlerException, MalformedNanopubException {\n\t\tInputStream in = new FileInputStream(file);\n\t\ttransformMultiNanopub(format, in, out, resolveCrossRefs);\n\t}\n\n\tpublic static void transformMultiNanopub(final RDFFormat format, InputStream in, final OutputStream out)\n\t\t\tthrows IOException, RDFParseException, RDFHandlerException, MalformedNanopubException {\n\t\ttransformMultiNanopub(format, in, out, false);\n\t}\n\n\tpublic static void transformMultiNanopub(final RDFFormat format, InputStream in, final OutputStream out, boolean resolveCrossRefs)\n\t\t\tthrows IOException, RDFParseException, RDFHandlerException, MalformedNanopubException {\n\t\tfinal Map<Resource,IRI> tempRefMap;\n\t\tif (resolveCrossRefs) {\n\t\t\ttempRefMap = new HashMap<>();\n\t\t} else {\n\t\t\ttempRefMap = null;\n\t\t}\n\t\tMultiNanopubRdfHandler.process(format, in, new NanopubHandler() {\n\n\t\t\t@Override\n\t\t\tpublic void handleNanopub(Nanopub np) {\n\t\t\t\ttry {\n\t\t\t\t\t// TODO temporary URI ref resolution not yet supported here\n\t\t\t\t\t// TODO prefix-based cross-ref resolution also not yet supported\n\t\t\t\t\twriteAsTrustyNanopub(np, format, out, tempRefMap, null);\n\t\t\t\t} catch (RDFHandlerException ex) {\n\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t} catch (TrustyUriException ex) {\n\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t}\n\t\t\t}\n\n\t\t});\n\t\tout.close();\n\t}\n\n\tpublic static Nanopub writeAsTrustyNanopub(Nanopub np, RDFFormat format, OutputStream out, Map<Resource,IRI> tempRefMap, Map<String,String> tempPrefixMap)\n\t\t\tthrows RDFHandlerException, TrustyUriException {\n\t\tnp = MakeTrustyNanopub.transform(np, tempRefMap, tempPrefixMap);\n\t\tRDFWriter w = Rio.createWriter(format, new OutputStreamWriter(out, Charset.forName(\"UTF-8\")));\n\t\tNanopubUtils.propagateToHandler(np, w);\n\t\treturn np;\n\t}\n\n\tstatic void mergeTransformMaps(Map<Resource,IRI> mainMap, Map<Resource,IRI> mapToMerge) {\n\t\tif (mainMap == null || mapToMerge == null) return;\n\t\tfor (Resource r : new HashSet<>(mainMap.keySet())) {\n\t\t\tIRI v = mainMap.get(r);\n\t\t\tif (mapToMerge.containsKey(v)) {\n\t\t\t\tmainMap.put(r, mapToMerge.get(v));\n\t\t\t\tmapToMerge.remove(v);\n\t\t\t}\n\t\t}\n\t\tfor (Resource r : mapToMerge.keySet()) {\n\t\t\tmainMap.put(r, mapToMerge.get(r));\n\t\t}\n\t}\n\n\tstatic void mergePrefixTransformMaps(Map<String,String> mainPrefixMap, Map<Resource,IRI> mapToMerge) {\n\t\tif (mainPrefixMap == null || mapToMerge == null) return;\n\t\tfor (Resource r : mapToMerge.keySet()) {\n\t\t\tif (r instanceof IRI && TrustyUriUtils.isPotentialTrustyUri(mapToMerge.get(r).stringValue())) {\n\t\t\t\tmainPrefixMap.put(r.stringValue(), mapToMerge.get(r).stringValue());\n\t\t\t}\n\t\t}\n\t}\n\n}"
] | import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.rdf4j.RDF4JException;
import org.nanopub.extra.index.MakeIndex;
import org.nanopub.extra.security.MakeKeys;
import org.nanopub.extra.security.SignNanopub;
import org.nanopub.extra.server.GetNanopub;
import org.nanopub.extra.server.GetServerInfo;
import org.nanopub.extra.server.NanopubStatus;
import org.nanopub.extra.server.PublishNanopub;
import org.nanopub.trusty.FixTrustyNanopub;
import org.nanopub.trusty.MakeTrustyNanopub; | package org.nanopub;
public class Run {
private Run() {} // no instances allowed
public static void main(String[] args) throws IOException, RDF4JException {
NanopubImpl.ensureLoaded();
run(args);
}
private static List<Class<?>> runnableClasses = new ArrayList<>();
private static Map<String,Class<?>> runnableClassesByName = new HashMap<>();
private static Map<String,Class<?>> runnableClassesByShortcut = new HashMap<>();
private static Map<Class<?>,String> runnableClassNames = new HashMap<>();
private static Map<Class<?>,String> runnableClassShortcuts = new HashMap<>();
private static void addRunnableClass(Class<?> c, String shortcut) {
runnableClasses.add(c);
runnableClassesByName.put(c.getSimpleName(), c);
runnableClassNames.put(c, c.getSimpleName());
if (shortcut != null) {
runnableClassesByShortcut.put(shortcut, c);
runnableClassShortcuts.put(c, shortcut);
}
}
static {
addRunnableClass(CheckNanopub.class, "check");
addRunnableClass(GetNanopub.class, "get");
addRunnableClass(PublishNanopub.class, "publish");
addRunnableClass(SignNanopub.class, "sign");
addRunnableClass(MakeTrustyNanopub.class, "mktrusty"); | addRunnableClass(FixTrustyNanopub.class, "fix"); | 7 |
engagingspaces/vertx-graphql-service-discovery | graphql-service-consumer/src/main/java/io/engagingspaces/graphql/servicediscovery/consumer/DiscoveryRegistrar.java | [
"public abstract class AbstractRegistrar<T extends Registration> implements Registrar {\n\n protected final Vertx vertx;\n private final Map<String, ManagedServiceDiscovery> serviceDiscoveries;\n private final Map<T, String> registrationMap;\n\n protected AbstractRegistrar(Vertx vertx) {\n this.vertx = vertx;\n this.serviceDiscoveries = new HashMap<>();\n this.registrationMap = new HashMap<>();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Vertx getVertx() {\n return vertx;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public List<String> serviceDiscoveryNames() {\n return Collections.unmodifiableList(new ArrayList<>(serviceDiscoveries.keySet()));\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ServiceDiscovery getDiscovery(String discoveryName) {\n if (serviceDiscoveryNames().contains(discoveryName)) {\n return serviceDiscoveries.get(discoveryName);\n }\n return null;\n }\n\n /**\n * Gets an existing managed repository, or creates it.\n *\n * @param options the service discovery options\n * @param closeHandler the action to perform when {@code discovery.close()} is called\n * @return the managed service discovery\n */\n protected ServiceDiscovery getOrCreateDiscovery(ServiceDiscoveryOptions options, Action<Void> closeHandler) {\n if (options.getName() == null) {\n options.setName(getNodeId(vertx));\n }\n String discoveryName = options.getName();\n if (serviceDiscoveries.containsKey(discoveryName)) {\n return serviceDiscoveries.get(discoveryName);\n }\n ServiceDiscovery discovery = ServiceDiscovery.create(vertx, options);\n if (closeHandler != null) {\n discovery = ManagedServiceDiscovery.of(discovery, closeHandler);\n serviceDiscoveries.put(discoveryName, (ManagedServiceDiscovery) discovery);\n }\n return discovery;\n }\n\n /**\n * Adds a new registration.\n *\n * @param discoveryName the name of the service discovery\n * @param registration the registration\n * @return the registration that was passed in\n */\n protected T register(String discoveryName, T registration) {\n registrationMap.put(registration, discoveryName);\n return registration;\n }\n\n /**\n * Unregisters the registration by removing it from the list of registrations.\n * <p>\n * If after un-registration the associated service discovery is no longer used, then it will also be closed.\n *\n * @param registration the schema registration\n */\n protected void unregister(T registration) {\n String discoveryName = registrationMap.get(registration);\n registrationMap.remove(registration);\n if (!registrationMap.containsValue(discoveryName)) {\n closeServiceDiscovery(discoveryName);\n }\n }\n\n /**\n * @return the current registrations of the registrar\n */\n protected List<T> registrations() {\n return new ArrayList<>(registrationMap.keySet());\n }\n\n /**\n * Closes the specified service discovery and unregisters event handlers.\n *\n * @param discoveryName the service discovery name\n */\n protected void closeServiceDiscovery(String discoveryName) {\n if (serviceDiscoveries.containsKey(discoveryName)) {\n ManagedServiceDiscovery.closeUnmanaged(serviceDiscoveries.remove(discoveryName));\n }\n }\n\n /**\n * Closes the registrar and release all its resources.\n */\n protected void close() {\n for (Map.Entry<String, ManagedServiceDiscovery> entry : serviceDiscoveries.entrySet()) {\n ManagedServiceDiscovery.closeUnmanaged(entry.getValue());\n }\n serviceDiscoveries.clear();\n registrationMap.clear();\n }\n\n private static String getNodeId(Vertx vertx) {\n if (vertx.isClustered()) {\n return ((VertxInternal) vertx).getNodeID();\n } else {\n return \"localhost\";\n }\n }\n}",
"public class AbstractRegistration implements Registration {\n\n private final ServiceDiscovery discovery;\n private final ServiceDiscoveryOptions options;\n\n protected AbstractRegistration(ServiceDiscovery discovery, ServiceDiscoveryOptions options) {\n Objects.requireNonNull(discovery, \"Service discovery cannot be null\");\n this.discovery = discovery;\n this.options = options;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ServiceDiscovery getDiscovery() {\n return discovery;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ServiceDiscoveryOptions getDiscoveryOptions() {\n return options == null ? null : new ServiceDiscoveryOptions(options);\n }\n\n /**\n * @param other the object to compare to this registration\n * @return {@code true} when equal, {@code false} otherwise\n */\n @Override\n public boolean equals(Object other) {\n if (other == this) {\n return true;\n }\n if (!(other instanceof AbstractRegistration)) {\n return false;\n }\n AbstractRegistration test = (AbstractRegistration) other;\n return fieldEquals(discovery, test.discovery) && fieldEquals(options.getName(), test.options.getName());\n }\n\n private static boolean fieldEquals(Object value1, Object value2) {\n return value1 == null ? value2 == null : value1.equals(value2);\n }\n\n /**\n * @return the hash code of the registration\n */\n @Override\n public int hashCode() {\n int result = 17;\n result = 31 * result + (discovery == null ? 0 : discovery.hashCode());\n result = 31 * result + (options.getName() == null ? 0 : options.getName().hashCode());\n return result;\n }\n}",
"@FunctionalInterface\npublic interface SchemaAnnounceHandler {\n\n /**\n * Event handler that handles service discovery `announce` events for GraphQL services.\n *\n * @param record the service record of the GraphQL service\n */\n void schemaDiscoveryEvent(Record record);\n}",
"@FunctionalInterface\npublic interface SchemaUsageHandler {\n\n /**\n * Event handler that handles service discovery `usage` events for GraphQL services that have been bound\n * or released.\n *\n * @param eventData the service reference state\n */\n void schemaReferenceEvent(SchemaReferenceData eventData);\n}",
"public class SchemaMessageConsumers {\n\n private final Vertx vertx;\n private final Map<String, MessageConsumer<JsonObject>> messageConsumers;\n private final List<String> consumerRegistrations;\n\n public SchemaMessageConsumers(Vertx vertx) {\n this.vertx = vertx;\n this.messageConsumers = new HashMap<>();\n this.consumerRegistrations = new ArrayList<>();\n }\n\n public void registerConsumer(String address, SchemaAnnounceHandler announceHandler) {\n registerConsumer(address, createAnnounceHandler(announceHandler));\n }\n\n public void registerConsumer(String address, SchemaUsageHandler usageHandler) {\n registerConsumer(address, createUsageHandler(usageHandler));\n }\n\n public <T extends Queryable> MessageConsumer<JsonObject> registerServiceConsumer(String address, T implementation) {\n MessageConsumer<JsonObject> serviceConsumer;\n if (!messageConsumers.containsKey(address)) {\n serviceConsumer = ProxyHelper.registerService(Queryable.class, vertx, implementation, address);\n messageConsumers.put(address, serviceConsumer);\n } else {\n serviceConsumer = messageConsumers.get(address);\n }\n consumerRegistrations.add(address);\n return serviceConsumer;\n }\n\n public void unregisterConsumer(String address) {\n consumerRegistrations.remove(address);\n messageConsumers.entrySet().stream()\n .filter(entry -> !consumerRegistrations.contains(address))\n .filter(entry -> entry.getKey().equals(address))\n .map(Map.Entry::getValue)\n .map(consumer -> {\n if (consumer.isRegistered()) {\n consumer.unregister();\n }\n return consumer;\n })\n .findFirst()\n .ifPresent(consumer -> messageConsumers.remove(consumer.address()));\n }\n\n public void close() {\n for (Iterator<Map.Entry<String,\n MessageConsumer<JsonObject>>> it = messageConsumers.entrySet().iterator(); it.hasNext();) {\n MessageConsumer consumer = it.next().getValue();\n if (consumer.isRegistered()) {\n consumer.unregister();\n }\n it.remove();\n }\n consumerRegistrations.clear();\n }\n\n /**\n * @return the message consumers that are registered\n */\n protected Map<String, MessageConsumer<JsonObject>> getConsumers() {\n return Collections.unmodifiableMap(messageConsumers);\n }\n\n private void registerConsumer(String address, Handler<Message<JsonObject>> handler) {\n if (!messageConsumers.containsKey(address) && handler != null) {\n messageConsumers.put(address, vertx.eventBus().consumer(address, handler));\n }\n consumerRegistrations.add(address);\n }\n\n private Handler<Message<JsonObject>> createAnnounceHandler(SchemaAnnounceHandler announceHandler) {\n return message -> {\n if (Queryable.SERVICE_TYPE.equals(message.body().getString(\"type\"))) {\n Record record = new Record(message.body());\n announceHandler.schemaDiscoveryEvent(record);\n }\n };\n }\n\n private Handler<Message<JsonObject>> createUsageHandler(SchemaUsageHandler usageHandler) {\n return message -> {\n if (Queryable.SERVICE_TYPE.equals(message.body().getJsonObject(\"record\").getString(\"type\"))) {\n SchemaReferenceData schemaReferenceData = new SchemaReferenceData(message.body());\n usageHandler.schemaReferenceEvent(schemaReferenceData);\n }\n };\n }\n}"
] | import io.engagingspaces.graphql.discovery.impl.AbstractRegistrar;
import io.engagingspaces.graphql.discovery.impl.AbstractRegistration;
import io.engagingspaces.graphql.events.SchemaAnnounceHandler;
import io.engagingspaces.graphql.events.SchemaUsageHandler;
import io.engagingspaces.graphql.events.impl.SchemaMessageConsumers;
import io.vertx.core.Vertx;
import io.vertx.servicediscovery.ServiceDiscovery;
import io.vertx.servicediscovery.ServiceDiscoveryOptions; | /*
* Copyright (c) 2016 The original author or authors
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.engagingspaces.graphql.servicediscovery.consumer;
/**
* Manages {@link ServiceDiscovery} creation, and registration of discovery events.
*
* @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a>
*/
public class DiscoveryRegistrar extends AbstractRegistrar<DiscoveryRegistration> {
private final SchemaMessageConsumers eventManager;
protected DiscoveryRegistrar(Vertx vertx) {
super(vertx);
this.eventManager = new SchemaMessageConsumers(vertx);
}
/**
* Creates a new discovery registrar instance for managing service discoveries and their event consumers.
*
* @param vertx the vert.x instance
* @return the discovery registrar
*/
public static DiscoveryRegistrar create(Vertx vertx) {
return new DiscoveryRegistrar(vertx);
}
/**
* Registers the provided event handlers to the `announce` and `usage` events of the service discovery
* specified in the service discovery options.
*
* @param options the service discovery options
* @param announceHandler the handler for `announce` events
* @param usageHandler the handler for `usage` events
* @return the discovery registration
*/
protected DiscoveryRegistration startListening( | ServiceDiscoveryOptions options, SchemaAnnounceHandler announceHandler, SchemaUsageHandler usageHandler) { | 3 |
startupheroes/startupheroes-checkstyle | startupheroes-checks/src/main/java/es/startuphero/checkstyle/checks/annotation/MissingOverrideCheck.java | [
"public static final String OVERRIDE_ANNOTATION_NAME_BY_PACKAGE = \"java.lang.Override\";",
"public static Boolean hasAnnotation(DetailAST ast, String fullAnnotation) {\n return CommonUtils.getSimpleAndFullNames(fullAnnotation).stream()\n .anyMatch(annotation -> AnnotationUtil.containsAnnotation(ast, annotation));\n}",
"public static String getClassName(DetailAST classAst) {\n DetailAST type = classAst.findFirstToken(TokenTypes.LITERAL_CLASS);\n return type.getNextSibling().getText();\n}",
"public static Optional<DetailAST> getClassOf(DetailAST anyAstBelowClass) {\n Optional<DetailAST> classAst = Optional.empty();\n for (DetailAST parent = anyAstBelowClass; parent != null; parent = parent.getParent()) {\n if (parent.getType() == TokenTypes.CLASS_DEF) {\n classAst = Optional.of(parent);\n break;\n }\n }\n return classAst;\n}",
"public static Map<String, String> getImportSimpleFullNameMap(DetailAST rootAst) {\n Map<String, String> simpleFullNameMapOfImports = new LinkedHashMap<>();\n for (DetailAST sibling = rootAst; sibling != null; sibling = sibling.getNextSibling()) {\n if (sibling.getType() == TokenTypes.IMPORT) {\n simpleFullNameMapOfImports.put(CommonUtils.getSimpleName(sibling),\n CommonUtils.getFullName(sibling));\n }\n }\n return simpleFullNameMapOfImports;\n}",
"public static String getPackageName(DetailAST ast) {\n String packageName = null;\n for (DetailAST parent = ast; parent != null; parent = parent.getParent()) {\n if (parent.getType() == TokenTypes.PACKAGE_DEF) {\n packageName = getFullName(parent);\n break;\n }\n }\n return packageName;\n}",
"public static String getMethodName(DetailAST methodAst) {\n DetailAST type = methodAst.findFirstToken(TokenTypes.TYPE);\n return type.getNextSibling().getText();\n}",
"public static Class<?>[] getParameterTypes(DetailAST methodAst,\n Map<String, String> importSimpleFullNameMap) {\n DetailAST parameters = methodAst.findFirstToken(TokenTypes.PARAMETERS);\n List<DetailAST> parameterNodes =\n CommonUtils.getChildsByType(parameters, TokenTypes.PARAMETER_DEF);\n List<Class<?>> parameterTypes = new ArrayList<>();\n for (DetailAST parameterNode : parameterNodes) {\n String paramTypeSimpleName = getParamTypeSimpleName(parameterNode);\n String paramTypeFullName =\n CommonUtils.getFullName(methodAst, importSimpleFullNameMap, paramTypeSimpleName);\n try {\n Class<?> parameterClass = Class.forName(paramTypeFullName);\n parameterTypes.add(parameterClass);\n } catch (ClassNotFoundException ignored) {\n }\n }\n return parameterTypes.stream().toArray(Class<?>[]::new);\n}",
"public static Boolean isMethodOverriden(Method method) {\n Class<?> declaringClass = method.getDeclaringClass();\n if (declaringClass.equals(Object.class)) {\n return false;\n }\n try {\n declaringClass.getSuperclass()\n .getDeclaredMethod(method.getName(), method.getParameterTypes());\n return true;\n } catch (NoSuchMethodException ex) {\n for (Class<?> implementedInterface : declaringClass.getInterfaces()) {\n try {\n implementedInterface.getDeclaredMethod(method.getName(), method.getParameterTypes());\n return true;\n } catch (NoSuchMethodException ignored) {\n }\n }\n return false;\n }\n}"
] | import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Optional;
import static es.startuphero.checkstyle.util.AnnotationUtils.OVERRIDE_ANNOTATION_NAME_BY_PACKAGE;
import static es.startuphero.checkstyle.util.AnnotationUtils.hasAnnotation;
import static es.startuphero.checkstyle.util.ClassUtils.getClassName;
import static es.startuphero.checkstyle.util.ClassUtils.getClassOf;
import static es.startuphero.checkstyle.util.ClassUtils.getImportSimpleFullNameMap;
import static es.startuphero.checkstyle.util.CommonUtils.getPackageName;
import static es.startuphero.checkstyle.util.MethodUtils.getMethodName;
import static es.startuphero.checkstyle.util.MethodUtils.getParameterTypes;
import static es.startuphero.checkstyle.util.MethodUtils.isMethodOverriden; | package es.startuphero.checkstyle.checks.annotation;
/**
* @author ozlem.ulag
*/
public class MissingOverrideCheck extends AbstractCheck {
/**
* A key is pointing to the warning message text in "messages.properties" file.
*/
private static final String MSG_KEY = "missing.override";
private String packageName;
private Map<String, String> importSimpleFullNameMap;
@Override
public int[] getDefaultTokens() {
return getAcceptableTokens();
}
@Override
public int[] getAcceptableTokens() {
return new int[] {TokenTypes.METHOD_DEF};
}
@Override
public int[] getRequiredTokens() {
return getAcceptableTokens();
}
@Override
public void beginTree(DetailAST rootAst) {
packageName = getPackageName(rootAst);
importSimpleFullNameMap = getImportSimpleFullNameMap(rootAst);
}
@Override
public void visitToken(DetailAST ast) {
try {
Optional<DetailAST> classNode = getClassOf(ast);
if (classNode.isPresent()) {
String className = getClassName(classNode.get());
String methodName = getMethodName(ast);
Class<?> classOfMethod = Class.forName(packageName + "." + className);
Method method = classOfMethod.getDeclaredMethod(methodName,
getParameterTypes(ast, importSimpleFullNameMap)); | if (isMethodOverriden(method) && !hasAnnotation(ast, OVERRIDE_ANNOTATION_NAME_BY_PACKAGE)) { | 0 |
cerner/beadledom | health/service/src/main/java/com/cerner/beadledom/health/HealthModule.java | [
"@Api(value = \"/health\",\n description = \"Health and dependency checks\")\[email protected](value = \"/health\",\n description = \"Health and dependency checks\")\n@Path(\"meta/availability\")\npublic interface AvailabilityResource {\n @GET\n @Produces(MediaType.TEXT_HTML)\n StreamingOutput getBasicAvailabilityCheckHtml();\n\n @ApiOperation(value = \"Basic Availability Check\",\n notes = \"Always returns 200. The JSON will only include the message field.\",\n response = HealthDto.class)\n @ApiResponses(value = {\n @ApiResponse(code = 503, message = \"unhealthy\"),\n @ApiResponse(code = 200, message = \"healthy\")})\n @io.swagger.annotations.ApiOperation(value = \"Basic Availability Check\",\n notes = \"Always returns 200. The JSON will only include the message field.\",\n response = HealthDto.class)\n @io.swagger.annotations.ApiResponses(value = {\n @io.swagger.annotations.ApiResponse(code = 503, message = \"unhealthy\"),\n @io.swagger.annotations.ApiResponse(code = 200, message = \"healthy\")})\n @GET\n @Produces(MediaType.APPLICATION_JSON)\n @JsonView(HealthJsonViews.Availability.class)\n HealthDto getBasicAvailabilityCheck();\n}",
"@Api(value = \"/health\",\n description = \"Lists health check dependencies\")\[email protected](value = \"/health\",\n description = \"Lists health check dependencies\")\n@Path(\"meta/health/diagnostic/dependencies\")\npublic interface DependenciesResource {\n @GET\n @Produces(MediaType.TEXT_HTML)\n StreamingOutput getDependencyListingHtml();\n\n @ApiOperation(value = \"Dependency Listing\",\n notes = \"Returns the name, internal URL and external URL (if applicable) of all \"\n + \"dependencies.\",\n response = HealthDependencyDto.class,\n responseContainer = \"List\")\n @ApiResponses(value = {\n @ApiResponse(code = 503, message = \"unhealthy\", response = HealthDependencyDto.class),\n @ApiResponse(code = 200, message = \"healthy\", response = HealthDependencyDto.class)})\n @io.swagger.annotations.ApiOperation(value = \"Dependency Listing\",\n notes = \"Returns the name, internal URL and external URL (if applicable) of all \"\n + \"dependencies.\",\n response = HealthDependencyDto.class,\n responseContainer = \"List\")\n @io.swagger.annotations.ApiResponses(value = {\n @io.swagger.annotations.ApiResponse(code = 503, message = \"unhealthy\",\n response = HealthDependencyDto.class),\n @io.swagger.annotations.ApiResponse(code = 200, message = \"healthy\",\n response = HealthDependencyDto.class)})\n @GET\n @Produces(MediaType.APPLICATION_JSON)\n @JsonView(HealthJsonViews.Dependency.class)\n List<HealthDependencyDto> getDependencyListing();\n\n @GET\n @Produces(MediaType.TEXT_HTML)\n @Path(\"/{name}\")\n Response getDependencyAvailabilityCheckHtml(@PathParam(\"name\") String name);\n\n @ApiOperation(value = \"Availability Check for Dependency\",\n notes =\n \"Invokes the basic availability check on the given dependency. \"\n + \"The response code will match the code returned by the dependency, and will be \"\n + \"omitted from the JSON.\",\n response = HealthDependencyDto.class)\n @ApiResponses(value = {\n @ApiResponse(code = 503, message = \"unhealthy\", response = HealthDependencyDto.class),\n @ApiResponse(code = 200, message = \"healthy\", response = HealthDependencyDto.class)})\n @io.swagger.annotations.ApiOperation(value = \"Availability Check for Dependency\",\n notes =\n \"Invokes the basic availability check on the given dependency. \"\n + \"The response code will match the code returned by the dependency, and will be \"\n + \"omitted from the JSON.\",\n response = HealthDependencyDto.class)\n @io.swagger.annotations.ApiResponses(value = {\n @io.swagger.annotations.ApiResponse(code = 503, message = \"unhealthy\",\n response = HealthDependencyDto.class),\n @io.swagger.annotations.ApiResponse(code = 200, message = \"healthy\",\n response = HealthDependencyDto.class)})\n @GET\n @Produces(MediaType.APPLICATION_JSON)\n @JsonView(HealthJsonViews.Dependency.class)\n @Path(\"/{name}\")\n Response getDependencyAvailabilityCheck(@PathParam(\"name\") String name);\n}",
"@Api(value = \"/health\",\n description = \"Diagnostic health check\")\[email protected](value = \"/health\",\n description = \"Diagnostic health check\")\n@Path(\"meta/health/diagnostic\")\npublic interface DiagnosticResource {\n\n @GET\n @Produces(MediaType.TEXT_HTML)\n Response getDiagnosticHealthCheckHtml();\n\n @ApiOperation(value = \"Diagnostic Health Check\",\n notes =\n \"The response JSON will contain all available diagnostic details and the results of \"\n + \"checking the health of all dependencies.\",\n response = HealthDto.class)\n @ApiResponses(value = {\n @ApiResponse(code = 503, message = \"unhealthy\", response = HealthDto.class),\n @ApiResponse(code = 200, message = \"healthy\", response = HealthDto.class)})\n @io.swagger.annotations.ApiOperation(value = \"Diagnostic Health Check\",\n notes =\n \"The response JSON will contain all available diagnostic details and the results of \"\n + \"checking the health of all dependencies.\",\n response = HealthDto.class)\n @io.swagger.annotations.ApiResponses(value = {\n @io.swagger.annotations.ApiResponse(code = 503, message = \"unhealthy\",\n response = HealthDto.class),\n @io.swagger.annotations.ApiResponse(code = 200, message = \"healthy\",\n response = HealthDto.class)})\n @GET\n @Produces(MediaType.APPLICATION_JSON)\n @JsonView(HealthJsonViews.Diagnostic.class)\n Response getDiagnosticHealthCheck();\n}",
"@Api(value = \"/health\", description = \"Health and dependency checks\")\[email protected](value = \"/health\", description = \"Health and dependency checks\")\n@Path(\"meta/health\")\npublic interface HealthResource {\n @GET\n @Produces(MediaType.TEXT_HTML)\n Response getPrimaryHealthCheckHtml();\n\n @ApiOperation(value = \"Primary Health Check\",\n notes =\n \"The response JSON will contain a message and the results of checking the health of \"\n + \"primary dependencies, although stack traces will be excluded.\",\n response = HealthDto.class)\n @ApiResponses(value = {\n @ApiResponse(code = 503, message = \"unhealthy\", response = HealthDto.class),\n @ApiResponse(code = 200, message = \"healthy\", response = HealthDto.class)})\n @io.swagger.annotations.ApiOperation(value = \"Primary Health Check\",\n notes =\n \"The response JSON will contain a message and the results of checking the health of \"\n + \"primary dependencies, although stack traces will be excluded.\",\n response = HealthDto.class)\n @io.swagger.annotations.ApiResponses(value = {\n @io.swagger.annotations.ApiResponse(code = 503, message = \"unhealthy\",\n response = HealthDto.class),\n @io.swagger.annotations.ApiResponse(code = 200, message = \"healthy\",\n response = HealthDto.class)})\n @GET\n @Produces(MediaType.APPLICATION_JSON)\n @JsonView(HealthJsonViews.Primary.class)\n Response getPrimaryHealthCheck();\n}",
"@Api(value = \"/health\",\n description = \"Application Version\")\[email protected](value = \"/health\",\n description = \"Application Version\")\n@Path(\"meta/version\")\npublic interface VersionResource {\n\n @GET\n @Produces(MediaType.TEXT_HTML)\n StreamingOutput getVersionInfoHtml();\n\n @ApiOperation(value = \"Application Version Information\",\n notes = \"The version information of the Application.\",\n response = BuildDto.class)\n @ApiResponses(value = {\n @ApiResponse(code = 503, message = \"Service Unavailable\"),\n @ApiResponse(code = 200, message = \"Success\")})\n @io.swagger.annotations.ApiOperation(value = \"Application Version Information\",\n notes = \"The version information of the Application.\",\n response = BuildDto.class)\n @io.swagger.annotations.ApiResponses(value = {\n @io.swagger.annotations.ApiResponse(code = 503, message = \"Service Unavailable\"),\n @io.swagger.annotations.ApiResponse(code = 200, message = \"Success\")})\n @GET\n @Produces(MediaType.APPLICATION_JSON)\n BuildDto getVersionInfo();\n}",
"public class DependenciesResourceImpl implements DependenciesResource {\n private final HealthChecker checker;\n private final MustacheFactory mustacheFactory;\n\n @Inject\n DependenciesResourceImpl(\n HealthChecker checker, @HealthTemplateFactory MustacheFactory mustacheFactory) {\n this.checker = checker;\n this.mustacheFactory = mustacheFactory;\n }\n\n @Override\n public StreamingOutput getDependencyListingHtml() {\n HealthDependenciesDto dto = HealthDependenciesDto.builder()\n .setDependencies(checker.doDependencyListing())\n .build();\n Mustache mustache = mustacheFactory.compile(\"dependency_listing.mustache\");\n return StreamingWriterOutput\n .with(writer -> mustache.execute(writer, new HealthDependenciesPresenter(dto)));\n }\n\n @Override\n public List<HealthDependencyDto> getDependencyListing() {\n return checker.doDependencyListing();\n }\n\n @Override\n public Response getDependencyAvailabilityCheckHtml(String name) {\n HealthDependencyDto dto = checker.doDependencyAvailabilityCheck(name);\n Mustache mustache = mustacheFactory.compile(\"dependency_availability.mustache\");\n Integer status = returnStatus(dto);\n return Response.status(status)\n .entity(StreamingWriterOutput\n .with(writer -> mustache.execute(writer, new HealthDependencyPresenter(dto))))\n .build();\n }\n\n @Override\n public Response getDependencyAvailabilityCheck(String name) {\n HealthDependencyDto dto = checker.doDependencyAvailabilityCheck(name);\n int status = returnStatus(dto);\n return Response.status(status).entity(dto).build();\n }\n\n private int returnStatus(HealthDependencyDto dto) {\n return dto.isHealthy() ? 200 : 503;\n }\n}"
] | import com.cerner.beadledom.health.api.AvailabilityResource;
import com.cerner.beadledom.health.api.DependenciesResource;
import com.cerner.beadledom.health.api.DiagnosticResource;
import com.cerner.beadledom.health.api.HealthResource;
import com.cerner.beadledom.health.api.VersionResource;
import com.cerner.beadledom.health.internal.HealthChecker;
import com.cerner.beadledom.health.internal.HealthTemplateFactory;
import com.cerner.beadledom.health.resource.AvailabilityResourceImpl;
import com.cerner.beadledom.health.resource.DependenciesResourceImpl;
import com.cerner.beadledom.health.resource.DiagnosticResourceImpl;
import com.cerner.beadledom.health.resource.HealthResourceImpl;
import com.cerner.beadledom.health.resource.VersionResourceImpl;
import com.cerner.beadledom.metadata.ServiceMetadata;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.MustacheFactory;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.multibindings.MultibindingsScanner;
import java.util.Map;
import java.util.Set;
import javax.inject.Singleton;
import javax.ws.rs.core.UriInfo; | package com.cerner.beadledom.health;
/**
* A Guice module that provides JAX-RS resources to implement the Health Check.
*
* <p>With the module installed, you can add new 'dependencies' to your service's health check by
* adding bindings of {@link com.cerner.beadledom.health.HealthDependency} using the Multibinder.
*
* <p>Example:
*
* <p><pre><code>
* class MyModule extends AbstractModule {
* {@literal @}Override
* protected void configure() {
* Multibinder<HealthDependency> healthDependencyBinder = Multibinder
* .newSetBinder(binder(), HealthDependency.class);
* healthDependencyBinder.addBinding().to(FoobarHealthDependency.class);
* }
* }
*
* class FoobarHealthDependency extends HealthDependency {
* {@literal @}Override
* public HealthStatus checkAvailability() {
* if (...) { // check health somehow
* return HealthStatus.create(200, "foobar is available");
* } else {
* return HealthStatus.create(503, "foobar is gone. just gone.");
* }
* }
*
* {@literal @}Override
* public String getName() {
* return "foobar";
* }
* }
* </code></pre>
*
* <p>Provides:
* <ul>
* <li>{@link AvailabilityResource}</li>
* <li>{@link HealthResource}</li>
* <li>{@link VersionResource}</li>
* <li>{@link DiagnosticResource}</li>
* <li>{@link DependenciesResource}</li>
* <li>The following {@link com.fasterxml.jackson.databind.Module Jackson module} multibindings:
* <ul>
* <li>{@link com.fasterxml.jackson.datatype.jdk8.Jdk8Module}</li>
* <li>{@link com.fasterxml.jackson.datatype.jsr310.JavaTimeModule}</li>
* </ul>
* </li>
* <li>{@link com.cerner.beadledom.health.internal.HealthChecker} (for internal use only)</li>
* <li>{@link Map}<{@link String}, {@link com.cerner.beadledom.health.HealthDependency}>
* (for internal use only)</li>
* <li>{@link com.github.mustachejava.MustacheFactory} with binding annotation
* HealthTemplateFactory (for internal use only)</li>
* </ul>
*
* <p>Requires:
* <ul>
* <li>{@link com.cerner.beadledom.metadata.ServiceMetadata}</li>
* <li>{@link javax.ws.rs.core.UriInfo} (request-scoped)</li>
* </ul>
*
* <p>Installs:
* <ul>
* <li> {@link MultibindingsScanner} </li>
* </ul>
*/
public class HealthModule extends AbstractModule {
@Override
protected void configure() {
requireBinding(ServiceMetadata.class);
requireBinding(UriInfo.class);
bind(AvailabilityResource.class).to(AvailabilityResourceImpl.class);
bind(HealthResource.class).to(HealthResourceImpl.class);
bind(DependenciesResource.class).to(DependenciesResourceImpl.class);
bind(DiagnosticResource.class).to(DiagnosticResourceImpl.class); | bind(VersionResource.class).to(VersionResourceImpl.class); | 4 |
Expugn/S-argo | src/main/java/io/github/spugn/Sargo/Functions/BannerInfo.java | [
"public class CommandManager\n{\n private final CommandLine COMMAND_LINE;\n private final Message MESSAGE;\n private final String userDiscordID;\n\n public CommandManager(Message message)\n {\n this.MESSAGE = message;\n\n if (message.getAuthor().isPresent())\n {\n userDiscordID = message.getAuthor().get().getId().asString();\n }\n else\n {\n Sargo.replyToMessage_Warning(MESSAGE, \"FAILED TO GET USER ID\", \"This wasn't supposed to happen.\");\n userDiscordID = \"\";\n COMMAND_LINE = null;\n return;\n }\n\n String botOwnerDiscordID = LoginSettingsParser.getBotOwnerDiscordID();\n\n DiscordCommand discordCommand = new DiscordCommand();\n discordCommand.setUseMention(false);\n discordCommand.setCommandPrefix(CommandSettingsParser.getCommandPrefix());\n discordCommand.setDeleteUserMessage(CommandSettingsParser.isDeleteUserMessage());\n\n DiscordCommand discordCommandMention = new DiscordCommand();\n discordCommandMention.setUseMention(true);\n discordCommandMention.setCommandPrefix(CommandSettingsParser.getCommandPrefix());\n discordCommandMention.setDeleteUserMessage(CommandSettingsParser.isDeleteUserMessage());\n\n Sargo.refreshPresence();\n\n if (discordCommand.meetsConditions(message) != null)\n {\n COMMAND_LINE = discordCommand.meetsConditions(message);\n }\n else if (discordCommandMention.meetsConditions(message) != null)\n {\n COMMAND_LINE = discordCommandMention.meetsConditions(message);\n }\n else\n {\n COMMAND_LINE = null;\n }\n\n if (COMMAND_LINE != null)\n {\n if (COMMAND_LINE.getCommand().equalsIgnoreCase(\"scout\"))\n {\n scoutCommand();\n }\n else if (COMMAND_LINE.getCommand().equalsIgnoreCase(\"help\"))\n {\n new Help(MESSAGE);\n }\n else if (COMMAND_LINE.getCommand().equalsIgnoreCase(\"info\"))\n {\n new Info(MESSAGE);\n }\n else if (COMMAND_LINE.getCommand().equalsIgnoreCase(\"shop\"))\n {\n shopCommand();\n }\n else if (COMMAND_LINE.getCommand().equalsIgnoreCase(\"profile\"))\n {\n profileCommand();\n }\n else if (COMMAND_LINE.getCommand().equalsIgnoreCase(\"user\"))\n {\n userCommand();\n }\n else if (COMMAND_LINE.getCommand().equalsIgnoreCase(\"reset\"))\n {\n resetCommand();\n }\n else if (COMMAND_LINE.getCommand().equalsIgnoreCase(\"update\") && userDiscordID.equals(botOwnerDiscordID))\n {\n updateCommand();\n }\n else if (COMMAND_LINE.getCommand().equalsIgnoreCase(\"stop\") && userDiscordID.equals(botOwnerDiscordID))\n {\n Sargo.replyToMessage_Warning(MESSAGE, \"SHUTTING DOWN\", \"Goodbye!\");\n System.exit(0);\n }\n else if (COMMAND_LINE.getCommand().equalsIgnoreCase(\"reload\") && userDiscordID.equals(botOwnerDiscordID))\n {\n reloadCommand();\n }\n else if (COMMAND_LINE.getCommand().equalsIgnoreCase(\"settings\") && userDiscordID.equals(botOwnerDiscordID))\n {\n new SettingsManager(MESSAGE, COMMAND_LINE);\n }\n }\n }\n\n private void scoutCommand()\n {\n try\n {\n if (COMMAND_LINE.getArgumentCount() >= 2)\n {\n // START \"TYPING\"\n MESSAGE.getChannel().cast(TextChannel.class).block().type().block();\n\n\n if (COMMAND_LINE.getArgument(2).equalsIgnoreCase(\"ws\") ||\n COMMAND_LINE.getArgument(2).equalsIgnoreCase(\"wsi\") ||\n COMMAND_LINE.getArgument(2).equalsIgnoreCase(\"wm\") ||\n COMMAND_LINE.getArgument(2).equalsIgnoreCase(\"wmi\"))\n {\n new WeaponScoutManager(MESSAGE, Integer.parseInt(COMMAND_LINE.getArgument(1)), COMMAND_LINE.getArgument(2), userDiscordID);\n }\n else\n {\n new ScoutManager(MESSAGE, Integer.parseInt(COMMAND_LINE.getArgument(1)), COMMAND_LINE.getArgument(2), userDiscordID);\n }\n\n }\n else if (COMMAND_LINE.getArgumentCount() >= 1)\n {\n new BannerInfo(MESSAGE, Integer.parseInt(COMMAND_LINE.getArgument(1)));\n }\n else\n {\n new BannerInfo(MESSAGE, \"1\");\n }\n }\n catch (NumberFormatException e)\n {\n if (COMMAND_LINE.getArgumentCount() == 1)\n {\n if (COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"nts\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"ntsi\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"ntm\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"ntmi\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"pts\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"ptsi\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"ptm\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"ptmi\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"nt2s\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"nt2si\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"nt2m\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"nt2mi\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"pt2s\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"pt2si\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"pt2m\") ||\n COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"pt2mi\"))\n {\n // START \"TYPING\"\n MESSAGE.getChannel().cast(TextChannel.class).block().type().block();\n\n new TicketScoutManager(MESSAGE, COMMAND_LINE.getArgument(1), userDiscordID);\n }\n else\n {\n try\n {\n int pageNumber = Integer.parseInt(COMMAND_LINE.getArgument(1).substring(1) + \"\");\n char pChar = COMMAND_LINE.getArgument(1).charAt(0);\n\n if (pChar == 'p' || pChar == 'P')\n {\n new BannerInfo(MESSAGE, String.valueOf(pageNumber));\n }\n else\n {\n /* FIRST CHARACTER IS NOT 'P' */\n Sargo.replyToMessage_Warning(MESSAGE, \"COMMAND ERROR\", \"Make sure you're entering a number for the banner ID.\");\n }\n }\n catch (NumberFormatException | NullPointerException | StringIndexOutOfBoundsException f)\n {\n Sargo.replyToMessage_Warning(MESSAGE, \"COMMAND ERROR\", \"Please review the help menu.\");\n }\n }\n }\n else\n {\n Sargo.replyToMessage_Warning(MESSAGE, \"COMMAND ERROR\", \"Make sure you're entering a number for the banner ID.\");\n }\n }\n }\n\n private void shopCommand()\n {\n if (COMMAND_LINE.getArgumentCount() >= 1)\n {\n if (COMMAND_LINE.getArgumentCount() >= 2)\n {\n try\n {\n int quantity = Integer.parseInt(COMMAND_LINE.getArgument(2));\n\n if (quantity < 0)\n {\n quantity = 1;\n }\n else if (quantity > ShopSettingsParser.getMaxShopLimit())\n {\n quantity = ShopSettingsParser.getMaxShopLimit();\n }\n\n new Shop(MESSAGE, COMMAND_LINE.getArgument(1), quantity, true);\n }\n catch (NumberFormatException e)\n {\n new Shop(MESSAGE, COMMAND_LINE.getArgument(1), 1, false);\n }\n }\n else\n {\n new Shop(MESSAGE, COMMAND_LINE.getArgument(1), 1, false);\n }\n }\n else\n {\n new Shop(MESSAGE);\n }\n }\n\n private void profileCommand()\n {\n if (COMMAND_LINE.getArgumentCount() >= 2)\n {\n String arg1 = COMMAND_LINE.getArgument(1);\n String arg2 = COMMAND_LINE.getArgument(2);\n\n if (arg1.equalsIgnoreCase(\"info\") || arg1.equalsIgnoreCase(\"i\"))\n {\n try\n {\n /* TEST IF ARGUMENT CAN BE PARSED INTO AN INTEGER */\n Integer.parseInt(arg2);\n\n /* OPEN BANNER INFO PROFILE */\n new Profile(MESSAGE, userDiscordID, 2, arg2);\n }\n catch (NumberFormatException e)\n {\n Sargo.replyToMessage_Warning(MESSAGE, \"COMMAND ERROR\", \"Make sure you're entering a number for the banner ID\");\n }\n }\n else if (arg1.equalsIgnoreCase(\"search\") || arg1.equalsIgnoreCase(\"s\"))\n {\n new Profile(MESSAGE, userDiscordID, 3, arg2);\n }\n else\n {\n Sargo.replyToMessage_Warning(MESSAGE, \"UNKNOWN ARGUMENT\", \"Please review the help menu.\");\n }\n }\n else if (COMMAND_LINE.getArgumentCount() >= 1)\n {\n String arg1 = COMMAND_LINE.getArgument(1);\n if (arg1.equalsIgnoreCase(\"data\") || arg1.equalsIgnoreCase(\"d\"))\n {\n new Profile(MESSAGE, userDiscordID, 1);\n }\n else\n {\n Sargo.replyToMessage_Warning(MESSAGE, \"UNKNOWN ARGUMENT\", \"Please review the help menu.\");\n }\n }\n else\n {\n new Profile(MESSAGE, userDiscordID);\n }\n }\n\n private void userCommand()\n {\n Sargo.replyToMessage_Warning(MESSAGE, \"DISCONTINUED COMMAND\", \"Command is no longer supported.\");\n /*\n if (COMMAND_LINE.getArgumentCount() >= 1)\n {\n IGuild guild = CHANNEL.getGuild();\n String userDiscordName = COMMAND_LINE.getArgument(1);\n\n if (!(guild.getUsersByName(userDiscordName).isEmpty()))\n {\n IUser foundUser = guild.getUsersByName(userDiscordName).get(0);\n new Profile(CHANNEL, foundUser.getStringID());\n }\n else\n {\n try\n {\n String userDiscordID = COMMAND_LINE.getArgument(1);\n userDiscordID = userDiscordID.replaceAll(\"<\", \"\");\n userDiscordID = userDiscordID.replaceAll(\"@\", \"\");\n userDiscordID = userDiscordID.replaceAll(\"!\", \"\");\n userDiscordID = userDiscordID.replaceAll(\">\", \"\");\n\n if (guild.getUserByID(Long.parseLong(userDiscordID)) != null)\n {\n IUser foundUser = guild.getUserByID(Long.parseLong(userDiscordID));\n new Profile(CHANNEL, foundUser.getStringID());\n }\n else\n {\n Sargo.replyToMessage_Warning(MESSAGE, \"UNKNOWN USER\", \"Could not find that user.\");\n }\n }\n catch (NumberFormatException e)\n {\n Sargo.replyToMessage_Warning(MESSAGE, \"UNKNOWN USER\", \"Could not find that user. Does their name have a space? Try `\" + getCommandPrefix() + \"user @[name]` instead.\");\n }\n }\n }\n else\n {\n Sargo.replyToMessage_Warning(MESSAGE, \"NOT ENOUGH ARGUMENTS\", \"Please review the help menu.\");\n }\n */\n }\n\n private void resetCommand()\n {\n if (COMMAND_LINE.getArgumentCount() >= 3)\n {\n String arg3 = COMMAND_LINE.getArgument(3);\n String arg2 = COMMAND_LINE.getArgument(2);\n int bannerID;\n try\n {\n bannerID = Integer.parseInt(COMMAND_LINE.getArgument(1));\n }\n catch (NumberFormatException e)\n {\n return;\n }\n boolean yes = (arg3.equalsIgnoreCase(\"y\") || arg3.equalsIgnoreCase(\"yes\"));\n\n if (arg2.equalsIgnoreCase(\"c\") ||\n arg2.equalsIgnoreCase(\"w\") ||\n arg2.equalsIgnoreCase(\"a\"))\n {\n new Reset(MESSAGE, userDiscordID, bannerID, arg2, yes);\n }\n else\n {\n Sargo.replyToMessage_Warning(MESSAGE, \"COMMAND ERROR\", \"Use `\" + CommandSettingsParser.getCommandPrefix() + \"reset [Banner ID] [c/w/a]`.\");\n }\n }\n else if (COMMAND_LINE.getArgumentCount() >= 2)\n {\n String arg2 = COMMAND_LINE.getArgument(2);\n int bannerID;\n try\n {\n bannerID = Integer.parseInt(COMMAND_LINE.getArgument(1));\n }\n catch (NumberFormatException e)\n {\n return;\n }\n\n if (arg2.equalsIgnoreCase(\"c\") ||\n arg2.equalsIgnoreCase(\"w\") ||\n arg2.equalsIgnoreCase(\"a\"))\n {\n new Reset(MESSAGE, userDiscordID, bannerID, arg2, false);\n }\n else\n {\n Sargo.replyToMessage_Warning(MESSAGE, \"COMMAND ERROR\", \"Use `\" + CommandSettingsParser.getCommandPrefix() + \"reset [Banner ID] [c/w/a]`.\");\n }\n }\n else if (COMMAND_LINE.getArgumentCount() >= 1)\n {\n String arg1 = COMMAND_LINE.getArgument(1);\n if (arg1.equalsIgnoreCase(\"y\") || arg1.equalsIgnoreCase(\"yes\"))\n {\n new Reset(MESSAGE, userDiscordID);\n }\n }\n else\n {\n new Reset(MESSAGE);\n }\n }\n\n private void updateCommand()\n {\n if (COMMAND_LINE.getArgumentCount() >= 1)\n {\n /* RESET */\n if (COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"r\"))\n {\n new Update(MESSAGE, true, true);\n }\n /* OVERWRITE */\n else if (COMMAND_LINE.getArgument(1).equalsIgnoreCase(\"o\"))\n {\n new Update(MESSAGE, false, true);\n }\n else\n {\n new Update(MESSAGE, false, false);\n }\n }\n else\n {\n new Update(MESSAGE, false, false);\n }\n }\n\n private void reloadCommand()\n {\n Reload.reloadBanners();\n Reload.reloadSettings();\n Sargo.replyToMessage_Warning(MESSAGE, \"FILES RELOADED\", \"The Banners and Settings xml files have been reloaded.\");\n }\n\n public static String getCommandPrefix()\n {\n return CommandSettingsParser.getCommandPrefix() + \"\";\n }\n}",
"public class Character\n{\n private String prefix;\n private String name;\n private int rarity;\n private String imagePath;\n\n public Character()\n {\n prefix = \"\";\n name = \"null\";\n rarity = 1;\n imagePath = \"\";\n }\n\n public void setPrefix(String prefix)\n {\n this.prefix = prefix;\n }\n\n public void setName(String name)\n {\n this.name = name;\n }\n\n public void setRarity(int rarity)\n {\n this.rarity = rarity;\n }\n\n public void setImagePath(String imagePath)\n {\n this.imagePath = imagePath;\n }\n\n public String getPrefix()\n {\n return prefix;\n }\n\n public String getName()\n {\n return name;\n }\n\n public int getRarity()\n {\n return rarity;\n }\n\n public String getImagePath()\n {\n return imagePath;\n }\n\n @Override\n public String toString()\n {\n if (prefix.isEmpty())\n {\n return rarity + \"★ \" + name;\n }\n return rarity + \"★ [\" + prefix + \"] \" + name;\n }\n\n public String toStringNoName()\n {\n if (prefix.isEmpty())\n {\n return rarity + \"★ \" + name;\n }\n return rarity + \"★ [\" + prefix + \"]\";\n }\n}",
"public class Sargo\n{\n private static DiscordClient CLIENT;\n private static final Logger LOGGER = LoggerFactory.getLogger(Sargo.class);\n\n public static void main(String[] args)\n {\n Reload.silentReloadSettings();\n\n CLIENT = new DiscordClientBuilder(LoginSettingsParser.getBotToken()).build();\n\n CLIENT.getEventDispatcher().on(ReadyEvent.class)\n .subscribe(ready -> {\n LOGGER.info(\"Starting up S'argo v\" + SystemData.getVERSION() + \" - SAO:MD Summon Simulator Discord Bot by S'pugn#2612\");\n LOGGER.info(\"Logged in and running as: \" + ready.getSelf().getUsername() + \"#\" + ready.getSelf().getDiscriminator());\n\n // UPDATE PRESENCE\n refreshPresence();\n\n // DOWNLOAD SYSTEM IMAGES IF NEEDED AND RELOAD BANNERS\n new Update();\n Reload.reloadBanners();\n });\n\n CLIENT.getEventDispatcher().on(MessageCreateEvent.class)\n .subscribe(event -> MessageListener.messageReceived(event.getMessage()));\n\n CLIENT.login().block();\n }\n\n public static DiscordClient getCLIENT()\n {\n return CLIENT;\n }\n\n public static void refreshPresence()\n {\n if (CLIENT.getSelfId().isPresent())\n {\n String playingText;\n String commandPrefix = CommandSettingsParser.getCommandPrefix() + \"\";\n String clientID = CLIENT.getSelfId().get().asString();\n String botName = new ScoutMasterParser().getBotName();\n\n playingText = botName +\n (clientID.equalsIgnoreCase(\"356981380338679810\") ||\n clientID.equalsIgnoreCase(\"309620271621341185\") ? \" devBot | \" : \" | \") +\n commandPrefix + \"help\";\n\n CLIENT.updatePresence(Presence.online(Activity.playing(playingText))).subscribe();\n }\n }\n\n public static void replyToMessage(TextChannel textChannel, String reply)\n {\n textChannel.createMessage(reply).block();\n }\n\n public static void replyToMessage(TextChannel textChannel, String reply, File image)\n {\n try\n {\n InputStream is = new FileInputStream(image);\n textChannel.createMessage( s -> s.setContent(reply).addFile(image.getName(), is) ).block();\n }\n catch (FileNotFoundException e)\n {\n textChannel.createMessage(reply).block();\n }\n\n }\n\n public static Message replyToMessage_Warning(Message sentMessage, String title, String text)\n {\n return sentMessage.getChannel().block().createMessage(\n s -> s.setEmbed(embed -> embed.setColor(Color.RED).setTitle(title).setDescription(text))).block();\n }\n\n public static void replyToMessage_Warning(Message sentMessage, String title, String text, String bannerName)\n {\n sentMessage.getChannel().block().createMessage(\n s -> s.setEmbed(embed -> embed.setColor(Color.RED).setTitle(title).setDescription(text).setFooter(bannerName, new GitHubImage(\"images/System/Scout_Icon.png\").getURL()))).block();\n }\n\n public static Message replyToMessage_Warning(TextChannel textChannel, String title, String text)\n {\n return textChannel.createMessage(\n s -> s.setEmbed(embed -> embed.setColor(Color.RED).setTitle(title).setDescription(text))).block();\n }\n\n public static void replyToMessage_Warning(TextChannel textChannel, String title, String text, String bannerName)\n {\n textChannel.createMessage(\n s -> s.setEmbed(embed -> embed.setColor(Color.RED).setTitle(title).setDescription(text).setFooter(bannerName, new GitHubImage(\"images/System/Scout_Icon.png\").getURL()))).block();\n }\n\n public static Message sendEmbed(TextChannel tc, Consumer<EmbedCreateSpec> ecsTemplate)\n {\n return tc.createMessage(ms -> ms.setEmbed(ecsTemplate.andThen(es -> {}))).block();\n }\n\n public static Message sendEmbed(TextChannel tc, Consumer<EmbedCreateSpec> ecsTemplate, File image)\n {\n try\n {\n InputStream is = new FileInputStream(image);\n Message sentMessage = tc.createMessage(s -> s.setEmbed(ecsTemplate.andThen(es -> es.setImage(\"attachment://\" + image.getName()))).addFile(image.getName(), is)).block();\n is.close();\n return sentMessage;\n }\n catch (FileNotFoundException e)\n {\n return tc.createMessage(ms -> ms.setEmbed(ecsTemplate.andThen(es -> es.addField(\"MISSING SCOUT RESULT\", \"Scout result image is missing.\", true)))).block();\n }\n catch (IOException e)\n {\n // IGNORED\n }\n return null;\n }\n\n public static Message editEmbedMessage(Message embedMessage, Consumer<EmbedCreateSpec> ecsTemplate)\n {\n return embedMessage.edit(spec -> spec.setEmbed(ecsTemplate)).block();\n }\n}",
"public class GitHubImage\n{\n private String filePath;\n private final String GITHUB_IMAGE;\n\n public GitHubImage(String filePath)\n {\n GITHUB_IMAGE = LoginSettingsParser.getGitHubRepoURL();\n this.filePath = filePath;\n }\n\n public String getURL()\n {\n String url = GITHUB_IMAGE + filePath;\n\n /* REPLACE ALL SPACES WITH %20 */\n url = url.replaceAll(\" \", \"%20\");\n\n /* REPLACE ALL ★ WITH %E2%98%85 */\n url = url.replaceAll(\"★\", \"%E2%98%85\");\n\n return url;\n }\n}",
"public class BannerParser\n{\n private static List<Banner> bannerFile;\n private static List<Integer> goldBanners;\n private static List<Integer> goldBannersv2;\n private static List<Integer> platinumBanners;\n private static List<Integer> platinumBannersv2;\n\n // Character Blacklist String: <BANNER ID>;<PREFIX>;<NAME>;<RARITY>\n private static List<String> excludedCharacters;\n\n /**\n * Returns a List of Banner objects.\n *\n * @return List of Banner objects\n */\n public static List<Banner> getBanners()\n {\n return bannerFile;\n }\n\n public static List<Integer> getGoldBanners()\n {\n return goldBanners;\n }\n\n public static List<Integer> getGoldBannersv2()\n {\n return goldBannersv2;\n }\n\n public static List<Integer> getPlatinumBanners()\n{\n return platinumBanners;\n}\n\n public static List<Integer> getPlatinumBannersv2()\n {\n return platinumBannersv2;\n }\n\n public static List<String> getExcludedCharacters()\n {\n return excludedCharacters;\n }\n\n /**\n * index 0 = banner id\n * index 1 = character prefix\n * index 2 = character name\n * index 3 = character rarity\n */\n public static String[] parseExcludeCharacterString(String excludedCharacterString)\n {\n // SPLIT ECS\n String[] splitECS = excludedCharacterString.split(\";\");\n\n // CONVERT ANY UNDERSCORES TO SPACES FROM CHARACTER NAME/PREFIX\n splitECS[1] = splitECS[1].replaceAll(\"_\", \" \");\n splitECS[2] = splitECS[2].replaceAll(\"_\", \" \");\n\n return splitECS;\n }\n\n /**\n * Reads the banners.xml file and returns a List of Banner objects.\n *\n * @param configFile Path where the file is located.\n * @return List of Banner objects.\n */\n @SuppressWarnings(\"unchecked\")\n public void reloadBanners(String configFile)\n {\n try\n {\n bannerFile = tryRead(configFile);\n return;\n }\n catch (FailedToReadBannerFileException e)\n {\n e.displayErrorMessage();\n }\n bannerFile = Collections.emptyList();\n }\n\n private List<Banner> tryRead(String configFile) throws FailedToReadBannerFileException\n {\n List<Banner> banners = new ArrayList();\n goldBanners = new ArrayList();\n goldBannersv2 = new ArrayList();\n platinumBanners = new ArrayList();\n platinumBannersv2 = new ArrayList();\n excludedCharacters = new ArrayList();\n InputStream in;\n XMLEventReader eventReader;\n\n Banner banner = null;\n ArrayList<Character> characters = null;\n Character character;\n\n ArrayList<Weapon> weapons = null;\n Weapon weapon;\n\n /* CREATE XMLInputFactory AND XMLEventReader */\n XMLInputFactory inputFactory = XMLInputFactory.newInstance();\n try { in = new FileInputStream(configFile); }\n catch (FileNotFoundException e) { throw new FailedToReadBannerFileException(); }\n try { eventReader = inputFactory.createXMLEventReader(in); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n throw new FailedToReadBannerFileException();\n }\n\n /* READ XML FILE */\n while (eventReader.hasNext())\n {\n XMLEvent event;\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadBannerFileException();\n }\n\n if (event.isStartElement())\n {\n StartElement startElement = event.asStartElement();\n\n /* CREATE NEW BANNER AND CHARACTER LIST OBJECT */\n if (startElement.getName().getLocalPart().equals(\"Banner\"))\n {\n banner = new Banner();\n characters = new ArrayList();\n weapons = new ArrayList<>();\n\n /* GET AND SAVE BANNER ID */\n Iterator<Attribute> attributes = startElement.getAttributes();\n while (attributes.hasNext())\n {\n Attribute attribute = attributes.next();\n if (attribute.getName().toString().equals(\"id\"))\n {\n banner.setBannerID(Integer.parseInt(attribute.getValue()));\n }\n }\n }\n\n /* GET AND SAVE BANNER NAME */\n if (event.isStartElement())\n {\n if (event.asStartElement().getName().getLocalPart().equals(\"name\"))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadBannerFileException();\n }\n banner.setBannerName(event.asCharacters().getData());\n continue;\n }\n }\n\n /* GET AND SAVE BANNER TYPE */\n if (event.asStartElement().getName().getLocalPart().equals(\"type\"))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadBannerFileException();\n }\n banner.setBannerType(Integer.parseInt(event.asCharacters().getData()));\n continue;\n }\n\n /* GET AND SAVE WEAPON BANNER TYPE */\n if (event.asStartElement().getName().getLocalPart().equals(\"wepType\"))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadBannerFileException();\n }\n banner.setBannerWepType(Integer.parseInt(event.asCharacters().getData()));\n continue;\n }\n\n /* GET AND SAVE IF BANNER IS INCLUDED WITH GOLD BANNERS/GOLD BANNERS V2/ETC */\n if (event.asStartElement().getName().getLocalPart().equals(\"include\"))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadBannerFileException();\n }\n String includeType = event.asCharacters().getData();\n if (includeType.equals(\"GoldBanners\"))\n {\n try { goldBanners.add(banner.getBannerID()); }\n catch (NullPointerException e) { /* IGNORED */ }\n }\n else if (includeType.equals(\"GoldBannersv2\"))\n {\n try { goldBannersv2.add(banner.getBannerID()); }\n catch (NullPointerException e) { /* IGNORED */ }\n }\n else if (includeType.equals(\"PlatinumBanners\"))\n {\n try { platinumBanners.add(banner.getBannerID()); }\n catch (NullPointerException e) { /* IGNORED */ }\n }\n else if (includeType.equals(\"PlatinumBannersv2\"))\n {\n try { platinumBannersv2.add(banner.getBannerID()); }\n catch (NullPointerException e) { /* IGNORED */ }\n }\n continue;\n }\n\n /* GET AND SAVE ANY EXCLUDED CHARACTERS */\n if (event.asStartElement().getName().getLocalPart().equals(\"exclude\"))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadBannerFileException();\n }\n String excludedCharacter = event.asCharacters().getData();\n\n // BANNERID_PREFIX_NAME_RARITY\n try { excludedCharacters.add(banner.getBannerID() + \";\" + excludedCharacter); }\n catch (NullPointerException e) { /* IGNORED */ }\n\n continue;\n }\n\n /* GET AND SAVE CHARACTER */\n if (event.asStartElement().getName().getLocalPart().equals(\"Character\"))\n {\n character = new Character();\n\n Iterator<Attribute> attributes = event.asStartElement().getAttributes();\n while (attributes.hasNext())\n {\n Attribute attribute = attributes.next();\n if (attribute.getName().toString().equals(\"prefix\"))\n {\n character.setPrefix(attribute.getValue());\n }\n if (attribute.getName().toString().equals(\"char\"))\n {\n character.setName(attribute.getValue());\n }\n if (attribute.getName().toString().equals(\"rarity\"))\n {\n character.setRarity(Integer.parseInt(attribute.getValue()));\n }\n }\n\n /* GENERATE IMAGE FILE PATH*/\n String characterImage = character.getPrefix() + \" \" + character.getName();\n character.setImagePath(\"images/Characters/\" + characterImage.replaceAll(\" \", \"_\") + \".png\");\n\n /* ADD CHARACTER TO CHARACTER LIST */\n characters.add(character);\n }\n\n /* GET AND SAVE WEAPON */\n if (event.asStartElement().getName().getLocalPart().equals(\"Weapon\"))\n {\n weapon = new Weapon();\n\n Iterator<Attribute> attributes = event.asStartElement().getAttributes();\n while (attributes.hasNext())\n {\n Attribute attribute = attributes.next();\n if (attribute.getName().toString().equals(\"name\"))\n {\n weapon.setName(attribute.getValue());\n }\n if (attribute.getName().toString().equals(\"rarity\"))\n {\n weapon.setRarity(Integer.parseInt(attribute.getValue()));\n }\n }\n\n /* GENERATE IMAGE FILE PATH*/\n weapon.setImagePath(\"images/Weapons/\" + weapon.getName().replaceAll(\" \", \"_\") + \".png\");\n\n /* ADD WEAPON TO WEAPON LIST */\n weapons.add(weapon);\n }\n }\n\n /* END OF BANNER ELEMENT. FINALIZE CHARACTER LIST AND ADD OBJECT TO ArrayList */\n if (event.isEndElement())\n {\n EndElement endElement = event.asEndElement();\n if (endElement.getName().getLocalPart().equals(\"Banner\"))\n {\n banner.setCharacters(characters);\n banner.setWeapons(weapons);\n banners.add(banner);\n //System.out.println(\"added \" + banner.getBannerName());\n }\n }\n }\n\n return banners;\n }\n}",
"public class ScoutSettingsParser extends XMLEditor\n{\n private final String FILE_PATH = \"data/settings/Scout.xml\";\n\n private static final String DISABLE_IMAGES = \"DisableImages\";\n private static final String SIMPLE_MESSAGE = \"SimpleMessage\";\n private static final String RARITY_STARS = \"RarityStars\";\n private static final String SCOUT_MASTER = \"ScoutMaster\";\n private static final String COPPER = \"Copper\";\n private static final String SILVER = \"Silver\";\n private static final String GOLD = \"Gold\";\n private static final String PLATINUM = \"Platinum\";\n private static final String PLATINUM6 = \"Platinum6\";\n private static final String RECORD_CRYSTAL = \"RecordCrystal\";\n private static final String CIRCULATING_RECORD_CRYSTAL = \"CirculatingRecordCrystal\";\n\n private static final String SCOUT_SETTINGS = \"ScoutSettings\";\n private static final String RATE = \"rate\";\n\n private static final boolean DEFAULT_DISABLE_IMAGES = false;\n private static final boolean DEFAULT_SIMPLE_MESSAGE = false;\n private static final boolean DEFAULT_RARITY_STARS = true;\n private static final double DEFAULT_COPPER_RATE = 0.65;\n private static final double DEFAULT_SILVER_RATE = 0.25;\n private static final double DEFAULT_GOLD_RATE = 0.04;\n private static final double DEFAULT_PLATINUM_RATE = 0.03;\n private static final double DEFAULT_PLATINUM6_RATE = 0.03;\n private static final List<Double> DEFAULT_RECORD_CRYSTAL = Arrays.asList(0.03, 0.37, 0.4, 0.1, 0.035, 0.035, 0.01, 0.01, 0.005, 0.005);\n private static final List<Double> DEFAULT_CIRCULATING_RECORD_CRYSTAL = Arrays.asList(0.36, 0.6, 0.025, 0.01, 0.005);\n\n private static boolean isDisableImages;\n private static boolean isSimpleMessage;\n private static boolean isRarityStars;\n private static String scoutMaster;\n private static double copperRate;\n private static double silverRate;\n private static double goldRate;\n private static double platinumRate;\n private static double platinum6Rate;\n private static List<Double> recordCrystalRates;\n private static List<Double> circulatingRecordCrystalRates;\n\n public static boolean isDisableImages() { return isDisableImages; }\n public static boolean isSimpleMessage() { return isSimpleMessage; }\n public static boolean isRarityStars() { return isRarityStars; }\n public static String getScoutMaster() { return scoutMaster; }\n public static double getCopperRate() { return copperRate; }\n public static double getSilverRate() { return silverRate; }\n public static double getGoldRate() { return goldRate; }\n public static double getPlatinumRate() { return platinumRate; }\n public static double getPlatinum6Rate() { return platinum6Rate; }\n public static List<Double> getRecordCrystalRates() { return recordCrystalRates; }\n public static List<Double> getCirculatingRecordCrystalRates() { return circulatingRecordCrystalRates; }\n\n public static void setDisableImages(boolean dI) { isDisableImages = dI; }\n public static void setSimpleMessage(boolean sM) { isSimpleMessage = sM; }\n public static void setRarityStars(boolean rS) { isRarityStars = rS; }\n public static void setScoutMaster(String sM) { scoutMaster = sM; }\n public static void setCopperRate(double cR) { copperRate = cR; }\n public static void setSilverRate(double sR) { silverRate = sR; }\n public static void setGoldRate(double gR) { goldRate = gR; }\n public static void setPlatinumRate(double pR) { platinumRate = pR; }\n public static void setPlatinum6Rate(double p6R) { platinum6Rate = p6R; }\n public static void setRecordCrystalRates(List<Double> rCR) { recordCrystalRates = rCR; }\n public static void setCirculatingRecordCrystalRates(List<Double> cRCR) { circulatingRecordCrystalRates = cRCR; }\n\n public void reload()\n {\n try\n {\n newFile();\n read();\n }\n catch (FailedToReadSettingFileException e)\n {\n e.displayErrorMessage();\n }\n }\n\n private void read() throws FailedToReadSettingFileException\n {\n InputStream in;\n XMLEventReader eventReader;\n\n /* CREATE XMLInputFactory AND XMLEventReader */\n XMLInputFactory inputFactory = XMLInputFactory.newInstance();\n try { in = new FileInputStream(FILE_PATH); }\n catch (FileNotFoundException e) { throw new FailedToReadSettingFileException(); }\n try { eventReader = inputFactory.createXMLEventReader(in); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n throw new FailedToReadSettingFileException();\n }\n\n recordCrystalRates = new ArrayList<>();\n circulatingRecordCrystalRates = new ArrayList<>();\n\n /* READ XML FILE */\n while (eventReader.hasNext())\n {\n XMLEvent event;\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadSettingFileException();\n }\n\n if (event.isStartElement())\n {\n if (event.asStartElement().getName().getLocalPart().equals(DISABLE_IMAGES))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadSettingFileException();\n }\n isDisableImages = Boolean.parseBoolean(event.asCharacters().getData());\n continue;\n }\n\n if (event.asStartElement().getName().getLocalPart().equals(SIMPLE_MESSAGE))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadSettingFileException();\n }\n isSimpleMessage = Boolean.parseBoolean(event.asCharacters().getData());\n continue;\n }\n\n if (event.asStartElement().getName().getLocalPart().equals(RARITY_STARS))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadSettingFileException();\n }\n isRarityStars = Boolean.parseBoolean(event.asCharacters().getData());\n continue;\n }\n\n if (event.asStartElement().getName().getLocalPart().equals(SCOUT_MASTER))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadSettingFileException();\n }\n try\n {\n scoutMaster = event.asCharacters().getData();\n }\n catch (ClassCastException e)\n {\n scoutMaster = \"\";\n }\n continue;\n }\n\n if (event.asStartElement().getName().getLocalPart().equals(COPPER))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadSettingFileException();\n }\n copperRate = Double.parseDouble(event.asCharacters().getData());\n continue;\n }\n\n if (event.asStartElement().getName().getLocalPart().equals(SILVER))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadSettingFileException();\n }\n silverRate = Double.parseDouble(event.asCharacters().getData());\n continue;\n }\n\n if (event.asStartElement().getName().getLocalPart().equals(GOLD))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadSettingFileException();\n }\n goldRate = Double.parseDouble(event.asCharacters().getData());\n continue;\n }\n\n if (event.asStartElement().getName().getLocalPart().equals(PLATINUM))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadSettingFileException();\n }\n platinumRate = Double.parseDouble(event.asCharacters().getData());\n continue;\n }\n\n if (event.asStartElement().getName().getLocalPart().equals(PLATINUM6))\n {\n try { event = eventReader.nextEvent(); }\n catch (XMLStreamException e)\n {\n try { in.close(); } catch (IOException ex) { /* IGNORED */ }\n try { eventReader.close(); } catch (XMLStreamException ex) { /* IGNORED */ }\n throw new FailedToReadSettingFileException();\n }\n platinum6Rate = Double.parseDouble(event.asCharacters().getData());\n continue;\n }\n\n if (event.asStartElement().getName().getLocalPart().equals(RECORD_CRYSTAL))\n {\n double rate = 0.0;\n\n Iterator<Attribute> attributes = event.asStartElement().getAttributes();\n while (attributes.hasNext())\n {\n Attribute attribute = attributes.next();\n if (attribute.getName().toString().equals(\"rate\"))\n {\n rate = Double.parseDouble(attribute.getValue());\n }\n }\n recordCrystalRates.add(rate);\n continue;\n }\n\n if (event.asStartElement().getName().getLocalPart().equals(CIRCULATING_RECORD_CRYSTAL))\n {\n double rate = 0.0;\n\n Iterator<Attribute> attributes = event.asStartElement().getAttributes();\n while (attributes.hasNext())\n {\n Attribute attribute = attributes.next();\n if (attribute.getName().toString().equals(\"rate\"))\n {\n rate = Double.parseDouble(attribute.getValue());\n }\n }\n circulatingRecordCrystalRates.add(rate);\n }\n }\n }\n }\n\n private void newFile()\n {\n File commandSettingsFile = new File(FILE_PATH);\n\n /* FILE DOES NOT EXIST, CREATE A NEW ONE */\n if (!commandSettingsFile.exists())\n {\n try\n {\n /* INITIALIZE VARIABLES */\n XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();\n XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream(FILE_PATH));\n XMLEventFactory eventFactory = XMLEventFactory.newInstance();\n\n XMLEvent end = eventFactory.createDTD(\"\\n\");\n //XMLEvent tab = eventFactory.createDTD(\"\\t\");\n\n /* WRITE START DOCUMENT ELEMENT */\n StartDocument startDocument = eventFactory.createStartDocument();\n eventWriter.add(startDocument);\n eventWriter.add(end);\n\n /* BEGIN WRITING USER CONFIG, WRITE CommandSettings START ELEMENT */\n StartElement configStartElement = eventFactory.createStartElement(\"\", \"\", SCOUT_SETTINGS);\n eventWriter.add(configStartElement);\n eventWriter.add(end);\n\n writeNode(eventWriter, DISABLE_IMAGES, String.valueOf(DEFAULT_DISABLE_IMAGES));\n writeNode(eventWriter, SIMPLE_MESSAGE, String.valueOf(DEFAULT_SIMPLE_MESSAGE));\n writeNode(eventWriter, RARITY_STARS, String.valueOf(DEFAULT_RARITY_STARS));\n writeNode(eventWriter, SCOUT_MASTER, \"\");\n writeNode(eventWriter, COPPER, String.valueOf(DEFAULT_COPPER_RATE));\n writeNode(eventWriter, SILVER, String.valueOf(DEFAULT_SILVER_RATE));\n writeNode(eventWriter, GOLD, String.valueOf(DEFAULT_GOLD_RATE));\n writeNode(eventWriter, PLATINUM, String.valueOf(DEFAULT_PLATINUM_RATE));\n writeNode(eventWriter, PLATINUM6, String.valueOf(DEFAULT_PLATINUM6_RATE));\n writeChild_Double(eventWriter, RECORD_CRYSTAL, RECORD_CRYSTAL, RATE, DEFAULT_RECORD_CRYSTAL);\n writeChild_Double(eventWriter, CIRCULATING_RECORD_CRYSTAL, CIRCULATING_RECORD_CRYSTAL, RATE, DEFAULT_CIRCULATING_RECORD_CRYSTAL);\n\n /* WRITE CommandSettings END ELEMENT AND CLOSE WRITER */\n eventWriter.add(eventFactory.createEndElement(\"\", \"\", SCOUT_SETTINGS));\n eventWriter.add(end);\n eventWriter.add(eventFactory.createEndDocument());\n eventWriter.close();\n }\n catch (FileNotFoundException | XMLStreamException e)\n {\n e.printStackTrace();\n }\n }\n }\n\n public void saveFile()\n {\n try\n {\n /* INITIALIZE VARIABLES */\n XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();\n XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream(FILE_PATH));\n XMLEventFactory eventFactory = XMLEventFactory.newInstance();\n\n XMLEvent end = eventFactory.createDTD(\"\\n\");\n //XMLEvent tab = eventFactory.createDTD(\"\\t\");\n\n /* WRITE START DOCUMENT ELEMENT */\n StartDocument startDocument = eventFactory.createStartDocument();\n eventWriter.add(startDocument);\n eventWriter.add(end);\n\n /* BEGIN WRITING USER CONFIG, WRITE CommandSettings START ELEMENT */\n StartElement configStartElement = eventFactory.createStartElement(\"\", \"\", SCOUT_SETTINGS);\n eventWriter.add(configStartElement);\n eventWriter.add(end);\n\n writeNode(eventWriter, DISABLE_IMAGES, String.valueOf(isDisableImages));\n writeNode(eventWriter, SIMPLE_MESSAGE, String.valueOf(isSimpleMessage));\n writeNode(eventWriter, RARITY_STARS, String.valueOf(isRarityStars));\n writeNode(eventWriter, SCOUT_MASTER, scoutMaster);\n writeNode(eventWriter, COPPER, String.valueOf(copperRate));\n writeNode(eventWriter, SILVER, String.valueOf(silverRate));\n writeNode(eventWriter, GOLD, String.valueOf(goldRate));\n writeNode(eventWriter, PLATINUM, String.valueOf(platinumRate));\n writeNode(eventWriter, PLATINUM6, String.valueOf(platinum6Rate));\n recordCrystalRates.remove(0);\n writeChild_Double(eventWriter, RECORD_CRYSTAL, RECORD_CRYSTAL, RATE, recordCrystalRates);\n circulatingRecordCrystalRates.remove(0);\n writeChild_Double(eventWriter, CIRCULATING_RECORD_CRYSTAL, CIRCULATING_RECORD_CRYSTAL, RATE, circulatingRecordCrystalRates);\n\n /* WRITE CommandSettings END ELEMENT AND CLOSE WRITER */\n eventWriter.add(eventFactory.createEndElement(\"\", \"\", SCOUT_SETTINGS));\n eventWriter.add(end);\n eventWriter.add(eventFactory.createEndDocument());\n eventWriter.close();\n }\n catch (FileNotFoundException | XMLStreamException e)\n {\n e.printStackTrace();\n }\n }\n}"
] | import discord4j.core.object.entity.Message;
import discord4j.core.object.entity.TextChannel;
import io.github.spugn.Sargo.Managers.CommandManager;
import io.github.spugn.Sargo.Objects.*;
import io.github.spugn.Sargo.Objects.Character;
import io.github.spugn.Sargo.Sargo;
import io.github.spugn.Sargo.Utilities.GitHubImage;
import io.github.spugn.Sargo.XMLParsers.BannerParser;
import io.github.spugn.Sargo.XMLParsers.ScoutSettingsParser;
import java.text.DecimalFormat;
import java.util.*; | package io.github.spugn.Sargo.Functions;
/**
* BANNER INFO
* <p>
* Manages the information in the Embed Messages when
* listing available banners or information about a
* specific banner.
* </p>
*
* @author S'pugn
* @version 2.0
* @since v1.0
* @see BannerListMenu
* @see BannerInfoMenu
*/
public class BannerInfo
{
//private static IChannel CHANNEL;
private TextChannel TEXT_CHANNEL;
private static List<Banner> BANNERS;
private double copper;
private double silver;
private double gold;
private double platinum;
private double platinum6;
private List<Double> recordCrystal;
private List<Double> circulatingRecordCrystal;
private int bannerID;
private int page;
public BannerInfo(Message message, String page)
{
TEXT_CHANNEL = (TextChannel) message.getChannel().block();
/* READ Banners.xml */
BANNERS = BannerParser.getBanners();
this.page = Integer.parseInt(page);
if (this.page < 1)
{
this.page = 1;
}
listBanners();
}
public BannerInfo(Message message, int bannerID)
{
TEXT_CHANNEL = (TextChannel) message.getChannel().block();
this.bannerID = bannerID - 1;
/* READ Banners.xml */
BANNERS = BannerParser.getBanners();
copper = (int) (ScoutSettingsParser.getCopperRate() * 100);
silver = (int) (ScoutSettingsParser.getSilverRate() * 100);
gold = (int) (ScoutSettingsParser.getGoldRate() * 100);
platinum = (int) (ScoutSettingsParser.getPlatinumRate() * 100);
platinum6 = (int) (ScoutSettingsParser.getPlatinum6Rate() * 100);
recordCrystal = ScoutSettingsParser.getRecordCrystalRates();
circulatingRecordCrystal = ScoutSettingsParser.getCirculatingRecordCrystalRates();
getBannerInfo();
}
private void listBanners()
{
BannerListMenu menu = new BannerListMenu();
menu.setBannerCount(BANNERS.size());
int pageLength = 10;
SortedMap<Integer, String> bannerList = new TreeMap<>();
for (Banner b : BANNERS)
{
bannerList.put(b.getBannerID(), b.getBannerName());
}
String message = "";
if (page > (((bannerList.size() % pageLength) == 0) ? bannerList.size() / pageLength : (bannerList.size() / pageLength) + 1))
page = (((bannerList.size() % pageLength) == 0) ? bannerList.size() / pageLength : (bannerList.size() / pageLength) + 1);
menu.setCurrentPage(page);
menu.setHighestPage(((bannerList.size() % pageLength) == 0) ? bannerList.size() / pageLength : (bannerList.size() / pageLength) + 1);
menu.setBannerCount(bannerList.size());
int i = 0, k = 0;
page--;
for(final Map.Entry<Integer, String> e : bannerList.entrySet())
{
k++;
if ((((page * pageLength) + i + 1) == k) && (k != (( page * pageLength) + pageLength + 1)))
{
i++;
message += "**" + e.getKey() + "**) *" + e.getValue() + "*\n";
}
}
menu.setBannerList(message);
Sargo.sendEmbed(TEXT_CHANNEL, menu.get());
}
private void getBannerInfo()
{
if (bannerID < BANNERS.size() && bannerID >= 0)
{
Banner banner = BANNERS.get(bannerID);
BannerInfoMenu menu = new BannerInfoMenu();
Random rng = new Random();
int charIndex = rng.nextInt(banner.getCharacters().size());
menu.setBannerType(banner.bannerTypeToString());
menu.setBannerWepType(banner.getBannerWepType());
menu.setBannerName(banner.getBannerName());
menu.setCharacterAmount(banner.getCharacters().size());
menu.setBannerID(bannerID);
menu.setImageURL(new GitHubImage(banner.getCharacters().get(charIndex).getImagePath()).getURL());
/* CREATE CHARACTER LIST */
String charList = "";
for (Character c : banner.getCharacters())
{
charList += "\n" + c.toString();
}
menu.setCharacterList(charList);
/* IF THERE ARE WEAPONS, CREATE WEAPON LIST */
if (banner.getWeapons().size() > 0)
{
String weapList = "";
for (Weapon w : banner.getWeapons())
{
weapList += "\n" + w.toString();
}
menu.setWeaponAmount(banner.getWeapons().size());
menu.setWeaponList(weapList);
}
/* CREATE RATE LIST */
List<Character> goldCharacters = new ArrayList<>();
List<Character> platinumCharacters = new ArrayList<>();
List<Character> platinum6Characters = new ArrayList<>();
/* SORT GOLD/PLATINUM/PLATINUM6 CHARACTERS AND STORE THEM IN THEIR OWN ARRAYS */
for (Character character : banner.getCharacters())
{
if (character.getRarity() == 4)
{
goldCharacters.add(character);
}
else if (character.getRarity() == 5)
{
platinumCharacters.add(character);
}
else if (character.getRarity() == 6)
{
platinum6Characters.add(character);
}
}
/* NO PLATINUM/PLATINUM6 CHARACTER, ADJUST RATES */
if (platinumCharacters.size() <= 0 && platinum6Characters.size() <= 0)
{
copper += platinum;
platinum = 0;
copper += platinum6;
platinum6 = 0;
}
/* PLATINUM CHARACTERS EXIST BUT NOT PLATINUM6, ADJUST RATES */
else if (platinumCharacters.size() > 0 && platinum6Characters.size() <= 0)
{
copper += platinum6;
platinum6 = 0;
}
/* IF EVENT SCOUT, SET EVERYTHING BUT GOLD TO 0 */
if (banner.getBannerType() == 9)
{
copper = 0.0;
silver = 0.0;
if (goldCharacters.size() > 0)
{
gold = 100.0;
}
else
{
gold = 0.0;
}
if (platinumCharacters.size() > 0)
{
platinum = 100.0;
}
else
{
platinum = 0.0;
}
if (platinum6Characters.size() > 0)
{
platinum6 = 100.0;
}
else
{
platinum6 = 0.0;
}
}
// IF OLDER THAN RECORD CRYSTAL V4 (EXCEPT EVENT), DECREASE PLATINUM RATES BY 1.5
if (banner.getBannerType() == 10 ||
banner.getBannerType() == 8 ||
banner.getBannerType() == 7 ||
banner.getBannerType() == 6 ||
banner.getBannerType() == 5 ||
banner.getBannerType() == 4 ||
banner.getBannerType() == 3 ||
banner.getBannerType() == 2 ||
banner.getBannerType() == 1 ||
banner.getBannerType() == 0)
{
copper = copper + (platinum - (platinum / 1.5));
platinum = platinum / 1.5;
}
String ratesList = "";
if (platinum6 != 0)
ratesList += "[6 ★] " + platinum6 + "%\n";
if (platinum != 0)
ratesList += "[5 ★] " + platinum + "%\n";
ratesList += "[4 ★] " + gold + "%\n";
ratesList += "[3 ★] " + silver + "%\n";
ratesList += "[2 ★] " + copper + "%";
menu.setRatesList(ratesList);
/* BANNER IS STEP UP */
if (banner.getBannerType() == 1)
{
double tC = copper - ((gold * 1.5) - gold);
double tS = silver;
double tG = gold * 1.5;
double tP = platinum;
double tP6 = platinum6;
String stepThreeRates = "";
if (tP6 != 0)
stepThreeRates += "[6 ★] " + tP6 + "%\n";
if (tP != 0)
stepThreeRates += "[5 ★] " + tP + "%\n";
stepThreeRates += "[4 ★] " + tG + "%\n";
stepThreeRates += "[3 ★] " + tS + "%\n";
stepThreeRates += "[2 ★] " + tC + "%\n";
stepThreeRates += "**(4 ★ Scout Rates 1.5x)**";
menu.setStepThreeRatesList(stepThreeRates);
tC = copper - ((gold * 2.0) - gold);
tS = silver;
tG = gold * 2.0;
tP = platinum;
tP6 = platinum6;
String stepFiveRates = "";
if (tP6 != 0)
stepFiveRates += "[6 ★] " + tP6 + "%\n";
if (tP != 0)
stepFiveRates += "[5 ★] " + tP + "%\n";
stepFiveRates += "[4 ★] " + tG + "%\n";
stepFiveRates += "[3 ★] " + tS + "%\n";
stepFiveRates += "[2 ★] " + tC + "%\n";
stepFiveRates += "**(4 ★ Scout Rates 2.0x)**";
menu.setStepFiveRatesList(stepFiveRates);
}
/* BANNER IS STEP UP V2 */
else if (banner.getBannerType() == 3 ||
banner.getBannerType() == 10 ||
banner.getBannerType() == 12 ||
banner.getBannerType() == 13 ||
banner.getBannerType() == 14 ||
banner.getBannerType() == 16)
{
double tC = copper - ((platinum * 1.5) - platinum);
double tS = silver;
double tG = gold;
double tP = platinum * 1.5;
double tP6 = platinum6;
if (banner.getBannerType() == 16)
{
String stepOneRates = "";
if (tP6 != 0)
stepOneRates += "[6 ★] 0.0%\n";
stepOneRates += "[5 ★] 3.0%\n";
stepOneRates += "[4 ★] 97.0%\n";
stepOneRates += "[3 ★] 0.0%\n";
stepOneRates += "[2 ★] 0.0%\n";
stepOneRates += "**(For One Character)**";
menu.setStepOneRatesList(stepOneRates);
}
String stepThreeRates = "";
if (tP6 != 0)
stepThreeRates += "[6 ★] " + tP6 + "%\n";
if (tP != 0)
stepThreeRates += "[5 ★] " + tP + "%\n";
stepThreeRates += "[4 ★] " + tG + "%\n";
stepThreeRates += "[3 ★] " + tS + "%\n";
stepThreeRates += "[2 ★] " + tC + "%\n";
stepThreeRates += "**(5 ★ Scout Rates 1.5x)**";
menu.setStepThreeRatesList(stepThreeRates);
tC = 0.0;
tS = 0.0;
tG = 0.0;
tP = 100.0;
tP6 = 0.0;
String stepFiveRates = "";
if (tP6 != 0)
stepFiveRates += "[6 ★] " + tP6 + "%\n";
stepFiveRates += "[5 ★] " + tP + "%\n";
stepFiveRates += "[4 ★] " + tG + "%\n";
stepFiveRates += "[3 ★] " + tS + "%\n";
stepFiveRates += "[2 ★] " + tC + "%\n";
stepFiveRates += "**(For One Character)**";
menu.setStepFiveRatesList(stepFiveRates);
tC = copper - ((platinum * 2.0) - platinum);
tS = silver;
tG = gold;
tP = platinum * 2.0;
tP6 = platinum6;
String stepSixRates = "";
if (tP6 != 0)
stepSixRates += "[6 ★] " + tP6 + "%\n";
if (tP != 0)
stepSixRates += "[5 ★] " + tP + "%\n";
stepSixRates += "[4 ★] " + tG + "%\n";
stepSixRates += "[3 ★] " + tS + "%\n";
stepSixRates += "[2 ★] " + tC + "%\n";
stepSixRates += "**(5 ★ Scout Rates 2.0x)**";
menu.setStepSixRatesList(stepSixRates);
}
/* BANNER IS STEP UP V7/V8/V9 */
else if (banner.getBannerType() == 17 ||
banner.getBannerType() == 19 ||
banner.getBannerType() == 21)
{
double tC = copper - ((platinum6 * 1.5) - platinum6);
double tS = silver;
double tG = gold;
double tP = platinum;
double tP6 = platinum6 * 1.5;
String stepThreeRates = "";
if (tP6 != 0)
stepThreeRates += "[6 ★] " + tP6 + "%\n";
stepThreeRates += "[5 ★] " + tP + "%\n";
stepThreeRates += "[4 ★] " + tG + "%\n";
stepThreeRates += "[3 ★] " + tS + "%\n";
stepThreeRates += "[2 ★] " + tC + "%\n";
stepThreeRates += "**(6 ★ Scout Rates 1.5x)**";
menu.setStepThreeRatesList(stepThreeRates);
tC = 0.0;
tS = 0.0;
tG = 0.0;
tP = 0.0;
tP6 = 100.0;
String stepFiveRates = "";
stepFiveRates += "[6 ★] " + tP6 + "%\n";
stepFiveRates += "[5 ★] " + tP + "%\n";
stepFiveRates += "[4 ★] " + tG + "%\n";
stepFiveRates += "[3 ★] " + tS + "%\n";
stepFiveRates += "[2 ★] " + tC + "%\n";
if (banner.getBannerType() == 21)
{
stepFiveRates += "**(" + banner.getCharacters().get(0) + " Guaranteed)**";
}
else
{
stepFiveRates += "**(For One Character)**";
}
menu.setStepFiveRatesList(stepFiveRates);
tC = copper - ((platinum6 * 2.0) - platinum6);
tS = silver;
tG = gold;
tP = platinum;
tP6 = platinum6 * 2.0;
String stepSixRates = "";
if (tP6 != 0)
stepSixRates += "[6 ★] " + tP6 + "%\n";
stepSixRates += "[5 ★] " + tP + "%\n";
stepSixRates += "[4 ★] " + tG + "%\n";
stepSixRates += "[3 ★] " + tS + "%\n";
stepSixRates += "[2 ★] " + tC + "%\n";
stepSixRates += "**(6 ★ Scout Rates 2.0x)**";
menu.setStepSixRatesList(stepSixRates);
}
/* BANNER IS BIRTHDAY STEP UP */
else if (banner.getBannerType() == 4)
{
double tC = copper - (((platinum * 2.0) - platinum) + ((gold * 2.0) - gold));
double tS = silver;
double tG = gold * 2.0;
double tP = platinum * 2.0;
double tP6 = platinum6;
String stepThreeRates = "";
if (tP6 != 0)
stepThreeRates += "[6 ★] " + tP6 + "%\n";
if (tP != 0)
stepThreeRates += "[5 ★] " + tP + "%\n";
stepThreeRates += "[4 ★] " + tG + "%\n";
stepThreeRates += "[3 ★] " + tS + "%\n";
stepThreeRates += "[2 ★] " + tC + "%\n";
stepThreeRates += "**(4+ ★ Scout Rates 2.0x)**";
menu.setStepThreeRatesList(stepThreeRates);
}
/* BANNER IS RECORD CRYSTAL */
else if (banner.getBannerType() == 2 ||
banner.getBannerType() == 5 ||
banner.getBannerType() == 8 ||
banner.getBannerType() == 11 ||
banner.getBannerType() == 18 ||
banner.getBannerType() == 20)
{
int counter = 0;
String recordCrystalRates = "";
DecimalFormat df = new DecimalFormat("0.0");
for (double d : recordCrystal)
{
if (d != 0)
{
recordCrystalRates += "[" + ++counter + " RC] " + df.format((d * 100)) + "%\n";
}
}
menu.setRecordCrystalRatesList(recordCrystalRates);
if (banner.getBannerType() == 8 ||
banner.getBannerType() == 11 ||
banner.getBannerType() == 20)
{
int counter2 = 0;
String circluatingRecordCrystalRates = "";
if (banner.getBannerType() == 8 ||
banner.getBannerType() == 11 ||
banner.getBannerType() == 20)
{
for (double d : circulatingRecordCrystal)
{
if (d != 0)
{
circluatingRecordCrystalRates += "[" + ++counter2 + " RC] " + df.format((d * 100)) + "%\n";
}
}
}
else
{
for (double d : recordCrystal)
{
if (d != 0)
{
circluatingRecordCrystalRates += "[" + ++counter2 + " RC] " + df.format((d * 100)) + "%\n";
}
}
}
menu.setCirculatingRecordCrystalRatesList(circluatingRecordCrystalRates);
}
}
/* BANNER IS STEP UP V3 */
else if (banner.getBannerType() == 7 ||
banner.getBannerType() == 15)
{
double tC = copper - ((platinum * 2.0) - platinum);
double tS = silver;
double tG = gold;
double tP = platinum * 2.0;
double tP6 = platinum6;
String stepThreeRates = "";
if (tP6 != 0)
stepThreeRates += "[6 ★] " + tP6 + "%\n";
if (tP != 0)
stepThreeRates += "[5 ★] " + tP + "%\n";
stepThreeRates += "[4 ★] " + tG + "%\n";
stepThreeRates += "[3 ★] " + tS + "%\n";
stepThreeRates += "[2 ★] " + tC + "%\n";
stepThreeRates += "**(5 ★ Scout Rates 2.0x)**";
menu.setStepThreeRatesList(stepThreeRates);
}
/* WEAPON BANNER IS STEP UP */
if (banner.getBannerWepType() == 1)
{
double tC = (copper + platinum) - ((gold * 2.0) - gold);
double tS = silver;
double tG = gold * 2.0;
String stepThreeRates = "";
stepThreeRates += "[4 ★] " + tG + "%\n";
stepThreeRates += "[3 ★] " + tS + "%\n";
stepThreeRates += "[2 ★] " + tC + "%\n";
stepThreeRates += "**(4 ★ Weapon Rates 2.0x)**";
menu.setStepThreeWeaponRatesList(stepThreeRates);
}
/* WEAPON BANNER IS GGO STEP UP OR STEP UP V2 OR STEP UP V3 */
else if (banner.getBannerWepType() == 2 ||
banner.getBannerWepType() == 3 ||
banner.getBannerWepType() == 4)
{
double tC = (copper + platinum) - ((gold * 1.5) - gold);
double tS = silver;
double tG = gold * 1.5;
String stepThreeRates = "";
stepThreeRates += "[4 ★] " + tG + "%\n";
stepThreeRates += "[3 ★] " + tS + "%\n";
stepThreeRates += "[2 ★] " + tC + "%\n";
stepThreeRates += "**(4 ★ Weapon Rates 1.5x)**";
menu.setStepThreeWeaponRatesList(stepThreeRates);
tC = 0.0;
tS = 0.0;
tG = 100.0;
String stepFiveRates = "";
stepFiveRates += "[4 ★] " + tG + "%\n";
stepFiveRates += "[3 ★] " + tS + "%\n";
stepFiveRates += "[2 ★] " + tC + "%\n";
if (banner.getBannerWepType() == 4)
{
stepFiveRates += "**(" + banner.getWeapons().get(0) + " Guaranteed)**";
}
else
{
stepFiveRates += "**(For One Weapon)**";
}
menu.setStepFiveWeaponRatesList(stepFiveRates);
tC = (copper + platinum) - ((gold * 2.0) - gold);
tS = silver;
tG = gold * 2.0;
String stepSixRates = "";
stepSixRates += "[4 ★] " + tG + "%\n";
stepSixRates += "[3 ★] " + tS + "%\n";
stepSixRates += "[2 ★] " + tC + "%\n";
stepSixRates += "**(4 ★ Weapon Rates 2.0x)**";
menu.setStepSixWeaponRatesList(stepSixRates);
}
Sargo.sendEmbed(TEXT_CHANNEL, menu.get());
}
else
{ | Sargo.replyToMessage_Warning(TEXT_CHANNEL, "UNKNOWN BANNER ID", "Use '" + CommandManager.getCommandPrefix() + "**scout**' for a list of banners."); | 0 |
takeshineshiro/android_convex_128 | wireless_scan_B_mode/app/src/main/java/com/medical/lepu/wireless_scan_b_mode/ui/MainActivity.java | [
"public class AppManager {\n\n private static Stack<Activity> activityStack ;\n\n private static AppManager appManager ;\n\n private AppManager () {\n\n\n }\n\n\n public static AppManager getIntance () {\n\n appManager = new AppManager() ;\n\n return appManager ;\n\n }\n\n\n public void addActivity (Activity activity) {\n\n\n if ( activityStack==null) {\n activityStack = new Stack<Activity>() ;\n }\n\n activityStack.add(activity) ;\n }\n\n\n public Activity getCurrentActivity () {\n\n return activityStack.lastElement() ;\n }\n\n\n public void finishCurrentActivity () {\n\n Activity activity = activityStack.lastElement() ;\n\n finishActivity(activity);\n\n }\n\n\n public void finishActivity (Activity activity) {\n\n if ( activity!=null && !activity.isFinishing()) {\n\n activityStack.remove(activity) ;\n\n activity.finish();\n\n activity = null ;\n\n }\n }\n\n\n\n public void finishActivity ( Class<?> cls) {\n\n for (Activity act : activityStack) {\n\n if (act.getClass().equals(cls)) {\n\n finishActivity(act);\n\n break;\n }\n\n\n\n }\n\n\n\n }\n\n\n public Activity getActivity (Class<?> cls) {\n\n if (activityStack != null) {\n\n for (Activity act : activityStack) {\n\n if (act.getClass().equals(cls)) {\n\n return act ;\n\n }\n\n }\n\n\n }\n\n return null ;\n\n\n }\n\n\n\n\n public void finishAllActivity () {\n\n for (int i =0,size=activityStack.size();i<size;i++) {\n if (activityStack.get(i)!=null) {\n\n activityStack.get(i).finish();\n }\n\n\n }\n activityStack.clear();\n\n }\n\n\n public void appExit (Context context) {\n\n try {\n finishAllActivity();\n\n android.os.Process.killProcess(android.os.Process.myPid());\n\n System.exit(0);\n\n\n } catch (Exception e ) {\n\n }\n\n\n\n }\n\n\n\n\n\n\n\n}",
"public class LeftDrawerAdapter extends BaseAdapter {\n\n private Context context ;\n\n private LayoutInflater layoutInflater ;\n\n private int [] submodule_name = {R.string.utrasound_image,R.string.utrasound_video,R.string.utrasound_setting,R.string.utrasound_person};\n\n\n private int[] submodule_pic = {R.drawable.drawer_menu_icon_image,R.drawable.drawer_menu_icon_video,\n\n R.drawable.drawer_menu_icon_setting,R.drawable.drawer_menu_icon_person } ;\n\n\n\n\n\n\n public LeftDrawerAdapter (Context context) {\n\n this.context = context ;\n\n layoutInflater = LayoutInflater.from(context);\n\n }\n\n\n static class ViewHolder {\n\n @Bind(R.id.submodule_image)\n ImageView submoduleImage ;\n\n @Bind(R.id.submodule_title)\n TextView submoduleTitle ;\n\n\n\n\n public ViewHolder(View view) {\n\n ButterKnife.bind(this,view);\n }\n\n\n }\n\n\n @Override\n public int getCount() {\n return submodule_name.length ;\n }\n\n\n @Override\n public Object getItem(int position) {\n return position;\n }\n\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n\n ViewHolder holder = null ;\n\n\n if (convertView == null || convertView.getTag() == null) {\n\n convertView = layoutInflater.inflate(\n R.layout.leftdraweradapter, null);\n\n holder = new ViewHolder(convertView);\n\n convertView.setTag(holder);\n\n } else {\n\n holder = (ViewHolder) convertView.getTag();\n }\n\n holder.submoduleImage.setImageBitmap(readBitMap(context,submodule_pic[position]));\n\n holder.submoduleTitle.setText(submodule_name[position]);\n\n\n\n return convertView ;\n\n }\n\n\n\n\n\n /**\n * 以最省内存的方式读取本地资源的图片\n *\n * @param context\n * @param resId\n * @return\n */\n public static Bitmap readBitMap(Context context, int resId) {\n BitmapFactory.Options opt = new BitmapFactory.Options();\n opt.inPreferredConfig = Bitmap.Config.RGB_565;\n opt.inPurgeable = true;\n opt.inInputShareable = true;\n// 获取资源图片\n InputStream is = context.getResources().openRawResource(resId);\n return BitmapFactory.decodeStream(is, null, opt);\n }\n\n\n @Override\n public View getDropDownView(int position, View convertView, ViewGroup parent) {\n return super.getDropDownView(position, convertView, parent);\n }\n}",
"public class BaseFragment extends Fragment implements android.view.View.OnClickListener,BaseFragmentInterface{\n\n\n protected LayoutInflater baseInflater ;\n\n\n public AppContext getAPPlication () {\n\n\n return (AppContext) getActivity().getApplication();\n\n\n }\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n }\n\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n\n this.baseInflater = inflater ;\n\n return super.onCreateView(inflater, container, savedInstanceState);\n\n }\n\n\n @Override\n public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n\n initData();\n }\n\n\n\n\n protected int getLayoutId() {\n\n return 0 ;\n }\n\n\n protected View inflateView(int resId) {\n return this.baseInflater.inflate(resId,null) ;\n\n }\n\n\n\n\n @Override\n public void initView( View view ) {\n\n }\n\n\n @Override\n public void initData() {\n\n }\n\n\n @Override\n public void onClick(View v) {\n\n }\n}",
"public class UtrasoundImageFrag extends BaseFragment implements SeekBar.OnSeekBarChangeListener,View.OnTouchListener {\n\n private String ssid ; //SSID字符串\n\n private boolean ssidValid ; //获取的SSID为探头的SSID\n\n private boolean socketConnected ; //套接字是否连接(三个套接字均已连接时为YES)\n\n private boolean beRunning ; // 探头是否在运行中\n\n private int sendState ; // 需要发送的运行状态 (-1: 无需要发送状态, 0:冻结状态, 1:运行状态)\n\n private int sendStateCnt ; //发送状态的等待计数\n\n private boolean haveImage ; //图像区是否有图像\n\n private boolean loadedImage ; //有图像的情况下也分为两种情况,一种是载入的图像,一种是重建的图像(回复或者在运行中)\n\n private boolean inCineLoop ; //是否处于回放状态中\n\n private boolean inFullScreen ; //是否处于全屏状态\n\n private double gamaValue ; //图像的gama校正,可以从PREF文件中读取\n\n\n private int probeType ; // 探头类型信息, 可以从PREF文件中读取\n\n private byte curr_gain ; // 探头当前增益\n\n private byte curr_zoom ; // 探头当前的缩放\n\n private byte send_gain ; // 需要下发的增益\n\n private byte send_zoom ; // 需要下发的缩放\n\n private int sales_code; // 探头的销售区域代码\n\n\n private SocketIOClient socket_data ;\n\n\n private SocketIOClient socket_state_control ;\n\n\n private SocketIOClient socket_receive_state ;\n\n\n private boolean data_socket_connected ;\n\n\n private boolean state_socket_connected;\n\n\n private boolean control_socket_connected;\n\n\n private ArrayList image_buffer_array ; //回放图像数据列表\n\n\n private Timer autoLockTimer ; // 自动锁屏定时器\n\n\n private RawImage nullImage ; // 空白图像\n\n private Timer nullImageTimer ;\n\n\n private Image gradientImage ; // 灰度条图像\n\n\n private TextView labelNote ; //提示信息\n\n\n private DecodeFrameUtil decodeFrame ;\n\n\n private ArrayList imageData ;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n @Bind(R.id.main_view)\n View main_view ;\n\n @Bind(R.id.app_start_button)\n ImageButton app_start_button ;\n\n @Bind(R.id.verticalSeekBar)\n VerticalSeekBar verticalSeekBar ;\n\n @Bind(R.id.pic_num)\n TextView picture_num ;\n\n @Bind(R.id.seek_bar)\n SeekBar seekBar ;\n\n @Bind(R.id.pre_button)\n ImageButton pre_button ;\n\n @Bind(R.id.play_button)\n ImageButton play_button ;\n\n @Bind(R.id.next_button)\n ImageButton next_button ;\n\n @Bind(R.id.save_button)\n ImageButton save_button ;\n\n @Bind(R.id.scanner_button)\n ImageButton scanner_button ;\n\n @Bind(R.id.setting_button)\n ImageButton setting_button ;\n\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n }\n\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n\n super.onCreate(savedInstanceState);\n\n initParamSetting() ;\n\n }\n\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n\n super.onCreateView(inflater, container, savedInstanceState);\n\n\n\n View view = inflater.inflate(R.layout.fragment_image_main_layout,container,false) ;\n\n\n ButterKnife.bind(this, view);\n\n\n initView(view);\n\n\n return view ;\n\n\n\n }\n\n\n\n @Override\n public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\n\n super.onViewCreated(view, savedInstanceState);\n\n\n initData();\n\n }\n\n\n @Override\n public void initView(View view) {\n\n\n super.initView(view);\n\n main_view.setOnClickListener(this);\n\n app_start_button.setOnClickListener(new ButtonClickListener());\n\n verticalSeekBar.setOnSeekBarChangeListener(this);\n\n seekBar.setOnSeekBarChangeListener(this);\n\n\n pre_button.setOnClickListener( new ButtonClickListener());\n\n\n play_button.setOnClickListener(new ButtonClickListener());\n\n\n next_button.setOnClickListener(new ButtonClickListener());\n\n\n save_button.setOnClickListener(new ButtonClickListener());\n\n\n scanner_button.setOnClickListener(new ButtonClickListener());\n\n setting_button.setOnClickListener(new ButtonClickListener());\n\n\n }\n\n\n @Override\n public void initData() {\n\n\n super.initData();\n\n ssid = \"\" ;\n\n ssidValid = false ;\n\n socketConnected = false ;\n\n beRunning = false ;\n\n sendState = -1 ;\n\n sendStateCnt = 0 ;\n\n haveImage = false ;\n\n inCineLoop = false ;\n\n inFullScreen = false ;\n\n gamaValue = 1.3 ;\n\n probeType = 0 ;\n\n curr_gain = 0 ;\n\n curr_zoom = 0 ;\n\n send_gain = 0 ;\n\n send_zoom = 0 ;\n\n socket_data = null ;\n\n socket_receive_state = null ;\n\n socket_state_control = null ;\n\n data_socket_connected= false ;\n\n state_socket_connected = false ;\n\n control_socket_connected = false ;\n\n\n image_buffer_array = new ArrayList() ;\n\n\n nullImage = new RawImage() ;\n\n nullImage.probeType = this.probeType ;\n\n nullImage.zoom = this.send_zoom ;\n\n nullImage.gain = this.send_gain ;\n\n nullImage.rawData = null ;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n }\n\n\n\n\n /*读取参数设置中写入到PREF文件中的图像参数设置*/\n private void initParamSetting () {\n\n\n\n\n\n }\n\n\n\n\n\n\n\n\n /*button listener event */\n\n private class ButtonClickListener implements View.OnClickListener\n\n {\n\n @Override\n public void onClick (View v){\n\n }\n\n\n\n }\n\n\n\n\n /*view touch gesture listener event */\n\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n\n\n return false;\n\n\n\n }\n\n\n\n\n /* seekbar listener event */\n\n @Override\n public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {\n\n }\n\n\n @Override\n public void onStartTrackingTouch(SeekBar seekBar) {\n\n }\n\n\n @Override\n public void onStopTrackingTouch(SeekBar seekBar) {\n\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n}",
"public class UtrasoundPersonInfo extends BaseFragment {\n\n\n\n}",
"public class UtrasoundSettingParam extends BaseFragment {\n\n\n\n}",
"public class UtrasoundVideoFrag extends BaseFragment {\n\n\n\n\n\n}"
] | import android.app.FragmentManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.medical.lepu.wireless_scan_b_mode.AppManager;
import com.medical.lepu.wireless_scan_b_mode.R;
import com.medical.lepu.wireless_scan_b_mode.adapter.LeftDrawerAdapter;
import com.medical.lepu.wireless_scan_b_mode.base.BaseFragment;
import com.medical.lepu.wireless_scan_b_mode.fragment.UtrasoundImageFrag;
import com.medical.lepu.wireless_scan_b_mode.fragment.UtrasoundPersonInfo;
import com.medical.lepu.wireless_scan_b_mode.fragment.UtrasoundSettingParam;
import com.medical.lepu.wireless_scan_b_mode.fragment.UtrasoundVideoFrag; | package com.medical.lepu.wireless_scan_b_mode.ui;
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout ;
private Toolbar toolbar ;
private ListView leftListView ;
private ActionBarDrawerToggle actionBarDrawerToggle ;
private CharSequence drawerTitle ;
private CharSequence title ;
private String[] drawer_array ;
private BaseFragment contentFragment ;
public static final String ITEM_POSITION = "item_position" ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
//set the default fragment for the activity content view created
if (savedInstanceState==null) {
selectedItem(0);
}
AppManager.getIntance().addActivity(this);
}
public void initView() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout) ;
toolbar = (Toolbar) findViewById(R.id.toolbar) ;
leftListView = (ListView) findViewById(R.id.left_drawer) ;
setSupportActionBar(toolbar);
// set a custom shadow that overlays the main content when the drawer opens
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
null, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerOpened(View drawerView) {
toolbar.setTitle(drawerTitle);
// getActionBar().setTitle(drawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerClosed(View view) {
toolbar.setTitle(title);
// getActionBar().setTitle(title);
// getSupportActionBar().setTitle(title);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
// enable ActionBar app icon to behave as action to toggle nav drawer
// getActionBar().setHomeButtonEnabled(true);
// getActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_top));
// set up the drawer's list view with items and click listener
leftListView.setAdapter(new LeftDrawerAdapter(this));
leftListView.setOnItemClickListener(new DrawerItemClickListener());
}
public void initData() {
drawer_array = getResources().getStringArray(R.array.drawer_submodules);
drawerTitle = title = getTitle();
}
//listenser
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedItem(position);
}
}
private void selectedItem (int position) {
switch (position) {
case 0:
contentFragment = new UtrasoundImageFrag() ;
break;
case 1:
| contentFragment = new UtrasoundVideoFrag() ; | 6 |
b3dgs/warcraft-remake | warcraft-game/src/main/java/com/b3dgs/warcraft/World.java | [
"public final class Constant\r\n{\r\n /** Application name. */\r\n public static final String PROGRAM_NAME = \"Warcraft Remake\";\r\n /** Application version. */\r\n public static final Version PROGRAM_VERSION = Version.create(0, 0, 7);\r\n /** Native resolution. */\r\n public static final Resolution NATIVE = new Resolution(384, 216, 60);\r\n\r\n /** Debug flag. */\r\n public static final boolean DEBUG = false;\r\n\r\n /** Corpse layer. */\r\n public static final int LAYER_CORPSE = 1;\r\n /** Buildings layer. */\r\n public static final int LAYER_BUILDING = LAYER_CORPSE + 1;\r\n /** Entity layer. */\r\n public static final int LAYER_ENTITY = LAYER_BUILDING + 1;\r\n /** Projectile layer. */\r\n public static final int LAYER_PROJECTILE = LAYER_ENTITY + 1;\r\n /** Explode layer. */\r\n public static final int LAYER_EXPLODE = LAYER_PROJECTILE + 1;\r\n /** Hud layer. */\r\n public static final int LAYER_HUD = LAYER_EXPLODE + 1;\r\n /** Selection layer. */\r\n public static final int LAYER_SELECTION = LAYER_HUD + 1;\r\n\r\n /** Selection render layer. */\r\n public static final int LAYER_SELECTION_RENDER = LAYER_HUD + 1;\r\n /** Hud render layer. */\r\n public static final int LAYER_HUD_RENDER = LAYER_SELECTION_RENDER + 1;\r\n /** Hud menus render layer. */\r\n public static final int LAYER_MENUS_RENDER = LAYER_HUD_RENDER + 1;\r\n\r\n /** Entity info X. */\r\n public static final int ENTITY_INFO_X = 2;\r\n /** Entity info X. */\r\n public static final int ENTITY_INFO_Y = 72;\r\n\r\n /** Minimap horizontal location. */\r\n public static final int MINIMAP_X = 3;\r\n /** Minimap vertical location. */\r\n public static final int MINIMAP_Y = 6;\r\n\r\n /** Tile path category tree. */\r\n public static final String CATEGORY_TREE = \"tree\";\r\n /** Tile number tree cut. */\r\n public static final int TILE_NUM_TREE_CUT = 124;\r\n\r\n /** Sfx attribute separator. */\r\n public static final String SFX_SEPARATOR = \";\";\r\n /** Default volume. */\r\n public static final int VOLUME_DEFAULT = 50;\r\n /** Sound bank id. */\r\n public static final Integer SOUND_BANK_ID = Integer.valueOf(43);\r\n\r\n /** Health percent warning value. */\r\n public static final int HEALTH_PERCENT_WARN = 50;\r\n /** Health percent alert value. */\r\n public static final int HEALTH_PERCENT_ALERT = 25;\r\n\r\n /** Construct phase 1 percent. */\r\n public static final int CONSTRUCT_PERCENT_PHASE1 = 25;\r\n /** Construct phase 2 percent. */\r\n public static final int CONSTRUCT_PERCENT_PHASE2 = 50;\r\n\r\n /** Color camera view. */\r\n public static final ColorRgba COLOR_VIEW = new ColorRgba(200, 200, 200);\r\n /** Color current selection. */\r\n public static final ColorRgba COLOR_SELECTION = new ColorRgba(0, 200, 0);\r\n /** Color allies. */\r\n public static final ColorRgba COLOR_ALLIES = new ColorRgba(0, 200, 0);\r\n /** Color warehouse. */\r\n public static final ColorRgba COLOR_WAREHOUSE = new ColorRgba(200, 200, 0);\r\n /** Color neutral. */\r\n public static final ColorRgba COLOR_NEUTRAL = new ColorRgba(200, 200, 200);\r\n /** Color enemies. */\r\n public static final ColorRgba COLOR_ENEMIES = new ColorRgba(200, 0, 0);\r\n /** Color health good. */\r\n public static final ColorRgba COLOR_HEALTH_GOOD = new ColorRgba(0, 200, 0);\r\n /** Color health warning. */\r\n public static final ColorRgba COLOR_HEALTH_WARN = new ColorRgba(255, 255, 0);\r\n /** Color health alert. */\r\n public static final ColorRgba COLOR_HEALTH_ALERT = new ColorRgba(255, 0, 0);\r\n\r\n /** Wood resource label. */\r\n public static final String HUD_RESOURCE_WOOD = \"LUMBER:\";\r\n /** Gold resource label. */\r\n public static final String HUD_RESOURCE_GOLD = \"GOLD:\";\r\n /** Hud resource curve speed. */\r\n public static final double HUD_CURVE_SPEED = 15.0;\r\n /** Hud resource curve round. */\r\n public static final double HUD_CURVE_ROUND = 10.0;\r\n /** Extract resource description prefix. */\r\n public static final String HUD_ACTION_EXTRACT = \"Harvest\";\r\n /** Carry resource description prefix. */\r\n public static final String HUD_ACTION_CARRY = \"Return\";\r\n\r\n /** Wood type. */\r\n public static final String RESOURCE_WOOD = \"wood\";\r\n /** Gold type. */\r\n public static final String RESOURCE_GOLD = \"gold\";\r\n\r\n /** Cursor id. */\r\n public static final int CURSOR_ID = 0;\r\n /** Cursor id order. */\r\n public static final int CURSOR_ID_ORDER = 1;\r\n /** Cursor id over. */\r\n public static final int CURSOR_ID_OVER = 2;\r\n\r\n /**\r\n * Private constructor.\r\n */\r\n private Constant()\r\n {\r\n throw new LionEngineException(LionEngineException.ERROR_PRIVATE_CONSTRUCTOR);\r\n }\r\n}\r",
"public final class Folder\r\n{\r\n /** Entities folder. */\r\n public static final String ENTITIES = \"entity\";\r\n /** Effects folder. */\r\n public static final String EFFECTS = \"effect\";\r\n /** Items folder. */\r\n public static final String ACTIONS = \"action\";\r\n /** Monsters folder. */\r\n public static final String ORCS = UtilFolder.getPathSeparator(Medias.getSeparator(), ENTITIES, \"orc\");\r\n /** Sceneries folder. */\r\n public static final String HUMANS = UtilFolder.getPathSeparator(Medias.getSeparator(), ENTITIES, \"human\");\r\n /** Players folder. */\r\n public static final String NEUTRAL = UtilFolder.getPathSeparator(Medias.getSeparator(), ENTITIES, \"neutral\");\r\n /** Effects folder. */\r\n public static final String MAPS = \"map\";\r\n /** Fog of war folder. */\r\n public static final String FOG = \"fog\";\r\n /** Levels folder. */\r\n public static final String MENU = \"menu\";\r\n /** Musics folder. */\r\n public static final String MUSICS = \"music\";\r\n /** Sounds folder. */\r\n public static final String SOUNDS = \"sfx\";\r\n\r\n /**\r\n * Private constructor.\r\n */\r\n private Folder()\r\n {\r\n throw new LionEngineException(LionEngineException.ERROR_PRIVATE_CONSTRUCTOR);\r\n }\r\n}\r",
"public enum Gfx\r\n{\r\n /** Game font. */\r\n GAME_FONT(Medias.create(\"font.png\")),\r\n\r\n /** Action background. */\r\n HUD_ACTION_BACKGROUND(Medias.create(\"action_background.png\")),\r\n /** Entity stats. */\r\n HUD_STATS(Medias.create(\"entity_stats.png\")),\r\n /** Progress bar. */\r\n HUD_PROGRESS(Medias.create(\"progress.png\")),\r\n /** Progress bar percent. */\r\n HUD_PROGRESS_PERCENT(Medias.create(\"progress_percent.png\")),\r\n /** Gold resource icon. */\r\n HUD_GOLD(Medias.create(\"gold.png\")),\r\n /** Wood resource icon. */\r\n HUD_WOOD(Medias.create(\"wood.png\")),\r\n\r\n /** Construction progress. */\r\n BUILDING_CONSTRUCTION(Medias.create(Folder.EFFECTS, \"construction.png\")),\r\n /** Burning building. */\r\n BUILDING_BURNING(Medias.create(Folder.EFFECTS, \"burning.png\")),\r\n\r\n /** Fog of war hidden layer. */\r\n FOG_HIDDEN(Medias.create(Folder.FOG, \"hide.png\")),\r\n /** Fog of war fogged layer. */\r\n FOG_FOGGED(Medias.create(Folder.FOG, \"fog.png\"));\r\n\r\n /** Associated resource. */\r\n private Image image;\r\n\r\n /**\r\n * Create gfx.\r\n * \r\n * @param media The media reference.\r\n */\r\n Gfx(Media media)\r\n {\r\n image = Drawable.loadImage(media);\r\n }\r\n\r\n /**\r\n * Get the associated resource.\r\n * \r\n * @return The associated resource.\r\n */\r\n public Resource get()\r\n {\r\n return image;\r\n }\r\n\r\n /**\r\n * Get associated surface.\r\n * \r\n * @return The associated surface.\r\n */\r\n public ImageBuffer getSurface()\r\n {\r\n return image.getSurface();\r\n }\r\n}\r",
"@FeatureInterface\r\npublic class AutoAttack extends FeatureModel implements Routine, Recyclable\r\n{\r\n private static final int CHECK_DELAY = 30;\r\n\r\n private final Tick tick = new Tick();\r\n private final Updatable checker;\r\n\r\n private final Handler handler = services.get(Handler.class);\r\n private final MapTilePath mapPath;\r\n\r\n private boolean force;\r\n\r\n @FeatureGet private Fovable fovable;\r\n @FeatureGet private Attacker attacker;\r\n @FeatureGet private Pathfindable pathfindable;\r\n @FeatureGet private Transformable transformable;\r\n @FeatureGet private StateHandler state;\r\n @FeatureGet private EntityStats stats;\r\n\r\n /**\r\n * Create feature.\r\n * \r\n * @param services The services reference.\r\n * @param setup The setup reference.\r\n */\r\n public AutoAttack(Services services, Setup setup)\r\n {\r\n super(services, setup);\r\n\r\n final MapTile map = services.get(MapTile.class);\r\n mapPath = map.getFeature(MapTilePath.class);\r\n checker = extrp ->\r\n {\r\n tick.update(extrp);\r\n if (canAutoAttack())\r\n {\r\n final Transformable target = findTarget();\r\n if (target != null\r\n && (Util.getDistanceInTile(map, transformable, target) < 1.5\r\n || pathfindable.setDestination(target)))\r\n {\r\n attacker.attack(target);\r\n }\r\n tick.restart();\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * Set force attack flag.\r\n * \r\n * @param force <code>true</code> to force checking, <code>false</code> else.\r\n */\r\n public void setForce(boolean force)\r\n {\r\n this.force = force;\r\n }\r\n\r\n /**\r\n * Check if can auto attack.\r\n * \r\n * @return <code>true</code> if can auto attack, <code>false</code> else.\r\n */\r\n private boolean canAutoAttack()\r\n {\r\n return tick.elapsed(CHECK_DELAY)\r\n && stats.getHealthPercent() > 0\r\n && (force || !pathfindable.isMoving())\r\n && (attacker.getTarget() == null\r\n || attacker.getTarget().getFeature(EntityStats.class).getHealthPercent() == 0);\r\n }\r\n\r\n /**\r\n * Find closest target on sight.\r\n * \r\n * @return The target found, <code>null</code> if none.\r\n */\r\n private Transformable findTarget()\r\n {\r\n int ray = 1;\r\n while (ray < fovable.getInTileFov())\r\n {\r\n final Transformable transformable = findTarget(ray);\r\n if (transformable != null)\r\n {\r\n return transformable;\r\n }\r\n ray++;\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Find closest target with the specified ray search.\r\n * \r\n * @param ray The ray search.\r\n * @return The target found, <code>null</code> if none.\r\n */\r\n private Transformable findTarget(int ray)\r\n {\r\n for (int ox = -ray; ox <= ray; ox++)\r\n {\r\n for (int oy = -ray; oy <= ray; oy++)\r\n {\r\n final Transformable target = findTarget(ox, oy);\r\n if (target != null)\r\n {\r\n return target;\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Find closest target on location.\r\n * \r\n * @param ox The horizontal location offset.\r\n * @param oy The vertical location offset.\r\n * @return The target found, <code>null</code> if none.\r\n */\r\n private Transformable findTarget(int ox, int oy)\r\n {\r\n final int tx = pathfindable.getInTileX();\r\n final int ty = pathfindable.getInTileY();\r\n if (ox != 0 && oy != 0)\r\n {\r\n for (final Integer id : mapPath.getObjectsId(tx + ox, ty + oy))\r\n {\r\n final Featurable featurable = handler.get(id);\r\n final EntityStats statsTarget = featurable.getFeature(EntityStats.class);\r\n final Race race = statsTarget.getRace();\r\n if (!race.equals(Race.NEUTRAL) && !stats.getRace().equals(race) && statsTarget.getHealthPercent() > 0)\r\n {\r\n return featurable.getFeature(Transformable.class);\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n @Override\r\n public void update(double extrp)\r\n {\r\n checker.update(extrp);\r\n }\r\n\r\n @Override\r\n public void recycle()\r\n {\r\n force = false;\r\n tick.restart();\r\n }\r\n}\r",
"@FeatureInterface\r\npublic class Warehouse extends FeatureModel implements Tiled\r\n{\r\n @FeatureGet private Pathfindable pathfindable;\r\n\r\n /**\r\n * Create warehouse.\r\n * \r\n * @param services The services reference.\r\n * @param setup The setup reference.\r\n */\r\n public Warehouse(Services services, Setup setup)\r\n {\r\n super(services, setup);\r\n }\r\n\r\n @Override\r\n public int getInTileX()\r\n {\r\n return pathfindable.getInTileX();\r\n }\r\n\r\n @Override\r\n public int getInTileY()\r\n {\r\n return pathfindable.getInTileY();\r\n }\r\n\r\n @Override\r\n public int getInTileWidth()\r\n {\r\n return pathfindable.getInTileWidth();\r\n }\r\n\r\n @Override\r\n public int getInTileHeight()\r\n {\r\n return pathfindable.getInTileHeight();\r\n }\r\n}\r",
"public class WorldMinimap implements Resource, Renderable\r\n{\r\n private final Camera camera;\r\n private final MapTile map;\r\n private final Handler handler;\r\n private final Player player;\r\n private final Minimap minimap;\r\n private final FogOfWar fogOfWar;\r\n private ImageBuffer buffer;\r\n\r\n /**\r\n * Create the world.\r\n * \r\n * @param services The services reference.\r\n */\r\n public WorldMinimap(Services services)\r\n {\r\n super();\r\n\r\n camera = services.get(Camera.class);\r\n map = services.get(MapTile.class);\r\n handler = services.get(Handler.class);\r\n player = services.get(Player.class);\r\n fogOfWar = services.get(FogOfWar.class);\r\n\r\n minimap = new Minimap(map);\r\n }\r\n\r\n /**\r\n * Draw entities.\r\n * \r\n * @param g The graphic output.\r\n */\r\n private void drawEntities(Graphic g)\r\n {\r\n for (final EntityStats entity : handler.get(EntityStats.class))\r\n {\r\n final Pathfindable pathfindable = entity.getFeature(Pathfindable.class);\r\n if (entity.getHealthPercent() > 0\r\n && entity.getFeature(EntityModel.class).isVisible()\r\n && fogOfWar.isVisible(pathfindable))\r\n {\r\n drawEntity(g, pathfindable, entity);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Draw entity.\r\n * \r\n * @param g The graphic output.\r\n * @param entity The entity reference.\r\n * @param stats The stats reference.\r\n */\r\n private void drawEntity(Graphic g, Pathfindable entity, EntityStats stats)\r\n {\r\n if (player.owns(entity) && entity.hasFeature(Warehouse.class))\r\n {\r\n g.setColor(Constant.COLOR_WAREHOUSE);\r\n }\r\n else\r\n {\r\n g.setColor(player.getColor(entity));\r\n }\r\n g.drawRect(getX(entity.getInTileX()),\r\n getY(entity.getInTileY(), entity.getInTileHeight()),\r\n entity.getInTileWidth(),\r\n entity.getInTileHeight(),\r\n true);\r\n }\r\n\r\n /**\r\n * Draw field of view.\r\n * \r\n * @param g The graphic output.\r\n */\r\n private void drawFov(Graphic g)\r\n {\r\n g.setColor(Constant.COLOR_VIEW);\r\n camera.drawFov(g, Constant.MINIMAP_X, Constant.MINIMAP_Y, map.getTileWidth(), map.getTileHeight(), minimap);\r\n }\r\n\r\n /**\r\n * Get horizontal on minimap.\r\n * \r\n * @param tx The location in tile to get.\r\n * @return The location on minimap.\r\n */\r\n private int getX(int tx)\r\n {\r\n return Constant.MINIMAP_X + tx;\r\n }\r\n\r\n /**\r\n * Get vertical on minimap.\r\n * \r\n * @param ty The location in tile to get.\r\n * @param th The height.\r\n * @return The location on minimap.\r\n */\r\n private int getY(int ty, int th)\r\n {\r\n return Constant.MINIMAP_Y - ty + map.getInTileHeight() - th;\r\n }\r\n\r\n @Override\r\n public void render(Graphic g)\r\n {\r\n minimap.render(g);\r\n g.drawImage(buffer, Constant.MINIMAP_X, Constant.MINIMAP_Y);\r\n drawEntities(g);\r\n drawFov(g);\r\n }\r\n\r\n @Override\r\n public void load()\r\n {\r\n minimap.load();\r\n minimap.automaticColor();\r\n minimap.prepare();\r\n minimap.setLocation(Constant.MINIMAP_X, Constant.MINIMAP_Y);\r\n\r\n buffer = Graphics.createImageBuffer(map.getInTileWidth(), map.getInTileHeight(), ColorRgba.BLACK);\r\n final Graphic g = buffer.createGraphic();\r\n g.setColor(ColorRgba.BLACK);\r\n g.drawRect(0, 0, buffer.getWidth(), buffer.getHeight(), true);\r\n g.dispose();\r\n\r\n fogOfWar.addListener((tx, ty) -> buffer.setRgb(tx, map.getInTileHeight() - ty - 1, 0));\r\n }\r\n\r\n @Override\r\n public boolean isLoaded()\r\n {\r\n return minimap.isLoaded();\r\n }\r\n\r\n @Override\r\n public void dispose()\r\n {\r\n minimap.dispose();\r\n }\r\n}\r",
"public class WorldNavigator implements Updatable\r\n{\r\n private static final int NAVIGATION_TICK = 3;\r\n\r\n private final Tick navigationDelay = new Tick();\r\n\r\n private final Camera camera;\r\n private final Cursor cursor;\r\n private final DeviceController device;\r\n private final Handler handler;\r\n private final MapTile map;\r\n private final MapTilePath mapPath;\r\n private final FogOfWar fogOfWar;\r\n private final Selector selector;\r\n private final SelectorModel selectorModel;\r\n\r\n private boolean selectorEnabled;\r\n private boolean selectorBackup;\r\n\r\n /**\r\n * Create the navigator.\r\n * \r\n * @param services The services reference.\r\n */\r\n public WorldNavigator(Services services)\r\n {\r\n super();\r\n\r\n camera = services.get(Camera.class);\r\n cursor = services.get(Cursor.class);\r\n device = services.get(DeviceController.class);\r\n handler = services.get(Handler.class);\r\n map = services.get(MapTile.class);\r\n mapPath = map.getFeature(MapTilePath.class);\r\n fogOfWar = map.getFeature(FogOfWar.class);\r\n selector = services.get(Selector.class);\r\n\r\n selectorModel = selector.getFeature(SelectorModel.class);\r\n selectorEnabled = selectorModel.isEnabled();\r\n navigationDelay.start();\r\n }\r\n\r\n /**\r\n * Update map navigation with pointer device.\r\n * \r\n * @param extrp The extrapolation value.\r\n */\r\n private void updateNavigationPointer(double extrp)\r\n {\r\n if (cursor.isPushed())\r\n {\r\n final int h = camera.getViewY() + camera.getHeight();\r\n final int marginY = map.getTileHeight() / 2;\r\n\r\n if (UtilMath.isBetween(cursor.getScreenY(), h - marginY, h))\r\n {\r\n camera.moveLocation(extrp, 0, -map.getTileHeight());\r\n }\r\n else if (UtilMath.isBetween(cursor.getScreenY(), camera.getViewY(), camera.getViewY() + marginY))\r\n {\r\n camera.moveLocation(extrp, 0, map.getTileHeight());\r\n }\r\n\r\n final int w = camera.getViewX() + camera.getWidth();\r\n final int marginX = map.getTileWidth() / 2;\r\n\r\n if (UtilMath.isBetween(cursor.getScreenX(), camera.getViewX(), camera.getViewX() + marginX))\r\n {\r\n camera.moveLocation(extrp, -map.getTileWidth(), 0);\r\n }\r\n else if (UtilMath.isBetween(cursor.getScreenX(), w - marginX, w))\r\n {\r\n camera.moveLocation(extrp, map.getTileWidth(), 0);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Update map navigation with minimap.\r\n * \r\n * @param extrp The extrapolation value.\r\n */\r\n private void updateNavigationMinimap(double extrp)\r\n {\r\n if (!selectorModel.isSelecting()\r\n && cursor.isPushed()\r\n && UtilMath.isBetween(cursor.getScreenX(), Constant.MINIMAP_X, Constant.MINIMAP_X + map.getInTileWidth())\r\n && UtilMath.isBetween(cursor.getScreenY(), Constant.MINIMAP_Y, Constant.MINIMAP_Y + map.getInTileHeight()))\r\n {\r\n final double x = (cursor.getScreenX() - Constant.MINIMAP_X) * map.getTileWidth();\r\n final double y = (map.getInTileHeight() + Constant.MINIMAP_Y - cursor.getScreenY()) * map.getTileHeight();\r\n camera.setLocation(UtilMath.getRounded(x - camera.getWidth() / 2.0, map.getTileWidth()),\r\n UtilMath.getRounded(y - camera.getHeight() / 2.0, map.getTileHeight()));\r\n\r\n if (!selectorBackup)\r\n {\r\n selectorBackup = true;\r\n selectorEnabled = selectorModel.isEnabled();\r\n selectorModel.setEnabled(false);\r\n }\r\n }\r\n else if (selectorBackup)\r\n {\r\n selectorBackup = false;\r\n selectorModel.setEnabled(selectorEnabled);\r\n }\r\n }\r\n\r\n /**\r\n * Check if cursor is inside map view.\r\n * \r\n * @return <code>true</code> if over map, <code>false</code> on Hud.\r\n */\r\n private boolean isCursorOverMap()\r\n {\r\n return UtilMath.isBetween(cursor.getScreenX(), camera.getViewX(), camera.getViewX() + camera.getWidth() - 8)\r\n && UtilMath.isBetween(cursor.getScreenY(),\r\n camera.getViewY(),\r\n camera.getViewY() + camera.getHeight() - 16);\r\n }\r\n\r\n @Override\r\n public void update(double extrp)\r\n {\r\n navigationDelay.update(extrp);\r\n\r\n if (navigationDelay.elapsed(NAVIGATION_TICK))\r\n {\r\n updateNavigationPointer(extrp);\r\n camera.moveLocation(extrp,\r\n device.getHorizontalDirection() * map.getTileWidth(),\r\n device.getVerticalDirection() * map.getTileHeight());\r\n navigationDelay.restart();\r\n }\r\n\r\n updateNavigationMinimap(extrp);\r\n updateCursorOver();\r\n\r\n if (isCursorOverMap() && cursor.isPushedOnce(DeviceMapping.ACTION_RIGHT))\r\n {\r\n final int marginX = map.getTileWidth() / 2;\r\n final int marginY = map.getTileHeight() / 2;\r\n if (UtilMath.isBetween(cursor.getScreenX(),\r\n camera.getViewX() + marginX,\r\n camera.getViewX() + camera.getWidth() - marginX)\r\n && UtilMath.isBetween(cursor.getScreenY(),\r\n camera.getViewY() + marginX,\r\n camera.getViewY() + camera.getHeight() - marginY))\r\n {\r\n checkRightClick();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Update cursor if over entity.\r\n */\r\n private void updateCursorOver()\r\n {\r\n if (cursor.getSurfaceId().intValue() != Constant.CURSOR_ID_ORDER)\r\n {\r\n final int tx = map.getInTileX(cursor);\r\n final int ty = map.getInTileY(cursor);\r\n\r\n if (!cursor.isPushed() && fogOfWar.isVisited(tx, ty) && !fogOfWar.isFogged(tx, ty) && isValidEntity(tx, ty))\r\n {\r\n cursor.setRenderingOffset(-5, -5);\r\n cursor.setSurfaceId(Constant.CURSOR_ID_OVER);\r\n }\r\n else\r\n {\r\n cursor.setRenderingOffset(0, 0);\r\n cursor.setSurfaceId(Constant.CURSOR_ID);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Check if pointing valid entity.\r\n * \r\n * @param tx The horizontal tile pointed.\r\n * @param ty The vertical tile pointed.\r\n * @return <code>true</code> if valid over, <code>false</code> else.\r\n */\r\n private boolean isValidEntity(int tx, int ty)\r\n {\r\n for (final Integer id : mapPath.getObjectsId(tx, ty))\r\n {\r\n final Featurable featurable = handler.get(id);\r\n if (featurable.getFeature(EntityStats.class).getHealthPercent() > 0\r\n && featurable.getFeature(EntityModel.class).isVisible())\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Check right click shortcut action.\r\n */\r\n private void checkRightClick()\r\n {\r\n final List<Selectable> selection = selector.getSelection();\r\n final int n = selection.size();\r\n for (int i = 0; i < n; i++)\r\n {\r\n final Selectable selectable = selection.get(i);\r\n if (selectable.hasFeature(RightClickHandler.class))\r\n {\r\n selectable.getFeature(RightClickHandler.class).execute();\r\n }\r\n }\r\n }\r\n}\r",
"public class WorldSelection\r\n{\r\n private static void switchExtractCarry(List<Selectable> selection, Actionable actionable)\r\n {\r\n for (final Selectable selectable : selection)\r\n {\r\n final boolean carry = selectable.getFeature(EntityModel.class).getCarryResource() != null;\r\n Util.switchExtractCarryAction(actionable, carry);\r\n }\r\n }\r\n\r\n private final AtomicReference<Race> race = new AtomicReference<>();\r\n private final AtomicBoolean moving = new AtomicBoolean();\r\n\r\n private final Player player;\r\n private final Hud hud;\r\n private final FogOfWar fogOfWar;\r\n\r\n /**\r\n * Create the world.\r\n * \r\n * @param services The services reference.\r\n */\r\n public WorldSelection(Services services)\r\n {\r\n super();\r\n\r\n player = services.get(Player.class);\r\n hud = services.get(Hud.class);\r\n fogOfWar = services.get(FogOfWar.class);\r\n\r\n final Selector selector = services.get(Selector.class);\r\n selector.addListener(new SelectionListener()\r\n {\r\n @Override\r\n public void notifySelectionStarted()\r\n {\r\n race.set(null);\r\n moving.set(false);\r\n }\r\n\r\n @Override\r\n public void notifySelected(List<Selectable> selection)\r\n {\r\n clearMenuIfNotOwned(selection);\r\n }\r\n });\r\n selector.setAccept(createFilter());\r\n\r\n final Cursor cursor = services.get(Cursor.class);\r\n hud.addListener(new HudListener()\r\n {\r\n @Override\r\n public void notifyCreated(List<Selectable> selection, Actionable actionable)\r\n {\r\n if (actionable.getFeature(Locker.class).isLocked(player))\r\n {\r\n actionable.setEnabled(false);\r\n }\r\n else\r\n {\r\n switchExtractCarry(selection, actionable);\r\n }\r\n }\r\n\r\n @Override\r\n public void notifyCanceled()\r\n {\r\n cursor.setVisible(true);\r\n cursor.setSurfaceId(0);\r\n selector.setEnabled(true);\r\n hud.setCancelShortcut(() -> false);\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Reset selection state.\r\n */\r\n public void reset()\r\n {\r\n race.set(null);\r\n moving.set(false);\r\n }\r\n\r\n private void clearMenuIfNotOwned(List<Selectable> selected)\r\n {\r\n for (final Selectable current : selected)\r\n {\r\n if (!player.owns(current))\r\n {\r\n hud.clearMenus();\r\n break;\r\n }\r\n }\r\n }\r\n\r\n private BiPredicate<List<Selectable>, Selectable> createFilter()\r\n {\r\n return (selected, selectable) ->\r\n {\r\n if (!selectable.hasFeature(EntityStats.class))\r\n {\r\n return false;\r\n }\r\n final EntityStats entity = selectable.getFeature(EntityStats.class);\r\n final Race current = entity.getRace();\r\n\r\n if (Race.NEUTRAL.equals(race.get()) && !Race.NEUTRAL.equals(current) || !moving.get())\r\n {\r\n clearSelectedIfNextIsOwned(selected);\r\n if (Race.NEUTRAL.equals(race.get()) && !Race.NEUTRAL.equals(current))\r\n {\r\n race.set(current);\r\n }\r\n }\r\n\r\n final boolean mover = entity.isMover();\r\n if (mover)\r\n {\r\n moving.set(true);\r\n }\r\n\r\n if (isInvalid(entity, mover))\r\n {\r\n return false;\r\n }\r\n\r\n return race.compareAndSet(null, current) || current.equals(race.get()) && !Race.NEUTRAL.equals(current);\r\n };\r\n }\r\n\r\n private void clearSelectedIfNextIsOwned(List<Selectable> selected)\r\n {\r\n for (final Selectable old : selected)\r\n {\r\n old.onSelection(false);\r\n }\r\n selected.clear();\r\n }\r\n\r\n private boolean isInvalid(EntityStats entity, boolean mover)\r\n {\r\n return entity.getHealthPercent() == 0\r\n || moving.get() && !mover\r\n || !player.owns(entity) && race.get() != null\r\n || !entity.getFeature(EntityModel.class).isVisible()\r\n || !fogOfWar.isVisible(entity.getFeature(Pathfindable.class));\r\n }\r\n}\r"
] | import java.io.IOException;
import com.b3dgs.lionengine.Align;
import com.b3dgs.lionengine.LionEngineException;
import com.b3dgs.lionengine.Medias;
import com.b3dgs.lionengine.Tick;
import com.b3dgs.lionengine.audio.Audio;
import com.b3dgs.lionengine.audio.AudioFactory;
import com.b3dgs.lionengine.game.Cursor;
import com.b3dgs.lionengine.game.feature.Featurable;
import com.b3dgs.lionengine.game.feature.LayerableModel;
import com.b3dgs.lionengine.game.feature.Services;
import com.b3dgs.lionengine.game.feature.Transformable;
import com.b3dgs.lionengine.game.feature.collidable.selector.Hud;
import com.b3dgs.lionengine.game.feature.collidable.selector.Selector;
import com.b3dgs.lionengine.game.feature.producible.Producer;
import com.b3dgs.lionengine.game.feature.producible.ProducerListenerVoid;
import com.b3dgs.lionengine.game.feature.tile.map.extractable.Extractor;
import com.b3dgs.lionengine.game.feature.tile.map.pathfinding.Pathfindable;
import com.b3dgs.lionengine.game.feature.tile.map.persister.MapTilePersister;
import com.b3dgs.lionengine.geom.Area;
import com.b3dgs.lionengine.geom.Geom;
import com.b3dgs.lionengine.graphic.Graphic;
import com.b3dgs.lionengine.graphic.drawable.Drawable;
import com.b3dgs.lionengine.graphic.drawable.Image;
import com.b3dgs.lionengine.graphic.drawable.SpriteFont;
import com.b3dgs.lionengine.helper.DeviceControllerConfig;
import com.b3dgs.lionengine.helper.WorldHelper;
import com.b3dgs.lionengine.io.DeviceController;
import com.b3dgs.lionengine.io.DevicePointer;
import com.b3dgs.lionengine.io.FileReading;
import com.b3dgs.warcraft.constant.Constant;
import com.b3dgs.warcraft.constant.Folder;
import com.b3dgs.warcraft.constant.Gfx;
import com.b3dgs.warcraft.object.feature.AutoAttack;
import com.b3dgs.warcraft.object.feature.Warehouse;
import com.b3dgs.warcraft.world.WorldMinimap;
import com.b3dgs.warcraft.world.WorldNavigator;
import com.b3dgs.warcraft.world.WorldSelection;
| /*
* Copyright (C) 2013-2022 Byron 3D Games Studio (www.b3dgs.com) Pierre-Alexandre ([email protected])
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.b3dgs.warcraft;
/**
* World game representation.
*/
public class World extends WorldHelper
{
private static final int VIEW_X = 72;
private static final int VIEW_Y = 12;
private static final int TEXT_X = 74;
private static final int TEXT_Y = 209;
private static final int RESOURCES_WOOD_X = 180;
private static final int RESOURCES_GOLD_X = 290;
private static final int RESOURCES_Y = 2;
private static final Area AREA = Geom.createArea(VIEW_X, VIEW_Y, 304, 192);
private static final int DELAY_ATTACK = 6000;
private final Player player = services.add(new Player(Race.ORC));
private final WorldMinimap minimap = new WorldMinimap(services);
private final Cursor cursor = services.create(Cursor.class);
private final Image wood = Util.getImage(Gfx.HUD_WOOD, RESOURCES_WOOD_X + 10, RESOURCES_Y - 2);
private final Image gold = Util.getImage(Gfx.HUD_GOLD, RESOURCES_GOLD_X + 10, RESOURCES_Y - 1);
private final SpriteFont text;
private final WorldNavigator navigator;
private final WorldSelection selection;
private final DeviceController device = services.add(DeviceControllerConfig.create(services,
Medias.create("input.xml")));
private final DeviceController deviceCursor = DeviceControllerConfig.create(services,
Medias.create("input_cursor.xml"));
private final Tick tick = new Tick();
private Audio music;
/**
* Create the world.
*
* @param services The services reference.
*/
public World(Services services)
{
super(services);
services.add(new ProduceProgress());
camera.setView(VIEW_X, VIEW_Y, AREA.getWidth(), AREA.getHeight(), AREA.getHeight());
text = services.add(Drawable.loadSpriteFont(Gfx.GAME_FONT.getSurface(), Medias.create("font.xml"), 6, 6));
text.setLocation(TEXT_X, TEXT_Y);
final Hud hud = services.add(factory.create(Medias.create("hud.xml")));
handler.add(hud);
final Selector selector = services.get(Selector.class);
selector.addFeatureAndGet(new LayerableModel(Constant.LAYER_SELECTION, Constant.LAYER_SELECTION_RENDER));
selector.setClickableArea(AREA);
selector.setSelectionColor(Constant.COLOR_SELECTION);
selector.setClickSelection(DeviceMapping.ACTION_LEFT.getIndex());
navigator = new WorldNavigator(services);
selection = new WorldSelection(services);
}
@Override
protected void loading(FileReading file) throws IOException
{
map.loadSheets(Medias.create(Folder.MAPS, WorldType.FOREST.getFolder(), "sheets.xml"));
map.getFeature(MapTilePersister.class).load(file);
minimap.load();
selection.reset();
cursor.addImage(Constant.CURSOR_ID, Medias.create("cursor.png"));
cursor.addImage(Constant.CURSOR_ID_ORDER, Medias.create("cursor_order.png"));
cursor.addImage(Constant.CURSOR_ID_OVER, Medias.create("cursor_over.png"));
cursor.load();
cursor.setGrid(map.getTileWidth(), map.getTileHeight());
cursor.setInputDevice(deviceCursor);
cursor.setSync((DevicePointer) getInputDevice(DeviceControllerConfig.imports(services,
Medias.create("input_cursor.xml"))
.iterator()
.next()
.getDevice()));
cursor.setViewer(camera);
createAi(Race.HUMAN, 8, 56);
createPlayer(Race.ORC, 46, 14);
spawn(Race.ORC, Unit.SPEARMAN, 50, 20);
music = AudioFactory.loadAudio(Music.ORC_CAMPAIGN2.get());
music.setVolume(Constant.VOLUME_DEFAULT);
music.play();
}
/**
* Create player base.
*
* @param race The race reference.
* @param tx The horizontal tile base.
* @param ty The vertical tile base.
*/
private void createPlayer(Race race, int tx, int ty)
{
spawn(Race.NEUTRAL, Unit.GOLDMINE, tx - 6, ty - 8);
spawn(race, Unit.WORKER, tx, ty - 2);
final Transformable townhall = spawn(race, Unit.TOWNHALL, tx, ty);
camera.center(townhall);
camera.round(map);
player.increaseFood(1);
player.consumeFood();
}
/**
* Create AI base.
*
* @param race The race reference.
* @param tx The horizontal tile base.
* @param ty The vertical tile base.
*/
private void createAi(Race race, int tx, int ty)
{
final Pathfindable goldmine = spawn(Race.NEUTRAL, Unit.GOLDMINE, tx - 6, ty - 8).getFeature(Pathfindable.class);
spawn(race, Unit.TOWNHALL, tx, ty);
final Extractor extractorWood = spawn(race, Unit.WORKER, tx, ty - 2).getFeature(Extractor.class);
extractorWood.setResource(Constant.RESOURCE_WOOD, tx - 2, ty + 5, 1, 1);
extractorWood.startExtraction();
final Extractor extractorGold = spawn(race, Unit.WORKER, tx, ty - 2).getFeature(Extractor.class);
extractorGold.setResource(Constant.RESOURCE_GOLD, goldmine);
extractorGold.startExtraction();
spawn(race, Unit.FARM, tx - 4, ty - 1);
spawn(race, Unit.FARM, tx - 6, ty - 1);
spawn(race, Unit.LUMBERMILL, tx + 6, ty - 4);
final Producer barracks = spawn(race, Unit.BARRACKS, tx + 6, ty + 1).getFeature(Producer.class);
barracks.addListener(new ProducerListenerVoid()
{
@Override
public void notifyProduced(Featurable featurable)
{
featurable.getFeature(AutoAttack.class).setForce(true);
| final Warehouse warehouse = Util.getWarehouse(services, player.getRace());
| 4 |
kevalpatel2106/smart-lens | app/src/main/java/com/kevalpatel2106/smartlens/camera/CameraConfig.java | [
"public final class CameraFacing {\n\n /**\n * Rear facing camera id.\n *\n * @see android.hardware.Camera.CameraInfo#CAMERA_FACING_BACK\n */\n public static final int REAR_FACING_CAMERA = 0;\n /**\n * Front facing camera id.\n *\n * @see android.hardware.Camera.CameraInfo#CAMERA_FACING_FRONT\n */\n public static final int FRONT_FACING_CAMERA = 1;\n\n private CameraFacing() {\n throw new RuntimeException(\"Cannot initialize this class.\");\n }\n\n @Retention(RetentionPolicy.SOURCE)\n @IntDef({REAR_FACING_CAMERA, FRONT_FACING_CAMERA})\n public @interface SupportedCameraFacing {\n }\n}",
"@SuppressWarnings(\"WeakerAccess\")\npublic final class CameraImageFormat {\n\n /**\n * Image format for .jpg/.jpeg.\n */\n public static final int FORMAT_JPEG = 849;\n /**\n * Image format for .png.\n */\n public static final int FORMAT_PNG = 545;\n /**\n * Image format for .png.\n */\n public static final int FORMAT_WEBP = 563;\n\n private CameraImageFormat() {\n throw new RuntimeException(\"Cannot initialize CameraImageFormat.\");\n }\n\n @Retention(RetentionPolicy.SOURCE)\n @IntDef({FORMAT_JPEG, FORMAT_PNG, FORMAT_WEBP})\n public @interface SupportedImageFormat {\n }\n}",
"@SuppressWarnings(\"WeakerAccess\")\npublic final class CameraResolution {\n\n /**\n * This will capture the image at the highest possible resolution. That means if the camera sensor\n * is of 13MP, output image will have resolution of 13MP.\n */\n public static final int HIGH_RESOLUTION = 2006;\n /**\n * This will capture the image at the medium resolution. That means if the camera sensor\n * is of 13MP, it will take image with resolution that is exact middle of the supported camera\n * resolutions ({@link Camera.Parameters#getSupportedPictureSizes()}).\n */\n public static final int MEDIUM_RESOLUTION = 7895;\n /**\n * This will capture the image at the lowest possible resolution. That means if the camera sensor\n * supports minimum 2MP, output image will have resolution of 2MP.\n */\n public static final int LOW_RESOLUTION = 7821;\n\n private CameraResolution() {\n throw new RuntimeException(\"Cannot initiate CameraResolution.\");\n }\n\n @Retention(RetentionPolicy.SOURCE)\n @IntDef({HIGH_RESOLUTION, MEDIUM_RESOLUTION, LOW_RESOLUTION})\n public @interface SupportedResolution {\n }\n}",
"public final class CameraRotation {\n\n /**\n * Rotate image by 90 degrees.\n */\n public static final int ROTATION_90 = 90;\n /**\n * Rotate image by 180 degrees.\n */\n public static final int ROTATION_180 = 180;\n /**\n * Rotate image by 270 (or -90) degrees.\n */\n public static final int ROTATION_270 = 270;\n /**\n * Don't rotate the image.\n */\n public static final int ROTATION_0 = 0;\n\n private CameraRotation() {\n throw new RuntimeException(\"Cannot initialize this class.\");\n }\n\n @Retention(RetentionPolicy.SOURCE)\n @IntDef({ROTATION_0, ROTATION_90, ROTATION_180, ROTATION_270})\n public @interface SupportedRotation {\n }\n}",
"public class FileUtils {\n\n private FileUtils() {\n throw new RuntimeException(\"Cannot initialize this class.\");\n }\n\n\n /**\n * @param context Instance of the caller.\n * @return If the external cache is available than this will return external cache directory or\n * else it will display internal cache directory.\n */\n @NonNull\n public static File getCacheDir(@NonNull Context context) {\n return context.getExternalCacheDir() != null ? context.getExternalCacheDir() : context.getCacheDir();\n }\n\n public static boolean copyFile(@NonNull File destFile,\n @NonNull File srcFile) {\n try {\n // download the file\n InputStream input = new FileInputStream(srcFile);\n OutputStream output = new FileOutputStream(destFile);\n\n byte data[] = new byte[4096];\n int count;\n while ((count = input.read(data)) != -1) output.write(data, 0, count);\n\n output.flush();\n output.close();\n input.close();\n\n //noinspection ResultOfMethodCallIgnored\n srcFile.delete();\n return true;\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return false;\n } catch (IOException e) {\n e.printStackTrace();\n return false;\n }\n }\n\n}"
] | import android.content.Context;
import android.support.annotation.NonNull;
import com.kevalpatel2106.smartlens.camera.config.CameraFacing;
import com.kevalpatel2106.smartlens.camera.config.CameraImageFormat;
import com.kevalpatel2106.smartlens.camera.config.CameraResolution;
import com.kevalpatel2106.smartlens.camera.config.CameraRotation;
import com.kevalpatel2106.smartlens.utils.FileUtils;
import java.io.File; | /*
* Copyright 2017 Keval Patel.
*
* 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.kevalpatel2106.smartlens.camera;
/**
* Created by Keval on 12-Nov-16.
* This class will manage the camera configuration parameters. User the {@link Builder} class to
* set different parameters for the camera.
*
* @author {@link 'https://github.com/kevalpatel2106'}
*/
@SuppressWarnings("WeakerAccess")
public final class CameraConfig {
private Context mContext;
@CameraResolution.SupportedResolution
private int mResolution = CameraResolution.MEDIUM_RESOLUTION;
@CameraFacing.SupportedCameraFacing
private int mFacing = CameraFacing.REAR_FACING_CAMERA;
@CameraImageFormat.SupportedImageFormat
private int mImageFormat = CameraImageFormat.FORMAT_JPEG;
@CameraRotation.SupportedRotation
private int mImageRotation = CameraRotation.ROTATION_0;
private File mImageFile;
/**
* Public constructor.
*/
public CameraConfig() {
//Do nothing
}
/**
* @param context Instance.
* @return {@link Builder}
*/
public Builder getBuilder(@NonNull Context context) {
mContext = context;
return new Builder();
}
@CameraResolution.SupportedResolution
public int getResolution() {
return mResolution;
}
@CameraFacing.SupportedCameraFacing
public int getFacing() {
return mFacing;
}
@CameraImageFormat.SupportedImageFormat
public int getImageFormat() {
return mImageFormat;
}
public File getImageFile() {
return mImageFile;
}
@CameraRotation.SupportedRotation
public int getImageRotation() {
return mImageRotation;
}
/**
* This is the builder class for {@link CameraConfig}.
*/
@SuppressWarnings({"unused", "UnusedReturnValue", "WeakerAccess"})
public class Builder {
/**
* Set the resolution of the output camera image. If you don't specify any resolution,
* default image resolution will set to {@link CameraResolution#MEDIUM_RESOLUTION}.
*
* @param resolution Any resolution from:
* <li>{@link CameraResolution#HIGH_RESOLUTION}</li>
* <li>{@link CameraResolution#MEDIUM_RESOLUTION}</li>
* <li>{@link CameraResolution#LOW_RESOLUTION}</li>
* @return {@link Builder}
* @see CameraResolution
*/
public Builder setCameraResolution(@CameraResolution.SupportedResolution int resolution) {
//Validate input
if (resolution != CameraResolution.HIGH_RESOLUTION &&
resolution != CameraResolution.MEDIUM_RESOLUTION &&
resolution != CameraResolution.LOW_RESOLUTION) {
throw new IllegalArgumentException("Invalid camera resolution.");
}
mResolution = resolution;
return this;
}
/**
* Set the camera facing with which you want to capture image.
* Either rear facing camera or front facing camera. If you don't provide any camera facing,
* default camera facing will be {@link CameraFacing#FRONT_FACING_CAMERA}.
*
* @param cameraFacing Any camera facing from:
* <li>{@link CameraFacing#REAR_FACING_CAMERA}</li>
* <li>{@link CameraFacing#FRONT_FACING_CAMERA}</li>
* @return {@link Builder}
* @see CameraFacing
*/
public Builder setCameraFacing(@CameraFacing.SupportedCameraFacing int cameraFacing) {
//Validate input
if (cameraFacing != CameraFacing.REAR_FACING_CAMERA &&
cameraFacing != CameraFacing.FRONT_FACING_CAMERA) {
throw new IllegalArgumentException("Invalid camera facing value.");
}
//Check if the any camera available?
if (!CameraUtils.isCameraAvailable(mContext)) {
throw new IllegalStateException("Device camera is not available.");
}
//Check if the front camera available?
if (cameraFacing == CameraFacing.FRONT_FACING_CAMERA
&& !CameraUtils.isFrontCameraAvailable(mContext)) {
throw new IllegalStateException("Front camera is not available.");
}
mFacing = cameraFacing;
return this;
}
/**
* Specify the image format for the output image. If you don't specify any output format,
* default output format will be {@link CameraImageFormat#FORMAT_JPEG}.
*
* @param imageFormat Any supported image format from:
* <li>{@link CameraImageFormat#FORMAT_JPEG}</li>
* <li>{@link CameraImageFormat#FORMAT_PNG}</li>
* @return {@link Builder}
* @see CameraImageFormat
*/
public Builder setImageFormat(@CameraImageFormat.SupportedImageFormat int imageFormat) {
//Validate input
if (imageFormat != CameraImageFormat.FORMAT_JPEG &&
imageFormat != CameraImageFormat.FORMAT_PNG) {
throw new IllegalArgumentException("Invalid output image format.");
}
mImageFormat = imageFormat;
return this;
}
/**
* Specify the output image rotation. The output image will be rotated by amount of degree specified
* before stored to the output file. By default there is no rotation applied.
*
* @param rotation Any supported rotation from:
* <li>{@link CameraRotation#ROTATION_0}</li>
* <li>{@link CameraRotation#ROTATION_90}</li>
* <li>{@link CameraRotation#ROTATION_180}</li>
* <li>{@link CameraRotation#ROTATION_270}</li>
* @return {@link Builder}
* @see CameraRotation
*/
public Builder setImageRotation(@CameraRotation.SupportedRotation int rotation) {
//Validate input
if (rotation != CameraRotation.ROTATION_0
&& rotation != CameraRotation.ROTATION_90
&& rotation != CameraRotation.ROTATION_180
&& rotation != CameraRotation.ROTATION_270) {
throw new IllegalArgumentException("Invalid image rotation.");
}
mImageRotation = rotation;
return this;
}
/**
* Set the location of the out put image. If you do not set any file for the output image, by
* default image will be stored in the application's cache directory.
*
* @param imageFile {@link File} where you want to store the image.
* @return {@link Builder}
*/
public Builder setImageFile(File imageFile) {
mImageFile = imageFile;
return this;
}
/**
* Build the configuration.
*
* @return {@link CameraConfig}
*/
public CameraConfig build() {
if (mImageFile == null) mImageFile = getDefaultStorageFile();
return CameraConfig.this;
}
/**
* If no file is supplied to save the captured image, image will be saved by default to the
* cache directory.
*
* @return File to save image bitmap.
*/
@NonNull
private File getDefaultStorageFile() { | return new File(FileUtils.getCacheDir(mContext).getAbsolutePath() | 4 |
rholder/fauxflake | fauxflake-core/src/main/java/com/github/rholder/fauxflake/IdGenerators.java | [
"public interface EncodingProvider {\n\n /**\n * Return a raw byte encoding of the given time and sequence number.\n *\n * @param time a time value to encode\n * @param sequence a sequence value to encode\n */\n public byte[] encodeAsBytes(long time, int sequence);\n\n /**\n * Return a Long encoding of the given the time and sequence number.\n *\n * @param time a time value to encode\n * @param sequence a sequence value to encode\n */\n public long encodeAsLong(long time, int sequence);\n\n /**\n * Return a String encoding of the given the time and sequence number.\n *\n * @param time a time value to encode\n * @param sequence a sequence value to encode\n */\n public String encodeAsString(long time, int sequence);\n\n /**\n * Return the maximum number of sequence numbers that can be encoded for a\n * given time by this implementation.\n */\n public int maxSequenceNumbers();\n}",
"public interface IdGenerator {\n\n /**\n * Return a unique identifier. This should be resilient enough to handle\n * leap seconds, however, backwards time that occurs when the system time is\n * updated, as from NTP, will result in an {@link InterruptedException}.\n *\n * NOTE: Generating more id's at a time than can be handled may result in\n * the current thread blocking for maxWait ms to ensure a new timestamp is\n * available.\n *\n * @param maxWait\n * the maximum amount of time to wait in ms before giving up\n * @throws InterruptedException\n * thrown when thread is interrupted, the maximum amount of time\n * to wait for a new timestamp to become available has expired, or\n * backwards time has been detected\n */\n public Id generateId(int maxWait) throws InterruptedException;\n}",
"public interface MachineIdProvider {\n\n /**\n * Return the unique machine identifier.\n */\n public long getMachineId();\n}",
"public class FlakeEncodingProvider implements EncodingProvider {\n\n private long shiftedMachineId;\n\n public FlakeEncodingProvider(long machineId) {\n shiftedMachineId = (0x0000FFFFFFFFFFFFl & machineId) << 16;\n }\n\n /**\n * Return a 128-bit version of the given time and sequence numbers according\n * to the Flake specification.\n *\n * @param time a time value to encode\n * @param sequence a sequence value to encode\n * @return the Flake id as bytes\n */\n @Override\n public byte[] encodeAsBytes(long time, int sequence) {\n byte[] buffer = new byte[16];\n buffer[0] = (byte) (time >>> 56);\n buffer[1] = (byte) (time >>> 48);\n buffer[2] = (byte) (time >>> 40);\n buffer[3] = (byte) (time >>> 32);\n buffer[4] = (byte) (time >>> 24);\n buffer[5] = (byte) (time >>> 16);\n buffer[6] = (byte) (time >>> 8);\n buffer[7] = (byte) (time);\n\n long rest = shiftedMachineId | (0x0000FFFF & sequence);\n buffer[8] = (byte) (rest >>> 56);\n buffer[9] = (byte) (rest >>> 48);\n buffer[10] = (byte) (rest >>> 40);\n buffer[11] = (byte) (rest >>> 32);\n buffer[12] = (byte) (rest >>> 24);\n buffer[13] = (byte) (rest >>> 16);\n buffer[14] = (byte) (rest >>> 8);\n buffer[15] = (byte) (rest);\n\n return buffer;\n }\n\n /**\n * This always throws an {@link UnsupportedOperationException} since the\n * output of this {@link EncodingProvider} doesn't fit in 4 bytes.\n *\n * @param time a time value to encode\n * @param sequence a sequence value to encode\n * @return never returns\n */\n @Override\n public long encodeAsLong(long time, int sequence) {\n throw new UnsupportedOperationException(\"Long value not supported\");\n }\n\n /**\n * Return the 32 character left padded hex version of the given id. These\n * can be lexicographically sorted.\n *\n * @param time a time value to encode\n * @param sequence a sequence value to encode\n * @return 32 character left padded hex version of the given id\n */\n @Override\n public String encodeAsString(long time, int sequence) {\n StringBuilder s = new StringBuilder(32);\n ByteBuffer bb = ByteBuffer.wrap(encodeAsBytes(time, sequence));\n s.append(leftPad(toHexString(bb.getLong()), 16, '0'));\n s.append(leftPad(toHexString(bb.getLong()), 16, '0'));\n\n return s.toString();\n }\n\n @Override\n public int maxSequenceNumbers() {\n // 2^16\n return 65536;\n }\n}",
"public class MacMachineIdProvider implements MachineIdProvider {\n\n private final long machineId;\n\n public MacMachineIdProvider() {\n long value = 0L;\n try {\n // first 6 bytes are MAC\n byte[] raw = Arrays.copyOf(macAddress(), 8);\n value = new DataInputStream(new ByteArrayInputStream(raw)).readLong();\n } catch (Throwable t) {\n t.printStackTrace();\n }\n machineId = value;\n }\n\n /**\n * Return the unique machine id based on the MAC address or 0 if an error\n * occurs.\n */\n @Override\n public long getMachineId() {\n return machineId;\n }\n}",
"public class MacPidMachineIdProvider implements MachineIdProvider {\n\n private final long machineId;\n\n public MacPidMachineIdProvider() {\n long value = 0L;\n try {\n // first 6 bytes are MAC\n byte[] raw = Arrays.copyOf(macAddress(), 8);\n value = new DataInputStream(new ByteArrayInputStream(raw)).readLong();\n\n // next 2 bytes are pid % 2^16\n value |= pid() % 65536;\n } catch (Throwable t) {\n t.printStackTrace();\n }\n machineId = value;\n }\n\n /**\n * Return the unique machine id based on the MAC address and current PID of\n * the running JVM or 0 if an error occurs.\n */\n @Override\n public long getMachineId() {\n return machineId;\n }\n}",
"public class SystemTimeProvider implements TimeProvider {\n\n @Override\n public long getCurrentTime() {\n return System.currentTimeMillis();\n }\n}",
"public class SnowflakeEncodingProvider implements EncodingProvider {\n\n /**\n * Wed Nov 03 20:42:54 CDT 2010, when time stamps begin for Twitter's epoch\n */\n public static final long EPOCH = 1288834974657L;\n\n /**\n * Total sequence numbers available within a single ms = 2^12\n */\n public static final int MAX_SEQUENCE_NUMBERS = 4096;\n\n /**\n * Number of bits to shift the time over\n */\n public static final int SHIFT_TIME_BITS = 22;\n\n /**\n * Number of bits to shift the machine code over\n */\n public static final int SHIFT_MACHINE_CODE_BITS = 12;\n\n /**\n * Total unique machine codes = 2^10\n */\n public static final int MACHINE_CODES = 1024;\n\n private long shiftedMachineId;\n\n public SnowflakeEncodingProvider(long machineId) {\n this.shiftedMachineId = ((machineId % MACHINE_CODES) << SHIFT_MACHINE_CODE_BITS);\n }\n\n @Override\n public byte[] encodeAsBytes(long time, int sequence) {\n long v = ((time - EPOCH) << SHIFT_TIME_BITS) | shiftedMachineId | sequence;\n\n byte[] buffer = new byte[8];\n buffer[0] = (byte)(v >>> 56);\n buffer[1] = (byte)(v >>> 48);\n buffer[2] = (byte)(v >>> 40);\n buffer[3] = (byte)(v >>> 32);\n buffer[4] = (byte)(v >>> 24);\n buffer[5] = (byte)(v >>> 16);\n buffer[6] = (byte)(v >>> 8);\n buffer[7] = (byte)(v);\n\n return buffer;\n }\n\n @Override\n public long encodeAsLong(long time, int sequence) {\n return ((time - EPOCH) << SHIFT_TIME_BITS) | shiftedMachineId | sequence;\n }\n\n /**\n * Return the 16 character left padded hex version of the given id. These\n * can be lexicographically sorted.\n */\n @Override\n public String encodeAsString(long time, int sequence) {\n return leftPad(toHexString(encodeAsLong(time, sequence)), 16, '0');\n }\n\n @Override\n public int maxSequenceNumbers() {\n return MAX_SEQUENCE_NUMBERS;\n }\n}"
] | import com.github.rholder.fauxflake.api.EncodingProvider;
import com.github.rholder.fauxflake.api.IdGenerator;
import com.github.rholder.fauxflake.api.MachineIdProvider;
import com.github.rholder.fauxflake.provider.boundary.FlakeEncodingProvider;
import com.github.rholder.fauxflake.provider.MacMachineIdProvider;
import com.github.rholder.fauxflake.provider.MacPidMachineIdProvider;
import com.github.rholder.fauxflake.provider.SystemTimeProvider;
import com.github.rholder.fauxflake.provider.twitter.SnowflakeEncodingProvider; | /*
* Copyright 2012-2014 Ray Holder
*
* 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.github.rholder.fauxflake;
/**
* This class provides a collection of convenience methods for constructing
* common {@link IdGenerator} implementations.
*/
public abstract class IdGenerators {
/**
* Create a Snowflake-based {@link IdGenerator} using the MAC address and
* PID for hashing out a pseudo-unique machine id.
*
* @return the {@link IdGenerator}
*/
public static IdGenerator newSnowflakeIdGenerator() {
MachineIdProvider machineIdProvider = new MacPidMachineIdProvider();
return newSnowflakeIdGenerator(machineIdProvider);
}
/**
* Create a Snowflake-based {@link IdGenerator} using the given
* {@link MachineIdProvider}.
*
* @return the {@link IdGenerator}
*/
public static IdGenerator newSnowflakeIdGenerator(MachineIdProvider machineIdProvider) {
EncodingProvider encodingProvider = new SnowflakeEncodingProvider(machineIdProvider.getMachineId()); | return new DefaultIdGenerator(new SystemTimeProvider(), encodingProvider); | 6 |
taskadapter/redmine-java-api | src/main/java/com/taskadapter/redmineapi/AttachmentManager.java | [
"public class Attachment implements Identifiable, FluentStyle {\n\n private final PropertyStorage storage = new PropertyStorage();\n\n /**\n * database numeric Id\n */\n public final static Property<Integer> DATABASE_ID = new Property<>(Integer.class, \"id\");\n public final static Property<String> FILE_NAME = new Property<>(String.class, \"fileName\");\n public final static Property<Long> FILE_SIZE = new Property<>(Long.class, \"fileSize\");\n public final static Property<String> CONTENT_TYPE = new Property<>(String.class, \"contentType\");\n public final static Property<String> CONTENT_URL = new Property<>(String.class, \"contentURL\");\n public final static Property<String> DESCRIPTION = new Property<>(String.class, \"description\");\n public final static Property<Date> CREATED_ON = new Property<>(Date.class, \"createdOn\");\n public final static Property<User> AUTHOR = new Property<>(User.class, \"author\");\n public final static Property<String> TOKEN = new Property<>(String.class, \"token\");\n private Transport transport;\n\n public Attachment(Transport transport) {\n setTransport(transport);\n }\n\n public Attachment setId(Integer id) {\n storage.set(DATABASE_ID, id);\n return this;\n }\n\n /**\n * @return id. NULL for attachments not added to Redmine yet.\n */\n @Override\n public Integer getId() {\n return storage.get(DATABASE_ID);\n }\n\n public String getContentType() {\n return storage.get(CONTENT_TYPE);\n }\n\n public Attachment setContentType(String contentType) {\n storage.set(CONTENT_TYPE, contentType);\n return this;\n }\n\n public String getContentURL() {\n return storage.get(CONTENT_URL);\n }\n\n public Attachment setContentURL(String contentURL) {\n storage.set(CONTENT_URL, contentURL);\n return this;\n }\n\n /**\n * Description is empty by default, not NULL.\n */\n public String getDescription() {\n return storage.get(DESCRIPTION);\n }\n\n public Attachment setDescription(String description) {\n storage.set(DESCRIPTION, description);\n return this;\n }\n\n public Date getCreatedOn() {\n return storage.get(CREATED_ON);\n }\n\n public Attachment setCreatedOn(Date createdOn) {\n storage.set(CREATED_ON, createdOn);\n return this;\n }\n\n public User getAuthor() {\n return storage.get(AUTHOR);\n }\n\n public Attachment setAuthor(User author) {\n storage.set(AUTHOR, author);\n return this;\n }\n\n public String getFileName() {\n return storage.get(FILE_NAME);\n }\n\n public Attachment setFileName(String fileName) {\n storage.set(FILE_NAME, fileName);\n return this;\n }\n\n public Long getFileSize() {\n return storage.get(FILE_SIZE);\n }\n\n public Attachment setFileSize(Long fileSize) {\n storage.set(FILE_SIZE, fileSize);\n return this;\n }\n\n public String getToken() {\n return storage.get(TOKEN);\n }\n\n public Attachment setToken(String token) {\n storage.set(TOKEN, token);\n return this;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Attachment that = (Attachment) o;\n\n if (getId() != null ? !getId().equals(that.getId()) : that.getId() != null) return false;\n if (getToken() != null ? !getToken().equals(that.getToken()) : that.getToken() != null) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int hash = 5;\n hash = 3 * hash + (getId() != null ? getId().hashCode() : 0);\n hash = 3 * hash + (getToken() != null ? getToken().hashCode() : 0);\n return hash;\n }\n\n @Override\n public String toString() {\n return \"Attachment{\" +\n \"id=\" + getId() +\n \", fileName='\" + getFileName() + '\\'' +\n \", fileSize=\" + getFileSize() +\n \", contentType='\" + getContentType() + '\\'' +\n \", contentURL='\" + getContentURL() + '\\'' +\n \", description='\" + getDescription() + '\\'' +\n \", createdOn=\" + getCreatedOn() +\n \", author=\" + getAuthor() +\n \", token=\" + getToken() +\n '}';\n }\n\n public PropertyStorage getStorage() {\n return storage;\n }\n\n /**\n * delete the attachment with pre-configured ID from the server.\n * <br>\n * see http://www.redmine.org/issues/14828\n *\n * @since Redmine 3.3.0\n */\n public void delete() throws RedmineException {\n transport.deleteObject(Attachment.class, Integer.toString(getId()));\n }\n\n @Override\n public void setTransport(Transport transport) {\n this.transport = transport;\n PropertyStorageUtil.updateCollections(storage, transport);\n }\n}",
"public class Issue implements Identifiable, FluentStyle {\n\n private final PropertyStorage storage = new PropertyStorage();\n\n public final static Property<Integer> DATABASE_ID = new Property<>(Integer.class, \"id\");\n public final static Property<String> SUBJECT = new Property<>(String.class, \"subject\");\n public final static Property<Date> START_DATE = new Property<>(Date.class, \"startDate\");\n public final static Property<Date> DUE_DATE = new Property<>(Date.class, \"dueDate\");\n public final static Property<Date> CREATED_ON = new Property<>(Date.class, \"createdOn\");\n public final static Property<Date> UPDATED_ON = new Property<>(Date.class, \"updatedOn\");\n public final static Property<Integer> DONE_RATIO = new Property<>(Integer.class, \"doneRatio\");\n public final static Property<Integer> PARENT_ID = new Property<>(Integer.class, \"parentId\");\n public final static Property<Integer> PRIORITY_ID = new Property<>(Integer.class, \"priorityId\");\n public final static Property<Float> ESTIMATED_HOURS = new Property<>(Float.class, \"estimatedHours\");\n public final static Property<Float> SPENT_HOURS = new Property<>(Float.class, \"spentHours\");\n public final static Property<Integer> ASSIGNEE_ID = new Property<>(Integer.class, \"assigneeId\");\n public final static Property<String> ASSIGNEE_NAME = new Property<>(String.class, \"assigneeName\");\n\n /**\n * Some comment describing an issue update.\n */\n public final static Property<String> NOTES = new Property<String>(String.class, \"notes\");\n public final static Property<Boolean> PRIVATE_NOTES = new Property<>(Boolean.class, \"notes\");\n public final static Property<String> PRIORITY_TEXT = new Property<>(String.class, \"priorityText\");\n public final static Property<Integer> PROJECT_ID = new Property<>(Integer.class, \"projectId\");\n public final static Property<String> PROJECT_NAME = new Property<>(String.class, \"projectName\");\n public final static Property<Integer> AUTHOR_ID = new Property<>(Integer.class, \"authorId\");\n public final static Property<String> AUTHOR_NAME = new Property<>(String.class, \"authorName\");\n public final static Property<Tracker> TRACKER = new Property<>(Tracker.class, \"tracker\");\n public final static Property<String> DESCRIPTION = new Property<>(String.class, \"description\");\n public final static Property<Date> CLOSED_ON = new Property<>(Date.class, \"closedOn\");\n public final static Property<Integer> STATUS_ID = new Property<>(Integer.class, \"statusId\");\n public final static Property<String> STATUS_NAME = new Property<>(String.class, \"statusName\");\n public final static Property<Version> TARGET_VERSION = new Property<>(Version.class, \"targetVersion\");\n public final static Property<IssueCategory> ISSUE_CATEGORY = new Property<>(IssueCategory.class, \"issueCategory\");\n public final static Property<Boolean> PRIVATE_ISSUE = new Property<>(Boolean.class, \"privateIssue\");\n\n /**\n * can't have two custom fields with the same ID in the collection, that's why it is declared\n * as a Set, not a List.\n */\n public final static Property<Set<CustomField>> CUSTOM_FIELDS = (Property<Set<CustomField>>) new Property(Set.class, \"customFields\");\n public final static Property<Set<Journal>> JOURNALS = (Property<Set<Journal>>) new Property(Set.class, \"journals\");\n public final static Property<Set<IssueRelation>> RELATIONS = (Property<Set<IssueRelation>>) new Property(Set.class, \"relations\");\n public final static Property<Set<Attachment>> ATTACHMENTS = (Property<Set<Attachment>>) new Property(Set.class, \"attachments\");\n public final static Property<Set<Changeset>> CHANGESETS = (Property<Set<Changeset>>) new Property(Set.class, \"changesets\");\n public final static Property<Set<Watcher>> WATCHERS = (Property<Set<Watcher>>) new Property(Set.class, \"watchers\");\n public final static Property<Set<Issue>> CHILDREN = (Property<Set<Issue>>) new Property(Set.class, \"children\");\n\n private Transport transport;\n\n public Issue() {\n initCollections(storage);\n }\n\n public Issue(Transport transport) {\n this();\n setTransport(transport);\n }\n\n /**\n * Each Issue object must have project Id set in order for Redmine 3.x to accept it via REST API.\n */\n public Issue(Transport transport, int projectId) {\n this();\n this.transport = transport;\n setProjectId(projectId);\n }\n\n /**\n * @param projectId Each Issue object must have project Id set in order for Redmine 3.x to accept it via REST API.\n */\n public Issue(Transport transport, int projectId, String subject) {\n this();\n this.transport = transport;\n setSubject(subject);\n setProjectId(projectId);\n }\n\n private void initCollections(PropertyStorage storage) {\n storage.set(CUSTOM_FIELDS, new HashSet<>());\n storage.set(CHILDREN, new HashSet<>());\n storage.set(WATCHERS, new HashSet<>());\n storage.set(CHANGESETS, new HashSet<>());\n storage.set(ATTACHMENTS, new HashSet<>());\n storage.set(RELATIONS, new HashSet<>());\n storage.set(JOURNALS, new HashSet<>());\n }\n\n public Integer getProjectId() {\n return storage.get(PROJECT_ID);\n }\n\n public Issue setProjectId(Integer projectId) {\n storage.set(PROJECT_ID, projectId);\n return this;\n }\n\n public String getProjectName() {\n return storage.get(PROJECT_NAME);\n }\n\n\n public Issue setProjectName(String name) {\n storage.set(PROJECT_NAME, name);\n return this;\n }\n\n /**\n * @param id database ID.\n */\n public Issue setId(Integer id) {\n storage.set(DATABASE_ID, id);\n return this;\n }\n\n public Integer getDoneRatio() {\n return storage.get(DONE_RATIO);\n }\n\n public Issue setDoneRatio(Integer doneRatio) {\n storage.set(DONE_RATIO, doneRatio);\n return this;\n }\n\n public String getPriorityText() {\n return storage.get(PRIORITY_TEXT);\n }\n\n /**\n * @deprecated This method has no effect when creating issues on Redmine Server, so we might as well just delete it\n * in the future releases.\n */\n public void setPriorityText(String priority) {\n storage.set(PRIORITY_TEXT, priority);\n }\n\n /**\n * Redmine can be configured to allow group assignments for issues:\n * Configuration option: Settings -> Issue Tracking -> Allow issue assignment to groups\n *\n * <p>An assignee can be a user or a group</p>\n */\n public Integer getAssigneeId() {\n return storage.get(ASSIGNEE_ID);\n }\n\n public Issue setAssigneeId(Integer assigneeId) {\n storage.set(ASSIGNEE_ID, assigneeId);\n return this;\n }\n\n public String getAssigneeName() {\n return storage.get(ASSIGNEE_NAME);\n }\n\n public Issue setAssigneeName(String assigneeName) {\n storage.set(ASSIGNEE_NAME, assigneeName);\n return this;\n }\n\n public Float getEstimatedHours() {\n return storage.get(ESTIMATED_HOURS);\n }\n\n public Issue setEstimatedHours(Float estimatedTime) {\n storage.set(ESTIMATED_HOURS, estimatedTime);\n return this;\n }\n\n public Float getSpentHours() {\n return storage.get(SPENT_HOURS);\n }\n\n public Issue setSpentHours(Float spentHours) {\n storage.set(SPENT_HOURS, spentHours);\n return this;\n }\n\n /**\n * Parent Issue ID, or NULL for issues without a parent.\n *\n * @return NULL, if there's no parent\n */\n public Integer getParentId() {\n return storage.get(PARENT_ID);\n }\n\n public Issue setParentId(Integer parentId) {\n storage.set(PARENT_ID, parentId);\n return this;\n }\n\n /**\n * @return database id for this object. can be NULL for Issues not added to Redmine yet\n */\n @Override\n public Integer getId() {\n return storage.get(DATABASE_ID);\n }\n\n public String getSubject() {\n return storage.get(SUBJECT);\n }\n\n public Issue setSubject(String subject) {\n storage.set(SUBJECT, subject);\n return this;\n }\n\n public Date getStartDate() {\n return storage.get(START_DATE);\n }\n\n public Issue setStartDate(Date startDate) {\n storage.set(START_DATE, startDate);\n return this;\n }\n\n public Date getDueDate() {\n return storage.get(DUE_DATE);\n }\n\n public Issue setDueDate(Date dueDate) {\n storage.set(DUE_DATE, dueDate);\n return this;\n }\n\n public Integer getAuthorId() {\n return storage.get(AUTHOR_ID);\n }\n\n /**\n * Marking as \"deprecated\": according to Redmine REST API docs\n * https://www.redmine.org/projects/redmine/wiki/Rest_Issues#Creating-an-issue , this parameter is not used\n * when creating issues (January 2020).\n */\n @Deprecated\n public Issue setAuthorId(Integer id) {\n storage.set(AUTHOR_ID, id);\n return this;\n }\n\n public String getAuthorName() {\n return storage.get(AUTHOR_NAME);\n }\n\n /**\n * Marking as \"deprecated\": according to Redmine REST API docs\n * https://www.redmine.org/projects/redmine/wiki/Rest_Issues#Creating-an-issue , this parameter is not used\n * when creating issues (January 2020).\n */\n @Deprecated\n public Issue setAuthorName(String name) {\n storage.set(AUTHOR_NAME, name);\n return this;\n }\n\n public Tracker getTracker() {\n return storage.get(TRACKER);\n }\n\n public Issue setTracker(Tracker tracker) {\n storage.set(TRACKER, tracker);\n return this;\n }\n\n public String getDescription() {\n return storage.get(DESCRIPTION);\n }\n\n public Issue setDescription(String description) {\n storage.set(DESCRIPTION, description);\n return this;\n }\n\n public Date getCreatedOn() {\n return storage.get(CREATED_ON);\n }\n\n public Issue setCreatedOn(Date createdOn) {\n storage.set(CREATED_ON, createdOn);\n return this;\n }\n\n public Date getUpdatedOn() {\n return storage.get(UPDATED_ON);\n }\n\n public Issue setUpdatedOn(Date updatedOn) {\n storage.set(UPDATED_ON, updatedOn);\n return this;\n }\n\n public Date getClosedOn() {\n return storage.get(CLOSED_ON);\n }\n\n public Issue setClosedOn(Date closedOn) {\n storage.set(CLOSED_ON, closedOn);\n return this;\n }\n\n public Integer getStatusId() {\n return storage.get(STATUS_ID);\n }\n\n public Issue setStatusId(Integer statusId) {\n storage.set(STATUS_ID, statusId);\n return this;\n }\n\n public String getStatusName() {\n return storage.get(STATUS_NAME);\n }\n\n public Issue setStatusName(String statusName) {\n storage.set(STATUS_NAME, statusName);\n return this;\n }\n\n /**\n * @return unmodifiable collection of Custom Field objects. the collection may be empty, but it is never NULL.\n */\n public Collection<CustomField> getCustomFields() {\n return Collections.unmodifiableCollection(storage.get(CUSTOM_FIELDS));\n }\n\n public Issue clearCustomFields() {\n storage.set(CUSTOM_FIELDS, new HashSet<>());\n return this;\n }\n\n /**\n * NOTE: The custom field(s) <strong>must have correct database ID set</strong> to be saved to Redmine.\n * This is Redmine REST API's requirement.\n */\n public Issue addCustomFields(Collection<CustomField> customFields) {\n storage.get(CUSTOM_FIELDS).addAll(customFields);\n return this;\n }\n\n /**\n * If there is a custom field with the same ID already present in the Issue,\n * the new field replaces the old one.\n *\n * @param customField the field to add to the issue.\n */\n public Issue addCustomField(CustomField customField) {\n storage.get(CUSTOM_FIELDS).add(customField);\n return this;\n }\n\n @Deprecated\n /**\n * This method should not be used by clients. \"notes\" only makes sense when creating/updating an issue - that is the\n * string value added along with the update.\n * <p>\n * use {@link #getJournals()} if you want to access previously saved notes. feel free to submit an enhancement\n * request to Redmine developers if you think this \"notes - journals\" separation looks weird...\n */\n public String getNotes() {\n return storage.get(NOTES);\n }\n\n /**\n * @param notes Some comment describing the issue update\n */\n public Issue setNotes(String notes) {\n storage.set(NOTES, notes);\n return this;\n }\n\n public boolean isPrivateNotes() {\n return storage.get(PRIVATE_NOTES);\n }\n\n /**\n * @param privateNotes mark note as private\n */\n public Issue setPrivateNotes(boolean privateNotes) {\n storage.set(PRIVATE_NOTES, privateNotes);\n return this;\n }\n\n /**\n * Don't forget to use Include.journals flag when loading issue from Redmine server:\n * <pre>\n * Issue issue = issueManager.getIssueById(3205, Include.journals);\n * </pre>\n * @return unmodifiable collection of Journal entries or empty collection if no objects found. Never NULL.\n * @see com.taskadapter.redmineapi.Include#journals\n */\n public Collection<Journal> getJournals() {\n return Collections.unmodifiableCollection(storage.get(JOURNALS));\n }\n\n /**\n * Issue journals are created automatically when you update existing issues.\n * journal entries are essentially log records for changes you make.\n * you cannot just add log records without making actual changes.\n * this API method is misleading and it should only be used internally by Redmine Json parser\n * when parsing response from server. we should hide it from public.\n *\n * TODO hide this method. https://github.com/taskadapter/redmine-java-api/issues/199\n */\n public void addJournals(Collection<Journal> journals) {\n storage.get(JOURNALS).addAll(journals);\n }\n\n /**\n * Don't forget to use Include.changesets flag when loading issue from Redmine server:\n * <pre>\n * Issue issue = issueManager.getIssueById(3205, Include.changesets);\n * </pre>\n * @return unmodifiable collection of entries or empty collection if no objects found.\n * @see com.taskadapter.redmineapi.Include#changesets\n */\n public Collection<Changeset> getChangesets() {\n return Collections.unmodifiableCollection(storage.get(CHANGESETS));\n }\n\n public Issue addChangesets(Collection<Changeset> changesets) {\n storage.get(CHANGESETS).addAll(changesets);\n return this;\n }\n\n /**\n * Don't forget to use Include.watchers flag when loading issue from Redmine server:\n * <pre>\n * Issue issue = issueManager.getIssueById(3205, Include.watchers);\n * </pre>\n * @return unmodifiable collection of entries or empty collection if no objects found.\n * @see com.taskadapter.redmineapi.Include#watchers\n */\n public Collection<Watcher> getWatchers() {\n return Collections.unmodifiableCollection(storage.get(WATCHERS));\n }\n\n public Issue addWatchers(Collection<Watcher> watchers) {\n storage.get(WATCHERS).addAll(watchers);\n return this;\n }\n\n /**\n * Don't forget to use Include.children flag when loading issue from Redmine server:\n * <pre>\n * Issue issue = issueManager.getIssueById(3205, Include.children);\n * </pre>\n * @return Collection of entries or empty collection if no objects found.\n * @see com.taskadapter.redmineapi.Include#children\n */\n public Collection<Issue> getChildren() {\n return Collections.unmodifiableCollection(storage.get(CHILDREN));\n }\n\n public Issue addChildren(Collection<Issue> children) {\n storage.get(CHILDREN).addAll(children);\n return this;\n }\n\n /**\n * Issues are considered equal if their IDs are equal. what about two issues with null ids?\n */\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Issue issue = (Issue) o;\n\n if (getId() != null ? !getId().equals(issue.getId()) : issue.getId() != null) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return getId() != null ? getId().hashCode() : 0;\n }\n\n /**\n * @return the custom field with given Id or NULL if the field is not found\n */\n public CustomField getCustomFieldById(int customFieldId) {\n for (CustomField customField : storage.get(CUSTOM_FIELDS)) {\n if (customFieldId == customField.getId()) {\n return customField;\n }\n }\n return null;\n }\n\n /**\n * @return the custom field with given name or NULL if the field is not found\n */\n public CustomField getCustomFieldByName(String customFieldName) {\n for (CustomField customField : storage.get(CUSTOM_FIELDS)) {\n if (customFieldName.equals(customField.getName())) {\n return customField;\n }\n }\n return null;\n }\n\n\n @Override\n public String toString() {\n return \"Issue [id=\" + getId() + \", subject=\" + getSubject() + \"]\";\n }\n\n /**\n * Relations are only loaded if you include Include.relations when loading the Issue.\n * <pre>\n * Issue issue = issueManager.getIssueById(3205, Include.relations);\n * </pre>\n * <p>Since the returned collection is not modifiable, you need to use addRelations() method\n * if you want to add elements, e.g.:\n * <pre>\n * issue.addRelations(Collections.singletonList(relation));\n * </pre>\n * @return unmodifiable collection of Relations or EMPTY collection if none found. Never returns NULL.\n * @see com.taskadapter.redmineapi.Include#relations\n */\n public Collection<IssueRelation> getRelations() {\n return Collections.unmodifiableCollection(storage.get(RELATIONS));\n }\n\n public Issue addRelations(Collection<IssueRelation> collection) {\n storage.get(RELATIONS).addAll(collection);\n return this;\n }\n\n public Integer getPriorityId() {\n return storage.get(PRIORITY_ID);\n }\n\n public Issue setPriorityId(Integer priorityId) {\n storage.set(PRIORITY_ID, priorityId);\n return this;\n }\n\n public Version getTargetVersion() {\n return storage.get(TARGET_VERSION);\n }\n\n /**\n * Don't forget to use <i>Include.attachments</i> flag when loading issue from Redmine server:\n * <pre>\n * Issue issue = issueManager.getIssueById(3205, Include.attachments);\n * </pre>\n * @return unmodifiable collection of entries or empty collection if no objects found.\n * @see com.taskadapter.redmineapi.Include#attachments\n */\n public Collection<Attachment> getAttachments() {\n return Collections.unmodifiableCollection(storage.get(ATTACHMENTS));\n }\n\n public Issue addAttachments(Collection<Attachment> collection) {\n storage.get(ATTACHMENTS).addAll(collection);\n return this;\n }\n\n public Issue addAttachment(Attachment attachment) {\n storage.get(ATTACHMENTS).add(attachment);\n return this;\n }\n\n public Issue setTargetVersion(Version version) {\n storage.set(TARGET_VERSION, version);\n return this;\n }\n\n public IssueCategory getCategory() {\n return storage.get(ISSUE_CATEGORY);\n }\n\n public Issue setCategory(IssueCategory category) {\n storage.set(ISSUE_CATEGORY, category);\n return this;\n }\n\n /**\n * Default value is not determines. it's up to the server what it thinks the default value is if not set.\n */\n public boolean isPrivateIssue() {\n return storage.get(PRIVATE_ISSUE);\n }\n\n public Issue setPrivateIssue(boolean privateIssue) {\n storage.set(PRIVATE_ISSUE, privateIssue);\n return this;\n }\n\n public PropertyStorage getStorage() {\n return storage;\n }\n\n /**\n * @return the newly created Issue.\n *\n * @throws RedmineAuthenticationException invalid or no API access key is used with the server, which\n * requires authorization. Check the constructor arguments.\n * @throws NotFoundException the required project is not found\n * @throws RedmineException\n */\n public Issue create(RequestParam... params) throws RedmineException {\n RequestParam[] enrichParams = Arrays.copyOf(params, params.length + 1);\n enrichParams[params.length] = new RequestParam(\"include\",\n Include.attachments.toString());\n return transport.addObject(this, enrichParams);\n }\n\n public void update(RequestParam... params) throws RedmineException {\n transport.updateObject(this, params);\n }\n\n public void delete() throws RedmineException {\n transport.deleteObject(Issue.class, Integer.toString(this.getId()));\n }\n\n public void addWatcher(int watcherId) throws RedmineException {\n transport.addWatcherToIssue(watcherId, getId());\n }\n\n public void deleteWatcher(int watcherId) throws RedmineException {\n transport.deleteChildId(Issue.class, Integer.toString(getId()), new Watcher(), watcherId);\n }\n\n @Override\n public void setTransport(Transport transport) {\n this.transport = transport;\n PropertyStorageUtil.updateCollections(storage, transport);\n }\n}",
"public final class CopyBytesHandler implements ContentHandler<BasicHttpResponse, Void> {\n\n\tprivate final OutputStream outStream;\n\n\tpublic CopyBytesHandler(OutputStream outStream) {\n\t\tthis.outStream = outStream;\n\t}\n\n\t@Override\n\tpublic Void processContent(BasicHttpResponse content)\n\t\t\tthrows RedmineException {\n\t\tfinal byte[] buffer = new byte[4096 * 4];\n\t\tint numberOfBytesRead;\n\t\ttry {\n\t\t\ttry (InputStream input = content.getStream()) {\n\t\t\t\twhile ((numberOfBytesRead = input.read(buffer)) > 0)\n\t\t\t\t\toutStream.write(buffer, 0, numberOfBytesRead);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tthrow new RedmineCommunicationException(e);\n\t\t}\n\t\treturn null;\n\t}\n}",
"public class Transport {\n\tprivate static final Map<Class<?>, EntityConfig<?>> OBJECT_CONFIGS = new HashMap<>();\n\tprivate static final String CONTENT_TYPE = \"application/json; charset=utf-8\";\n\tprivate static final int DEFAULT_OBJECTS_PER_PAGE = 25;\n\tprivate static final String KEY_TOTAL_COUNT = \"total_count\";\n\tprivate static final String KEY_LIMIT = \"limit\";\n\tprivate static final String KEY_OFFSET = \"offset\";\n\n\tprivate final Logger logger = LoggerFactory.getLogger(RedmineManager.class);\n\tprivate SimpleCommunicator<String> communicator;\n\tprivate Communicator<BasicHttpResponse> errorCheckingCommunicator;\n\tprivate Communicator<HttpResponse> authenticator;\n\n private String onBehalfOfUser = null;\n\n static {\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tProject.class,\n\t\t\t\tconfig(\"project\", \"projects\",\n\t\t\t\t\t\tRedmineJSONBuilder::writeProject,\n\t\t\t\t\t\tRedmineJSONParser::parseProject));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tIssue.class,\n\t\t\t\tconfig(\"issue\", \"issues\", RedmineJSONBuilder::writeIssue,\n\t\t\t\t\t\tRedmineJSONParser::parseIssue));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tUser.class,\n\t\t\t\tconfig(\"user\", \"users\", RedmineJSONBuilder::writeUser,\n\t\t\t\t\t\tRedmineJSONParser::parseUser));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tGroup.class,\n\t\t\t\tconfig(\"group\", \"groups\", RedmineJSONBuilder::writeGroup,\n\t\t\t\t\t\tRedmineJSONParser::parseGroup));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tIssueCategory.class,\n\t\t\t\tconfig(\"issue_category\", \"issue_categories\",\n\t\t\t\t\t\tRedmineJSONBuilder::writeCategory,\n\t\t\t\t\t\tRedmineJSONParser::parseCategory));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tVersion.class,\n\t\t\t\tconfig(\"version\", \"versions\",\n\t\t\t\t\t\tRedmineJSONBuilder::writeVersion,\n\t\t\t\t\t\tRedmineJSONParser::parseVersion));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tTimeEntry.class,\n\t\t\t\tconfig(\"time_entry\", \"time_entries\",\n\t\t\t\t\t\tRedmineJSONBuilder::writeTimeEntry,\n\t\t\t\t\t\tRedmineJSONParser::parseTimeEntry));\n\t\tOBJECT_CONFIGS.put(News.class,\n\t\t\t\tconfig(\"news\", \"news\", null, RedmineJSONParser::parseNews));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tIssueRelation.class,\n\t\t\t\tconfig(\"relation\", \"relations\",\n\t\t\t\t\t\tRedmineJSONBuilder::writeRelation,\n\t\t\t\t\t\tRedmineJSONParser::parseRelation));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tTracker.class,\n\t\t\t\tconfig(\"tracker\", \"trackers\", null,\n\t\t\t\t\t\tRedmineJSONParser::parseTracker));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tIssueStatus.class,\n\t\t\t\tconfig(\"status\", \"issue_statuses\", null,\n\t\t\t\t\t\tRedmineJSONParser::parseStatus));\n\t\tOBJECT_CONFIGS\n\t\t\t\t.put(SavedQuery.class,\n\t\t\t\t\t\tconfig(\"query\", \"queries\", null,\n\t\t\t\t\t\t\t\tRedmineJSONParser::parseSavedQuery));\n\t\tOBJECT_CONFIGS.put(Role.class,\n\t\t\t\tconfig(\"role\", \"roles\", null, RedmineJSONParser::parseRole));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tMembership.class,\n\t\t\t\tconfig(\"membership\", \"memberships\",\n\t\t\t\t\t\tRedmineJSONBuilder::writeMembership,\n\t\t\t\t\t\tRedmineJSONParser::parseMembership));\n OBJECT_CONFIGS.put(\n IssuePriority.class,\n config(\"issue_priority\", \"issue_priorities\", null,\n RedmineJSONParser::parseIssuePriority));\n OBJECT_CONFIGS.put(\n TimeEntryActivity.class,\n config(\"time_entry_activity\", \"time_entry_activities\", null,\n RedmineJSONParser::parseTimeEntryActivity));\n\n OBJECT_CONFIGS.put(\n Watcher.class,\n config(\"watcher\", \"watchers\", null,\n RedmineJSONParser::parseWatcher));\n\n OBJECT_CONFIGS.put(\n WikiPage.class,\n config(\"wiki_page\", \"wiki_pages\", null, RedmineJSONParser::parseWikiPage)\n );\n\n OBJECT_CONFIGS.put(\n WikiPageDetail.class,\n config(\"wiki_page\", null, RedmineJSONBuilder::writeWikiPageDetail, RedmineJSONParser::parseWikiPageDetail)\n );\n OBJECT_CONFIGS.put(\n CustomFieldDefinition.class,\n config(\"custom_field\", \"custom_fields\", null,\n RedmineJSONParser::parseCustomFieldDefinition));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tAttachment.class,\n\t\t\t\tconfig(\"attachment\", \"attachments\", null,\n\t\t\t\t\t\tRedmineJSONParser::parseAttachments));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tFile.class,\n\t\t\t\tconfig(\"file\", \"files\", null, RedmineJSONParser::parseFiles));\n }\n\n\tprivate URIConfigurator configurator;\n\tprivate int objectsPerPage = DEFAULT_OBJECTS_PER_PAGE;\n\tprivate static final String CHARSET = \"UTF-8\";\n\n\tpublic Transport(URIConfigurator configurator, HttpClient client) {\n\t\tvar baseCommunicator = new BaseCommunicator(client);\n\t\tvar redmineAuthenticator = new RedmineAuthenticator<>(baseCommunicator, CHARSET);\n\t\tconfigure(configurator, redmineAuthenticator);\n\t}\n\n\tpublic Transport(URIConfigurator configurator, Communicator communicator) {\n\t\tconfigure(configurator, communicator);\n\t}\n\n\tprivate void configure(URIConfigurator configurator, Communicator communicator) {\n\t\tthis.configurator = configurator;\n\t\tthis.authenticator = communicator;\n\t\tfinal ContentHandler<BasicHttpResponse, BasicHttpResponse> errorProcessor = new RedmineErrorHandler();\n\t\terrorCheckingCommunicator = Communicators.fmap(\n\t\t\t\tauthenticator,\n\t\t\t\tCommunicators.compose(errorProcessor,\n\t\t\t\t\t\tCommunicators.transportDecoder()));\n\t\tCommunicator<String> coreCommunicator = Communicators.fmap(errorCheckingCommunicator,\n\t\t\t\tCommunicators.contentReader());\n\t\tthis.communicator = Communicators.simplify(coreCommunicator,\n\t\t\t\tCommunicators.<String>identityHandler());\n\t}\n\n\tpublic User getCurrentUser(RequestParam... params) throws RedmineException {\n\t\tURI uri = getURIConfigurator().createURI(\"users/current.json\", params);\n\t\tHttpGet http = new HttpGet(uri);\n\t\tString response = send(http);\n\t\treturn parseResponse(response, \"user\", RedmineJSONParser::parseUser);\n\t}\n\n\t/**\n\t * Performs an \"add object\" request.\n\t * \n\t * @param object\n\t * object to use.\n\t * @param params\n\t * name params.\n\t * @return object to use.\n\t * @throws RedmineException\n\t * if something goes wrong.\n\t */\n\tpublic <T> T addObject(T object, RequestParam... params)\n\t\t\tthrows RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(object.getClass());\n if (config.writer == null) {\n throw new RuntimeException(\"can't create object: writer is not implemented or is not registered in RedmineJSONBuilder for object \" + object);\n }\n\t\tURI uri = getURIConfigurator().getObjectsURI(object.getClass(), params);\n\t\tHttpPost httpPost = new HttpPost(uri);\n\t\tString body = RedmineJSONBuilder.toSimpleJSON(config.singleObjectName, object, config.writer);\n\t\tsetEntity(httpPost, body);\n\t\tString response = send(httpPost);\n\t\tlogger.debug(response);\n\t\treturn parseResponse(response, config.singleObjectName, config.parser);\n\t}\n\n\t/**\n\t * Performs an \"add child object\" request.\n\t * \n\t * @param parentClass\n\t * parent object id.\n\t * @param object\n\t * object to use.\n\t * @param params\n\t * name params.\n\t * @return object to use.\n\t * @throws RedmineException\n\t * if something goes wrong.\n\t */\n\tpublic <T> T addChildEntry(Class<?> parentClass, String parentId, T object,\n\t\t\tRequestParam... params) throws RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(object.getClass());\n\t\tURI uri = getURIConfigurator().getChildObjectsURI(parentClass,\n\t\t\t\tparentId, object.getClass(), params);\n\t\tHttpPost httpPost = new HttpPost(uri);\n\t\tString body = RedmineJSONBuilder.toSimpleJSON(config.singleObjectName,\n\t\t\t\tobject, config.writer);\n\t\tsetEntity(httpPost, body);\n\t\tString response = send(httpPost);\n\t\tlogger.debug(response);\n\t\treturn parseResponse(response, config.singleObjectName, config.parser);\n\t}\n\n\t/*\n\t * note: This method cannot return the updated object from Redmine because\n\t * the server does not provide any XML in response.\n\t * \n\t * @since 1.8.0\n\t */\n\tpublic <T extends Identifiable> void updateObject(T obj,\n\t\t\tRequestParam... params) throws RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(obj.getClass());\n\t\tfinal Integer id = obj.getId();\n\t\tif (id == null) {\n\t\t\tthrow new RuntimeException(\"'id' field cannot be NULL in the given object:\" +\n\t\t\t\t\t\" it is required to identify the object in the target system\");\n\t\t}\n\t\tfinal URI uri = getURIConfigurator().getObjectURI(obj.getClass(),\n\t\t\t\tInteger.toString(id), params);\n\t\tfinal HttpPut http = new HttpPut(uri);\n\t\tfinal String body = RedmineJSONBuilder.toSimpleJSON(\n\t\t\t\tconfig.singleObjectName, obj, config.writer);\n\t\tsetEntity(http, body);\n\t\tsend(http);\n\t}\n\n\t/*\n\t * note: This method cannot return the updated object from Redmine because\n\t * the server does not provide anything in response.\n\t */\n\tpublic <T> void updateChildEntry(Class<?> parentClass, String parentId,\n\t\t\tT obj, String objId, RequestParam... params) throws RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(obj.getClass());\n\t\tURI uri = getURIConfigurator().getChildIdURI(parentClass, parentId, obj.getClass(), objId, params);\n\t\tfinal HttpPut http = new HttpPut(uri);\n\t\tfinal String body = RedmineJSONBuilder.toSimpleJSON(config.singleObjectName, obj, config.writer);\n\t\tsetEntity(http, body);\n\t\tsend(http);\n\t}\n\n\t/**\n\t * Performs \"delete child Id\" request.\n\t * \n\t * @param parentClass\n\t * parent object id.\n\t * @param object\n\t * object to use.\n\t * @param value\n\t * child object id.\n\t * @throws RedmineException\n\t * if something goes wrong.\n\t */\n public <T> void deleteChildId(Class<?> parentClass, String parentId, T object, Integer value) throws RedmineException {\n URI uri = getURIConfigurator().getChildIdURI(parentClass, parentId, object.getClass(), value);\n HttpDelete httpDelete = new HttpDelete(uri);\n String response = send(httpDelete);\n logger.debug(response);\n }\n\n\t/**\n\t * Deletes an object.\n\t * \n\t * @param classs\n\t * object class.\n\t * @param id\n\t * object id.\n\t * @throws RedmineException\n\t * if something goes wrong.\n\t */\n\tpublic <T extends Identifiable> void deleteObject(Class<T> classs, String id)\n\t\t\tthrows RedmineException {\n\t\tfinal URI uri = getURIConfigurator().getObjectURI(classs, id);\n\t\tfinal HttpDelete http = new HttpDelete(uri);\n\t\tsend(http);\n\t}\n\n\t/**\n\t * @param classs\n\t * target class\n\t * @param key\n\t * item key\n\t * @param params\n\t * extra arguments.\n\t * @throws RedmineAuthenticationException\n\t * invalid or no API access key is used with the server, which\n\t * requires authorization. Check the constructor arguments.\n\t * @throws NotFoundException\n\t * the object with the given key is not found\n\t * @throws RedmineException\n\t */\n\tpublic <T> T getObject(Class<T> classs, String key, RequestParam... params)\n\t\t\tthrows RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(classs);\n\t\tfinal URI uri = getURIConfigurator().getObjectURI(classs, key, params);\n\t\tfinal HttpGet http = new HttpGet(uri);\n\t\tString response = send(http);\n\t\tlogger.debug(response);\n\t\treturn parseResponse(response, config.singleObjectName, config.parser);\n\t}\n\n\t/**\n\t * Downloads redmine content.\n\t * \n\t * @param uri\n\t * target uri.\n\t * @param handler\n\t * content handler.\n\t * @return handler result.\n\t * @throws RedmineException\n\t * if something goes wrong.\n\t */\n\tpublic <R> R download(String uri,\n\t\t\tContentHandler<BasicHttpResponse, R> handler)\n\t\t\tthrows RedmineException {\n\t\tfinal HttpGet request = new HttpGet(uri);\n if (onBehalfOfUser != null) {\n request.addHeader(\"X-Redmine-Switch-User\", onBehalfOfUser);\n }\n return errorCheckingCommunicator.sendRequest(request, handler);\n }\n\n\t/**\n\t * Deprecated because Redmine server can return invalid string depending on its configuration.\n\t * See https://github.com/taskadapter/redmine-java-api/issues/78 .\n\t * <p>Use {@link #upload(InputStream, long)} instead.\n\t *\n\t * <p>\n\t * Uploads content on a server. This method calls {@link #upload(InputStream, long)} with -1 as content length.\n\t * \n\t * @param content the content stream.\n\t * @return uploaded item token.\n\t * @throws RedmineException if something goes wrong.\n\t */\n\t@Deprecated\n\tpublic String upload(InputStream content) throws RedmineException {\n\t\treturn upload(content, -1);\n\t}\n\n\t/**\n\t * @param content the content\n\t * @param contentLength the length of the content in bytes. you can provide -1 but be aware that some\n\t * users reported Redmine configuration problems that prevent it from processing -1 correctly.\n\t * See https://github.com/taskadapter/redmine-java-api/issues/78 for details.\n\t * @return the string token of the uploaded item. see {@link Attachment#getToken()}\n\t */\n\tpublic String upload(InputStream content, long contentLength) throws RedmineException {\n\t\tfinal URI uploadURI = getURIConfigurator().getUploadURI();\n\t\tfinal HttpPost request = new HttpPost(uploadURI);\n\t\tfinal AbstractHttpEntity entity = new InputStreamEntity(content, contentLength);\n\t\t/* Content type required by a Redmine */\n\t\tentity.setContentType(\"application/octet-stream\");\n\t\trequest.setEntity(entity);\n\n\t\tfinal String result = send(request);\n\t\treturn parseResponse(result, \"upload\", input -> JsonInput.getStringNotNull(input, \"token\"));\n\t}\n\n\t/**\n\t * @param classs\n\t * target class\n\t * @param key\n\t * item key\n\t * @param params\n\t * extra arguments.\n\t * @throws RedmineAuthenticationException\n\t * invalid or no API access key is used with the server, which\n\t * requires authorization. Check the constructor arguments.\n\t * @throws NotFoundException\n\t * the object with the given key is not found\n\t * @throws RedmineException\n\t */\n\tpublic <T> T getObject(Class<T> classs, Integer key, RequestParam... params) throws RedmineException {\n\t\treturn getObject(classs, key.toString(), params);\n\t}\n\n\tpublic <T> List<T> getObjectsList(Class<T> objectClass, RequestParam... params) throws RedmineException {\n\t\treturn getObjectsList(objectClass, Arrays.asList(params));\n\t}\n\n\t/**\n\t * Returns all objects found using the provided parameters.\n\t * This method IGNORES \"limit\" and \"offset\" parameters and handles paging AUTOMATICALLY for you.\n\t * Please use getObjectsListNoPaging() method if you want to control paging yourself with \"limit\" and \"offset\" parameters.\n\t * \n\t * @return objects list, never NULL\n\t *\n\t * @see #getObjectsListNoPaging(Class, Collection)\n\t */\n\tpublic <T> List<T> getObjectsList(Class<T> objectClass,\n\t\t\t\t\t\t\t\t\t Collection<? extends RequestParam> params) throws RedmineException {\n\t\tfinal List<T> result = new ArrayList<>();\n\t\tint offset = 0;\n\n\t\tInteger totalObjectsFoundOnServer;\n\t\tdo {\n\t\t\tfinal List<RequestParam> newParams = new ArrayList<>(params);\n\t\t\tnewParams.add(new RequestParam(\"limit\", String.valueOf(objectsPerPage)));\n\t\t\tnewParams.add(new RequestParam(\"offset\", String.valueOf(offset)));\n\n\t\t\tfinal ResultsWrapper<T> wrapper = getObjectsListNoPaging(objectClass, newParams);\n\t\t\tresult.addAll(wrapper.getResults());\n\n\t\t\ttotalObjectsFoundOnServer = wrapper.getTotalFoundOnServer();\n\t\t\t// Necessary for trackers.\n\t\t\t// TODO Alexey: is this still necessary for Redmine 2.x?\n\t\t\tif (totalObjectsFoundOnServer == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!wrapper.hasSomeResults()) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toffset += wrapper.getResultsNumber();\n\t\t} while (offset < totalObjectsFoundOnServer);\n\t\treturn result;\n\t}\n\n\t/**\n\t * Returns an object list. Provide your own \"limit\" and \"offset\" parameters if you need those, otherwise\n\t * this method will return the first page of some default size only (this default is controlled by\n\t * your Redmine configuration).\n\t *\n\t * @return objects list, never NULL\n\t */\n\tpublic <T> ResultsWrapper<T> getObjectsListNoPaging(Class<T> objectClass,\n\t\t\t\t\t\t\t\t\t\t\t Collection<? extends RequestParam> params) throws RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(objectClass);\n\t\ttry {\n\t\t\tfinal JSONObject responseObject = getJsonResponseFromGet(objectClass, params);\n\t\t\tList<T> results = JsonInput.getListOrNull(responseObject, config.multiObjectName, config.parser);\n\t\t\tInteger totalFoundOnServer = JsonInput.getIntOrNull(responseObject, KEY_TOTAL_COUNT);\n\t\t\tInteger limitOnServer = JsonInput.getIntOrNull(responseObject, KEY_LIMIT);\n\t\t\tInteger offsetOnServer = JsonInput.getIntOrNull(responseObject, KEY_OFFSET);\n\t\t\treturn new ResultsWrapper<>(totalFoundOnServer, limitOnServer, offsetOnServer, results);\n\t\t} catch (JSONException e) {\n\t\t\tthrow new RedmineFormatException(e);\n\t\t}\n\t}\n\n\t/**\n\t * Use this method if you need direct access to Json results.\n\t <pre>\n\t Params params = new Params()\n\t .add(...)\n getJsonResponseFromGet(Issue.class, params);\n\t </pre>\n\t */\n\tpublic <T> JSONObject getJsonResponseFromGet(Class<T> objectClass,\n\t\t\t\t\t\t\t\t\t\t\t\t Collection<? extends RequestParam> params) throws RedmineException, JSONException {\n\t\tfinal List<RequestParam> newParams = new ArrayList<>(params);\n\t\tList<RequestParam> paramsList = new ArrayList<>(newParams);\n\t\tfinal URI uri = getURIConfigurator().getObjectsURI(objectClass, paramsList);\n\t\tfinal HttpGet http = new HttpGet(uri);\n\t\tfinal String response = send(http);\n\t\treturn RedmineJSONParser.getResponse(response);\n\t}\n\n\tpublic <T> List<T> getChildEntries(Class<?> parentClass, int parentId, Class<T> classs) throws RedmineException {\n\t\treturn getChildEntries(parentClass, parentId + \"\", classs);\n\t}\n\n\t/**\n\t * Delivers a list of a child entries.\n\t * \n\t * @param classs\n\t * target class.\n\t */\n\tpublic <T> List<T> getChildEntries(Class<?> parentClass, String parentKey, Class<T> classs) throws RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(classs);\n\t\tfinal URI uri = getURIConfigurator().getChildObjectsURI(parentClass,\n\t\t\t\tparentKey, classs, new RequestParam(\"limit\", String.valueOf(objectsPerPage)));\n\n\t\tHttpGet http = new HttpGet(uri);\n\t\tString response = send(http);\n\t\tfinal JSONObject responseObject;\n\t\ttry {\n\t\t\tresponseObject = RedmineJSONParser.getResponse(response);\n\t\t\treturn JsonInput.getListNotNull(responseObject, config.multiObjectName, config.parser);\n\t\t} catch (JSONException e) {\n\t\t\tthrow new RedmineFormatException(\"Bad categories response \" + response, e);\n\t\t}\n\t}\n\n /**\n * Delivers a single child entry by its identifier.\n */\n public <T> T getChildEntry(Class<?> parentClass, String parentId,\n Class<T> classs, String childId, RequestParam... params) throws RedmineException {\n final EntityConfig<T> config = getConfig(classs);\n\t\tfinal URI uri = getURIConfigurator().getChildIdURI(parentClass, parentId, classs, childId, params);\n HttpGet http = new HttpGet(uri);\n String response = send(http);\n\n return parseResponse(response, config.singleObjectName, config.parser);\n }\n\n /**\n\t * This number of objects (tasks, projects, users) will be requested from\n\t * Redmine server in 1 request.\n\t */\n\tpublic void setObjectsPerPage(int pageSize) {\n\t\tif (pageSize <= 0) {\n\t\t\tthrow new IllegalArgumentException(\"Page size must be >= 0. You provided: \" + pageSize);\n\t\t}\n\t\tthis.objectsPerPage = pageSize;\n\t}\n\t\n\tpublic void addUserToGroup(int userId, int groupId) throws RedmineException {\n\t\tlogger.debug(\"adding user \" + userId + \" to group \" + groupId + \"...\");\n\t\tURI uri = getURIConfigurator().getChildObjectsURI(Group.class, Integer.toString(groupId), User.class);\n\t\tHttpPost httpPost = new HttpPost(uri);\n\t\tfinal StringWriter writer = new StringWriter();\n\t\tfinal JSONWriter jsonWriter = new JSONWriter(writer);\n\t\ttry {\n\t\t\tjsonWriter.object().key(\"user_id\").value(userId).endObject();\n\t\t} catch (JSONException e) {\n\t\t\tthrow new RedmineInternalError(\"Unexpected exception\", e);\n\t\t}\n\t\tString body = writer.toString();\n\t\tsetEntity(httpPost, body);\n\t\tString response = send(httpPost);\n\t\tlogger.debug(response);\n\t}\n\n\tpublic void addWatcherToIssue(int watcherId, int issueId) throws RedmineException {\n\t\tlogger.debug(\"adding watcher \" + watcherId + \" to issue \" + issueId + \"...\");\n\t\tURI uri = getURIConfigurator().getChildObjectsURI(Issue.class, Integer.toString(issueId), Watcher.class);\n\t\tHttpPost httpPost = new HttpPost(uri);\n\t\tfinal StringWriter writer = new StringWriter();\n\t\tfinal JSONWriter jsonWriter = new JSONWriter(writer);\n\t\ttry {\n\t\t\tjsonWriter.object().key(\"user_id\").value(watcherId).endObject();\n\t\t} catch (JSONException e) {\n\t\t\tthrow new RedmineInternalError(\"Unexpected exception\", e);\n\t\t}\n\t\tString body = writer.toString();\n\t\tsetEntity(httpPost, body);\n\t\tString response = send(httpPost);\n\t\tlogger.debug(response);\n\t}\n\n private String send(HttpRequestBase http) throws RedmineException {\n if (onBehalfOfUser != null) {\n http.addHeader(\"X-Redmine-Switch-User\", onBehalfOfUser);\n }\n return communicator.sendRequest(http);\n }\n\n\tprivate <T> T parseResponse(String response, String tag,\n JsonObjectParser<T> parser) throws RedmineFormatException {\n\t\ttry {\n\t\t\tT parse = parser.parse(RedmineJSONParser.getResponseSingleObject(response, tag));\n\t\t\tif (parse instanceof FluentStyle) {\n\t\t\t\t((FluentStyle) parse).setTransport(this);\n\t\t\t}\n\t\t\treturn parse;\n\t\t} catch (JSONException e) {\n\t\t\tthrow new RedmineFormatException(e);\n\t\t}\n\t}\n\n\tprivate static void setEntity(HttpEntityEnclosingRequest request, String body) {\n\t\tsetEntity(request, body, CONTENT_TYPE);\n\t}\n\n\tprivate static void setEntity(HttpEntityEnclosingRequest request, String body, String contentType) {\n\t\tStringEntity entity;\n\t\ttry {\n\t\t\tentity = new StringEntity(body, CHARSET);\n\t\t} catch (UnsupportedCharsetException e) {\n\t\t\tthrow new RedmineInternalError(\"Required charset \" + CHARSET\n\t\t\t\t\t+ \" is not supported\", e);\n\t\t}\n\t\tentity.setContentType(contentType);\n\t\trequest.setEntity(entity);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate <T> EntityConfig<T> getConfig(Class<?> class1) {\n\t\tfinal EntityConfig<?> guess = OBJECT_CONFIGS.get(class1);\n\t\tif (guess == null)\n\t\t\tthrow new RedmineInternalError(\"Unsupported class \" + class1);\n\t\treturn (EntityConfig<T>) guess;\n\t}\n\n\tprivate URIConfigurator getURIConfigurator() {\n\t\treturn configurator;\n\t}\n\n\tprivate static <T> EntityConfig<T> config(String objectField,\n\t\t\tString urlPrefix, JsonObjectWriter<T> writer,\n\t\t\tJsonObjectParser<T> parser) {\n\t\treturn new EntityConfig<>(objectField, urlPrefix, writer, parser);\n\t}\n\n /**\n * This works only when the main authentication has led to Redmine Admin level user.\n * The given user name will be sent to the server in \"X-Redmine-Switch-User\" HTTP Header\n * to indicate that the action (create issue, delete issue, etc) must be done\n * on behalf of the given user name.\n *\n * @param loginName Redmine user login name to provide to the server\n *\n * @see <a href=\"http://www.redmine.org/issues/11755\">Redmine issue 11755</a>\n */\n public void setOnBehalfOfUser(String loginName) {\n this.onBehalfOfUser = loginName;\n }\n\n\t/**\n\t * Entity config.\n\t */\n\tstatic class EntityConfig<T> {\n\t\tfinal String singleObjectName;\n\t\tfinal String multiObjectName;\n\t\tfinal JsonObjectWriter<T> writer;\n\t\tfinal JsonObjectParser<T> parser;\n\n\t\tpublic EntityConfig(String objectField, String urlPrefix,\n\t\t\t\tJsonObjectWriter<T> writer, JsonObjectParser<T> parser) {\n\t\t\tsuper();\n\t\t\tthis.singleObjectName = objectField;\n\t\t\tthis.multiObjectName = urlPrefix;\n\t\t\tthis.writer = writer;\n\t\t\tthis.parser = parser;\n\t\t}\n\t}\n\n}",
"public class MarkedIOException extends IOException {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate final String tag;\n\n\tpublic MarkedIOException(String tag, IOException cause) {\n\t\tsuper(cause);\n\t\tthis.tag = tag;\n\t}\n\n\tpublic String getTag() {\n\t\treturn tag;\n\t}\n\n\tpublic IOException getIOException() {\n\t\treturn (IOException) getCause();\n\t}\n\n}",
"public final class MarkedInputStream extends FilterInputStream {\n\n\tprivate final String tag;\n\n\tpublic MarkedInputStream(InputStream in, String tag) {\n\t\tsuper(in);\n\t\tthis.tag = tag;\n\t}\n\n\t@Override\n\tpublic int available() throws IOException {\n\t\ttry {\n\t\t\treturn super.available();\n\t\t} catch (IOException e) {\n\t\t\tthrow new MarkedIOException(tag, e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void close() throws IOException {\n\t\ttry {\n\t\t\tsuper.close();\n\t\t} catch (IOException e) {\n\t\t\tthrow new MarkedIOException(tag, e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic int read() throws IOException {\n\t\ttry {\n\t\t\treturn super.read();\n\t\t} catch (IOException e) {\n\t\t\tthrow new MarkedIOException(tag, e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic int read(byte[] b) throws IOException {\n\t\ttry {\n\t\t\treturn super.read(b);\n\t\t} catch (IOException e) {\n\t\t\tthrow new MarkedIOException(tag, e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic int read(byte[] b, int off, int len) throws IOException {\n\t\ttry {\n\t\t\treturn super.read(b, off, len);\n\t\t} catch (IOException e) {\n\t\t\tthrow new MarkedIOException(tag, e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void reset() throws IOException {\n\t\ttry {\n\t\t\tsuper.reset();\n\t\t} catch (IOException e) {\n\t\t\tthrow new MarkedIOException(tag, e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic long skip(long n) throws IOException {\n\t\ttry {\n\t\t\treturn super.skip(n);\n\t\t} catch (IOException e) {\n\t\t\tthrow new MarkedIOException(tag, e);\n\t\t}\n\t}\n}"
] | import com.taskadapter.redmineapi.bean.Attachment;
import com.taskadapter.redmineapi.bean.Issue;
import com.taskadapter.redmineapi.internal.CopyBytesHandler;
import com.taskadapter.redmineapi.internal.Transport;
import com.taskadapter.redmineapi.internal.io.MarkedIOException;
import com.taskadapter.redmineapi.internal.io.MarkedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; | package com.taskadapter.redmineapi;
/**
* Works with Attachments (files).
* <p>Obtain it via RedmineManager:
* <pre>
RedmineManager redmineManager = RedmineManagerFactory.createWithUserAuth(redmineURI, login, password);
AttachmentManager attachmentManager = redmineManager.getAttachmentManager();
* </pre>
*
* <p>Sample usage:
* <pre>
File file = ...
attachmentManager.addAttachmentToIssue(issueId, file, ContentType.TEXT_PLAIN.getMimeType());
* </pre>
*
* @see RedmineManager#getAttachmentManager()
*/
public class AttachmentManager {
private final Transport transport;
AttachmentManager(Transport transport) {
this.transport = transport;
}
/**
*
* @param issueId database ID of the Issue
* @param attachmentFile the file to upload
* @param contentType MIME type. depending on this parameter, the file will be recognized by the server as
* text or image or binary. see http://en.wikipedia.org/wiki/Internet_media_type for possible MIME types.
* sample value: ContentType.TEXT_PLAIN.getMimeType()
* @return the created attachment object.
*/ | public Attachment addAttachmentToIssue(Integer issueId, File attachmentFile, String contentType) throws RedmineException, IOException { | 0 |
unruly/control | src/test/java/co/unruly/control/pair/PairTest.java | [
"static <K, V> Pair<K, V> entry(K key, V value) {\n return Pair.of(key, value);\n}",
"@SafeVarargs\nstatic <K, V> Map<K, V> mapOf(Pair<K, V> ...entries) {\n return Stream.of(entries).collect(toMap());\n}",
"static <K, V> Collector<Pair<K, V>, ?, Map<K, V>> toMap() {\n return Collectors.toMap(Pair::left, Pair::right);\n}",
"public interface Pairs {\n\n /**\n * Applies the given function to the left element of a Pair, returning a new Pair with the result of that\n * function as the left element and the original right element untouched\n */\n static <OL, NL, R> Function<Pair<OL, R>, Pair<NL, R>> onLeft(Function<? super OL, NL> leftMapper) {\n return pair -> Pair.of(leftMapper.apply(pair.left), pair.right);\n }\n\n /**\n * Applies the given function to the right element of a Pair, returning a new Pair with the result of that\n * function as the right element and the original left element untouched\n */\n static <L, OR, NR> Function<Pair<L, OR>, Pair<L, NR>> onRight(Function<OR, NR> rightMapper) {\n return pair -> Pair.of(pair.left, rightMapper.apply(pair.right));\n }\n\n /**\n * Applies the given function to both elements off a Pair, assuming that both elements are of the\n * same type\n */\n static <T, R> Function<Pair<T, T>, Pair<R, R>> onBoth(Function<T, R> f) {\n return pair -> Pair.of(f.apply(pair.left), f.apply(pair.right));\n }\n\n /**\n * Applies the given function to both elements off a Pair, yielding a non-Pair value\n */\n static <L, R, T> Function<Pair<L, R>, T> merge(BiFunction<L, R, T> f) {\n return pair -> pair.then(f);\n }\n\n /**\n * Merges a Pair of Lists of T into a single List of T, with the left items at the front of the list.\n */\n static <T> Function<Pair<List<T>, List<T>>, List<T>> mergeLists() {\n return pair -> Stream.of(pair.left, pair.right).flatMap(List::stream).collect(toList());\n }\n\n /**\n * Collects a Stream of Pairs into a single Pair of lists, where a given index can be used to access the left\n * and right parts of the input pairs respectively.\n */\n static <L, R> Collector<Pair<L, R>, Pair<List<L>, List<R>>, Pair<List<L>, List<R>>> toParallelLists() {\n return using(Collections::unmodifiableList, Collections::unmodifiableList);\n }\n\n /**\n * Collects a Stream of Pairs into a single Pair of arrays, where a given index can be used to access the left\n * and right parts of the input pairs respectively.\n */\n static <L, R> Collector<Pair<L, R>, Pair<List<L>, List<R>>, Pair<L[], R[]>> toArrays(IntFunction<L[]> leftArrayConstructor, IntFunction<R[]> rightArrayConstructor) {\n return using(\n left -> left.stream().toArray(leftArrayConstructor),\n right -> right.stream().toArray(rightArrayConstructor)\n );\n }\n\n /**\n * Reduces a stream of pairs to a single pair, using the provided identities and reducer functions\n */\n static <L, R> PairReducingCollector<L, R> reducing(\n L leftIdentity, BinaryOperator<L> leftReducer,\n R rightIdentity, BinaryOperator<R> rightReducer) {\n return new PairReducingCollector<>(leftIdentity, rightIdentity, leftReducer, rightReducer);\n }\n\n\n static <L, R, FL, FR> Collector<Pair<L, R>, Pair<List<L>, List<R>>, Pair<FL, FR>> using(\n Function<List<L>, FL> leftFinisher,\n Function<List<R>, FR> rightFinisher) {\n return new PairListCollector<>(leftFinisher, rightFinisher);\n }\n\n /**\n * If there are any elements in the right side of the Pair, return a failure of\n * the right side, otherwise return a success of the left.\n */\n static <L, R> Result<List<L>, List<R>> anyFailures(Pair<List<L>, List<R>> sides) {\n return sides.right.isEmpty() ? success(sides.left) : failure(sides.right);\n }\n\n /**\n * If there are any elements in the left side of the Pair, return a success of\n * the left side, otherwise return a failure of the left.\n */\n static <L, R> Result<List<L>, List<R>> anySuccesses(Pair<List<L>, List<R>> sides) {\n return sides.left.isEmpty() ? failure(sides.right) : success(sides.left);\n }\n}",
"static <L, R> Optional<Pair<L, R>> allOf(Optional<L> maybeLeft, Optional<R> maybeRight) {\n return maybeLeft.flatMap(left ->\n maybeRight.map(right ->\n Pair.of(left, right)));\n}",
"static <L, R, T> Function<Pair<L, R>, T> onAll(BiFunction<L, R, T> f) {\n return pair -> pair.then(f);\n}"
] | import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import static co.unruly.control.pair.Maps.entry;
import static co.unruly.control.pair.Maps.mapOf;
import static co.unruly.control.pair.Maps.toMap;
import static co.unruly.control.pair.Pairs.*;
import static co.unruly.control.pair.Comprehensions.allOf;
import static co.unruly.control.pair.Comprehensions.onAll;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat; | package co.unruly.control.pair;
public class PairTest {
@Test
public void canTransformStreamOfPairs() {
List<Pair<Integer, String>> transformedPairs = Stream.of(Pair.of(2, "hello"), Pair.of(4, "goodbye"))
.map(onLeft(x -> x * 3))
.map(onRight(String::toUpperCase))
.collect(toList());
assertThat(transformedPairs, CoreMatchers.hasItems(Pair.of(6, "HELLO"), Pair.of(12, "GOODBYE")));
}
@Test
public void canTransformAnIndividualPair() {
Pair<Integer, String> transformedPair = Pair.of(2, "hello")
.then(onLeft(x -> x * 3))
.then(onRight(String::toUpperCase));
assertThat(transformedPair, is(Pair.of(6, "HELLO")));
}
@Test
public void canCollectToParallelLists() {
Pair<List<Integer>, List<String>> parallelLists = Stream.of(Pair.of(2, "hello"), Pair.of(4, "goodbye"))
.collect(toParallelLists());
assertThat(parallelLists, is(Pair.of(asList(2, 4), asList("hello", "goodbye"))));
}
@Test
public void canCollectToParallelArrays() {
Pair<Integer[], String[]> parallelArrays = Stream.of(Pair.of(2, "hello"), Pair.of(4, "goodbye"))
.collect(toArrays(Integer[]::new, String[]::new));
assertThat(asList(parallelArrays.left), is(asList(2, 4)));
assertThat(asList(parallelArrays.right), is(asList("hello", "goodbye")));
}
@Test
public void canReduceAStreamOfPairs() {
Pair<Integer, String> reduced = Stream.of(Pair.of(2, "hello"), Pair.of(4, "goodbye"))
.collect(reducing(
0, (x, y) -> x + y,
"", String::concat
));
assertThat(reduced, is(Pair.of(6, "hellogoodbye")));
}
@Test
public void canCreateMaps() {
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("hello", "world");
expectedMap.put("six of one", "half a dozen of the other");
Map<String, String> actualMap = mapOf(
entry("hello", "world"),
entry("six of one", "half a dozen of the other")
);
assertThat(actualMap, is(expectedMap));
}
@Test
public void canCollectPairsIntoMap() {
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("hello", "world");
expectedMap.put("six of one", "half a dozen of the other");
Map<String, String> actualMap = Stream.of(
entry("hello", "world"),
entry("six of one", "half a dozen of the other")
).collect(toMap());
assertThat(actualMap, is(expectedMap));
}
@Test
public void canAggregateOptionalPairs() {
Optional<String> actual = allOf(
Optional.of("hello"),
Optional.of("world") | ).map(onAll((a, b) -> a + ", " + b)); | 5 |
emina/kodkod | test/kodkod/test/sys/ExamplesTestWithRegularSolver.java | [
"public final class Solution {\n\tprivate final Outcome outcome;\n\tprivate final Statistics stats;\n\tprivate final Instance instance;\n\tprivate final Proof proof;\n\n\t\n\t/**\n\t * Constructs a Solution from the given values.\n\t * @requires outcome != null && stats != null\n\t * @requires outcome = SATISFIABLE || TRIVIALLY_SATISFIABLE => instance != null\n\t */\n\tprivate Solution(Outcome outcome, Statistics stats, Instance instance, Proof proof) {\n\t\tassert outcome != null && stats != null;\n\t\tthis.outcome = outcome;\n\t\tthis.stats = stats;\n\t\tthis.instance = instance;\n\t\tthis.proof = proof;\n\t}\n\t\n\t/**\n\t * Returns a new Solution with a SATISFIABLE outcome, given stats and instance.\n\t * @return {s: Solution | s.outcome() = SATISFIABLE && s.stats() = stats && s.instance() = instance }\n\t */\n\tstatic Solution satisfiable(Statistics stats, Instance instance) {\n\t\treturn new Solution(Outcome.SATISFIABLE, stats, instance, null);\n\t}\n\t\n\t/**\n\t * Returns a new Solution with a TRIVIALLY_SATISFIABLE outcome, given stats and instance.\n\t * @return {s: Solution | s.outcome() = TRIVIALLY_SATISFIABLE && s.stats() = stats && s.instance() = instance }\n\t */\n\tstatic Solution triviallySatisfiable(Statistics stats, Instance instance) {\n\t\treturn new Solution(Outcome.TRIVIALLY_SATISFIABLE, stats, instance, null);\n\t}\n\t\n\t/**\n\t * Returns a new Solution with a UNSATISFIABLE outcome, given stats and proof.\n\t * @return {s: Solution | s.outcome() = UNSATISFIABLE && s.stats() = stats && s.proof() = proof }\n\t */\n\tstatic Solution unsatisfiable(Statistics stats, Proof proof) {\n\t\treturn new Solution(Outcome.UNSATISFIABLE, stats, null, proof);\n\t}\n\t\n\t/**\n\t * Returns a new Solution with a TRIVIALLY_UNSATISFIABLE outcome, given stats and proof.\n\t * @return {s: Solution | s.outcome() = TRIVIALLY_UNSATISFIABLE && s.stats() = stats && s.proof() = proof }\n\t */\n\tstatic Solution triviallyUnsatisfiable(Statistics stats, Proof proof) {\n\t\treturn new Solution(Outcome.TRIVIALLY_UNSATISFIABLE, stats, null, proof);\n\t}\n\t\t\n\t/**\n\t * Returns the outcome of the attempt to find\n\t * a model for this.formula. If the outcome is \n\t * SATISFIABLE or TRIVIALLY_SATISFIABLE, a satisfying \n\t * instance can be obtained by calling {@link #instance()}.\n\t * If the formula is UNSATISFIABLE, a proof of unsatisfiability\n\t * can be obtained by calling {@link #proof()} provided that\n\t * translation logging was enabled and the unsatisfiability was\n\t * determined using a core extracting \n\t * {@link kodkod.engine.satlab.SATSolver sat solver}.\n\t * Lastly, if the returned Outcome is\n\t * or TRIVIALLY_UNSATISFIABLE, a proof of unsatisfiability can\n\t * be obtained by calling {@link #proof()} provided that\n\t * translation logging was enabled.\n\t * @return an Outcome instance designating the \n\t * satisfiability of this.formula with respect to this.bounds\n\t */\n\tpublic Outcome outcome() {\n\t\treturn outcome;\n\t}\n\t\n\t/**\n\t * Returns true iff this solution has a (trivially) satisfiable outcome.\n\t * @return this.outcome = Outcome.SATISFIABLE || this.outcome = Outcome.TRIVIALLY_SATISFIABLE\n\t */\n\tpublic final boolean sat() {\n\t\treturn outcome==Outcome.SATISFIABLE || outcome==Outcome.TRIVIALLY_SATISFIABLE;\n\t}\n\t\n\t/**\n\t * Returns true iff this solution has a (trivially) unsatisfiable outcome.\n\t * @return this.outcome = Outcome.UNSATISFIABLE || this.outcome = Outcome.TRIVIALLY_UNSATISFIABLE\n\t */\n\tpublic final boolean unsat() {\n\t\treturn outcome==Outcome.UNSATISFIABLE || outcome==Outcome.TRIVIALLY_UNSATISFIABLE;\n\t}\n\t\n\t/**\n\t * Returns a satisfiying instance for this.formula, if the\n\t * value returned by {@link #outcome() this.outcome()} is either\n\t * SATISFIABLE or TRIVIALLY_SATISFIABLE. Otherwise returns null.\n\t * @return a satisfying instance for this.formula, if one exists.\n\t */\n\tpublic Instance instance() {\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Returns a proof of this.formula's unsatisfiability if the value \n\t * returned by {@link #outcome() this.outcome()} is UNSATISFIABLE or\n\t * TRIVIALLY_UNSATISFIABLE, translation logging was enabled during solving, \n\t * and a core extracting {@link kodkod.engine.satlab.SATProver sat solver} (if any)\n\t * was used to determine unsatisfiability.\n\t * Otherwise, null is returned. \n\t * @return a proof of this.formula's unsatisfiability, if one is available.\n\t */\n\tpublic Proof proof() {\n\t\treturn proof;\n\t}\n\t\n\t/**\n\t * Returns the statistics gathered while solving\n\t * this.formula.\n\t * @return the statistics gathered while solving\n\t * this.formula.\n\t */\n\tpublic Statistics stats() {\n\t\treturn stats;\n\t}\n\t\n\t/**\n\t * Returns a string representation of this Solution.\n\t * @return a string representation of this Solution.\n\t */\n\tpublic String toString() {\n\t\tfinal StringBuilder b = new StringBuilder();\n\t\tb.append(\"---OUTCOME---\\n\");\n\t\tb.append(outcome);\n\t\tb.append(\"\\n\");\n\t\tif (instance!=null) {\n\t\t\tb.append(\"\\n---INSTANCE---\\n\");\n\t\t\tb.append(instance);\n\t\t\tb.append(\"\\n\");\n\t\t}\n\t\tif (proof!=null) {\n\t\t\tb.append(\"\\n---PROOF---\\n\");\n\t\t\tb.append(proof);\n\t\t\tb.append(\"\\n\");\n\t\t}\n\t\tb.append(\"\\n---STATS---\\n\");\n\t\tb.append(stats);\n\t\tb.append(\"\\n\");\n\t\treturn b.toString();\n\t}\n\t\n\t/**\n\t * Enumerates the possible outcomes of an attempt\n\t * to find a model for a FOL formula.\n\t */\n\tpublic static enum Outcome {\n\t\t/** The formula is satisfiable with respect to the specified bounds. */\n\t\tSATISFIABLE,\n\t\t/** The formula is unsatisfiable with respect to the specified bounds. */\n\t\tUNSATISFIABLE,\n\t\t/** \n\t\t * The formula is trivially satisfiable with respect to the specified bounds: \n\t\t * a series of simple transformations reduces the formula to the constant TRUE. \n\t\t **/\n\t\tTRIVIALLY_SATISFIABLE,\n\t\t/**\n\t\t * The formula is trivially unsatisfiable with respect to the specified bounds:\n\t\t * a series of simple transformations reduces the formula to the constant FALSE. \n\t\t */\n\t\tTRIVIALLY_UNSATISFIABLE;\n\t\t\n\t}\n\t\n}",
"public final class Solver implements KodkodSolver {\n\tprivate final Options options;\n\n\t/**\n\t * Constructs a new Solver with the default options.\n\t * @ensures this.options' = new Options()\n\t */\n\tpublic Solver() {\n\t\tthis.options = new Options();\n\t}\n\n\t/**\n\t * Constructs a new Solver with the given options.\n\t * @ensures this.options' = options\n\t * @throws NullPointerException options = null\n\t */\n\tpublic Solver(Options options) {\n\t\tif (options == null)\n\t\t\tthrow new NullPointerException();\n\t\tthis.options = options;\n\t}\n\n\t/**\n\t * Returns the Options object used by this Solver\n\t * to guide translation of formulas from first-order\n\t * logic to cnf.\n\t * @return this.options\n\t */\n\tpublic Options options() {\n\t\treturn options;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @see kodkod.engine.KodkodSolver#free()\n\t */\n\tpublic void free() {}\n\t\n\t/**\n\t * Attempts to satisfy the given {@code formula} and {@code bounds} with respect to \n\t * {@code this.options} or, optionally, prove the problem's unsatisfiability. If the method \n\t * completes normally, the result is a {@linkplain Solution solution} containing either an \n\t * {@linkplain Instance instance} of the given problem or, optionally, a {@linkplain Proof proof} of \n\t * its unsatisfiability. An unsatisfiability\n\t * proof will be constructed iff {@code this.options.solver} specifies a {@linkplain SATProver} and \n\t * {@code this.options.logTranslation > 0}.\n\t * \n\t * @return some sol: {@link Solution} | \n\t * some sol.instance() => \n\t * sol.instance() in MODELS(formula, bounds, this.options) else \n\t * UNSAT(formula, bound, this.options) \n\t * \n\t * @throws NullPointerException formula = null || bounds = null\n\t * @throws UnboundLeafException the formula contains an undeclared variable or a relation not mapped by the given bounds\n\t * @throws HigherOrderDeclException the formula contains a higher order declaration that cannot\n\t * be skolemized, or it can be skolemized but {@code this.options.skolemDepth} is insufficiently large\n\t * @throws AbortedException this solving task was aborted \n\t * @see Options\n\t * @see Solution\n\t * @see Instance\n\t * @see Proof\n\t */\n\tpublic Solution solve(Formula formula, Bounds bounds) throws HigherOrderDeclException, UnboundLeafException, AbortedException {\n\t\t\n\t\tfinal long startTransl = System.currentTimeMillis();\n\t\t\n\t\ttry {\t\t\t\n\t\t\tfinal Translation.Whole translation = Translator.translate(formula, bounds, options);\n\t\t\tfinal long endTransl = System.currentTimeMillis();\n\t\t\t\n\t\t\tif (translation.trivial())\n\t\t\t\treturn trivial(translation, endTransl - startTransl);\n\n\t\t\tfinal SATSolver cnf = translation.cnf();\n\t\t\t\n\t\t\toptions.reporter().solvingCNF(translation.numPrimaryVariables(), cnf.numberOfVariables(), cnf.numberOfClauses());\n\t\t\tfinal long startSolve = System.currentTimeMillis();\n\t\t\tfinal boolean isSat = cnf.solve();\n\t\t\tfinal long endSolve = System.currentTimeMillis();\n\n\t\t\tfinal Statistics stats = new Statistics(translation, endTransl - startTransl, endSolve - startSolve);\n\t\t\treturn isSat ? sat(translation, stats) : unsat(translation, stats);\n\t\t\t\n\t\t} catch (SATAbortedException sae) {\n\t\t\tthrow new AbortedException(sae);\n\t\t}\n\t}\n\t\n\t/**\n\t * Attempts to find all solutions to the given formula with respect to the specified bounds or\n\t * to prove the formula's unsatisfiability.\n\t * If the operation is successful, the method returns an iterator over n Solution objects. The outcome\n\t * of the first n-1 solutions is SAT or trivially SAT, and the outcome of the nth solution is UNSAT\n\t * or trivially UNSAT. Note that an unsatisfiability\n\t * proof will be constructed for the last solution iff this.options specifies the use of a core extracting SATSolver.\n\t * Additionally, the CNF variables in the proof can be related back to the nodes in the given formula \n\t * iff this.options has variable tracking enabled. Translation logging also requires that \n\t * there are no subnodes in the given formula that are both syntactically shared and contain free variables. \n\t * \n\t * @return an iterator over all the Solutions to the formula with respect to the given bounds\n\t * @throws NullPointerException formula = null || bounds = null\n\t * @throws kodkod.engine.fol2sat.UnboundLeafException the formula contains an undeclared variable or\n\t * a relation not mapped by the given bounds\n\t * @throws kodkod.engine.fol2sat.HigherOrderDeclException the formula contains a higher order declaration that cannot\n\t * be skolemized, or it can be skolemized but this.options.skolemize is false.\n\t * @throws AbortedException this solving task was interrupted with a call to Thread.interrupt on this thread\n\t * @throws IllegalStateException !this.options.solver().incremental()\n\t * @see Solution\n\t * @see Options\n\t * @see Proof\n\t */\n\tpublic Iterator<Solution> solveAll(final Formula formula, final Bounds bounds) \n\t\tthrows HigherOrderDeclException, UnboundLeafException, AbortedException {\n\t\t\n\t\tif (!options.solver().incremental())\n\t\t\tthrow new IllegalArgumentException(\"cannot enumerate solutions without an incremental solver.\");\n\t\t\n\t\treturn new SolutionIterator(formula, bounds, options);\n\t\t\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @see java.lang.Object#toString()\n\t */\n\tpublic String toString() {\n\t\treturn options.toString();\n\t}\n\t\n\t/**\n\t * Returns the result of solving a sat formula.\n\t * @param bounds Bounds with which solve() was called\n\t * @param translation the translation\n\t * @param stats translation / solving stats\n\t * @return the result of solving a sat formula.\n\t */\n\tprivate static Solution sat(Translation.Whole translation, Statistics stats) {\n\t\tfinal Solution sol = Solution.satisfiable(stats, translation.interpret());\n\t\ttranslation.cnf().free();\n\t\treturn sol;\n\t}\n\n\t/**\n\t * Returns the result of solving an unsat formula.\n\t * @param translation the translation \n\t * @param stats translation / solving stats\n\t * @return the result of solving an unsat formula.\n\t */\n\tprivate static Solution unsat(Translation.Whole translation, Statistics stats) {\n\t\tfinal SATSolver cnf = translation.cnf();\n\t\tfinal TranslationLog log = translation.log();\n\t\tif (cnf instanceof SATProver && log != null) {\n\t\t\treturn Solution.unsatisfiable(stats, new ResolutionBasedProof((SATProver) cnf, log));\n\t\t} else { // can free memory\n\t\t\tfinal Solution sol = Solution.unsatisfiable(stats, null);\n\t\t\tcnf.free();\n\t\t\treturn sol;\n\t\t}\n\t}\n\t\n\t/**\n\t * Returns the result of solving a trivially (un)sat formula.\n\t * @param translation trivial translation produced as the result of {@code translation.formula} \n\t * simplifying to a constant with respect to {@code translation.bounds}\n\t * @param translTime translation time\n\t * @return the result of solving a trivially (un)sat formula.\n\t */\n\tprivate static Solution trivial(Translation.Whole translation, long translTime) {\n\t\tfinal Statistics stats = new Statistics(0, 0, 0, translTime, 0);\n\t\tfinal Solution sol;\n\t\tif (translation.cnf().solve()) {\n\t\t\tsol = Solution.triviallySatisfiable(stats, translation.interpret());\n\t\t} else {\n\t\t\tsol = Solution.triviallyUnsatisfiable(stats, trivialProof(translation.log()));\n\t\t}\n\t\ttranslation.cnf().free();\n\t\treturn sol;\n\t}\n\t\n\t/**\n\t * Returns a proof for the trivially unsatisfiable log.formula,\n\t * provided that log is non-null. Otherwise returns null.\n\t * @requires log != null => log.formula is trivially unsatisfiable\n\t * @return a proof for the trivially unsatisfiable log.formula,\n\t * provided that log is non-null. Otherwise returns null.\n\t */\n\tprivate static Proof trivialProof(TranslationLog log) {\n\t\treturn log==null ? null : new TrivialProof(log);\n\t}\n\t\t\n\t/**\n\t * An iterator over all solutions of a model.\n\t * @author Emina Torlak\n\t */\n\tprivate static final class SolutionIterator implements Iterator<Solution> {\n\t\tprivate Translation.Whole translation;\n\t\tprivate long translTime;\n\t\tprivate int trivial;\n\t\t\n\t\t/**\n\t\t * Constructs a solution iterator for the given formula, bounds, and options.\n\t\t */\n\t\tSolutionIterator(Formula formula, Bounds bounds, Options options) {\n\t\t\tthis.translTime = System.currentTimeMillis();\n\t\t\tthis.translation = Translator.translate(formula, bounds, options);\n\t\t\tthis.translTime = System.currentTimeMillis() - translTime;\n\t\t\tthis.trivial = 0;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns true if there is another solution.\n\t\t * @see java.util.Iterator#hasNext()\n\t\t */\n\t\tpublic boolean hasNext() { return translation != null; }\n\t\t\n\t\t/**\n\t\t * Returns the next solution if any.\n\t\t * @see java.util.Iterator#next()\n\t\t */\n\t\tpublic Solution next() {\n\t\t\tif (!hasNext()) throw new NoSuchElementException();\t\t\t\n\t\t\ttry {\n\t\t\t\treturn translation.trivial() ? nextTrivialSolution() : nextNonTrivialSolution();\n\t\t\t} catch (SATAbortedException sae) {\n\t\t\t\ttranslation.cnf().free();\n\t\t\t\tthrow new AbortedException(sae);\n\t\t\t}\n\t\t}\n\n\t\t/** @throws UnsupportedOperationException */\n\t\tpublic void remove() { throw new UnsupportedOperationException(); }\n\t\t\n\t\t/**\n\t\t * Solves {@code translation.cnf} and adds the negation of the\n\t\t * found model to the set of clauses. The latter has the \n\t\t * effect of forcing the solver to come up with the next solution\n\t\t * or return UNSAT. If {@code this.translation.cnf.solve()} is false, \n\t\t * sets {@code this.translation} to null.\n\t\t * @requires this.translation != null\n\t\t * @ensures this.translation.cnf is modified to eliminate\n\t\t * the current solution from the set of possible solutions\n\t\t * @return current solution\n\t\t */\n\t\tprivate Solution nextNonTrivialSolution() {\n\t\t\tfinal Translation.Whole transl = translation;\n\t\t\t\n\t\t\tfinal SATSolver cnf = transl.cnf();\n\t\t\tfinal int primaryVars = transl.numPrimaryVariables();\n\t\t\t\n\t\t\ttransl.options().reporter().solvingCNF(primaryVars, cnf.numberOfVariables(), cnf.numberOfClauses());\n\t\t\t\n\t\t\tfinal long startSolve = System.currentTimeMillis();\n\t\t\tfinal boolean isSat = cnf.solve();\n\t\t\tfinal long endSolve = System.currentTimeMillis();\n\n\t\t\tfinal Statistics stats = new Statistics(transl, translTime, endSolve - startSolve);\n\t\t\tfinal Solution sol;\n\t\t\t\n\t\t\tif (isSat) {\t\t\t\n\t\t\t\t// extract the current solution; can't use the sat(..) method because it frees the sat solver\n\t\t\t\tsol = Solution.satisfiable(stats, transl.interpret());\n\t\t\t\t// add the negation of the current model to the solver\n\t\t\t\tfinal int[] notModel = new int[primaryVars];\n\t\t\t\tfor(int i = 1; i <= primaryVars; i++) {\n\t\t\t\t\tnotModel[i-1] = cnf.valueOf(i) ? -i : i;\n\t\t\t\t}\n\t\t\t\tcnf.addClause(notModel);\n\t\t\t} else {\n\t\t\t\tsol = unsat(transl, stats); // this also frees up solver resources, if any\n\t\t\t\ttranslation = null; // unsat, no more solutions\n\t\t\t}\n\t\t\treturn sol;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns the trivial solution corresponding to the trivial translation stored in {@code this.translation},\n\t\t * and if {@code this.translation.cnf.solve()} is true, sets {@code this.translation} to a new translation \n\t\t * that eliminates the current trivial solution from the set of possible solutions. The latter has the effect \n\t\t * of forcing either the translator or the solver to come up with the next solution or return UNSAT.\n\t\t * If {@code this.translation.cnf.solve()} is false, sets {@code this.translation} to null.\n\t\t * @requires this.translation != null\n\t\t * @ensures this.translation is modified to eliminate the current trivial solution from the set of possible solutions\n\t\t * @return current solution\n\t\t */\n\t\tprivate Solution nextTrivialSolution() {\n\t\t\tfinal Translation.Whole transl = this.translation;\n\t\t\t\n\t\t\tfinal Solution sol = trivial(transl, translTime); // this also frees up solver resources, if unsat\n\t\t\t\n\t\t\tif (sol.instance()==null) {\n\t\t\t\ttranslation = null; // unsat, no more solutions\n\t\t\t} else {\n\t\t\t\ttrivial++;\n\t\t\t\t\n\t\t\t\tfinal Bounds bounds = transl.bounds();\n\t\t\t\tfinal Bounds newBounds = bounds.clone();\n\t\t\t\tfinal List<Formula> changes = new ArrayList<Formula>();\n\n\t\t\t\tfor(Relation r : bounds.relations()) {\n\t\t\t\t\tfinal TupleSet lower = bounds.lowerBound(r); \n\t\t\t\t\t\n\t\t\t\t\tif (lower != bounds.upperBound(r)) { // r may change\n\t\t\t\t\t\tif (lower.isEmpty()) { \n\t\t\t\t\t\t\tchanges.add(r.some());\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfinal Relation rmodel = Relation.nary(r.name()+\"_\"+trivial, r.arity());\n\t\t\t\t\t\t\tnewBounds.boundExactly(rmodel, lower);\t\n\t\t\t\t\t\t\tchanges.add(r.eq(rmodel).not());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// nothing can change => there can be no more solutions (besides the current trivial one).\n\t\t\t\t// note that transl.formula simplifies to the constant true with respect to \n\t\t\t\t// transl.bounds, and that newBounds is a superset of transl.bounds.\n\t\t\t\t// as a result, finding the next instance, if any, for transl.formula.and(Formula.or(changes)) \n\t\t\t\t// with respect to newBounds is equivalent to finding the next instance of Formula.or(changes) alone.\n\t\t\t\tfinal Formula formula = changes.isEmpty() ? Formula.FALSE : Formula.or(changes);\n\t\t\t\t\n\t\t\t\tfinal long startTransl = System.currentTimeMillis();\n\t\t\t\ttranslation = Translator.translate(formula, newBounds, transl.options());\n\t\t\t\ttranslTime += System.currentTimeMillis() - startTransl;\n\t\t\t} \n\t\t\treturn sol;\n\t\t}\n\t\t\n\t}\n}",
"public abstract class SATFactory {\n\t\n\t/**\n\t * Constructs a new instance of SATFactory.\n\t */\n\tprotected SATFactory() {}\n\t\n\t/**\n\t * Returns true iff the given factory generates solvers that \n\t * are available for use on this system.\n\t * @return true iff the given factory generates solvers that \n\t * are available for use on this system.\n\t */\n\tpublic static final boolean available(SATFactory factory) {\n\t\tSATSolver solver = null;\n\t\ttry {\n\t\t\tsolver = factory.instance();\n\t\t\tsolver.addVariables(1);\n\t\t\tsolver.addClause(new int[]{1});\n\t\t\treturn solver.solve();\n\t\t} catch (RuntimeException|UnsatisfiedLinkError t) {\t\n\t\t\treturn false;\n\t\t} finally {\n\t\t\tif (solver!=null) {\n\t\t\t\tsolver.free();\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * The factory that produces instances of the default sat4j solver.\n\t * @see org.sat4j.core.ASolverFactory#defaultSolver()\n\t */\n\tpublic static final SATFactory DefaultSAT4J = new SATFactory() { \n\t\tpublic SATSolver instance() { \n\t\t\treturn new SAT4J(SolverFactory.instance().defaultSolver()); \n\t\t}\n\t\tpublic String toString() { return \"DefaultSAT4J\"; }\n\t};\n\t\n\t/**\n\t * The factory that produces instances of the \"light\" sat4j solver. The\n\t * light solver is suitable for solving many small instances of SAT problems.\n\t * @see org.sat4j.core.ASolverFactory#lightSolver()\n\t */\n\tpublic static final SATFactory LightSAT4J = new SATFactory() {\n\t\tpublic SATSolver instance() { \n\t\t\treturn new SAT4J(SolverFactory.instance().lightSolver()); \n\t\t}\n\t\tpublic String toString() { return \"LightSAT4J\"; }\n\t};\n\t\n\t/**\n\t * The factory that produces instances of Niklas Eén and Niklas Sörensson's\n\t * MiniSat solver.\n\t */\n\tpublic static final SATFactory MiniSat = new SATFactory() {\n\t\tpublic SATSolver instance() {\n\t\t\treturn new MiniSat();\n\t\t}\n\t\tpublic String toString() { return \"MiniSat\"; }\n\t};\n\t\n\t/**\n\t * The factory the produces {@link SATProver proof logging} \n\t * instances of the MiniSat solver. Note that core\n\t * extraction can incur a significant time overhead during solving,\n\t * so if you do not need this functionality, use the {@link #MiniSat} factory\n\t * instead.\n\t */\n\tpublic static final SATFactory MiniSatProver = new SATFactory() {\n\t\tpublic SATSolver instance() { \n\t\t\treturn new MiniSatProver(); \n\t\t}\n\t\t@Override\n\t\tpublic boolean prover() { return true; }\n\t\tpublic String toString() { return \"MiniSatProver\"; }\n\t};\n\t\n\t/**\n\t * The factory that produces instances of Gilles Audemard and Laurent Simon's \n\t * Glucose solver.\n\t */\n\tpublic static final SATFactory Glucose = new SATFactory() {\n\t\tpublic SATSolver instance() {\n\t\t\treturn new Glucose();\n\t\t}\n\t\tpublic String toString() { return \"Glucose\"; }\n\t};\n\t\n\t/**\n\t * The factory that produces instances of Armin Biere's\n\t * Lingeling solver.\n\t */\n\tpublic static final SATFactory Lingeling = new SATFactory() {\n\t\tpublic SATSolver instance() {\n\t\t\treturn new Lingeling();\n\t\t}\n\t\tpublic boolean incremental() { return false; }\n\t\tpublic String toString() { return \"Lingeling\"; }\n\t};\n\t\n\t/**\n\t * Returns a SATFactory that produces SATSolver wrappers for Armin Biere's Plingeling\n\t * solver. This is a parallel solver that is invoked as an external program rather than \n\t * via the Java Native Interface. As a result, it cannot be used incrementally. Its\n\t * external factory manages the creation and deletion of temporary files automatically.\n\t * A statically compiled version of plingeling is assumed to be available in a\n\t * java.library.path directory. The effect of this method is the same as calling\n\t * {@link #plingeling(Integer, Boolean) plingeling(null, null)}.\n\t * @return SATFactory that produces SATSolver wrappers for the Plingeling solver\n\t */\n\tpublic static final SATFactory plingeling() {\n\t\treturn plingeling(null, null);\n\t}\n\t\n\t/**\n\t * Returns a SATFactory that produces SATSolver wrappers for Armin Biere's Plingeling\n\t * solver. This is a parallel solver that is invoked as an external program rather than \n\t * via the Java Native Interface. As a result, it cannot be used incrementally. Its\n\t * external factory manages the creation and deletion of temporary files automatically.\n\t * A statically compiled version of plingeling is assumed to be available in a\n\t * java.library.path directory. \n\t * \n\t * <p>Plingling takes as input two optional parameters: {@code threads}, specifying how\n\t * many worker threads to use, and {@code portfolio}, specifying whether the threads should\n\t * run in portfolio mode (no sharing of clauses) or sharing mode. If {@code threads}\n\t * is null, the solver uses one worker per core. If {@code portfolio} is null, it is set to \n\t * true by default.</p>\n\t * \n\t * @requires threads != null => numberOfThreads > 0\n\t * \n\t * @return SATFactory that produces SATSolver wrappers for the Plingeling solver\n\t */\n\tpublic static final SATFactory plingeling(Integer threads, Boolean portfolio) {\n\t\t\n\t\tfinal List<String> opts = new ArrayList<String>(3);\n\t\tif (threads!=null) {\n\t\t\tif (threads < 1)\n\t\t\t\tthrow new IllegalArgumentException(\"Number of threads must be at least 1: numberOfThreads=\" + threads);\n\t\t\topts.add(\"-t\");\n\t\t\topts.add(threads.toString());\n\t\t}\n\t\tif (portfolio!=null && portfolio)\n\t\t\topts.add(\"-p\");\n\t\t\n\t\tfinal String executable = findStaticLibrary(\"plingeling\");\n\t\treturn externalFactory(executable==null ? \"plingeling\" : executable, \n\t\t\t\tnull, opts.toArray(new String[opts.size()]));\n\t\n\t}\n\t\n\t/**\n\t * Searches the {@code java.library.path} for an executable with the given name. Returns a fully \n\t * qualified path to the first found executable. Otherwise returns null.\n\t * @return a fully qualified path to an executable with the given name, or null if no executable \n\t * is found.\n\t */\n\tprivate static String findStaticLibrary(String name) { \n\t\tfinal String[] dirs = System.getProperty(\"java.library.path\").split(System.getProperty(\"path.separator\"));\n\t\t\n\t\tfor(int i = dirs.length-1; i >= 0; i--) {\n\t\t\tfinal File file = new File(dirs[i]+File.separator+name);\n\t\t\tif (file.canExecute())\n\t\t\t\treturn file.getAbsolutePath();\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Returns a SATFactory that produces instances of the specified\n\t * SAT4J solver. For the list of available SAT4J solvers see\n\t * {@link org.sat4j.core.ASolverFactory#solverNames() org.sat4j.core.ASolverFactory#solverNames()}.\n\t * @requires solverName is a valid solver name\n\t * @return a SATFactory that returns the instances of the specified\n\t * SAT4J solver\n\t * @see org.sat4j.core.ASolverFactory#solverNames()\n\t */\n\tpublic static final SATFactory sat4jFactory(final String solverName) {\n\t\treturn new SATFactory() {\n\t\t\t@Override\n\t\t\tpublic SATSolver instance() {\n\t\t\t\treturn new SAT4J(SolverFactory.instance().createSolverByName(solverName));\n\t\t\t}\n\t\t\tpublic String toString() { return solverName; }\n\t\t};\n\t}\n\t\n\t/**\n\t * Returns a SATFactory that produces SATSolver wrappers for the external\n\t * SAT solver specified by the executable parameter. The solver's input\n\t * and output formats must conform to the \n\t * <a href=\"http://www.satcompetition.org/2011/rules.pdf\">SAT competition standards</a>. The solver\n\t * will be called with the specified options, and it is expected to write properly formatted\n\t * output to standard out. If the {@code cnf} string is non-null, it will be \n\t * used as the file name for generated CNF files by all solver instances that the factory generates. \n\t * If {@code cnf} null, each solver instance will use an automatically generated temporary file, which \n\t * will be deleted when the solver instance is garbage-collected. The {@code cnf} file, if provided, is not \n\t * automatically deleted; it is the caller's responsibility to delete it when no longer needed. \n\t * External solvers are never incremental.\n\t * @return SATFactory that produces SATSolver wrappers for the specified external\n\t * SAT solver\n\t */\n\tpublic static final SATFactory externalFactory(final String executable, final String cnf, final String... options) {\n\t\treturn new SATFactory() {\n\n\t\t\t@Override\n\t\t\tpublic SATSolver instance() {\n\t\t\t\tif (cnf != null) {\n\t\t\t\t\treturn new ExternalSolver(executable, cnf, false, options);\n\t\t\t\t} else {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn new ExternalSolver(executable, \n\t\t\t\t\t\t\t\tFile.createTempFile(\"kodkod\", String.valueOf(executable.hashCode())).getAbsolutePath(), \n\t\t\t\t\t\t\t\ttrue, options);\n\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\tthrow new SATAbortedException(\"Could not create a temporary file.\", e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic boolean incremental() {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tpublic String toString() {\n\t\t\t\treturn (new File(executable)).getName();\n\t\t\t}\n\t\t};\n\t}\n\t\n\t\n\t/**\n\t * Returns an instance of a SATSolver produced by this factory.\n\t * @return a SATSolver instance\n\t */\n\tpublic abstract SATSolver instance();\n\t\n\t/**\n\t * Returns true if the solvers returned by this.instance() are\n\t * {@link SATProver SATProvers}. Otherwise returns false.\n\t * @return true if the solvers returned by this.instance() are\n\t * {@link SATProver SATProvers}. Otherwise returns false.\n\t */\n\tpublic boolean prover() {\n\t\treturn false;\n\t}\n\t\n\t/**\n\t * Returns true if the solvers returned by this.instance() are incremental;\n\t * i.e. if clauses/variables can be added to the solver between multiple\n\t * calls to solve().\n\t * @return true if the solvers returned by this.instance() are incremental\n\t */\n\tpublic boolean incremental() {\n\t\treturn true;\n\t}\n\n}",
"public final class Bounds implements Cloneable {\n\tprivate final TupleFactory factory;\n\tprivate final Map<Relation, TupleSet> lowers, uppers;\n\tprivate final SparseSequence<TupleSet> intbounds;\n\tprivate final Set<Relation> relations;\n\t\n\t/**\n\t * Constructs a Bounds object with the given factory and mappings.\n\t */\n\tprivate Bounds(TupleFactory factory, Map<Relation, TupleSet> lower, Map<Relation, TupleSet> upper, SparseSequence<TupleSet> intbounds) {\n\t\tthis.factory = factory;\n\t\tthis.lowers = lower;\n\t\tthis.uppers = upper;\n\t\tthis.intbounds = intbounds;\n\t\tthis.relations = relations(lowers, uppers);\n\t}\n\t\n\t/**\n\t * Constructs new Bounds over the given universe.\n\t * @ensures this.universe' = universe && no this.relations' && no this.intBound'\n\t * @throws NullPointerException universe = null\n\t */\n\tpublic Bounds(Universe universe) {\n\t\tthis.factory = universe.factory();\n\t\tthis.lowers = new LinkedHashMap<Relation, TupleSet>();\n\t\tthis.uppers = new LinkedHashMap<Relation, TupleSet>();\n\t\tthis.intbounds = new TreeSequence<TupleSet>();\n\t\tthis.relations = relations(lowers, uppers);\n\t}\n\t\n\t/**\n\t * Returns a set view of the relations mapped by the given lower/upper bounds.\n\t * @requires lowers.keySet().equals(uppers.keySet())\n\t * @return a set view of the relations mapped by the given lower/upper bounds\n\t */\n\tprivate static Set<Relation> relations(final Map<Relation, TupleSet> lowers, final Map<Relation, TupleSet> uppers) {\n\t\treturn new AbstractSet<Relation>() {\n\n\t\t\tpublic Iterator<Relation> iterator() {\n\t\t\t\treturn new Iterator<Relation>() {\n\t\t\t\t\tfinal Iterator<Relation> itr = uppers.keySet().iterator();\n\t\t\t\t\tRelation last = null;\n\t\t\t\t\tpublic boolean hasNext() { return itr.hasNext(); }\n\t\t\t\t\tpublic Relation next() { return last = itr.next(); }\n\t\t\t\t\tpublic void remove() {\n\t\t\t\t\t\titr.remove();\n\t\t\t\t\t\tlowers.remove(last);\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tpublic int size() { return uppers.size(); }\t\t\t\n\t\t\tpublic boolean contains(Object key) { return uppers.containsKey(key); }\n\t\t\t\n\t\t\tpublic boolean remove(Object key) { \n\t\t\t\treturn (uppers.remove(key) != null) && (lowers.remove(key) != null); \n\t\t\t}\n\t\t\tpublic boolean removeAll(Collection<?> c) {\n\t\t\t\treturn uppers.keySet().removeAll(c) && lowers.keySet().removeAll(c);\n\t\t\t}\n\t\t\tpublic boolean retainAll(Collection<?> c) {\n\t\t\t\treturn uppers.keySet().retainAll(c) && lowers.keySet().retainAll(c);\n\t\t\t}\n\t\t};\n\t}\n\t\n\t/**\n\t * Returns this.universe.\n\t * @return this.universe\n\t */\n\tpublic Universe universe() { return factory.universe(); }\n\n\t/**\n\t * Returns the set of all relations bound by this Bounds.\n\t * The returned set does not support the add operation.\n\t * It supports removal iff this is not an unmodifiable Bounds.\n\t * @return this.relations\n\t */\n\tpublic Set<Relation> relations() { \n\t\treturn relations; \n\t}\n\t\n\t/**\n\t * Returns the set of all integers bound by this Bounds.\n\t * The returned set does not support the add operation.\n\t * It supports removal iff this is not an unmodifiable Bounds.\n\t * @return this.intBounds.TupleSet\n\t */\n\tpublic IntSet ints() {\n\t\treturn intbounds.indices();\n\t}\n\t\n\t/**\n\t * Returns the set of tuples that r must contain (the lower bound on r's contents).\n\t * If r is not mapped by this, null is returned.\n\t * @return r in this.relations => lowerBound[r], null\n\t */\n\tpublic TupleSet lowerBound(Relation r) {\n\t\treturn lowers.get(r);\n\t}\n\t\n\t/**\n\t * Returns a map view of this.lowerBound. The returned map is not modifiable.\n\t * @return a map view of this.lowerBound\n\t */\n\tpublic Map<Relation, TupleSet> lowerBounds() {\n\t\treturn unmodifiableMap(lowers);\n\t}\n\t\n\t/**\n\t * Returns the set of tuples that r may contain (the upper bound on r's contents).\n\t * If r is not mapped by this, null is returned.\n\t * @return r in this.relations => upperBound[r], null\n\t */\n\tpublic TupleSet upperBound(Relation r) {\n\t\treturn uppers.get(r);\n\t}\n\t\n\t/**\n\t * Returns a map view of this.upperBound. The returned map is not modifiable.\n\t * @return a map view of this.upperBound\n\t */\n\tpublic Map<Relation, TupleSet> upperBounds() {\n\t\treturn unmodifiableMap(uppers);\n\t}\n\t\n\t/**\n\t * Returns the set of tuples representing the given integer. If i is not\n\t * mapped by this, null is returned.\n\t * @return this.intBound[i]\n\t */\n\tpublic TupleSet exactBound(int i) {\n\t\treturn intbounds.get(i);\n\t}\n\t\n\t/**\n\t * Returns a sparse sequence view of this.intBound. The returned sequence\n\t * is not modifiable.\n\t * @return a sparse sequence view of this.intBound\n\t */\n\tpublic SparseSequence<TupleSet> intBounds() {\n\t\treturn unmodifiableSequence(intbounds);\n\t}\n\t\n\t/**\n\t * @throws IllegalArgumentException arity != bound.arity\n\t * @throws IllegalArgumentException bound.universe != this.universe\n\t */\n\tprivate void checkBound(int arity, TupleSet bound) {\n\t\tif (arity != bound.arity())\n\t\t\tthrow new IllegalArgumentException(\"bound.arity != r.arity\");\n\t\tif (!bound.universe().equals(factory.universe()))\n\t\t\tthrow new IllegalArgumentException(\"bound.universe != this.universe\");\t\n\t}\n\t\n\t/**\n\t * Sets both the lower and upper bounds of the given relation to \n\t * the given set of tuples. \n\t * \n\t * @requires tuples.arity = r.arity && tuples.universe = this.universe\n\t * @ensures this.relations' = this.relations + r \n\t * this.lowerBound' = this.lowerBound' ++ r->tuples &&\n\t * this.upperBound' = this.lowerBound' ++ r->tuples\n\t * @throws NullPointerException r = null || tuples = null \n\t * @throws IllegalArgumentException tuples.arity != r.arity || tuples.universe != this.universe\n\t */\n\tpublic void boundExactly(Relation r, TupleSet tuples) {\n\t\tcheckBound(r.arity(), tuples);\n\t\tfinal TupleSet unmodifiableTuplesCopy = tuples.clone().unmodifiableView();\n\t\tlowers.put(r, unmodifiableTuplesCopy);\n\t\tuppers.put(r, unmodifiableTuplesCopy);\n\t}\n\t\n\t/**\n\t * Sets the lower and upper bounds for the given relation. \n\t * \n\t * @requires lower.tuples in upper.tuples && lower.arity = upper.arity = r.arity &&\n\t * lower.universe = upper.universe = this.universe \n\t * @ensures this.relations' = this.relations + r &&\n\t * this.lowerBound' = this.lowerBound ++ r->lower &&\n\t * this.upperBound' = this.upperBound ++ r->upper\n\t * @throws NullPointerException r = null || lower = null || upper = null\n\t * @throws IllegalArgumentException lower.arity != r.arity || upper.arity != r.arity\n\t * @throws IllegalArgumentException lower.universe != this.universe || upper.universe != this.universe\n\t * @throws IllegalArgumentException lower.tuples !in upper.tuples \n\t */\n\tpublic void bound(Relation r, TupleSet lower, TupleSet upper) {\n\t\tif (!upper.containsAll(lower))\n\t\t\tthrow new IllegalArgumentException(\"lower.tuples !in upper.tuples\");\n\t\tif (upper.size()==lower.size()) { \n\t\t\t// upper.containsAll(lower) && upper.size()==lower.size() => upper.equals(lower)\n\t\t\tboundExactly(r, lower);\n\t\t} else {\n\t\t\tcheckBound(r.arity(), lower);\n\t\t\tcheckBound(r.arity(), upper);\t\t\n\t\t\tlowers.put(r, lower.clone().unmodifiableView());\n\t\t\tuppers.put(r, upper.clone().unmodifiableView());\n\t\t}\n\t}\n\t\n\t/**\n\t * Makes the specified tupleset the upper bound on the contents of the given relation. \n\t * The lower bound automatically become an empty tupleset with the same arity as\n\t * the relation. \n\t * \n\t * @requires upper.arity = r.arity && upper.universe = this.universe\n\t * @ensures this.relations' = this.relations + r \n\t * this.lowerBound' = this.lowerBound ++ r->{s: TupleSet | s.universe = this.universe && s.arity = r.arity && no s.tuples} && \n\t * this.upperBound' = this.upperBound ++ r->upper\n\t * @throws NullPointerException r = null || upper = null \n\t * @throws IllegalArgumentException upper.arity != r.arity || upper.universe != this.universe\n\t */\n\tpublic void bound(Relation r, TupleSet upper) {\n\t\tcheckBound(r.arity(), upper);\n\t\tlowers.put(r, factory.noneOf(r.arity()).unmodifiableView());\n\t\tuppers.put(r, upper.clone().unmodifiableView());\n\t}\n\t\n\t/**\n\t * Makes the specified tupleset an exact bound on the relational value\n\t * that corresponds to the given integer.\n\t * @requires ibound.arity = 1 && i.bound.size() = 1\n\t * @ensures this.intBound' = this.intBound' ++ i -> ibound\n\t * @throws NullPointerException ibound = null\n\t * @throws IllegalArgumentException ibound.arity != 1 || ibound.size() != 1\n\t * @throws IllegalArgumentException ibound.universe != this.universe\n\t */\n\tpublic void boundExactly(int i, TupleSet ibound) {\n\t\tcheckBound(1, ibound);\n\t\tif (ibound.size() != 1)\n\t\t\tthrow new IllegalArgumentException(\"ibound.size != 1: \" + ibound);\n\t\tintbounds.put(i, ibound.clone().unmodifiableView());\n\t}\n\t\n\n\t/**\n\t * Returns an unmodifiable view of this Bounds object.\n\t * @return an unmodifiable view of his Bounds object.\n\t */\n\tpublic Bounds unmodifiableView() {\n\t\treturn new Bounds(factory, unmodifiableMap(lowers), unmodifiableMap(uppers), unmodifiableSequence(intbounds));\n\t}\n\t\n\t/**\n\t * Returns a deep (modifiable) copy of this Bounds object.\n\t * @return a deep (modifiable) copy of this Bounds object.\n\t */\n\tpublic Bounds clone() {\n\t\ttry {\n\t\t\treturn new Bounds(factory, new LinkedHashMap<Relation, TupleSet>(lowers), \n\t\t\t\t\tnew LinkedHashMap<Relation, TupleSet>(uppers), intbounds.clone());\n\t\t} catch (CloneNotSupportedException cnse) {\n\t\t\tthrow new InternalError(); // should not be reached\n\t\t}\n\t}\n\t\n\t/**\n\t * @see java.lang.Object#toString()\n\t */\n\tpublic String toString() {\n\t\tfinal StringBuilder str = new StringBuilder();\n\t\tstr.append(\"relation bounds:\");\n\t\tfor(Map.Entry<Relation, TupleSet> entry: lowers.entrySet()) {\n\t\t\tstr.append(\"\\n \");\n\t\t\tstr.append(entry.getKey());\n\t\t\tstr.append(\": [\");\n\t\t\tstr.append(entry.getValue());\n\t\t\tTupleSet upper = uppers.get(entry.getKey());\n\t\t\tif (!upper.equals(entry.getValue())) {\n\t\t\t\tstr.append(\", \");\n\t\t\t\tstr.append(upper);\n\t\t\t} \n\t\t\tstr.append(\"]\");\n\t\t}\n\t\tstr.append(\"\\nint bounds: \");\n\t\tstr.append(\"\\n \");\n\t\tstr.append(intbounds);\n\t\treturn str.toString();\n\t}\n}",
"public class Solvers {\n\t\n\t/**\n\t * Returns a list view of all solver factories available for use on this system.\n\t * @return a list view of all solver factories available for use on this system.\n\t */\n\tpublic static final List<SATFactory> allAvailableSolvers() {\n\t\tfinal List<SATFactory> ret = new ArrayList<>();\n\t\tfor(Field f : SATFactory.class.getFields()) {\n\t\t\ttry {\n\t\t\t\t final SATFactory factory = (SATFactory) f.get(null);\n\t\t\t\t if (SATFactory.available(factory))\n\t\t\t\t\t ret.add(factory);\n\t\t\t} catch (Exception e) {\n\t\t\t\tcontinue;\n\t\t\t} \n\t\t}\n\t\tfor(Method m : SATFactory.class.getDeclaredMethods()) {\n\t\t\tif (!Modifier.isPublic(m.getModifiers())) continue;\n\t\t\ttry {\n\t\t\t\tfinal SATFactory factory = (SATFactory) m.invoke(null);\n\t\t\t\tif (SATFactory.available(factory))\n\t\t\t\t\t ret.add(factory);\n\t\t\t} catch (Exception e) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n\t\n\t/**\n\t * Prints the list of all solvers found on this system.\n\t */\n\tpublic static void main(String[] args) { \n\t\tSystem.out.println(allAvailableSolvers().toString());\n\t}\n\t\n}"
] | import java.util.ArrayList;
import java.util.Collection;
import kodkod.ast.Formula;
import kodkod.engine.Solution;
import kodkod.engine.Solver;
import kodkod.engine.satlab.SATFactory;
import kodkod.instance.Bounds;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import kodkod.test.util.Solvers; | package kodkod.test.sys;
@RunWith(Parameterized.class)
public class ExamplesTestWithRegularSolver extends ExamplesTest {
private final Solver solver;
public ExamplesTestWithRegularSolver(SATFactory solverOpt) {
this.solver = new Solver();
this.solver.options().setSolver(solverOpt);
}
@Parameters
public static Collection<Object[]> solversToTestWith() {
final Collection<Object[]> ret = new ArrayList<Object[]>(); | for(SATFactory factory : Solvers.allAvailableSolvers()) { | 4 |
delving/x3ml | src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java | [
"public interface Generator {\r\n\r\n interface UUIDSource {\r\n\r\n String generateUUID();\r\n }\r\n\r\n void setDefaultArgType(SourceType sourceType);\r\n\r\n void setLanguageFromMapping(String language);\r\n\r\n void setNamespace(String prefix, String uri);\r\n\r\n String getLanguageFromMapping();\r\n\r\n public interface ArgValues {\r\n\r\n ArgValue getArgValue(String name, SourceType sourceType);\r\n }\r\n\r\n GeneratedValue generate(String name, ArgValues arguments);\r\n}\r",
"public static X3MLException exception(String message) {\n return new X3MLException(message);\n}",
"public interface X3ML {\r\n\r\n public enum SourceType {\r\n\r\n xpath,\r\n constant,\r\n position\r\n }\r\n\r\n @XStreamAlias(\"x3ml\")\r\n public static class RootElement extends Visible {\r\n\r\n @XStreamAsAttribute\r\n public String version;\r\n\r\n @XStreamAsAttribute\r\n @XStreamAlias(\"source_type\")\r\n public SourceType sourceType;\r\n\r\n @XStreamAsAttribute\r\n public String language;\r\n\r\n @XStreamOmitField\r\n public String info;\r\n\r\n public List<MappingNamespace> namespaces;\r\n\r\n public List<Mapping> mappings;\r\n\r\n public void apply(Root context) {\r\n for (Mapping mapping : mappings) {\r\n mapping.apply(context);\r\n }\r\n }\r\n\r\n @XStreamOmitField\r\n public String comments;\r\n }\r\n\r\n @XStreamAlias(\"mapping\")\r\n public static class Mapping extends Visible {\r\n\r\n public DomainElement domain;\r\n\r\n @XStreamImplicit\r\n public List<LinkElement> links;\r\n\r\n public void apply(Root context) {\r\n for (Domain domain : context.createDomainContexts(this.domain)) {\r\n domain.resolve();\r\n if (links == null) {\r\n continue;\r\n }\r\n for (LinkElement linkElement : links) {\r\n linkElement.apply(domain);\r\n }\r\n }\r\n }\r\n }\r\n\r\n @XStreamAlias(\"link\")\r\n public static class LinkElement extends Visible {\r\n\r\n public PathElement path;\r\n\r\n public RangeElement range;\r\n\r\n public void apply(Domain domain) {\r\n String pathSource = this.path.source_relation.relation.expression;\r\n String pathSource2 = \"\";\r\n String node_inside = \"\";\r\n\r\n System.out.println(pathSource);\r\n if (this.path.source_relation.relation2 != null) {\r\n pathSource2 = this.path.source_relation.relation2.expression;\r\n System.out.println(\"pathSource2: \" + pathSource2);\r\n }\r\n\r\n if (this.path.source_relation.node != null) {\r\n node_inside = this.path.source_relation.node.expression;\r\n System.out.println(\"node: \" + node_inside);\r\n }\r\n\r\n if (this.path.source_relation.node != null) {\r\n\r\n int equals = pathSource.indexOf(\"==\");\r\n\r\n if (equals >= 0) {\r\n\r\n String domainForeignKey = pathSource.trim();\r\n String rangePrimaryKey = pathSource2.trim();\r\n\r\n String intermediateFirst = domainForeignKey.substring(domainForeignKey.indexOf(\"==\") + 2).trim();\r\n String intermediateSecond = rangePrimaryKey.substring(0, rangePrimaryKey.indexOf(\"==\")).trim();\r\n\r\n domainForeignKey = domainForeignKey.substring(0, domainForeignKey.indexOf(\"==\")).trim();\r\n rangePrimaryKey = rangePrimaryKey.substring(rangePrimaryKey.indexOf(\"==\") + 2).trim();\r\n\r\n for (Link link : domain.createLinkContexts(this, domainForeignKey, rangePrimaryKey,\r\n intermediateFirst, intermediateSecond, node_inside)) {\r\n link.range.link();\r\n }\r\n\r\n }\r\n } else if (pathSource.contains(\"==\")) {\r\n\r\n int equals = pathSource.indexOf(\"==\");\r\n if (equals >= 0) {\r\n String domainForeignKey = pathSource.substring(0, equals).trim();\r\n String rangePrimaryKey = pathSource.substring(equals + 2).trim();\r\n for (Link link : domain.createLinkContexts(this, domainForeignKey, rangePrimaryKey)) {\r\n link.range.link();\r\n }\r\n }\r\n\r\n } else {\r\n System.out.println(this.path);\r\n for (Path path : domain.createPathContexts(this.path)) {\r\n System.out.println(this.path);\r\n for (Range range : path.createRangeContexts(this.range)) {\r\n range.link();\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n @XStreamAlias(\"namespace\")\r\n public static class MappingNamespace extends Visible {\r\n\r\n @XStreamAsAttribute\r\n public String prefix;\r\n @XStreamAsAttribute\r\n public String uri;\r\n }\r\n\r\n @XStreamConverter(value = ToAttributedValueConverter.class, strings = {\"expression\"})\r\n public static class Source extends Visible {\r\n\r\n public String expression;\r\n }\r\n\r\n @XStreamAlias(\"domain\")\r\n public static class DomainElement extends Visible {\r\n\r\n public Source source_node;\r\n\r\n public TargetNode target_node;\r\n\r\n public Comments comments;\r\n }\r\n\r\n @XStreamAlias(\"target_relation\")\r\n @XStreamConverter(TargetRelationConverter.class)\r\n public static class TargetRelation extends Visible {\r\n\r\n public Condition condition;\r\n\r\n public List<Relationship> properties;\r\n\r\n public List<EntityElement> entities;\r\n }\r\n\r\n public static class TargetRelationConverter implements Converter {\r\n // make sure the output is property-entity-property-entity-property\r\n\r\n @Override\r\n public boolean canConvert(Class type) {\r\n return TargetRelation.class.equals(type);\r\n }\r\n\r\n @Override\r\n public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {\r\n TargetRelation relation = (TargetRelation) source;\r\n if (relation.condition != null) {\r\n writer.startNode(\"if\");\r\n context.convertAnother(relation.condition);\r\n writer.endNode();\r\n }\r\n Iterator<Relationship> walkProperties = relation.properties.iterator();\r\n Relationship relationship = walkProperties.next();\r\n writer.startNode(\"relationship\");\r\n context.convertAnother(relationship);\r\n writer.endNode();\r\n for (EntityElement entityElement : relation.entities) {\r\n relationship = walkProperties.next();\r\n writer.startNode(\"entity\");\r\n context.convertAnother(entityElement);\r\n writer.endNode();\r\n writer.startNode(\"relationship\");\r\n context.convertAnother(relationship);\r\n writer.endNode();\r\n }\r\n }\r\n\r\n @Override\r\n public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {\r\n TargetRelation relation = new TargetRelation();\r\n relation.properties = new ArrayList<Relationship>();\r\n relation.entities = new ArrayList<EntityElement>();\r\n while (reader.hasMoreChildren()) {\r\n reader.moveDown();\r\n if (\"if\".equals(reader.getNodeName())) {\r\n relation.condition = (Condition) context.convertAnother(relation, Condition.class);\r\n } else if (\"relationship\".equals(reader.getNodeName())) {\r\n relation.properties.add((Relationship) context.convertAnother(relation, Relationship.class));\r\n } else if (\"entity\".equals(reader.getNodeName())) {\r\n relation.entities.add((EntityElement) context.convertAnother(relation, EntityElement.class));\r\n } else {\r\n throw new ConversionException(\"Unrecognized: \" + reader.getNodeName());\r\n }\r\n reader.moveUp();\r\n }\r\n return relation;\r\n }\r\n }\r\n\r\n @XStreamAlias(\"target_node\")\r\n public static class TargetNode extends Visible {\r\n\r\n @XStreamAlias(\"if\")\r\n public Condition condition;\r\n\r\n @XStreamAlias(\"entity\")\r\n public EntityElement entityElement;\r\n }\r\n\r\n @XStreamAlias(\"path\")\r\n public static class PathElement extends Visible {\r\n\r\n public SourceRelation source_relation;\r\n\r\n public TargetRelation target_relation;\r\n\r\n public Comments comments;\r\n }\r\n\r\n @XStreamAlias(\"source_relation\")\r\n public class SourceRelation extends Visible {\r\n\r\n public Source relation2;\r\n public Source relation;\r\n public Source node;\r\n }\r\n\r\n @XStreamAlias(\"range\")\r\n public static class RangeElement extends Visible {\r\n\r\n public Source source_node;\r\n\r\n public TargetNode target_node;\r\n\r\n public Comments comments;\r\n }\r\n\r\n @XStreamAlias(\"additional\")\r\n public static class Additional extends Visible {\r\n\r\n @XStreamAlias(\"property\")\r\n public Relationship relationship;\r\n\r\n @XStreamAlias(\"entity\")\r\n public EntityElement entityElement;\r\n }\r\n\r\n @XStreamAlias(\"if\")\r\n public static class Condition extends Visible {\r\n\r\n public Narrower narrower;\r\n public Exists exists;\r\n public Equals equals;\r\n public AndCondition and;\r\n public OrCondition or;\r\n public NotCondition not;\r\n\r\n private static class Outcome {\r\n\r\n final GeneratorContext context;\r\n boolean failure;\r\n\r\n private Outcome(GeneratorContext context) {\r\n this.context = context;\r\n }\r\n\r\n Outcome evaluate(YesOrNo yesOrNo) {\r\n if (yesOrNo != null && !failure && !yesOrNo.yes(context)) {\r\n failure = true;\r\n }\r\n return this;\r\n }\r\n }\r\n\r\n public boolean failure(GeneratorContext context) {\r\n return new Outcome(context)\r\n .evaluate(narrower)\r\n .evaluate(exists)\r\n .evaluate(equals)\r\n .evaluate(and)\r\n .evaluate(or)\r\n .evaluate(not).failure;\r\n }\r\n\r\n }\r\n\r\n interface YesOrNo {\r\n\r\n boolean yes(GeneratorContext context);\r\n }\r\n\r\n @XStreamConverter(value = ToAttributedValueConverter.class, strings = {\"expression\"})\r\n @XStreamAlias(\"exists\")\r\n public static class Exists extends Visible implements YesOrNo {\r\n\r\n public String expression;\r\n\r\n @Override\r\n public boolean yes(GeneratorContext context) {\r\n return context.evaluate(expression).length() > 0;\r\n }\r\n }\r\n\r\n @XStreamConverter(value = ToAttributedValueConverter.class, strings = {\"expression\"})\r\n @XStreamAlias(\"equals\")\r\n public static class Equals extends Visible implements YesOrNo {\r\n\r\n @XStreamAsAttribute\r\n public String value;\r\n\r\n public String expression;\r\n\r\n @Override\r\n public boolean yes(GeneratorContext context) {\r\n return value.equals(context.evaluate(expression));\r\n }\r\n }\r\n\r\n @XStreamConverter(value = ToAttributedValueConverter.class, strings = {\"expression\"})\r\n @XStreamAlias(\"narrower\")\r\n public static class Narrower extends Visible implements YesOrNo {\r\n\r\n @XStreamAsAttribute\r\n public String value;\r\n\r\n public String expression;\r\n\r\n @Override\r\n public boolean yes(GeneratorContext context) {\r\n return true;\r\n }\r\n }\r\n\r\n @XStreamAlias(\"and\")\r\n public static class AndCondition extends Visible implements YesOrNo {\r\n\r\n @XStreamImplicit\r\n List<Condition> list;\r\n\r\n @Override\r\n public boolean yes(GeneratorContext context) {\r\n boolean result = true;\r\n for (Condition condition : list) {\r\n if (condition.failure(context)) {\r\n result = false;\r\n }\r\n }\r\n return result;\r\n }\r\n }\r\n\r\n @XStreamAlias(\"or\")\r\n public static class OrCondition extends Visible implements YesOrNo {\r\n\r\n @XStreamImplicit\r\n List<Condition> list;\r\n\r\n @Override\r\n public boolean yes(GeneratorContext context) {\r\n boolean result = false;\r\n for (Condition condition : list) {\r\n if (!condition.failure(context)) {\r\n result = true;\r\n }\r\n }\r\n return result;\r\n }\r\n }\r\n\r\n @XStreamAlias(\"not\")\r\n public static class NotCondition extends Visible implements YesOrNo {\r\n\r\n @XStreamAlias(\"if\")\r\n Condition condition;\r\n\r\n @Override\r\n public boolean yes(GeneratorContext context) {\r\n return condition.failure(context);\r\n }\r\n }\r\n\r\n @XStreamAlias(\"relationship\")\r\n @XStreamConverter(value = ToAttributedValueConverter.class, strings = {\"tag\"})\r\n public static class Relationship extends Visible {\r\n\r\n public String tag;\r\n\r\n public String getPrefix() {\r\n int colon = tag.indexOf(':');\r\n if (colon < 0) {\r\n throw exception(\"Unqualified tag \" + tag);\r\n }\r\n return tag.substring(0, colon);\r\n }\r\n\r\n public String getLocalName() {\r\n int colon = tag.indexOf(':');\r\n if (colon < 0) {\r\n throw exception(\"Unqualified tag \" + tag);\r\n }\r\n return tag.substring(colon + 1);\r\n }\r\n }\r\n\r\n @XStreamAlias(\"instance_info\") // documentation purposes only\r\n public static class InstanceInfo extends Visible {\r\n\r\n public String language;\r\n public String constant;\r\n public String description;\r\n\r\n }\r\n\r\n @XStreamAlias(\"entity\")\r\n public static class EntityElement extends Visible {\r\n\r\n @XStreamAsAttribute\r\n public String variable;\r\n\r\n @XStreamImplicit\r\n public List<TypeElement> typeElements;\r\n\r\n @XStreamAlias(\"instance_info\")\r\n public InstanceInfo instanceInfo; // documentation purposes only\r\n\r\n @XStreamAlias(\"instance_generator\")\r\n public GeneratorElement instanceGenerator;\r\n\r\n @XStreamImplicit\r\n public List<GeneratorElement> labelGenerators;\r\n\r\n @XStreamImplicit\r\n public List<Additional> additionals;\r\n\r\n public GeneratedValue getInstance(GeneratorContext context, String unique) {\r\n return context.getInstance(instanceGenerator, variable, unique);\r\n }\r\n }\r\n\r\n @XStreamAlias(\"type\")\r\n @XStreamConverter(value = ToAttributedValueConverter.class, strings = {\"tag\"})\r\n public static class TypeElement extends Visible {\r\n\r\n public String tag;\r\n\r\n @XStreamOmitField\r\n public String namespaceUri;\r\n\r\n public TypeElement() {\r\n }\r\n\r\n public TypeElement(String tag, String namespaceUri) {\r\n this.tag = tag;\r\n this.namespaceUri = namespaceUri;\r\n }\r\n\r\n public String getPrefix() {\r\n int colon = tag.indexOf(':');\r\n if (colon < 0) {\r\n throw exception(\"Unqualified tag \" + tag);\r\n }\r\n return tag.substring(0, colon);\r\n }\r\n\r\n public String getLocalName() {\r\n int colon = tag.indexOf(':');\r\n if (colon < 0) {\r\n throw exception(\"Unqualified tag \" + tag);\r\n }\r\n return tag.substring(colon + 1);\r\n }\r\n }\r\n\r\n @XStreamAlias(\"comments\")\r\n public static class Comments extends Visible {\r\n\r\n @XStreamImplicit\r\n public List<Comment> comments;\r\n\r\n }\r\n\r\n @XStreamAlias(\"comment\")\r\n @XStreamConverter(value = ToAttributedValueConverter.class, strings = {\"content\"})\r\n public static class Comment extends Visible {\r\n\r\n @XStreamAsAttribute\r\n public String type;\r\n\r\n public String content;\r\n }\r\n\r\n @XStreamAlias(\"label_generator\")\r\n public static class GeneratorElement extends Visible {\r\n\r\n @XStreamAsAttribute\r\n public String name;\r\n\r\n @XStreamImplicit\r\n public List<GeneratorArg> args;\r\n }\r\n\r\n @XStreamAlias(\"arg\")\r\n @XStreamConverter(value = ToAttributedValueConverter.class, strings = {\"value\"})\r\n public static class GeneratorArg extends Visible {\r\n\r\n @XStreamAsAttribute\r\n public String name;\r\n\r\n @XStreamAsAttribute\r\n public String type;\r\n\r\n public String value;\r\n }\r\n\r\n @XStreamAlias(\"generator_policy\")\r\n public static class GeneratorPolicy extends Visible {\r\n\r\n @XStreamImplicit\r\n public List<GeneratorSpec> generators;\r\n }\r\n\r\n @XStreamAlias(\"generator\")\r\n public static class GeneratorSpec extends Visible {\r\n\r\n @XStreamAsAttribute\r\n public String name;\r\n\r\n @XStreamAsAttribute\r\n public String prefix;\r\n\r\n public CustomGenerator custom;\r\n\r\n public String pattern;\r\n\r\n public String toString() {\r\n return name;\r\n }\r\n }\r\n\r\n @XStreamAlias(\"custom\")\r\n public static class CustomGenerator extends Visible {\r\n\r\n @XStreamAsAttribute\r\n public String generatorClass;\r\n\r\n @XStreamImplicit\r\n public List<CustomArg> setArgs;\r\n\r\n public String toString() {\r\n return generatorClass;\r\n }\r\n }\r\n\r\n @XStreamAlias(\"set-arg\")\r\n public static class CustomArg extends Visible {\r\n\r\n @XStreamAsAttribute\r\n public String name;\r\n\r\n @XStreamAsAttribute\r\n public String type;\r\n }\r\n\r\n public static class ArgValue {\r\n\r\n public final String string;\r\n public final String language;\r\n\r\n public ArgValue(String string, String language) {\r\n this.string = string;\r\n this.language = language;\r\n }\r\n\r\n public String toString() {\r\n if (string != null) {\r\n return \"ArgValue(\" + string + \")\";\r\n } else {\r\n return \"ArgValue?\";\r\n }\r\n }\r\n }\r\n\r\n public enum GeneratedType {\r\n\r\n URI,\r\n LITERAL,\r\n TYPED_LITERAL\r\n }\r\n\r\n public static class GeneratedValue {\r\n\r\n public final GeneratedType type;\r\n public final String text;\r\n public final String language;\r\n\r\n public GeneratedValue(GeneratedType type, String text, String language) {\r\n this.type = type;\r\n this.text = text;\r\n this.language = language;\r\n }\r\n\r\n public GeneratedValue(GeneratedType type, String text) {\r\n this(type, text, null);\r\n }\r\n\r\n public String toString() {\r\n return type + \":\" + text;\r\n }\r\n }\r\n\r\n static class Visible {\r\n\r\n public String toString() {\r\n return Helper.toString(this);\r\n }\r\n }\r\n\r\n static class Helper {\r\n\r\n static String toString(Object thing) {\r\n return \"\\n\" + x3mlStream().toXML(thing);\r\n }\r\n\r\n public static XStream generatorStream() {\r\n XStream xstream = new XStream(new PureJavaReflectionProvider(), new XppDriver(new NoNameCoder()));\r\n xstream.setMode(XStream.NO_REFERENCES);\r\n xstream.processAnnotations(GeneratorPolicy.class);\r\n return xstream;\r\n }\r\n\r\n public static XStream x3mlStream() {\r\n XStream xstream = new XStream(new PureJavaReflectionProvider(), new XppDriver(new NoNameCoder()));\r\n xstream.setMode(XStream.NO_REFERENCES);\r\n xstream.processAnnotations(RootElement.class);\r\n return xstream;\r\n }\r\n\r\n public static ArgValue argVal(String string, String language) {\r\n return new ArgValue(string, language);\r\n }\r\n\r\n public static GeneratedValue uriValue(String uri) {\r\n return new GeneratedValue(GeneratedType.URI, uri, null);\r\n }\r\n\r\n public static GeneratedValue literalValue(String literal, String language) {\r\n return new GeneratedValue(GeneratedType.LITERAL, literal, language);\r\n }\r\n\r\n public static GeneratedValue literalValue(String literal) {\r\n return literalValue(literal, null);\r\n }\r\n\r\n public static GeneratedValue typedLiteralValue(String literal) {\r\n return new GeneratedValue(GeneratedType.TYPED_LITERAL, literal);\r\n }\r\n }\r\n}\r",
"public static XStream generatorStream() {\r\n XStream xstream = new XStream(new PureJavaReflectionProvider(), new XppDriver(new NoNameCoder()));\r\n xstream.setMode(XStream.NO_REFERENCES);\r\n xstream.processAnnotations(GeneratorPolicy.class);\r\n return xstream;\r\n}\r",
"public static GeneratedValue literalValue(String literal, String language) {\r\n return new GeneratedValue(GeneratedType.LITERAL, literal, language);\r\n}\r",
"public static GeneratedValue typedLiteralValue(String literal) {\r\n return new GeneratedValue(GeneratedType.TYPED_LITERAL, literal);\r\n}\r",
"public static GeneratedValue uriValue(String uri) {\r\n return new GeneratedValue(GeneratedType.URI, uri, null);\r\n}\r"
] | import com.damnhandy.uri.template.MalformedUriTemplateException;
import com.damnhandy.uri.template.UriTemplate;
import com.damnhandy.uri.template.VariableExpansionException;
import eu.delving.x3ml.engine.Generator;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.*;
import static eu.delving.x3ml.engine.X3ML.Helper.generatorStream;
import static eu.delving.x3ml.engine.X3ML.Helper.literalValue;
import static eu.delving.x3ml.engine.X3ML.Helper.typedLiteralValue;
import static eu.delving.x3ml.engine.X3ML.Helper.uriValue;
import static eu.delving.x3ml.engine.X3ML.SourceType.constant;
import static eu.delving.x3ml.engine.X3ML.SourceType.xpath; | //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml;
/**
* @author Gerald de Jong <[email protected]>
*/
public class X3MLGeneratorPolicy implements Generator {
private static final Pattern BRACES = Pattern.compile("\\{[?;+#]?([^}]+)\\}");
private Map<String, GeneratorSpec> generatorMap = new TreeMap<String, GeneratorSpec>();
private Map<String, String> namespaceMap = new TreeMap<String, String>();
private UUIDSource uuidSource;
private SourceType defaultSourceType;
private String languageFromMapping;
public interface CustomGenerator {
void setArg(String name, String value) throws CustomGeneratorException;
String getValue() throws CustomGeneratorException;
String getValueType() throws CustomGeneratorException;
}
public static class CustomGeneratorException extends Exception {
public CustomGeneratorException(String message) {
super(message);
}
}
public static X3MLGeneratorPolicy load(InputStream inputStream, UUIDSource uuidSource) {
return new X3MLGeneratorPolicy(inputStream, uuidSource);
}
public static UUIDSource createUUIDSource(int uuidSize) {
return uuidSize > 0 ? new TestUUIDSource(uuidSize) : new RealUUIDSource();
}
private X3MLGeneratorPolicy(InputStream inputStream, UUIDSource uuidSource) {
if (inputStream != null) { | GeneratorPolicy policy = (GeneratorPolicy) generatorStream().fromXML(inputStream); | 3 |
senseobservationsystems/sense-android-library | sense-android-library/src/nl/sense_os/service/motion/FallDetector.java | [
"public static class DataPoint implements BaseColumns {\n\n public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE\n + \"/vnd.sense_os.data_point\";\n public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE\n + \"/vnd.sense_os.data_point\";\n public static final String CONTENT_URI_PATH = \"/recent_values\";\n @Deprecated\n public static final String CONTENT_PERSISTED_URI_PATH = \"/persisted_values\";\n public static final String CONTENT_REMOTE_URI_PATH = \"/remote_values\";\n\n /**\n * The name of the sensor that generated the data point. <br>\n * <br>\n * TYPE: String\n */\n public static final String SENSOR_NAME = \"sensor_name\";\n /**\n * Description of the sensor that generated the data point. Can either be the hardware name,\n * or any other useful description. <br>\n * <br>\n * TYPE: String\n */\n public static final String SENSOR_DESCRIPTION = \"sensor_description\";\n /**\n * The data type of the data point. <br>\n * <br>\n * TYPE: String\n * \n * @see SenseDataTypes\n */\n public static final String DATA_TYPE = \"data_type\";\n /**\n * The human readable display name of the sensor that generated the data point. <br>\n * <br>\n * TYPE: String\n * \n * @see SenseDataTypes\n */\n public static final String DISPLAY_NAME = \"display_name\";\n /**\n * Time stamp for the data point, in milliseconds. <br>\n * <br>\n * TYPE: long\n */\n public static final String TIMESTAMP = \"timestamp\";\n /**\n * Data point value. <br>\n * <br>\n * TYPE: String\n */\n public static final String VALUE = \"value\";\n /**\n * Transmit state of the data point, signalling whether the point has been sent to\n * CommonSense already.<br>\n * <br>\n * TYPE: integer status code: 0 (not sent), or 1 (sent)\n */\n public static final String TRANSMIT_STATE = \"transmit_state\";\n /**\n * Device UUID of the sensor. Use this for sensors that are originated from\n * \"external sensors\", or leave <code>null</code> to use the phone as default device.<br>\n * <br>\n * TYPE: String\n */\n public static final String DEVICE_UUID = \"device_uuid\";\n\n private DataPoint() {\n // class should not be instantiated\n }\n}",
"public static class SensorNames {\n\n /**\n * Fall detector sensor. Can be a real fall or a regular free fall for demo's. Part of the\n * Motion sensors.\n */\n public static final String FALL_DETECTOR = \"fall_detector\";\n\n /** Noise level sensor. Part of the Ambience sensors. */\n public static final String NOISE = \"noise_sensor\";\n\n /** Noise level sensor (Burst-mode). Part of the Ambience sensors. */\n public static final String NOISE_BURST = \"noise_sensor (burst-mode)\";\n\n /** Audio spectrum sensor. Part of the Ambience sensors. */\n public static final String AUDIO_SPECTRUM = \"audio_spectrum\";\n\n /** Microphone output. Part of the Ambience sensors (real-time mode only). */\n public static final String MIC = \"microphone\";\n\n /** Light sensor. Part of the Ambience sensors. */\n public static final String LIGHT = \"light\";\n\n /** Camera Light sensor. Part of the Ambience sensors. */\n public static final String CAMERA_LIGHT = \"camera_light\";\n\n /** Bluetooth discovery sensor. Part of the Neighboring Devices sensors. */\n public static final String BLUETOOTH_DISCOVERY = \"bluetooth_discovery\";\n\n /** Wi-Fi scan sensor. Part of the Neighboring Devices sensors. */\n public static final String WIFI_SCAN = \"wifi scan\";\n\n /** NFC sensor. Part of the Neighboring Devices sensors. */\n public static final String NFC_SCAN = \"nfc_scan\";\n\n /** Acceleration sensor. Part of the Motion sensors, also used in Zephyr BioHarness */\n public static final String ACCELEROMETER = \"accelerometer\";\n\n /** Motion sensor. The basis for the other Motion sensors. */\n public static final String MOTION = \"motion\";\n\n /** Linear acceleration sensor name. Part of the Motion sensors. */\n public static final String LIN_ACCELERATION = \"linear acceleration\";\n\n /** Gyroscope sensor name. Part of the Motion sensors. */\n public static final String GYRO = \"gyroscope\";\n\n /** Magnetic field sensor name. Part of the Ambience sensors. */\n public static final String MAGNETIC_FIELD = \"magnetic field\";\n\n /** Orientation sensor name. Part of the Motion sensors. */\n public static final String ORIENT = \"orientation\";\n\n /** Epi-mode accelerometer sensor. Special part of the Motion sensors. */\n public static final String ACCELEROMETER_EPI = \"accelerometer (epi-mode)\";\n\n /** Burst-mode accelerometer sensor. Special part of the Motion sensors. */\n public static final String ACCELEROMETER_BURST = \"accelerometer (burst-mode)\";\n\n /** Burst-mode gyroscope sensor. Special part of the Motion sensors. */\n public static final String GYRO_BURST = \"gyroscope (burst-mode)\";\n\n /** Burst-mode linear acceleration sensor. Special part of the Motion sensors. */\n public static final String LINEAR_BURST = \"linear acceleration (burst-mode)\";\n\n /** Motion energy sensor name. Special part of the Motion sensors. */\n public static final String MOTION_ENERGY = \"motion energy\";\n\n /*** battery sensor for Zephyr BioHarness external sensor */\n public static final String BATTERY_LEVEL = \"battery level\";\n\n /** heart rate sensor for Zephyr BioHarness and HxM external sensors */\n public static final String HEART_RATE = \"heart rate\";\n\n /** respiration rate sensor for Zephyr BioHarness external sensor */\n public static final String RESPIRATION = \"respiration rate\";\n\n /** temperature sensor for Zephyr BioHarness external sensor */\n public static final String TEMPERATURE = \"temperature\";\n\n /** worn status for Zephyr BioHarness external sensor */\n public static final String WORN_STATUS = \"worn status\";\n\n /** blood pressure sensor */\n public static final String BLOOD_PRESSURE = \"blood_pressure\";\n\n /** reaction time sensor */\n public static final String REACTION_TIME = \"reaction_time\";\n\n /** speed sensor for Zephyr HxM external sensor */\n public static final String SPEED = \"speed\";\n\n /** distance sensor for Zephyr HxM external sensor */\n public static final String DISTANCE = \"distance\";\n\n /** battery sensor for Zephyr HxM external sensor */\n public static final String BATTERY_CHARGE = \"battery charge\";\n\n /** strides sensor (stappenteller) for Zephyr HxM external sensor */\n public static final String STRIDES = \"strides\";\n\n /** Location sensor. */\n public static final String LOCATION = \"position\";\n\n /** TimeZone sensor. */\n public static final String TIME_ZONE = \"time_zone\";\n\n /** Battery sensor. Part of the Phone State sensors. */\n public static final String BATTERY_SENSOR = \"battery sensor\";\n \n /** App info sensor. Part of the Phone State sensors. */\n public static final String APP_INFO_SENSOR = \"app_info\";\n\n /** Screen activity sensor. Part of the Phone State sensors. */\n public static final String SCREEN_ACTIVITY = \"screen activity\";\n\n /** Pressure sensor. Part of the Phone State sensors. */\n public static final String PRESSURE = \"pressure\";\n\n /** Proximity sensor. Part of the Phone State sensors. */\n public static final String PROXIMITY = \"proximity\";\n\n /** Call state sensor. Part of the Phone State sensors. */\n public static final String CALL_STATE = \"call state\";\n\n /** Data connection state sensor. Part of the Phone State sensors. */\n public static final String DATA_CONN = \"data connection\";\n\n /** IP address sensor. Part of the Phone State sensors. */\n public static final String IP_ADDRESS = \"ip address\";\n\n /** Mobile service state sensor. Part of the Phone State sensors. */\n public static final String SERVICE_STATE = \"service state\";\n\n /** Mobile signal strength sensor. Part of the Phone State sensors. */\n public static final String SIGNAL_STRENGTH = \"signal strength\";\n\n /** Unread messages sensor. Part of the Phone State sensors. */\n public static final String UNREAD_MSG = \"unread msg\";\n\n /** Data connection type sensor. Part of the Phone State sensors. */\n public static final String CONN_TYPE = \"connection type\";\n\n /** Monitor status since DTCs cleared. Part of the OBD-II sensors. */\n public static final String MONITOR_STATUS = \"monitor status\";\n\n /** Fuel system status. Part of the OBD-II sensors. */\n public static final String FUEL_SYSTEM_STATUS = \"fuel system status\";\n\n /** Calculated engine load. Part of the OBD-II sensors. */\n public static final String ENGINE_LOAD = \"calculated engine load value\";\n\n /** Engine coolant. Part of the OBD-II sensors. */\n public static final String ENGINE_COOLANT = \"engine coolant\";\n\n /** Short/Long term fuel trim bank 1 & 2. Part of the OBD-II sensors. */\n public static final String FUEL_TRIM = \"fuel trim\";\n\n /** Fuel Pressure. Part of the OBD-II sensors. */\n public static final String FUEL_PRESSURE = \"fuel pressure\";\n\n /** Intake manifold absolute pressure. Part of the OBD-II sensors. */\n public static final String INTAKE_PRESSURE = \"intake manifold absolute pressure\";\n\n /** Engine RPM. Part of the OBD-II sensors. */\n public static final String ENGINE_RPM = \"engine RPM\";\n\n /** Vehicle speed. Part of the OBD-II sensors. */\n public static final String VEHICLE_SPEED = \"vehicle speed\";\n\n /** Timing advance. Part of the OBD-II sensors. */\n public static final String TIMING_ADVANCE = \"timing advance\";\n\n /** Intake air temperature. Part of the OBD-II sensors. */\n public static final String INTAKE_TEMPERATURE = \"intake air temperature\";\n\n /** MAF air flow rate. Part of the OBD-II sensors. */\n public static final String MAF_AIRFLOW = \"MAF air flow rate\";\n\n /** Throttle position. Part of the OBD-II sensors. */\n public static final String THROTTLE_POSITION = \"throttle position\";\n\n /** Commanded secondary air status. Part of the OBD-II sensors. */\n public static final String AIR_STATUS = \"commanded secondary air status\";\n\n /** Oxygen sensors. Part of the OBD-II sensors. */\n public static final String OXYGEN_SENSORS = \"oxygen sensors\";\n\n /** OBD standards. Part of the OBD-II sensors. */\n public static final String OBD_STANDARDS = \"OBD standards\";\n\n /** Auxiliary input status. Part of the OBD-II sensors. */\n public static final String AUXILIARY_INPUT = \"auxiliary input status\";\n\n /** Run time since engine start. Part of the OBD-II sensors. */\n public static final String RUN_TIME = \"run time\";\n\n /** Ambient temperature sensor. Part of the ambience sensors. From API >= 14 only */\n public static final String AMBIENT_TEMPERATURE = \"ambient_temperature\";\n\n /** Relative humidity sensor. Part of the ambience sensors. From API >= 14 only */\n public static final String RELATIVE_HUMIDITY = \"relative_humidity\";\n\n /** Bluetooth number of neighbours, count sensor */\n public static final String BLUETOOTH_NEIGHBOURS_COUNT = \"bluetooth neighbours count\";\n\n /** Traveled distance for each day */\n public static final String TRAVELED_DISTANCE_24H = \"traveled distance 24h\";\n\n /** Traveled distance for each hour */\n public static final String TRAVELED_DISTANCE_1H = \"traveled distance 1h\";\n\n public static final String LOUDNESS = \"loudness\";\n\n public static final String ATTACHED_TO_MYRIANODE = \"attachedToMyriaNode\";\n\n public static final String APP_INSTALLED = \"installed_apps\";\n\n public static final String APP_FOREGROUND = \"foreground_app\";\n\n private SensorNames() {\n // class should not be instantiated\n }\n}",
"public class SNTP {\n private static final String TAG = \"SNTP\";\n\n private static final int ORIGINATE_TIME_OFFSET = 24;\n private static final int RECEIVE_TIME_OFFSET = 32;\n private static final int TRANSMIT_TIME_OFFSET = 40;\n private static final int NTP_PACKET_SIZE = 48;\n\n private static final int NTP_PORT = 123;\n private static final int NTP_MODE_CLIENT = 3;\n private static final int NTP_VERSION = 3;\n public static final String HOST_WORLDWIDE = \"pool.ntp.org\";\n public static final String HOST_ASIA = \"asia.pool.ntp.org\";\n public static final String HOST_EUROPE = \"europe.pool.ntp.org\";\n public static final String HOST_NORTH_AMERICA = \"north-america.pool.ntp.org\";\n public static final String HOST_SOUTH_AMERICA = \"south-america.pool.ntp.org\";\n public static final String HOST_OCEANIA = \"oceania.pool.ntp.org\";\n private boolean useSimulateTime = false;\n\n // Number of seconds between Jan 1, 1900 and Jan 1, 1970\n // 70 years plus 17 leap days\n private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;\n\n // system time computed from NTP server response\n private long mNtpTime;\n\n // value of SystemClock.elapsedRealtime() corresponding to mNtpTime\n private long mNtpTimeReference;\n\n // round trip time in milliseconds\n private long mRoundTripTime;\n\n private long clockOffset = -1;\n\n private static SNTP sntp = null;\n\n /**\n * Returns whether time simulation is used\n * @return True is simulate time is being used\n */\n public boolean isSimulatingTime()\n {\n return useSimulateTime;\n }\n\n /**\n * Sets the current simulation time\n *\n * Will set the clock to the provided simulation time.<br>\n * #getTime will give the updated time based on this simulation time<br>\n * @param time The epoch time in ms to use as current time\n */\n public void setCurrentSimulationTime(long time)\n {\n clockOffset = time - System.currentTimeMillis();\n useSimulateTime = true;\n }\n\n /**\n * Disables the time simulation\n */\n public void disableTimeSimulation()\n {\n if(!useSimulateTime)\n return;\n clockOffset = -1;\n useSimulateTime = false;\n }\n /*\n * Nice singleton :)\n */\n public synchronized static SNTP getInstance() {\n if (sntp == null)\n sntp = new SNTP();\n return sntp;\n }\n\n /**\n * Sends an SNTP request to the given host and processes the response.\n * \n * @param host\n * host name of the server.\n * @param timeout\n * network timeout in milliseconds.\n * @return true if the transaction was successful.\n */\n public boolean requestTime(String host, int timeout) {\n\ttry {\n\t DatagramSocket socket = new DatagramSocket();\n\t socket.setSoTimeout(timeout);\n\t InetAddress address = InetAddress.getByName(host);\n\t byte[] buffer = new byte[NTP_PACKET_SIZE];\n\t DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);\n\n\t // set mode = 3 (client) and version = 3\n\t // mode is in low 3 bits of first byte\n\t // version is in bits 3-5 of first byte\n\t buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);\n\n\t // get current time and write it to the request packet\n\t long requestTime = System.currentTimeMillis();\n\t long requestTicks = SystemClock.elapsedRealtime();\n\t writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);\n\n\t socket.send(request);\n\n\t // read the response\n\t DatagramPacket response = new DatagramPacket(buffer, buffer.length);\n\t socket.receive(response);\n\t long responseTicks = SystemClock.elapsedRealtime();\n\t long responseTime = requestTime + (responseTicks - requestTicks);\n\t socket.close();\n\n\t // extract the results\n\t long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);\n\t long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);\n\t long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);\n\t long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);\n\t // receiveTime = originateTime + transit + skew\n\t // responseTime = transmitTime + transit - skew\n\t // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2\n\t // = ((originateTime + transit + skew - originateTime) +\n\t // (transmitTime - (transmitTime + transit - skew)))/2\n\t // = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2\n\t // = (transit + skew - transit + skew)/2\n\t // = (2 * skew)/2 = skew\n\t clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime)) / 2;\n\t // if (Config.LOGD) Log.d(TAG, \"round trip: \" + roundTripTime + \" ms\");\n\t // if (Config.LOGD) Log.d(TAG, \"clock offset: \" + clockOffset + \" ms\");\n\n\t // save our results - use the times on this side of the network latency\n\t // (response rather than request time)\n\t mNtpTime = responseTime + clockOffset;\n\t mNtpTimeReference = responseTicks;\n\t mRoundTripTime = roundTripTime;\n\t} catch (Exception e) {\n\t Log.w(TAG, \"Request time failed: \" + e);\n\t return false;\n\t}\n\n\treturn true;\n }\n\n /**\n * Get the current time, based on NTP clockOffset if or System time\n * \n * @return the ntp time from the worldwide pool if available else the system time\n */\n public long getTime() {\n\t// get the clock offset\n\tif (clockOffset == -1) {\n\t if (requestTime(HOST_WORLDWIDE, 1000)) {\n\t\treturn getNtpTime();\n\t } else {\n\t\tclockOffset = 0;\n\t }\n\t}\n\n\treturn System.currentTimeMillis() + clockOffset;\n }\n\n /**\n * Returns the time computed from the NTP transaction.\n * \n * @return time value computed from NTP server response.\n */\n public long getNtpTime() {\n \t//Log.d(TAG,\"SNTP time requested\");\n \t//return 1412175540000l;\n \treturn mNtpTime;\n }\n\n /**\n * Returns the reference clock value (value of SystemClock.elapsedRealtime()) corresponding to\n * the NTP time.\n * \n * @return reference clock corresponding to the NTP time.\n */\n public long getNtpTimeReference() {\n\treturn mNtpTimeReference;\n }\n\n /**\n * Returns the round trip time of the NTP transaction\n * \n * @return round trip time in milliseconds.\n */\n public long getRoundTripTime() {\n\treturn mRoundTripTime;\n }\n\n /**\n * Reads an unsigned 32 bit big endian number from the given offset in the buffer.\n */\n private long read32(byte[] buffer, int offset) {\n\tbyte b0 = buffer[offset];\n\tbyte b1 = buffer[offset + 1];\n\tbyte b2 = buffer[offset + 2];\n\tbyte b3 = buffer[offset + 3];\n\n\t// convert signed bytes to unsigned values\n\tint i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);\n\tint i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);\n\tint i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);\n\tint i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);\n\n\treturn ((long) i0 << 24) + ((long) i1 << 16) + ((long) i2 << 8) + (long) i3;\n }\n\n /**\n * Reads the NTP time stamp at the given offset in the buffer and returns it as a system time\n * (milliseconds since January 1, 1970).\n */\n private long readTimeStamp(byte[] buffer, int offset) {\n\tlong seconds = read32(buffer, offset);\n\tlong fraction = read32(buffer, offset + 4);\n\treturn ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);\n }\n\n /**\n * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp at the given\n * offset in the buffer.\n */\n private void writeTimeStamp(byte[] buffer, int offset, long time) {\n\tlong seconds = time / 1000L;\n\tlong milliseconds = time - seconds * 1000L;\n\tseconds += OFFSET_1900_TO_1970;\n\n\t// write seconds in big endian format\n\tbuffer[offset++] = (byte) (seconds >> 24);\n\tbuffer[offset++] = (byte) (seconds >> 16);\n\tbuffer[offset++] = (byte) (seconds >> 8);\n\tbuffer[offset++] = (byte) (seconds >> 0);\n\n\tlong fraction = milliseconds * 0x100000000L / 1000L;\n\t// write fraction in big endian format\n\tbuffer[offset++] = (byte) (fraction >> 24);\n\tbuffer[offset++] = (byte) (fraction >> 16);\n\tbuffer[offset++] = (byte) (fraction >> 8);\n\t// low order bits should be random data\n\tbuffer[offset++] = (byte) (Math.random() * 255.0);\n }\n}",
"public class SensorDataPoint {\n\n public enum DataType {\n INT, FLOAT, BOOL, DOUBLE, STRING, ARRAYLIST, JSON, JSONSTRING, FILE, SENSOREVENT\n };\n\n /**\n * Name of the sensor that produced the data point.\n */\n public String sensorName;\n /**\n * Description of the sensor that produces the data point. Corresponds to the \"sensor_type\"\n * field in the CommonSense API.\n */\n public String sensorDescription;\n /**\n * Time stamp of the data point.\n */\n public long timeStamp;\n private DataType dataType;\n private Object value;\n\n /**\n * @see #SensorDataPoint(int)\n */\n public SensorDataPoint(Object value) { \n this.value = value;\n }\n \n /**\n * @see #SensorDataPoint(int)\n */\n public SensorDataPoint(ArrayList<SensorDataPoint> value) {\n dataType = DataType.ARRAYLIST;\n this.value = value;\n }\n\n /**\n * @see #SensorDataPoint(int)\n */\n public SensorDataPoint(Boolean value) {\n dataType = DataType.BOOL;\n this.value = value;\n }\n\n /**\n * @see #SensorDataPoint(int)\n */\n public SensorDataPoint(double value) {\n dataType = DataType.DOUBLE;\n this.value = value;\n }\n\n /**\n * @see #SensorDataPoint(int)\n */\n public SensorDataPoint(float value) {\n dataType = DataType.FLOAT;\n this.value = value;\n }\n\n /**\n * Sets the value of the SensorDataPoint based on the input value the dataType. The dataType can\n * be changed by {@link #setDataType(DataType)}.\n * \n * @param value\n * The input value which is stored in the SensorDataPoint\n */\n public SensorDataPoint(int value) {\n dataType = DataType.INT;\n this.value = value;\n }\n\n /**\n * @see #setValue(int)\n */\n public SensorDataPoint(JSONObject value) {\n dataType = DataType.JSON;\n this.value = value;\n }\n\n /**\n * @see #setValue(int)\n */\n public SensorDataPoint(SensorEvent value) {\n dataType = DataType.SENSOREVENT;\n this.value = value;\n }\n\n /**\n * @see #setValue(int)\n */\n public SensorDataPoint(String value) {\n dataType = DataType.STRING;\n this.value = value;\n }\n\n /**\n * @see #getIntValue()\n */\n @SuppressWarnings(\"unchecked\")\n public ArrayList<SensorDataPoint> getArrayValue() {\n return (ArrayList<SensorDataPoint>) value;\n }\n\n /**\n * @see #getIntValue()\n */\n public Boolean getBoolValue() {\n return (Boolean) value;\n }\n\n /**\n * Returns the dataType of the SensorDataPoint\n * \n * @return DataTypes\n */\n public DataType getDataType() {\n return dataType;\n }\n\n /**\n * @see #getIntValue()\n */\n public double getDoubleValue() {\n return (Double) value;\n }\n\n /**\n * @see #getIntValue()\n */\n public float getFloatValue() {\n return (Float) value;\n }\n\n /**\n * Return the value of the SensorDataPoint\n * \n * @return value\n */\n public int getIntValue() {\n return (Integer) value;\n }\n\n /**\n * @see #getIntValue()\n */\n public JSONObject getJSONValue() {\n return (JSONObject) value;\n }\n\n /**\n * @see #getIntValue()\n */\n public SensorEvent getSensorEventValue() {\n return (SensorEvent) value;\n }\n\n /**\n * @see #getIntValue()\n */\n public String getStringValue() {\n return (String) value;\n }\n\n /**\n * Sets the data type.\n * \n * This method overrides the dataType which has been set automatically. This method can be used\n * when a more precise dataType like FILE is needed.\n * \n * @param dataType\n * The dataType of the SensorDataPoint\n */\n public void setDataType(DataType dataType) {\n this.dataType = dataType;\n }\n}",
"public enum DataType {\n INT, FLOAT, BOOL, DOUBLE, STRING, ARRAYLIST, JSON, JSONSTRING, FILE, SENSOREVENT\n};",
"public abstract class BaseDataProducer implements DataProducer {\n\n\tprotected final String TAG = \"BaseDataProducer\";\n\t\n /** The DataProcessors which are subscribed to this sensor for sensor data */\n protected List<DataConsumer> mSubscribers = new ArrayList<DataConsumer>();\n\n /**\n * Adds a data consumer as subscriber to this data producer. This method is synchronized to\n * prevent concurrent modifications to the list of subscribers.\n * \n * @param consumer\n * The DataProcessor that wants the sensor data as input\n * @return <code>true</code> if the DataConsumer was successfully subscribed\n */\n @Override\n public synchronized boolean addSubscriber(DataConsumer consumer) {\n if (!hasSubscriber(consumer)) {\n return mSubscribers.add(consumer);\n } else {\n return false;\n }\n }\n\n /**\n * Checks subscribers if the sample is complete. This method uses\n * {@link DataConsumer#isSampleComplete()} to see if the sample is completed, or if the data\n * processors need more data.\n * \n * @return true when all the subscribers have complete samples\n */\n protected synchronized boolean checkSubscribers() {\n boolean complete = true;\n for (DataConsumer subscriber : mSubscribers) {\n if (subscriber != null) {\n complete &= subscriber.isSampleComplete();\n }\n }\n return complete;\n }\n\n @Override\n public synchronized boolean hasSubscriber(DataConsumer consumer) {\n for (DataConsumer subscriber : mSubscribers) {\n if (subscriber != null && subscriber.equals(consumer)) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public boolean hasSubscribers() {\n return !mSubscribers.isEmpty();\n }\n\n /**\n * Notifies subscribers that a new sample is starting. This method calls\n * {@link DataConsumer#startNewSample()} on each subscriber.\n */\n protected synchronized void notifySubscribers() {\n for (DataConsumer subscriber : mSubscribers) {\n if (subscriber != null) {\n subscriber.startNewSample();\n }\n }\n }\n\n /**\n * Removes a data subscriber if present. This method is synchronized to prevent concurrent\n * modifications.\n * \n * @param subscriber\n * The DataConsumer that should be unsubscribed\n */\n @Override\n public synchronized boolean removeSubscriber(DataConsumer consumer) {\n if (mSubscribers.contains(consumer)) {\n return mSubscribers.remove(consumer);\n }\n return true;\n }\n\n /**\n * Sends data to all subscribed data consumers.\n * \n * @param dataPoint\n * The SensorDataPoint to send\n */\n // TODO: do a-sync\n protected synchronized void sendToSubscribers(SensorDataPoint dataPoint) {\n for (DataConsumer subscriber : mSubscribers) {\n if (subscriber != null && !subscriber.isSampleComplete()) {\n \ttry\n \t{\n \t\tsubscriber.onNewData(dataPoint);\n \t}\n \tcatch(Exception e)\n \t{\n \t\tLog.e(TAG, \"Error sending data to subscriber.\", e);\n \t}\n }\n }\n }\n}",
"public interface DataConsumer {\n\n /**\n * Starts a new sample.\n * \n * @see #isSampleComplete()\n */\n public abstract void startNewSample();\n\n /**\n * @return <code>true</code> if the data consumer has received enough sensor events so that the\n * sample is complete\n */\n public abstract boolean isSampleComplete();\n\n /**\n * Handles a new data point. Take care: the sensor event is not guaranteed to be from the sensor\n * that the DataConsumer is interested in, so implementing classes need to check this.\n * \n * @param dataPoint\n */\n public abstract void onNewData(SensorDataPoint dataPoint);\n}"
] | import nl.sense_os.service.R;
import nl.sense_os.service.constants.SenseDataTypes;
import nl.sense_os.service.constants.SensorData.DataPoint;
import nl.sense_os.service.constants.SensorData.SensorNames;
import nl.sense_os.service.provider.SNTP;
import nl.sense_os.service.shared.SensorDataPoint;
import nl.sense_os.service.shared.SensorDataPoint.DataType;
import nl.sense_os.service.subscription.BaseDataProducer;
import nl.sense_os.service.subscription.DataConsumer;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.os.SystemClock;
import android.util.FloatMath;
import android.util.Log; | }
}
private boolean fallDetected(float accVecSum) {
// Log.d("Fall detection:", "time:"+(SystemClock.elapsedRealtime()-time));
time = SystemClock.elapsedRealtime();
if (interrupt.FALL || (demo && interrupt.FREE_FALL))
reset();
freeFall(accVecSum);
if (demo) {
if (interrupt.FREE_FALL) {
reset();
return true;
}
} else {
activity(accVecSum);
if (useInactivity) {
if (!interrupt.INACTIVITY)
inactivity(accVecSum);
} else
interrupt.FALL = interrupt.ACTIVITY;
if (interrupt.FALL) {
reset();
return true;
}
}
return false;
}
private void freeFall(float accVecSum) {
if (accVecSum < THRESH_FF) {
if (startInterrupt == 0)
startInterrupt = SystemClock.elapsedRealtime();
else if ((SystemClock.elapsedRealtime() - startInterrupt > TIME_FF && !demo)
|| (SystemClock.elapsedRealtime() - startInterrupt > TIME_FF_DEMO && demo)) {
// Log.v("Fall detection", "FF time:" + (SystemClock.elapsedRealtime() -
// startInterrupt));
interrupt.FREE_FALL = true;
}
} else if (interrupt.FREE_FALL) {
interrupt.stopFreeFall = SystemClock.elapsedRealtime();
interrupt.FREE_FALL = false;
startInterrupt = 0;
} else
startInterrupt = 0;
if (interrupt.FREE_FALL) {
Log.w(TAG, "FALL!!!");
}
}
private void inactivity(float accVecSum) {
if (interrupt.stopActivity == 0)
return;
if (accVecSum < THRESH_INACT) {
if (SystemClock.elapsedRealtime() - interrupt.stopActivity < TIME_ACT_INACT)
if (startInterrupt == 0)
startInterrupt = SystemClock.elapsedRealtime();
if (startInterrupt != 0 && SystemClock.elapsedRealtime() - startInterrupt > TIME_INACT)
interrupt.INACTIVITY = true;
} else if (startInterrupt != 0 && !interrupt.INACTIVITY)
reset();
if (SystemClock.elapsedRealtime() - interrupt.stopActivity >= TIME_ACT_INACT
&& startInterrupt == 0)
reset();
interrupt.FALL = interrupt.INACTIVITY;
if (interrupt.INACTIVITY) {
Log.w(TAG, "Inactivity!!!");
}
}
@Override
public boolean isSampleComplete() {
// never unregister
return false;
}
@Override
public void onNewData(SensorDataPoint dataPoint) {
if(dataPoint.getDataType() != DataType.SENSOREVENT)
return;
SensorEvent event = dataPoint.getSensorEventValue();
// check if this is useful data point
Sensor sensor = event.sensor;
if (sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return;
}
float aX = event.values[1];
float aY = event.values[0];
float aZ = event.values[2];
float accVecSum = FloatMath.sqrt(aX * aX + aY * aY + aZ * aZ);
if (fallDetected(accVecSum)) {
// send msg
sendFallMessage(true);
}
}
private void reset() {
interrupt = new Interrupt();
startInterrupt = 0;
}
public void sendFallMessage(boolean fall) {
this.notifySubscribers();
SensorDataPoint dataPoint = new SensorDataPoint(fall); | dataPoint.sensorName = SensorNames.FALL_DETECTOR; | 1 |
1014277960/DailyReader | app/src/main/java/com/wulinpeng/daiylreader/read/ui/BookFactory.java | [
"public class Application extends android.app.Application {\n\n private static Context context;\n\n @Override\n public void onCreate() {\n super.onCreate();\n context = getApplicationContext();\n CrashReport.initCrashReport(getApplicationContext(), \"869beebc76\", false);\n }\n\n public static Context getContext() {\n return context;\n }\n}",
"public class ChapterDetailResponse {\n /**\n * {\n \"ok\": true,\n \"chapter\": {\n \"title\": \"第1章 苏雪\",\n \"body\": \"\\n\\r\\n\\r\\n\\r请安装最新版追书 以便使用优质资源\",\n \"isVip\": false,\n \"cpContent\": \"“谢谢老板!”凌心开心的接过老板递过来的钱,跟老板道谢着。\\n\\n 老板钟发白看着眼前的凌心,对于凌心这样的年轻人心中也是也很满意。在钟发白看来这小伙子为人机灵,任务每次都完成的不错,所以钟发白也乐得多照顾一下他,每月都多发了好几百工资给凌心。\\n\\n 今天是月结工资的日子,在拘谨了半个月后,凌心终于又有钱开销了。\\n\\n 3000华夏币的工资,这笔收入,在华夏低级穷人区里可是不多见的。像华夏的高级穷人区,他们的每个月最高收入也就差不多3000地球币,地球币与华夏币的兑率在10倍左右。\\n\\n 而高级穷人区的生活质量可是低级穷人区的百倍,此刻凌心拿到的工资可是足有高级穷人区的十分之一,这可是非常不错的了,当然凌心干的活也不是什么体面的活。\\n\\n!\\n\\n\",\n \"currency\": 15,\n \"id\": \"586e14be3ceecbf110f72c42\"\n }\n }\n */\n\n private boolean ok;\n private Chapter chapter;\n\n public boolean isOk() {\n return ok;\n }\n\n public void setOk(boolean ok) {\n this.ok = ok;\n }\n\n @Override\n public String toString() {\n return \"ChapterDetailResponse{\" +\n \"ok=\" + ok +\n \", chapter=\" + chapter +\n '}';\n }\n\n public Chapter getChapter() {\n return chapter;\n }\n\n public void setChapter(Chapter chapter) {\n this.chapter = chapter;\n }\n\n public static class Chapter {\n private String title;\n private String body;\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getBody() {\n return body;\n }\n\n public void setBody(String body) {\n this.body = body;\n }\n\n @Override\n public String toString() {\n return \"Chapter{\" +\n \"title='\" + title + '\\'' +\n \", body='\" + body + '\\'' +\n '}';\n }\n }\n}",
"public class ChaptersResponse {\n /**\n * {\n \"mixToc\":{\n \"_id\":\"53a2c9fbfda0a68d82ff5e51\",\n \"book\":\"51651e375a29ee6a5e0000af\",\n \"chaptersUpdated\":\"2016-07-08T12:05:45.737Z\",\n \"updated\":\"2016-09-29T20:41:01.440Z\",\n \"chapters\":[{\n \"title\":\"第一章 古洞\",\n \"link\":\"http://www.17k.com/chapter/367975/8098369.html\",\n \"unreadble\":false\n },\n ...\n ]\n },\n \"ok\":true\n }\n */\n\n private MixToc mixToc;\n\n private boolean ok;\n\n\n public MixToc getMixToc() {\n return mixToc;\n }\n\n public void setMixToc(MixToc mixToc) {\n this.mixToc = mixToc;\n }\n\n public boolean isOk() {\n return ok;\n }\n\n public void setOk(boolean ok) {\n this.ok = ok;\n }\n\n\n @Override\n public String toString() {\n return \"ChaptersResponse{\" +\n \"mixToc=\" + mixToc +\n \", ok=\" + ok +\n '}';\n }\n\n public static class MixToc {\n private String _id;\n private String book;\n private String chaptersUpdated;\n private String updated;\n private List<Chapter> chapters;\n\n public String get_id() {\n return _id;\n }\n\n public void set_id(String _id) {\n this._id = _id;\n }\n\n public String getBook() {\n return book;\n }\n\n public void setBook(String book) {\n this.book = book;\n }\n\n public String getChaptersUpdated() {\n return chaptersUpdated;\n }\n\n public void setChaptersUpdated(String chaptersUpdated) {\n this.chaptersUpdated = chaptersUpdated;\n }\n\n public String getUpdated() {\n return updated;\n }\n\n public void setUpdated(String updated) {\n this.updated = updated;\n }\n\n public List<Chapter> getChapters() {\n return chapters;\n }\n\n public void setChapters(List<Chapter> chapters) {\n this.chapters = chapters;\n }\n\n @Override\n public String toString() {\n return \"MixToc{\" +\n \"_id='\" + _id + '\\'' +\n \", book='\" + book + '\\'' +\n \", chaptersUpdated='\" + chaptersUpdated + '\\'' +\n \", updated='\" + updated + '\\'' +\n \", chapters=\" + chapters +\n '}';\n }\n }\n\n public static class Chapter {\n private String title;\n private String link;\n private boolean unreadble;\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getLink() {\n return link;\n }\n\n public void setLink(String link) {\n this.link = link;\n }\n\n public boolean isUnreadble() {\n return unreadble;\n }\n\n public void setUnreadble(boolean unreadble) {\n this.unreadble = unreadble;\n }\n\n @Override\n public String toString() {\n return \"Chapter{\" +\n \"title='\" + title + '\\'' +\n \", link='\" + link + '\\'' +\n \", unreadble=\" + unreadble +\n '}';\n }\n }\n}",
"public class CacheManager {\n\n private static volatile CacheManager mInstance;\n\n private CacheHelper mCacheHelper;\n\n public CacheManager() {\n mCacheHelper = CacheHelper.getInstance();\n }\n\n public static CacheManager getInstance() {\n if (mInstance == null) {\n synchronized (CacheManager.class) {\n if (mInstance == null) {\n mInstance = new CacheManager();\n }\n }\n }\n return mInstance;\n }\n\n /**\n * =============================================================\n * ================== 收藏书籍 ========================\n * =============================================================\n */\n\n public void saveCollection(BookCollection collection) {\n mCacheHelper.saveObject(\"collection\", collection);\n }\n\n public BookCollection getCollection() {\n return mCacheHelper.getObject(\"collection\", BookCollection.class);\n }\n\n /**\n * =============================================================\n * ================== 书本章节列表 ========================\n * =============================================================\n */\n\n /**\n * 返回某一本书籍的全部信息缓存路径\n * @param bookId\n * @return\n */\n private File getBookDir(String bookId) {\n File file = new File(mCacheHelper.getRootFile(), \"book\");\n if (!file.exists()) {\n file.mkdir();\n }\n File bookDir = new File(file, bookId);\n if (!bookDir.exists()) {\n bookDir.mkdir();\n }\n return bookDir;\n }\n\n public void saveChapters(ChaptersResponse.MixToc toc) {\n File book = new File(getBookDir(toc.getBook()), \"chapters\");\n try {\n book.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n mCacheHelper.saveObject(book, toc);\n }\n\n public ChaptersResponse.MixToc getChapters(String bookId) {\n File chapters = new File(getBookDir(bookId), \"chapters\");\n if (!chapters.exists()) {\n return null;\n }\n return mCacheHelper.getObject(chapters, ChaptersResponse.MixToc.class);\n }\n\n /**\n * =============================================================\n * ================== 书本章节内容 ========================\n * =============================================================\n */\n\n public void saveChapter(String bookId, int index, ChapterDetailResponse.Chapter chapter) {\n File chapterFile = new File(getBookDir(bookId), \"chapter\" + index);\n try {\n chapterFile.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n mCacheHelper.saveString(chapterFile, chapter.getBody());\n }\n\n public ChapterDetailResponse.Chapter getChapter(String bookId, int index) {\n File chapterFile = new File(getBookDir(bookId), \"chapter\" + index);\n if (!chapterFile.exists()) {\n return null;\n }\n return mCacheHelper.getObject(chapterFile, ChapterDetailResponse.Chapter.class);\n }\n\n public File getChapterFile(String bookId, int index) {\n File chapterFile = new File(getBookDir(bookId), \"chapter\" + index);\n if (!chapterFile.exists()) {\n return null;\n }\n return chapterFile;\n }\n\n}",
"public class OnChapterLoadEvent {\n}",
"public class RxUtil {\n\n public static <T> Observable.Transformer<T, T> rxScheduler() {\n return observable -> observable\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread());\n }\n}",
"public static Context getContext() {\n return context;\n}"
] | import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.Toast;
import com.wulinpeng.daiylreader.Application;
import com.wulinpeng.daiylreader.R;
import com.wulinpeng.daiylreader.net.ReaderApiManager;
import com.wulinpeng.daiylreader.bean.ChapterDetailResponse;
import com.wulinpeng.daiylreader.bean.ChaptersResponse;
import com.wulinpeng.daiylreader.manager.CacheManager;
import com.wulinpeng.daiylreader.read.event.OnChapterLoadEvent;
import com.wulinpeng.daiylreader.util.RxUtil;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.wulinpeng.daiylreader.Application.getContext; | package com.wulinpeng.daiylreader.read.ui;
/**
* @author wulinpeng
* @datetime: 17/2/8 下午7:00
* @description:
*/
public class BookFactory {
/**
* 翻页的状态,如果是新章节且内存中没有那么可能会有网络请求那就是异步,就不能直接draw了,等待读取完毕再调用接口通知draw
*/
public static final int STATE_SUCCESS = 0;
public static final int STATE_ASYN = 1;
public static final int STATE_NULL = 2;
private int mHeight;
private int mWidth;
public int mNormalSize = 45;
public int mTitleSize = 64;
public Paint mNormalPaint;
public Paint mTitlePaint;
public int mNormalMargin = 30;
private String mTitle;
private Bitmap mBackgroundBitmap;
// 当前章节数
private int mCurrentChapterIndex;
//当前是第几页
public int mCurrentPage;
private ChaptersResponse.MixToc mChaptersInfo;
// 根据当前格式处理后的章节内容
private Map<Integer, List<List<String>>> mFormatChapters = new HashMap<>();
private ChapterDetailResponse.Chapter mCurrentChapter;
public BookFactory(ChaptersResponse.MixToc chaptersInfo){
this.mChaptersInfo = chaptersInfo;
getWidthAndHeight();
mNormalPaint = new Paint();
mNormalPaint.setTextSize(mNormalSize);
mNormalPaint.setColor(Color.BLACK);
mNormalPaint.setTextAlign(Paint.Align.LEFT);
mTitlePaint = new Paint();
mTitlePaint.setTextSize(mTitleSize);
mTitlePaint.setColor(Color.DKGRAY);
mTitlePaint.setTextAlign(Paint.Align.CENTER);
mTitlePaint.setTypeface(Typeface.DEFAULT_BOLD);
mCurrentPage = 0;
mBackgroundBitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.bg_read);
}
private void getWidthAndHeight() {
WindowManager wm = (WindowManager) getContext()
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
mWidth = metrics.widthPixels;
mHeight = metrics.heightPixels;
}
/**
* 打开小说某一章
* @param chapter
* @param start 0首页还是1尾页
* @return
*/
public int openBook(int chapter, int start) {
mCurrentChapterIndex = chapter;
mTitle = mChaptersInfo.getChapters().get(chapter).getTitle();
if (mFormatChapters.get(mCurrentChapterIndex) == null) {
// 缓存没有到内存拿
if (getChapterFromCache(chapter, start)) {
return STATE_SUCCESS;
} else {
getChapterFromNet(chapter, start);
return STATE_ASYN;
}
} else {
// 是0就就是0,否则1不影响
mCurrentPage = (mFormatChapters.get(mCurrentChapterIndex).size() - 1) * start;
return STATE_SUCCESS;
}
}
private boolean getChapterFromCache(int chapter, int start) {
ChapterDetailResponse.Chapter c = CacheManager.getInstance().getChapter(mChaptersInfo.getBook(), chapter);
if (c != null) {
formatChapter(c);
mCurrentPage = (mFormatChapters.get(mCurrentChapterIndex).size() - 1) * start;
return true;
} else {
return false;
}
}
private void getChapterFromNet(int chapter, int start) {
ReaderApiManager.INSTANCE.getChapterDetail(mChaptersInfo.getChapters().get(chapter).getLink()) | .compose(RxUtil.rxScheduler()) | 5 |
endercrest/VoidSpawn | src/main/java/com/endercrest/voidspawn/commands/DetectorCommand.java | [
"public class ConfigManager {\n private VoidSpawn plugin;\n private static final ConfigManager instance = new ConfigManager();\n private File worldFile;\n private FileConfiguration config;\n private final int CURRENT_VERSION = 2;\n\n /**\n * Get the running instance of the ConfigManager\n *\n * @return The ConfigManager\n */\n public static ConfigManager getInstance() {\n return instance;\n }\n\n /**\n * Setup the ConfigManager instance. Should only be called on startup.\n *\n * @param plugin VoidSpawn Plugin.\n */\n public void setUp(VoidSpawn plugin) {\n this.plugin = plugin;\n worldFile = new File(plugin.getDataFolder(), \"worlds.yml\");\n boolean isCreated = isFileCreated();\n if (!isCreated) {\n createFile();\n }\n config = YamlConfiguration.loadConfiguration(worldFile);\n\n if (!isCreated) {\n config.set(\"version\", CURRENT_VERSION);\n }\n\n //Run Migration\n migrate();\n }\n\n /**\n * Migrate the config to new versions.\n */\n private void migrate() {\n migrateV1();\n migrateV2();\n\n saveConfig();\n }\n\n /**\n * Migrate the config to version 1 from 0.\n * <p>\n * This migration involves converting names to safe names that do not contain spaces.\n */\n private void migrateV1() {\n if (!config.isSet(\"version\")) {\n plugin.log(\"Converting worlds.yml to version 1\");\n config.set(\"version\", 1);\n\n ConfigurationSection section = config.getRoot();\n if (section != null) {\n for (String key: section.getKeys(false)) {\n //Convert world names into safe world names.\n if ((!key.equalsIgnoreCase(\"version\")) && (!key.equals(WorldUtil.configSafe(key)))) {\n config.set(WorldUtil.configSafe(key), config.get(key));\n config.set(key, null);\n }\n }\n }\n\n plugin.log(\"Version 1 conversion complete.\");\n }\n }\n\n private void migrateV2() {\n if (config.getInt(\"version\", 0) >= 2)\n return;\n\n long time = Instant.now().toEpochMilli();\n\n String newName = String.format(\"worlds.%s.yml\", time);\n File file = new File(plugin.getDataFolder(), newName);\n plugin.log(String.format(\"Backing up worlds.yml to %s\", newName));\n try {\n config.save(file);\n } catch (IOException e) {\n plugin.log(\"Failed to backup worlds.yml\");\n e.printStackTrace();\n return;\n }\n\n plugin.log(\"Converting world.yml to version 2\");\n config.set(\"version\", 2);\n\n for (String key: config.getKeys(false)) {\n if (!config.isConfigurationSection(key))\n continue;\n ConfigurationSection section = config.getConfigurationSection(key);\n if (section == null)\n continue;\n\n section.set(\"options.offset\", section.get(\"offset\"));\n section.set(\"options.\" + BaseMode.OPTION_MESSAGE.getName(), section.get(\"message\"));\n section.set(\"options.\" + BaseMode.OPTION_HYBRID.getName(), section.get(\"hybrid\"));\n section.set(\"options.\" + BaseMode.OPTION_SOUND.getName(), section.get(\"sound.name\"));\n section.set(\"options.\" + BaseMode.OPTION_SOUND_VOLUME.getName(), section.get(\"sound.volume\"));\n section.set(\"options.\" + BaseMode.OPTION_SOUND_PITCH.getName(), section.get(\"sound.pitch\"));\n section.set(\"options.\" + BaseMode.OPTION_KEEP_INVENTORY.getName(), section.get(\"keep_inventory\"));\n section.set(\"options.\" + BaseMode.OPTION_COMMAND.getName(), section.get(\"command\"));\n\n section.set(\"offset\", null);\n section.set(\"message\", null);\n section.set(\"hybrid\", null);\n section.set(\"sound.name\", null);\n section.set(\"sound.volume\", null);\n section.set(\"sound.pitch\", null);\n section.set(\"keep_inventory\", null);\n section.set(\"command\", null);\n }\n\n plugin.log(\"Version 2 conversion complete.\");\n }\n\n /**\n * Checks if world has been set in config\n *\n * @param world The world name\n * @return boolean whether the world is set in the config.\n */\n public boolean isWorldSpawnSet(String world) {\n world = WorldUtil.configSafe(world);\n\n return (isSet(world)) && (isSet(world + \".spawn.x\")) && (isSet(world + \".spawn.y\"))\n && (isSet(world + \".spawn.z\")) && (isSet(world + \".spawn.pitch\"))\n && (isSet(world + \".spawn.yaw\")) && (isSet(world + \".spawn.world\"));\n }\n\n /**\n * Reloads the config from the original file. DOES NOT SAVE BEFORE RELOADING.\n */\n public void reloadConfig() {\n worldFile = new File(plugin.getDataFolder(), \"worlds.yml\");\n if (!isFileCreated()) {\n createFile();\n }\n config = YamlConfiguration.loadConfiguration(worldFile);\n }\n\n /**\n * Set the spawn mode for the specified world.\n *\n * @param world The world being set.\n * @param mode The mode for teleporting.\n */\n public void setMode(String world, String mode) {\n world = WorldUtil.configSafe(world);\n\n if (mode.equalsIgnoreCase(\"none\")) {\n set(world + \".mode\", null);\n return;\n }\n if ((mode.equalsIgnoreCase(\"command\")) && (!isSet(world + \".command\"))) {\n set(world + \".command\", \"spawn\");\n }\n set(world + \".mode\", mode);\n saveConfig();\n }\n\n /**\n * Get the current mode for the specified world.\n *\n * @param world The world that the mode is set for.\n * @return String name of the mode or empty string if nothing is found.\n */\n public String getMode(String world) {\n world = WorldUtil.configSafe(world);\n\n return getString(world + \".mode\", \"\");\n }\n\n /**\n * Checks whether anything is set for the mode in a particular world.\n *\n * @param world The wolrd to be checked.\n * @return true if world has a mode set. Does not verify whether mode is valid.\n */\n public boolean isModeSet(String world) {\n world = WorldUtil.configSafe(world);\n\n return isSet(world + \".mode\");\n }\n\n /**\n * Set spawn for a specific world at the location of the specified player.\n *\n * @param player The player who is setting the location.\n * @param world THe world in which the spawn is being set for.\n */\n public void setSpawn(Player player, String world) {\n world = WorldUtil.configSafe(world);\n\n Location loc = player.getLocation();\n set(world + \".spawn.x\", loc.getX());\n set(world + \".spawn.y\", loc.getY());\n set(world + \".spawn.z\", loc.getZ());\n set(world + \".spawn.pitch\", loc.getPitch());\n set(world + \".spawn.yaw\", loc.getYaw());\n set(world + \".spawn.world\", loc.getWorld().getName());\n saveConfig();\n }\n\n @Nullable\n public Location getSpawn(String world) {\n if(!isWorldSpawnSet(world))\n return null;\n\n world = WorldUtil.configSafe(world);\n\n\n return new Location(Bukkit.getWorld(getString(world + \".spawn.world\", null)),\n getDouble(world + \".spawn.x\", 0.0),\n getDouble(world + \".spawn.y\", 0.0),\n getDouble(world + \".spawn.z\", 0.0),\n getFloat(world + \".spawn.pitch\", 0.0f),\n getFloat(world + \".spawn.yaw\", 0.0f));\n }\n\n /**\n * Removes the spawn of a world based on the world name.\n *\n * @param world The world name.\n */\n public void removeSpawn(String world) {\n world = WorldUtil.configSafe(world);\n set(world + \".spawn\", null);\n saveConfig();\n }\n\n /**\n * Checks if the world data file exists.\n *\n * @return True if world.yml exists.\n */\n public boolean isFileCreated() {\n return worldFile.exists();\n }\n\n /**\n * Create the world file.\n */\n public void createFile() {\n try {\n worldFile.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public String getOption(String world, OptionIdentifier<?> identifier) {\n return getOption(world, identifier.getName());\n }\n\n public String getOption(String world, String option) {\n world = WorldUtil.configSafe(world);\n\n return getString(world + \".options.\" + option, null);\n }\n\n public void setOption(String world, String options, String value) {\n world = WorldUtil.configSafe(world);\n\n set(world + \".options.\" + options, value);\n saveConfig();\n }\n\n /**\n * Set the detector value for a world, this method doesn't validate whether it is a valid detector.\n *\n * @param detector The detector value to set.\n * @param world The world.\n */\n public void setDetector(String detector, String world) {\n world = WorldUtil.configSafe(world);\n\n set(world + \".detector\", detector);\n saveConfig();\n }\n\n /**\n * Gets the detector set for a world. If it is not set, the value will return the default detector\n * defined in DetectorManager.\n *\n * @param world The world\n * @return The string name of the detector or defaults to default value set in DetectorManager.\n */\n public String getDetector(String world) {\n world = WorldUtil.configSafe(world);\n\n String detector = getString(world + \".detector\", \"\");\n return !detector.isEmpty() ? detector : DetectorManager.getInstance().getDefaultDetectorName();\n }\n\n /**\n * Checks if the path is set.\n *\n * @param path The YAML path to check.\n * @return True if there is a value assigned to it.\n */\n private boolean isSet(String path) {\n return config.isSet(path);\n }\n\n /**\n * Get the double at the specified path.\n *\n * @param path THe YAML path.\n * @return double if it exists.\n */\n public double getDouble(String path, double def) {\n return config.getDouble(path, def);\n }\n\n /**\n * Get the float at the specified path.\n *\n * @param path THe YAML path.\n * @return float if it exists.\n */\n public float getFloat(String path, float def) {\n return (float) config.getDouble(path, def);\n }\n\n /**\n * Get the string at the specified path.\n *\n * @param path THe YAML path.\n * @return string if it exists.\n */\n public String getString(String path, String def) {\n return config.getString(path, def);\n }\n\n /**\n * Get the boolean at the specified path.\n *\n * @param path THe YAML path.\n * @return boolean if it exists.\n */\n public boolean getBoolean(String path, boolean def) {\n return config.getBoolean(path, def);\n }\n\n /**\n * Get the integer at the specified path.\n *\n * @param path THe YAML path.\n * @return integer if it exists.\n */\n public int getInt(String path, int def) {\n return config.getInt(path, def);\n }\n\n /**\n * Set the path in the world data file with the desired value.\n *\n * @param path The path in the YAML file.\n * @param obj The object being saved into the file.\n */\n private void set(String path, Object obj) {\n config.set(path, obj);\n }\n\n /**\n * Save the world data file.\n */\n public void saveConfig() {\n try {\n config.save(worldFile);\n } catch (IOException e) {\n plugin.log(\"&4Could not save worldFile\");\n e.printStackTrace();\n }\n }\n}",
"public class DetectorManager {\n\n private static DetectorManager instance = new DetectorManager();\n\n public static DetectorManager getInstance() {\n return instance;\n }\n\n private Detector defaultDetector;\n private HashMap<String, Detector> detectors;\n\n /**\n * Setup the DetectorManager, should only be called once.\n */\n public void setUp() {\n defaultDetector = new VoidDetector();\n\n detectors = new HashMap<String, Detector>() {{\n put(\"void\", defaultDetector);\n put(\"nether\", new NetherDetector());\n }};\n }\n\n /**\n * Gets a HashMap of the detectors.\n *\n * @return A clone of the detectors HashMap where string is the key of the detector and SubDetector is detector class.\n */\n public HashMap<String, Detector> getDetectors() {\n return new HashMap<>(detectors);\n }\n\n /**\n * Add a new detector that can be accessed in-game and be set for worlds.\n *\n * @param name The name of the detector.\n * @param detector The class definition.\n * @throws NameAlreadyBoundException Thrown when the detector has already been set with that name.\n */\n public void addDetector(String name, Detector detector) throws NameAlreadyBoundException {\n name = name.toLowerCase();\n\n if (detectors.containsKey(name))\n throw new NameAlreadyBoundException(String.format(\"A detector with the name %s has already been set.\", name));\n\n detectors.put(name, detector);\n }\n\n /**\n * Removes detector, from being selectable and stops world from using this detector.\n *\n * @param name The name of the detector.\n */\n public void removeDetector(String name) {\n detectors.remove(name.toLowerCase());\n }\n\n /**\n * Get the world detector or returns the default detector (VoidDetector)\n *\n * @param worldName The world name.\n * @return Detector if set or defaults to VoidDetector.\n */\n public Detector getWorldDetector(String worldName) {\n String detector = ConfigManager.getInstance().getDetector(worldName);\n return getDetector(detector.toLowerCase());\n }\n\n /**\n * Get the detector by it's name/id. Returns default if does not exist.\n *\n * @param detector The detector name/id.\n * @return Detector or default if not exists.\n */\n public Detector getDetector(String detector) {\n Detector sd = detectors.get(detector.toLowerCase());\n return sd == null ? defaultDetector : sd;\n }\n\n /**\n * Get the default detectors names.\n *\n * @return The default detectors name.\n */\n public String getDefaultDetectorName() {\n return defaultDetector.getName();\n }\n\n /**\n * Get the default detector's class.\n *\n * @return Detector's class.\n */\n public Detector getDefaultDetector() {\n return defaultDetector;\n }\n\n /**\n * Set a new default detector.\n *\n * @param name The name of the detector.\n * @return Returns true if the default detector has successfully been set.\n */\n public boolean setDefaultDetector(String name) {\n Detector newDetector = getDetector(name);\n\n if (newDetector != null)\n defaultDetector = newDetector;\n\n return newDetector != null;\n }\n}",
"public class VoidSpawn extends JavaPlugin {\n public static String prefix = \"[&6VS&f] \";\n\n public void onEnable(){\n try {\n // This is the class we check for as it was added in 1.13 and should remain in place for the long term.\n Class.forName(\"org.bukkit.Tag\");\n } catch (ClassNotFoundException e) {\n log(\"&cERROR: Unsupported version of Spigot/Paper detected!\");\n log(\"&cERROR: Disabling plugin! Please update to latest version\");\n log(\"&cERROR: or use an unsupported version of VoidSpawn\");\n Bukkit.getPluginManager().disablePlugin(this);\n return;\n }\n\n /* if[PROD] */\n Metrics metrics = new Metrics(this, 3514);\n /* end[PROD] */\n\n loadConfiguration();\n ConfigManager.getInstance().setUp(this);\n TeleportManager.getInstance().setUp(this);\n ModeManager.getInstance().setUp(this);\n DetectorManager.getInstance().setUp();\n getServer().getPluginManager().registerEvents(new VoidListener(this), this);\n getServer().getPluginManager().registerEvents(new QuitListener(), this);\n\n PluginCommand command = getCommand(\"voidspawn\");\n CommandHandler commandHandler = new CommandHandler(this);\n command.setExecutor(commandHandler);\n command.setTabCompleter(new VoidSpawnTabCompleter(commandHandler));\n\n Bukkit.getScheduler().runTaskTimer(this, new TouchTracker(), 5, 5);\n\n log(\"&ev\" + getDescription().getVersion() + \" by EnderCrest enabled\");\n }\n\n public void onDisable(){\n log(\"&ev\" + getDescription().getVersion() + \" saving config\");\n ConfigManager.getInstance().saveConfig();\n log(\"&ev\" + getDescription().getVersion() + \" disabled\");\n }\n\n public void loadConfiguration(){\n if(!getConfig().contains(\"color-logs\")){\n getConfig().addDefault(\"color-logs\", true);\n }\n getConfig().options().copyDefaults(true);\n saveConfig();\n }\n\n /**\n * Sends Messages to Console\n *\n * @param obj The Obj(Message)\n */\n public void log(Object obj){\n if(getConfig().getBoolean(\"color-logs\", true)){\n getServer().getConsoleSender().sendMessage(MessageUtil.colorize(\"&3[&d\" + getName() + \"&3] &r\" + obj));\n }else{\n Bukkit.getLogger().log(Level.INFO, \"[\" + getName() + \"] \" + MessageUtil.colorize((String) obj).replaceAll(\"(?)\\u00a7([a-f0-9k-or])\", \"\"));\n }\n }\n\n}",
"public interface Detector extends OptionContainer {\n\n /**\n * Checks if the current player is within the 'detected' region. This is used to signal to the mode whether it\n * should activate\n * @param mode The current mode\n * @param player The player\n * @param world The world\n */\n boolean isDetected(Mode mode, Player player, World world);\n\n String getDescription();\n\n /**\n * Get the name of the detector.\n *\n * @return The string version of the mode.\n */\n String getName();\n}",
"public class CommandUtil {\n\n public static String constructWorldFromArgs(String[] args, int start, String defaultWorld) {\n String world = defaultWorld;\n if(args.length > start) {\n StringBuilder worldName = new StringBuilder();\n for(int i = start; i < args.length; i++){\n worldName.append(args[i]).append(\" \");\n }\n if(!WorldUtil.isValidWorld(worldName.toString().trim())){\n return null;\n }\n world = worldName.toString().trim();\n }\n return world;\n }\n}",
"public class MessageUtil {\n\n /**\n * Add Color to Messages\n *\n * @param str The String\n * @return Coloured String\n */\n public static String colorize(String str){\n return str.replaceAll(\"(?i)&([a-f0-9k-or])\", \"\\u00a7$1\");\n }\n\n public static String colorize(String str, Object... args){\n return colorize(String.format(str, args));\n }\n}",
"public class WorldUtil {\n\n public static String configSafe(String worldName){\n return worldName.replace(\" \", \"_\");\n }\n\n /**\n * Checks if the selected world is a valid world.\n *\n * @param worldName The world name that will be checked.\n * @return True if the world does not return null.\n */\n public static boolean isValidWorld(String worldName){\n return Bukkit.getWorld(worldName) != null;\n }\n\n /**\n * get a list of world names that begin with partial. If partial is\n * empty, all worlds are returned.\n * @param partial String to compare against.\n * @return List of world names.\n */\n public static List<String> getMatchingWorlds(String partial) {\n return Bukkit.getWorlds().stream()\n .map(World::getName)\n .filter(world -> world.toLowerCase().startsWith(partial.toLowerCase()))\n .collect(Collectors.toList());\n }\n}"
] | import com.endercrest.voidspawn.ConfigManager;
import com.endercrest.voidspawn.DetectorManager;
import com.endercrest.voidspawn.VoidSpawn;
import com.endercrest.voidspawn.detectors.Detector;
import com.endercrest.voidspawn.utils.CommandUtil;
import com.endercrest.voidspawn.utils.MessageUtil;
import com.endercrest.voidspawn.utils.WorldUtil;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors; | package com.endercrest.voidspawn.commands;
public class DetectorCommand implements SubCommand {
@Override
public boolean onCommand(Player p, String[] args){
if(args.length == 1){
p.sendMessage(MessageUtil.colorize(VoidSpawn.prefix + "--- &6Available Detectors&f ---"));
for(Detector detector : DetectorManager.getInstance().getDetectors().values()){
String detectorSummary = String.format("&6%s &f- %s", detector.getName(), detector.getDescription());
p.sendMessage(MessageUtil.colorize(VoidSpawn.prefix + detectorSummary));
}
}else if(args.length >= 2) {
String world = CommandUtil.constructWorldFromArgs(args, 2, p.getWorld().getName());
if(world == null) {
p.sendMessage(MessageUtil.colorize(VoidSpawn.prefix + "&cThat is not a valid world!"));
return false;
}
if(DetectorManager.getInstance().getDetectors().containsKey(args[1].toLowerCase())){
Detector detector = DetectorManager.getInstance().getDetector(args[1].toLowerCase());
ConfigManager.getInstance().setDetector(detector.getName().toLowerCase(), world);
p.sendMessage(MessageUtil.colorize(VoidSpawn.prefix + "Updated detector!"));
}else{
p.sendMessage(MessageUtil.colorize(VoidSpawn.prefix + "&cThis is not a valid detector!"));
}
}
return false;
}
@Override
public String helpInfo(){
return "/vs detector (detector) [world] - Sets world detector";
}
@Override
public String permission(){
return "vs.admin.detector";
}
@Override
public List<String> getTabCompletion(Player player, String[] args) {
switch(args.length) {
case 1:
Set<String> detectors = DetectorManager.getInstance().getDetectors().keySet();
return detectors.stream()
.filter(detector -> detector.toLowerCase().startsWith(args[0].toLowerCase()))
.collect(Collectors.toList());
case 2: | return WorldUtil.getMatchingWorlds(args[1]); | 6 |
aelstad/keccakj | src/test/java/com/github/aelstad/keccakj/provider/TestKeccakjProvider.java | [
"public interface CipherProviderFactory {\n\tpublic CipherInterface getInstance(String transformation) throws NoSuchAlgorithmException, NoSuchPaddingException;\n}",
"public final class SHA3_224 extends AbstractKeccakMessageDigest {\n\tprivate final static byte DOMAIN_PADDING = 2;\n\tprivate final static int DOMMAIN_PADDING_LENGTH = 2;\n\n\tpublic SHA3_224() {\n\t\tsuper(\"SHA3-224\", 224*2, 224/8, DOMAIN_PADDING, DOMMAIN_PADDING_LENGTH);\n\t}\n\n}",
"public final class SHA3_256 extends AbstractKeccakMessageDigest {\n\tprivate final static byte DOMAIN_PADDING = 2;\n\tprivate final static int DOMMAIN_PADDING_LENGTH = 2;\n\n\tpublic SHA3_256() {\n\t\tsuper(\"SHA3-256\", 2*256, 256/8, DOMAIN_PADDING, DOMMAIN_PADDING_LENGTH);\n\t}\n\n}",
"public final class SHA3_384 extends AbstractKeccakMessageDigest {\n\tprivate final static byte DOMAIN_PADDING = 2;\n\tprivate final static int DOMMAIN_PADDING_LENGTH = 2;\n\n\tpublic SHA3_384() {\n\t\tsuper(\"SHA3-384\", 2*384, 384/8, DOMAIN_PADDING, DOMMAIN_PADDING_LENGTH);\n\t}\n}",
"public final class SHA3_512 extends AbstractKeccakMessageDigest {\n\n\tprivate final static byte DOMAIN_PADDING = 2;\n\tprivate final static int DOMMAIN_PADDING_LENGTH = 2;\n\n\tpublic SHA3_512() {\n\t\tsuper(\"SHA3-512\", 2*512, 512/8, DOMAIN_PADDING, DOMMAIN_PADDING_LENGTH);\n\t}\n\n}"
] | import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.Security;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.github.aelstad.keccakj.cipher.CipherProviderFactory;
import com.github.aelstad.keccakj.fips202.SHA3_224;
import com.github.aelstad.keccakj.fips202.SHA3_256;
import com.github.aelstad.keccakj.fips202.SHA3_384;
import com.github.aelstad.keccakj.fips202.SHA3_512; | /*
* Copyright 2014 Amund Elstad.
*
* 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.github.aelstad.keccakj.provider;
public class TestKeccakjProvider {
@BeforeClass
public static void beforeClass() {
Security.addProvider(new KeccakjProvider());
}
@Test
public void testSha3_224() throws Exception {
Assert.assertTrue(Constants.SHA3_224.equals("SHA3-224"));
Assert.assertTrue(MessageDigest.getInstance(Constants.SHA3_224, Constants.PROVIDER) instanceof SHA3_224);
}
@Test
public void testSha3_256() throws Exception {
Assert.assertTrue(Constants.SHA3_256.equals("SHA3-256"));
Assert.assertTrue(MessageDigest.getInstance(Constants.SHA3_256, Constants.PROVIDER) instanceof SHA3_256);
}
@Test
public void testSha3_384() throws Exception {
Assert.assertTrue(Constants.SHA3_384.equals("SHA3-384"));
Assert.assertTrue(MessageDigest.getInstance(Constants.SHA3_384, Constants.PROVIDER) instanceof SHA3_384);
}
@Test
public void testSha3_512() throws Exception {
Assert.assertTrue(Constants.SHA3_512.equals("SHA3-512"));
Assert.assertTrue(MessageDigest.getInstance(Constants.SHA3_512, Constants.PROVIDER) instanceof SHA3_512);
}
@Test
public void testKeccackRnd128() throws Exception {
Assert.assertNotNull(SecureRandom.getInstance(Constants.KECCAK_RND128, Constants.PROVIDER));
}
@Test
public void testKeccackRnd256() throws Exception {
Assert.assertNotNull(SecureRandom.getInstance(Constants.KECCAK_RND256, Constants.PROVIDER));
byte[] buf = new byte[1024];
SecureRandom.getInstance(Constants.KECCAK_RND256, Constants.PROVIDER).nextBytes(buf);
}
@Test
public void testShake128StreamCipher() throws Exception { | CipherProviderFactory cpf = (CipherProviderFactory) Security.getProvider(Constants.PROVIDER); | 0 |
flapdoodle-oss/de.flapdoodle.embed.process | src/main/java/de/flapdoodle/embed/process/runtime/Processes.java | [
"@Value.Immutable\npublic interface SupportConfig {\n\n\tString name();\n\n\tString supportUrl();\n\n\tBiFunction<Class<?>, Exception, String> messageOnException();\n\n\tstatic SupportConfig generic() {\n\t\treturn builder()\n\t\t\t\t.name(\"generic\")\n\t\t\t\t.supportUrl(\"https://github.com/flapdoodle-oss/de.flapdoodle.embed.process\")\n\t\t\t\t.messageOnException((clazz,ex) -> null)\n\t\t\t\t.build();\n\t}\n\n\tstatic ImmutableSupportConfig.Builder builder() {\n\t\treturn ImmutableSupportConfig.builder();\n\t}\n}",
"@Immutable\npublic interface ProcessConfig {\n\n\tList<String> commandLine();\n\n\tStreamProcessor output();\n\n\t@Default\n\tdefault StreamProcessor error() {\n\t\treturn output();\n\t}\n\n\tpublic static Builder builder() {\n\t\treturn ImmutableProcessConfig.builder();\n\t}\n}",
"public class LogWatchStreamProcessor implements StreamProcessor {\n\n\t//private final Reader _reader;\n\tprivate final StringBuilder output = new StringBuilder();\n\tprivate final String success;\n\tprivate final Set<String> failures;\n\n\tprivate boolean initWithSuccess = false;\n\tprivate String failureFound = null;\n\n\tprivate final StreamProcessor destination;\n\n\tpublic LogWatchStreamProcessor(String success, Set<String> failures, StreamProcessor destination) {\n\t\tthis.success = success;\n\t\tthis.failures = new HashSet<>(failures);\n\t\tthis.destination = destination;\n\t}\n\n\t@Override\n\tpublic void process(String block) {\n\t\tdestination.process(block);\n\n\t\toutput.append((CharSequence) block);\n\n\t\tif (output.indexOf(success) != -1) {\n\t\t\tgotResult(true,null);\n\t\t} else {\n\t\t\tfor (String failure : failures) {\n\t\t\t\tint failureIndex = output.indexOf(failure);\n\t\t\t\tif (failureIndex != -1) {\n\t\t\t\t\tgotResult(false,output.substring(failureIndex));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onProcessed() {\n\t\tgotResult(false,\"<EOF>\");\n\t}\n\n\tprivate synchronized void gotResult(boolean success, String message) {\n\t\tthis.initWithSuccess=success;\n\t\tfailureFound=message;\n\t\tnotify();\n\t}\n\n\tpublic synchronized void waitForResult(long timeout) {\n\t\ttry {\n\t\t\twait(timeout);\n\t\t} catch (InterruptedException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic boolean isInitWithSuccess() {\n\t\treturn initWithSuccess;\n\t}\n\t\n\tpublic String getFailureFound() {\n\t\treturn failureFound;\n\t}\n\t\n\tpublic String getOutput() {\n\t\treturn output.toString();\n\t}\n\n\n}",
"public class Processors {\n\n\tprivate Processors() {\n\t\tthrow new IllegalAccessError(\"singleton\");\n\t}\n\n\tpublic static StreamProcessor console() {\n\t\treturn new ConsoleOutputStreamProcessor();\n\t}\n\t\n\tpublic static StreamProcessor silent() {\n\t\treturn new NullProcessor();\n\t}\n\n\tpublic static StreamProcessor named(String name, StreamProcessor destination) {\n\t\treturn new NamedOutputStreamProcessor(name, destination);\n\t}\n\n\tpublic static StreamProcessor namedConsole(String name) {\n\t\treturn named(name, console());\n\t}\n\n\tpublic static StreamProcessor logTo(Logger logger, Slf4jLevel level) {\n\t\treturn new Slf4jStreamProcessor(logger, level);\n\t}\n\n\tpublic static ReaderProcessor connect(Reader reader, StreamProcessor processor) {\n\t\treturn new ReaderProcessor(reader, processor);\n\t}\n}",
"public interface StreamProcessor {\n\tvoid process(String block);\n\n\tvoid onProcessed();\n}",
"public class StreamToLineProcessor implements StreamProcessor {\n\n\tprivate final StreamProcessor destination;\n\tprivate final StringBuilder buffer = new StringBuilder();\n\n\tpublic StreamToLineProcessor(StreamProcessor destination) {\n\t\tthis.destination = destination;\n\t}\n\n\t@Override\n\tpublic void process(String block) {\n\t\tint newLineEnd = block.indexOf('\\n');\n\t\tif (newLineEnd == -1) {\n\t\t\tbuffer.append(block);\n\t\t} else {\n\t\t\tbuffer.append(block.substring(0, newLineEnd + 1));\n\t\t\tdestination.process(getAndClearBuffer());\n\t\t\tdo {\n\t\t\t\tint lastEnd = newLineEnd;\n\t\t\t\tnewLineEnd = block.indexOf('\\n', newLineEnd + 1);\n\t\t\t\tif (newLineEnd != -1) {\n\t\t\t\t\tdestination.process(block.substring(lastEnd + 1, newLineEnd + 1));\n\t\t\t\t} else {\n\t\t\t\t\tbuffer.append(block.substring(lastEnd + 1));\n\t\t\t\t}\n\t\t\t} while (newLineEnd != -1);\n\t\t}\n\t}\n\n\tprivate String getAndClearBuffer() {\n\t\tString ret = buffer.toString();\n\t\tbuffer.setLength(0);\n\t\treturn ret;\n\t}\n\n\t@Override\n\tpublic void onProcessed() {\n\t\tif (buffer.length() > 0) {\n\t\t\tdestination.process(getAndClearBuffer());\n\t\t}\n\t\tdestination.onProcessed();\n\t}\n\n\tpublic static StreamProcessor wrap(StreamProcessor destination) {\n\t\treturn new StreamToLineProcessor(destination);\n\t}\n}"
] | import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinNT;
import de.flapdoodle.embed.process.config.SupportConfig;
import de.flapdoodle.embed.process.config.process.ProcessConfig;
import de.flapdoodle.embed.process.io.LogWatchStreamProcessor;
import de.flapdoodle.embed.process.io.Processors;
import de.flapdoodle.embed.process.io.StreamProcessor;
import de.flapdoodle.embed.process.io.StreamToLineProcessor;
import de.flapdoodle.os.OS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.lang.model.SourceVersion;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashSet;
import static java.util.Arrays.asList; | /**
* Copyright (C) 2011
* Michael Mosmann <[email protected]>
* Martin Jöhren <[email protected]>
*
* with contributions from
* konstantin-ba@github,
Archimedes Trajano (trajano@github),
Kevin D. Keck (kdkeck@github),
Ben McCann (benmccann@github)
*
* 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 de.flapdoodle.embed.process.runtime;
public abstract class Processes {
private static final Logger logger = LoggerFactory.getLogger(ProcessControl.class);
private static final PidHelper PID_HELPER;
static {
// Comparing with the string value to avoid a strong dependency on JDK 9
String sourceVersion = SourceVersion.latest().toString();
switch (sourceVersion) {
case "RELEASE_9":
PID_HELPER = PidHelper.JDK_9;
break;
case "RELEASE_10":
case "RELEASE_11":
case "RELEASE_12":
case "RELEASE_13":
case "RELEASE_14":
case "RELEASE_15":
case "RELEASE_16":
case "RELEASE_17":
PID_HELPER = PidHelper.JDK_11;
break;
default:
PID_HELPER = PidHelper.LEGACY;
}
}
private Processes() {
// no instance
}
public static Long processId(Process process) {
return PID_HELPER.getPid(process);
}
private static Long unixLikeProcessId(Process process) {
Class<?> clazz = process.getClass();
try {
if (clazz.getName().equals("java.lang.UNIXProcess")) {
Field pidField = clazz.getDeclaredField("pid");
pidField.setAccessible(true);
Object value = pidField.get(process);
if (value instanceof Integer) {
logger.debug("Detected pid: {}", value);
return ((Integer) value).longValue();
}
}
} catch (SecurityException | IllegalAccessException | IllegalArgumentException | NoSuchFieldException sx) {
sx.printStackTrace();
}
return null;
}
/**
* @see "http://www.golesny.de/p/code/javagetpid"
*
* @return windows process id
*/
private static Long windowsProcessId(Process process) {
if (process.getClass().getName().equals("java.lang.Win32Process")
|| process.getClass().getName().equals("java.lang.ProcessImpl")) {
/* determine the pid on windows plattforms */
try {
Field f = process.getClass().getDeclaredField("handle");
f.setAccessible(true);
long handl = f.getLong(process);
Kernel32 kernel = Kernel32.INSTANCE;
WinNT.HANDLE handle = new WinNT.HANDLE();
handle.setPointer(Pointer.createConstant(handl));
int ret = kernel.GetProcessId(handle);
logger.debug("Detected pid: {}", ret);
return (long) ret;
} catch (Throwable e) {
e.printStackTrace();
}
}
return null;
}
public static boolean killProcess(SupportConfig support,de.flapdoodle.os.Platform platform, StreamProcessor output, long pid) {
return isUnixLike(platform) && ProcessControl.executeCommandLine(support, "[kill process]",
ProcessConfig.builder().commandLine(asList("kill", "-2", "" + pid)).output(output).build());
}
public static boolean termProcess(SupportConfig support,de.flapdoodle.os.Platform platform, StreamProcessor output, long pid) {
return isUnixLike(platform) && ProcessControl.executeCommandLine(support, "[term process]",
ProcessConfig.builder().commandLine(asList("kill", "" + pid)).output(output).build());
}
public static boolean tryKillProcess(SupportConfig support,de.flapdoodle.os.Platform platform, StreamProcessor output, long pid) {
return platform.operatingSystem() == OS.Windows && ProcessControl.executeCommandLine(support, "[taskkill process]",
ProcessConfig.builder().commandLine(asList("taskkill", "/F", "/pid", "" + pid)).output(output).build());
}
private static boolean isUnixLike(de.flapdoodle.os.Platform platform) {
return platform.operatingSystem() != OS.Windows;
}
public static boolean isProcessRunning(de.flapdoodle.os.Platform platform, long pid) {
try {
final Process pidof;
if (isUnixLike(platform)) {
pidof = Runtime.getRuntime().exec(
new String[] { "kill", "-0", "" + pid });
return pidof.waitFor() == 0;
} else {
// windows
// process might be in either NOT RESPONDING due to
// firewall blocking, or could be RUNNING
final String[] cmd = { "tasklist.exe",
"/FI", "PID eq " + pid ,"/FO", "CSV" };
logger.trace("Command: {}", asList(cmd));
ProcessBuilder processBuilder = ProcessControl
.newProcessBuilder(asList(cmd), true);
Process process = processBuilder.start();
// look for the PID in the output, pass it in for 'success' state
LogWatchStreamProcessor logWatch = new LogWatchStreamProcessor(""+pid, | new HashSet<>(), StreamToLineProcessor.wrap(Processors.silent())); | 5 |
pdsoftplan/zap-maven-plugin | zap-maven-plugin-core/src/main/java/br/com/softplan/security/zap/maven/SeleniumAnalyzeMojo.java | [
"public class ZapClient {\n\n\tprivate String apiKey;\n\tprivate ClientApi api;\n\t\n\tprivate AuthenticationHandler authenticationHandler;\n\tprivate SessionManager sessionManager;\n\t\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(ZapClient.class);\n\n\t/**\n\t * Constructs the client providing information about ZAP.\n\t * \n\t * @param zapInfo required information about the ZAP instance.\n\t */\n\tpublic ZapClient(ZapInfo zapInfo) {\n\t\tthis.apiKey = zapInfo.getApiKey();\n\t\tthis.api = new ClientApi(zapInfo.getHost(), zapInfo.getPort());\n\t\tthis.sessionManager = new SessionManager();\n\t}\n\n\t/**\n\t * Constructs the client providing information about ZAP and the authentication to be done.\n\t * \n\t * @param zapInfo required information about the ZAP instance.\n\t * @param authenticationInfo information about the authentication to be done.\n\t */\n\tpublic ZapClient(ZapInfo zapInfo, AuthenticationInfo authenticationInfo) {\n\t\tthis(zapInfo);\n\t\tthis.authenticationHandler = AuthenticationHandlerFactory.makeHandler(api, zapInfo, authenticationInfo);\n\t}\n\n\tpublic ZapReport analyze(AnalysisInfo analysisInfo) {\n\t\tif (analysisInfo.shouldStartNewSession()) {\n\t\t\tsessionManager.createNewSession(api, apiKey);\n\t\t}\n\n\t\tZapHelper.includeInContext(api, apiKey, analysisInfo);\n\t\tZapHelper.setTechnologiesInContext(api, apiKey, analysisInfo);\n\t\t\n\t\tif (authenticationHandler != null) {\n\t\t\tauthenticationHandler.handleAuthentication(analysisInfo.getTargetUrl());\n\t\t}\n\n\t\tLOGGER.info(\"--- Starting analysis ---\");\n\t\t\n\t\tAnalyzer analyzer = AnalyzerFactory.makeAnalyzer(apiKey, api, analysisInfo);\n\t\tZapReport zapReport = analyzer.analyze(analysisInfo);\n\t\t\n\t\tLOGGER.info(\"--- Finished analysis ---\\n\");\n\t\t\n\t\treturn zapReport;\n\t}\n\n}",
"public class AnalysisInfo {\n\n\tprivate static final long DEFAULT_ANALYSIS_TIMEOUT_IN_MINUTES = 480;\n\tprivate static final AnalysisType DEFAULT_ANALYSIS_TYPE = AnalysisType.WITH_SPIDER;\n\tprivate static final boolean DEFAULT_SHOULD_START_NEW_SESSION = true;\n\t\n\tprivate String targetUrl;\n\tprivate String spiderStartingPointUrl;\n\tprivate String activeScanStartingPointUrl;\n\tprivate String[] context;\n\tprivate String[] technologies;\n\tprivate String technologiesSeparatedByComma;\n\t\n\tprivate long analysisTimeoutInMinutes;\n\tprivate AnalysisType analysisType;\n\tprivate boolean shouldStartNewSession;\n\t\n\tpublic static Builder builder() {\n\t\treturn new Builder();\n\t}\n\t\n\tpublic String getTargetUrl() {\n\t\treturn targetUrl;\n\t}\n\t\n\tpublic String getSpiderStartingPointUrl() {\n\t\tif (spiderStartingPointUrl != null) {\n\t\t\treturn spiderStartingPointUrl;\n\t\t}\n\t\treturn targetUrl;\n\t}\n\n\tpublic String getActiveScanStartingPointUrl() {\n\t\tif (activeScanStartingPointUrl != null) {\n\t\t\treturn activeScanStartingPointUrl;\n\t\t}\n\t\treturn targetUrl;\n\t}\n\t\n\tpublic String[] getContext() {\n\t\tif (context != null && context.length > 0) {\n\t\t\treturn context;\n\t\t}\n\t\treturn new String[]{targetUrl};\n\t}\n\n\tpublic String[] getTechnologies() {\n\t\treturn technologies;\n\t}\n\t\n\tpublic String getTechnologiesSeparatedByComma() {\n\t\treturn technologiesSeparatedByComma;\n\t}\n\t\n\tpublic long getAnalysisTimeoutInMillis() {\n\t\treturn TimeUnit.MILLISECONDS.convert(analysisTimeoutInMinutes, TimeUnit.MINUTES);\n\t}\n\t\n\tpublic long getAnalysisTimeoutInMinutes() {\n\t\treturn analysisTimeoutInMinutes;\n\t}\n\n\tpublic AnalysisType getAnalysisType() {\n\t\treturn analysisType;\n\t}\n\t\n\tpublic boolean shouldStartNewSession() {\n\t\treturn shouldStartNewSession;\n\t}\n\t\n\tpublic static class Builder {\n\t\t\n\t\tprivate String targetUrl;\n\t\tprivate String spiderStartingPointUrl;\n\t\tprivate String activeScanStartingPointUrl;\n\t\tprivate String[] context;\n\t\tprivate String[] technologies;\n\t\tprivate String technologiesSeparatedByComma;\n\t\tprivate long analysisTimeoutInMinutes = DEFAULT_ANALYSIS_TIMEOUT_IN_MINUTES;\n\t\tprivate AnalysisType analysisType = DEFAULT_ANALYSIS_TYPE;\n\t\tprivate boolean shouldStartNewSession = DEFAULT_SHOULD_START_NEW_SESSION;\n\t\t\n\t\t/**\n\t\t * Sets the target URL.\n\t\t * \n\t\t * @param targetUrl URL of the application that will be analyzed (e.g. {@code http://myapp.com}).\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder targetUrl(String targetUrl) {\n\t\t\tthis.targetUrl = targetUrl;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the starting point URL for the Spider (and AJAX Spider, in case it runs).\n\t\t * \n\t\t * @param spiderStartingPointUrl the starting point URL for the Spiders (default: {@code targetUrl}). \n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder spiderStartingPointUrl(String spiderStartingPointUrl) {\n\t\t\tthis.spiderStartingPointUrl = spiderStartingPointUrl;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the starting point URL for the Active Scan.\n\t\t * \n\t\t * @param activeScanStartingPointUrl the starting point URL for the Active Scan (default: {@code targetUrl}). \n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder activeScanStartingPointUrl(String activeScanStartingPointUrl) {\n\t\t\tthis.activeScanStartingPointUrl = activeScanStartingPointUrl;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the URLs to be set as the context of ZAP.\n\t\t * \n\t\t * @param context an array of URLs (absolute or relative) to be set on ZAP's context.\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder context(String... context) {\n\t\t\tthis.context = context;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the technologies that will be considered during the scan.\n\t\t * The default behavior is to consider all the technologies.\n\t\t * \n\t\t * @param technologies an array of technologies to be considered during the scan.\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder technologies(String... technologies) {\n\t\t\tthis.technologies = technologies;\n\t\t\tif (technologies != null) {\n\t\t\t\ttechnologiesSeparatedByComma = StringUtils.join(technologies, \",\"); \n\t\t\t} else {\n\t\t\t\ttechnologiesSeparatedByComma = null;\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the analysis timeout in minutes.\n\t\t * \n\t\t * @param analysisTimeoutInMinutes the timeout in minutes for the analysis (default: {@code 480}). \n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder analysisTimeoutInMinutes(long analysisTimeoutInMinutes) {\n\t\t\tthis.analysisTimeoutInMinutes = analysisTimeoutInMinutes;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the analysis type.\n\t\t * \n\t\t * @param analysisType the analysis type indicating which analysis should be done:\n\t\t * <ul>\n\t\t * <li><b>WITH_SPIDER</b>: default analysis, which runs the Spider before runnning the Active Scan.</li>\n\t \t * <li><b>WITH_AJAX_SPIDER</b>: after running the default Spider, the AJAX Spider is executed before the Active Scan.\n\t \t * This is useful for applications that rely on AJAX.</li>\n\t \t * <li><b>ACTIVE_SCAN_ONLY</b>: no Spider is executed before the Active Scan. This is useful in case the application\n\t \t * navigation is done via proxy (proxied Selenium tests, for instance).</li>\n\t \t * <li><b>SPIDER_ONLY</b>: </li> no Active Scan is executed after the Spider. This is useful when on wants to run the\n\t \t * passive scan only.\n\t \t * <li><b>SPIDER_AND_AJAX_SPIDER_ONLY</b>: Just like the previous, but including the AJAX Spider.</li>\n\t \t * </ul> \n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder analysisType(AnalysisType analysisType) {\n\t\t\tthis.analysisType = analysisType;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the analysis type.\n\t\t * \n\t\t * @param analysisType the analysis type as a string (case-insensitive) indicating which analysis should be done:\n\t\t * <ul>\n\t\t * <li><b>WITH_SPIDER</b>: default analysis, which runs the Spider before runnning the Active Scan.</li>\n\t \t * <li><b>WITH_AJAX_SPIDER</b>: after running the default Spider, the AJAX Spider is executed before the Active Scan.\n\t \t * This is useful for applications that rely on AJAX.</li>\n\t \t * <li><b>ACTIVE_SCAN_ONLY</b>: no Spider is executed before the Active Scan. This is useful in case the application\n\t \t * navigation is done via proxy (proxied Selenium tests, for instance).</li>\n\t \t * <li><b>SPIDER_ONLY</b>: </li> no Active Scan is executed after the Spider. This is useful when on wants to run the\n\t \t * passive scan only.\n\t \t * <li><b>SPIDER_AND_AJAX_SPIDER_ONLY</b>: Just like the previous, but including the AJAX Spider.</li>\n\t \t * </ul> \n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder analysisType(String analysisType) {\n\t\t\tif (analysisType != null) {\n\t\t\t\tthis.analysisType = AnalysisType.valueOf(analysisType.toUpperCase());\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets whether a new session should be started on ZAP before the analysis.\n\t\t * \n\t\t * @param shouldStartNewSession {@code true} if a new session on ZAP should be started before the analysis,\n\t\t * {@code false} otherwise (default: {@code true}). \n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder shouldStartNewSession(boolean shouldStartNewSession) {\n\t\t\tthis.shouldStartNewSession = shouldStartNewSession;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Builds a {@link AnalysisInfo} instance based on the builder parameters.\n\t\t * \n\t\t * @return a {@link AnalysisInfo} instance.\n\t\t */\n\t\tpublic AnalysisInfo build() {\n\t\t\treturn new AnalysisInfo(this);\n\t\t}\n\t\t\n\t}\n\t\n\tprivate AnalysisInfo(Builder builder) {\n\t\tthis.targetUrl = builder.targetUrl;\n\t\tthis.spiderStartingPointUrl = builder.spiderStartingPointUrl;\n\t\tthis.activeScanStartingPointUrl = builder.activeScanStartingPointUrl;\n\t\tthis.context = builder.context;\n\t\tthis.technologies = builder.technologies;\n\t\tthis.technologiesSeparatedByComma = builder.technologiesSeparatedByComma;\n\t\tthis.analysisTimeoutInMinutes = builder.analysisTimeoutInMinutes;\n\t\tthis.analysisType = builder.analysisType;\n\t\tthis.shouldStartNewSession = builder.shouldStartNewSession;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)\n\t\t\t\t.append(\"targetUrl\", targetUrl)\n\t\t\t\t.append(\"spiderStartingPointUrl\", spiderStartingPointUrl)\n\t\t\t\t.append(\"activeScanStartingPointUrl\", activeScanStartingPointUrl)\n\t\t\t\t.append(\"context\", Arrays.toString(context))\n\t\t\t\t.append(\"technologies\", Arrays.toString(technologies))\n\t\t\t\t.append(\"analysisTimeoutInMinutes\", analysisTimeoutInMinutes)\n\t\t\t\t.append(\"analysisType\", analysisType)\n\t\t\t\t.append(\"shouldStartNewSession\", shouldStartNewSession)\n\t\t\t\t.toString();\n\t}\n\t\n}",
"public enum AnalysisType {\n\t\n\tWITH_SPIDER, \n\tWITH_AJAX_SPIDER, \n\tACTIVE_SCAN_ONLY, \n\tSPIDER_ONLY, \n\tSPIDER_AND_AJAX_SPIDER_ONLY;\n\t\n}",
"public final class AuthenticationInfo {\n\n\tprivate static final String DEFAULT_USERNAME_PARAMETER = \"username\";\n\tprivate static final String DEFAULT_PASSWORD_PARAMETER = \"password\";\n\tprivate static final String DEFAULT_LOGIN_REQUEST_DATA = DEFAULT_USERNAME_PARAMETER + \"={%username%}&\" + DEFAULT_PASSWORD_PARAMETER + \"={%password%}\";\n\tprivate static final SeleniumDriver DEFAULT_SELENIUM_DRIVER = SeleniumDriver.FIREFOX;\n\t\n\tprivate AuthenticationType type;\n\tprivate String loginUrl;\n\tprivate String username;\n\tprivate String password;\n\tprivate String extraPostData;\n\tprivate String loggedInRegex;\n\tprivate String loggedOutRegex;\n\tprivate String[] excludeFromScan;\n\tprivate String[] protectedPages;\n\tprivate String protectedPagesSeparatedByComma;\n\tprivate String loginRequestData;\n\tprivate String usernameParameter;\n\tprivate String passwordParameter;\n\tprivate String[] httpSessionTokens;\n\tprivate SeleniumDriver seleniumDriver;\n\tprivate String hostname;\n\tprivate String realm;\n\tprivate int port;\n\n\tpublic static Builder builder() {\n\t\treturn new Builder();\n\t}\n\t\n\tpublic AuthenticationType getType() {\n\t\treturn type;\n\t}\n\n\tpublic String getLoginUrl() {\n\t\treturn loginUrl;\n\t}\n\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\t\n\tpublic String getExtraPostData() {\n\t\treturn extraPostData;\n\t}\n\t\n\tpublic String getFullLoginRequestData() {\n\t\tif (extraPostData != null) {\n\t\t\treturn loginRequestData + \"&\" + extraPostData; \t\t\t\n\t\t}\n\t\treturn loginRequestData;\n\t}\n\n\tpublic String getLoggedInRegex() {\n\t\treturn loggedInRegex;\n\t}\n\t\n\tpublic String getLoggedOutRegex() {\n\t\treturn loggedOutRegex;\n\t}\n\n\tpublic String[] getExcludeFromScan() {\n\t\treturn excludeFromScan;\n\t}\n\t\n\tpublic String[] getProtectedPages() {\n\t\treturn protectedPages;\n\t}\n\n\tpublic String getProtectedPagesSeparatedByComma() {\n\t\treturn protectedPagesSeparatedByComma;\n\t}\n\t\n\tpublic String getLoginRequestData() {\n\t\treturn loginRequestData;\n\t}\n\t\n\tpublic String getUsernameParameter() {\n\t\treturn usernameParameter;\n\t}\n\t\n\tpublic String getPasswordParameter() {\n\t\treturn passwordParameter;\n\t}\n\t\n\tpublic String[] getHttpSessionTokens() {\n\t\treturn httpSessionTokens;\n\t}\n\t\n\tpublic SeleniumDriver getSeleniumDriver() {\n\t\treturn seleniumDriver;\n\t}\n\t\n\tpublic String getHostname() {\n\t\treturn hostname;\n\t}\n\n\tpublic String getRealm() {\n\t\treturn realm;\n\t}\n\t\n\tpublic int getPort() {\n\t\treturn port;\n\t}\n\t\n\tpublic String getPortAsString() {\n\t\treturn String.valueOf(port);\n\t}\n\t\n\tpublic static class Builder {\n\t\t\n\t\tprivate AuthenticationType type;\n\t\tprivate String loginUrl;\n\t\tprivate String username;\n\t\tprivate String password;\n\t\tprivate String extraPostData;\n\t\tprivate String loggedInRegex;\n\t\tprivate String loggedOutRegex;\n\t\tprivate String[] excludeFromScan;\n\t\tprivate String[] protectedPages;\n\t\tprivate String protectedPagesSeparatedByComma;\n\t\tprivate String loginRequestData = DEFAULT_LOGIN_REQUEST_DATA;\n\t\tprivate String usernameParameter = DEFAULT_USERNAME_PARAMETER;\n\t\tprivate String passwordParameter = DEFAULT_PASSWORD_PARAMETER;\n\t\tprivate String[] httpSessionTokens;\n\t\tprivate SeleniumDriver seleniumDriver = DEFAULT_SELENIUM_DRIVER;\n\t\tprivate String hostname;\n\t\tprivate String realm;\n\t\tprivate int port;\n\t\t\n\t\t/**\n\t\t * Builds an {@code AuthenticationInfo} instance with the minimum information required for HTTP authentication.\n\t\t * \n\t\t * @param hostname the host name for HTTP authentication.\n\t\t * @param realm the realm for HTTP authentication.\n\t\t * @return the built {@code AuthenticationInfo} instance.\n\t\t */\n\t\tpublic AuthenticationInfo buildHttpAuthenticationInfo(String username, String password, String hostname, String realm) {\n\t\t\treturn type(AuthenticationType.HTTP)\n\t\t\t\t\t.username(username)\n\t\t\t\t\t.password(password)\n\t\t\t\t\t.hostname(hostname)\n\t\t\t\t\t.realm(realm)\n\t\t\t\t\t.build();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Builds an {@code AuthenticationInfo} instance with the minimum information required for form authentication.\n\t\t * \n\t\t * @param loginUrl the login URL (i.e. {@code http://myapp.com/login}).\n\t\t * @param username the username that will be authenticated.\n\t\t * @param password the user's password.\n\t\t * @return the built {@code AuthenticationInfo} instance.\n\t\t */\n\t\tpublic AuthenticationInfo buildFormAuthenticationInfo(String loginUrl, String username, String password) {\n\t\t\treturn type(AuthenticationType.FORM)\n\t\t\t\t\t.loginUrl(loginUrl)\n\t\t\t\t\t.username(username)\n\t\t\t\t\t.password(password)\n\t\t\t\t\t.build();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Builds an {@code AuthenticationInfo} instance with the minimum information required for CAS authentication.\n\t\t * <p>\n\t\t * The {@code protectedPages} parameter is needed so we can access them after the authentication and before ZAP's\n\t\t * analysis. This is required to avoid circular redirections during the scan, not supported by ZAP.\n\t\t * \n\t\t * @param loginUrl the login URL (i.e. {@code http://myapp.com/login}).\n\t\t * @param username the username that will be authenticated.\n\t\t * @param password the user's password.\n\t\t * @param protectedPages an array of URLs with at least one protected page for each context that will be analyzed.\n\t\t * @return the built {@code AuthenticationInfo} instance.\n\t\t */\n\t\tpublic AuthenticationInfo buildCasAuthenticationInfo(String loginUrl, String username, String password, String... protectedPages) {\n\t\t\treturn type(AuthenticationType.CAS)\n\t\t\t\t\t.loginUrl(loginUrl)\n\t\t\t\t\t.username(username)\n\t\t\t\t\t.password(password)\n\t\t\t\t\t.protectedPages(protectedPages)\n\t\t\t\t\t.build();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Builds an {@code AuthenticationInfo} instance with the minimum information required for Selenium authentication.\n\t\t * \n\t\t * @param loginUrl the login URL (i.e. {@code http://myapp.com/login}).\n\t\t * @param username the username that will be authenticated.\n\t\t * @param password the user's password.\n\t\t * @return the built {@code AuthenticationInfo} instance.\n\t\t */\n\t\tpublic AuthenticationInfo buildSeleniumAuthenticationInfo(String loginUrl, String username, String password) {\n\t\t\treturn type(AuthenticationType.SELENIUM)\n\t\t\t\t\t.loginUrl(loginUrl)\n\t\t\t\t\t.username(username)\n\t\t\t\t\t.password(password)\n\t\t\t\t\t.build();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the {@link AuthenticationType}.\n\t\t * \n\t\t * @param type the {@link AuthenticationType} ({@code HTTP}, {@code CAS}, {@code FORM} or {@code SELENIUM}).\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder type(AuthenticationType type) {\n\t\t\tthis.type = type;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the {@link AuthenticationType}.\n\t\t * \n\t\t * @param type the {@link AuthenticationType} as a string ({@code HTTP}, {@code CAS}, {@code FORM} or {@code SELENIUM}, case-insensitive).\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder type(String type) {\n\t\t\tif (type != null) {\n\t\t\t\tthis.type = AuthenticationType.valueOf(type.toUpperCase());\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the login URL. <b>This is a required parameter.</b>\n\t\t * \n\t\t * @param loginUrl the login URL (i.e. {@code http://myapp.com/login}).\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder loginUrl(String loginUrl) {\n\t\t\tthis.loginUrl = loginUrl;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the username. <b>This is a required parameter.</b>\n\t\t * \n\t\t * @param username the username that will be authenticated.\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder username(String username) {\n\t\t\tthis.username = username;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the password. <b>This is a required parameter.</b>\n\t\t * \n\t\t * @param password the user's password.\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder password(String password) {\n\t\t\tthis.password = password;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets any extra post data needed for the authentication.\n\t\t * \n\t\t * @param extraPostData extra post data that will be sent in the login request (i.e. {@code domain=someDomain¶m=value}).\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder extraPostData(String extraPostData) {\n\t\t\tthis.extraPostData = extraPostData;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the logged in regex, thus enabling reauthentication.\n\t\t * <p>\n\t\t * This regex should match logged in response messages, so ZAP is able reauthenticate\n\t\t * in case it logs itself out during the scan.\n\t\t * <p>\n\t\t * <b>There is no need to set both {@code loggedInRegex} and {@code loggedOutRegex} options, only one is enough.</b>\n\t\t * \n\t\t * @param loggedInRegex the regex that matches logged in response messages.\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder loggedInRegex(String loggedInRegex) {\n\t\t\tthis.loggedInRegex = loggedInRegex;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the logged out regex, thus enabling reauthentication.\n\t\t * <p>\n\t\t * This regex should match logged in response messages, so ZAP is able reauthenticate\n\t\t * in case it logs itself out during the scan.\n\t\t * <p>\n\t\t * <b>There is no need to set both {@code loggedInRegex} and {@code loggedOutRegex} options, only one is enough.</b>\n\t\t * \n\t\t * @param loggedOutRegex the regex that matches logged out response messages.\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder loggedOutRegex(String loggedOutRegex) {\n\t\t\tthis.loggedOutRegex = loggedOutRegex;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the URLs that will not be scanned.\n\t\t * \n\t\t * @param excludeFromScan an array of URLs to be excluded from the scan.\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder excludeFromScan(String... excludeFromScan) {\n\t\t\tthis.excludeFromScan = excludeFromScan;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * <b>This is a required parameter for CAS authentication.</b> \n\t\t * <p>\n\t\t * For CAS authentication, the login is done directly at the CAS server. So, when accessing the app\n\t\t * for the first time, the user will be redirected to the CAS server, which will redirect the user back to the app\n\t\t * since the user is authenticated. ZAP doesn't support circular redirection, thus it can't handle this process.\n\t\t * <p>\n\t\t * The URLs defined here will be accessed once after the authentication and before the scan, triggering the\n\t\t * circular redirections and avoiding them to happen during the analysis.\n\t\t * \n\t\t * @param protectedPages an array of URLs with at least one protected page for each context that will be analyzed.\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder protectedPages(String... protectedPages) {\n\t\t\tthis.protectedPages = protectedPages;\n\t\t\tif (protectedPages != null) {\n\t\t\t\tprotectedPagesSeparatedByComma = StringUtils.join(protectedPages, \",\"); \n\t\t\t} else {\n\t\t\t\tprotectedPagesSeparatedByComma = null;\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the login request data used for form authentication.\n\t\t * \n\t\t * @param loginRequestData the login request data for form based authentication \n\t\t * (default: <code>username={%username%}&password={%password%}</code>).\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder loginRequestData(String loginRequestData) {\n\t\t\tif (loginRequestData != null) {\n\t\t\t\tthis.loginRequestData = loginRequestData;\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Builds the login request data based on the {@code usernameParameter} \n\t\t * and {@code passwordParameter} current values.\n\t\t * \n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder loginRequestData() {\n\t\t\tthis.loginRequestData = usernameParameter + \"={%username%}&\" + passwordParameter + \"={%password%}\";\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the username parameter name.\n\t\t * \n\t\t * @param usernameParameter the username parameter that holds the username (default: {@code username}).\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder usernameParameter(String usernameParameter) {\n\t\t\tthis.usernameParameter = usernameParameter;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the password parameter name.\n\t\t * \n\t\t * @param passwordParameter the password parameter that holds the password (default: {@code password}).\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder passwordParameter(String passwordParameter) {\n\t\t\tthis.passwordParameter = passwordParameter;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Includes additional HTTP session tokens to ZAP. \n\t\t * \n\t\t * @param httpSessionTokens the session tokens to be added to ZAP.\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder httpSessionTokens(String... httpSessionTokens) {\n\t\t\tif (httpSessionTokens != null) {\n\t\t\t\tthis.httpSessionTokens = httpSessionTokens;\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the Selenium web driver that will be used to perform authentication.\n\t\t * \n\t\t * @param seleniumDriver the Selenium web driver to be used during authentication. \n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder seleniumDriver(SeleniumDriver seleniumDriver) {\n\t\t\tthis.seleniumDriver = seleniumDriver;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the Selenium web driver that will be used to perform authentication.\n\t\t * \n\t\t * @param seleniumDriver the Selenium web driver as a string (case-insensitive) to be used during authentication. \n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder seleniumDriver(String seleniumDriver) {\n\t\t\tif (seleniumDriver != null) {\n\t\t\t\tthis.seleniumDriver = SeleniumDriver.valueOf(seleniumDriver.toUpperCase());\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the host name for HTTP authentication.\n\t\t * \n\t\t * @param hostname the host name for HTTP authentication. \n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder hostname(String hostname) {\n\t\t\tthis.hostname = hostname;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the realm for HTTP authentication.\n\t\t * \n\t\t * @param realm the realm for HTTP authentication. \n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder realm(String realm) {\n\t\t\tthis.realm = realm;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the port for HTTP authentication.\n\t\t * \n\t\t * @param port the port for HTTP authentication. \n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder port(int port) {\n\t\t\tthis.port = port;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Validates and builds an {@code AuthenticationInfo} instance based on the builder parameters.\n\t\t * \n\t\t * @return a {@code AuthenticationInfo} instance.\n\t\t */\n\t\tpublic AuthenticationInfo build() {\n\t\t\tAuthenticationInfo authenticationInfo = new AuthenticationInfo(this);\n\t\t\tAuthenticationInfoValidator.validate(authenticationInfo);\n\t\t\treturn authenticationInfo;\n\t\t}\n\t\t\n\t}\n\t\n\tprivate AuthenticationInfo(Builder builder) {\n\t\tthis.type = builder.type;\n\t\tthis.loginUrl = builder.loginUrl;\n\t\tthis.username = builder.username;\n\t\tthis.password = builder.password;\n\t\tthis.extraPostData = builder.extraPostData;\n\t\tthis.loggedInRegex = builder.loggedInRegex;\n\t\tthis.loggedOutRegex = builder.loggedOutRegex;\n\t\tthis.excludeFromScan = builder.excludeFromScan;\n\t\tthis.protectedPages = builder.protectedPages;\n\t\tthis.protectedPagesSeparatedByComma = builder.protectedPagesSeparatedByComma;\n\t\tthis.loginRequestData = builder.loginRequestData;\n\t\tthis.usernameParameter = builder.usernameParameter;\n\t\tthis.passwordParameter = builder.passwordParameter;\n\t\tthis.httpSessionTokens = builder.httpSessionTokens;\n\t\tthis.seleniumDriver = builder.seleniumDriver;\n\t\tthis.hostname = builder.hostname;\n\t\tthis.realm = builder.realm;\n\t\tthis.port = builder.port;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)\n\t\t\t\t.append(\"type\", type.name())\n\t\t\t\t.append(\"loginUrl\", loginUrl)\n\t\t\t\t.append(\"username\", username)\n\t\t\t\t.append(\"password\", password)\n\t\t\t\t.append(\"extraPostData\", extraPostData)\n\t\t\t\t.append(\"loggedInRegex\", loggedInRegex)\n\t\t\t\t.append(\"loggedOutRegex\", loggedOutRegex)\n\t\t\t\t.append(\"excludeFromScan\", excludeFromScan)\n\t\t\t\t.append(\"protectedPages\", protectedPages)\n\t\t\t\t.append(\"loginRequestData\", loginRequestData)\n\t\t\t\t.append(\"usernameParameter\", usernameParameter)\n\t\t\t\t.append(\"passwordParameter\", passwordParameter)\n\t\t\t\t.append(\"httpSessionTokens\", httpSessionTokens)\n\t\t\t\t.append(\"seleniumDriver\", seleniumDriver)\n\t\t\t\t.append(\"hostname\", hostname)\n\t\t\t\t.append(\"realm\", realm)\n\t\t\t\t.append(\"port\", port)\n\t\t\t\t.toString();\n\t}\n\n}",
"public class ZapReport {\n\t\n\tprivate byte[] htmlReport;\n\tprivate byte[] xmlReport;\n\t\n\tprivate List<String> spiderResults;\n\tprivate String htmlSpiderResults;\n\tprivate String xmlSpiderResults;\n\t\n\t/**\n\t * Creates a new {@code ZapReport} instance based on the ZAP reports and the Spider results.\n\t * \n\t * @param htmlReport byte representation of the HTML Report.\n\t * @param xmlReport byte representation of the XML Report.\n\t * @param spiderResults the list with the URLs visited by the Spider.\n\t */\n\tpublic ZapReport(byte[] htmlReport, byte[] xmlReport, List<String> spiderResults) {\n\t\tthis.htmlReport = htmlReport;\n\t\tthis.xmlReport = xmlReport;\n\t\tthis.spiderResults = spiderResults;\n\t\t\n\t\tbuildSpiderResultsReports(spiderResults);\n\t}\n\n\tprivate void buildSpiderResultsReports(List<String> spiderResults) {\n\t\tthis.htmlSpiderResults = SpiderResultsReportBuilder.buildHtmlReport(spiderResults);\n\t\tthis.xmlSpiderResults = SpiderResultsReportBuilder.buildXmlReport(spiderResults);\n\t}\n\t\n\tpublic String getHtmlReportAsString() {\n\t\treturn new String(this.htmlReport, StandardCharsets.UTF_8);\n\t}\n\t\n\tpublic byte[] getHtmlReport() {\n\t\treturn this.htmlReport;\n\t}\n\n\tpublic String getXmlReportAsString() {\n\t\treturn new String(this.xmlReport, StandardCharsets.UTF_8);\n\t}\n\t\n\tpublic byte[] getXmlReport() {\n\t\treturn this.xmlReport;\n\t}\n\t\n\tpublic List<String> getSpiderResults() {\n\t\treturn Collections.unmodifiableList(spiderResults);\n\t}\n\t\n\tpublic String getHtmlSpiderResultsAsString() {\n\t\treturn htmlSpiderResults;\n\t}\n\t\n\tpublic byte[] getHtmlSpiderResults() {\n\t\treturn htmlSpiderResults.getBytes(StandardCharsets.UTF_8);\n\t}\n\t\n\tpublic String getXmlSpiderResultsAsString() {\n\t\treturn xmlSpiderResults;\n\t}\n\t\n\tpublic byte[] getXmlSpiderResults() {\n\t\treturn xmlSpiderResults.getBytes();\n\t}\n\t\n}",
"public final class ZapInfo {\n\n\tprivate static final String DEFAULT_HOST = \"localhost\";\n\tprivate static final String DEFAULT_KEY = \"\";\n\tprivate static final Long DEFAULT_INITIALIZATION_TIMEOUT_IN_MILLIS = new Long(120000);\n\tprivate static final String DEFAULT_JVM_OPTIONS = \"-Xmx512m\";\n\tpublic static final String DEFAULT_OPTIONS = \"-daemon -config api.disablekey=true -config api.incerrordetails=true -config proxy.ip=0.0.0.0\";\n\t\n\tprivate String host;\n\tprivate Integer port;\n\tprivate String apiKey;\n\tprivate String path;\n\tprivate String jmvOptions;\n\tprivate String options;\n\tprivate Long initializationTimeoutInMillis;\n\tprivate boolean shouldRunWithDocker;\n\t\n\tpublic static Builder builder() {\n\t\treturn new Builder();\n\t}\n\t\n\tpublic String getApiKey() {\n\t\treturn apiKey;\n\t}\n\n\tpublic int getPort() {\n\t\treturn port;\n\t}\n\n\tpublic String getHost() {\n\t\treturn host;\n\t}\n\t\n\tpublic String getPath() {\n\t\treturn path;\n\t}\n\n\tpublic String getJmvOptions() {\n\t\treturn jmvOptions;\n\t}\n\t\n\tpublic String getOptions() {\n\t\treturn options;\n\t}\n\n\tpublic long getInitializationTimeoutInMillis() {\n\t\treturn initializationTimeoutInMillis;\n\t}\n\t\n\tpublic boolean shouldRunWithDocker() {\n\t\treturn shouldRunWithDocker;\n\t}\n\t\n\tpublic static class Builder {\n\t\t\n\t\tprivate String host = DEFAULT_HOST;\n\t\tprivate Integer port;\n\t\tprivate String apiKey = DEFAULT_KEY;\n\t\tprivate String path;\n\t\tprivate String jmvOptions = DEFAULT_JVM_OPTIONS;\n\t\tprivate String options = DEFAULT_OPTIONS;\n\t\tprivate Long initializationTimeoutInMillis = DEFAULT_INITIALIZATION_TIMEOUT_IN_MILLIS;\n\t\tprivate boolean shouldRunWithDocker; \n\t\t\n\t\t/**\n\t\t * Use this if ZAP is up and running (locally or in a remote machine). \n\t\t * \n\t\t * @param host the host where ZAP is running (e.g. {@code localhost}, {@code 172.23.45.13}).\n\t\t * @param port the port where ZAP is running (e.g. {@code 8080}).\n\t\t * @return the built {@link ZapInfo} instance.\n\t\t */\n\t\tpublic ZapInfo buildToUseRunningZap(String host, int port) {\n\t\t\treturn host(host).port(port).build();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Use this if ZAP is up and running (locally or in a remote machine). \n\t\t * \n\t\t * @param host the host where ZAP is running (e.g. {@code localhost}, {@code 172.23.45.13}).\n\t\t * @param port the port where ZAP is running (e.g. {@code 8080}).\n\t\t * @param apiKey the API key needed to use ZAP's API, if the key is enabled. It can be found at ZAP - Tools - Options - API.\n\t\t * @return the built {@link ZapInfo} instance.\n\t\t */\n\t\tpublic ZapInfo buildToUseRunningZap(String host, int port, String apiKey) {\n\t\t\treturn host(host).port(port).apiKey(apiKey).build();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Use this if ZAP is installed and you want ZAP to be started and stopped automatically.\n\t\t * <p>\n\t\t * <b>ZAP must be installed locally for this to work.</b>\n\t\t * \n\t\t * @param port the port where ZAP will run (e.g. {@code 8080}).\n\t\t * @param path the path where ZAP is installed (e.g. {@code C:\\Program Files (x86)\\OWASP\\Zed Attack Proxy}).\n\t\t * @return the built {@link ZapInfo} instance.\n\t\t */\n\t\tpublic ZapInfo buildToRunZap(int port, String path) {\n\t\t\treturn port(port).path(path).build();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Use this if ZAP is installed and you want ZAP to be started and stopped automatically.\n\t\t * <p>\n\t\t * <b>ZAP must be installed locally for this to work.</b>\n\t\t * \n\t\t * @param port the port where ZAP will run (e.g. {@code 8080}).\n\t\t * @param path the path where ZAP is installed (e.g. {@code C:\\Program Files (x86)\\OWASP\\Zed Attack Proxy}).\n\t\t * @param options the options that will be used to start ZAP. This is an optional parameter, the default options used are:\n\t\t * {@code -daemon -config api.disablekey=true -config api.incerrordetails=true -config proxy.ip=0.0.0.0}\n\t\t * @return the built {@link ZapInfo} instance.\n\t\t */\n\t\tpublic ZapInfo buildToRunZap(int port, String path, String options) {\n\t\t\treturn port(port).path(path).options(options).build();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Use this if ZAP is installed and you want ZAP to be started and stopped automatically.\n\t\t * <p>\n\t\t * <b>ZAP must be installed locally for this to work.</b>\n\t\t * \n\t\t * @param port the port where ZAP will run (e.g. {@code 8080}).\n\t\t * @param path the path where ZAP is installed (e.g. {@code C:\\Program Files (x86)\\OWASP\\Zed Attack Proxy}).\n\t\t * @param options the options that will be used to start ZAP. This is an optional parameter, the default options used are:\n\t\t * {@code -daemon -config api.disablekey=true -config api.incerrordetails=true -config proxy.ip=0.0.0.0}\n\t\t * @param apiKey the API key needed to use ZAP's API, if the key is enabled. It can be found at ZAP - Tools - Options - API.\n\t\t * @return the built {@link ZapInfo} instance.\n\t\t */\n\t\tpublic ZapInfo buildToRunZap(int port, String path, String options, String apiKey) {\n\t\t\treturn port(port).path(path).options(options).apiKey(apiKey).build();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Use this if Docker is installed and you want to use ZAP from its Docker image.\n\t\t * <p>\n\t\t * <b>Docker must be installed locally for this to work.</b>\n\t\t * \n\t\t * @param port the port where ZAP will run (e.g. {@code 8080}).\n\t\t * @return the built {@link ZapInfo} instance.\n\t\t */\n\t\tpublic ZapInfo buildToRunZapWithDocker(int port) {\n\t\t\treturn shouldRunWithDocker(true).port(port).build();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Use this if Docker is installed and you want to use ZAP from its Docker image.\n\t\t * <p>\n\t\t * <b>Docker must be installed locally for this to work.</b>\n\t\t * \n\t\t * @param port the port where ZAP will run (e.g. {@code 8080}).\n\t\t * @param options the options that will be used to start ZAP. This is an optional parameter, the default options used are:\n\t\t * {@code -daemon -config api.disablekey=true -config api.incerrordetails=true -config proxy.ip=0.0.0.0}\n\t\t * @return the built {@link ZapInfo} instance.\n\t\t */\n\t\tpublic ZapInfo buildToRunZapWithDocker(int port, String options) {\n\t\t\treturn shouldRunWithDocker(true).port(port).options(options).build();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Use this if Docker is installed and you want to use ZAP from its Docker image.\n\t\t * <p>\n\t\t * <b>Docker must be installed locally for this to work.</b>\n\t\t * \n\t\t * @param port the port where ZAP will run (e.g. {@code 8080}).\n\t\t * @param options the options that will be used to start ZAP. This is an optional parameter, the default options used are:\n\t\t * {@code -daemon -config api.disablekey=true -config api.incerrordetails=true -config proxy.ip=0.0.0.0}\n\t\t * @param apiKey the API key needed to use ZAP's API, if the key is enabled. It can be found at ZAP - Tools - Options - API.\n\t\t * @return the built {@link ZapInfo} instance.\n\t\t */\n\t\tpublic ZapInfo buildToRunZapWithDocker(int port, String options, String apiKey) {\n\t\t\treturn shouldRunWithDocker(true).port(port).options(options).apiKey(apiKey).build();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the host where ZAP is running. Don't call this if you want ZAP to be started automatically.\n\t\t * \n\t\t * @param host the host where ZAP is running (e.g. {@code localhost}, {@code 172.23.45.13}).\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder host(String host) {\n\t\t\tif (host != null) {\n\t\t\t\tthis.host = host;\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Either sets the port where ZAP is running or the port where ZAP will run, if ZAP is to be started automatically.\n\t\t * <p>\n\t\t * If the {@code host} was set, then the {@code port} represents where ZAP is currently running on the host.\n\t\t * Otherwise, it represents the {@code port} where ZAP will run (locally or in a Docker image).\n\t\t * \n\t\t * @param port the port where ZAP is running or where ZAP will run (e.g. {@code 8080}).\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder port(int port) {\n\t\t\tthis.port = port;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the API key needed to access ZAP's API, in case the key is enabled (it is by default).\n\t\t * \n\t\t * @param apiKey the API key needed to use ZAP's API, if the key is enabled. It can be found at ZAP - Tools - Options - API.\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder apiKey(String apiKey) {\n\t\t\tif (apiKey != null) {\n\t\t\t\tthis.apiKey = apiKey;\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the path where ZAP is installed.\n\t\t * <p>\n\t\t * This should be used when ZAP is installed locally, so the API is able to automatically start ZAP.\n\t\t * \n\t\t * @param path the path where ZAP is installed (e.g. {@code C:\\Program Files (x86)\\OWASP\\Zed Attack Proxy}).\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder path(String path) {\n\t\t\tthis.path = path;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the JVM options used to run ZAP.\n\t\t * <p>\n\t\t * This should be used when ZAP is installed locally and it is automatically started and stopped.\n\t\t * \n\t\t * @param jmvOptions the JVM options used to start ZAP.\n\t\t * @return this {@code Builder} instance.\n\t\t * @see #path(String)\n\t\t */\n\t\tpublic Builder jmvOptions(String jmvOptions) {\n\t\t\tthis.jmvOptions = jmvOptions;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the options used to start ZAP.\n\t\t * <p>\n\t\t * This should be used to overwrite the default options used to start ZAP (locally or in a Docker image). \n\t\t * \n\t\t * @param options the options that will be used to start ZAP. This is an optional parameter, the default options used are:\n\t\t * {@code -daemon -config api.disablekey=true -config api.incerrordetails=true -config proxy.ip=0.0.0.0}\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder options(String options) {\n\t\t\tif (options != null) {\n\t\t\t\tthis.options = options;\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Sets the timeout in milliseconds for ZAP's initialization, if ZAP is to be started automatically.\n\t\t * The default value is {@code 120000}.\n\t\t * \n\t\t * @param initializationTimeoutInMillis the timeout in milliseconds for ZAP's initialization.\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder initializationTimeoutInMillis(Long initializationTimeoutInMillis) {\n\t\t\tif (initializationTimeoutInMillis != null) {\n\t\t\t\tthis.initializationTimeoutInMillis = initializationTimeoutInMillis;\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Use this to indicate that ZAP should be started automatically with Docker. This is {@code false} by default. \n\t\t * \n\t\t * @param shouldRunWithDocker {@code true} if ZAP should be automatically started with Docker, {@code false} otherwise.\n\t\t * @return this {@code Builder} instance.\n\t\t */\n\t\tpublic Builder shouldRunWithDocker(boolean shouldRunWithDocker) {\n\t\t\tthis.shouldRunWithDocker = shouldRunWithDocker;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Builds a {@link ZapInfo} instance based on the builder parameters.\n\t\t * <p>\n\t\t * You should probably use the other build methods, choosing the one that suits your needs.\n\t\t * \n\t\t * @return a {@link ZapInfo} instance.\n\t\t * @see #buildToUseRunningZap(String, int) buildToUseRunningZap()\n\t\t * @see #buildToRunZap(int, String, String) buildToRunZap()\n\t\t * @see #buildToRunZapWithDocker(int, String) buildToRunZapWithDocker()\n\t\t */\n\t\tpublic ZapInfo build() {\n\t\t\treturn new ZapInfo(this);\n\t\t}\n\t\t\n\t}\n\t\n\tprivate ZapInfo(Builder builder) {\n\t\tthis.host = builder.host;\n\t\tthis.port = builder.port;\n\t\tthis.apiKey = builder.apiKey;\n\t\tthis.path = builder.path;\n\t\tthis.jmvOptions = builder.jmvOptions;\n\t\tthis.options = builder.options;\n\t\tthis.initializationTimeoutInMillis = builder.initializationTimeoutInMillis;\n\t\tthis.shouldRunWithDocker = builder.shouldRunWithDocker;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)\n\t\t\t\t.append(\"host\", host)\n\t\t\t\t.append(\"port\", port)\n\t\t\t\t.append(\"apiKey\", apiKey)\n\t\t\t\t.append(\"path\", path)\n\t\t\t\t.append(\"jvmOptions\", jmvOptions)\n\t\t\t\t.append(\"options\", options)\n\t\t\t\t.append(\"initializationTimeout\", initializationTimeoutInMillis)\n\t\t\t\t.append(\"shouldRunWithDocker\", shouldRunWithDocker)\n\t\t\t\t.toString();\n\t}\n\t\n}",
"public final class Zap {\n\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(Zap.class);\n\t\n\tprivate static ZapBoot zap;\n\t\n\tpublic static void startZap(ZapInfo zapInfo) {\n\t\tzap = ZapBootFactory.makeZapBoot(zapInfo);\n\t\tLOGGER.debug(\"ZAP will be started by: [{}].\", zap.getClass().getSimpleName());\n\t\t\n\t\tzap.startZap(zapInfo);\n\t}\n\t\n\tpublic static void stopZap() {\n\t\tif (zap != null) {\n\t\t\tzap.stopZap();\n\t\t}\n\t}\n\t\n\tprivate Zap() {}\n\t\n}"
] | import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import br.com.softplan.security.zap.api.ZapClient;
import br.com.softplan.security.zap.api.model.AnalysisInfo;
import br.com.softplan.security.zap.api.model.AnalysisType;
import br.com.softplan.security.zap.api.model.AuthenticationInfo;
import br.com.softplan.security.zap.api.report.ZapReport;
import br.com.softplan.security.zap.commons.ZapInfo;
import br.com.softplan.security.zap.commons.boot.Zap; | package br.com.softplan.security.zap.maven;
/**
* Run ZAP's Active Scan and generates the reports. <b>No Spider is executed.</b>
* This scan assumes that integration tests ran using ZAP as a proxy, so the Active Scan
* is able to use the navigation done during the tests for the scan.
* <p>
* Normally this goal will be executed in the phase <i>post-integration-test</i>, while the
* goal {@code startZap} will run in the phase <i>pre-integration-test</i>, to make sure
* ZAP is running during the tests.
*
* @author pdsec
*/
@Mojo(name="seleniumAnalyze")
public class SeleniumAnalyzeMojo extends ZapMojo {
@Override
public void doExecute() throws MojoExecutionException, MojoFailureException {
getLog().info("Starting ZAP analysis at target: " + super.getTargetUrl());
ZapInfo zapInfo = buildZapInfo();
AuthenticationInfo authenticationInfo = buildAuthenticationInfo(); | AnalysisInfo analysisInfo = buildAnalysisInfo(AnalysisType.ACTIVE_SCAN_ONLY); | 2 |
Beloumi/PeaFactory | src/peafactory/peas/image_pea/LockFrameImage.java | [
"public class PeaSettings {\n\n\tprivate static JDialog keyboard = null;\n\tprivate static final JDialog pswGenerator = null;\n\t\n\tprivate static final boolean BOUND = true;\n\tprivate static final String EXTERNAL_FILE_PATH = null;\n\tprivate static final boolean EXTERN_FILE = true;\n\tprivate static final String JAR_FILE_NAME = \"default\";\n\tprivate static final String LABEL_TEXT = null;\n\t\n\tprivate static final byte[] PROGRAM_RANDOM_BYTES = {-128, 125, -121, 32, -104, 88, -90, -116, 122, -64, 58, 67, -4, -51, -93, -89, 70, -22, -61, -109, 114, 75, -49, -114, -42, -128, -71, 5, -48, -92, 0, -71};\n\tprivate static final byte[] FILE_IDENTIFIER = {108, -39, -123, 86, 41, -111, -124, 107};\n\t\n\tprivate static final BlockCipher CIPHER_ALGO = PeaFactory.getDefaultCipher();//new TwofishEngine();\n\tprivate static final Digest HASH_ALGO = PeaFactory.getDefaultHash();//new SkeinDigest(512, 512);\n\tprivate static final KeyDerivation KDF_SCHEME = PeaFactory.getDefaultKDF();//new CatenaKDF();\n\t\n\tprivate static final int ITERATIONS = CatenaKDF.getDragonflyLambda();//2\n\tprivate static final int MEMORY = CatenaKDF.getGarlicDragonfly();//18;\n\tprivate static final int PARALLELIZATION = 0;\n\t\n\tprivate static final String VERSION_STRING = \"\";\n\t\n\t\n\tpublic final static JDialog getKeyboard() { \n\t\treturn keyboard; \n\t}\n\tpublic final static JDialog getPswGenerator() { \n\t\treturn pswGenerator; \n\t}\t\n\tpublic final static Digest getHashAlgo() { \n\t\treturn HASH_ALGO; \n\t}\n\tpublic final static BlockCipher getCipherAlgo() { \n\t\treturn CIPHER_ALGO; \n\t}\n\tpublic final static KeyDerivation getKdfScheme() { \n\t\treturn KDF_SCHEME; \n\t}\n\tpublic final static int getIterations() { \n\t\treturn ITERATIONS; \n\t}\n\tpublic final static int getMemory() { \n\t\treturn MEMORY; \n\t}\n\tpublic final static int getParallelization() { \n\t\treturn PARALLELIZATION; \n\t}\n\tpublic final static String getVersionString() { \n\t\treturn VERSION_STRING; \n\t}\n\tpublic final static byte[] getProgramRandomBytes() { \n\t\treturn PROGRAM_RANDOM_BYTES; \n\t}\n\tpublic final static byte[] getFileIdentifier() { \n\t\treturn FILE_IDENTIFIER; \n\t}\n\tpublic final static String getJarFileName() { \n\t\treturn JAR_FILE_NAME; \n\t}\n\tpublic final static String getLabelText() { \n\t\treturn LABEL_TEXT; \n\t}\n\tpublic final static boolean getExternFile() { \n\t\treturn EXTERN_FILE; \n\t}\n\tpublic final static boolean getBound() { \n\t\treturn BOUND; \n\t}\n\tpublic final static String getExternalFilePath() { \n\t\treturn EXTERNAL_FILE_PATH; \n\t}\n}",
"public class CipherStuff {\n\t\n\tprivate static CipherStuff cipherStuff = new CipherStuff();\n\t\n\tprivate static BlockCipher cipherAlgo;\n\t\n\tprivate static AuthenticatedEncryption authenticatedEncryption = new EAXMode();\n\t\n\tprivate static String errorMessage = null;\n\t\n\tprivate static SessionKeyCrypt skc = null;\n\t\n\tprivate static boolean bound = true;\n\t\n\t// returns required length of key in bytes\n\tpublic final static int getKeySize() {\n\t\t\n\t\tint keySize = 0;\n\t\t\n\t\tif (cipherAlgo == null) {\n\t\t\tSystem.err.println(\"CipherStuff getKeySize: cipherAlgo null\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\t\n\t\tif (cipherAlgo.getAlgorithmName().startsWith(\"Threefish\") ) {\n\t\t\t// key size = block size for Threefish 256/512/1024\n\t\t\tkeySize = cipherAlgo.getBlockSize();\n\t\t} else if ( cipherAlgo.getAlgorithmName().equals(\"Twofish\" )) {\n\t\t\tkeySize = 32; // Bytes\n\t\t} else if (cipherAlgo.getAlgorithmName().equals(\"Serpent\") ) {\n\t\t\t//System.out.println(\"SerpentEngine\");\n\t\t\tkeySize = 32; // Bytes\t\t\t\n\t\t} else if (cipherAlgo.getAlgorithmName().equals(\"AES\") ) {\n\t\t\tkeySize = 32; // Bytes\t\t\n\t\t} else if (cipherAlgo.getAlgorithmName().equals(\"AESFast\") ) {\n\t\t\tkeySize = 32; // Bytes\t\n\t\t} else if (cipherAlgo.getAlgorithmName().equals(\"Shacal2\") ) {\n\t\t\tkeySize = 64; // Bytes\n\t\t} else {\n\t\t\tSystem.err.println(\"CipherStuff getKeySize: invalid Algorithm\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\treturn keySize;\n\t}\n\t\n\t/**\n\t * Encrypt/decrypt an array of bytes. This function is only used to \n\t * encrypt the session key\n\t * \n\t * @param forEncryption - true for encryption, false for decryption\n\t * @param input\t\t\t- plain text or cipher text\n\t * @param key\t\t\t- the cryptographic key for the cipher\n\t * @param zeroize\t\t- fills the key with 0 for true (when the key is no longer used)\n\t * @return\t\t\t\t- plain text or cipher text\n\t */\n\tpublic final static byte[] processCTR(boolean forEncryption, byte[] input, byte[] key,\n\t\t\tboolean zeroize) {\n\t\t//Help.printBytes(\"key\", input);\n\t\tKeyParameter kp = new KeyParameter(key);\n\t\tif (zeroize == true) {\n\t\t\tZeroizer.zero(key);\n\t\t}\n\t\t\n\t\tbyte[] iv = null;\n\t\t\n\t\tif (forEncryption == false) {\n\t\t\t// input is ciphertext, IV is stored on top of ciphertext\n\t\t\t// get IV:\n\t\t\tiv = new byte[CipherStuff.getCipherAlgo().getBlockSize()];\n\t\t\tSystem.arraycopy(input, 0, iv, 0, iv.length);\n\t\t\t// truncate ciphertext:\n\t\t\tbyte[] tmp = new byte[input.length - iv.length];\n\t\t\tSystem.arraycopy(input, iv.length, tmp, 0, tmp.length);\n\t\t\tinput = tmp;\n\t\t} else {\n\t\t\t// input is plaintext\n\t\t\tiv = new RandomStuff().createRandomBytes(CipherStuff.getCipherAlgo().getBlockSize());\n\t\t}\n\t\tParametersWithIV ivp = new ParametersWithIV(kp, iv);\n\n\t\tBufferedBlockCipher b = new BufferedBlockCipher(new SICBlockCipher(cipherAlgo));\n\n b.init(true, ivp);\n byte[] out = new byte[input.length];\n\n int len = b.processBytes(input, 0, input.length, out, 0);\n\n try {\n\t\t\tlen += b.doFinal(out, len);\n\t\t} catch (DataLengthException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (IllegalStateException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (InvalidCipherTextException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n Zeroizer.zero(kp.getKey());\n\n\t\tif (forEncryption == false) {// decryption: output plaintext\n\t\t\treturn out;\n\t\t} else { // encryption: output (IV || ciphertext)\n\t\t\tZeroizer.zero(input);\n\t\t\t// store IV on top of ciphertext\n\t\t\tbyte[] tmp = new byte[out.length + iv.length];\n\t\t\tSystem.arraycopy(iv, 0, tmp, 0, iv.length);\n\t\t\tSystem.arraycopy(out, 0, tmp, iv.length, out.length);\n\t\t\treturn tmp;\n\t\t}\t\t\n\t}\n\n\t\n\t/*\n\t * Encryption if plainBytes can be loaded in memory in one block\n\t */\n\t/**\n\t * Encrypt an array of bytes. \n\t * \n\t * @param plainBytes\t\t\tthe plain text to encrypt\n\t * @param keyMaterial\t\t\tthe derived key or null (there\n\t * \t\t\t\t\t\t\t\tis a session key available)\n\t * @param encryptBySessionKey\tif true, the derived key is encrypted, \n\t * \t\t\t\t\t\t\t\totherwise the key is cleared\n\t * @return\t\t\t\t\t\tthe cipher text\n\t */\n\tpublic final byte[] encrypt(byte[] plainBytes, byte[] keyMaterial, \n\t\t\tboolean encryptBySessionKey){\n\t\t\n\t\tcheckSessionKeyCrypt();\n\t\t\n\t\t// Check if plainBytes is too long to be loaded in memory:\n\t\tif (plainBytes.length > 8192 * 64 * 16) { // fileBlockSize = 8192 * 64 * 16\n\t\t\t\n\t\t\t// check free memory to avoid swapping:\n\t\t\tSystem.gc(); // this might not work...\n\t\t\tlong freeMemory = Runtime.getRuntime().maxMemory() \n\t\t\t\t\t- (Runtime.getRuntime().totalMemory()\n\t\t\t\t\t\t\t- Runtime.getRuntime().freeMemory());\n\t\t\t//System.out.println(\"Free memory: \" + freeMemory);\n\t\t\tif (plainBytes.length <= freeMemory) {\t\t\t\n\t\t\t\tSystem.out.println(\"Warning: long plain text\");\n\t\t\t} else {\n\t\t\t\tJOptionPane.showMessageDialog(null,\n\t\t\t\t\t \"The content you want to encrypt is too large \\n\"\n\t\t\t\t\t + \"to encrypt in one block on your system: \\n\"\n\t\t\t\t\t + plainBytes.length + \"\\n\\n\"\n\t\t\t\t\t + \"Use the file encrytion pea instead. \\n\"\n\t\t\t\t\t + \"(If you blew up an existing text based pea, \\n\"\n\t\t\t\t\t + \"you have to save the content by copy-and-paste).\",\n\t\t\t\t\t \"Memory error\",\n\t\t\t\t\t JOptionPane.ERROR_MESSAGE);\n\t\t\t\tSystem.exit(1);\n\t\t\t}\t\t\t\n\t\t}\n\t\t\n\t\t// unique for each encryption\n\t\tbyte[] iv = Attachments.getNonce();\n\t\tif (iv == null) {\n\t\t\t// for every file: new unique and random IV\n\t\t\tiv = Attachments.generateNonce( );\n\t\t\tAttachments.setNonce(iv);\n\t\t}\n\t\tbyte[] key = detectKey(keyMaterial);\n\t\t//\n\t\t//------ENCRYPTION: \n\t\t//\t\t\t\t\n\t\t// add pswIdentifier to check password in decryption after check of Mac\n\t\tplainBytes = Attachments.addPswIdentifier(plainBytes);\n\n\t\tbyte[] cipherBytes = authenticatedEncryption.processBytes(true, plainBytes, key, iv);\t\n\t\tZeroizer.zero(plainBytes);\t\t\t\t\n\t\t// prepare to save:\n\t\tcipherBytes = Attachments.addNonce(cipherBytes, iv);\t\n\t\tif (CipherStuff.isBound() == false) {\n\t\t\tcipherBytes = Attachments.attachBytes(cipherBytes, KeyDerivation.getAttachedSalt());\n\t\t}\n\t\tcipherBytes = Attachments.addFileIdentifier(cipherBytes);\t\n\t\t//\n\t\t// handle the keys\n\t\t//\n\t\thandleKey(key, encryptBySessionKey);\n\n//\tHelp.printBytes(\"cipherBytes\", cipherBytes);\n\t\treturn cipherBytes;\n\t}\n\t\n\n\t\n\t// changes the encryptedKey for new keyMaterial\n\t// used by changing password\n\t/**\n\t * Encrypt the derived key and use as session key\n\t * \n\t * @param keyMaterial\tthe derived key\n\t */\n\tpublic final void encryptKeyFromKeyMaterial(byte[] keyMaterial) {\n\t\t\n\t\tcheckSessionKeyCrypt();\n\t\t\n\t\tif (keyMaterial == null) {\n\t\t\tSystem.err.println(\"Error: new keyMaterial null (CryptStuff.encryptKeyFromKeyMaterial\");\n\t\t\tSystem.exit(1);\n\t\t}\t\t\n\t\tbyte[] key = detectKey(keyMaterial);\n\t\thandleKey(key, true);\n\t}\n\n\t\n\t\n\t//\n\t// returns null for incorrect password or input\n\t//\n\t/**\n\t * Decrypt an array of bytes. \n\t * \n\t * @param cipherText\t\t\tthe cipher text to decrypt\n\t * @param keyMaterial\t\t\tthe derived key or null if \n\t * \t\t\t\t\t\t\t\tthere is a session key\n\t * @param encryptBySessionKey\tencrypt the key or clear it\n\t * @return\t\t\t\t\t\tthe plain text or null if the\n\t * \t\t\t\t\t\t\t\tdecryption failed\n\t */\n\tpublic final byte[] decrypt(byte[] cipherText, byte[] keyMaterial, \t\t\n\t\t\tboolean encryptBySessionKey) {\n\t\t\n\t\tcheckSessionKeyCrypt();\n\t\t//Help.printBytes(\"ciphertext + Nonce + fileId\", cipherText);\n\t\t// check\n\t\tif (cipherText == null) {\n\t\t\terrorMessage = \"no cipher text\";\n\t\t\treturn null;\n\t\t}\n\t\tcipherText = Attachments.checkFileIdentifier(cipherText, true);\n\t\tif (cipherText == null) { // check returns null if failed\n\t\t\terrorMessage = \"unsuitable cipher text (identifier)\";\n\t\t\treturn null;\n\t\t}\n\t\tif (CipherStuff.isBound() == false){ // cut salt\n\t\t\tcipherText = Attachments.cutSalt(cipherText);\n\t\t}\n\n\t\tbyte[] iv = Attachments.calculateNonce(cipherText);\n\t\tif (iv == null) {\n\t\t\terrorMessage = \"unsuitable cipher text (length)\";\n\t\t\treturn null;\n\t\t} else {\n\t\t\tcipherText = Attachments.cutNonce(cipherText);\n\t\t}\t\t\n\n\t\t// Check if plainBytes is too long to be loaded in memory:\n\t\tif (cipherText.length > 8192 * 64 * 16) { // fileBlockSize = 8192 * 64 * 16\n\t\t\t\n\t\t\t// get free memory to avoid swapping:\n\t\t\tSystem.gc(); // this might not work...\n\t\t\tlong freeMemory = Runtime.getRuntime().maxMemory() \n\t\t\t\t\t- (Runtime.getRuntime().totalMemory()\n\t\t\t\t\t\t\t- Runtime.getRuntime().freeMemory());\n\t\t\t//System.out.println(\"Free memory: \" + freeMemory);\n\t\t\tif (cipherText.length <= freeMemory) {\t\t\t\n\t\t\t\tSystem.out.println(\"Warning: long plain text\");\n\t\t\t\t\n\t\t\t\tif (cipherText.length > (freeMemory - 8192 * 64)){\n\t\t\t\t\tJOptionPane.showMessageDialog(null,\n\t\t\t\t\t\t \"The content you want to decrypt is already large: \\n\"\n\t\t\t\t\t\t + cipherText.length + \"\\n\\n\"\n\t\t\t\t\t\t + \"Adding more content may cause a memory error. \\n\",\n\t\t\t\t\t\t \"Memory warning\",\n\t\t\t\t\t\t JOptionPane.WARNING_MESSAGE);\t\t\t\t\t\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tJOptionPane.showMessageDialog(null,\n\t\t\t\t\t \"The content you want to decrypt is too large \\n\"\n\t\t\t\t\t + \"to decrypt in one block on your system: \\n\"\n\t\t\t\t\t + cipherText.length + \"\\n\\n\"\n\t\t\t\t\t + \"It was probably encrypted on a system with more memory. \\n\"\n\t\t\t\t\t + \"You have to decrypt it on another system... \\n\",\n\t\t\t\t\t \"Memory error\",\n\t\t\t\t\t JOptionPane.ERROR_MESSAGE);\n\t\t\t\tSystem.exit(1);\n\t\t\t}\t\t\t\n\t\t}\n\t\t\n\t\tbyte[] key = detectKey(keyMaterial);\n\n\t\tint macLength = CipherStuff.getCipherAlgo().getBlockSize();\t\t\n\t\t// check mac length:\n\t\tif (cipherText.length < macLength) {\n\t\t\terrorMessage = \"unsuitable cipher text (Mac length)\";\n\t\t\treturn null;\t\t\t\n\t\t}\n\n\t\tbyte[] plainText = authenticatedEncryption.processBytes(false, cipherText, key, iv);\n\t\tif (plainText == null) { // wrong password\n\t\t\terrorMessage = \"authentication failed for password\";\n\t\t\treturn null;\n\t\t}\n\t\tbyte[] rescueText = null;\n\t\tif (PswDialogBase.getWorkingMode().equals(\"-r\")) { // rescue mode: make copy of plainText\n\t\t\trescueText = new byte[plainText.length];\n\t\t\tSystem.arraycopy(plainText, 0, rescueText, 0, plainText.length);\n\t\t}\n\t\tplainText = Attachments.checkAndCutPswIdentifier(plainText); // truncates pswIdentifier\n\n\t\tif (plainText == null) {\n\t\t\t\n\t\t\tSystem.out.println(\"Password identifier failed.\");\n\t\t\t\n\t\t\tif (PswDialogBase.getWorkingMode().equals(\"-r\")) { // rescue mode\n\t\t\t\t \n\t\t\t\t Object[] options = {\"Continue\",\n\t \"Break\"};\n\t\t\t\t int n = JOptionPane.showOptionDialog(null,\n\t\t\t\t\t\t \"Password identifier failed: \\n\"\n\t\t\t\t\t\t\t\t + \"The password identifier checks if the beginning and the end \\n\"\n\t\t\t\t\t\t\t\t + \"of the content.\\n \"\n\t\t\t\t\t\t\t\t + \"An error means that wether the beginning or the end is not correct.\\n\"\n\t\t\t\t\t\t\t\t + \"Normally that means, that the password is wrong, \\n\"\n\t\t\t\t\t\t\t\t + \"but there is the possibility that a file is damaged. \\n\"\n\t\t\t\t\t\t\t\t + \"In this case, some parts of the file might be restored \\n\"\n\t\t\t\t\t\t\t\t + \"by the decryption. \\n\"\n\t\t\t\t\t\t\t\t + \"If you are sure, the password is correct, continue.\\n\"\n\t\t\t\t\t\t\t\t + \"Warning: For incorrect password files may be irretrievably lost. \",\n\t\t\t\t\t\t\"Password Identification Error\",\n\t\t\t\t\t\tJOptionPane.YES_NO_OPTION,\n\t\t\t\t\t\tJOptionPane.ERROR_MESSAGE,\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\toptions[1]);\n\t\t\t \n\t\t\t\t if (n == JOptionPane.YES_OPTION) {\n\t\t\t\t\t// do nothing\n\t\t\t\t\t System.out.println(\"continue\");\n\t\t\t\t\t plainText = rescueText;\n\t\t\t\t } else {\n\t\t\t\t\t System.out.println(\"break\");\n\t\t\t\t\treturn null;\n\t\t\t\t }\t\t \n\t\t\t } else {// not recue mode\n\t\t\t\t\terrorMessage = \"password failed (identifier)\";\n\t\t\t\t\treturn null;\n\t\t\t }\t\t\t\t\n\t\t} \n\n\t\t//\n\t\t// handle the keys\n\t\t//\t\t\n\t\thandleKey(key, encryptBySessionKey);\n\t\treturn plainText;\n\t}\n\n\t/**\n\t * Get the key from keyMaterial or the session key\n\t * \n\t * @param keyMaterial\tthe derived key or null\n\t * @return\t\t\t\tthe key\n\t */\n\tprotected final byte[] detectKey(byte[] keyMaterial) {\n\t\t\n\t\tbyte[] key = null;\n\t\tif (keyMaterial != null) { // use as key \n\t\t\t\n\t\t\t// check size:\n\t\t\tint keySize = CipherStuff.getKeySize();\n\t\t\tif (keyMaterial.length != keySize) {\n\t\t\t\tSystem.err.println(\"CryptStuff detectKey: invalid size of keyMaterial\");\n\t\t\t\tSystem.exit(1);\n\t\t\t} else {\n\t\t\t\tkey = keyMaterial;\n\t\t\t}\n\t\t\t\n\t\t} else { // keyMaterial == null: decrypt encryptedKey to get key\n\t\t\tif (skc == null) {\n\t\t\t\tskc = new SessionKeyCrypt();\n\t\t\t}\n\t\t\tkey = skc.getKey();\n\t\t}\n\t\treturn key;\n\t}\n\t/**\n\t * Encrypt or clear the key\n\t * \n\t * @param key\t\t\t\tthe key\n\t * @param encryptSessionKey\tif true, encrypt the key, if\n\t * \t\t\t\t\t\t\tfalse clear it\n\t */\n\tprotected final void handleKey(byte[] key, boolean encryptSessionKey) {\t\t\n\n\t\tif (encryptSessionKey == false) {\n\t\t\tZeroizer.zero(key);\n\t\t\t\n\t\t} else {\t\t\n\t\t\tif (skc == null) {\n\t\t\t\tskc = new SessionKeyCrypt();\n\t\t\t}\n\t\t\tskc.storeKey(key);\n\t\t}\n\t}\n\tprivate final void checkSessionKeyCrypt(){\n\t\tif (skc == null) {\n\t\t\tskc = new SessionKeyCrypt();\n\t\t}\n\t}\n\n\t\n\t//=========================\n\t// Getter & Setter:\n\tpublic final static void setCipherAlgo (BlockCipher _cipherAlgo) {\n\t\tcipherAlgo = _cipherAlgo;\n\t}\n\tpublic final static BlockCipher getCipherAlgo () {\n\t\treturn cipherAlgo;\n\t}\t\n\t\n\tpublic final static void setCipherMode (AuthenticatedEncryption _cipherMode) {\n\t\tauthenticatedEncryption = _cipherMode;\n\t}\n\tpublic final static AuthenticatedEncryption getCipherMode(){\n\t\treturn authenticatedEncryption;\n\t}\n\t\n\tpublic final SessionKeyCrypt getSessionKeyCrypt(){\n\t\treturn skc;\n\t}\n\t// used in PswDialogFile for initialization\n\tpublic final static void setSessionKeyCrypt(SessionKeyCrypt _skc){ \n\t\tskc = _skc;\n\t}\n\tpublic final static String getErrorMessage() {\n\t\treturn errorMessage;\n\t}\n\tpublic final static void setErrorMessage(String _errorMessage) {\n\t\terrorMessage = _errorMessage;\n\t}\n\n\t/**\n\t * @return the cipherStuff\n\t */\n\tpublic final static CipherStuff getInstance() {\n\t\tif(cipherStuff == null){\n\t\t\tcipherStuff = new CipherStuff();\n\t\t}\n\t\treturn cipherStuff;\n\t}\n\n\t/**\n\t * @return the bound\n\t */\n\tpublic static boolean isBound() {\n\t\treturn bound;\n\t}\n\n\t/**\n\t * @param bound the bound to set\n\t */\n\tpublic static void setBound(boolean bound) {\n\t\tCipherStuff.bound = bound;\n\t}\n}",
"public abstract class PswDialogBase { \n\n\t// special panel for PswDialogView, currently only used in fileType:\n\tprivate static JPanel typePanel;\n\t\n\tprivate static String encryptedFileName;\t\n\t\n\tprivate static String fileType; // set in daughter class\n\t\n\tprivate final static String PATH_FILE_NAME = PeaSettings.getJarFileName() + \".path\";\n\t\n\tprivate static PswDialogBase dialog;\n\t\n\tprivate char[] initializedPassword = null;\n\t\n\tprivate static String errorMessage = null;\n\t\n\t// i18n: \t\n\tprivate static String language; \n\tprivate static Locale currentLocale;\n\tprivate static Locale defaultLocale = Locale.getDefault();\n\tprivate static ResourceBundle languagesBundle;\n\t\n\tpublic static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\t\n\t\n\tprivate static String workingMode = \"\"; // rescue mode or test mode\n\t\n\t//============================================================\n\t// --- abstract Methods:\n\t//\n\n\t// pre computation with windowOpening\n\t// this is nowhere used yet, but maybe used later \n\t// for example ROM-hard KDF schemes \n\tpublic abstract void preComputeInThread();\n\t//\n\t// before exit: clear secret values\n\tpublic abstract void clearSecretValues();\n\t//\n\tpublic abstract void startDecryption();\n\n\t\n\t// currently only used in fileType:\n\tpublic abstract String[] getSelectedFileNames();\n\n\t//============================================================\n\t\n\tpublic final static void setLanguagesBundle(String _language) throws MalformedURLException {\n\t\t\n\t\t\n/*\t\tif(languagesBundle == null){\n\t\t\ttry {\n\t\t\t\t//System.out.println(\"language: \" + Locale.getDefault().getLanguage());\n\t\t\t\tif (Locale.getDefault().getLanguage().contains(\"de\")) {\n\t\t\t\t\tsetLanguagesBundle(Locale.getDefault().getLanguage());\n\t\t\t\t} else {\n\t\t\t\t\tsetLanguagesBundle(null);\n\t\t\t\t}\n\t\t\t} catch (MalformedURLException e1) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te1.printStackTrace();\n\t\t\t}\n\t\t}*/\n\t\t\n\t\t// i18n: \n\t\tif (_language == null) {\n\t\t\tif (defaultLocale == null) { // openSuse\n\t\t\t\tdefaultLocale = new Locale( System.getProperty(\"user.language\") );\n\t\t\t}\t\t\n\t\t\tlanguage = defaultLocale.getLanguage(); // get default language\n\t\t} else {\n\t\t\tlanguage = _language;\n\t\t}\n\t currentLocale = new Locale(language); // set default language as language\n\t \n\t // First try to open Peafactory i18n, if PswDialogBase is not used inside of a pea \n\t // FilePanel uses this bundle\n\t try {\n\t \tlanguagesBundle = ResourceBundle.getBundle(\"config.i18n.LanguagesBundle\", currentLocale);\n\t } catch (MissingResourceException mre) {// used inside of pea\n\n\t \ttry {\t \n\t \t /* File file = new File(\"resources\"); \n\t \t URL[] urls = {file.toURI().toURL()}; \n\t \t ClassLoader loader = new URLClassLoader(urls); \n\t \t languagesBundle = ResourceBundle.getBundle(\"LanguagesBundle\", currentLocale, loader); */ \n\t \t\tlanguagesBundle = ResourceBundle.getBundle(\"resources.PeaLanguagesBundle\", currentLocale);\n\t \t} catch (MissingResourceException mre1) {\n\t \t\t\n\t \t\ttry{\n\t \t\t\tFile file = new File(\"resources\"); \n\t\t \t URL[] urls = {file.toURI().toURL()}; \n\t\t \t ClassLoader loader = new URLClassLoader(urls); \n\t\t \t languagesBundle = ResourceBundle.getBundle(\"LanguagesBundle\", currentLocale, loader); \n\n\t \t\t} catch (MissingResourceException mre2) {\n\t \t\t\n\t\t \t\tcurrentLocale = new Locale(\"en\"); // set default language as language\n\t\t \t\tlanguage = \"en\";\n\n\t\t \t //File file = new File(\"src\" + File.separator + \"config\" + File.separator + \"i18n\");\n\t\t \t File file = new File(\"resources\"); \n\n\t\t \t URL[] urls = {file.toURI().toURL()}; \n\t\t \t ClassLoader loader = new URLClassLoader(urls); \n\t\t \t languagesBundle = ResourceBundle.getBundle(\"LanguagesBundle\", currentLocale, loader);\n\t \t\t}\n\t \t}\n\t }\n\t}\n\t\n\n\t@SuppressWarnings(\"all\")\n\tpublic final static void printInformations() {\n\t\tSystem.out.println(\"Cipher: \" + PeaSettings.getCipherAlgo().getAlgorithmName() );\n\t\tSystem.out.println(\"Hash: \" + PeaSettings.getHashAlgo().getAlgorithmName() );\n\t}\n\t\n\tpublic final static byte[] deriveKeyFromPsw(char[] pswInputChars) { \n\n\t\tif (pswInputChars == null) {\n\t\t\tpswInputChars = \"no password\".toCharArray();\n\t\t} else if (pswInputChars.length == 0) {\n\t\t\tpswInputChars = \"no password\".toCharArray();\n\t\t}\n\t\tbyte[] pswInputBytes = Converter.chars2bytes(pswInputChars); \n\t\tif (pswInputBytes.length > 0) {\n\t\t\tZeroizer.zero(pswInputChars);\n\t\t}\n\t\t// prevent using a zero password:\n\t\tpswInputChars = null;\n\n\t\t//=============\n\t\t// derive key: \n\t\t//\t\n\t\t// 1. initial hash: Bcrypt limited password length, password remains n RAM in Bcrypt and Scrypt\n\t\tbyte[] pswHash = HashStuff.hashAndOverwrite(pswInputBytes);\n\t\tZeroizer.zero(pswInputBytes);\n\n\t\t// 2. derive key from selected KDF: \n\t\tbyte[] keyMaterial = KeyDerivation.getKdf().deriveKey(pswHash);\n\n\t\tZeroizer.zero(pswHash);\t\t\n\t\n\t\treturn keyMaterial;\n\t}\n\n\n\tprotected final byte[] getKeyMaterial() {\n\n\t\t//-------------------------------------------------------------------------------\n\t\t// Check if t is alive, if so: wait...\n\t\tif (PswDialogView.getThread().isAlive()) { // this should never happen... \n\t\t\tSystem.err.println(\"PswDialogBase: WhileTypingThread still alive!\");\n\t\t\ttry {\n\t\t\t\tPswDialogView.getThread().join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"PswDialogBase: Joining thread interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\t\t\t\t\t\t\t\t\n\t\t\n\t\t//---------------------------------------------------------------------\n\t\t// get password \n\t\tchar[] pswInputChars = null;\n\t\tif (PswDialogView.isInitializing() == false){\n\t\t\tpswInputChars = PswDialogView.getPassword();\t\n\t\t} else {\n\t\t\tpswInputChars = initializedPassword;\n\t\t}\n\n\t\tbyte[] keyMaterial = deriveKeyFromPsw(pswInputChars);\t\n\t\t\n\t\tZeroizer.zero(initializedPassword);\n\t\tinitializedPassword = null;\n\n\t\tprintInformations();\n\t\n\t\tif (keyMaterial == null) {\n\t\t\tPswDialogView.getView().displayErrorMessages(\"Key derivation failed.\\n\"\n\t\t\t\t\t+ \"Program bug.\");\n\t\t\tPswDialogView.clearPassword();\n\t\t\tif (CipherStuff.isBound() == false) {\n\t\t\t\t// reset the salt:\n\t\t\t\tKeyDerivation.setSalt(Attachments.getProgramRandomBytes());\n\t\t\t}\n\t\t}\t\t\n\t\treturn keyMaterial;\n\t}\n\n\tpublic final static void initializeVariables() {\t\n\t\t\n\t\tHashStuff.setHashAlgo(PeaSettings.getHashAlgo() );\n\t\tCipherStuff.setCipherAlgo(PeaSettings.getCipherAlgo() );\n\t\tCipherStuff.setBound(PeaSettings.getBound());\n\t\tKeyDerivation.setKdf( PeaSettings.getKdfScheme() );\n\t\tKeyDerivation.settCost(PeaSettings.getIterations() );\n\t\t//KDFScheme.setScryptCPUFactor(PeaSettings.getIterations() );\n\t\tKeyDerivation.setmCost(PeaSettings.getMemory() );\n\t\tKeyDerivation.setArg3(PeaSettings.getParallelization());\n\t\tKeyDerivation.setVersionString(PeaSettings.getVersionString() );\n\t\tAttachments.setProgramRandomBytes(PeaSettings.getProgramRandomBytes() );\n\t\tKeyDerivation.setSalt(Attachments.getProgramRandomBytes() );\n\t\t\n\t\tAttachments.setFileIdentifier(PeaSettings.getFileIdentifier() );\n\t}\n\t\n\t// If a blank PEA is started first: \n\tpublic final byte[] initializeCiphertext(byte[] ciphertext){\n\t\t// salt must be set manually and will be attached to the file later\n\t\t// in encryption step\n\t\tKeyDerivation.setSalt(Attachments.getProgramRandomBytes());\n\t\tbyte[] attachedSalt = new RandomStuff().createRandomBytes(KeyDerivation.getSaltSize());\n\t\t// this will set attachedSalt and update the salt:\n\t\tKeyDerivation.setAttachedAndUpdateSalt(attachedSalt);\n\t\t\n\t\t// attach salt:\n\t\tciphertext = Attachments.attachBytes(ciphertext, attachedSalt);\n\t\t// attach fileIdentifier\n\t\tciphertext = Attachments.attachBytes(ciphertext, Attachments.getFileIdentifier());\n\t\t\n\t\treturn ciphertext;\n\t}\n\t\n\t// if the PAE is not bonded to a content: the salt is attached\n\tpublic final void handleAttachedSalt(byte[] ciphertext) {\n\t\t// reset salt if password failed before:\n\t\tKeyDerivation.setSalt(Attachments.getProgramRandomBytes());\n\n\t\tbyte[] tmp = new byte[KeyDerivation.getSaltSize()];\n\t\tSystem.arraycopy(ciphertext, \n\t\t\t\tciphertext.length \n\t\t\t\t- Attachments.getFileIdentifierSize()\n\t\t\t\t- KeyDerivation.getSaltSize(), \n\t\t\t\ttmp, 0, tmp.length);\n\t\tKeyDerivation.setAttachedAndUpdateSalt(tmp);\n\t}\n\n\t//== file functions: ===============================================================\t\n\t\n\t// checks access and file identifier\n\t// sets errorMessages\n\tpublic final static boolean checkFile(String fileName) {\n\t\tFile file = new File( fileName );\t\t\n\t\t\n\n\t\tif (file.exists() && file.isFile() && file.canRead() && file.canWrite() ) {\n\t\t\t//byte[] content = ReadResources.readExternFile(PswDialogBase.getExternalFilePath());\n\t\t\tRandomAccessFile f;\n\t\t\ttry {\n\t\t\t\tf = new RandomAccessFile(file, \"rwd\");\n\t\t \tif ( Attachments.checkFileIdentifier(f, false) == true) {\n\t\t\t \tf.close();\n\t\t\t \t//============================\n\t\t\t \t// external file name success:\n\t\t\t \t//============================\n\t\t\t \treturn true;\n\t\t\t\t} else {\t\t\t\t\t\n\t\t\t\t\t/*if (fileType.equals(\"passwordSafe\") && f.length() == 0) { // just not initialized\n\t\t\t\t\t\tSystem.out.println(\"Program not initialized.\");\n\t\t\t\t\t\tf.close();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}*/\n\t\t\t\t\tf.close();\n\t\t\t\t\tSystem.out.println(\"PswDialogView: External file path - file identifier failed : \" + fileName );\n\t\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t\t+ fileName + languagesBundle.getString(\"file_identifier_failed\") + \"\\n\");//\": \\n file identifier failed.\\n\");\n\t\t\t\t}\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t+ fileName + \": \" + e +\".\\n\");\n\t\t\t\t//e.printStackTrace();\n\t\t\t} catch (HeadlessException e) {\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t+ fileName + \": \" + e +\".\\n\");\n\t\t\t\t//e.printStackTrace();\n\t\t\t} catch (IOException e) {\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t+ fileName + \": \" + e +\".\\n\");\n\t\t\t\t//e.printStackTrace();\n\t\t\t} catch (Exception e) {\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t+ fileName + \": \" + e +\".\\n\");\n\t\t\t\t//e.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\n\t\n\t//\n\t// 1. checks external file name\n\t// 2. checks path file\n\t// success-> sets fileLabel, PswDialogBase.setEncryptedFileName(...)\n\t// no success -> PswDialogBase.setErrorMessage(...)\n\tpublic final static String searchSingleFile() {\n\t\t\n\t\tPswDialogBase.setErrorMessage(\"\");\n\n\t\t// 1. externalFilePath:\n\t\tif ( PeaSettings.getExternalFilePath() != null) {\n\t\t\t\n\t\t\tString externalFileName = PeaSettings.getExternalFilePath();\n\t\t/*\tif (PswDialogBase.getFileType().equals(\"passwordSafe\")) { \n\t\t\t\texternalFileName = externalFileName \n\t\t\t\t\t\t+ File.separator \n\t\t\t\t\t\t+ PswDialogBase.getJarFileName() + File.separator\n\t\t\t\t\t\t+ \"resources\" + File.separator + \"password_safe_1.lock\";\t\n\t\t\t}*/\n\t\t\tif ( checkFile(externalFileName) == true ) { // access and fileIdentifier\n\t\t\t\tPswDialogView.setFileName( PeaSettings.getExternalFilePath() );\n\t\t\t\tPswDialogBase.setEncryptedFileName( PeaSettings.getExternalFilePath() ); \n\t\t \treturn externalFileName;\n\t\t\t} else {\n\t\t\t\tSystem.out.println(\"PswDialogView: External file path invalid : \" + externalFileName );\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t//+ \"Default file: \" + EXTERNAL_FILE_PATH + \"--- No access.\\n\");\n\t\t\t\t\t\t+ languagesBundle.getString(\"default_file\") + \" \"\n\t\t\t\t\t\t+ PeaSettings.getExternalFilePath()\n\t\t\t\t\t\t+ \"--- \" + languagesBundle.getString(\"no_access\") + \"\\n\");\n\t\t\t}\n\n\t\t} else { //if (PswDialogBase.getEncryptedFileName() == null) {\n\t\t\tif (fileType.equals(\"image\") ) {\n\t\t\t\t//if ( PeaSettings.getBound() == false) {\n\t\t\t\t//\tSystem.out.println(\"Base\");\n\t\t\t\t//} else {\n\t\t\t\t\t// image was stored as text.lock inside jar file in directory resource\n\t\t\t\treturn \"insideJar\";\n\t\t\t\t//}\n\t\t\t}\n\t\t}\n\t\t\t\n\t\t// check path file\n\t\tString[] pathNames = accessPathFile();\n\t\t\n\t\tif (pathNames == null) {\n\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t+ languagesBundle.getString(\"no_path_file_result\") + \"\\n\");\n\t\t\t\t\t//+ \"No result from previously saved file names in path file.\\n\");\n\t\t} else {\n\t\t\t\n\t\t\tfor (int i = 0; i < pathNames.length; i++) {\n\t\t\t\t\n\t\t\t\tif (checkFile(pathNames[i]) == true ) {\n\t\t\t\t\tPswDialogView.setFileName(pathNames[i]);\n\t\t\t\t\tPswDialogBase.setEncryptedFileName(pathNames[i]);\n\t\t\t\t\treturn pathNames[i];\n\t\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\t\tPswDialogBase.getErrorMessage() +\n\t\t\t\t\t\t\t//\"File from path file: \" + pathNames[i] + \"--- No access.\\n\");\n\t\t\t\t\t languagesBundle.getString(\"file_from_path_file\") + \" \"\n\t\t\t\t\t+ pathNames[i] \n\t\t\t\t\t+ \"--- \" + languagesBundle.getString(\"no_access\") + \"\\n\");\n\t\t\t\t}\n\t\t\t}\t\t\t\t\t\t\n\t\t}\n\n\t\t// no file found from external file name and path file:\n\t\tif (PswDialogView.getFileName() == null) {\n\t\t\tPswDialogView.setFileName(languagesBundle.getString(\"no_valid_file_found\"));//\"no valid file found\");\n\t\t}\t\t\t\t\n\t\treturn null;\n\t}\n\t\n\t// detects file names from path file\n\tprotected final static String[] accessPathFile() {\n\t\tFile file = new File(PATH_FILE_NAME);\n\t\tif (! file.exists() ) {\n\t\t\tSystem.err.println(\"PswDialogBase: no path file specified\");\n\t\t\treturn null;\n\t\t}\n\t\tif (! file.canRead() ) {\n\t\t\tSystem.err.println(\"PswDialogBase: can not read path file \" + file.getName() );\n\t\t\tPswDialogView.setMessage(languagesBundle.getString(\"path_file_access_error\")\n\t\t\t\t+ \"\\n\" + PATH_FILE_NAME);\n/*\t\t\tJOptionPane.showInternalMessageDialog(PswDialogView.getView(),\n\t\t\t\t\tlanguagesBundle.getString(\"path_file_access_error\")\n\t\t\t\t//\"There is are file containing names of potentially encrypted files,\\n\" +\n\t\t\t\t//\" but no access to it: \\n\"\n\t\t\t\t+ PATH_FILE_NAME, \n\t\t\t\t\"Info\",//title\n\t\t\t\tJOptionPane.INFORMATION_MESSAGE);*/\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tbyte[] pathBytes = ReadResources.readExternFile( file.getName() );\n\t\tif (pathBytes == null) {\n\t\t\tSystem.err.println(\"PswDialogBase: path file does not contain any file name: \" + file.getPath() );\n\t\t\treturn null;\n\t\t}\n\t\tString pathString = new String(pathBytes, UTF_8);\n\n\t\tString[] pathNames = pathString.split(\"\\n\");\n\t\n\t\treturn pathNames;\t\t\t\n\t}\n\t\n\t// checks if file names already exist in path file\n\t// if not: adds them\t\n\tpublic final static void addFilesToPathFile(String[] selectedFileNames) {\n\n\t\tbyte[] newPathBytes = null;\n\t\tStringBuilder newPathNames = null;\n\t\t\t\t\n\t\tFile file = new File(PATH_FILE_NAME);\n\t\t\n\t\tif (! file.exists() ) { // WriteResources creates new file\n\t\t\t\n\t\t\tnewPathNames = new StringBuilder();\n\t\t\t\n\t\t\tfor (int i = 0; i < selectedFileNames.length; i++) {\n\t\t\t\tnewPathNames.append(selectedFileNames[i]);\n\t\t\t\tnewPathNames.append(\"\\n\");\n\t\t\t}\n\t\t\t\n\t\t} else {\t// path file exists\n\t\t\n\t\t\tif (! file.canRead() || ! file.canWrite() ) {\n\t\t\t\tSystem.err.println(\"PswDialogBase: can not read and write path file \" + file.getName() );\n\t\t\t\t\n\t\t\t\tPswDialogView.setMessage(languagesBundle.getString(\"path_file_access_error\")\n\t\t\t\t\t\t+ \"\\n\" \n\t\t\t\t\t\t+ PATH_FILE_NAME);\n\t\t\t/*\tJOptionPane.showInternalMessageDialog(PswDialogView.getView(),\n\t\t\t\t\t\tlanguagesBundle.getString(\"path_file_access_error\")\n\t\t\t\t\t//\"There is are file containing names of potentially encrypted files,\\n\" +\n\t\t\t\t\t//\" but no access to it: \\n\" \n\t\t\t\t\t+ PATH_FILE_NAME, \n\t\t\t\t\t\"Info\",//title\n\t\t\t\t\tJOptionPane.INFORMATION_MESSAGE); */\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t// get file names from path file:\n\t\t\tString[] oldPathNames = accessPathFile();\n\t\t\t\n\t\t\tnewPathNames = new StringBuilder();\n\t\t\t\n\t\t\t// append old file names:\n\t\t\tfor (int i = 0; i < oldPathNames.length; i++) {\n\t\t\t\tnewPathNames.append(oldPathNames[i]);\n\t\t\t\tnewPathNames.append(\"\\n\");\n\t\t\t}\n\t\t\t// check if file name already exists, if not append\n\t\t\tfor (int i = 0; i < selectedFileNames.length; i++) {\n\t\t\t\tboolean append = true;\n\t\t\t\tfor (int j = 0; j < oldPathNames.length; j++) {\n\t\t\t\t\tif (selectedFileNames[i].equals(oldPathNames[j] )){\n\t\t\t\t\t\tappend = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (append == true) {\n\t\t\t\t\tnewPathNames.append(selectedFileNames[i]);\n\t\t\t\t\tnewPathNames.append(\"\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnewPathBytes = new String(newPathNames).getBytes(UTF_8);\n\t\t\t\n\t\tWriteResources.write(newPathBytes, PATH_FILE_NAME, null);\t\t\n\t}\n\t\n\t// checks if current encryptedFileName is in path file\n\t// asks to remember if not\n\tprotected final static void pathFileCheck() {\n\t\t//String encryptedFileName = getEncryptedFileName();\n\t\tif (encryptedFileName != null) {\n\t\t\tif (encryptedFileName.equals(PeaSettings.getExternalFilePath() )) {\n\t\t\t\treturn; // no need to remember\n\t\t\t}\t\t\t\n\t\t}\n\t\tString pathFileName = PeaSettings.getJarFileName() + \".path\";\n\t\tbyte[] pathFileContent = ReadResources.readExternFile(pathFileName);\n\t\tif (pathFileContent == null) {\n\t\t\tint n = JOptionPane.showConfirmDialog(null,\n\t\t\t\t\tlanguagesBundle.getString(\"remember_files\")\n\t\t\t//\t\t\"Should the name of the file be saved to remember for the next program start? \\n\" \n\t\t\t\t\t+ languagesBundle.getString(\"path_file_storage_info\")\n\t\t\t\t//+ \"The name is then saved in the same folder as this program in:\"\n\t\t\t+ pathFileName , \n\t\t\t\t\"?\", \n\t\t\t\tJOptionPane.OK_CANCEL_OPTION, \n\t\t\t\tJOptionPane.PLAIN_MESSAGE);\n\t\t\t\tif (n == 2) { // cancel\n\t\t\t\t\treturn;\n\t\t\t\t} else if (n == 0){\n\t\t\t\t\tbyte[] encryptedFileNameBytes = encryptedFileName.getBytes(UTF_8);\n\n\t\t\t\t\tWriteResources.write(encryptedFileNameBytes, pathFileName, null);\n\t\t\t\t}\n\t\t\treturn;\n\t\t} else {\n\t\t\tString pathNamesString = new String(pathFileContent, UTF_8);\n\n\t\t\tString[] pathNames = pathNamesString.split(\"\\n\");\n\t\t\t// check if encryptedFileName is already included\n\t\t\tfor (int i = 0; i < pathNames.length; i++) {\n\t\t\t\tif (pathNames[i].equals(encryptedFileName)) {\n\t\t\t\t\tSystem.out.println(\"Already included: \" + encryptedFileName);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t// is not included:\n\t\t\tint n = JOptionPane.showConfirmDialog(null,\n\t\t\t//\t\"Should the name of the file be saved to remember for the next program start? \\n\" \n\t\t\t//+ \"(The name is then saved in \" + pathFileName + \" in the same folder as this program).\", \n\t\t\tlanguagesBundle.getString(\"remember_files\")\n\t\t\t+ languagesBundle.getString(\"path_file_storage_info\")\n\t\t\t+ pathFileName , \n\t\t\t\"?\", \n\t\t\tJOptionPane.OK_CANCEL_OPTION, \n\t\t\tJOptionPane.PLAIN_MESSAGE);\n\t\t\tif (n == 2) { // cancel\n\t\t\t\treturn;\n\t\t\t} else if (n == 0){\n\t\t\t\tbyte[] encryptedFileNameBytes = (\"\\n\" + encryptedFileName).getBytes(UTF_8);\n\n\t\t\t\tbyte[] newContent = new byte[pathFileContent.length + encryptedFileNameBytes.length];\n\t\t\t\tSystem.arraycopy(pathFileContent, 0, newContent, 0, pathFileContent.length);\n\t\t\t\tSystem.arraycopy(encryptedFileNameBytes, 0, newContent, pathFileContent.length, encryptedFileNameBytes.length);\n\t\t\t\t\n\t\t\t\tif (newContent != null) {\n\t\t\t\t\tWriteResources.write(newContent, pathFileName, null);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\t\t\n\t} \n\n\n\t//==========================================\n\t// Getter & Setter\n\n\tpublic final static Charset getCharset(){\n\t\treturn UTF_8;\n\t}\n\t\n\tprotected final static void setFileType(String _fileType) {\n\t\tfileType = _fileType;\n\t}\n\tpublic final static String getFileType() {\n\t\treturn fileType;\n\t}\n\tpublic final static String getEncryptedFileName() {\n\t\treturn encryptedFileName;\n\t}\n\tpublic final static void setEncryptedFileName(String _encryptedFileName) {\n\t\tencryptedFileName = _encryptedFileName;\n\t}\n\tprotected final static void setDialog(PswDialogBase _dialog) {\n\t\tdialog = _dialog;\n\t}\n\tpublic final static PswDialogBase getDialog() {\n\t\treturn dialog;\n\t}\n\tpublic final static String getPathFileName() {\n\t\treturn PATH_FILE_NAME;\n\t}\n\tpublic final static JPanel getTypePanel() {\n\t\treturn typePanel;\n\t}\n\tpublic final static void setTypePanel( JPanel panel){\n\t\ttypePanel = panel;\n\t}\n\tpublic final static String getErrorMessage() {\n\t\treturn errorMessage;\n\t}\n\tpublic final static void setErrorMessage(String newErrorMessage) {\n\t\terrorMessage = newErrorMessage;\n\t}\n\tpublic final static ResourceBundle getBundle(){\n\t\tif (languagesBundle == null) { // set default language\n\t\t\ttry {\n\t\t\t\tsetLanguagesBundle(null);\n\t\t\t} catch (MalformedURLException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn languagesBundle;\n\t}\n\t\n\tpublic char[] getInitializedPasword(){\n\t\treturn initializedPassword;\n\t}\n\tpublic void setInitializedPassword(char[] psw){\n\t\tinitializedPassword = psw;\n\t}\n\t/**\n\t * @return the workingMode\n\t */\n\tpublic static String getWorkingMode() {\n\t\treturn workingMode;\n\t}\n\t/**\n\t * @param workingMode the workingMode to set\n\t */\n\tpublic static void setWorkingMode(String workingMode) {\n\t\tPswDialogBase.workingMode = workingMode;\n\t}\n}",
"@SuppressWarnings(\"serial\")\npublic abstract class LockFrame extends JFrame implements WindowListener {\n\t\n\n\tprotected abstract void windowClosingCommands();\n\t\n\tprotected abstract byte[] getPlainBytes();\n\t\n\t\n\t\n\tpublic final static void saveContent(byte[] keyMaterial, byte[] plainBytes, String fileName) {\n\t\t\n\t\tif (new File(fileName).isFile() == false) {\n\t\t\tSystem.err.println(\"LockFrame wrong file\");\n\t\t\treturn;\n\t\t}\n\n\t\t//Help.printBytes(\"LockFrame: plainBytes\", plainBytes);\n\t\tbyte[] cipherBytes = CipherStuff.getInstance().encrypt(plainBytes, keyMaterial, \n\t\t\t\ttrue );\n\n\t\tif(PeaSettings.getExternFile() == true) {\n\t\t\tWriteResources.write(cipherBytes,fileName, null);\n\t\t} else {\n\t\t\tWriteResources.write(cipherBytes, \"text.lock\", \"resources\");// PswDialog2.jarFileName + File.separator +\n\t\t}\n\t}\n\t\n\tpublic final void changePassword(byte[] plainBytes, String[] fileNames){\n\t\t\n\t\tNewPasswordDialog newPswDialog = NewPasswordDialog.getInstance(this);\n\t\tchar[] newPsw = newPswDialog.getDialogInput();\t\t\n\t\t\n\t\tbyte[] keyMaterial = PswDialogBase.deriveKeyFromPsw(newPsw);\n\t\tif (newPsw != null){\n\t\t\tZeroizer.zero(newPsw);\n\t\t}\n\t\tbyte[] unfilledKeyMaterial = new byte[keyMaterial.length];\n\t\tfor (int i = 0; i < fileNames.length; i++) {\t\t\t\n\t\t\tif (keyMaterial != null) {\n\t\t\t\t// keyMaterial is filled/overwritten in encryption\n\t\t\t\tSystem.arraycopy(keyMaterial, 0, unfilledKeyMaterial, 0, keyMaterial.length);\t\n\t\t\t}\n\t\t\tsaveContent(unfilledKeyMaterial, plainBytes, fileNames[i]);\n\t\t}\n\t\tZeroizer.zero(keyMaterial);\n\t}\n\t\n\n\n\t@Override\n\tpublic void windowActivated(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowClosed(WindowEvent arg0) {}\n\n\t@Override\n\tpublic void windowClosing(WindowEvent arg0) {\n\t\twindowClosingCommands();\n\t\tSystem.exit(0);\n\t}\n\n\t@Override\n\tpublic void windowDeactivated(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowDeiconified(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowIconified(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowOpened(WindowEvent arg0) {}\n}",
"@SuppressWarnings(\"serial\")\npublic class PswDialogView extends JDialog implements WindowListener,\n\t\tActionListener, KeyListener {\n\t\n\tprivate static final Color peaColor = new Color(230, 249, 233);\n\tprivate static final Color messageColor = new Color(252, 194, 171);//(255, 216, 151)\n\t\n\tprivate static JLabel pswLabel;\n\tprivate static JPasswordField pswField;\n\tprivate JButton okButton;\n\t\n\tprivate JPanel filePanel;\n\t\n\tprivate static JLabel fileLabel;\n\n\tprivate static String fileType = \"dingsda\";\n\t\n\tprivate static JCheckBox rememberCheck;\n\t\n\tprivate static PswDialogView dialog;\n\t\n\t// display warnings and error messages\n\tprivate static JTextArea messageArea;\n\t\n\tprivate static WhileTypingThread t;\n\t\n\tprivate static Image image;\n\t\n\tprivate static ResourceBundle languagesBundle;\n\t\n\tprivate static boolean started = false;// to check if decryption was startet by ok-button\n\t\n\tprivate static boolean initializing = false; // if started first time (no password, no content)\n\t\n\tprivate PswDialogView() {\n\t\t\n\t\tsetUI();\n\t\t\n\t\tlanguagesBundle = PswDialogBase.getBundle();\n\t\t\n\t\tfileType = PswDialogBase.getFileType();\n\t\n\t\tdialog = this;\n\t\tthis.setTitle(PeaSettings.getJarFileName() );\n\t\t\t\t\n\t\tthis.setBackground(peaColor);\n\n\t\tURL url = this.getClass().getResource(\"resources/pea-lock.png\");\n\t\tif (url == null) {\n\t\t\ttry{\n\t\t\timage = new ImageIcon(getClass().getClassLoader().getResource(\"resources/pea-lock.png\")).getImage();\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"image not found\");\n\t\t\t}\n\t\t} else {\t\t\t\n\t\t\timage = new ImageIcon(url).getImage();\n\t\t}\n\n\n\t this.setIconImage(image);\n\t\n\t\tthis.addWindowListener(this);\n\t\t\n\t\tthis.addMouseMotionListener(new MouseRandomCollector() );\n\n\t\tJPanel topPanel = (JPanel) this.getContentPane();\n\t\t// more border for right and bottom to start\n\t\t// EntropyPool if there is no password\n\t\ttopPanel.setBackground(peaColor);\n\t\ttopPanel.setBorder(new EmptyBorder(5,5,15,15));\n\t\t\n\t\ttopPanel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\n\t\tmessageArea = new JTextArea();\n\t\tmessageArea.setEditable(false);\t\n\t\tmessageArea.setLineWrap(true);\n\t\tmessageArea.setWrapStyleWord(true);\n\t\tmessageArea.setBackground(topPanel.getBackground());\t\t\n\t\t\n\t\tokButton = new JButton(\"ok\");\n\t\tokButton.setPreferredSize(new Dimension( 60, 30));\n\t\tokButton.setActionCommand(\"ok\");\n\t\tokButton.addActionListener(this);\n\t\t// if there is no password, this might be the only \n\t\t// chance to start EntropyPool\n\t\tokButton.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\n\t\ttopPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));\t\t\n\t\t\n\t\ttopPanel.add(messageArea);\n\t\t\n\t\tif (initializing == false) {\t\t\t\n\t\t\t\n\t\t\tif (PswDialogBase.getWorkingMode().equals(\"-r\")) { // rescue mode\n\t\t\t\tJLabel rescueLabel = new JLabel(\"=== RESCUE MODE ===\");\n\t\t\t\trescueLabel.setForeground(Color.RED);\n\t\t\t\ttopPanel.add(rescueLabel);\n\t\t\t}\n\n\t\t\tif (PeaSettings.getExternFile() == true) {\t// display files and menu\t\t\n\t\t\t\t\n\t\t\t\tif (fileType.equals(\"file\") ) {\n\t\t\t\t\tfilePanel = PswDialogBase.getTypePanel();\n\t\t\t\t\tfilePanel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\t\t\ttopPanel.add(filePanel);\n\t\t\t\t\t\n\t\t\t\t} else { // text, passwordSafe, image: one single file\n\t\t\t\t\t\n\t\t\t\t\tJPanel singleFilePanel = new JPanel();\n\t\t\t\t\tsingleFilePanel.setLayout(new BoxLayout(singleFilePanel, BoxLayout.Y_AXIS));\n\t\t\t\t\t\n\t\t\t\t\tJPanel fileNamePanel = new JPanel();\n\t\t\t\t\tfileNamePanel.setLayout(new BoxLayout(fileNamePanel, BoxLayout.X_AXIS));\n\t\t\t\t\tsingleFilePanel.add(fileNamePanel);\n\t\t\t\t\t\n\t\t\t\t\tJLabel noteLabel = new JLabel();\n\t\t\t\t\tnoteLabel.setText(languagesBundle.getString(\"encrypted_file\"));//\"encryptedFile: \");\t\t\t\t\n\t\t\t\t\tfileNamePanel.add(noteLabel);\n\t\t\t\t\tfileNamePanel.add(Box.createHorizontalStrut(10));\n\t\t\t\t\t\n\t\t\t\t\tfileLabel = new JLabel(languagesBundle.getString(\"no_valid_file_found\") + languagesBundle.getString(\"select_new_file\"));//\"no valid file found - select a new file\");\n\t\t\t\t\tfileNamePanel.add(fileLabel);\n\t\t\t\t\tfileNamePanel.add(Box.createHorizontalGlue() );\n\t\t\t\t\t\n\t\t\t\t\tJPanel openButtonPanel = new JPanel();\n\t\t\t\t\topenButtonPanel.setLayout(new BoxLayout(openButtonPanel, BoxLayout.X_AXIS));\n\t\t\t\t\tsingleFilePanel.add(openButtonPanel);\n\t\t\t\t\t\n\t\t\t\t\tJButton openFileButton = new JButton();\n\t\t\t\t\topenFileButton.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11));\n\t\t\t\t\t\n\t\t\t\t\tif (fileType.equals(\"passwordSafe\")){\n\t\t\t\t\t\topenFileButton.setText(\"open directory\");\n\t\t\t\t\t} else { // text, image\n\t\t\t\t\t\topenFileButton.setText(languagesBundle.getString(\"open_file\"));//\"open file\");\n\t\t\t\t\t}\n\t\t\t\t\topenFileButton.addActionListener(this);\n\t\t\t\t\topenFileButton.setActionCommand(\"openFile\");\n\t\t\t\t\topenButtonPanel.add(openFileButton);\n\t\t\t\t\topenButtonPanel.add(Box.createHorizontalGlue() );\n\t\t\t\t\t\n\t\t\t\t\ttopPanel.add(singleFilePanel);\n\t\t\t\t\t\n\t\t\t\t\tif (PswDialogBase.searchSingleFile() == null) {\n\t\t\t\t\t\tJOptionPane.showMessageDialog(this,\n\t\t\t\t\t\t\t\tPswDialogBase.getErrorMessage(),\n\t\t\t\t\t\t\t \"Error\",\n\t\t\t\t\t\t\t JOptionPane.ERROR_MESSAGE);\n\t\t\t\t\t\t//reset errorMessage:\n\t\t\t\t\t\tPswDialogBase.setErrorMessage(\"\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}//else\n\t\t\ttopPanel.add(Box.createVerticalStrut(10));//Box.createVerticalStrut(10));\n\t\t\t\n\t\t\tJPanel pswLabelPanel = new JPanel();\n\t\t\tpswLabelPanel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\tpswLabelPanel.setLayout(new BoxLayout(pswLabelPanel, BoxLayout.X_AXIS));\n\t\t\ttopPanel.add(pswLabelPanel);\n\t\t\t\n\t\t\tif (PeaSettings.getLabelText() == null) {\n\t\t\t\tpswLabel = new JLabel( languagesBundle.getString(\"enter_password\") );\n\t\t\t} else {\n\t\t\t\tpswLabel = new JLabel( PeaSettings.getLabelText() );\n\t\t\t\t//pswLabel.setText(PeaSettings.getLabelText() );\n\t\t\t}\n\t\t\tpswLabel.setPreferredSize(new Dimension( 460, 20));\n\t\t\tpswLabelPanel.add(pswLabel);\n\t\t\tpswLabelPanel.add(Box.createHorizontalGlue());\n\t\t\tJButton charTableButton = new JButton(languagesBundle.getString(\"char_table\"));\n\t\t\tcharTableButton.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\tcharTableButton.addActionListener(this);\n\t\t\tcharTableButton.setActionCommand(\"charTable1\");\n\t\t\tpswLabelPanel.add(charTableButton);\n\n\t\t\t\n\t\t\tJPanel pswPanel = new JPanel();\n\t\t\tpswPanel.setLayout(new BoxLayout(pswPanel, BoxLayout.X_AXIS));\n\t\t\t\n\t\t\tpswField = new JPasswordField();\n\t\t\tpswField.setBackground(new Color(231, 231, 231) );\n\t\t\tpswField.setPreferredSize(new Dimension(400, 30));\n\t\t\tpswField.addKeyListener(this);\n\t\t\tpswField.addKeyListener(new KeyRandomCollector() );\n\n\t\t\tpswPanel.add(pswField);\n\t\t\t\n\t\t\tpswPanel.add(okButton);\n\t\t\ttopPanel.add(pswPanel);\n\t\t\n\t\t} else {// initializing\n\t\t\t\n\t\t\tif (fileType.equals(\"file\") ) {\n\t\t\t\tJPanel initPanel1 = new JPanel();\n\t\t\t\tinitPanel1.setLayout(new BoxLayout(initPanel1, BoxLayout.X_AXIS));\n\t\t\t\tJLabel fileInitializationLabel = new JLabel(\"Select one file and type a password to initialize...\");\n\t\t\t\tinitPanel1.add(fileInitializationLabel);\n\t\t\t\tinitPanel1.add(Box.createHorizontalGlue());\n\t\t\t\ttopPanel.add(initPanel1);\n\t\t\t\t\n\t\t\t\tJPanel initPanel2 = new JPanel();\n\t\t\t\tinitPanel2.setLayout(new BoxLayout(initPanel2, BoxLayout.X_AXIS));\n\t\t\t\tJLabel fileInitializationLabel2 = new JLabel(\"(you can add more files or directories later).\");\n\t\t\t\tinitPanel2.add(fileInitializationLabel2);\n\t\t\t\tinitPanel2.add(Box.createHorizontalGlue());\n\t\t\t\ttopPanel.add(initPanel2);\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tJPanel panel = new JPanel();\n\t\t\tpanel.setPreferredSize(new Dimension(400, 300));\n\t\t\tpanel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\t\n\t\t\tJLabel infoLabel = new JLabel(\"Initialization... \");\n\t\t\tinfoLabel.setForeground(Color.RED);\n\t\t\tinfoLabel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\tpanel.add(infoLabel);\n\t\t\tpanel.add(okButton);\n\t\t\t\n\t\t\ttopPanel.add(panel);\n\t\t}\t\t\n\t\t\n\t\tif (PeaSettings.getExternFile() == true){\t\t\n\t\t\t\n\t\t\tJPanel checkRememberPanel = new JPanel();\n\t\t\tcheckRememberPanel.setLayout(new BoxLayout(checkRememberPanel, BoxLayout.X_AXIS));\n\t\t\t\n\t\t\trememberCheck = new JCheckBox();\n\t\t rememberCheck = new JCheckBox();\t\n\t\t rememberCheck.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));\n\t\t rememberCheck.setText(languagesBundle.getString(\"remember_file_names\"));//\"remember selected file names\");\n\t\t rememberCheck.setToolTipText(languagesBundle.getString(\"file_storage_info\")// \"file names will be saved in the file \" +\n\t\t \t\t+ \" \" + PeaSettings.getJarFileName() + \".path\");// in current directory\");\n\t\t\t\n\t\t checkRememberPanel.add(Box.createVerticalStrut(10));\n\t\t checkRememberPanel.add(rememberCheck);\n\t\t checkRememberPanel.add(Box.createHorizontalGlue() );\n\t\t \n\t\t topPanel.add(checkRememberPanel);\n\t\t}\n\t\tif (PeaSettings.getKeyboard() != null) {\n\t\t\tJButton keyboardButton = new JButton(\"keyboard\");\n\t\t\tkeyboardButton.addActionListener(this);\n\t\t\tkeyboardButton.setActionCommand(\"keyboard\");\n\t\t\ttopPanel.add(keyboardButton);\t\t\t\n\t\t}\n\n\t\tthis.setLocation(100,30);\n\t\tpack();\n\t}\n\t\n\tpublic final static PswDialogView getInstance() {\n\t\tif (dialog == null) {\n\t\t\tdialog = new PswDialogView();\n\t\t} else {\n\t\t\t//return null\n\t\t}\n\t\treturn dialog;\n\t}\n\t\n\tpublic static void checkInitialization(){\n\t\t// check if this file was not yet initialized and if not, \n\t\t// remove password field\n\t\ttry {\n\t\t\t// the String \"uninitializedFile\" is stored in the file \"text.lock\"\n\t\t\t// if the pea was not yet initialized\n\t\t\t\n\t\t\t// try to read only the first line: \n\t\t\tBufferedReader brTest = new BufferedReader(new FileReader(\"resources\" + File.separator + \"text.lock\"));\n\t\t String test = brTest .readLine();\n\t\t brTest.close();\n\t\t\tif (test.startsWith(\"uninitializedFile\")){\n\t\t\t\t// set variable initializing to indicate that there is no password or content \n\t\t\t\t//PswDialogView.setInitialize(true);\n\t\t\t\tinitializing = true;\n\t\t\t\tSystem.out.println(\"Initialization\");\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\t// ignore\n\t\t}\n\t}\n\n\tpublic final void displayErrorMessages(String topic) {\n\t\t\n\t\tsetMessage(topic + \":\\n\" + CipherStuff.getErrorMessage());\n\n\t\tPswDialogView.clearPassword();\n\t}\n\n\t@Override\n\tpublic void keyPressed(KeyEvent kpe) {\n\t\t// EntropyPool must be started by mouse events if initializing\n\t\tif(kpe.getKeyChar() == KeyEvent.VK_ENTER && initializing == false){\n\t\t\tokButton.doClick();\n\t\t}\n\t}\n\t@Override\n\tpublic void keyReleased(KeyEvent arg0) {}\n\t@Override\n\tpublic void keyTyped(KeyEvent arg0) {}\n\n\t@Override\n\tpublic void actionPerformed(ActionEvent ape) {\n\t\tString command = ape.getActionCommand();\n\t\t//System.out.println(\"command: \" + command);\n\t\tif(command.equals(\"keyboard\")){\n\t\t\tPeaSettings.getKeyboard().setVisible(true);\n\t\t\t\n\t\t} else if (command.equals(\"charTable1\")){\n\t\t\tCharTable table = new CharTable(this, pswField);\n\t\t\ttable.setVisible(true);\n\t\t\t\n\t\t} else if (command.equals(\"ok\")){\n\n\t\t\tif (PeaSettings.getKeyboard() != null) {\n\t\t\t\tPeaSettings.getKeyboard().dispose();\n\t\t\t}\n\t\t\t\n\t\t\tstarted = true;\n\n\t\t\tEntropyPool.getInstance().stopCollection();\n\n\t\t\tif (PeaSettings.getExternFile() == true && initializing == false) {\n\n\t\t\t\t// remember this file?\n\t\t\t\tif (rememberCheck.isSelected() ) {\n\t\t\t\t\t\n\t\t\t\t\t\tString[] newNames;\n\t\t\t\t\t\tif (PswDialogBase.getFileType().equals(\"file\")) {\n\t\t\t\t\t\t\t// set encrypted file names:\n\t\t\t\t\t\t\tnewNames = PswDialogBase.getDialog().getSelectedFileNames();\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnewNames = new String[1];\n\t\t\t\t\t\t\tnewNames[0] = PswDialogBase.getEncryptedFileName();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tPswDialogBase.addFilesToPathFile( newNames );\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif ( ! fileType.equals(\"file\")) { // text, image\n\t\t\t\t\t\n\t\t\t\t\t// check if one valid file is selected:\n\t\t\t\t\tif (PswDialogBase.getEncryptedFileName() == null) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tsetMessage(languagesBundle.getString(\"no_file_selected\"));\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tPswDialogBase.getDialog().startDecryption();\n\t\t\t\t} else { // file\n\t\t\t\t\tPswDialogBase.getDialog().startDecryption();\n\t\t\t\t}\n\t\t\t} else { // internal File in directory \"resources\"\n\n\t\t\t\t// set resources/text.lock as encryptedFileName\n\t\t\t\tString newFileName = \"resources\" + File.separator + \"text.lock\";\n\n\t\t\t\tPswDialogBase.setEncryptedFileName(newFileName);\n\n\t\t\t\tPswDialogBase.getDialog().startDecryption();\n\t\t\n\t\t\t\t// remember this file?\n\t\t\t\tif (PeaSettings.getExternFile() == true && initializing == false) {\n\t\t\t\t\tif (rememberCheck.isSelected() ) {\n\t\t\t\t\t\tString[] newName = { PswDialogBase.getEncryptedFileName() };\n\t\t\t\t\t\tPswDialogBase.addFilesToPathFile( newName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tstarted = false;\n\n\t\t\t\n\t\t} else if (command.equals(\"openFile\")) {\n\n\t\t\tJFileChooser chooser = new JFileChooser();\n\n\t\t\tif (fileType.equals(\"text\")) {\n\t\t\t\tFileNameExtensionFilter filter = new FileNameExtensionFilter(\"TEXT FILES\", \"txt\", \"text\", \"rtf\");\n\t\t\t\tchooser.setFileFilter( filter );\n\t\t\t} else if (fileType.equals(\"passwordSafe\")) {\n\t\t\t\tchooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);\n\t\t\t chooser.setAcceptAllFileFilterUsed(false);\n\t\t\t} else if (fileType.equals(\"image\")) {\n\t\t\t\tFileNameExtensionFilter filter = new FileNameExtensionFilter(\"IMAGE FILES\", \"png\", \"jpg\", \"jpeg\", \"bmp\", \"gif\");\n\t\t\t\tchooser.setFileFilter( filter );\n\t\t\t}\n\t\t int returnVal = chooser.showOpenDialog(this);\n\t\t if(returnVal == JFileChooser.APPROVE_OPTION) {\t\t \n\t\t \t\n\t\t \tFile file = chooser.getSelectedFile();\n\t\t \tString selectedFileName = file.getAbsolutePath();\n\t\t \t\n\t\t \tif ( PswDialogBase.checkFile(selectedFileName ) == true ) {\n\t\t\t\t\tfileLabel.setText( selectedFileName );\n\t\t\t\t\tPswDialogBase.setEncryptedFileName( selectedFileName ); \n\t\t \t} else {\n\t\t \t\tsetMessage(languagesBundle.getString(\"error\") \n\t\t \t\t\t\t+ \"\\n\" + languagesBundle.getString(\"no_access_to_file\")\n\t\t \t\t\t\t+ \"\\n\" + file.getAbsolutePath());\n\t\t\t\t\treturn;\n\t\t \t}\n\t\t }\n\t\t}\t\t\n\t}\n\t\n\n\t@Override\n\tpublic void windowActivated(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowClosed(WindowEvent arg0) { // dispose\n\n\t\t// if attacker has access to memory but not to file\n\t\tif (Attachments.getNonce() != null) {\n\t\t\tZeroizer.zero(Attachments.getNonce());\n\t\t}\n\t\tif (PswDialogBase.getDialog() != null) {\n\t\t\tPswDialogBase.getDialog().clearSecretValues();\n\t\t}\t\n\n\t\tthis.dispose();\n\t\t//System.exit(0);\t// do not exit, otherwise files leave unencrypted\t\n\t}\n\t@Override\n\tpublic void windowClosing(WindowEvent arg0) { // x\n\t\t\n\t\tif (started == true) {\n\t\t\treturn;\n\t\t} else {\n\t\t\t// if attacker has access to memory but not to file\n\t\t\tif (Attachments.getNonce() != null) {\n\t\t\t\tZeroizer.zero(Attachments.getNonce());\n\t\t\t}\n\t\t\tif (PswDialogBase.getDialog() != null) {\n\t\t\t\tPswDialogBase.getDialog().clearSecretValues();\n\t\t\t}\n\t\t\tSystem.exit(0);\n\t\t}\t\n\t}\n\t@Override\n\tpublic void windowDeactivated(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowDeiconified(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowIconified(WindowEvent arg0) {}\n\n\t@Override\n\tpublic void windowOpened(WindowEvent arg0) {\n\t\t\n\t\t// do some expensive computations while user tries to remember the password\n\t\tt = this.new WhileTypingThread();\n\t\tt.setPriority( Thread.MAX_PRIORITY );// 10\n\t\tt.start();\n\t\tif (initializing == false) {\n\t\t\tpswField.requestFocus();\n\t\t}\n\t}\n\n\t\n\t//=======================================\n\t// Helper Functions\n\t\n\tpublic final static void setUI() {\n//\t\tUIManager.put(\"Button.background\", peaColor );\t\t\t\t\t\n//\t\tUIManager.put(\"MenuBar.background\", peaColor ); // menubar\n//\t\tUIManager.put(\"MenuItem.background\", color2 ); // menuitem\n\t\tUIManager.put(\"PopupMenu.background\", peaColor );\t//submenu\t\t\t\t\t\t\t\t\t\n\t\tUIManager.put(\"OptionPane.background\", peaColor );\n\t\tUIManager.put(\"Panel.background\", peaColor );\n\t\tUIManager.put(\"RadioButton.background\", peaColor );\n\t\tUIManager.put(\"ToolTip.background\", peaColor );\n\t\tUIManager.put(\"CheckBox.background\", peaColor );\t\n\t\t\n\t\tUIManager.put(\"InternalFrame.background\", peaColor );\n\t\tUIManager.put(\"ScrollPane.background\", peaColor );\n\t\tUIManager.put(\"Viewport.background\", peaColor );\t\n\t\t// ScrollBar.background Viewport.background\n\t}\n\t\n\n\t\n\tprotected final static void updateView(){\n\t\tdialog.dispose();\n\t\tdialog = new PswDialogView();\n\t\tdialog.setVisible(true);\n\t}\n\t\n\t/**\n\t * Perform he action for ok button. Used for initialization. \n\t */\n\tpublic void clickOkButton() {\n\t\tokButton.doClick();\n\t}\n\t\n\n\t\n\t//===============================================\n\t// Getter & Setter\n\tpublic final static char[] getPassword() {\n\t\treturn pswField.getPassword();\n\t}\n\tprotected final static void setPassword(char[] psw) { // for Keyboard\n\t\tpswField.setText( new String(psw) );\n\t}\n\tprotected final static void setPassword(char pswChar) { // for charTable\n\t\tpswField.setText(\"\" + pswChar );\n\t}\n\tpublic final static void clearPassword() {\n\t\tif (pswField != null) {\n\t\t\tpswField.setText(\"\");\n\t\t}\n\t}\n\tpublic final static void setMessage(String message) {\n\t\tif (message != null) {\n\t\t\tmessageArea.setBackground(messageColor);\n\t\t\tmessageArea.setText(message);\n\t\t\tdialog.pack();\n\t\t}\n\t}\n\tpublic final static void setLabelText(String labelText) {\n\t\tif (initializing == true){\n\t\t\tpswLabel.setText(labelText);\n\t\t}\n\t}\n\tpublic final static WhileTypingThread getThread() {\n\t\treturn t;\n\t}\n\tpublic final static Image getImage() {\n\t\tif (image == null) {\n\t\t\tSystem.err.println(\"PswDialogView getImage: image null\");\n\t\t}\n\t return image;\n\t}\n\tpublic final static PswDialogView getView() {\n\t\treturn dialog;\n\t}\n\tpublic final JPanel getFilePanel() {\n\t\treturn filePanel;\n\t}\n\tpublic final static void setFileName(String fileName) {\n\t\tfileLabel.setText(fileName);\n\t}\n\tpublic final static String getFileName() {\n\t\treturn fileLabel.getText();\n\t}\n\tpublic final static Color getPeaColor(){\n\t\treturn peaColor;\n\t}\n\t\n\t/**\n\t * @return the initializing\n\t */\n\tpublic static boolean isInitializing() {\n\t\treturn initializing;\n\t}\n\n\t/**\n\t * @param initializing the initializing to set\n\t */\n\tpublic static void setInitializing(boolean initialize) {\n\t\tPswDialogView.initializing = initialize;\n\t}\n\n\t//================================================\n\t// inner class\n\tpublic class WhileTypingThread extends Thread {\n\t\t// some pre-computations while typing the password\n\t\t@Override\n\t\tpublic void run() {\t\t\n\t\t\tif (PswDialogBase.getDialog() != null) {\n\t\t\t\tPswDialogBase.getDialog().preComputeInThread();\n\t\t\t}\n\t\t}\n\t}\n}",
"public final class Converter {\n\t\n\tpublic final static int[] chars2ints( char[] input) {\n\t\tif (input == null) {\n\t\t\tSystem.err.println(\"Converter: input null (char -> int)\");\n\t\t\treturn null;\n\t\t}\n\t\tif (input.length %2 != 0) {\n\t\t\tSystem.err.println(\"Converter (char -> int): wrong size, must be even. Is padded.\");\n\t\t\tchar[] tmp = new char[input.length + 1];\n\t\t\tSystem.arraycopy(input, 0 ,tmp, 0, input.length);\n\t\t\ttmp[tmp.length - 1] = '\\0';\n\t\t}\n\t\tint[] result = new int[input.length / 2];\n\t\t\n\t\tfor (int i=0; i<result.length; i++) {\n\t\t\t//System.out.println(\" \" + ( (int)input[i*2]) + \" \" + (((int) (input[i*2+1]) << 16)));\n\t\t\tresult[i] = ( (int)input[i*2]) | (((int) (input[i*2+1]) << 16));\n\t\t}\n\t\treturn result;\n\t}\t\t\n\t// Converts char[] to byte[]\n\tpublic final static byte[] chars2bytes(char[] charArray) {\n\t\tif (charArray == null) {\n\t\t\tSystem.err.println(\"Converter: input null (char -> byte)\");\n\t\t\treturn null;\n\t\t}\n\t\tbyte[] result = Charset.forName(\"UTF-8\").encode(CharBuffer.wrap(charArray)).array();\n\t\treturn result;\n\t}\n\t// Converts byte[] to char[]\n\tpublic final static char[] bytes2chars(byte[] byteArray) {\t\t\n\t\t//ByteBuffer bbuff = ByteBuffer.allocate(byteArray.length);\n\t\tif (byteArray == null) {\n\t\t\tSystem.err.println(\"Converter: input null (byte -> char)\");\n\t\t\treturn null;\n\t\t}\t\t\n\t\tchar[] result = Charset.forName(\"UTF-8\").decode(ByteBuffer.wrap(byteArray)).array();\n\t\t\n\t\t// cut last null-bytes, appeared because of Charset/CharBuffer in bytes2chars for Linux\n\t\tint cutMarker;\n\t\tfor (cutMarker = result.length - 1; cutMarker > 0; cutMarker--) {\n\t\t\tif (result[cutMarker] != 0) break;\n\t\t}\n\t\tchar[] tmp = new char[cutMarker + 1];\n\t\tSystem.arraycopy(result, 0, tmp, 0, cutMarker + 1);\n\t\tZeroizer.zero(result);\n\t\tresult = tmp;\t\t\t\n\t\t\n\t\treturn result;\n\t}\n\n\t\n\t//===============================\n\t// BIG ENDIAN:\n\t\n\tpublic final static int[] bytes2intsBE( byte[] bytes) {\n\t\tif (bytes == null) {\n\t\t\tSystem.err.println(\"Converter: input null (byte -> int)\");\n\t\t\treturn null;\n\t\t}\n\t\tif (bytes.length % 4 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2int invalid length %4\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tint[] result = new int[bytes.length/4];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = ((bytes[i*4 ] & 0xFF) << 24) \n\t\t\t\t\t| ((bytes[i*4+1] & 0xFF) << 16) \n\t\t\t\t\t| ((bytes[i*4+2] & 0xFF) << 8) \n\t\t\t\t\t| (bytes[i*4+3] & 0xFF); \n\t\t}\n\t\treturn result;\n\t}\n\t\n\t/**\n\t * Convert an array of 8-bit signed values (Java: bytes) \n\t * into an array of 32-bit signed values (Java: int)\n\t * \n\t * @param bytes\t\tinput: array of 8-bit signed values to convert\n\t * @param inIndex\tindex at input to start\n\t * @param inLen\t\tnumber of bytes to convert\n\t * @param outIndex\tindex at output, to store the converted values\n\t * @return\t\t\toutput: array of 32-bit signed vales, \n\t * \t\t\t\t\tmust be larger than outIndex + inLen/4\n\t */\n\tpublic final static int[] bytes2intsBE( byte[] bytes, int inIndex, int inLen, int outIndex) {\n\t\tif (bytes == null) {\n\t\t\tSystem.err.println(\"Converter: input null (byte -> int)\");\n\t\t\treturn null;\n\t\t}\n\t\tif (bytes.length % 4 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2int invalid length %4\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tint[] result = new int[bytes.length/4];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = ((bytes[i*4 ] & 0xFF) << 24) \n\t\t\t\t\t| ((bytes[i*4+1] & 0xFF) << 16) \n\t\t\t\t\t| ((bytes[i*4+2] & 0xFF) << 8) \n\t\t\t\t\t| (bytes[i*4+3] & 0xFF); \n\t\t}\n\t\treturn result;\n\t}\n\t\n\tpublic final static byte[] ints2bytesBE(int[] ints) {\n\t\tif (ints == null) {\n\t\t\tSystem.err.println(\"Converter: input null (int -> byte)\");\n\t\t\treturn null;\n\t\t}\n\t\tbyte[] result = new byte[ints.length * 4];\n\t\tfor (int i = 0; i < ints.length; i++ ) {\n\t\t\tresult[i*4+3] = (byte) (ints[i]);\n\t\t\tresult[i*4+2] = (byte)(ints[i] >>> 8);\n\t\t\tresult[i*4+1] = (byte)(ints[i] >>> 16);\n\t\t\tresult[i*4] = (byte)(ints[i] >>> 24);\n\t\t}\t\t\n\t\treturn result;\n\t}\n\tpublic final static byte[] int2bytesBE(int input) {\n\n\t\tbyte[] result = new byte[4];\n\n\t\t\tresult[3] = (byte) (input);\n\t\t\tresult[2] = (byte)(input >>> 8);\n\t\t\tresult[1] = (byte)(input >>> 16);\n\t\t\tresult[0] = (byte)(input >>> 24);\n\t\t\n\t\treturn result;\n\t}\n\t\n\t\n\tpublic final static byte[] long2bytesBE(long longValue) {\n\t return new byte[] {\n\t (byte) (longValue >> 56),\n\t (byte) (longValue >> 48),\n\t (byte) (longValue >> 40),\n\t (byte) (longValue >> 32),\n\t (byte) (longValue >> 24),\n\t (byte) (longValue >> 16),\n\t (byte) (longValue >> 8),\n\t (byte) longValue\n\t };\n\t}\n\tpublic final static byte[] longs2bytesBE(long[] longArray) {\n\t\tbyte[] result = new byte[longArray.length * 8];\n\t\tfor (int i = 0; i < longArray.length; i++) {\n\t\t\tresult[i * 8 + 0] = (byte) (longArray[i] >>> 56);\n\t\t\tresult[i * 8 + 1] = (byte) (longArray[i] >>> 48);\n\t\t\tresult[i * 8 + 2] = (byte) (longArray[i] >>> 40);\n\t\t\tresult[i * 8 + 3] = (byte) (longArray[i] >>> 32);\n\t\t\tresult[i * 8 + 4] = (byte) (longArray[i] >>> 24);\n\t\t\tresult[i * 8 + 5] = (byte) (longArray[i] >>> 16);\n\t\t\tresult[i * 8 + 6] = (byte) (longArray[i] >>> 8);\n\t\t\tresult[i * 8 + 7] = (byte) (longArray[i] >>> 0);\n\t\t}\n\t return result;\n\t}\n\tpublic final static long bytes2longBE(byte[] byteArray) {\n\t\tif (byteArray.length != 8) {\n\t\t\tSystem.err.println(\"Converter bytes2long: invalid length\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t return ((long)(byteArray[0] & 0xff) << 56) |\n\t ((long)(byteArray[1] & 0xff) << 48) |\n\t ((long)(byteArray[2] & 0xff) << 40) |\n\t ((long)(byteArray[3] & 0xff) << 32) |\n\t ((long)(byteArray[4] & 0xff) << 24) |\n\t ((long)(byteArray[5] & 0xff) << 16) |\n\t ((long)(byteArray[6] & 0xff) << 8) |\n\t ((long)(byteArray[7] & 0xff));\n\t}\n\tpublic final static long[] bytes2longsBE(byte[] byteArray) {\n\t\tif (byteArray.length % 8 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2long: invalid length: \" + byteArray.length);\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tlong[] result = new long[byteArray.length / 8];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = \n\t\t\t ((long)(byteArray[i * 8 + 0] & 0xff) << 56) |\n\t\t ((long)(byteArray[i * 8 + 1] & 0xff) << 48) |\n\t\t ((long)(byteArray[i * 8 + 2] & 0xff) << 40) |\n\t\t ((long)(byteArray[i * 8 + 3] & 0xff) << 32) |\n\t\t ((long)(byteArray[i * 8 + 4] & 0xff) << 24) |\n\t\t ((long)(byteArray[i * 8 + 5] & 0xff) << 16) |\n\t\t ((long)(byteArray[i * 8 + 6] & 0xff) << 8) |\n\t\t ((long)(byteArray[i * 8 + 7] & 0xff));\n\t\t}\n\t return result;\n\t}\n\tpublic final static long[] ints2longsBE(int[] intArray) {\n\t\tif (intArray.length % 2 != 0) {\n\t\t\tSystem.err.println(\"Converter ints2long: invalid length: \" + intArray.length);\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tlong[] result = new long[intArray.length / 2];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = (long) (intArray[i * 2 + 1] & 0x00000000FFFFFFFFL) \n\t\t\t\t\t| (long)intArray[i * 2 + 0] << 32;\n\t\t}\n\t return result;\n\t}\n\t\n\t//===============================\n\t// LITTLE ENDIAN:\n\tpublic final static int[] bytes2intsLE( byte[] bytes) {\n\t\tif (bytes == null) {\n\t\t\tSystem.err.println(\"Converter: input null (byte -> int)\");\n\t\t\treturn null;\n\t\t}\n\t\tif (bytes.length % 4 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2int invalid length %4\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tint[] result = new int[bytes.length/4];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = ((bytes[i*4+3 ] & 0xFF) << 24) \n\t\t\t\t\t| ((bytes[i*4+2] & 0xFF) << 16) \n\t\t\t\t\t| ((bytes[i*4+1] & 0xFF) << 8) \n\t\t\t\t\t| (bytes[i*4+0] & 0xFF); \n\t\t}\n\t\treturn result;\n\t}\n\tpublic final static byte[] ints2bytesLE(int[] ints) {\n\t\tif (ints == null) {\n\t\t\tSystem.err.println(\"Converter: input null (int -> byte)\");\n\t\t\treturn null;\n\t\t}\n\t\tbyte[] result = new byte[ints.length * 4];\n\t\tfor (int i = 0; i < ints.length; i++ ) {\n\t\t\tresult[i*4+0] = (byte) (ints[i]);\n\t\t\tresult[i*4+1] = (byte)(ints[i] >>> 8);\n\t\t\tresult[i*4+2] = (byte)(ints[i] >>> 16);\n\t\t\tresult[i*4+3] = (byte)(ints[i] >>> 24);\n\t\t}\t\t\n\t\treturn result;\n\t}\n\tpublic final static byte[] int2bytesLE(int input) {\n\n\t\tbyte[] result = new byte[4];\n\t\tresult[0] = (byte) (input);\n\t\tresult[1] = (byte)(input >>> 8);\n\t\tresult[2] = (byte)(input >>> 16);\n\t\tresult[3] = (byte)(input >>> 24);\t\n\t\treturn result;\n\t}\n\n\t\n\tpublic final static byte[] long2bytesLE(long longValue) {\n\t return new byte[] {\n\t (byte) (longValue),\n\t (byte) (longValue >> 8),\n\t (byte) (longValue >> 16),\n\t (byte) (longValue >> 24),\n\t (byte) (longValue >> 32),\n\t (byte) (longValue >> 40),\n\t (byte) (longValue >> 48),\n\t (byte) (longValue >> 56)\n\t };\n\t}\n\tpublic final static byte[] longs2bytesLE(long[] longArray) {\n\t\tbyte[] result = new byte[longArray.length * 8];\n\t\tfor (int i = 0; i < longArray.length; i++) {\n\t\t\tresult[i * 8 + 7] = (byte) (longArray[i] >>> 56);\n\t\t\tresult[i * 8 + 6] = (byte) (longArray[i] >>> 48);\n\t\t\tresult[i * 8 + 5] = (byte) (longArray[i] >>> 40);\n\t\t\tresult[i * 8 + 4] = (byte) (longArray[i] >>> 32);\n\t\t\tresult[i * 8 + 3] = (byte) (longArray[i] >>> 24);\n\t\t\tresult[i * 8 + 2] = (byte) (longArray[i] >>> 16);\n\t\t\tresult[i * 8 + 1] = (byte) (longArray[i] >>> 8);\n\t\t\tresult[i * 8 + 0] = (byte) (longArray[i] >>> 0);\n\t\t}\n\t return result;\n\t}\n\tpublic final static byte[] longs2intsLE(long[] longArray) {\n\t\tbyte[] result = new byte[longArray.length * 2];\n\t\tfor (int i = 0; i < longArray.length; i++) {\n\t\t\tresult[i * 2 + 1] = (byte) (longArray[i] >>> 32);\n\t\t\tresult[i * 2 + 0] = (byte) (longArray[i] >>> 0);\n\t\t}\n\t return result;\n\t}\n\tpublic final static long bytes2longLE(byte[] byteArray) {\n\t\tif (byteArray.length % 8 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2long: invalid length: \" + byteArray.length);\n\t\t\tSystem.exit(1);\n\t\t}\n\t return \n\t ((long)(byteArray[7] & 0xff) << 56) |\n\t ((long)(byteArray[6] & 0xff) << 48) |\n\t ((long)(byteArray[5] & 0xff) << 40) |\n\t ((long)(byteArray[4] & 0xff) << 32) |\n\t ((long)(byteArray[3] & 0xff) << 24) |\n\t ((long)(byteArray[2] & 0xff) << 16) |\n\t ((long)(byteArray[1] & 0xff) << 8) |\n\t ((long)(byteArray[0] & 0xff));\n\t}\n\tpublic final static long[] bytes2longsLE(byte[] byteArray) {\n\t\tif (byteArray.length % 8 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2long: invalid length\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tlong[] result = new long[byteArray.length / 8];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = \n\t\t\t ((long)(byteArray[i * 8 + 7] & 0xff) << 56) |\n\t\t ((long)(byteArray[i * 8 + 6] & 0xff) << 48) |\n\t\t ((long)(byteArray[i * 8 + 5] & 0xff) << 40) |\n\t\t ((long)(byteArray[i * 8 + 4] & 0xff) << 32) |\n\t\t ((long)(byteArray[i * 8 + 3] & 0xff) << 24) |\n\t\t ((long)(byteArray[i * 8 + 2] & 0xff) << 16) |\n\t\t ((long)(byteArray[i * 8 + 1] & 0xff) << 8) |\n\t\t ((long)(byteArray[i * 8 + 0] & 0xff));\n\t\t}\n\t return result;\n\t}\n\tpublic final static long[] ints2longsLE(int[] intArray) {\n\t\tif (intArray.length % 2 != 0) {\n\t\t\tSystem.err.println(\"Converter ints2long: invalid length: \" + intArray.length);\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tlong[] result = new long[intArray.length / 2];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = (long)intArray[i * 2 + 1] << 32 |\n\t\t\t\t\t(long) (intArray[i * 2 + 0] & 0x00000000FFFFFFFFL);\n\t\t}\n\t return result;\n\t}\n\t\n/*\tpublic final static byte[] swapBytes(byte[] byteArray) {\n\t\tbyte[] result = new byte[byteArray.length];\n\t\tint index = result.length -1;\n\t\tfor (int i = 0; i < byteArray.length; i++) {\n\t\t\tresult[index--] = byteArray[i];\n\t\t}\n\t\treturn result;\n\t}*/\n\t\n\tpublic final static long swapEndianOrder (long longValue) {\n\t\treturn\n\t\t\t((((long)longValue) << 56) & 0xff00000000000000L) | \n\t\t\t((((long)longValue) << 40) & 0x00ff000000000000L) | \n\t\t\t((((long)longValue) << 24) & 0x0000ff0000000000L) | \n\t\t\t((((long)longValue) << 8) & 0x000000ff00000000L) | \n\t\t\t((((long)longValue) >> 8) & 0x00000000ff000000L) | \n\t\t\t((((long)longValue) >> 24) & 0x0000000000ff0000L) | \n\t\t\t((((long)longValue) >> 40) & 0x000000000000ff00L) | \n\t\t\t((((long)longValue) >> 56) & 0x00000000000000ffL);\n\t}\n\tpublic final static int swapEndianOrder (int intValue) {\n\t\treturn\n\t\t\t((((int)intValue) << 24) & 0xff000000) | \n\t\t\t((((int)intValue) << 8) & 0x00ff0000) | \n\t\t\t((((int)intValue) >>> 8) & 0x0000ff00) | \n\t\t\t((((int)intValue) >>> 24) & 0x000000ff);\n\t}\n\t\n\t//==============================================\n\t// HEX STRINGS AND BYTE ARRAYS:\n\tpublic final static byte[] hex2bytes(String hexString) {\n\n\t\tbyte[] byteArray = new byte[hexString.length() / 2];// 2 Character = 1 Byte\n\t\t\tint len = hexString.length();\n\t\t\tif ( (len & 1) == 1){ // ungerade\n\t\t\t\tSystem.err.println(\"Illegal Argument (Function hexStringToBytes): HexString is not even\");\n\t\t\t\treturn byteArray; // return null-Array\n\t\t\t}\n\t\t\tfinal char [] hexCharArray = hexString.toCharArray ();// Umwandeln in char-Array\n\t\t\tfor (int i = 0; i < hexString.length(); i+=2) {\n\t\t\t\t// 1. char in hex <<4, 2. char in hex\n\t\t\t\tbyteArray[i / 2] = (byte) ((Character.digit (hexCharArray[i], 16) << 4) \n\t\t\t\t\t\t\t\t+ Character.digit (hexCharArray[i + 1], 16));\n\t\t\t}\t\t\n\t\t\treturn byteArray;\n\t}\n\t\n\tpublic final static char[] hexArray = \"0123456789ABCDEF\".toCharArray();\n\tpublic static String bytes2hex(byte[] bytes) {\n\t char[] hexChars = new char[bytes.length * 2];\n\t for ( int j = 0; j < bytes.length; j++ ) {\n\t int v = bytes[j] & 0xFF;\n\t hexChars[j * 2] = hexArray[v >>> 4];\n\t hexChars[j * 2 + 1] = hexArray[v & 0x0F];\n\t }\n\t return new String(hexChars);\n\t}\n\tprivate static final String HEXES = \"0123456789ABCDEF\";\n\tpublic static String getHex( byte [] raw ) {\n\t final StringBuilder hex = new StringBuilder( 2 * raw.length );\n\t for ( final byte b : raw ) {\n\t hex.append(HEXES.charAt((b & 0xF0) >> 4))\n\t .append(HEXES.charAt((b & 0x0F)));\n\t }\n\t return hex.toString();\n\t // oder: System.out.println(javax.xml.bind.DatatypeConverter.printHexBinary(bytes));\n\t}\n\t\n\t//===========================================\n\t// DOCUMENTS AND BYTE ARRAYS\n\tpublic final static byte[] serialize(DefaultStyledDocument dsd) {\n\n\t\tRTFEditorKit kit = new RTFEditorKit();\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\ttry {\n\t\t\tkit.write( out, dsd, 0, dsd.getLength() );\n\t\t\tout.close();\n\t\t} catch (BadLocationException e) {\n\t\t\tSystem.err.println(\"Converter: \" + e);\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(\"Converter: \" + e);\n\t\t\te.printStackTrace();\n\t\t} \n\t return out.toByteArray();\n\t}\n\tpublic final static DefaultStyledDocument deserialize(byte[] data) {\n\t\tRTFEditorKit kit = new RTFEditorKit();\n\t\tDefaultStyledDocument dsd = new DefaultStyledDocument();\n\t\tByteArrayInputStream in = new ByteArrayInputStream(data);\n\t\ttry {\n\t\t\tkit.read(in, dsd, 0);\n\t\t\tin.close();\n\t\t} catch (BadLocationException e) {\n\t\t\t// \n\t\t\tSystem.err.println(\"Converter deserialize: \"+ e.toString());\n\t\t\treturn null;\n\t\t\t//e.printStackTrace();\n\t\t\t//System.err.println(\"BadLocationException\");\n\t\t} catch (IOException e) {\n\n\t\t\tSystem.err.println(\"Converter deserialize: \"+ e.toString());\n\t\t\treturn null;\n\t\t\t//e.printStackTrace();\n\t\t}\t\t\n\t return dsd;\n\t}\n}",
"public final class WriteResources {\n\t\n\n\t\n\tpublic static void write(byte[] textBytes , String fileName, String dir) {\n\t\t\n\t\t//System.out.println(\"fileName: \" + fileName + \" dir: \" + dir);\n\t\t\n\t\tByteBuffer bytebuff = ByteBuffer.allocate( textBytes.length );\n\t\tbytebuff.clear();\n\t\tbytebuff.put( textBytes );\n\t\tbytebuff.flip();\n\t\t\n\t\tFileOutputStream fos = null;\n\t\tFileChannel chan = null;\n\n\t\tFile file = null;\n\t\tif ( dir == null) {\n\t\t\tfile = new File(fileName);\n\t\t} else {\n\t\t\tfileName = dir + java.io.File.separator+ fileName;\n\t\t\tfile = new File(fileName);\n\t\t}\n\t\tif (dir != null && ! new File(dir).exists()) {\n\t\t\tnew File(dir).mkdirs();\n\t\t}\n\t\tif ( ! file.exists() ) {\t\t\t\n\t\t\t//System.out.println(\"WriteResources: fileName: \" + fileName + \" file getName: \" + file.getPath() );\n\t\t\ttry {\n\t\t\t\tfile.createNewFile();\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\"WriteResources: can not create new file: \" + file.getPath());\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t\t\n\t\ttry {\n\t\t\tfos = new FileOutputStream(file);\n\t\t\tchan = fos.getChannel();\n\t\t\twhile(bytebuff.hasRemaining()) {\n\t\t\t chan.write(bytebuff);\n\t\t\t}\t\t\n\t\t} catch (IOException ioe) {\t\t\t\n\t\t\tSystem.err.println(\"WriteResources: \" + ioe.toString() + \" \" + fileName);\n\t\t\tioe.printStackTrace();\n\t\t} \n\t\tif ( chan != null){\n\t\t\ttry {\n\t\t\t\tchan.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\"WriteResources: \" + e.toString() + \" close() \" + fileName);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tif ( fos != null) {\n\t\t\ttry {\n\t\t\t\tfos.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\"WriteResources: \" + e);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t// Message ausgeben, dass Datei geschrieben wurde\n\t\t//JOptionPane.showMessageDialog(null, \"Die Datei \" + fileName + \" wurde geschrieben.\");\t\n\t}\t\n\t\n\t\n\tpublic static void writeText(String text, String fileName) {\n\t\t//FileWriter fw = null;\n\t\tBufferedWriter buff = null;\n\t\ttry {\n\t\t\t // overwrites file if exists\n\t\t\tbuff = new BufferedWriter(new FileWriter(fileName));\n\t\t\tbuff.write(text);\n\t\t\t\n\t\t\t// Message ausgeben, dass Datei geschrieben wurde\n//\t\t\tJOptionPane.showMessageDialog(null, \"New file: \" + fileName);\n\t\t} catch (IOException ioe) {\n\t\t\tSystem.out.println(\"WriteResources: \" + ioe.getMessage());\n\t\t\tioe.printStackTrace();\n\t\t} finally {\n\t\t\tif (buff != null) {\n\t\t\t\ttry {\n\t\t\t\t\tbuff.close();\n\t\t\t\t} catch (IOException ioe) {\n\t\t\t\t\tSystem.out.println(\"WriteResources: \" + ioe.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"public class Zeroizer {\n\t\n\tprivate static byte zero8bit = 0;\n\tprivate static char zeroChar = '\\0';\n\tprivate static int zero32bit = 0;\n\tprivate static long zero64bit = 0L;\n\t\n\tpublic final static void zero(byte[] input) {\t\t\n\t\tif (input != null && input.length > 0) {\n\t\t\tArrays.fill(input, (byte) 0);\t\t\n\t\t\t/*for (int i = 0; i < input.length; i++) {\n\t\t\t\tzero8bit |= input[i];\n\t\t\t} */\n\t\t\tzero8bit |= input[input.length - 1];\n\t\t}\n\t}\n\tpublic final static void zero(int[] input) {\t\n\t\tif (input != null && input.length > 0) {\n\t\t\tArrays.fill(input, 0);\t\t\n\t\t\t/*for (int i = 0; i < input.length; i++) {\n\t\t\t\tzero32bit |= input[i];\n\t\t\t}*/\n\t\t\tzero32bit |= input[input.length - 1];\n\t\t}\n\t}\t\n\tpublic final static void zero(long[] input) {\t\t\n\t\tif (input != null && input.length > 0) {\n\t\t\tArrays.fill(input, 0);\t\t\n\t\t\t/*for (int i = 0; i < input.length; i++) {\n\t\t\t\tzero64bit |= input[i];\n\t\t\t}*/\n\t\t\tzero64bit |= input[input.length - 1];\n\t\t}\n\t}\t\t\n\tpublic final static void zero(char[] input) {\t\t\t\n\t\t/*for (int i = 0; i < input.length; i++) {\n\t\t\tzeroChar |= input[i];\n\t\t}*/\n\t\tif (input != null && input.length > 0) {\n\t\t\tArrays.fill(input, '\\0');\t\n\t\t\tzeroChar |= input[input.length - 1];\n\t\t}\n\t}\n\t\n\tpublic final static void zero(byte zero) {\n\t\tzero = (byte) 0;\n\t\tzero8bit |= zero;\n\t}\n\tpublic final static void zero(int zero) {\n\t\tzero = 0;\n\t\tzero32bit |= zero;\n\t}\n\tpublic final static void zero(long zero) {\n\t\tzero = (byte) 0;\n\t\tzero64bit |= zero;\n\t}\n\tpublic final static void zero(char zero) {\n\t\tzero = '\\0';\n\t\tzeroChar |= zero;\n\t}\n\tpublic final static void zeroFile(String fileName) {\n\t\tRandomAccessFile raf = null;\n\t\ttry {\n\t\t\traf = new RandomAccessFile(fileName, \"rw\");\n\t\t\tbyte[] zeroBytes = new byte[(int)raf.length()];\n\t\t\traf.seek(0);\n\t\t\traf.write(zeroBytes);\n\t\t\traf.close();\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t\n\t/**\n\t * To check the execution, this function should be \n\t * called as last step before the application exits\n\t */\n\tpublic final static void getZeroizationResult() {\n\t\t\n\t\tif (zeroChar != '\\0') {\n\t\t\tSystem.err.println(\"Zeroization failed - char: \" + zeroChar); \n\t\t}\n\n\t\tif ( (zero8bit != 0) || (zero32bit != 0) || (zero64bit != 0)) {\n\t\t\tSystem.err.println(\"Zeroization failed - \\nbyte: \" + zero8bit \n\t\t\t\t\t+ \"\\nint: \" + zero32bit\n\t\t\t\t\t+ \"\\nlong: \" + zero64bit);\n\t\t} else {\n\t\t\tSystem.out.println(\"Zeroization: success\");\n\t\t}\n\t}\n\t\n\t// Test:\n/*\tpublic static void main(String[] args) {\n\t\t\n\t\tchar[] testChars = \"abcdefghijklmnopqrstuvwxyz\".toCharArray();\n\t\tbyte[] testBytes = new byte[128];\n\t\tArrays.fill(testBytes, (byte) 5);\n\t\tint[] testInts = new int[55];\n\t\tArrays.fill(testInts, 55);\n\t\tlong[] testLongs = new long[33];\n\t\tArrays.fill(testLongs, 33L);\n\t\tbyte b = (byte) 0xFF;\n\t\tint i = 0xFFFFFFFF;\n\t\tlong l = 0xFFFFFFFFFFFFFFFFL;\n\t\tchar c = 'X';\n\t\t\n\t\tzero(testChars);\n\t\tzero(testBytes);\n\t\tzero(testInts);\n\t\tzero(testLongs);\n\t\t\n\t\tzero(b);\n\t\tzero(i);\n\t\tzero(l);\n\t\tzero(c);\n\t\t\n\t\tgetZeroizationResult();\n\t} */\n}"
] | import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import settings.PeaSettings;
import cologne.eck.peafactory.crypto.CipherStuff;
import cologne.eck.peafactory.peas.PswDialogBase;
import cologne.eck.peafactory.peas.gui.LockFrame;
import cologne.eck.peafactory.peas.gui.PswDialogView;
import cologne.eck.peafactory.tools.Converter;
import cologne.eck.peafactory.tools.WriteResources;
import cologne.eck.peafactory.tools.Zeroizer;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent; | package cologne.eck.peafactory.peas.image_pea;
/*
* Peafactory - Production of Password Encryption Archives
* Copyright (C) 2015 Axel von dem Bruch
*
* This library 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 2 of the License,
* or (at your option) any later version.
* This library 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.
* See: http://www.gnu.org/licenses/gpl-2.0.html
* You should have received a copy of the GNU General Public License
* along with this library.
*/
/**
* Main view of image pea.
*/
/*
* Frame to display images, decrypted in PswDialogImage
* (this is not a daughter class of LockFrame!)
*
*/
@SuppressWarnings("serial")
final class LockFrameImage extends LockFrame implements ActionListener {
private static byte[] imageBytes;
private static boolean isInstantiated = false;
private LockFrameImage() {
this.setIconImage(PswDialogView.getImage());
this.addWindowListener(this);// for windowClosing
JPanel contentPane = new JPanel();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
this.setContentPane(contentPane);
JScrollPane scrollPane = null;
// get the image from file name:
BufferedImage image = null;
try {
image = ImageIO.read(new ByteArrayInputStream(imageBytes));
//Arrays.fill(imageBytes, (byte) 0);
} catch (IOException e) {
System.err.println("LockFrameImage: " + e);
e.printStackTrace();
}
if (image == null) { // invalid file
JOptionPane.showMessageDialog(this,
"Invalid or unsuitable image file: \n"
+ PswDialogImage.getEncryptedFileName(),
"Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
// get settings:
int picWidth = PswDialogImage.imageWidth;
int picHeight = PswDialogImage.imageHeight;
int w = picWidth,h = picHeight;
JLabel picLabel = null;
// keep ratio of image width and height if resize == true:
if (PswDialogImage.resize == true) {
double op = 0;
if (image.getWidth() < picWidth) {
op = (double)picWidth / image.getWidth();
if (image.getHeight() * op > picHeight) op = (double)picHeight / image.getHeight();
w = (int) (image.getWidth() * op);
h = (int) (image.getHeight() * op);
} else {
op = image.getWidth() / (double)picWidth;
if ( (image.getHeight() / op) > picHeight) op = image.getHeight() / (double)picHeight;
w = (int) (image.getWidth() / op);
h = (int) (image.getHeight() / op);
}
Image scaledImage = image.getScaledInstance(w, h, Image.SCALE_FAST);
picLabel = new JLabel(new ImageIcon(scaledImage));
scrollPane = new JScrollPane(picLabel);
} else {
picLabel = new JLabel(new ImageIcon(image));
scrollPane = new JScrollPane(picLabel);
scrollPane.setPreferredSize(new Dimension(PswDialogImage.imageWidth, PswDialogImage.imageHeight));
}
contentPane.add(scrollPane);
if (PeaSettings.getExternFile() == true) {
JPanel buttonPanel = new JPanel();
JButton unencryptedButton = new JButton ("close unencrypted");
unencryptedButton.setActionCommand("unencrypted");
unencryptedButton.addActionListener(this);
buttonPanel.add(unencryptedButton);
JButton encryptedButton = new JButton ("close encrypted");
encryptedButton.setActionCommand("encrypted");
encryptedButton.addActionListener(this);
buttonPanel.add(encryptedButton);
JButton passwordButton = new JButton ("change password");
passwordButton.setActionCommand("changePassword");
passwordButton.addActionListener(this);
buttonPanel.add(passwordButton);
contentPane.add(buttonPanel);
}
this.setLocation(100, 100);
pack();
}
protected final static LockFrameImage getInstance() {
LockFrameImage frame = null;
if (isInstantiated == false) {
frame = new LockFrameImage();
} else {
//return null
}
return frame;
}
protected final static void setImageBytes( byte[] input ) {
//imageBytes = input;
imageBytes = new byte[input.length];
System.arraycopy(input, 0, imageBytes, 0, input.length);
}
@Override
public void actionPerformed(ActionEvent ape) {
String command = ape.getActionCommand();
if (command.equals("unencrypted")) {
WriteResources.write(imageBytes, PeaSettings.getExternalFilePath(), null );
Zeroizer.zero(imageBytes);
System.exit(0);
} else if (command.equals("encrypted")){
// file was not modified, just loaded unencrypted in RAM
Zeroizer.zero(imageBytes);
System.exit(0);
} else if (command.equals("changePassword")){
String[] fileNames = {PswDialogBase.getEncryptedFileName()};
changePassword(imageBytes, fileNames);
}
}
@Override
protected void windowClosingCommands() {
// append settings for this image and then encrypt and store
if (PswDialogView.isInitializing() == true) {
// get setting values
int resizeValue = 0;
if (PswDialogImage.resize == true) resizeValue = 1;
int[] settings = new int[3];
settings[0] = PswDialogImage.imageWidth;
settings[1] = PswDialogImage.imageHeight;
settings[2] = resizeValue;
byte[] settingBytes = Converter.ints2bytesBE(settings);;
// append setting values to plaintext
byte[] plainBytes = new byte[imageBytes.length + settingBytes.length];
System.arraycopy(imageBytes, 0, plainBytes, 0, imageBytes.length);
System.arraycopy(settingBytes, 0, plainBytes, imageBytes.length, settingBytes.length);
// encrypt | byte[] cipherBytes = CipherStuff.getInstance().encrypt(plainBytes, null, true); | 1 |
gillius/jalleg | jalleg-framework/src/main/java/org/gillius/jalleg/framework/io/AllegroLoader.java | [
"@SuppressWarnings({\"unused\", \"WeakerAccess\", \"PointlessBitwiseExpression\"})\npublic class AllegroLibrary implements Library {\n\tpublic static final String JNA_LIBRARY_NAME;\n\tpublic static final NativeLibrary JNA_NATIVE_LIB;\n\t/**\n\t * Keep a strong reference to all loaded libraries, so that GC won't close them.\n */\n\t@SuppressWarnings(\"MismatchedQueryAndUpdateOfCollection\")\n\tprivate static final List<NativeLibrary> supportingLibs = new ArrayList<>();\n\tstatic {\n\t\tString libName = null;\n\t\ttry {\n\t\t\tlibName = System.getProperty(\"AL_NAME\");\n\t\t} catch (SecurityException ignored) {}\n\t\tif (libName == null) {\n\t\t\ttry {\n\t\t\t\tlibName = System.getenv(\"AL_NAME\");\n\t\t\t} catch (SecurityException ignored) {}\n\t\t}\n\t\tif (libName == null)\n\t\t\tlibName = \"allegro_monolith-5.2\";\n\t\tNativeLibrary mainLib;\n\t\ttry {\n\t\t\t//First, try to load the monolith library\n\t\t\tmainLib = NativeLibrary.getInstance(libName);\n\t\t} catch (Throwable t) {\n\t\t\tString lastLib = null;\n\t\t\ttry {\n\t\t\t\t//Next, try to load all of the individual libraries:\n\t\t\t\tlastLib = \"allegro\";\n\t\t\t\tsupportingLibs.add(NativeLibrary.getInstance(lastLib));\n\t\t\t\tlastLib = \"allegro_video\";\n\t\t\t\tsupportingLibs.add(NativeLibrary.getInstance(lastLib));\n\t\t\t\tlastLib = \"allegro_ttf\";\n\t\t\t\tsupportingLibs.add(NativeLibrary.getInstance(lastLib));\n\t\t\t\tlastLib = \"allegro_primitives\";\n\t\t\t\tsupportingLibs.add(NativeLibrary.getInstance(lastLib));\n\t\t\t\tlastLib = \"allegro_physfs\";\n\t\t\t\tsupportingLibs.add(NativeLibrary.getInstance(lastLib));\n\t\t\t\tlastLib = \"allegro_memfile\";\n\t\t\t\tsupportingLibs.add(NativeLibrary.getInstance(lastLib));\n\t\t\t\tlastLib = \"allegro_image\";\n\t\t\t\tsupportingLibs.add(NativeLibrary.getInstance(lastLib));\n\t\t\t\tlastLib = \"allegro_font\";\n\t\t\t\tsupportingLibs.add(NativeLibrary.getInstance(lastLib));\n\t\t\t\tlastLib = \"allegro_dialog\";\n\t\t\t\tsupportingLibs.add(NativeLibrary.getInstance(lastLib));\n\t\t\t\tlastLib = \"allegro_color\";\n\t\t\t\tsupportingLibs.add(NativeLibrary.getInstance(lastLib));\n\t\t\t\tlastLib = \"allegro_audio\";\n\t\t\t\tsupportingLibs.add(NativeLibrary.getInstance(lastLib));\n\t\t\t\tlastLib = \"allegro_acodec\";\n\t\t\t\tsupportingLibs.add(NativeLibrary.getInstance(lastLib));\n\t\t\t\tmainLib = NativeLibrary.getProcess();\n\t\t\t\tlibName = \"allegro\"; //only in case someone wants to observe the used JNA_LIBRARY_NAME\n\t\t\t} catch (Throwable t2) {\n\t\t\t\tsupportingLibs.clear();\n\t\t\t\tthrow new AllegroError(\"Unable to load \" + libName + \", or Allegro parts (\" +\n\t\t\t\t lastLib + \"). Ensure Allegro is installed on library loading path, see \" +\n\t\t\t\t \"https://github.com/gillius/jalleg/wiki/Troubleshooting\",\n\t\t\t\t new AllegroError(t2.getMessage(),\n\t\t\t\t t));\n\t\t\t}\n\t\t}\n\n\t\tJNA_LIBRARY_NAME = libName;\n\t\tJNA_NATIVE_LIB = mainLib;\n\t\tNative.register(AllegroLibrary.class, JNA_NATIVE_LIB);\n\t}\n\tpublic interface ALLEGRO_PIXEL_FORMAT {\n\t\tint ALLEGRO_PIXEL_FORMAT_ANY = 0;\n\t\tint ALLEGRO_PIXEL_FORMAT_ANY_NO_ALPHA = 1;\n\t\tint ALLEGRO_PIXEL_FORMAT_ANY_WITH_ALPHA = 2;\n\t\tint ALLEGRO_PIXEL_FORMAT_ANY_15_NO_ALPHA = 3;\n\t\tint ALLEGRO_PIXEL_FORMAT_ANY_16_NO_ALPHA = 4;\n\t\tint ALLEGRO_PIXEL_FORMAT_ANY_16_WITH_ALPHA = 5;\n\t\tint ALLEGRO_PIXEL_FORMAT_ANY_24_NO_ALPHA = 6;\n\t\tint ALLEGRO_PIXEL_FORMAT_ANY_32_NO_ALPHA = 7;\n\t\tint ALLEGRO_PIXEL_FORMAT_ANY_32_WITH_ALPHA = 8;\n\t\tint ALLEGRO_PIXEL_FORMAT_ARGB_8888 = 9;\n\t\tint ALLEGRO_PIXEL_FORMAT_RGBA_8888 = 10;\n\t\tint ALLEGRO_PIXEL_FORMAT_ARGB_4444 = 11;\n\t\tint ALLEGRO_PIXEL_FORMAT_RGB_888 = 12;\n\t\tint ALLEGRO_PIXEL_FORMAT_RGB_565 = 13;\n\t\tint ALLEGRO_PIXEL_FORMAT_RGB_555 = 14;\n\t\tint ALLEGRO_PIXEL_FORMAT_RGBA_5551 = 15;\n\t\tint ALLEGRO_PIXEL_FORMAT_ARGB_1555 = 16;\n\t\tint ALLEGRO_PIXEL_FORMAT_ABGR_8888 = 17;\n\t\tint ALLEGRO_PIXEL_FORMAT_XBGR_8888 = 18;\n\t\tint ALLEGRO_PIXEL_FORMAT_BGR_888 = 19;\n\t\tint ALLEGRO_PIXEL_FORMAT_BGR_565 = 20;\n\t\tint ALLEGRO_PIXEL_FORMAT_BGR_555 = 21;\n\t\tint ALLEGRO_PIXEL_FORMAT_RGBX_8888 = 22;\n\t\tint ALLEGRO_PIXEL_FORMAT_XRGB_8888 = 23;\n\t\tint ALLEGRO_PIXEL_FORMAT_ABGR_F32 = 24;\n\t\tint ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE = 25;\n\t\tint ALLEGRO_PIXEL_FORMAT_RGBA_4444 = 26;\n\t\tint ALLEGRO_PIXEL_FORMAT_SINGLE_CHANNEL_8 = 27;\n\t\tint ALLEGRO_PIXEL_FORMAT_COMPRESSED_RGBA_DXT1 = 28;\n\t\tint ALLEGRO_PIXEL_FORMAT_COMPRESSED_RGBA_DXT3 = 29;\n\t\tint ALLEGRO_PIXEL_FORMAT_COMPRESSED_RGBA_DXT5 = 30;\n\t\tint ALLEGRO_NUM_PIXEL_FORMATS = 31;\n\t}\n\n\tpublic static final int ALLEGRO_MEMORY_BITMAP = 0x0001;\n\tpublic static final int _ALLEGRO_KEEP_BITMAP_FORMAT = 0x0002;\n\tpublic static final int ALLEGRO_FORCE_LOCKING = 0x0004;\n\tpublic static final int ALLEGRO_NO_PRESERVE_TEXTURE = 0x0008;\n\tpublic static final int _ALLEGRO_ALPHA_TEST = 0x0010;\n\tpublic static final int _ALLEGRO_INTERNAL_OPENGL = 0x0020;\n\tpublic static final int ALLEGRO_MIN_LINEAR = 0x0040;\n\tpublic static final int ALLEGRO_MAG_LINEAR = 0x0080;\n\tpublic static final int ALLEGRO_MIPMAP = 0x0100;\n\tpublic static final int _ALLEGRO_NO_PREMULTIPLIED_ALPHA = 0x0200;\n\tpublic static final int ALLEGRO_VIDEO_BITMAP = 0x0400;\n\tpublic static final int ALLEGRO_CONVERT_BITMAP = 0x1000;\n\tpublic static final int ALLEGRO_FLIP_HORIZONTAL = 0x00001;\n\tpublic static final int ALLEGRO_FLIP_VERTICAL = 0x00002;\n\tpublic interface ALLEGRO_SEEK {\n\t\tint ALLEGRO_SEEK_SET = 0;\n\t\tint ALLEGRO_SEEK_CUR = 1;\n\t\tint ALLEGRO_SEEK_END = 2;\n\t}\n\n\tpublic static final int ALLEGRO_KEEP_BITMAP_FORMAT = 0x0002;\n\tpublic static final int ALLEGRO_NO_PREMULTIPLIED_ALPHA = 0x0200;\n\tpublic static final int ALLEGRO_KEEP_INDEX = 0x0800;\n\tpublic static final int ALLEGRO_LOCK_READWRITE = 0;\n\tpublic static final int ALLEGRO_LOCK_READONLY = 1;\n\tpublic static final int ALLEGRO_LOCK_WRITEONLY = 2;\n\tpublic interface ALLEGRO_BLEND_MODE {\n\t\tint ALLEGRO_ZERO = 0;\n\t\tint ALLEGRO_ONE = 1;\n\t\tint ALLEGRO_ALPHA = 2;\n\t\tint ALLEGRO_INVERSE_ALPHA = 3;\n\t\tint ALLEGRO_SRC_COLOR = 4;\n\t\tint ALLEGRO_DEST_COLOR = 5;\n\t\tint ALLEGRO_INVERSE_SRC_COLOR = 6;\n\t\tint ALLEGRO_INVERSE_DEST_COLOR = 7;\n\t\tint ALLEGRO_CONST_COLOR = 8;\n\t\tint ALLEGRO_INVERSE_CONST_COLOR = 9;\n\t\tint ALLEGRO_NUM_BLEND_MODES = 10;\n\t}\n\n\tpublic interface ALLEGRO_BLEND_OPERATIONS {\n\t\tint ALLEGRO_ADD = 0;\n\t\tint ALLEGRO_SRC_MINUS_DEST = 1;\n\t\tint ALLEGRO_DEST_MINUS_SRC = 2;\n\t\tint ALLEGRO_NUM_BLEND_OPERATIONS = 3;\n\t}\n\n\tpublic static final int ALLEGRO_EVENT_JOYSTICK_AXIS = 1;\n\tpublic static final int ALLEGRO_EVENT_JOYSTICK_BUTTON_DOWN = 2;\n\tpublic static final int ALLEGRO_EVENT_JOYSTICK_BUTTON_UP = 3;\n\tpublic static final int ALLEGRO_EVENT_JOYSTICK_CONFIGURATION = 4;\n\tpublic static final int ALLEGRO_EVENT_KEY_DOWN = 10;\n\tpublic static final int ALLEGRO_EVENT_KEY_CHAR = 11;\n\tpublic static final int ALLEGRO_EVENT_KEY_UP = 12;\n\tpublic static final int ALLEGRO_EVENT_MOUSE_AXES = 20;\n\tpublic static final int ALLEGRO_EVENT_MOUSE_BUTTON_DOWN = 21;\n\tpublic static final int ALLEGRO_EVENT_MOUSE_BUTTON_UP = 22;\n\tpublic static final int ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY = 23;\n\tpublic static final int ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY = 24;\n\tpublic static final int ALLEGRO_EVENT_MOUSE_WARPED = 25;\n\tpublic static final int ALLEGRO_EVENT_TIMER = 30;\n\tpublic static final int ALLEGRO_EVENT_DISPLAY_EXPOSE = 40;\n\tpublic static final int ALLEGRO_EVENT_DISPLAY_RESIZE = 41;\n\tpublic static final int ALLEGRO_EVENT_DISPLAY_CLOSE = 42;\n\tpublic static final int ALLEGRO_EVENT_DISPLAY_LOST = 43;\n\tpublic static final int ALLEGRO_EVENT_DISPLAY_FOUND = 44;\n\tpublic static final int ALLEGRO_EVENT_DISPLAY_SWITCH_IN = 45;\n\tpublic static final int ALLEGRO_EVENT_DISPLAY_SWITCH_OUT = 46;\n\tpublic static final int ALLEGRO_EVENT_DISPLAY_ORIENTATION = 47;\n\tpublic static final int ALLEGRO_EVENT_DISPLAY_HALT_DRAWING = 48;\n\tpublic static final int ALLEGRO_EVENT_DISPLAY_RESUME_DRAWING = 49;\n\tpublic static final int ALLEGRO_EVENT_TOUCH_BEGIN = 50;\n\tpublic static final int ALLEGRO_EVENT_TOUCH_END = 51;\n\tpublic static final int ALLEGRO_EVENT_TOUCH_MOVE = 52;\n\tpublic static final int ALLEGRO_EVENT_TOUCH_CANCEL = 53;\n\tpublic static final int ALLEGRO_EVENT_DISPLAY_CONNECTED = 60;\n\tpublic static final int ALLEGRO_EVENT_DISPLAY_DISCONNECTED = 61;\n\tpublic static final int ALLEGRO_WINDOWED = 1 << 0;\n\tpublic static final int ALLEGRO_FULLSCREEN = 1 << 1;\n\tpublic static final int ALLEGRO_OPENGL = 1 << 2;\n\tpublic static final int ALLEGRO_DIRECT3D_INTERNAL = 1 << 3;\n\tpublic static final int ALLEGRO_RESIZABLE = 1 << 4;\n\tpublic static final int ALLEGRO_FRAMELESS = 1 << 5;\n\tpublic static final int ALLEGRO_NOFRAME = (int)AllegroLibrary.ALLEGRO_FRAMELESS;\n\tpublic static final int ALLEGRO_GENERATE_EXPOSE_EVENTS = 1 << 6;\n\tpublic static final int ALLEGRO_OPENGL_3_0 = 1 << 7;\n\tpublic static final int ALLEGRO_OPENGL_FORWARD_COMPATIBLE = 1 << 8;\n\tpublic static final int ALLEGRO_FULLSCREEN_WINDOW = 1 << 9;\n\tpublic static final int ALLEGRO_MINIMIZED = 1 << 10;\n\tpublic static final int ALLEGRO_PROGRAMMABLE_PIPELINE = 1 << 11;\n\tpublic static final int ALLEGRO_GTK_TOPLEVEL_INTERNAL = 1 << 12;\n\tpublic static final int ALLEGRO_MAXIMIZED = 1 << 13;\n\tpublic static final int ALLEGRO_OPENGL_ES_PROFILE = 1 << 14;\n\tpublic interface ALLEGRO_DISPLAY_OPTIONS {\n\t\tint ALLEGRO_RED_SIZE = 0;\n\t\tint ALLEGRO_GREEN_SIZE = 1;\n\t\tint ALLEGRO_BLUE_SIZE = 2;\n\t\tint ALLEGRO_ALPHA_SIZE = 3;\n\t\tint ALLEGRO_RED_SHIFT = 4;\n\t\tint ALLEGRO_GREEN_SHIFT = 5;\n\t\tint ALLEGRO_BLUE_SHIFT = 6;\n\t\tint ALLEGRO_ALPHA_SHIFT = 7;\n\t\tint ALLEGRO_ACC_RED_SIZE = 8;\n\t\tint ALLEGRO_ACC_GREEN_SIZE = 9;\n\t\tint ALLEGRO_ACC_BLUE_SIZE = 10;\n\t\tint ALLEGRO_ACC_ALPHA_SIZE = 11;\n\t\tint ALLEGRO_STEREO = 12;\n\t\tint ALLEGRO_AUX_BUFFERS = 13;\n\t\tint ALLEGRO_COLOR_SIZE = 14;\n\t\tint ALLEGRO_DEPTH_SIZE = 15;\n\t\tint ALLEGRO_STENCIL_SIZE = 16;\n\t\tint ALLEGRO_SAMPLE_BUFFERS = 17;\n\t\tint ALLEGRO_SAMPLES = 18;\n\t\tint ALLEGRO_RENDER_METHOD = 19;\n\t\tint ALLEGRO_FLOAT_COLOR = 20;\n\t\tint ALLEGRO_FLOAT_DEPTH = 21;\n\t\tint ALLEGRO_SINGLE_BUFFER = 22;\n\t\tint ALLEGRO_SWAP_METHOD = 23;\n\t\tint ALLEGRO_COMPATIBLE_DISPLAY = 24;\n\t\tint ALLEGRO_UPDATE_DISPLAY_REGION = 25;\n\t\tint ALLEGRO_VSYNC = 26;\n\t\tint ALLEGRO_MAX_BITMAP_SIZE = 27;\n\t\tint ALLEGRO_SUPPORT_NPOT_BITMAP = 28;\n\t\tint ALLEGRO_CAN_DRAW_INTO_BITMAP = 29;\n\t\tint ALLEGRO_SUPPORT_SEPARATE_ALPHA = 30;\n\t\tint ALLEGRO_AUTO_CONVERT_BITMAPS = 31;\n\t\tint ALLEGRO_SUPPORTED_ORIENTATIONS = 32;\n\t\tint ALLEGRO_OPENGL_MAJOR_VERSION = 33;\n\t\tint ALLEGRO_OPENGL_MINOR_VERSION = 34;\n\t\tint ALLEGRO_DISPLAY_OPTIONS_COUNT = 35;\n\t}\n\n\tpublic static final int ALLEGRO_DONTCARE = 0;\n\tpublic static final int ALLEGRO_REQUIRE = 1;\n\tpublic static final int ALLEGRO_SUGGEST = 2;\n\tpublic interface ALLEGRO_DISPLAY_ORIENTATION {\n\t\tint ALLEGRO_DISPLAY_ORIENTATION_UNKNOWN = 0;\n\t\tint ALLEGRO_DISPLAY_ORIENTATION_0_DEGREES = 1;\n\t\tint ALLEGRO_DISPLAY_ORIENTATION_90_DEGREES = 2;\n\t\tint ALLEGRO_DISPLAY_ORIENTATION_180_DEGREES = 4;\n\t\tint ALLEGRO_DISPLAY_ORIENTATION_270_DEGREES = 8;\n\t\tint ALLEGRO_DISPLAY_ORIENTATION_PORTRAIT = 5;\n\t\tint ALLEGRO_DISPLAY_ORIENTATION_LANDSCAPE = 10;\n\t\tint ALLEGRO_DISPLAY_ORIENTATION_ALL = 15;\n\t\tint ALLEGRO_DISPLAY_ORIENTATION_FACE_UP = 16;\n\t\tint ALLEGRO_DISPLAY_ORIENTATION_FACE_DOWN = 32;\n\t}\n\n\tpublic static final int _ALLEGRO_PRIM_MAX_USER_ATTR = 10;\n\tpublic interface ALLEGRO_FILE_MODE {\n\t\tint ALLEGRO_FILEMODE_READ = 1;\n\t\tint ALLEGRO_FILEMODE_WRITE = 1 << 1;\n\t\tint ALLEGRO_FILEMODE_EXECUTE = 1 << 2;\n\t\tint ALLEGRO_FILEMODE_HIDDEN = 1 << 3;\n\t\tint ALLEGRO_FILEMODE_ISFILE = 1 << 4;\n\t\tint ALLEGRO_FILEMODE_ISDIR = 1 << 5;\n\t}\n\n\tpublic interface ALLEGRO_FOR_EACH_FS_ENTRY_RESULT {\n\t\tint ALLEGRO_FOR_EACH_FS_ENTRY_ERROR = -1;\n\t\tint ALLEGRO_FOR_EACH_FS_ENTRY_OK = 0;\n\t\tint ALLEGRO_FOR_EACH_FS_ENTRY_SKIP = 1;\n\t\tint ALLEGRO_FOR_EACH_FS_ENTRY_STOP = 2;\n\t}\n\n\tpublic interface ALLEGRO_JOYFLAGS {\n\t\tint ALLEGRO_JOYFLAG_DIGITAL = 0x01;\n\t\tint ALLEGRO_JOYFLAG_ANALOGUE = 0x02;\n\t}\n\n\tpublic static final int ALLEGRO_KEY_A = 1;\n\tpublic static final int ALLEGRO_KEY_B = 2;\n\tpublic static final int ALLEGRO_KEY_C = 3;\n\tpublic static final int ALLEGRO_KEY_D = 4;\n\tpublic static final int ALLEGRO_KEY_E = 5;\n\tpublic static final int ALLEGRO_KEY_F = 6;\n\tpublic static final int ALLEGRO_KEY_G = 7;\n\tpublic static final int ALLEGRO_KEY_H = 8;\n\tpublic static final int ALLEGRO_KEY_I = 9;\n\tpublic static final int ALLEGRO_KEY_J = 10;\n\tpublic static final int ALLEGRO_KEY_K = 11;\n\tpublic static final int ALLEGRO_KEY_L = 12;\n\tpublic static final int ALLEGRO_KEY_M = 13;\n\tpublic static final int ALLEGRO_KEY_N = 14;\n\tpublic static final int ALLEGRO_KEY_O = 15;\n\tpublic static final int ALLEGRO_KEY_P = 16;\n\tpublic static final int ALLEGRO_KEY_Q = 17;\n\tpublic static final int ALLEGRO_KEY_R = 18;\n\tpublic static final int ALLEGRO_KEY_S = 19;\n\tpublic static final int ALLEGRO_KEY_T = 20;\n\tpublic static final int ALLEGRO_KEY_U = 21;\n\tpublic static final int ALLEGRO_KEY_V = 22;\n\tpublic static final int ALLEGRO_KEY_W = 23;\n\tpublic static final int ALLEGRO_KEY_X = 24;\n\tpublic static final int ALLEGRO_KEY_Y = 25;\n\tpublic static final int ALLEGRO_KEY_Z = 26;\n\tpublic static final int ALLEGRO_KEY_0 = 27;\n\tpublic static final int ALLEGRO_KEY_1 = 28;\n\tpublic static final int ALLEGRO_KEY_2 = 29;\n\tpublic static final int ALLEGRO_KEY_3 = 30;\n\tpublic static final int ALLEGRO_KEY_4 = 31;\n\tpublic static final int ALLEGRO_KEY_5 = 32;\n\tpublic static final int ALLEGRO_KEY_6 = 33;\n\tpublic static final int ALLEGRO_KEY_7 = 34;\n\tpublic static final int ALLEGRO_KEY_8 = 35;\n\tpublic static final int ALLEGRO_KEY_9 = 36;\n\tpublic static final int ALLEGRO_KEY_PAD_0 = 37;\n\tpublic static final int ALLEGRO_KEY_PAD_1 = 38;\n\tpublic static final int ALLEGRO_KEY_PAD_2 = 39;\n\tpublic static final int ALLEGRO_KEY_PAD_3 = 40;\n\tpublic static final int ALLEGRO_KEY_PAD_4 = 41;\n\tpublic static final int ALLEGRO_KEY_PAD_5 = 42;\n\tpublic static final int ALLEGRO_KEY_PAD_6 = 43;\n\tpublic static final int ALLEGRO_KEY_PAD_7 = 44;\n\tpublic static final int ALLEGRO_KEY_PAD_8 = 45;\n\tpublic static final int ALLEGRO_KEY_PAD_9 = 46;\n\tpublic static final int ALLEGRO_KEY_F1 = 47;\n\tpublic static final int ALLEGRO_KEY_F2 = 48;\n\tpublic static final int ALLEGRO_KEY_F3 = 49;\n\tpublic static final int ALLEGRO_KEY_F4 = 50;\n\tpublic static final int ALLEGRO_KEY_F5 = 51;\n\tpublic static final int ALLEGRO_KEY_F6 = 52;\n\tpublic static final int ALLEGRO_KEY_F7 = 53;\n\tpublic static final int ALLEGRO_KEY_F8 = 54;\n\tpublic static final int ALLEGRO_KEY_F9 = 55;\n\tpublic static final int ALLEGRO_KEY_F10 = 56;\n\tpublic static final int ALLEGRO_KEY_F11 = 57;\n\tpublic static final int ALLEGRO_KEY_F12 = 58;\n\tpublic static final int ALLEGRO_KEY_ESCAPE = 59;\n\tpublic static final int ALLEGRO_KEY_TILDE = 60;\n\tpublic static final int ALLEGRO_KEY_MINUS = 61;\n\tpublic static final int ALLEGRO_KEY_EQUALS = 62;\n\tpublic static final int ALLEGRO_KEY_BACKSPACE = 63;\n\tpublic static final int ALLEGRO_KEY_TAB = 64;\n\tpublic static final int ALLEGRO_KEY_OPENBRACE = 65;\n\tpublic static final int ALLEGRO_KEY_CLOSEBRACE = 66;\n\tpublic static final int ALLEGRO_KEY_ENTER = 67;\n\tpublic static final int ALLEGRO_KEY_SEMICOLON = 68;\n\tpublic static final int ALLEGRO_KEY_QUOTE = 69;\n\tpublic static final int ALLEGRO_KEY_BACKSLASH = 70;\n\tpublic static final int ALLEGRO_KEY_BACKSLASH2 = 71;\n\tpublic static final int ALLEGRO_KEY_COMMA = 72;\n\tpublic static final int ALLEGRO_KEY_FULLSTOP = 73;\n\tpublic static final int ALLEGRO_KEY_SLASH = 74;\n\tpublic static final int ALLEGRO_KEY_SPACE = 75;\n\tpublic static final int ALLEGRO_KEY_INSERT = 76;\n\tpublic static final int ALLEGRO_KEY_DELETE = 77;\n\tpublic static final int ALLEGRO_KEY_HOME = 78;\n\tpublic static final int ALLEGRO_KEY_END = 79;\n\tpublic static final int ALLEGRO_KEY_PGUP = 80;\n\tpublic static final int ALLEGRO_KEY_PGDN = 81;\n\tpublic static final int ALLEGRO_KEY_LEFT = 82;\n\tpublic static final int ALLEGRO_KEY_RIGHT = 83;\n\tpublic static final int ALLEGRO_KEY_UP = 84;\n\tpublic static final int ALLEGRO_KEY_DOWN = 85;\n\tpublic static final int ALLEGRO_KEY_PAD_SLASH = 86;\n\tpublic static final int ALLEGRO_KEY_PAD_ASTERISK = 87;\n\tpublic static final int ALLEGRO_KEY_PAD_MINUS = 88;\n\tpublic static final int ALLEGRO_KEY_PAD_PLUS = 89;\n\tpublic static final int ALLEGRO_KEY_PAD_DELETE = 90;\n\tpublic static final int ALLEGRO_KEY_PAD_ENTER = 91;\n\tpublic static final int ALLEGRO_KEY_PRINTSCREEN = 92;\n\tpublic static final int ALLEGRO_KEY_PAUSE = 93;\n\tpublic static final int ALLEGRO_KEY_ABNT_C1 = 94;\n\tpublic static final int ALLEGRO_KEY_YEN = 95;\n\tpublic static final int ALLEGRO_KEY_KANA = 96;\n\tpublic static final int ALLEGRO_KEY_CONVERT = 97;\n\tpublic static final int ALLEGRO_KEY_NOCONVERT = 98;\n\tpublic static final int ALLEGRO_KEY_AT = 99;\n\tpublic static final int ALLEGRO_KEY_CIRCUMFLEX = 100;\n\tpublic static final int ALLEGRO_KEY_COLON2 = 101;\n\tpublic static final int ALLEGRO_KEY_KANJI = 102;\n\tpublic static final int ALLEGRO_KEY_PAD_EQUALS = 103;\n\tpublic static final int ALLEGRO_KEY_BACKQUOTE = 104;\n\tpublic static final int ALLEGRO_KEY_SEMICOLON2 = 105;\n\tpublic static final int ALLEGRO_KEY_COMMAND = 106;\n\tpublic static final int ALLEGRO_KEY_BACK = 107;\n\tpublic static final int ALLEGRO_KEY_VOLUME_UP = 108;\n\tpublic static final int ALLEGRO_KEY_VOLUME_DOWN = 109;\n\tpublic static final int ALLEGRO_KEY_SEARCH = 110;\n\tpublic static final int ALLEGRO_KEY_DPAD_CENTER = 111;\n\tpublic static final int ALLEGRO_KEY_BUTTON_X = 112;\n\tpublic static final int ALLEGRO_KEY_BUTTON_Y = 113;\n\tpublic static final int ALLEGRO_KEY_DPAD_UP = 114;\n\tpublic static final int ALLEGRO_KEY_DPAD_DOWN = 115;\n\tpublic static final int ALLEGRO_KEY_DPAD_LEFT = 116;\n\tpublic static final int ALLEGRO_KEY_DPAD_RIGHT = 117;\n\tpublic static final int ALLEGRO_KEY_SELECT = 118;\n\tpublic static final int ALLEGRO_KEY_START = 119;\n\tpublic static final int ALLEGRO_KEY_BUTTON_L1 = 120;\n\tpublic static final int ALLEGRO_KEY_BUTTON_R1 = 121;\n\tpublic static final int ALLEGRO_KEY_BUTTON_L2 = 122;\n\tpublic static final int ALLEGRO_KEY_BUTTON_R2 = 123;\n\tpublic static final int ALLEGRO_KEY_BUTTON_A = 124;\n\tpublic static final int ALLEGRO_KEY_BUTTON_B = 125;\n\tpublic static final int ALLEGRO_KEY_THUMBL = 126;\n\tpublic static final int ALLEGRO_KEY_THUMBR = 127;\n\tpublic static final int ALLEGRO_KEY_UNKNOWN = 128;\n\tpublic static final int ALLEGRO_KEY_MODIFIERS = 215;\n\tpublic static final int ALLEGRO_KEY_LSHIFT = 215;\n\tpublic static final int ALLEGRO_KEY_RSHIFT = 216;\n\tpublic static final int ALLEGRO_KEY_LCTRL = 217;\n\tpublic static final int ALLEGRO_KEY_RCTRL = 218;\n\tpublic static final int ALLEGRO_KEY_ALT = 219;\n\tpublic static final int ALLEGRO_KEY_ALTGR = 220;\n\tpublic static final int ALLEGRO_KEY_LWIN = 221;\n\tpublic static final int ALLEGRO_KEY_RWIN = 222;\n\tpublic static final int ALLEGRO_KEY_MENU = 223;\n\tpublic static final int ALLEGRO_KEY_SCROLLLOCK = 224;\n\tpublic static final int ALLEGRO_KEY_NUMLOCK = 225;\n\tpublic static final int ALLEGRO_KEY_CAPSLOCK = 226;\n\tpublic static final int ALLEGRO_KEY_MAX = 227;\n\tpublic static final int ALLEGRO_KEYMOD_SHIFT = 0x00001;\n\tpublic static final int ALLEGRO_KEYMOD_CTRL = 0x00002;\n\tpublic static final int ALLEGRO_KEYMOD_ALT = 0x00004;\n\tpublic static final int ALLEGRO_KEYMOD_LWIN = 0x00008;\n\tpublic static final int ALLEGRO_KEYMOD_RWIN = 0x00010;\n\tpublic static final int ALLEGRO_KEYMOD_MENU = 0x00020;\n\tpublic static final int ALLEGRO_KEYMOD_ALTGR = 0x00040;\n\tpublic static final int ALLEGRO_KEYMOD_COMMAND = 0x00080;\n\tpublic static final int ALLEGRO_KEYMOD_SCROLLLOCK = 0x00100;\n\tpublic static final int ALLEGRO_KEYMOD_NUMLOCK = 0x00200;\n\tpublic static final int ALLEGRO_KEYMOD_CAPSLOCK = 0x00400;\n\tpublic static final int ALLEGRO_KEYMOD_INALTSEQ = 0x00800;\n\tpublic static final int ALLEGRO_KEYMOD_ACCENT1 = 0x01000;\n\tpublic static final int ALLEGRO_KEYMOD_ACCENT2 = 0x02000;\n\tpublic static final int ALLEGRO_KEYMOD_ACCENT3 = 0x04000;\n\tpublic static final int ALLEGRO_KEYMOD_ACCENT4 = 0x08000;\n\tpublic static final int ALLEGRO_DEFAULT_DISPLAY_ADAPTER = -1;\n\tpublic interface ALLEGRO_SYSTEM_MOUSE_CURSOR {\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_NONE = 0;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT = 1;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_ARROW = 2;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_BUSY = 3;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_QUESTION = 4;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_EDIT = 5;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_MOVE = 6;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_N = 7;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_W = 8;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_S = 9;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_E = 10;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NW = 11;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_SW = 12;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_SE = 13;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NE = 14;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_PROGRESS = 15;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_PRECISION = 16;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_LINK = 17;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_ALT_SELECT = 18;\n\t\tint ALLEGRO_SYSTEM_MOUSE_CURSOR_UNAVAILABLE = 19;\n\t\tint ALLEGRO_NUM_SYSTEM_MOUSE_CURSORS = 20;\n\t}\n\n\tpublic interface ALLEGRO_RENDER_STATE {\n\t\tint ALLEGRO_ALPHA_TEST = 0x0010;\n\t\tint ALLEGRO_WRITE_MASK = (0x0010 + 1);\n\t\tint ALLEGRO_DEPTH_TEST = (0x0010 + 2);\n\t\tint ALLEGRO_DEPTH_FUNCTION = (0x0010 + 3);\n\t\tint ALLEGRO_ALPHA_FUNCTION = (0x0010 + 4);\n\t\tint ALLEGRO_ALPHA_TEST_VALUE = (0x0010 + 5);\n\t}\n\n\tpublic interface ALLEGRO_RENDER_FUNCTION {\n\t\tint ALLEGRO_RENDER_NEVER = 0;\n\t\tint ALLEGRO_RENDER_ALWAYS = 1;\n\t\tint ALLEGRO_RENDER_LESS = 2;\n\t\tint ALLEGRO_RENDER_EQUAL = 3;\n\t\tint ALLEGRO_RENDER_LESS_EQUAL = 4;\n\t\tint ALLEGRO_RENDER_GREATER = 5;\n\t\tint ALLEGRO_RENDER_NOT_EQUAL = 6;\n\t\tint ALLEGRO_RENDER_GREATER_EQUAL = 7;\n\t}\n\n\tpublic interface ALLEGRO_WRITE_MASK_FLAGS {\n\t\tint ALLEGRO_MASK_RED = 1 << 0;\n\t\tint ALLEGRO_MASK_GREEN = 1 << 1;\n\t\tint ALLEGRO_MASK_BLUE = 1 << 2;\n\t\tint ALLEGRO_MASK_ALPHA = 1 << 3;\n\t\tint ALLEGRO_MASK_DEPTH = 1 << 4;\n\t\tint ALLEGRO_MASK_RGB = (ALLEGRO_WRITE_MASK_FLAGS.ALLEGRO_MASK_RED | ALLEGRO_WRITE_MASK_FLAGS.ALLEGRO_MASK_GREEN | ALLEGRO_WRITE_MASK_FLAGS.ALLEGRO_MASK_BLUE);\n\t\tint ALLEGRO_MASK_RGBA = (ALLEGRO_WRITE_MASK_FLAGS.ALLEGRO_MASK_RGB | ALLEGRO_WRITE_MASK_FLAGS.ALLEGRO_MASK_ALPHA);\n\t}\n\n\tpublic interface ALLEGRO_SHADER_TYPE {\n\t\tint ALLEGRO_VERTEX_SHADER = 1;\n\t\tint ALLEGRO_PIXEL_SHADER = 2;\n\t}\n\n\tpublic interface ALLEGRO_SHADER_PLATFORM {\n\t\tint ALLEGRO_SHADER_AUTO = 0;\n\t\tint ALLEGRO_SHADER_GLSL = 1;\n\t\tint ALLEGRO_SHADER_HLSL = 2;\n\t}\n\n\tpublic static final int ALLEGRO_RESOURCES_PATH = 0;\n\tpublic static final int ALLEGRO_TEMP_PATH = 1;\n\tpublic static final int ALLEGRO_USER_DATA_PATH = 2;\n\tpublic static final int ALLEGRO_USER_HOME_PATH = 3;\n\tpublic static final int ALLEGRO_USER_SETTINGS_PATH = 4;\n\tpublic static final int ALLEGRO_USER_DOCUMENTS_PATH = 5;\n\tpublic static final int ALLEGRO_EXENAME_PATH = 6;\n\tpublic static final int ALLEGRO_LAST_PATH = 7;\n\tpublic interface ALLEGRO_STATE_FLAGS {\n\t\tint ALLEGRO_STATE_NEW_DISPLAY_PARAMETERS = 0x0001;\n\t\tint ALLEGRO_STATE_NEW_BITMAP_PARAMETERS = 0x0002;\n\t\tint ALLEGRO_STATE_DISPLAY = 0x0004;\n\t\tint ALLEGRO_STATE_TARGET_BITMAP = 0x0008;\n\t\tint ALLEGRO_STATE_BLENDER = 0x0010;\n\t\tint ALLEGRO_STATE_NEW_FILE_INTERFACE = 0x0020;\n\t\tint ALLEGRO_STATE_TRANSFORM = 0x0040;\n\t\tint ALLEGRO_STATE_PROJECTION_TRANSFORM = 0x0100;\n\t\tint ALLEGRO_STATE_BITMAP = ALLEGRO_STATE_FLAGS.ALLEGRO_STATE_TARGET_BITMAP + ALLEGRO_STATE_FLAGS.ALLEGRO_STATE_NEW_BITMAP_PARAMETERS;\n\t\tint ALLEGRO_STATE_ALL = 0xffff;\n\t}\n\n\tpublic static final int ALLEGRO_VERSION = (int)5;\n\tpublic static final int ALLEGRO_SUB_VERSION = (int)2;\n\tpublic static final int ALLEGRO_WIP_VERSION = (int)0;\n\tpublic static final int ALLEGRO_UNSTABLE_BIT = (int)0;\n\tpublic static final int ALLEGRO_RELEASE_NUMBER = (int)1;\n\tpublic static final String ALLEGRO_VERSION_STR = (String)\"5.2.0\";\n\tpublic static final String ALLEGRO_DATE_STR = (String)\"2016\";\n\tpublic static final int ALLEGRO_DATE = (int)20160401;\n\tpublic static final int ALLEGRO_VERSION_INT = (int)((5 << 24) | (2 << 16) | (0 << 8) | 1 | 0);\n\tpublic static final double ALLEGRO_PI = (double)3.14159265358979323846;\n\tpublic static final char ALLEGRO_NATIVE_PATH_SEP = (char)'\\\\';\n\tpublic static final char ALLEGRO_NATIVE_DRIVE_SEP = (char)':';\n\tpublic static final int ALLEGRO_NEW_WINDOW_TITLE_MAX_SIZE = (int)255;\n\tpublic static final int EOF = (int)(-1);\n\tpublic static final int _AL_MAX_JOYSTICK_AXES = (int)3;\n\tpublic static final int _AL_MAX_JOYSTICK_STICKS = (int)16;\n\tpublic static final int _AL_MAX_JOYSTICK_BUTTONS = (int)32;\n\tpublic static final int ALLEGRO_MOUSE_MAX_EXTRA_AXES = (int)4;\n\tpublic static final int ALLEGRO_TOUCH_INPUT_MAX_TOUCH_COUNT = (int)16;\n\tpublic static final String ALLEGRO_SHADER_VAR_COLOR = (String)\"al_color\";\n\tpublic static final String ALLEGRO_SHADER_VAR_POS = (String)\"al_pos\";\n\tpublic static final String ALLEGRO_SHADER_VAR_PROJVIEW_MATRIX = (String)\"al_projview_matrix\";\n\tpublic static final String ALLEGRO_SHADER_VAR_TEX = (String)\"al_tex\";\n\tpublic static final String ALLEGRO_SHADER_VAR_TEXCOORD = (String)\"al_texcoord\";\n\tpublic static final String ALLEGRO_SHADER_VAR_TEX_MATRIX = (String)\"al_tex_matrix\";\n\tpublic static final String ALLEGRO_SHADER_VAR_USER_ATTR = (String)\"al_user_attr_\";\n\tpublic static final String ALLEGRO_SHADER_VAR_USE_TEX = (String)\"al_use_tex\";\n\tpublic static final String ALLEGRO_SHADER_VAR_USE_TEX_MATRIX = (String)\"al_use_tex_matrix\";\n\tpublic interface al_run_main_arg1_callback extends Callback {\n\t\tint apply(int int1, Pointer charPtrPtr1);\n\t}\n\n\tpublic interface ALLEGRO_IIO_LOADER_FUNCTION extends Callback {\n\t\tPointerByReference apply(Pointer filename, int flags);\n\t}\n\n\tpublic interface ALLEGRO_IIO_FS_LOADER_FUNCTION extends Callback {\n\t\tPointerByReference apply(Pointer fp, int flags);\n\t}\n\n\tpublic interface ALLEGRO_IIO_SAVER_FUNCTION extends Callback {\n\t\tbyte apply(Pointer filename, Pointer bitmap);\n\t}\n\n\tpublic interface ALLEGRO_IIO_FS_SAVER_FUNCTION extends Callback {\n\t\tbyte apply(Pointer fp, Pointer bitmap);\n\t}\n\n\tpublic interface ALLEGRO_IIO_IDENTIFIER_FUNCTION extends Callback {\n\t\tbyte apply(Pointer f);\n\t}\n\n\tpublic interface al_emit_user_event_dtor_callback extends Callback {\n\t\tvoid apply(ALLEGRO_USER_EVENT ALLEGRO_USER_EVENTPtr1);\n\t}\n\n\tpublic interface _al_user_assert_handler_callback extends Callback {\n\t\tvoid apply(Pointer expr, Pointer file, int line, Pointer func);\n\t}\n\n\tpublic interface al_register_assert_handler_handler_callback extends Callback {\n\t\tvoid apply(Pointer expr, Pointer file, int line, Pointer func);\n\t}\n\n\tpublic interface al_register_trace_handler_handler_callback extends Callback {\n\t\tvoid apply(Pointer charPtr1);\n\t}\n\n\tpublic interface al_for_each_fs_entry_callback_callback extends Callback {\n\t\tint apply(ALLEGRO_FS_ENTRY entry, Pointer extra);\n\t}\n\n\tpublic interface al_install_system_atexit_ptr_callback_arg1_callback extends Callback {\n\t\tvoid apply();\n\t}\n\n\tpublic interface al_install_system_atexit_ptr_callback extends Callback {\n\t\tint apply(AllegroLibrary.al_install_system_atexit_ptr_callback_arg1_callback arg1);\n\t}\n\n\tpublic interface al_create_thread_proc_callback extends Callback {\n\t\tPointer apply(Pointer thread, Pointer arg);\n\t}\n\n\tpublic interface al_run_detached_thread_proc_callback extends Callback {\n\t\tPointer apply(Pointer arg);\n\t}\n\n\tpublic static native int al_get_allegro_version();\n\tpublic static native int al_run_main(int argc, Pointer argv, AllegroLibrary.al_run_main_arg1_callback arg1);\n\n\t//Time routines\n\tpublic static native double al_get_time();\n\tpublic static native void al_rest(double seconds);\n\tpublic static native void al_init_timeout(ALLEGRO_TIMEOUT timeout, double seconds);\n\n\t//Graphics routines\n\t//Colors\n\tpublic static native ALLEGRO_COLOR al_map_rgb(byte r, byte g, byte b);\n\tpublic static native ALLEGRO_COLOR al_map_rgba(byte r, byte g, byte b, byte a);\n\tpublic static native ALLEGRO_COLOR al_map_rgb_f(float r, float g, float b);\n\tpublic static native ALLEGRO_COLOR al_map_rgba_f(float r, float g, float b, float a);\n\tpublic static native ALLEGRO_COLOR al_premul_rgba(byte r, byte g, byte b, byte a);\n\tpublic static native ALLEGRO_COLOR al_premul_rgba_f(float r, float g, float b, float a);\n\tpublic static native void al_unmap_rgb(ALLEGRO_COLOR color, ByteByReference r, ByteByReference g, ByteByReference b);\n\tpublic static native void al_unmap_rgba(ALLEGRO_COLOR color, ByteByReference r, ByteByReference g, ByteByReference b, ByteByReference a);\n\tpublic static native void al_unmap_rgb_f(ALLEGRO_COLOR color, FloatByReference r, FloatByReference g, FloatByReference b);\n\tpublic static native void al_unmap_rgba_f(ALLEGRO_COLOR color, FloatByReference r, FloatByReference g, FloatByReference b, FloatByReference a);\n\t//Locking and pixel formats\n\tpublic static native int al_get_pixel_size(int format);\n\tpublic static native int al_get_pixel_format_bits(int format);\n\tpublic static native int al_get_pixel_block_size(int format);\n\tpublic static native int al_get_pixel_block_width(int format);\n\tpublic static native int al_get_pixel_block_height(int format);\n\t//Other\n\tpublic static native void al_set_new_bitmap_format(int format);\n\tpublic static native void al_set_new_bitmap_flags(int flags);\n\tpublic static native int al_get_new_bitmap_format();\n\tpublic static native int al_get_new_bitmap_flags();\n\tpublic static native void al_add_new_bitmap_flag(int flag);\n\tpublic static native int al_get_bitmap_width(ALLEGRO_BITMAP bitmap);\n\tpublic static native int al_get_bitmap_height(ALLEGRO_BITMAP bitmap);\n\tpublic static native int al_get_bitmap_format(ALLEGRO_BITMAP bitmap);\n\tpublic static native int al_get_bitmap_flags(ALLEGRO_BITMAP bitmap);\n\tpublic static native ALLEGRO_BITMAP al_create_bitmap(int w, int h);\n\tpublic static native void al_destroy_bitmap(ALLEGRO_BITMAP bitmap);\n\tpublic static native void al_put_pixel(int x, int y, ALLEGRO_COLOR color);\n\tpublic static native void al_put_blended_pixel(int x, int y, ALLEGRO_COLOR color);\n\tpublic static native ALLEGRO_COLOR al_get_pixel(ALLEGRO_BITMAP bitmap, int x, int y);\n\tpublic static native void al_convert_mask_to_alpha(ALLEGRO_BITMAP bitmap, ALLEGRO_COLOR mask_color);\n\tpublic static native void al_set_clipping_rectangle(int x, int y, int width, int height);\n\tpublic static native void al_reset_clipping_rectangle();\n\tpublic static native void al_get_clipping_rectangle(IntByReference x, IntByReference y, IntByReference w, IntByReference h);\n\tpublic static native ALLEGRO_BITMAP al_create_sub_bitmap(ALLEGRO_BITMAP parent, int x, int y, int w, int h);\n\tpublic static native boolean al_is_sub_bitmap(ALLEGRO_BITMAP bitmap);\n\tpublic static native ALLEGRO_BITMAP al_get_parent_bitmap(ALLEGRO_BITMAP bitmap);\n\tpublic static native int al_get_bitmap_x(ALLEGRO_BITMAP bitmap);\n\tpublic static native int al_get_bitmap_y(ALLEGRO_BITMAP bitmap);\n\tpublic static native void al_reparent_bitmap(ALLEGRO_BITMAP bitmap, ALLEGRO_BITMAP parent, int x, int y, int w, int h);\n\tpublic static native ALLEGRO_BITMAP al_clone_bitmap(ALLEGRO_BITMAP bitmap);\n\tpublic static native void al_convert_bitmap(ALLEGRO_BITMAP bitmap);\n\tpublic static native void al_convert_memory_bitmaps();\n\t//Drawing operations\n\tpublic static native void al_draw_bitmap(ALLEGRO_BITMAP bitmap, float dx, float dy, int flags);\n\tpublic static native void al_draw_bitmap_region(ALLEGRO_BITMAP bitmap, float sx, float sy, float sw, float sh, float dx, float dy, int flags);\n\tpublic static native void al_draw_scaled_bitmap(ALLEGRO_BITMAP bitmap, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, int flags);\n\tpublic static native void al_draw_rotated_bitmap(ALLEGRO_BITMAP bitmap, float cx, float cy, float dx, float dy, float angle, int flags);\n\tpublic static native void al_draw_scaled_rotated_bitmap(ALLEGRO_BITMAP bitmap, float cx, float cy, float dx, float dy, float xscale, float yscale, float angle, int flags);\n\tpublic static native void al_draw_tinted_bitmap(ALLEGRO_BITMAP bitmap, ALLEGRO_COLOR tint, float dx, float dy, int flags);\n\tpublic static native void al_draw_tinted_bitmap_region(ALLEGRO_BITMAP bitmap, ALLEGRO_COLOR tint, float sx, float sy, float sw, float sh, float dx, float dy, int flags);\n\tpublic static native void al_draw_tinted_scaled_bitmap(ALLEGRO_BITMAP bitmap, ALLEGRO_COLOR tint, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, int flags);\n\tpublic static native void al_draw_tinted_rotated_bitmap(ALLEGRO_BITMAP bitmap, ALLEGRO_COLOR tint, float cx, float cy, float dx, float dy, float angle, int flags);\n\tpublic static native void al_draw_tinted_scaled_rotated_bitmap(ALLEGRO_BITMAP bitmap, ALLEGRO_COLOR tint, float cx, float cy, float dx, float dy, float xscale, float yscale, float angle, int flags);\n\tpublic static native void al_draw_tinted_scaled_rotated_bitmap_region(ALLEGRO_BITMAP bitmap, float sx, float sy, float sw, float sh, ALLEGRO_COLOR tint, float cx, float cy, float dx, float dy, float xscale, float yscale, float angle, int flags);\n\n\t//Path structures\n\tpublic static native ALLEGRO_PATH al_create_path(String str);\n\tpublic static native ALLEGRO_PATH al_create_path_for_directory(String str);\n\tpublic static native ALLEGRO_PATH al_clone_path(ALLEGRO_PATH path);\n\tpublic static native int al_get_path_num_components(ALLEGRO_PATH path);\n\tpublic static native String al_get_path_component(ALLEGRO_PATH path, int i);\n\tpublic static native void al_replace_path_component(ALLEGRO_PATH path, int i, String s);\n\tpublic static native void al_remove_path_component(ALLEGRO_PATH path, int i);\n\tpublic static native void al_insert_path_component(ALLEGRO_PATH path, int i, String s);\n\tpublic static native String al_get_path_tail(ALLEGRO_PATH path);\n\tpublic static native void al_drop_path_tail(ALLEGRO_PATH path);\n\tpublic static native void al_append_path_component(ALLEGRO_PATH path, String s);\n\tpublic static native boolean al_join_paths(ALLEGRO_PATH path, ALLEGRO_PATH tail);\n\tpublic static native boolean al_rebase_path(ALLEGRO_PATH head, ALLEGRO_PATH tail);\n\tpublic static native String al_path_cstr(ALLEGRO_PATH path, byte delim);\n\tpublic static native void al_destroy_path(ALLEGRO_PATH path);\n\tpublic static native void al_set_path_drive(ALLEGRO_PATH path, String drive);\n\tpublic static native String al_get_path_drive(ALLEGRO_PATH path);\n\tpublic static native void al_set_path_filename(ALLEGRO_PATH path, String filename);\n\tpublic static native String al_get_path_filename(ALLEGRO_PATH path);\n\tpublic static native String al_get_path_extension(ALLEGRO_PATH path);\n\tpublic static native boolean al_set_path_extension(ALLEGRO_PATH path, String extension);\n\tpublic static native String al_get_path_basename(ALLEGRO_PATH path);\n\tpublic static native boolean al_make_path_canonical(ALLEGRO_PATH path);\n\n\tpublic static native ALLEGRO_USTR al_ustr_new(String s);\n\tpublic static native ALLEGRO_USTR al_ustr_new_from_buffer(ByteBuffer s, size_t size);\n//\tpublic static native ALLEGRO_USTR al_ustr_newf(String fmt, Object... varArgs1);\n\tpublic static native void al_ustr_free(ALLEGRO_USTR us);\n\tpublic static native String al_cstr(ALLEGRO_USTR us);\n\tpublic static native void al_ustr_to_buffer(ALLEGRO_USTR us, ByteBuffer buffer, int size);\n\tpublic static native Pointer al_cstr_dup(ALLEGRO_USTR us);\n\tpublic static native ALLEGRO_USTR al_ustr_dup(ALLEGRO_USTR us);\n\tpublic static native ALLEGRO_USTR al_ustr_dup_substr(ALLEGRO_USTR us, int start_pos, int end_pos);\n\tpublic static native ALLEGRO_USTR al_ustr_empty_string();\n\tpublic static native ALLEGRO_USTR al_ref_cstr(ALLEGRO_USTR info, Pointer s);\n\tpublic static native ALLEGRO_USTR al_ref_buffer(ALLEGRO_USTR info, ByteBuffer s, size_t size);\n\tpublic static native ALLEGRO_USTR al_ref_ustr(ALLEGRO_USTR info, ALLEGRO_USTR us, int start_pos, int end_pos);\n\tpublic static native size_t al_ustr_size(ALLEGRO_USTR us);\n\tpublic static native size_t al_ustr_length(ALLEGRO_USTR us);\n\tpublic static native int al_ustr_offset(ALLEGRO_USTR us, int index);\n\tpublic static native boolean al_ustr_next(ALLEGRO_USTR us, IntByReference pos);\n\tpublic static native boolean al_ustr_prev(ALLEGRO_USTR us, IntByReference pos);\n\tpublic static native int al_ustr_get(ALLEGRO_USTR us, int pos);\n\tpublic static native int al_ustr_get_next(ALLEGRO_USTR us, IntByReference pos);\n\tpublic static native int al_ustr_prev_get(ALLEGRO_USTR us, IntByReference pos);\n\tpublic static native boolean al_ustr_insert(ALLEGRO_USTR us1, int pos, ALLEGRO_USTR us2);\n\tpublic static native boolean al_ustr_insert_cstr(ALLEGRO_USTR us, int pos, String us2);\n\tpublic static native size_t al_ustr_insert_chr(ALLEGRO_USTR us, int pos, int c);\n\tpublic static native boolean al_ustr_append(ALLEGRO_USTR us1, ALLEGRO_USTR us2);\n\tpublic static native boolean al_ustr_append_cstr(ALLEGRO_USTR us, String s);\n\tpublic static native size_t al_ustr_append_chr(ALLEGRO_USTR us, int c);\n//\tpublic static native boolean al_ustr_appendf(ALLEGRO_USTR us, String fmt, Object... varArgs1);\n//\tpublic static native boolean al_ustr_vappendf(ALLEGRO_USTR us, String fmt, Object... ap);\n\tpublic static native boolean al_ustr_remove_chr(ALLEGRO_USTR us, int pos);\n\tpublic static native boolean al_ustr_remove_range(ALLEGRO_USTR us, int start_pos, int end_pos);\n\tpublic static native boolean al_ustr_truncate(ALLEGRO_USTR us, int start_pos);\n\tpublic static native boolean al_ustr_ltrim_ws(ALLEGRO_USTR us);\n\tpublic static native boolean al_ustr_rtrim_ws(ALLEGRO_USTR us);\n\tpublic static native boolean al_ustr_trim_ws(ALLEGRO_USTR us);\n\tpublic static native boolean al_ustr_assign(ALLEGRO_USTR us1, ALLEGRO_USTR us2);\n\tpublic static native boolean al_ustr_assign_substr(ALLEGRO_USTR us1, ALLEGRO_USTR us2, int start_pos, int end_pos);\n\tpublic static native boolean al_ustr_assign_cstr(ALLEGRO_USTR us1, String s);\n\tpublic static native size_t al_ustr_set_chr(ALLEGRO_USTR us, int pos, int c);\n\tpublic static native boolean al_ustr_replace_range(ALLEGRO_USTR us1, int start_pos1, int end_pos1, ALLEGRO_USTR us2);\n\tpublic static native int al_ustr_find_chr(ALLEGRO_USTR us, int start_pos, int c);\n\tpublic static native int al_ustr_rfind_chr(ALLEGRO_USTR us, int start_pos, int c);\n\tpublic static native int al_ustr_find_set(ALLEGRO_USTR us, int start_pos, ALLEGRO_USTR accept);\n\tpublic static native int al_ustr_find_set_cstr(ALLEGRO_USTR us, int start_pos, String accept);\n\tpublic static native int al_ustr_find_cset(ALLEGRO_USTR us, int start_pos, ALLEGRO_USTR reject);\n\tpublic static native int al_ustr_find_cset_cstr(ALLEGRO_USTR us, int start_pos, String reject);\n\tpublic static native int al_ustr_find_str(ALLEGRO_USTR haystack, int start_pos, ALLEGRO_USTR needle);\n\tpublic static native int al_ustr_find_cstr(ALLEGRO_USTR haystack, int start_pos, String needle);\n\tpublic static native int al_ustr_rfind_str(ALLEGRO_USTR haystack, int start_pos, ALLEGRO_USTR needle);\n\tpublic static native int al_ustr_rfind_cstr(ALLEGRO_USTR haystack, int start_pos, String needle);\n\tpublic static native boolean al_ustr_find_replace(ALLEGRO_USTR us, int start_pos, ALLEGRO_USTR find, ALLEGRO_USTR replace);\n\tpublic static native boolean al_ustr_find_replace_cstr(ALLEGRO_USTR us, int start_pos, String find, String replace);\n\tpublic static native boolean al_ustr_equal(ALLEGRO_USTR us1, ALLEGRO_USTR us2);\n\tpublic static native int al_ustr_compare(ALLEGRO_USTR u, ALLEGRO_USTR v);\n\tpublic static native int al_ustr_ncompare(ALLEGRO_USTR us1, ALLEGRO_USTR us2, int n);\n\tpublic static native boolean al_ustr_has_prefix(ALLEGRO_USTR u, ALLEGRO_USTR v);\n\tpublic static native boolean al_ustr_has_prefix_cstr(ALLEGRO_USTR u, String s);\n\tpublic static native boolean al_ustr_has_suffix(ALLEGRO_USTR u, ALLEGRO_USTR v);\n\tpublic static native boolean al_ustr_has_suffix_cstr(ALLEGRO_USTR us1, String s);\n\tpublic static native size_t al_utf8_width(int c);\n\tpublic static native size_t al_utf8_encode(ByteBuffer s, int c);\n\tpublic static native ALLEGRO_USTR al_ustr_new_from_utf16(ByteBuffer s);\n\tpublic static native size_t al_ustr_size_utf16(ALLEGRO_USTR us);\n\tpublic static native size_t al_ustr_encode_utf16(ALLEGRO_USTR us, ByteBuffer s, size_t n);\n\tpublic static native size_t al_utf16_width(int c);\n\tpublic static native size_t al_utf16_encode(ByteBuffer s, int c);\n\n\t//File I/O\n\tpublic static native ALLEGRO_FILE al_fopen(String path, String mode);\n\tpublic static native ALLEGRO_FILE al_fopen_interface(ALLEGRO_FILE_INTERFACE vt, String path, String mode);\n\tpublic static native ALLEGRO_FILE al_create_file_handle(ALLEGRO_FILE_INTERFACE vt, Pointer userdata);\n\tpublic static native boolean al_fclose(ALLEGRO_FILE f);\n\tpublic static native size_t al_fread(ALLEGRO_FILE f, Pointer ptr, size_t size);\n\tpublic static native size_t al_fread(ALLEGRO_FILE f, Buffer ptr, size_t size);\n\tpublic static native size_t al_fwrite(ALLEGRO_FILE f, Pointer ptr, size_t size);\n\tpublic static native size_t al_fwrite(ALLEGRO_FILE f, Buffer ptr, size_t size);\n\tpublic static native boolean al_fflush(ALLEGRO_FILE f);\n\tpublic static native long al_ftell(ALLEGRO_FILE f);\n\tpublic static native boolean al_fseek(ALLEGRO_FILE f, long offset, int whence);\n\tpublic static native boolean al_feof(ALLEGRO_FILE f);\n\tpublic static native int al_ferror(ALLEGRO_FILE f);\n\tpublic static native Pointer al_ferrmsg(ALLEGRO_FILE f);\n\tpublic static native void al_fclearerr(ALLEGRO_FILE f);\n\tpublic static native int al_fungetc(ALLEGRO_FILE f, int c);\n\tpublic static native long al_fsize(ALLEGRO_FILE f);\n\tpublic static native int al_fgetc(ALLEGRO_FILE f);\n\tpublic static native int al_fputc(ALLEGRO_FILE f, int c);\n\tpublic static native short al_fread16le(ALLEGRO_FILE f);\n\tpublic static native short al_fread16be(ALLEGRO_FILE f);\n\tpublic static native size_t al_fwrite16le(ALLEGRO_FILE f, short w);\n\tpublic static native size_t al_fwrite16be(ALLEGRO_FILE f, short w);\n\tpublic static native int al_fread32le(ALLEGRO_FILE f);\n\tpublic static native int al_fread32be(ALLEGRO_FILE f);\n\tpublic static native size_t al_fwrite32le(ALLEGRO_FILE f, int l);\n\tpublic static native size_t al_fwrite32be(ALLEGRO_FILE f, int l);\n\tpublic static native Pointer al_fgets(ALLEGRO_FILE f, Pointer p, size_t max);\n\tpublic static native ALLEGRO_USTR al_fget_ustr(ALLEGRO_FILE f);\n\tpublic static native int al_fputs(ALLEGRO_FILE f, Pointer p);\n\t//TODO: how to map the following in JNA direct mapping, which can't handle arrays or varargs?\n//\tpublic static native int al_fprintf(ALLEGRO_FILE f, Pointer format, Object... varArgs1);\n//\tpublic static native int al_vfprintf(ALLEGRO_FILE f, Pointer format, Object... args);\n\tpublic static native ALLEGRO_FILE al_fopen_fd(int fd, String mode);\n//\tpublic static native ALLEGRO_FILE al_make_temp_file(String tmpl, ALLEGRO_PATH[] ret_path);\n\tpublic static native ALLEGRO_FILE al_fopen_slice(ALLEGRO_FILE fp, size_t initial_size, String mode);\n\tpublic static native ALLEGRO_FILE_INTERFACE al_get_new_file_interface();\n\tpublic static native void al_set_new_file_interface(ALLEGRO_FILE_INTERFACE file_interface);\n\tpublic static native void al_set_standard_file_interface();\n\tpublic static native Pointer al_get_file_userdata(ALLEGRO_FILE f);\n\n\tpublic static native boolean al_register_bitmap_loader(String ext, AllegroLibrary.ALLEGRO_IIO_LOADER_FUNCTION loader);\n\tpublic static native boolean al_register_bitmap_saver(String ext, AllegroLibrary.ALLEGRO_IIO_SAVER_FUNCTION saver);\n\tpublic static native boolean al_register_bitmap_loader_f(String ext, AllegroLibrary.ALLEGRO_IIO_FS_LOADER_FUNCTION fs_loader);\n\tpublic static native boolean al_register_bitmap_saver_f(String ext, AllegroLibrary.ALLEGRO_IIO_FS_SAVER_FUNCTION fs_saver);\n\tpublic static native boolean al_register_bitmap_identifier(String ext, AllegroLibrary.ALLEGRO_IIO_IDENTIFIER_FUNCTION identifier);\n\tpublic static native ALLEGRO_BITMAP al_load_bitmap(String filename);\n\tpublic static native ALLEGRO_BITMAP al_load_bitmap_flags(String filename, int flags);\n\tpublic static native ALLEGRO_BITMAP al_load_bitmap_f(ALLEGRO_FILE fp, String ident);\n\tpublic static native ALLEGRO_BITMAP al_load_bitmap_flags_f(ALLEGRO_FILE fp, String ident, int flags);\n\tpublic static native boolean al_save_bitmap(Pointer filename, ALLEGRO_BITMAP bitmap);\n\tpublic static native boolean al_save_bitmap_f(ALLEGRO_FILE fp, String ident, ALLEGRO_BITMAP bitmap);\n\tpublic static native String al_identify_bitmap_f(ALLEGRO_FILE fp);\n\tpublic static native String al_identify_bitmap(String filename);\n\tpublic static native ALLEGRO_LOCKED_REGION al_lock_bitmap(ALLEGRO_BITMAP bitmap, int format, int flags);\n\tpublic static native ALLEGRO_LOCKED_REGION al_lock_bitmap_region(ALLEGRO_BITMAP bitmap, int x, int y, int width, int height, int format, int flags);\n\tpublic static native ALLEGRO_LOCKED_REGION al_lock_bitmap_blocked(ALLEGRO_BITMAP bitmap, int flags);\n\tpublic static native ALLEGRO_LOCKED_REGION al_lock_bitmap_region_blocked(ALLEGRO_BITMAP bitmap, int x_block, int y_block, int width_block, int height_block, int flags);\n\tpublic static native void al_unlock_bitmap(ALLEGRO_BITMAP bitmap);\n\tpublic static native boolean al_is_bitmap_locked(ALLEGRO_BITMAP bitmap);\n\t\n\tpublic static native void al_set_blender(int op, int source, int dest);\n\tpublic static native void al_set_blend_color(ALLEGRO_COLOR color);\n\tpublic static native void al_get_blender(IntByReference op, IntByReference source, IntByReference dest);\n\tpublic static native ALLEGRO_COLOR al_get_blend_color();\n\tpublic static native void al_set_separate_blender(int op, int source, int dest, int alpha_op, int alpha_source, int alpha_dest);\n\tpublic static native void al_get_separate_blender(IntByReference op, IntByReference source, IntByReference dest, IntByReference alpha_op, IntByReference alpha_src, IntByReference alpha_dest);\n\n\t//Event functions\n\tpublic static class ALLEGRO_EVENT_SOURCE extends PointerType {\n\t\tpublic ALLEGRO_EVENT_SOURCE(Pointer address) { super(address); }\n\t\tpublic ALLEGRO_EVENT_SOURCE() { super(); }\n\t}\n\tpublic static native void al_init_user_event_source(ALLEGRO_EVENT_SOURCE src);\n\tpublic static native void al_destroy_user_event_source(ALLEGRO_EVENT_SOURCE src);\n\tpublic static native boolean al_emit_user_event(ALLEGRO_EVENT_SOURCE src, ALLEGRO_EVENT event, al_emit_user_event_dtor_callback dtor);\n\tpublic static native void al_unref_user_event(ALLEGRO_USER_EVENT event);\n\tpublic static native void al_set_event_source_data(ALLEGRO_EVENT_SOURCE source, Pointer data);\n\tpublic static native Pointer al_get_event_source_data(ALLEGRO_EVENT_SOURCE source);\n\tpublic static native ALLEGRO_EVENT_QUEUE al_create_event_queue();\n\tpublic static native void al_destroy_event_queue(ALLEGRO_EVENT_QUEUE queue);\n\tpublic static native boolean al_is_event_source_registered(ALLEGRO_EVENT_QUEUE queue, ALLEGRO_EVENT_SOURCE source);\n\tpublic static native void al_register_event_source(ALLEGRO_EVENT_QUEUE queue, ALLEGRO_EVENT_SOURCE source);\n\tpublic static native void al_unregister_event_source(ALLEGRO_EVENT_QUEUE queue, ALLEGRO_EVENT_SOURCE source);\n\tpublic static native void al_pause_event_queue(ALLEGRO_EVENT_QUEUE queue, boolean paused);\n\tpublic static native boolean al_is_event_queue_paused(ALLEGRO_EVENT_QUEUE queue);\n\tpublic static native boolean al_is_event_queue_empty(ALLEGRO_EVENT_QUEUE queue);\n\tpublic static native boolean al_get_next_event(ALLEGRO_EVENT_QUEUE queue, ALLEGRO_EVENT ret_event);\n\tpublic static native boolean al_peek_next_event(ALLEGRO_EVENT_QUEUE queue, ALLEGRO_EVENT ret_event);\n\tpublic static native boolean al_drop_next_event(ALLEGRO_EVENT_QUEUE queue);\n\tpublic static native void al_flush_event_queue(ALLEGRO_EVENT_QUEUE queue);\n\tpublic static native void al_wait_for_event(ALLEGRO_EVENT_QUEUE queue, ALLEGRO_EVENT ret_event);\n\tpublic static native byte al_wait_for_event_timed(ALLEGRO_EVENT_QUEUE queue, ALLEGRO_EVENT ret_event, float secs);\n\tpublic static native byte al_wait_for_event_until(ALLEGRO_EVENT_QUEUE queue, ALLEGRO_EVENT ret_event, ALLEGRO_TIMEOUT timeout);\n\n\t//Display Functions\n\tpublic static native void al_set_new_display_refresh_rate(int refresh_rate);\n\tpublic static native void al_set_new_display_flags(int flags);\n\tpublic static native int al_get_new_display_refresh_rate();\n\tpublic static native int al_get_new_display_flags();\n\tpublic static native void al_set_new_window_title(String title);\n\tpublic static native String al_get_new_window_title();\n\tpublic static native int al_get_display_width(ALLEGRO_DISPLAY display);\n\tpublic static native int al_get_display_height(ALLEGRO_DISPLAY display);\n\tpublic static native int al_get_display_format(ALLEGRO_DISPLAY display);\n\tpublic static native int al_get_display_refresh_rate(ALLEGRO_DISPLAY display);\n\tpublic static native int al_get_display_flags(ALLEGRO_DISPLAY display);\n\tpublic static native int al_get_display_orientation(ALLEGRO_DISPLAY display);\n\tpublic static native boolean al_set_display_flag(ALLEGRO_DISPLAY display, int flag, boolean onoff);\n\tpublic static native ALLEGRO_DISPLAY al_create_display(int w, int h);\n\tpublic static native void al_destroy_display(ALLEGRO_DISPLAY display);\n\tpublic static native ALLEGRO_DISPLAY al_get_current_display();\n\tpublic static native void al_set_target_bitmap(ALLEGRO_BITMAP bitmap);\n\tpublic static native void al_set_target_backbuffer(ALLEGRO_DISPLAY display);\n\tpublic static native ALLEGRO_BITMAP al_get_backbuffer(ALLEGRO_DISPLAY display);\n\tpublic static native ALLEGRO_BITMAP al_get_target_bitmap();\n\tpublic static native boolean al_acknowledge_resize(ALLEGRO_DISPLAY display);\n\tpublic static native boolean al_resize_display(ALLEGRO_DISPLAY display, int width, int height);\n\tpublic static native void al_flip_display();\n\tpublic static native void al_update_display_region(int x, int y, int width, int height);\n\tpublic static native boolean al_is_compatible_bitmap(ALLEGRO_BITMAP bitmap);\n\tpublic static native boolean al_wait_for_vsync();\n\tpublic static native ALLEGRO_EVENT_SOURCE al_get_display_event_source(ALLEGRO_DISPLAY display);\n\tpublic static native void al_set_display_icon(ALLEGRO_DISPLAY display, ALLEGRO_BITMAP icon);\n\tpublic static native void al_set_display_icons(ALLEGRO_DISPLAY display, int num_icons, Pointer icons);\n\tpublic static native void al_set_new_window_position(int x, int y);\n\tpublic static native void al_get_new_window_position(IntByReference x, IntByReference y);\n\tpublic static native void al_set_window_position(ALLEGRO_DISPLAY display, int x, int y);\n\tpublic static native void al_get_window_position(ALLEGRO_DISPLAY display, IntByReference x, IntByReference y);\n\tpublic static native boolean al_set_window_constraints(ALLEGRO_DISPLAY display, int min_w, int min_h, int max_w, int max_h);\n\tpublic static native boolean al_get_window_constraints(ALLEGRO_DISPLAY display, IntByReference min_w, IntByReference min_h, IntByReference max_w, IntByReference max_h);\n\tpublic static native void al_set_window_title(ALLEGRO_DISPLAY display, String title);\n\tpublic static native void al_set_new_display_option(int option, int value, int importance);\n\tpublic static native int al_get_new_display_option(int option, IntByReference importance);\n\tpublic static native void al_reset_new_display_options();\n\tpublic static native void al_set_display_option(ALLEGRO_DISPLAY display, int option, int value);\n\tpublic static native int al_get_display_option(ALLEGRO_DISPLAY display, int option);\n\tpublic static native void al_acknowledge_drawing_halt(ALLEGRO_DISPLAY display);\n\tpublic static native void al_acknowledge_drawing_resume(ALLEGRO_DISPLAY display);\n\t/**\n\t * al_get_clipboard_text returns the text on the clipboard. Allegro has called {@link #al_malloc(long)} on this\n\t * string, and expects you to call {@link #al_free(Pointer)} on it. That is why the binding can not return String, as\n\t * it would copy the string and leak memory. Use {@link #jalleg_get_clipboard_text(ALLEGRO_DISPLAY)} to copy to a\n\t * String and free the native memory.\n\t */\n\tpublic static native Pointer al_get_clipboard_text(ALLEGRO_DISPLAY display);\n\t/**\n\t * Makes a direct call to {@link #al_get_clipboard_text(ALLEGRO_DISPLAY)} and transforms the results into a Java\n\t * String without a memory leak.\n\t */\n\tpublic static String jalleg_get_clipboard_text(ALLEGRO_DISPLAY display) {\n\t\tPointer p = al_get_clipboard_text(display);\n\t\tif (p != null) {\n\t\t\tString ret = p.getString(0);\n\t\t\tal_free(p);\n\t\t\treturn ret;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\tpublic static native boolean al_set_clipboard_text(ALLEGRO_DISPLAY display, String text);\n\tpublic static native boolean al_clipboard_has_text(ALLEGRO_DISPLAY display);\n\n\t//Monitors functions\n\tpublic static native int al_get_new_display_adapter();\n\tpublic static native void al_set_new_display_adapter(int adapter);\n\tpublic static native int al_get_num_video_adapters();\n\tpublic static native boolean al_get_monitor_info(int adapter, ALLEGRO_MONITOR_INFO info);\n\n\tpublic static native void al_hold_bitmap_drawing(boolean hold);\n\tpublic static native boolean al_is_bitmap_drawing_held();\n\n\t//Configuration Files functions\n\tpublic static native ALLEGRO_CONFIG al_create_config();\n\tpublic static native void al_add_config_section(ALLEGRO_CONFIG config, String name);\n\tpublic static native void al_set_config_value(ALLEGRO_CONFIG config, String section, String key, String value);\n\tpublic static native void al_add_config_comment(ALLEGRO_CONFIG config, String section, String comment);\n\tpublic static native String al_get_config_value(ALLEGRO_CONFIG config, String section, String key);\n\tpublic static native ALLEGRO_CONFIG al_load_config_file(String filename);\n\tpublic static native ALLEGRO_CONFIG al_load_config_file_f(ALLEGRO_FILE file);\n\tpublic static native boolean al_save_config_file(String filename, ALLEGRO_CONFIG config);\n\tpublic static native boolean al_save_config_file_f(ALLEGRO_FILE file, ALLEGRO_CONFIG config);\n\tpublic static native void al_merge_config_into(ALLEGRO_CONFIG master, ALLEGRO_CONFIG add);\n\tpublic static native ALLEGRO_CONFIG al_merge_config(ALLEGRO_CONFIG cfg1, ALLEGRO_CONFIG cfg2);\n\tpublic static native void al_destroy_config(ALLEGRO_CONFIG config);\n\tpublic static native boolean al_remove_config_section(ALLEGRO_CONFIG config, String section);\n\tpublic static native boolean al_remove_config_key(ALLEGRO_CONFIG config, String section, String key);\n\tpublic static native String al_get_first_config_section(ALLEGRO_CONFIG config, PointerByReference iterator);\n\tpublic static native String al_get_next_config_section(PointerByReference iterator);\n\tpublic static native String al_get_first_config_entry(ALLEGRO_CONFIG config, String section, PointerByReference iterator);\n\tpublic static native String al_get_next_config_entry(PointerByReference iterator);\n\n\tpublic static native int al_get_cpu_count();\n\tpublic static native int al_get_ram_size();\n\t@Deprecated \n\tpublic static native byte _al_trace_prefix(Pointer channel, int level, Pointer file, int line, Pointer function);\n\tpublic static native byte _al_trace_prefix(String channel, int level, String file, int line, String function);\n//\t@Deprecated\n//\tpublic static native void _al_trace_suffix(Pointer msg, Object... varArgs1);\n//\tpublic static native void _al_trace_suffix(String msg, Object... varArgs1);\n\tpublic static native void al_register_assert_handler(AllegroLibrary.al_register_assert_handler_handler_callback handler);\n\tpublic static native void al_register_trace_handler(AllegroLibrary.al_register_trace_handler_handler_callback handler);\n\tpublic static native void al_clear_to_color(ALLEGRO_COLOR color);\n\tpublic static native void al_clear_depth_buffer(float x);\n\tpublic static native void al_draw_pixel(float x, float y, ALLEGRO_COLOR color);\n\n\t//Fixed point math routines\n\tpublic static native int al_fixsqrt(int x);\n\tpublic static native int al_fixhypot(int x, int y);\n\tpublic static native int al_fixatan(int x);\n\tpublic static native int al_fixatan2(int y, int x);\n\n\t//File system routines\n\tpublic static class ALLEGRO_FS_ENTRY extends PointerType {\n\t\tpublic ALLEGRO_FS_ENTRY(Pointer address) { super(address); }\n\t\tpublic ALLEGRO_FS_ENTRY() { super(); }\n\t}\n\tpublic static native ALLEGRO_FS_ENTRY al_create_fs_entry(String path);\n\tpublic static native void al_destroy_fs_entry(ALLEGRO_FS_ENTRY e);\n\tpublic static native String al_get_fs_entry_name(ALLEGRO_FS_ENTRY e);\n\tpublic static native boolean al_update_fs_entry(ALLEGRO_FS_ENTRY e);\n\tpublic static native int al_get_fs_entry_mode(ALLEGRO_FS_ENTRY e);\n\t//public static native time_t al_get_fs_entry_atime(ALLEGRO_FS_ENTRY e)\n\t//public static native time_t al_get_fs_entry_ctime(ALLEGRO_FS_ENTRY e)\n\t//public static native time_t al_get_fs_entry_mtime(ALLEGRO_FS_ENTRY e)\n\t//public static native off_t al_get_fs_entry_size(ALLEGRO_FS_ENTRY e);\n\tpublic static native boolean al_fs_entry_exists(ALLEGRO_FS_ENTRY e);\n\tpublic static native boolean al_remove_fs_entry(ALLEGRO_FS_ENTRY e);\n\tpublic static native boolean al_open_directory(ALLEGRO_FS_ENTRY e);\n\tpublic static native ALLEGRO_FS_ENTRY al_read_directory(ALLEGRO_FS_ENTRY e);\n\tpublic static native boolean al_close_directory(ALLEGRO_FS_ENTRY e);\n\tpublic static native boolean al_filename_exists(String path);\n\tpublic static native boolean al_remove_filename(String path);\n\t/**\n\t * Returns the current directory as a string, but requires that the data is freed, so use\n\t * {@link #jalleg_get_current_directory()} to manage the memory automatically.\n\t */\n\tpublic static native Pointer al_get_current_directory();\n\t/**\n\t * Calls {@link #al_get_current_directory()}, converts the returned char* to a String then {@link #al_free}s\n\t * the memory.\n\t */\n\tpublic static String jalleg_get_current_directory() {\n\t\tPointer p = al_get_current_directory();\n\t\tString ret = p.getString(0);\n\t\tal_free(p);\n\t\treturn ret;\n\t}\n\tpublic static native boolean al_change_directory(String path);\n\tpublic static native boolean al_make_directory(String path);\n\tpublic static native ALLEGRO_FILE al_open_fs_entry(ALLEGRO_FS_ENTRY e, String mode);\n\tpublic static native int al_for_each_fs_entry(ALLEGRO_FS_ENTRY dir, AllegroLibrary.al_for_each_fs_entry_callback_callback callback, Pointer extra);\n\tpublic static native ALLEGRO_FS_INTERFACE al_get_fs_interface();\n\tpublic static native void al_set_fs_interface(ALLEGRO_FS_INTERFACE vtable);\n\tpublic static native void al_set_standard_fs_interface();\n\n\t//Fullscreen modes\n\tpublic static native int al_get_num_display_modes();\n\tpublic static native ALLEGRO_DISPLAY_MODE al_get_display_mode(int index, ALLEGRO_DISPLAY_MODE mode);\n\t\n\t//Haptic routines\n\tpublic static class ALLEGRO_HAPTIC extends PointerType {\n\t\tpublic ALLEGRO_HAPTIC(Pointer address) { super(address); }\n\t\tpublic ALLEGRO_HAPTIC() { super(); }\n\t}\n\tpublic static native boolean al_install_haptic();\n\tpublic static native void al_uninstall_haptic();\n\tpublic static native boolean al_is_haptic_installed();\n\tpublic static native boolean al_is_mouse_haptic(ALLEGRO_MOUSE dev);\n\tpublic static native boolean al_is_joystick_haptic(ALLEGRO_JOYSTICK dev);\n\tpublic static native boolean al_is_keyboard_haptic(ALLEGRO_KEYBOARD dev);\n\tpublic static native boolean al_is_display_haptic(ALLEGRO_DISPLAY dev);\n\tpublic static native boolean al_is_touch_input_haptic(ALLEGRO_TOUCH_INPUT dev);\n\tpublic static native ALLEGRO_HAPTIC al_get_haptic_from_mouse(ALLEGRO_MOUSE dev);\n\tpublic static native ALLEGRO_HAPTIC al_get_haptic_from_joystick(ALLEGRO_JOYSTICK dev);\n\tpublic static native ALLEGRO_HAPTIC al_get_haptic_from_keyboard(ALLEGRO_KEYBOARD dev);\n\tpublic static native ALLEGRO_HAPTIC al_get_haptic_from_display(ALLEGRO_DISPLAY dev);\n\tpublic static native ALLEGRO_HAPTIC al_get_haptic_from_touch_input(ALLEGRO_TOUCH_INPUT dev);\n\tpublic static native boolean al_release_haptic(ALLEGRO_HAPTIC haptic);\n\tpublic static native boolean al_is_haptic_active(ALLEGRO_HAPTIC haptic);\n\tpublic static native int al_get_haptic_capabilities(ALLEGRO_HAPTIC haptic);\n\tpublic static native boolean al_is_haptic_capable(ALLEGRO_HAPTIC haptic, int query);\n\tpublic static native boolean al_set_haptic_gain(ALLEGRO_HAPTIC haptic, double gain);\n\tpublic static native double al_get_haptic_gain(ALLEGRO_HAPTIC haptic);\n\tpublic static native boolean al_set_haptic_autocenter(ALLEGRO_HAPTIC haptic, double intensity);\n\tpublic static native double al_get_haptic_autocenter(ALLEGRO_HAPTIC haptic);\n\tpublic static native int al_get_max_haptic_effects(ALLEGRO_HAPTIC haptic);\n\tpublic static native boolean al_is_haptic_effect_ok(ALLEGRO_HAPTIC haptic, ALLEGRO_HAPTIC_EFFECT effect);\n\tpublic static native boolean al_upload_haptic_effect(ALLEGRO_HAPTIC haptic, ALLEGRO_HAPTIC_EFFECT effect, ALLEGRO_HAPTIC_EFFECT_ID id);\n\tpublic static native boolean al_play_haptic_effect(ALLEGRO_HAPTIC_EFFECT_ID id, int loop);\n\tpublic static native boolean al_upload_and_play_haptic_effect(ALLEGRO_HAPTIC haptic, ALLEGRO_HAPTIC_EFFECT effect, ALLEGRO_HAPTIC_EFFECT_ID id, int loop);\n\tpublic static native boolean al_stop_haptic_effect(ALLEGRO_HAPTIC_EFFECT_ID id);\n\tpublic static native boolean al_is_haptic_effect_playing(ALLEGRO_HAPTIC_EFFECT_ID id);\n\tpublic static native boolean al_release_haptic_effect(ALLEGRO_HAPTIC_EFFECT_ID id);\n\tpublic static native double al_get_haptic_effect_duration(ALLEGRO_HAPTIC_EFFECT effect);\n\tpublic static native boolean al_rumble_haptic(ALLEGRO_HAPTIC haptic, double intensity, double duration, ALLEGRO_HAPTIC_EFFECT_ID id);\n\n\n\t//Joystick routines\n\tpublic static native boolean al_install_joystick();\n\tpublic static native void al_uninstall_joystick();\n\tpublic static native boolean al_is_joystick_installed();\n\tpublic static native boolean al_reconfigure_joysticks();\n\tpublic static native int al_get_num_joysticks();\n\tpublic static native ALLEGRO_JOYSTICK al_get_joystick(int joyn);\n\tpublic static native void al_release_joystick(ALLEGRO_JOYSTICK joy);\n\tpublic static native boolean al_get_joystick_active(ALLEGRO_JOYSTICK joy);\n\tpublic static native String al_get_joystick_name(ALLEGRO_JOYSTICK joy);\n\tpublic static native int al_get_joystick_num_sticks(ALLEGRO_JOYSTICK joy);\n\tpublic static native int al_get_joystick_stick_flags(ALLEGRO_JOYSTICK joy, int stick);\n\tpublic static native String al_get_joystick_stick_name(ALLEGRO_JOYSTICK joy, int stick);\n\tpublic static native int al_get_joystick_num_axes(ALLEGRO_JOYSTICK joy, int stick);\n\tpublic static native String al_get_joystick_axis_name(ALLEGRO_JOYSTICK joy, int stick, int axis);\n\tpublic static native int al_get_joystick_num_buttons(ALLEGRO_JOYSTICK joy);\n\tpublic static native String al_get_joystick_button_name(ALLEGRO_JOYSTICK joy, int buttonn);\n\tpublic static native void al_get_joystick_state(ALLEGRO_JOYSTICK joy, ALLEGRO_JOYSTICK_STATE ret_state);\n\tpublic static native ALLEGRO_EVENT_SOURCE al_get_joystick_event_source();\n\n\t//Keyboard routines\n\tpublic static native boolean al_is_keyboard_installed();\n\tpublic static native boolean al_install_keyboard();\n\tpublic static native void al_uninstall_keyboard();\n\tpublic static native boolean al_set_keyboard_leds(int leds);\n\tpublic static native String al_keycode_to_name(int keycode);\n\tpublic static native void al_get_keyboard_state(ALLEGRO_KEYBOARD_STATE ret_state);\n\tpublic static native boolean al_key_down(ALLEGRO_KEYBOARD_STATE state, int keycode);\n\tpublic static native ALLEGRO_EVENT_SOURCE al_get_keyboard_event_source();\n\n\t//Mouse routines\n\tpublic static native boolean al_is_mouse_installed();\n\tpublic static native boolean al_install_mouse();\n\tpublic static native void al_uninstall_mouse();\n\tpublic static native int al_get_mouse_num_buttons();\n\tpublic static native int al_get_mouse_num_axes();\n\tpublic static native boolean al_set_mouse_xy(ALLEGRO_DISPLAY display, int x, int y);\n\tpublic static native boolean al_set_mouse_z(int z);\n\tpublic static native boolean al_set_mouse_w(int w);\n\tpublic static native boolean al_set_mouse_axis(int axis, int value);\n\tpublic static native void al_get_mouse_state(ALLEGRO_MOUSE_STATE ret_state);\n\tpublic static native boolean al_mouse_button_down(ALLEGRO_MOUSE_STATE state, int button);\n\tpublic static native int al_get_mouse_state_axis(ALLEGRO_MOUSE_STATE state, int axis);\n\tpublic static native boolean al_get_mouse_cursor_position(IntByReference ret_x, IntByReference ret_y);\n\tpublic static native boolean al_grab_mouse(ALLEGRO_DISPLAY display);\n\tpublic static native boolean al_ungrab_mouse();\n\tpublic static native void al_set_mouse_wheel_precision(int precision);\n\tpublic static native int al_get_mouse_wheel_precision();\n\tpublic static native ALLEGRO_EVENT_SOURCE al_get_mouse_event_source();\n\t//Mouse cursors\n\tpublic static native ALLEGRO_MOUSE_CURSOR al_create_mouse_cursor(ALLEGRO_BITMAP bmp, int xfocus, int yfocus);\n\tpublic static native void al_destroy_mouse_cursor(ALLEGRO_MOUSE_CURSOR cursor);\n\tpublic static native boolean al_set_mouse_cursor(ALLEGRO_DISPLAY display, ALLEGRO_MOUSE_CURSOR cursor);\n\tpublic static native boolean al_set_system_mouse_cursor(ALLEGRO_DISPLAY display, int cursor_id);\n\tpublic static native boolean al_show_mouse_cursor(ALLEGRO_DISPLAY display);\n\tpublic static native boolean al_hide_mouse_cursor(ALLEGRO_DISPLAY display);\n\n\t//Touch input\n\tpublic static native boolean al_is_touch_input_installed();\n\tpublic static native boolean al_install_touch_input();\n\tpublic static native void al_uninstall_touch_input();\n\tpublic static native void al_get_touch_input_state(ALLEGRO_TOUCH_INPUT_STATE ret_state);\n\tpublic static native ALLEGRO_EVENT_SOURCE al_get_touch_input_event_source();\n\n\t//Memory management routines\n\tpublic static Pointer al_malloc(long size) {\n\t\treturn al_malloc_with_context(new size_t(size), 0, \"AllegroLibrary\", \"al_malloc\");\n\t}\n\tpublic static Pointer al_calloc(long num, long size) {\n\t\treturn al_calloc_with_context(new size_t(num), new size_t(size), 0, \"AllegroLibrary\", \"al_calloc\");\n\t}\n\tpublic static Pointer al_realloc(Pointer ptr, long size) {\n\t\treturn al_realloc_with_context(ptr, new size_t(size), 0, \"AllegroLibrary\", \"al_realloc\");\n\t}\n\tpublic static void al_free(Pointer ptr) {\n\t\tal_free_with_context(ptr, 0, \"AllegroLibrary\", \"al_free\");\n\t}\n\tpublic static native void al_set_memory_interface(ALLEGRO_MEMORY_INTERFACE iface);\n\tpublic static native Pointer al_malloc_with_context(size_t n, int line, String file, String func);\n\tpublic static native void al_free_with_context(Pointer ptr, int line, String file, String func);\n\tpublic static native Pointer al_realloc_with_context(Pointer ptr, size_t n, int line, String file, String func);\n\tpublic static native Pointer al_calloc_with_context(size_t count, size_t n, int line, String file, String func);\n\n\tpublic static native void al_set_render_state(int state, int value);\n\n\t//Transformations functions\n\tpublic static native void al_use_transform(ALLEGRO_TRANSFORM trans);\n\tpublic static native void al_use_projection_transform(ALLEGRO_TRANSFORM trans);\n\tpublic static native void al_copy_transform(ALLEGRO_TRANSFORM dest, ALLEGRO_TRANSFORM src);\n\tpublic static native void al_identity_transform(ALLEGRO_TRANSFORM trans);\n\tpublic static native void al_build_transform(ALLEGRO_TRANSFORM trans, float x, float y, float sx, float sy, float theta);\n\tpublic static native void al_build_camera_transform(ALLEGRO_TRANSFORM trans, float position_x, float position_y, float position_z, float look_x, float look_y, float look_z, float up_x, float up_y, float up_z);\n\tpublic static native void al_translate_transform(ALLEGRO_TRANSFORM trans, float x, float y);\n\tpublic static native void al_translate_transform_3d(ALLEGRO_TRANSFORM trans, float x, float y, float z);\n\tpublic static native void al_rotate_transform(ALLEGRO_TRANSFORM trans, float theta);\n\tpublic static native void al_rotate_transform_3d(ALLEGRO_TRANSFORM trans, float x, float y, float z, float angle);\n\tpublic static native void al_scale_transform(ALLEGRO_TRANSFORM trans, float sx, float sy);\n\tpublic static native void al_scale_transform_3d(ALLEGRO_TRANSFORM trans, float sx, float sy, float sz);\n\tpublic static native void al_transform_coordinates(ALLEGRO_TRANSFORM trans, FloatByReference x, FloatByReference y);\n\tpublic static native void al_transform_coordinates_3d(ALLEGRO_TRANSFORM trans, FloatByReference x, FloatByReference y, FloatByReference z);\n\tpublic static native void al_compose_transform(ALLEGRO_TRANSFORM trans, ALLEGRO_TRANSFORM other);\n\tpublic static native ALLEGRO_TRANSFORM al_get_current_transform();\n\tpublic static native ALLEGRO_TRANSFORM al_get_current_inverse_transform();\n\tpublic static native ALLEGRO_TRANSFORM al_get_current_projection_transform();\n\tpublic static native void al_invert_transform(ALLEGRO_TRANSFORM trans);\n\tpublic static native int al_check_inverse(ALLEGRO_TRANSFORM trans, float tol);\n\tpublic static native void al_orthographic_transform(ALLEGRO_TRANSFORM trans, float left, float top, float n, float right, float bottom, float f);\n\tpublic static native void al_perspective_transform(ALLEGRO_TRANSFORM trans, float left, float top, float n, float right, float bottom, float f);\n\tpublic static native void al_horizontal_shear_transform(ALLEGRO_TRANSFORM trans, float theta);\n\tpublic static native void al_vertical_shear_transform(ALLEGRO_TRANSFORM trans, float theta);\n\n\t//Shader routines\n\tpublic static native ALLEGRO_SHADER al_create_shader(int platform);\n\tpublic static native boolean al_attach_shader_source(ALLEGRO_SHADER shader, int type, String source);\n\tpublic static native boolean al_attach_shader_source_file(ALLEGRO_SHADER shader, int type, String filename);\n\tpublic static native boolean al_build_shader(ALLEGRO_SHADER shader);\n\tpublic static native String al_get_shader_log(ALLEGRO_SHADER shader);\n\tpublic static native int al_get_shader_platform(ALLEGRO_SHADER shader);\n\tpublic static native boolean al_use_shader(ALLEGRO_SHADER shader);\n\tpublic static native void al_destroy_shader(ALLEGRO_SHADER shader);\n\tpublic static native boolean al_set_shader_sampler(String name, ALLEGRO_BITMAP bitmap, int unit);\n\tpublic static native boolean al_set_shader_matrix(String name, ALLEGRO_TRANSFORM matrix);\n\tpublic static native boolean al_set_shader_int(String name, int i);\n\tpublic static native boolean al_set_shader_float(String name, float f);\n\tpublic static native boolean al_set_shader_int_vector(String name, int num_components, IntBuffer i, int num_elems);\n\tpublic static native boolean al_set_shader_float_vector(String name, int num_components, FloatBuffer f, int num_elems);\n\tpublic static native boolean al_set_shader_bool(String name, boolean b);\n\tpublic static native String al_get_default_shader_source(int platform, int type);\n\n\tpublic static native boolean al_install_system(int version, al_install_system_atexit_ptr_callback atexit_ptr);\n\tpublic static native void al_uninstall_system();\n\tpublic static native boolean al_is_system_installed();\n\tpublic static native PointerByReference al_get_system_driver();\n\tpublic static native ALLEGRO_CONFIG al_get_system_config();\n\tpublic static native PointerByReference al_get_standard_path(int id);\n\tpublic static native void al_set_exe_name(String path);\n\tpublic static native void al_set_org_name(String org_name);\n\tpublic static native void al_set_app_name(String app_name);\n\tpublic static native String al_get_org_name();\n\tpublic static native String al_get_app_name();\n\tpublic static native byte al_inhibit_screensaver(byte inhibit);\n\t\n\t//Threads\n\tpublic static native ALLEGRO_THREAD al_create_thread(al_create_thread_proc_callback proc, Pointer arg);\n\tpublic static native void al_start_thread(ALLEGRO_THREAD outer);\n\tpublic static native void al_join_thread(ALLEGRO_THREAD outer, PointerByReference ret_value);\n\tpublic static native void al_set_thread_should_stop(ALLEGRO_THREAD outer);\n\tpublic static native byte al_get_thread_should_stop(ALLEGRO_THREAD outer);\n\tpublic static native void al_destroy_thread(ALLEGRO_THREAD thread);\n\tpublic static native void al_run_detached_thread(al_run_detached_thread_proc_callback proc, Pointer arg);\n\tpublic static native ALLEGRO_MUTEX al_create_mutex();\n\tpublic static native ALLEGRO_MUTEX al_create_mutex_recursive();\n\tpublic static native void al_lock_mutex(ALLEGRO_MUTEX mutex);\n\tpublic static native void al_unlock_mutex(ALLEGRO_MUTEX mutex);\n\tpublic static native void al_destroy_mutex(ALLEGRO_MUTEX mutex);\n\tpublic static native ALLEGRO_COND al_create_cond();\n\tpublic static native void al_destroy_cond(ALLEGRO_COND cond);\n\tpublic static native void al_wait_cond(ALLEGRO_COND cond, ALLEGRO_MUTEX mutex);\n\tpublic static native int al_wait_cond_until(ALLEGRO_COND cond, ALLEGRO_MUTEX mutex, ALLEGRO_TIMEOUT timeout);\n\tpublic static native void al_broadcast_cond(ALLEGRO_COND cond);\n\tpublic static native void al_signal_cond(ALLEGRO_COND cond);\n\n\t//Timer functions\n\tpublic static native ALLEGRO_TIMER al_create_timer(double speed_secs);\n\tpublic static native void al_destroy_timer(ALLEGRO_TIMER timer);\n\tpublic static native void al_start_timer(ALLEGRO_TIMER timer);\n\tpublic static native void al_stop_timer(ALLEGRO_TIMER timer);\n\tpublic static native void al_resume_timer(ALLEGRO_TIMER timer);\n\tpublic static native boolean al_get_timer_started(ALLEGRO_TIMER timer);\n\tpublic static native double al_get_timer_speed(ALLEGRO_TIMER timer);\n\tpublic static native void al_set_timer_speed(ALLEGRO_TIMER timer, double speed_secs);\n\tpublic static native long al_get_timer_count(ALLEGRO_TIMER timer);\n\tpublic static native void al_set_timer_count(ALLEGRO_TIMER timer, long count);\n\tpublic static native void al_add_timer_count(ALLEGRO_TIMER timer, long diff);\n\tpublic static native ALLEGRO_EVENT_SOURCE al_get_timer_event_source(ALLEGRO_TIMER timer);\n\n\t//State functions\n\tpublic static native void al_store_state(ALLEGRO_STATE state, int flags);\n\tpublic static native void al_restore_state(ALLEGRO_STATE state);\n\tpublic static native int al_get_errno();\n\tpublic static native void al_set_errno(int errnum);\n\n\t//Primitives addon\n\tpublic interface al_triangulate_polygon_emit_triangle_callback extends Callback {\n\t\tvoid apply(int int1, int int2, int int3, Pointer voidPtr1);\n\t}\n\n\tpublic interface al_draw_soft_triangle_init_callback extends Callback {\n\t\tvoid apply(IntByReference uintptr_t1, ALLEGRO_VERTEX ALLEGRO_VERTEXPtr1, ALLEGRO_VERTEX ALLEGRO_VERTEXPtr2, ALLEGRO_VERTEX ALLEGRO_VERTEXPtr3);\n\t}\n\n\tpublic interface al_draw_soft_triangle_first_callback extends Callback {\n\t\tvoid apply(IntByReference uintptr_t1, int int1, int int2, int int3, int int4);\n\t}\n\n\tpublic interface al_draw_soft_triangle_step_callback extends Callback {\n\t\tvoid apply(IntByReference uintptr_t1, int int1);\n\t}\n\n\tpublic interface al_draw_soft_triangle_draw_callback extends Callback {\n\t\tvoid apply(IntByReference uintptr_t1, int int1, int int2, int int3);\n\t}\n\n\tpublic interface al_draw_soft_line_first_callback extends Callback {\n\t\tvoid apply(IntByReference uintptr_t1, int int1, int int2, ALLEGRO_VERTEX ALLEGRO_VERTEXPtr1, ALLEGRO_VERTEX ALLEGRO_VERTEXPtr2);\n\t}\n\n\tpublic interface al_draw_soft_line_step_callback extends Callback {\n\t\tvoid apply(IntByReference uintptr_t1, int int1);\n\t}\n\n\tpublic interface al_draw_soft_line_draw_callback extends Callback {\n\t\tvoid apply(IntByReference uintptr_t1, int int1, int int2);\n\t}\n\n\tpublic static native int al_get_allegro_primitives_version();\n\tpublic static native boolean al_init_primitives_addon();\n\tpublic static native void al_shutdown_primitives_addon();\n\tpublic static native int al_draw_prim(Pointer vtxs, ALLEGRO_VERTEX_DECL decl, ALLEGRO_BITMAP texture, int start, int end, int type);\n\tpublic static native int al_draw_indexed_prim(Pointer vtxs, ALLEGRO_VERTEX_DECL decl, ALLEGRO_BITMAP texture, IntBuffer indices, int num_vtx, int type);\n\tpublic static native int al_draw_vertex_buffer(ALLEGRO_VERTEX_BUFFER vertex_buffer, ALLEGRO_BITMAP texture, int start, int end, int type);\n\tpublic static native int al_draw_indexed_buffer(ALLEGRO_VERTEX_BUFFER vertex_buffer, ALLEGRO_BITMAP texture, ALLEGRO_INDEX_BUFFER index_buffer, int start, int end, int type);\n\tpublic static native ALLEGRO_VERTEX_DECL al_create_vertex_decl(Pointer elements, int stride);\n\tpublic static native void al_destroy_vertex_decl(ALLEGRO_VERTEX_DECL decl);\n\tpublic static native ALLEGRO_VERTEX_BUFFER al_create_vertex_buffer(ALLEGRO_VERTEX_DECL decl, Pointer initial_data, int num_vertices, int flags);\n\tpublic static native void al_destroy_vertex_buffer(ALLEGRO_VERTEX_BUFFER buffer);\n\tpublic static native Pointer al_lock_vertex_buffer(ALLEGRO_VERTEX_BUFFER buffer, int offset, int length, int flags);\n\tpublic static native void al_unlock_vertex_buffer(ALLEGRO_VERTEX_BUFFER buffer);\n\tpublic static native int al_get_vertex_buffer_size(ALLEGRO_VERTEX_BUFFER buffer);\n\tpublic static native ALLEGRO_INDEX_BUFFER al_create_index_buffer(int index_size, Pointer initial_data, int num_indices, int flags);\n\tpublic static native void al_destroy_index_buffer(ALLEGRO_INDEX_BUFFER buffer);\n\tpublic static native Pointer al_lock_index_buffer(ALLEGRO_INDEX_BUFFER buffer, int offset, int length, int flags);\n\tpublic static native void al_unlock_index_buffer(ALLEGRO_INDEX_BUFFER buffer);\n\tpublic static native int al_get_index_buffer_size(ALLEGRO_INDEX_BUFFER buffer);\n\tpublic static native boolean al_triangulate_polygon(FloatBuffer vertices, size_t vertex_stride, IntBuffer vertex_counts, AllegroLibrary.al_triangulate_polygon_emit_triangle_callback emit_triangle, Pointer userdata);\n\tpublic static native void al_draw_soft_triangle(ALLEGRO_VERTEX v1, ALLEGRO_VERTEX v2, ALLEGRO_VERTEX v3, Pointer state, AllegroLibrary.al_draw_soft_triangle_init_callback init, AllegroLibrary.al_draw_soft_triangle_first_callback first, AllegroLibrary.al_draw_soft_triangle_step_callback step, AllegroLibrary.al_draw_soft_triangle_draw_callback draw);\n\tpublic static native void al_draw_soft_line(ALLEGRO_VERTEX v1, ALLEGRO_VERTEX v2, Pointer state, AllegroLibrary.al_draw_soft_line_first_callback first, AllegroLibrary.al_draw_soft_line_step_callback step, AllegroLibrary.al_draw_soft_line_draw_callback draw);\n\tpublic static native void al_draw_line(float x1, float y1, float x2, float y2, ALLEGRO_COLOR color, float thickness);\n\tpublic static native void al_draw_triangle(float x1, float y1, float x2, float y2, float x3, float y3, ALLEGRO_COLOR color, float thickness);\n\tpublic static native void al_draw_rectangle(float x1, float y1, float x2, float y2, ALLEGRO_COLOR color, float thickness);\n\tpublic static native void al_draw_rounded_rectangle(float x1, float y1, float x2, float y2, float rx, float ry, ALLEGRO_COLOR color, float thickness);\n\tpublic static native void al_calculate_arc(FloatBuffer dest, int stride, float cx, float cy, float rx, float ry, float start_theta, float delta_theta, float thickness, int num_points);\n\tpublic static native void al_draw_circle(float cx, float cy, float r, ALLEGRO_COLOR color, float thickness);\n\tpublic static native void al_draw_ellipse(float cx, float cy, float rx, float ry, ALLEGRO_COLOR color, float thickness);\n\tpublic static native void al_draw_arc(float cx, float cy, float r, float start_theta, float delta_theta, ALLEGRO_COLOR color, float thickness);\n\tpublic static native void al_draw_elliptical_arc(float cx, float cy, float rx, float ry, float start_theta, float delta_theta, ALLEGRO_COLOR color, float thickness);\n\tpublic static native void al_draw_pieslice(float cx, float cy, float r, float start_theta, float delta_theta, ALLEGRO_COLOR color, float thickness);\n\tpublic static native void al_calculate_spline(FloatBuffer dest, int stride, FloatBuffer points, float thickness, int num_segments);\n\tpublic static native void al_draw_spline(FloatBuffer points, ALLEGRO_COLOR color, float thickness);\n\tpublic static native void al_calculate_ribbon(FloatBuffer dest, int dest_stride, FloatBuffer points, int points_stride, float thickness, int num_segments);\n\tpublic static native void al_draw_ribbon(FloatBuffer points, int points_stride, ALLEGRO_COLOR color, float thickness, int num_segments);\n\tpublic static native void al_draw_filled_triangle(float x1, float y1, float x2, float y2, float x3, float y3, ALLEGRO_COLOR color);\n\tpublic static native void al_draw_filled_rectangle(float x1, float y1, float x2, float y2, ALLEGRO_COLOR color);\n\tpublic static native void al_draw_filled_ellipse(float cx, float cy, float rx, float ry, ALLEGRO_COLOR color);\n\tpublic static native void al_draw_filled_circle(float cx, float cy, float r, ALLEGRO_COLOR color);\n\tpublic static native void al_draw_filled_pieslice(float cx, float cy, float r, float start_theta, float delta_theta, ALLEGRO_COLOR color);\n\tpublic static native void al_draw_filled_rounded_rectangle(float x1, float y1, float x2, float y2, float rx, float ry, ALLEGRO_COLOR color);\n\tpublic static native void al_draw_polyline(FloatBuffer vertices, int vertex_stride, int vertex_count, int join_style, int cap_style, ALLEGRO_COLOR color, float thickness, float miter_limit);\n\tpublic static native void al_draw_polygon(FloatBuffer vertices, int vertex_count, int join_style, ALLEGRO_COLOR color, float thickness, float miter_limit);\n\tpublic static native void al_draw_filled_polygon(FloatBuffer vertices, int vertex_count, ALLEGRO_COLOR color);\n\tpublic static native void al_draw_filled_polygon_with_holes(FloatBuffer vertices, IntBuffer vertex_counts, ALLEGRO_COLOR color);\n\t\n\t//Font addon\n\tpublic static final int ALLEGRO_NO_KERNING = -1;\n\tpublic static final int ALLEGRO_ALIGN_LEFT = 0;\n\tpublic static final int ALLEGRO_ALIGN_CENTRE = 1;\n\tpublic static final int ALLEGRO_ALIGN_CENTER = 1;\n\tpublic static final int ALLEGRO_ALIGN_RIGHT = 2;\n\tpublic static final int ALLEGRO_ALIGN_INTEGER = 4;\n\n\tpublic interface al_register_font_loader_load_callback extends Callback {\n\t\tALLEGRO_FONT apply(Pointer filename, int size, int flags);\n\t}\n\n\tpublic interface al_do_multiline_text_cb_callback extends Callback {\n\t\tbyte apply(int line_num, Pointer line, int size, Pointer extra);\n\t}\n\n\tpublic interface al_do_multiline_ustr_cb_callback extends Callback {\n\t\tbyte apply(int line_num, ALLEGRO_USTR line, Pointer extra);\n\t}\n\n\tpublic static native boolean al_register_font_loader(String ext, AllegroLibrary.al_register_font_loader_load_callback load);\n\tpublic static native ALLEGRO_FONT al_load_bitmap_font(String filename);\n\tpublic static native ALLEGRO_FONT al_load_bitmap_font_flags(String filename, int flags);\n\tpublic static native ALLEGRO_FONT al_load_font(String filename, int size, int flags);\n\tpublic static native ALLEGRO_FONT al_grab_font_from_bitmap(ALLEGRO_BITMAP bmp, int n, IntBuffer ranges);\n\tpublic static native ALLEGRO_FONT al_create_builtin_font();\n\tpublic static native void al_draw_ustr(ALLEGRO_FONT font, ALLEGRO_COLOR color, float x, float y, int flags, ALLEGRO_USTR ustr);\n\tpublic static native void al_draw_text(ALLEGRO_FONT font, ALLEGRO_COLOR color, float x, float y, int flags, String text);\n\tpublic static native void al_draw_justified_text(ALLEGRO_FONT font, ALLEGRO_COLOR color, float x1, float x2, float y, float diff, int flags, String text);\n\tpublic static native void al_draw_justified_ustr(ALLEGRO_FONT font, ALLEGRO_COLOR color, float x1, float x2, float y, float diff, int flags, ALLEGRO_USTR text);\n//\tpublic static native void al_draw_textf(ALLEGRO_FONT font, ALLEGRO_COLOR color, float x, float y, int flags, String format, Object... varArgs1);\n//\tpublic static native void al_draw_justified_textf(ALLEGRO_FONT font, ALLEGRO_COLOR color, float x1, float x2, float y, float diff, int flags, String format, Object... varArgs1);\n\tpublic static native int al_get_text_width(ALLEGRO_FONT f, String str);\n\tpublic static native int al_get_ustr_width(ALLEGRO_FONT f, ALLEGRO_USTR ustr);\n\tpublic static native int al_get_font_line_height(ALLEGRO_FONT f);\n\tpublic static native int al_get_font_ascent(ALLEGRO_FONT f);\n\tpublic static native int al_get_font_descent(ALLEGRO_FONT f);\n\tpublic static native void al_destroy_font(ALLEGRO_FONT f);\n\tpublic static native void al_get_ustr_dimensions(ALLEGRO_FONT f, ALLEGRO_USTR text, IntByReference bbx, IntByReference bby, IntByReference bbw, IntByReference bbh);\n\tpublic static native void al_get_text_dimensions(ALLEGRO_FONT f, Pointer text, IntByReference bbx, IntByReference bby, IntByReference bbw, IntByReference bbh);\n\tpublic static native boolean al_init_font_addon();\n\tpublic static native void al_shutdown_font_addon();\n\tpublic static native int al_get_allegro_font_version();\n\tpublic static native int al_get_font_ranges(ALLEGRO_FONT font, int ranges_count, IntBuffer ranges);\n\tpublic static native void al_draw_glyph(ALLEGRO_FONT font, ALLEGRO_COLOR color, float x, float y, int codepoint);\n\tpublic static native int al_get_glyph_width(ALLEGRO_FONT f, int codepoint);\n\tpublic static native boolean al_get_glyph_dimensions(ALLEGRO_FONT f, int codepoint, IntByReference bbx, IntByReference bby, IntByReference bbw, IntByReference bbh);\n\tpublic static native int al_get_glyph_advance(ALLEGRO_FONT f, int codepoint1, int codepoint2);\n\tpublic static native void al_draw_multiline_text(ALLEGRO_FONT font, ALLEGRO_COLOR color, float x, float y, float max_width, float line_height, int flags, String text);\n//\tpublic static native void al_draw_multiline_textf(ALLEGRO_FONT font, ALLEGRO_COLOR color, float x, float y, float max_width, float line_height, int flags, String format, Object... varArgs1);\n\tpublic static native void al_draw_multiline_ustr(ALLEGRO_FONT font, ALLEGRO_COLOR color, float x, float y, float max_width, float line_height, int flags, ALLEGRO_USTR text);\n\tpublic static native void al_do_multiline_text(ALLEGRO_FONT font, float max_width, String text, AllegroLibrary.al_do_multiline_text_cb_callback cb, Pointer extra);\n\tpublic static native void al_do_multiline_ustr(ALLEGRO_FONT font, float max_width, ALLEGRO_USTR ustr, AllegroLibrary.al_do_multiline_ustr_cb_callback cb, Pointer extra);\n\tpublic static native void al_set_fallback_font(ALLEGRO_FONT font, ALLEGRO_FONT fallback);\n\tpublic static native ALLEGRO_FONT al_get_fallback_font(ALLEGRO_FONT font);\n\n\t\n\t//Audio addon\n\tpublic interface ALLEGRO_AUDIO_DEPTH {\n\t\tint ALLEGRO_AUDIO_DEPTH_INT8 = 0x00;\n\t\tint ALLEGRO_AUDIO_DEPTH_INT16 = 0x01;\n\t\tint ALLEGRO_AUDIO_DEPTH_INT24 = 0x02;\n\t\tint ALLEGRO_AUDIO_DEPTH_FLOAT32 = 0x03;\n\t\tint ALLEGRO_AUDIO_DEPTH_UNSIGNED = 0x08;\n\t\tint ALLEGRO_AUDIO_DEPTH_UINT8 = ALLEGRO_AUDIO_DEPTH.ALLEGRO_AUDIO_DEPTH_INT8 | ALLEGRO_AUDIO_DEPTH.ALLEGRO_AUDIO_DEPTH_UNSIGNED;\n\t\tint ALLEGRO_AUDIO_DEPTH_UINT16 = ALLEGRO_AUDIO_DEPTH.ALLEGRO_AUDIO_DEPTH_INT16 | ALLEGRO_AUDIO_DEPTH.ALLEGRO_AUDIO_DEPTH_UNSIGNED;\n\t\tint ALLEGRO_AUDIO_DEPTH_UINT24 = ALLEGRO_AUDIO_DEPTH.ALLEGRO_AUDIO_DEPTH_INT24 | ALLEGRO_AUDIO_DEPTH.ALLEGRO_AUDIO_DEPTH_UNSIGNED;\n\t}\n\n\tpublic interface ALLEGRO_CHANNEL_CONF {\n\t\tint ALLEGRO_CHANNEL_CONF_1 = 0x10;\n\t\tint ALLEGRO_CHANNEL_CONF_2 = 0x20;\n\t\tint ALLEGRO_CHANNEL_CONF_3 = 0x30;\n\t\tint ALLEGRO_CHANNEL_CONF_4 = 0x40;\n\t\tint ALLEGRO_CHANNEL_CONF_5_1 = 0x51;\n\t\tint ALLEGRO_CHANNEL_CONF_6_1 = 0x61;\n\t\tint ALLEGRO_CHANNEL_CONF_7_1 = 0x71;\n\t}\n\n\tpublic interface ALLEGRO_PLAYMODE {\n\t\tint ALLEGRO_PLAYMODE_ONCE = 0x100;\n\t\tint ALLEGRO_PLAYMODE_LOOP = 0x101;\n\t\tint ALLEGRO_PLAYMODE_BIDIR = 0x102;\n\t\tint _ALLEGRO_PLAYMODE_STREAM_ONCE = 0x103;\n\t\tint _ALLEGRO_PLAYMODE_STREAM_ONEDIR = 0x104;\n\t}\n\n\tpublic interface ALLEGRO_MIXER_QUALITY {\n\t\tint ALLEGRO_MIXER_QUALITY_POINT = 0x110;\n\t\tint ALLEGRO_MIXER_QUALITY_LINEAR = 0x111;\n\t\tint ALLEGRO_MIXER_QUALITY_CUBIC = 0x112;\n\t}\n\n\tpublic static final int ALLEGRO_EVENT_AUDIO_STREAM_FRAGMENT = (int)(513);\n\tpublic static final int ALLEGRO_EVENT_AUDIO_STREAM_FINISHED = (int)(514);\n\tpublic static final int ALLEGRO_EVENT_AUDIO_RECORDER_FRAGMENT = (int)(515);\n\tpublic static final int ALLEGRO_MAX_CHANNELS = (int)8;\n\tpublic static final float ALLEGRO_AUDIO_PAN_NONE = (float)(-1000.0f);\n\tpublic interface al_set_mixer_postprocess_callback_cb_callback extends Callback {\n\t\tvoid apply(Pointer buf, int samples, Pointer data);\n\t}\n\n\tpublic interface al_register_sample_loader_loader_callback extends Callback {\n\t\tPointerByReference apply(Pointer filename);\n\t}\n\n\tpublic interface al_register_sample_saver_saver_callback extends Callback {\n\t\tbyte apply(Pointer filename, Pointer spl);\n\t}\n\n\tpublic interface al_register_audio_stream_loader_stream_loader_callback extends Callback {\n\t\tPointerByReference apply(Pointer filename, size_t buffer_count, int samples);\n\t}\n\n\tpublic interface al_register_sample_loader_f_loader_callback extends Callback {\n\t\tPointerByReference apply(Pointer fp);\n\t}\n\n\tpublic interface al_register_sample_saver_f_saver_callback extends Callback {\n\t\tbyte apply(Pointer fp, Pointer spl);\n\t}\n\n\tpublic interface al_register_audio_stream_loader_f_stream_loader_callback extends Callback {\n\t\tPointerByReference apply(Pointer fp, size_t buffer_count, int samples);\n\t}\n\n\tpublic static native ALLEGRO_SAMPLE al_create_sample(Buffer buf, int samples, int freq, int depth, int chan_conf, boolean free_buf);\n\tpublic static native ALLEGRO_SAMPLE al_create_sample(Pointer buf, int samples, int freq, int depth, int chan_conf, boolean free_buf);\n\tpublic static native void al_destroy_sample(ALLEGRO_SAMPLE spl);\n\tpublic static native ALLEGRO_SAMPLE_INSTANCE al_create_sample_instance(ALLEGRO_SAMPLE data);\n\tpublic static native void al_destroy_sample_instance(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native int al_get_sample_frequency(PointerByReference spl);\n\tpublic static native int al_get_sample_length(ALLEGRO_SAMPLE spl);\n\tpublic static native int al_get_sample_depth(ALLEGRO_SAMPLE spl);\n\tpublic static native int al_get_sample_channels(ALLEGRO_SAMPLE spl);\n\tpublic static native Pointer al_get_sample_data(ALLEGRO_SAMPLE spl);\n\n\tpublic static native int al_get_sample_instance_frequency(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native int al_get_sample_instance_length(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native int al_get_sample_instance_position(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native float al_get_sample_instance_speed(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native float al_get_sample_instance_gain(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native float al_get_sample_instance_pan(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native float al_get_sample_instance_time(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native int al_get_sample_instance_depth(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native int al_get_sample_instance_channels(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native int al_get_sample_instance_playmode(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native boolean al_get_sample_instance_playing(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native boolean al_get_sample_instance_attached(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native boolean al_set_sample_instance_position(ALLEGRO_SAMPLE_INSTANCE spl, int val);\n\tpublic static native boolean al_set_sample_instance_length(ALLEGRO_SAMPLE_INSTANCE spl, int val);\n\tpublic static native boolean al_set_sample_instance_speed(ALLEGRO_SAMPLE_INSTANCE spl, float val);\n\tpublic static native boolean al_set_sample_instance_gain(ALLEGRO_SAMPLE_INSTANCE spl, float val);\n\tpublic static native boolean al_set_sample_instance_pan(ALLEGRO_SAMPLE_INSTANCE spl, float val);\n\tpublic static native boolean al_set_sample_instance_playmode(ALLEGRO_SAMPLE_INSTANCE spl, int val);\n\tpublic static native boolean al_set_sample_instance_playing(ALLEGRO_SAMPLE_INSTANCE spl, boolean val);\n\tpublic static native boolean al_detach_sample_instance(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native boolean al_set_sample(ALLEGRO_SAMPLE_INSTANCE spl, ALLEGRO_SAMPLE data);\n\tpublic static native ALLEGRO_SAMPLE al_get_sample(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native boolean al_play_sample_instance(ALLEGRO_SAMPLE_INSTANCE spl);\n\tpublic static native boolean al_stop_sample_instance(ALLEGRO_SAMPLE_INSTANCE spl);\n\n\tpublic static native ALLEGRO_AUDIO_STREAM al_create_audio_stream(size_t buffer_count, int samples, int freq, int depth, int chan_conf);\n\tpublic static native void al_destroy_audio_stream(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native void al_drain_audio_stream(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native int al_get_audio_stream_frequency(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native int al_get_audio_stream_length(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native int al_get_audio_stream_fragments(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native int al_get_available_audio_stream_fragments(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native float al_get_audio_stream_speed(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native float al_get_audio_stream_gain(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native float al_get_audio_stream_pan(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native int al_get_audio_stream_channels(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native int al_get_audio_stream_depth(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native int al_get_audio_stream_playmode(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native boolean al_get_audio_stream_playing(ALLEGRO_AUDIO_STREAM spl);\n\tpublic static native boolean al_get_audio_stream_attached(ALLEGRO_AUDIO_STREAM spl);\n\tpublic static native long al_get_audio_stream_played_samples(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native Pointer al_get_audio_stream_fragment(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native boolean al_set_audio_stream_speed(ALLEGRO_AUDIO_STREAM stream, float val);\n\tpublic static native boolean al_set_audio_stream_gain(ALLEGRO_AUDIO_STREAM stream, float val);\n\tpublic static native boolean al_set_audio_stream_pan(ALLEGRO_AUDIO_STREAM stream, float val);\n\tpublic static native boolean al_set_audio_stream_playmode(ALLEGRO_AUDIO_STREAM stream, int val);\n\tpublic static native boolean al_set_audio_stream_playing(ALLEGRO_AUDIO_STREAM stream, boolean val);\n\tpublic static native boolean al_detach_audio_stream(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native boolean al_set_audio_stream_fragment(ALLEGRO_AUDIO_STREAM stream, Pointer val);\n\tpublic static native boolean al_rewind_audio_stream(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native boolean al_seek_audio_stream_secs(ALLEGRO_AUDIO_STREAM stream, double time);\n\tpublic static native double al_get_audio_stream_position_secs(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native double al_get_audio_stream_length_secs(ALLEGRO_AUDIO_STREAM stream);\n\tpublic static native boolean al_set_audio_stream_loop_secs(ALLEGRO_AUDIO_STREAM stream, double start, double end);\n\tpublic static native ALLEGRO_EVENT_SOURCE al_get_audio_stream_event_source(ALLEGRO_AUDIO_STREAM stream);\n\t\n\tpublic static native ALLEGRO_MIXER al_create_mixer(int freq, int depth, int chan_conf);\n\tpublic static native void al_destroy_mixer(ALLEGRO_MIXER mixer);\n\tpublic static native boolean al_attach_sample_instance_to_mixer(ALLEGRO_SAMPLE_INSTANCE stream, ALLEGRO_MIXER mixer);\n\tpublic static native boolean al_attach_audio_stream_to_mixer(ALLEGRO_AUDIO_STREAM stream, ALLEGRO_MIXER mixer);\n\tpublic static native boolean al_attach_mixer_to_mixer(ALLEGRO_MIXER stream, ALLEGRO_MIXER mixer);\n\tpublic static native boolean al_set_mixer_postprocess_callback(ALLEGRO_MIXER mixer, AllegroLibrary.al_set_mixer_postprocess_callback_cb_callback cb, Pointer data);\n\tpublic static native int al_get_mixer_frequency(ALLEGRO_MIXER mixer);\n\tpublic static native int al_get_mixer_channels(ALLEGRO_MIXER mixer);\n\tpublic static native int al_get_mixer_depth(ALLEGRO_MIXER mixer);\n\tpublic static native int al_get_mixer_quality(ALLEGRO_MIXER mixer);\n\tpublic static native float al_get_mixer_gain(ALLEGRO_MIXER mixer);\n\tpublic static native boolean al_get_mixer_playing(ALLEGRO_MIXER mixer);\n\tpublic static native boolean al_get_mixer_attached(ALLEGRO_MIXER mixer);\n\tpublic static native boolean al_set_mixer_frequency(ALLEGRO_MIXER mixer, int val);\n\tpublic static native boolean al_set_mixer_quality(ALLEGRO_MIXER mixer, int val);\n\tpublic static native boolean al_set_mixer_gain(ALLEGRO_MIXER mixer, float gain);\n\tpublic static native boolean al_set_mixer_playing(ALLEGRO_MIXER mixer, boolean val);\n\tpublic static native boolean al_detach_mixer(ALLEGRO_MIXER mixer);\n\t\n\tpublic static native ALLEGRO_VOICE al_create_voice(int freq, int depth, int chan_conf);\n\tpublic static native void al_destroy_voice(ALLEGRO_VOICE voice);\n\tpublic static native boolean al_attach_sample_instance_to_voice(ALLEGRO_SAMPLE_INSTANCE stream, ALLEGRO_VOICE voice);\n\tpublic static native boolean al_attach_audio_stream_to_voice(ALLEGRO_AUDIO_STREAM stream, ALLEGRO_VOICE voice);\n\tpublic static native boolean al_attach_mixer_to_voice(ALLEGRO_MIXER mixer, ALLEGRO_VOICE voice);\n\tpublic static native void al_detach_voice(ALLEGRO_VOICE voice);\n\tpublic static native int al_get_voice_frequency(ALLEGRO_VOICE voice);\n\tpublic static native int al_get_voice_position(ALLEGRO_VOICE voice);\n\tpublic static native int al_get_voice_channels(ALLEGRO_VOICE voice);\n\tpublic static native int al_get_voice_depth(ALLEGRO_VOICE voice);\n\tpublic static native boolean al_get_voice_playing(ALLEGRO_VOICE voice);\n\tpublic static native boolean al_set_voice_position(ALLEGRO_VOICE voice, int val);\n\tpublic static native boolean al_set_voice_playing(ALLEGRO_VOICE voice, boolean val);\n\t\n\tpublic static native boolean al_install_audio();\n\tpublic static native void al_uninstall_audio();\n\tpublic static native boolean al_is_audio_installed();\n\tpublic static native int al_get_allegro_audio_version();\n\tpublic static native size_t al_get_channel_count(int conf);\n\tpublic static native size_t al_get_audio_depth_size(int conf);\n\tpublic static native void al_fill_silence(ByteBuffer buf, int samples, int depth, int chan_conf);\n\tpublic static native boolean al_reserve_samples(int reserve_samples);\n\tpublic static native ALLEGRO_MIXER al_get_default_mixer();\n\tpublic static native boolean al_set_default_mixer(ALLEGRO_MIXER mixer);\n\tpublic static native boolean al_restore_default_mixer();\n\tpublic static native boolean al_play_sample(ALLEGRO_SAMPLE data, float gain, float pan, float speed, int loop, ALLEGRO_SAMPLE_ID ret_id);\n\tpublic static native void al_stop_sample(ALLEGRO_SAMPLE_ID spl_id);\n\tpublic static native void al_stop_samples();\n\tpublic static native ALLEGRO_VOICE al_get_default_voice();\n\tpublic static native void al_set_default_voice(ALLEGRO_VOICE voice);\n\tpublic static native boolean al_register_sample_loader(String ext, AllegroLibrary.al_register_sample_loader_loader_callback loader);\n\tpublic static native boolean al_register_sample_saver(String ext, AllegroLibrary.al_register_sample_saver_saver_callback saver);\n\tpublic static native boolean al_register_audio_stream_loader(String ext, AllegroLibrary.al_register_audio_stream_loader_stream_loader_callback stream_loader);\n\tpublic static native boolean al_register_sample_loader_f(String ext, AllegroLibrary.al_register_sample_loader_f_loader_callback loader);\n\tpublic static native boolean al_register_sample_saver_f(String ext, AllegroLibrary.al_register_sample_saver_f_saver_callback saver);\n\tpublic static native boolean al_register_audio_stream_loader_f(String ext, AllegroLibrary.al_register_audio_stream_loader_f_stream_loader_callback stream_loader);\n\t\n\tpublic static native ALLEGRO_SAMPLE al_load_sample(String filename);\n\tpublic static native byte al_save_sample(String filename, ALLEGRO_SAMPLE spl);\n\tpublic static native ALLEGRO_AUDIO_STREAM al_load_audio_stream(String filename, size_t buffer_count, int samples);\n\tpublic static native ALLEGRO_SAMPLE al_load_sample_f(ALLEGRO_FILE fp, String ident);\n\tpublic static native byte al_save_sample_f(ALLEGRO_FILE fp, String ident, ALLEGRO_SAMPLE spl);\n\tpublic static native ALLEGRO_AUDIO_STREAM al_load_audio_stream_f(ALLEGRO_FILE fp, String ident, size_t buffer_count, int samples);\n\n\tpublic static class ALLEGRO_SAMPLE extends PointerType {\n\t\tpublic ALLEGRO_SAMPLE(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_SAMPLE() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\tpublic static class ALLEGRO_AUDIO_STREAM extends PointerType {\n\t\tpublic ALLEGRO_AUDIO_STREAM(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_AUDIO_STREAM() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\tpublic static class ALLEGRO_MIXER extends PointerType {\n\t\tpublic ALLEGRO_MIXER(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_MIXER() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\tpublic static class ALLEGRO_VOICE extends PointerType {\n\t\tpublic ALLEGRO_VOICE(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_VOICE() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\tpublic static class ALLEGRO_SAMPLE_INSTANCE extends PointerType {\n\t\tpublic ALLEGRO_SAMPLE_INSTANCE(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_SAMPLE_INSTANCE() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t//Audio codecs addon\n\tpublic static native boolean al_init_acodec_addon();\n\tpublic static native int al_get_allegro_acodec_version();\n\n\t//Image I/O addon\n\tpublic static native boolean al_init_image_addon();\n\tpublic static native void al_shutdown_image_addon();\n\tpublic static native int al_get_allegro_image_version();\n\n\t//Memfile addon\n\tpublic static native ALLEGRO_FILE al_open_memfile(Pointer mem, long size, String mode);\n\tpublic static native ALLEGRO_FILE al_open_memfile(ByteBuffer mem, long size, String mode);\n\tpublic static native int al_get_allegro_memfile_version();\n\n\t//PhysicsFS integration addon\n\tpublic static native void al_set_physfs_file_interface();\n\tpublic static native int al_get_allegro_physfs_version();\n\t\n\t//Color addon\n\tpublic static native int al_get_allegro_color_version();\n\tpublic static native void al_color_hsv_to_rgb(float hue, float saturation, float value, FloatByReference red, FloatByReference green, FloatByReference blue);\n\tpublic static native void al_color_rgb_to_hsl(float red, float green, float blue, FloatByReference hue, FloatByReference saturation, FloatByReference lightness);\n\tpublic static native void al_color_rgb_to_hsv(float red, float green, float blue, FloatByReference hue, FloatByReference saturation, FloatByReference value);\n\tpublic static native void al_color_hsl_to_rgb(float hue, float saturation, float lightness, FloatByReference red, FloatByReference green, FloatByReference blue);\n\tpublic static native boolean al_color_name_to_rgb(String name, FloatByReference r, FloatByReference g, FloatByReference b);\n\tpublic static native String al_color_rgb_to_name(float r, float g, float b);\n\tpublic static native void al_color_cmyk_to_rgb(float cyan, float magenta, float yellow, float key, FloatByReference red, FloatByReference green, FloatByReference blue);\n\tpublic static native void al_color_rgb_to_cmyk(float red, float green, float blue, FloatByReference cyan, FloatByReference magenta, FloatByReference yellow, FloatByReference key);\n\tpublic static native void al_color_yuv_to_rgb(float y, float u, float v, FloatByReference red, FloatByReference green, FloatByReference blue);\n\tpublic static native void al_color_rgb_to_yuv(float red, float green, float blue, FloatByReference y, FloatByReference u, FloatByReference v);\n\tpublic static native void al_color_rgb_to_html(float red, float green, float blue, ByteBuffer string);\n\tpublic static native boolean al_color_html_to_rgb(String string, FloatByReference red, FloatByReference green, FloatByReference blue);\n\tpublic static native ALLEGRO_COLOR al_color_yuv(float y, float u, float v);\n\tpublic static native ALLEGRO_COLOR al_color_cmyk(float c, float m, float y, float k);\n\tpublic static native ALLEGRO_COLOR al_color_hsl(float h, float s, float l);\n\tpublic static native ALLEGRO_COLOR al_color_hsv(float h, float s, float v);\n\tpublic static native ALLEGRO_COLOR al_color_name(String name);\n\tpublic static native ALLEGRO_COLOR al_color_html(String string);\n\n\t//Native dialogs support\n\tpublic static final int ALLEGRO_FILECHOOSER_FILE_MUST_EXIST = 1;\n\tpublic static final int ALLEGRO_FILECHOOSER_SAVE = 2;\n\tpublic static final int ALLEGRO_FILECHOOSER_FOLDER = 4;\n\tpublic static final int ALLEGRO_FILECHOOSER_PICTURES = 8;\n\tpublic static final int ALLEGRO_FILECHOOSER_SHOW_HIDDEN = 16;\n\tpublic static final int ALLEGRO_FILECHOOSER_MULTIPLE = 32;\n\tpublic static final int ALLEGRO_MESSAGEBOX_WARN = 1 << 0;\n\tpublic static final int ALLEGRO_MESSAGEBOX_ERROR = 1 << 1;\n\tpublic static final int ALLEGRO_MESSAGEBOX_OK_CANCEL = 1 << 2;\n\tpublic static final int ALLEGRO_MESSAGEBOX_YES_NO = 1 << 3;\n\tpublic static final int ALLEGRO_MESSAGEBOX_QUESTION = 1 << 4;\n\tpublic static final int ALLEGRO_TEXTLOG_NO_CLOSE = 1 << 0;\n\tpublic static final int ALLEGRO_TEXTLOG_MONOSPACE = 1 << 1;\n\tpublic static final int ALLEGRO_EVENT_NATIVE_DIALOG_CLOSE = 600;\n\tpublic static final int ALLEGRO_EVENT_MENU_CLICK = 601;\n\tpublic static final int ALLEGRO_MENU_ITEM_ENABLED = 0;\n\tpublic static final int ALLEGRO_MENU_ITEM_CHECKBOX = 1;\n\tpublic static final int ALLEGRO_MENU_ITEM_CHECKED = 2;\n\tpublic static final int ALLEGRO_MENU_ITEM_DISABLED = 4;\n\tpublic static native int al_get_allegro_native_dialog_version();\n\tpublic static native boolean al_init_native_dialog_addon();\n\tpublic static native void al_shutdown_native_dialog_addon();\n\tpublic static native ALLEGRO_MENU al_create_native_file_dialog(String initial_path, String title, String patterns, int mode);\n\tpublic static native boolean al_show_native_file_dialog(ALLEGRO_MENU display, ALLEGRO_FILECHOOSER dialog);\n\tpublic static native int al_get_native_file_dialog_count(ALLEGRO_FILECHOOSER dialog);\n\tpublic static native String al_get_native_file_dialog_path(ALLEGRO_FILECHOOSER dialog, size_t index);\n\tpublic static native void al_destroy_native_file_dialog(ALLEGRO_FILECHOOSER dialog);\n\tpublic static native int al_show_native_message_box(ALLEGRO_DISPLAY display, String title, String heading, String text, String buttons, int flags);\n\tpublic static native ALLEGRO_TEXTLOG al_open_native_text_log(String title, int flags);\n\tpublic static native void al_close_native_text_log(ALLEGRO_TEXTLOG textlog);\n\tprivate static native void al_append_native_text_log(ALLEGRO_TEXTLOG textlog, String format, String text);\n\t/**\n\t * Calls al_append_native_text_log with the formatted result using {@link String#format(String, Object...)}, and NOT\n\t * Allegro's native formatting. This works around varargs limitations in JNA direct mapping.\n\t */\n\tpublic static void jalleg_append_native_text_log(ALLEGRO_TEXTLOG textlog, String format, Object... args) {\n\t\tal_append_native_text_log(textlog, \"%s\", String.format(format, args));\n\t}\n\t/**\n\t * Calls al_append_native_text_log with the \"%s\" format and given text. This works around varargs limitations in JNA\n\t * direct mapping.\n\t */\n\tpublic static void jalleg_append_native_text_log(ALLEGRO_TEXTLOG textlog, String text) {\n\t\tal_append_native_text_log(textlog, \"%s\", text);\n\t}\n\tpublic static native ALLEGRO_EVENT_SOURCE al_get_native_text_log_event_source(ALLEGRO_TEXTLOG textlog);\n\tpublic static native ALLEGRO_MENU al_create_menu();\n\tpublic static native ALLEGRO_MENU al_create_popup_menu();\n//\tpublic static native ALLEGRO_MENU al_build_menu(ALLEGRO_MENU_INFO info);\n\tpublic static native int al_append_menu_item(ALLEGRO_MENU parent, String title, short id, int flags, ALLEGRO_BITMAP icon, ALLEGRO_MENU submenu);\n\tpublic static native int al_insert_menu_item(ALLEGRO_MENU parent, int pos, String title, short id, int flags, ALLEGRO_BITMAP icon, ALLEGRO_MENU submenu);\n\tpublic static native boolean al_remove_menu_item(ALLEGRO_MENU menu, int pos);\n\tpublic static native ALLEGRO_MENU al_clone_menu(ALLEGRO_MENU menu);\n\tpublic static native ALLEGRO_MENU al_clone_menu_for_popup(ALLEGRO_MENU menu);\n\tpublic static native void al_destroy_menu(ALLEGRO_MENU menu);\n\tpublic static native String al_get_menu_item_caption(ALLEGRO_MENU menu, int pos);\n\tpublic static native void al_set_menu_item_caption(ALLEGRO_MENU menu, int pos, String caption);\n\tpublic static native int al_get_menu_item_flags(ALLEGRO_MENU menu, int pos);\n\tpublic static native void al_set_menu_item_flags(ALLEGRO_MENU menu, int pos, int flags);\n\tpublic static native ALLEGRO_MENU al_get_menu_item_icon(ALLEGRO_MENU menu, int pos);\n\tpublic static native void al_set_menu_item_icon(ALLEGRO_MENU menu, int pos, ALLEGRO_BITMAP icon);\n\tpublic static native ALLEGRO_MENU al_find_menu(ALLEGRO_MENU haystack, short id);\n\tpublic static native boolean al_find_menu_item(ALLEGRO_MENU haystack, short id, PointerByReference menu, IntByReference index);\n\tpublic static native ALLEGRO_EVENT_SOURCE al_get_default_menu_event_source();\n\tpublic static native ALLEGRO_EVENT_SOURCE al_enable_menu_event_source(ALLEGRO_MENU menu);\n\tpublic static native void al_disable_menu_event_source(ALLEGRO_MENU menu);\n\tpublic static native ALLEGRO_MENU al_get_display_menu(ALLEGRO_DISPLAY display);\n\tpublic static native boolean al_set_display_menu(ALLEGRO_DISPLAY display, ALLEGRO_MENU menu);\n\tpublic static native boolean al_popup_menu(ALLEGRO_MENU popup, ALLEGRO_DISPLAY display);\n\tpublic static native ALLEGRO_MENU al_remove_display_menu(ALLEGRO_MENU display);\n\tpublic static class ALLEGRO_FILECHOOSER extends PointerType {\n\t\tpublic ALLEGRO_FILECHOOSER(Pointer address) { super(address); }\n\t\tpublic ALLEGRO_FILECHOOSER() { super(); }\n\t}\n\tpublic static class ALLEGRO_MENU extends PointerType {\n\t\tpublic ALLEGRO_MENU(Pointer address) { super(address); }\n\t\tpublic ALLEGRO_MENU() { super(); }\n\t}\n\tpublic static class ALLEGRO_TEXTLOG extends PointerType {\n\t\tpublic ALLEGRO_TEXTLOG(Pointer address) { super(address); }\n\t\tpublic ALLEGRO_TEXTLOG() { super(); }\n\t}\n\n\t//Other Allegro pointer types\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_CONFIG extends PointerType {\n\t\tpublic ALLEGRO_CONFIG(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_CONFIG() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_SHADER extends PointerType {\n\t\tpublic ALLEGRO_SHADER(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_SHADER() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_CONFIG_ENTRY extends PointerType {\n\t\tpublic ALLEGRO_CONFIG_ENTRY(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_CONFIG_ENTRY() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_DISPLAY extends PointerType {\n\t\tpublic ALLEGRO_DISPLAY(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_DISPLAY() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_PATH extends PointerType {\n\t\tpublic ALLEGRO_PATH(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_PATH() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_FILE extends PointerType {\n\t\tpublic ALLEGRO_FILE(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_FILE() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_THREAD extends PointerType {\n\t\tpublic ALLEGRO_THREAD(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_THREAD() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_KEYBOARD extends PointerType {\n\t\tpublic ALLEGRO_KEYBOARD(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_KEYBOARD() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_SYSTEM extends PointerType {\n\t\tpublic ALLEGRO_SYSTEM(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_SYSTEM() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_BITMAP extends PointerType {\n\t\tpublic ALLEGRO_BITMAP(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_BITMAP() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_TOUCH_INPUT extends PointerType {\n\t\tpublic ALLEGRO_TOUCH_INPUT(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_TOUCH_INPUT() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_CONFIG_SECTION extends PointerType {\n\t\tpublic ALLEGRO_CONFIG_SECTION(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_CONFIG_SECTION() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_COND extends PointerType {\n\t\tpublic ALLEGRO_COND(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_COND() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_USER_EVENT_DESCRIPTOR extends PointerType {\n\t\tpublic ALLEGRO_USER_EVENT_DESCRIPTOR(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_USER_EVENT_DESCRIPTOR() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_MUTEX extends PointerType {\n\t\tpublic ALLEGRO_MUTEX(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_MUTEX() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_JOYSTICK extends PointerType {\n\t\tpublic ALLEGRO_JOYSTICK(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_JOYSTICK() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_MOUSE extends PointerType {\n\t\tpublic ALLEGRO_MOUSE(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_MOUSE() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_TIMER extends PointerType {\n\t\tpublic ALLEGRO_TIMER(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_TIMER() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_EVENT_QUEUE extends PointerType {\n\t\tpublic ALLEGRO_EVENT_QUEUE(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_EVENT_QUEUE() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_MOUSE_CURSOR extends PointerType {\n\t\tpublic ALLEGRO_MOUSE_CURSOR(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_MOUSE_CURSOR() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_VERTEX_DECL extends PointerType {\n\t\tpublic ALLEGRO_VERTEX_DECL(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_VERTEX_DECL() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_VERTEX_BUFFER extends PointerType {\n\t\tpublic ALLEGRO_VERTEX_BUFFER(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_VERTEX_BUFFER() {\n\t\t\tsuper();\n\t\t}\n\t}\n\n\t/** Pointer to unknown (opaque) type */\n\tpublic static class ALLEGRO_INDEX_BUFFER extends PointerType {\n\t\tpublic ALLEGRO_INDEX_BUFFER(Pointer address) {\n\t\t\tsuper(address);\n\t\t}\n\t\tpublic ALLEGRO_INDEX_BUFFER() {\n\t\t\tsuper();\n\t\t}\n\t}\n}",
"public static class ALLEGRO_BITMAP extends PointerType {\n\tpublic ALLEGRO_BITMAP(Pointer address) {\n\t\tsuper(address);\n\t}\n\tpublic ALLEGRO_BITMAP() {\n\t\tsuper();\n\t}\n}",
"public static class ALLEGRO_CONFIG extends PointerType {\n\tpublic ALLEGRO_CONFIG(Pointer address) {\n\t\tsuper(address);\n\t}\n\tpublic ALLEGRO_CONFIG() {\n\t\tsuper();\n\t}\n}",
"public class AllegroException extends RuntimeException {\n\tpublic AllegroException() {\n\t}\n\n\tpublic AllegroException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic AllegroException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic AllegroException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n\n\tpublic AllegroException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t}\n}",
"public static native ALLEGRO_BITMAP al_load_bitmap_flags_f(ALLEGRO_FILE fp, String ident, int flags);",
"public static native ALLEGRO_CONFIG al_load_config_file_f(ALLEGRO_FILE file);"
] | import org.gillius.jalleg.binding.AllegroLibrary;
import org.gillius.jalleg.binding.AllegroLibrary.ALLEGRO_BITMAP;
import org.gillius.jalleg.binding.AllegroLibrary.ALLEGRO_CONFIG;
import org.gillius.jalleg.framework.AllegroException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import static org.gillius.jalleg.binding.AllegroLibrary.al_load_bitmap_flags_f;
import static org.gillius.jalleg.binding.AllegroLibrary.al_load_config_file_f; | package org.gillius.jalleg.framework.io;
/**
* Utility methods to load Allegro resources such as images from Java byte arrays, {@link InputStream}s, or classpath
* resources.
*/
public class AllegroLoader {
/**
* Pulls an Allegro "ident" file extension such as ".png" by looking at the end of the given path.
*/
public static String getIdentFromPath(String path) {
int idx = path.lastIndexOf('.');
if (idx >= 0) {
return path.substring(idx);
} else {
return null;
}
}
/**
* Uses {@link AllegroLibrary#al_load_bitmap_f} to load bitmap data. File type will be autodetected from the path's
* extension if possible (via {@link #getIdentFromPath(String)}), or from {@link AllegroLibrary#al_identify_bitmap_f}.
*
* @param path classpath available from the root (boot) classpath
*
* @throws AllegroException if al_load_bitmap_flags_f fails
*/
public static ALLEGRO_BITMAP loadBitmapFromClasspath(String path) throws IOException {
return loadBitmapFromClasspath(path, null, 0);
}
/**
* Uses {@link AllegroLibrary#al_load_bitmap_f} to load bitmap data.
*
* @param path classpath available from the root (boot) classpath
* @param ident type of file such as ".png" or null to use {@link #getIdentFromPath(String)}. If the path does not
* end with a file extension, then auto-detect with {@link AllegroLibrary#al_identify_bitmap_f}
* @param flags flags to pass such as {@link AllegroLibrary#ALLEGRO_NO_PREMULTIPLIED_ALPHA}
*
* @throws AllegroException if al_load_bitmap_flags_f fails
*/
public static ALLEGRO_BITMAP loadBitmapFromClasspath(String path, String ident, int flags) throws IOException {
if (ident == null)
ident = getIdentFromPath(path);
return loadBitmap(getInputStream(path), ident, flags);
}
/**
* Uses {@link AllegroLibrary#al_load_bitmap_f} to load bitmap data.
*
* @param is image data; stream is closed by this function
* @param ident type of file such as ".png" or null to auto-detect with {@link AllegroLibrary#al_identify_bitmap_f}
*
* @throws AllegroException if al_load_bitmap_flags_f fails
*/
public static ALLEGRO_BITMAP loadBitmap(InputStream is, String ident) throws IOException {
return loadBitmap(is, ident, 0);
}
/**
* Uses {@link AllegroLibrary#al_load_bitmap_f} to load bitmap data.
*
* @param is image data; stream is closed by this function
* @param ident type of file such as ".png" or null to auto-detect with {@link AllegroLibrary#al_identify_bitmap_f}
* @param flags flags to pass such as {@link AllegroLibrary#ALLEGRO_NO_PREMULTIPLIED_ALPHA}
*
* @throws AllegroException if al_load_bitmap_flags_f fails
*/
public static ALLEGRO_BITMAP loadBitmap(InputStream is, String ident, int flags) throws IOException {
try (Memfile file = Memfile.from(is)) {
ALLEGRO_BITMAP ret = al_load_bitmap_flags_f(file.getFile(), ident, flags);
if (ret == null)
throw new AllegroException("Failed to load bitmap with type " + ident);
return ret;
}
}
| public static ALLEGRO_CONFIG loadConfigFromClasspath(String path) throws IOException { | 2 |
yammer/tenacity | tenacity-core/src/test/java/com/yammer/tenacity/tests/TenacityCircuitBreakerHealthCheckTest.java | [
"@JsonDeserialize(using = CircuitBreaker.Deserializer.class)\npublic class CircuitBreaker {\n public enum State {\n OPEN, CLOSED, FORCED_OPEN, FORCED_CLOSED,\n FORCED_RESET //Used to \"unset\" any FORCED state\n }\n\n public static class Deserializer extends StdDeserializer<CircuitBreaker> {\n private static final long serialVersionUID = -1293812392173912L;\n private transient final TenacityPropertyKeyFactory keyFactory = new StringTenacityPropertyKeyFactory();\n\n public Deserializer() {\n super(CircuitBreaker.class);\n }\n\n @Override\n public CircuitBreaker deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {\n final ObjectNode objectNode = p.readValueAsTree();\n final TenacityPropertyKey key = keyFactory.from(objectNode.get(\"id\").asText());\n return new CircuitBreaker(key, State.valueOf(objectNode.get(\"state\").asText().toUpperCase()));\n }\n }\n\n @NotNull @Valid\n private final TenacityPropertyKey id;\n @NotNull @Valid\n private final State state;\n\n @JsonCreator\n public CircuitBreaker(@JsonProperty(\"id\") TenacityPropertyKey id,\n @JsonProperty(\"state\") State state) {\n this.id = id;\n this.state = state;\n }\n\n public static CircuitBreaker open(TenacityPropertyKey id) {\n return new CircuitBreaker(id, State.OPEN);\n }\n\n public static CircuitBreaker closed(TenacityPropertyKey id) {\n return new CircuitBreaker(id, State.CLOSED);\n }\n\n public static CircuitBreaker forcedOpen(TenacityPropertyKey id) {\n return new CircuitBreaker(id, State.FORCED_OPEN);\n }\n\n public static CircuitBreaker forcedClosed(TenacityPropertyKey id) {\n return new CircuitBreaker(id, State.FORCED_CLOSED);\n }\n\n public static Optional<CircuitBreaker> usingHystrix(TenacityPropertyKey id) {\n final HystrixCircuitBreaker circuitBreaker = TenacityCommand.getCircuitBreaker(id);\n\n if (circuitBreaker == null) {\n return Optional.empty();\n }\n\n final HystrixCommandProperties commandProperties = TenacityCommand.getCommandProperties(id);\n\n if (commandProperties.circuitBreakerForceOpen().get()) {\n return Optional.of(CircuitBreaker.forcedOpen(id));\n } else if (commandProperties.circuitBreakerForceClosed().get()) {\n return Optional.of(CircuitBreaker.forcedClosed(id));\n } else if (circuitBreaker.allowRequest()) {\n return Optional.of(CircuitBreaker.closed(id));\n } else {\n return Optional.of(CircuitBreaker.open(id));\n }\n }\n\n public TenacityPropertyKey getId() {\n return id;\n }\n\n public boolean isOpen() {\n return state == State.OPEN || state == State.FORCED_OPEN;\n }\n\n public State getState() {\n return state;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, state);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n final CircuitBreaker other = (CircuitBreaker) obj;\n return Objects.equals(this.id.name(), other.id.name())\n && Objects.equals(this.state, other.state);\n }\n\n @Override\n public String toString() {\n return MoreObjects.toStringHelper(this)\n .add(\"id\", id)\n .add(\"state\", state)\n .toString();\n }\n}",
"public class CircuitBreakers {\n private CircuitBreakers() {}\n\n private static Stream<CircuitBreaker> toCircuitBreakers(Collection<TenacityPropertyKey> keys) {\n return keys.stream()\n .map(CircuitBreaker::usingHystrix)\n .filter(Optional::isPresent)\n .map(Optional::get);\n }\n\n public static Collection<CircuitBreaker> allOpen(TenacityPropertyKey... keys) {\n return allOpen(ImmutableList.copyOf(keys));\n }\n\n public static Collection<CircuitBreaker> allOpen(Collection<TenacityPropertyKey> keys) {\n return toCircuitBreakers(keys)\n .filter(CircuitBreaker::isOpen)\n .collect(ImmutableList.toImmutableList());\n }\n\n public static Collection<CircuitBreaker> all(Collection<TenacityPropertyKey> keys) {\n return toCircuitBreakers(keys)\n .collect(ImmutableList.toImmutableList());\n }\n\n public static Collection<CircuitBreaker> all(TenacityPropertyKey... keys) {\n return all(ImmutableList.copyOf(keys));\n }\n\n public static Optional<CircuitBreaker> find(Collection<TenacityPropertyKey> keys,\n TenacityPropertyKey key) {\n return CircuitBreaker.usingHystrix(key.validate(keys));\n }\n}",
"public class TenacityCircuitBreakerHealthCheck extends HealthCheck {\n protected Collection<TenacityPropertyKey> propertyKeys;\n\n public TenacityCircuitBreakerHealthCheck(TenacityPropertyKey... propertyKeys) {\n this(ImmutableList.copyOf(propertyKeys));\n }\n\n public TenacityCircuitBreakerHealthCheck(Iterable<TenacityPropertyKey> propertyKeys) {\n this.propertyKeys = ImmutableList.copyOf(propertyKeys);\n }\n\n public String getName() {\n return \"tenacity-circuitbreakers\";\n }\n\n @Override\n protected Result check() throws Exception {\n final Collection<CircuitBreaker> openCircuits = CircuitBreakers.allOpen(propertyKeys);\n\n if (Iterables.isEmpty(openCircuits)) {\n return Result.healthy();\n } else {\n return Result.unhealthy(\"Open circuit(s): \" + Joiner.on(',')\n .join(Collections2.transform(openCircuits, new Function<CircuitBreaker, String>() {\n @Nullable\n @Override\n public String apply(CircuitBreaker input) {\n return input.getId().name();\n }\n })));\n }\n }\n}",
"public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey {\n default Predicate<TenacityPropertyKey> isEqualPredicate() {\n return (value) -> value.name().equals(name());\n }\n\n default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) {\n return keys.stream()\n .filter(isEqualPredicate())\n .findAny()\n .orElseThrow(() -> new NoSuchElementException(\"No TenacityPropertyKey \" + name()));\n }\n}",
"public class TenacityPropertyRegister {\n protected final ImmutableMap<TenacityPropertyKey, TenacityConfiguration> configurations;\n protected final BreakerboxConfiguration breakerboxConfiguration;\n protected final ArchaiusPropertyRegister archaiusPropertyRegister;\n\n public TenacityPropertyRegister(Map<TenacityPropertyKey, TenacityConfiguration> configurations,\n BreakerboxConfiguration breakerboxConfiguration) {\n this(configurations, breakerboxConfiguration, new ArchaiusPropertyRegister());\n }\n\n public TenacityPropertyRegister(Map<TenacityPropertyKey, TenacityConfiguration> configurations,\n BreakerboxConfiguration breakerboxConfiguration,\n ArchaiusPropertyRegister archaiusPropertyRegister) {\n this.configurations = ImmutableMap.copyOf(configurations);\n this.breakerboxConfiguration = breakerboxConfiguration;\n this.archaiusPropertyRegister = archaiusPropertyRegister;\n }\n\n public void register() {\n final AbstractConfiguration configInstance = ConfigurationManager.getConfigInstance();\n for (Map.Entry<TenacityPropertyKey, TenacityConfiguration> entry : configurations.entrySet()) {\n registerConfiguration(entry.getKey(), entry.getValue(), configInstance);\n }\n archaiusPropertyRegister.register(breakerboxConfiguration);\n }\n\n public static void registerCircuitForceOpen(TenacityPropertyKey key) {\n ConfigurationManager.getConfigInstance().setProperty(circuitBreakerForceOpen(key), true);\n }\n\n public static void registerCircuitForceClosed(TenacityPropertyKey key) {\n ConfigurationManager.getConfigInstance().setProperty(circuitBreakerForceClosed(key), true);\n }\n\n public static void registerCircuitForceReset(TenacityPropertyKey key) {\n final AbstractConfiguration configInstance = ConfigurationManager.getConfigInstance();\n configInstance.setProperty(circuitBreakerForceOpen(key), false);\n configInstance.setProperty(circuitBreakerForceClosed(key), false);\n }\n\n private void registerConfiguration(TenacityPropertyKey key,\n TenacityConfiguration configuration,\n AbstractConfiguration configInstance) {\n configInstance.setProperty(\n executionIsolationThreadTimeoutInMilliseconds(key),\n configuration.getExecutionIsolationThreadTimeoutInMillis());\n\n configInstance.setProperty(\n circuitBreakerRequestVolumeThreshold(key),\n configuration.getCircuitBreaker().getRequestVolumeThreshold());\n\n configInstance.setProperty(\n circuitBreakerSleepWindowInMilliseconds(key),\n configuration.getCircuitBreaker().getSleepWindowInMillis());\n\n configInstance.setProperty(\n circuitBreakerErrorThresholdPercentage(key),\n configuration.getCircuitBreaker().getErrorThresholdPercentage());\n\n configInstance.setProperty(\n circuitBreakermetricsRollingStatsNumBuckets(key),\n configuration.getCircuitBreaker().getMetricsRollingStatisticalWindowBuckets());\n\n configInstance.setProperty(\n circuitBreakermetricsRollingStatsTimeInMilliseconds(key),\n configuration.getCircuitBreaker().getMetricsRollingStatisticalWindowInMilliseconds());\n\n configInstance.setProperty(\n threadpoolCoreSize(key),\n configuration.getThreadpool().getThreadPoolCoreSize());\n\n configInstance.setProperty(\n threadpoolKeepAliveTimeMinutes(key),\n configuration.getThreadpool().getKeepAliveTimeMinutes());\n\n configInstance.setProperty(\n threadpoolMaxQueueSize(key),\n configuration.getThreadpool().getMaxQueueSize());\n\n configInstance.setProperty(\n threadpoolQueueSizeRejectionThreshold(key),\n configuration.getThreadpool().getQueueSizeRejectionThreshold());\n\n configInstance.setProperty(\n threadpoolMetricsRollingStatsNumBuckets(key),\n configuration.getThreadpool().getMetricsRollingStatisticalWindowBuckets());\n\n configInstance.setProperty(\n threadpoolMetricsRollingStatsTimeInMilliseconds(key),\n configuration.getThreadpool().getMetricsRollingStatisticalWindowInMilliseconds());\n\n configInstance.setProperty(\n semaphoreMaxConcurrentRequests(key),\n configuration.getSemaphore().getMaxConcurrentRequests());\n\n configInstance.setProperty(\n semaphoreFallbackMaxConcurrentRequests(key),\n configuration.getSemaphore().getFallbackMaxConcurrentRequests());\n\n if (configuration.hasExecutionIsolationStrategy()) {\n configInstance.setProperty(\n executionIsolationStrategy(key),\n configuration.getExecutionIsolationStrategy());\n }\n }\n\n public static void setDefaultMetricsHealthSnapshotInterval(Duration duration) {\n ConfigurationManager\n .getConfigInstance()\n .setProperty(defaultMetricsHealthSnapshotIntervalInMilliseconds(),\n duration.toMilliseconds());\n }\n\n public static String defaultMetricsHealthSnapshotIntervalInMilliseconds() {\n return \"hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds\";\n }\n\n public static String executionIsolationThreadTimeoutInMilliseconds(TenacityPropertyKey key) {\n return String.format(\"hystrix.command.%s.execution.isolation.thread.timeoutInMilliseconds\", key.name());\n }\n\n public static String circuitBreakerRequestVolumeThreshold(TenacityPropertyKey key) {\n return String.format(\"hystrix.command.%s.circuitBreaker.requestVolumeThreshold\", key.name());\n }\n\n public static String circuitBreakerSleepWindowInMilliseconds(TenacityPropertyKey key) {\n return String.format(\"hystrix.command.%s.circuitBreaker.sleepWindowInMilliseconds\", key.name());\n }\n\n public static String circuitBreakerErrorThresholdPercentage(TenacityPropertyKey key) {\n return String.format(\"hystrix.command.%s.circuitBreaker.errorThresholdPercentage\", key.name());\n }\n\n public static String circuitBreakermetricsRollingStatsTimeInMilliseconds(TenacityPropertyKey key) {\n return String.format(\"hystrix.command.%s.metrics.rollingStats.timeInMilliseconds\", key.name());\n }\n\n public static String circuitBreakermetricsRollingStatsNumBuckets(TenacityPropertyKey key) {\n return String.format(\"hystrix.command.%s.metrics.rollingStats.numBuckets\", key.name());\n }\n\n public static String threadpoolMetricsRollingStatsTimeInMilliseconds(TenacityPropertyKey key) {\n return String.format(\"hystrix.threadpool.%s.metrics.rollingStats.timeInMilliseconds\", key.name());\n }\n\n public static String threadpoolMetricsRollingStatsNumBuckets(TenacityPropertyKey key) {\n return String.format(\"hystrix.threadpool.%s.metrics.rollingStats.numBuckets\", key.name());\n }\n\n public static String threadpoolCoreSize(TenacityPropertyKey key) {\n return String.format(\"hystrix.threadpool.%s.coreSize\", key.name());\n }\n\n public static String threadpoolKeepAliveTimeMinutes(TenacityPropertyKey key) {\n return String.format(\"hystrix.threadpool.%s.keepAliveTimeMinutes\", key.name());\n }\n\n public static String threadpoolQueueSizeRejectionThreshold(TenacityPropertyKey key) {\n return String.format(\"hystrix.threadpool.%s.queueSizeRejectionThreshold\", key.name());\n }\n\n public static String threadpoolMaxQueueSize(TenacityPropertyKey key) {\n return String.format(\"hystrix.threadpool.%s.maxQueueSize\", key.name());\n }\n\n public static String semaphoreMaxConcurrentRequests(TenacityPropertyKey key) {\n return String.format(\"hystrix.command.%s.execution.isolation.semaphore.maxConcurrentRequests\", key.name());\n }\n\n public static String semaphoreFallbackMaxConcurrentRequests(TenacityPropertyKey key) {\n return String.format(\"hystrix.command.%s.fallback.isolation.semaphore.maxConcurrentRequests\", key.name());\n }\n\n public static String executionIsolationStrategy(TenacityPropertyKey key) {\n return String.format(\"hystrix.command.%s.execution.isolation.strategy\", key.name());\n }\n\n public static String circuitBreakerForceOpen(TenacityPropertyKey key) {\n return String.format(\"hystrix.command.%s.circuitBreaker.forceOpen\", key.name());\n }\n\n public static String circuitBreakerForceClosed(TenacityPropertyKey key) {\n return String.format(\"hystrix.command.%s.circuitBreaker.forceClosed\", key.name());\n }\n}",
"public class TenacityTestRule implements TestRule {\n private void setup() {\n resetStreams();\n Hystrix.reset();\n final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance();\n configuration.setProperty(\"hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds\", \"100\");\n }\n\n public void teardown() {\n Hystrix.reset(1, TimeUnit.SECONDS);\n ConfigurationManager.getConfigInstance().clear();\n }\n\n private void resetStreams() {\n /* BucketedCounterStream */\n CumulativeCommandEventCounterStream.reset();\n RollingCommandEventCounterStream.reset();\n CumulativeCollapserEventCounterStream.reset();\n RollingCollapserEventCounterStream.reset();\n CumulativeThreadPoolEventCounterStream.reset();\n RollingThreadPoolEventCounterStream.reset();\n HealthCountsStream.reset();\n /* --------------------- */\n\n /* RollingConcurrencyStream */\n RollingThreadPoolMaxConcurrencyStream.reset();\n RollingCommandMaxConcurrencyStream.reset();\n /* ------------------------ */\n\n /* RollingDistributionStream */\n RollingCommandLatencyDistributionStream.reset();\n RollingCommandUserLatencyDistributionStream.reset();\n RollingCollapserBatchSizeDistributionStream.reset();\n /* ------------------------- */\n }\n\n @Override\n public Statement apply(final Statement base, Description description) {\n return new Statement() {\n @Override\n public void evaluate() throws Throwable {\n try {\n setup();\n base.evaluate();\n } finally {\n teardown();\n }\n }\n };\n }\n}"
] | import com.codahale.metrics.health.HealthCheck;
import com.google.common.collect.ImmutableList;
import com.yammer.tenacity.core.core.CircuitBreaker;
import com.yammer.tenacity.core.core.CircuitBreakers;
import com.yammer.tenacity.core.healthcheck.TenacityCircuitBreakerHealthCheck;
import com.yammer.tenacity.core.properties.TenacityPropertyKey;
import com.yammer.tenacity.core.properties.TenacityPropertyRegister;
import com.yammer.tenacity.testing.TenacityTestRule;
import io.dropwizard.util.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; | package com.yammer.tenacity.tests;
public class TenacityCircuitBreakerHealthCheckTest {
@Rule
public final TenacityTestRule tenacityTestRule = new TenacityTestRule();
@Before
public void setup() {
TenacityPropertyRegister.setDefaultMetricsHealthSnapshotInterval(Duration.milliseconds(10));
}
@Test
public void healthyWhenNoCircuitBreakers() {
assertThat(new TenacityCircuitBreakerHealthCheck().execute().isHealthy()).isTrue();
}
@Test
public void healthyWhenThereIsNoOpenCircuitBreakers() {
final HealthCheck healthCheck = new TenacityCircuitBreakerHealthCheck(DependencyKey.EXISTENT_HEALTHCHECK);
assertThat(CircuitBreakers.all(DependencyKey.EXISTENT_HEALTHCHECK)).isEmpty();
new TenacitySuccessCommand(DependencyKey.EXISTENT_HEALTHCHECK).execute();
assertThat(CircuitBreakers.all(DependencyKey.EXISTENT_HEALTHCHECK))
.contains(CircuitBreaker.closed(DependencyKey.EXISTENT_HEALTHCHECK));
assertThat(healthCheck.execute().isHealthy()).isTrue();
}
@Test
public void unhealthyWhenThereIsAnOpenCircuitBreaker() {
final HealthCheck healthCheck = new TenacityCircuitBreakerHealthCheck(DependencyKey.EXISTENT_HEALTHCHECK);
assertThat(CircuitBreakers.all(DependencyKey.EXISTENT_HEALTHCHECK)).isEmpty();
tryToOpenCircuitBreaker(DependencyKey.EXISTENT_HEALTHCHECK);
assertThat(CircuitBreakers.all(DependencyKey.EXISTENT_HEALTHCHECK))
.contains(CircuitBreaker.open(DependencyKey.EXISTENT_HEALTHCHECK));
assertThat(healthCheck.execute())
.isEqualToComparingOnlyGivenFields(HealthCheck.Result.unhealthy(""), "healthy");
}
@Test
public void multipleUnhealthyWhenThereIsAnOpenCircuitBreaker() { | final ImmutableList<TenacityPropertyKey> keys = ImmutableList.<TenacityPropertyKey>of( | 3 |
Cazsius/Spice-of-Life-Carrot-Edition | src/main/java/com/cazsius/solcarrot/client/TooltipHandler.java | [
"@Mod(SOLCarrot.MOD_ID)\[email protected](modid = SOLCarrot.MOD_ID, bus = MOD)\npublic final class SOLCarrot {\n\tpublic static final String MOD_ID = \"solcarrot\";\n\t\n\tpublic static final Logger LOGGER = LogManager.getLogger(MOD_ID);\n\t\n\tprivate static final String PROTOCOL_VERSION = \"1.0\";\n\tpublic static SimpleChannel channel = NetworkRegistry.ChannelBuilder\n\t\t.named(resourceLocation(\"main\"))\n\t\t.clientAcceptedVersions(PROTOCOL_VERSION::equals)\n\t\t.serverAcceptedVersions(PROTOCOL_VERSION::equals)\n\t\t.networkProtocolVersion(() -> PROTOCOL_VERSION)\n\t\t.simpleChannel();\n\t\n\tpublic static ResourceLocation resourceLocation(String path) {\n\t\treturn new ResourceLocation(MOD_ID, path);\n\t}\n\t\n\t// TODO: not sure if this is even implemented anymore\n\t@SubscribeEvent\n\tpublic static void onFingerprintViolation(FMLFingerprintViolationEvent event) {\n\t\t// This complains if jar not signed, even if certificateFingerprint is blank\n\t\tLOGGER.warn(\"Invalid Fingerprint!\");\n\t}\n\t\n\t@SubscribeEvent\n\tpublic static void setUp(FMLCommonSetupEvent event) {\n\t\tchannel.messageBuilder(FoodListMessage.class, 0)\n\t\t\t.encoder(FoodListMessage::write)\n\t\t\t.decoder(FoodListMessage::new)\n\t\t\t.consumer(FoodListMessage::handle)\n\t\t\t.add();\n\t}\n\t\n\tpublic SOLCarrot() {\n\t\tSOLCarrotConfig.setUp();\n\t}\n}",
"@Mod.EventBusSubscriber(modid = SOLCarrot.MOD_ID, bus = MOD)\npublic final class SOLCarrotConfig {\n\tprivate static String localizationPath(String path) {\n\t\treturn \"config.\" + SOLCarrot.MOD_ID + \".\" + path;\n\t}\n\t\n\tpublic static final Server SERVER;\n\tpublic static final ForgeConfigSpec SERVER_SPEC;\n\t\n\tstatic {\n\t\tPair<Server, ForgeConfigSpec> specPair = new Builder().configure(Server::new);\n\t\tSERVER = specPair.getLeft();\n\t\tSERVER_SPEC = specPair.getRight();\n\t}\n\t\n\tpublic static final Client CLIENT;\n\tpublic static final ForgeConfigSpec CLIENT_SPEC;\n\t\n\tstatic {\n\t\tPair<Client, ForgeConfigSpec> specPair = new Builder().configure(Client::new);\n\t\tCLIENT = specPair.getLeft();\n\t\tCLIENT_SPEC = specPair.getRight();\n\t}\n\t\n\tpublic static void setUp() {\n\t\tModLoadingContext context = ModLoadingContext.get();\n\t\tcontext.registerConfig(ModConfig.Type.SERVER, SERVER_SPEC);\n\t\tcontext.registerConfig(ModConfig.Type.CLIENT, CLIENT_SPEC);\n\t}\n\t\n\t@SubscribeEvent\n\tpublic static void onConfigReload(ModConfig.ConfigReloading event) {\n\t\tMinecraftServer currentServer = ServerLifecycleHooks.getCurrentServer();\n\t\tif (currentServer == null) return;\n\t\t\n\t\tPlayerList players = currentServer.getPlayerList();\n\t\tfor (PlayerEntity player : players.getPlayers()) {\n\t\t\tFoodList.get(player).invalidateProgressInfo();\n\t\t\tCapabilityHandler.syncFoodList(player);\n\t\t}\n\t}\n\t\n\tpublic static int getBaseHearts() {\n\t\treturn SERVER.baseHearts.get();\n\t}\n\t\n\tpublic static int getHeartsPerMilestone() {\n\t\treturn SERVER.heartsPerMilestone.get();\n\t}\n\t\n\tpublic static List<Integer> getMilestones() {\n\t\treturn new ArrayList<>(SERVER.milestones.get());\n\t}\n\t\n\tpublic static List<String> getBlacklist() {\n\t\treturn new ArrayList<>(SERVER.blacklist.get());\n\t}\n\t\n\tpublic static List<String> getWhitelist() {\n\t\treturn new ArrayList<>(SERVER.whitelist.get());\n\t}\n\t\n\tpublic static int getMinimumFoodValue() {\n\t\treturn SERVER.minimumFoodValue.get();\n\t}\n\t\n\tpublic static boolean shouldResetOnDeath() {\n\t\treturn SERVER.shouldResetOnDeath.get();\n\t}\n\t\n\tpublic static class Server {\n\t\tpublic final IntValue baseHearts;\n\t\tpublic final IntValue heartsPerMilestone;\n\t\tpublic final ConfigValue<List<? extends Integer>> milestones;\n\t\t\n\t\tpublic final ConfigValue<List<? extends String>> blacklist;\n\t\tpublic final ConfigValue<List<? extends String>> whitelist;\n\t\tpublic final IntValue minimumFoodValue;\n\t\t\n\t\tpublic final BooleanValue shouldResetOnDeath;\n\t\t\n\t\tServer(Builder builder) {\n\t\t\tbuilder.push(\"milestones\");\n\t\t\t\n\t\t\tbaseHearts = builder\n\t\t\t\t.translation(localizationPath(\"base_hearts\"))\n\t\t\t\t.comment(\"Number of hearts you start out with.\")\n\t\t\t\t.defineInRange(\"baseHearts\", 10, 0, 1000);\n\t\t\t\n\t\t\theartsPerMilestone = builder\n\t\t\t\t.translation(localizationPath(\"hearts_per_milestone\"))\n\t\t\t\t.comment(\"Number of hearts you gain for reaching a new milestone.\")\n\t\t\t\t.defineInRange(\"heartsPerMilestone\", 2, 0, 1000);\n\t\t\t\n\t\t\tmilestones = builder\n\t\t\t\t.translation(localizationPath(\"milestones\"))\n\t\t\t\t.comment(\"A list of numbers of unique foods you need to eat to unlock each milestone, in ascending order.\")\n\t\t\t\t.defineList(\"milestones\", Lists.newArrayList(5, 10, 15, 20, 25), e -> e instanceof Integer);\n\t\t\t\n\t\t\tbuilder.pop();\n\t\t\tbuilder.push(\"filtering\");\n\t\t\t\n\t\t\tblacklist = builder\n\t\t\t\t.translation(localizationPath(\"blacklist\"))\n\t\t\t\t.comment(\"Foods in this list won't affect the player's health nor show up in the food book.\")\n\t\t\t\t.defineList(\"blacklist\", Lists.newArrayList(), e -> e instanceof String);\n\t\t\t\n\t\t\twhitelist = builder\n\t\t\t\t.translation(localizationPath(\"whitelist\"))\n\t\t\t\t.comment(\"When this list contains anything, the blacklist is ignored and instead only foods from here count.\")\n\t\t\t\t.defineList(\"whitelist\", Lists.newArrayList(), e -> e instanceof String);\n\t\t\t\n\t\t\tminimumFoodValue = builder\n\t\t\t\t.translation(localizationPath(\"minimum_food_value\"))\n\t\t\t\t.comment(\"The minimum hunger value foods need to provide in order to count for milestones, in half drumsticks.\")\n\t\t\t\t.defineInRange(\"minimumFoodValue\", 1, 0, 1000);\n\t\t\t\n\t\t\tbuilder.pop();\n\t\t\tbuilder.push(\"miscellaneous\");\n\t\t\t\n\t\t\tshouldResetOnDeath = builder\n\t\t\t\t.translation(localizationPath(\"reset_on_death\"))\n\t\t\t\t.comment(\"Whether or not to reset the food list on death, effectively losing all bonus hearts.\")\n\t\t\t\t.define(\"resetOnDeath\", false);\n\t\t\t\n\t\t\tbuilder.pop();\n\t\t}\n\t}\n\t\n\tpublic static boolean shouldPlayMilestoneSounds() {\n\t\treturn CLIENT.shouldPlayMilestoneSounds.get();\n\t}\n\t\n\tpublic static boolean shouldSpawnIntermediateParticles() {\n\t\treturn CLIENT.shouldSpawnIntermediateParticles.get();\n\t}\n\t\n\tpublic static boolean shouldSpawnMilestoneParticles() {\n\t\treturn CLIENT.shouldSpawnMilestoneParticles.get();\n\t}\n\t\n\tpublic static boolean isFoodTooltipEnabled() {\n\t\treturn CLIENT.isFoodTooltipEnabled.get();\n\t}\n\t\n\tpublic static boolean shouldShowProgressAboveHotbar() {\n\t\treturn CLIENT.shouldShowProgressAboveHotbar.get();\n\t}\n\t\n\tpublic static boolean shouldShowUneatenFoods() {\n\t\treturn CLIENT.shouldShowUneatenFoods.get();\n\t}\n\t\n\tpublic static class Client {\n\t\tpublic final BooleanValue shouldPlayMilestoneSounds;\n\t\tpublic final BooleanValue shouldSpawnIntermediateParticles;\n\t\tpublic final BooleanValue shouldSpawnMilestoneParticles;\n\t\t\n\t\tpublic final BooleanValue isFoodTooltipEnabled;\n\t\tpublic final BooleanValue shouldShowProgressAboveHotbar;\n\t\tpublic final BooleanValue shouldShowUneatenFoods;\n\t\t\n\t\tClient(Builder builder) {\n\t\t\tbuilder.push(\"milestone celebration\");\n\t\t\t\n\t\t\tshouldPlayMilestoneSounds = builder\n\t\t\t\t.translation(localizationPath(\"should_play_milestone_sounds\"))\n\t\t\t\t.comment(\"If true, reaching a new milestone plays a ding sound.\")\n\t\t\t\t.define(\"shouldPlayMilestoneSounds\", true);\n\t\t\t\n\t\t\tshouldSpawnIntermediateParticles = builder\n\t\t\t\t.translation(localizationPath(\"should_spawn_intermediate_particles\"))\n\t\t\t\t.comment(\"If true, trying a new food spawns particles.\")\n\t\t\t\t.define(\"shouldSpawnIntermediateParticles\", true);\n\t\t\t\n\t\t\tshouldSpawnMilestoneParticles = builder\n\t\t\t\t.translation(localizationPath(\"should_spawn_milestone_particles\"))\n\t\t\t\t.comment(\"If true, reaching a new milestone spawns particles.\")\n\t\t\t\t.define(\"shouldSpawnMilestoneParticles\", true);\n\t\t\t\n\t\t\tbuilder.pop();\n\t\t\tbuilder.push(\"miscellaneous\");\n\t\t\t\n\t\t\tisFoodTooltipEnabled = builder\n\t\t\t\t.translation(localizationPath(\"is_food_tooltip_enabled\"))\n\t\t\t\t.comment(\"If true, foods indicate in their tooltips whether or not they have been eaten.\")\n\t\t\t\t.define(\"isFoodTooltipEnabled\", true);\n\t\t\t\n\t\t\tshouldShowProgressAboveHotbar = builder\n\t\t\t\t.translation(localizationPath(\"should_show_progress_above_hotbar\"))\n\t\t\t\t.comment(\"Whether the messages notifying you of reaching new milestones should be displayed above the hotbar or in chat.\")\n\t\t\t\t.define(\"shouldShowProgressAboveHotbar\", true);\n\t\t\t\n\t\t\tshouldShowUneatenFoods = builder\n\t\t\t\t.translation(localizationPath(\"should_show_uneaten_foods\"))\n\t\t\t\t.comment(\"If true, the food book also lists foods that you haven't eaten, in addition to the ones you have.\")\n\t\t\t\t.define(\"shouldShowUneatenFoods\", true);\n\t\t\t\n\t\t\tbuilder.pop();\n\t\t}\n\t}\n\t\n\t// TODO: investigate performance of all these get() calls\n\t\n\tpublic static int milestone(int i) {\n\t\treturn SERVER.milestones.get().get(i);\n\t}\n\t\n\tpublic static int getMilestoneCount() {\n\t\treturn SERVER.milestones.get().size();\n\t}\n\t\n\tpublic static int highestMilestone() {\n\t\treturn milestone(getMilestoneCount() - 1);\n\t}\n\t\n\tpublic static boolean hasWhitelist() {\n\t\treturn !SERVER.whitelist.get().isEmpty();\n\t}\n\t\n\tpublic static boolean isAllowed(Item food) {\n\t\tString id = Objects.requireNonNull(ForgeRegistries.ITEMS.getKey(food)).toString();\n\t\tif (hasWhitelist()) {\n\t\t\treturn matchesAnyPattern(id, SERVER.whitelist.get());\n\t\t} else {\n\t\t\treturn !matchesAnyPattern(id, SERVER.blacklist.get());\n\t\t}\n\t}\n\t\n\tpublic static boolean shouldCount(Item food) {\n\t\treturn isHearty(food) && isAllowed(food);\n\t}\n\t\n\tpublic static boolean isHearty(Item food) {\n\t\tFood foodInfo = food.getFood();\n\t\tif (foodInfo == null) return false;\n\t\treturn foodInfo.getHealing() >= SERVER.minimumFoodValue.get();\n\t}\n\t\n\tprivate static boolean matchesAnyPattern(String query, Collection<? extends String> patterns) {\n\t\tfor (String glob : patterns) {\n\t\t\tStringBuilder pattern = new StringBuilder(glob.length());\n\t\t\tfor (String part : glob.split(\"\\\\*\", -1)) {\n\t\t\t\tif (!part.isEmpty()) { // not necessary\n\t\t\t\t\tpattern.append(Pattern.quote(part));\n\t\t\t\t}\n\t\t\t\tpattern.append(\".*\");\n\t\t\t}\n\t\t\t\n\t\t\t// delete extraneous trailing \".*\" wildcard\n\t\t\tpattern.delete(pattern.length() - 2, pattern.length());\n\t\t\t\n\t\t\tif (Pattern.matches(pattern.toString(), query)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n}",
"@ParametersAreNonnullByDefault\npublic final class FoodList implements FoodCapability {\n\tprivate static final String NBT_KEY_FOOD_LIST = \"foodList\";\n\t\n\tpublic static FoodList get(PlayerEntity player) {\n\t\treturn (FoodList) player.getCapability(SOLCarrotAPI.foodCapability)\n\t\t\t.orElseThrow(FoodListNotFoundException::new);\n\t}\n\t\n\tprivate final Set<FoodInstance> foods = new HashSet<>();\n\t\n\t@Nullable\n\tprivate ProgressInfo cachedProgressInfo;\n\t\n\tpublic FoodList() {}\n\t\n\tprivate final LazyOptional<FoodList> capabilityOptional = LazyOptional.of(() -> this);\n\t\n\t@Override\n\tpublic <T> LazyOptional<T> getCapability(Capability<T> capability, @Nullable Direction side) {\n\t\treturn capability == SOLCarrotAPI.foodCapability ? capabilityOptional.cast() : LazyOptional.empty();\n\t}\n\t\n\t/** used for persistent storage */\n\t@Override\n\tpublic CompoundNBT serializeNBT() {\n\t\tCompoundNBT tag = new CompoundNBT();\n\t\t\n\t\tListNBT list = new ListNBT();\n\t\tfoods.stream()\n\t\t\t.map(FoodInstance::encode)\n\t\t\t.filter(Objects::nonNull)\n\t\t\t.map(StringNBT::new)\n\t\t\t.forEach(list::add);\n\t\ttag.put(NBT_KEY_FOOD_LIST, list);\n\t\t\n\t\treturn tag;\n\t}\n\t\n\t/** used for persistent storage */\n\t@Override\n\tpublic void deserializeNBT(CompoundNBT tag) {\n\t\tListNBT list = tag.getList(NBT_KEY_FOOD_LIST, new StringNBT().getId());\n\t\t\n\t\tfoods.clear();\n\t\tlist.stream()\n\t\t\t.map(nbt -> (StringNBT) nbt)\n\t\t\t.map(StringNBT::getString)\n\t\t\t.map(FoodInstance::decode)\n\t\t\t.filter(Objects::nonNull)\n\t\t\t.forEach(foods::add);\n\t\t\n\t\tinvalidateProgressInfo();\n\t}\n\t\n\t/** @return true if the food was not previously known, i.e. if a new food has been tried */\n\tpublic boolean addFood(Item food) {\n\t\tboolean wasAdded = foods.add(new FoodInstance(food)) && SOLCarrotConfig.shouldCount(food);\n\t\tinvalidateProgressInfo();\n\t\treturn wasAdded;\n\t}\n\t\n\t@Override\n\tpublic boolean hasEaten(Item food) {\n\t\tif (!food.isFood()) return false;\n\t\treturn foods.contains(new FoodInstance(food));\n\t}\n\t\n\tpublic void clearFood() {\n\t\tfoods.clear();\n\t\tinvalidateProgressInfo();\n\t}\n\t\n\tpublic Set<FoodInstance> getEatenFoods() {\n\t\treturn new HashSet<>(foods);\n\t}\n\t\n\t// TODO: is this actually desirable? it doesn't filter at all\n\t@Override\n\tpublic int getEatenFoodCount() {\n\t\treturn foods.size();\n\t}\n\t\n\tpublic ProgressInfo getProgressInfo() {\n\t\tif (cachedProgressInfo == null) {\n\t\t\tcachedProgressInfo = new ProgressInfo(this);\n\t\t}\n\t\treturn cachedProgressInfo;\n\t}\n\t\n\tpublic void invalidateProgressInfo() {\n\t\tcachedProgressInfo = null;\n\t}\n\t\n\tpublic static final class Storage implements Capability.IStorage<FoodCapability> {\n\t\t@Override\n\t\tpublic INBT writeNBT(Capability<FoodCapability> capability, FoodCapability instance, Direction side) {\n\t\t\treturn instance.serializeNBT();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void readNBT(Capability<FoodCapability> capability, FoodCapability instance, Direction side, INBT tag) {\n\t\t\tinstance.deserializeNBT((CompoundNBT) tag);\n\t\t}\n\t}\n\t\n\tpublic static class FoodListNotFoundException extends RuntimeException {\n\t\tpublic FoodListNotFoundException() {\n\t\t\tsuper(\"Player must have food capability attached, but none was found.\");\n\t\t}\n\t}\n}",
"public final class ProgressInfo {\n\t/** the number of unique foods eaten */\n\tpublic final int foodsEaten;\n\t\n\tProgressInfo(FoodList foodList) {\n\t\tfoodsEaten = (int) foodList.getEatenFoods().stream()\n\t\t\t.filter(food -> SOLCarrotConfig.shouldCount(food.item))\n\t\t\t.count();\n\t}\n\t\n\tpublic boolean hasReachedMax() {\n\t\treturn foodsEaten >= SOLCarrotConfig.highestMilestone();\n\t}\n\t\n\t/** the next milestone to reach, or a negative value if the maximum has been reached */\n\tpublic int nextMilestone() {\n\t\treturn hasReachedMax() ? -1 : SOLCarrotConfig.milestone(milestonesAchieved());\n\t}\n\t\n\t/** the number of foods remaining until the next milestone, or a negative value if the maximum has been reached */\n\tpublic int foodsUntilNextMilestone() {\n\t\treturn nextMilestone() - foodsEaten;\n\t}\n\t\n\t/** the number of milestones achieved, doubling as the index of the next milestone */\n\tpublic int milestonesAchieved() {\n\t\treturn (int) SOLCarrotConfig.getMilestones().stream()\n\t\t\t.filter(milestone -> foodsEaten >= milestone).count();\n\t}\n}",
"public static ITextComponent localizedComponent(String domain, IForgeRegistryEntry entry, String path, Object... args) {\n\treturn new TranslationTextComponent(keyString(domain, entry, path), args);\n}"
] | import com.cazsius.solcarrot.SOLCarrot;
import com.cazsius.solcarrot.SOLCarrotConfig;
import com.cazsius.solcarrot.tracking.FoodList;
import com.cazsius.solcarrot.tracking.ProgressInfo;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.*;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import java.util.List;
import static com.cazsius.solcarrot.lib.Localization.localizedComponent; | package com.cazsius.solcarrot.client;
@OnlyIn(Dist.CLIENT)
@Mod.EventBusSubscriber(value = Dist.CLIENT, modid = SOLCarrot.MOD_ID)
public final class TooltipHandler {
@SubscribeEvent
public static void onItemTooltip(ItemTooltipEvent event) {
if (!SOLCarrotConfig.isFoodTooltipEnabled()) return;
if (event.getEntityPlayer() == null) return;
PlayerEntity player = event.getEntityPlayer();
Item food = event.getItemStack().getItem();
if (!food.isFood()) return;
| FoodList foodList = FoodList.get(player); | 2 |
sherlok/sherlok | src/main/java/org/sherlok/mappings/PipelineDef.java | [
"public static void validateArgument(boolean expression, String errorMessage)\n throws SherlokException {\n if (!expression) {\n throw new SherlokException(errorMessage);\n }\n}",
"public static void validateDomain(String domain) throws SherlokException {\n if (domain == null) {\n throw new SherlokException(\"domain cannot be null\");\n }\n\n validatePath(domain);\n\n if (ALPHANUM_DOT_UNDERSCORE_SLASH.matcher(domain).find()) {\n throw new SherlokException(\"domain '\" + domain\n + \"' contains something else than\"\n + \" letters, numbers or dots\");\n }\n}",
"public static void validateTypeIdentifier(String identifier,\n String errorMessage) throws SherlokException {\n\n if (!VALID_TYPE_IDENTIFIER.matcher(identifier).matches()) {\n throw new SherlokException(errorMessage);\n }\n}",
"public static <E> ArrayList<E> list() {\n return new ArrayList<E>();\n}",
"public static <K, V> HashMap<K, V> map() {\n return new HashMap<K, V>();\n}",
"public class Controller {\n protected static final Logger LOG = getLogger(Controller.class);\n\n // these act as caching:\n /** key:id, value:bundle */\n protected Map<String, BundleDef> bundleDefs;\n /** key:id, value:engine */\n protected Map<String, EngineDef> engineDefs;\n /** key:id, value:pipeline */\n protected Map<String, PipelineDef> pipelineDefs;\n\n /**\n * Loads {@link BundleDef}s and {@link PipelineDef}s from\n * {@link AetherResolver#LOCAL_REPO_PATH} folder, using {@link FileBased}.\n */\n public Controller load() throws SherlokException {\n Controller c;\n try {\n c = _load(FileBased.allBundleDefs(), FileBased.allPipelineDefs());\n } catch (SherlokException e) {\n throw e.setWhen(\"loading pipelines and bundles\");\n }\n\n LOG.info(\n \"Done loading from local File store ('{}'): {} bundles, {} engines and {} pipelines\",\n new Object[] { FileBased.CONFIG_DIR_PATH, bundleDefs.size(),\n engineDefs.size(), pipelineDefs.size() });\n return c;\n }\n\n /** Loads bundles and pipelines into this controller */\n protected Controller _load(Collection<BundleDef> bundles,\n Collection<PipelineDef> pipelines) throws SherlokException {\n\n // BUNDLES AND ENGINES\n bundleDefs = map(); // reinit\n engineDefs = map(); // reinit\n for (BundleDef b : bundles) {\n b.validate(b.toString());\n String key = b.getId();\n if (bundleDefs.containsKey(key)) {\n throw new SherlokException(\"duplicate bundle ids\", key);\n } else {\n // validate all engines\n for (EngineDef en : b.getEngines()) {\n en.validate();\n en.setBundle(b); // this reference is needed later on\n if (engineDefs.containsKey(en.getId())) {\n throw new SherlokException(\"duplicate engine ids\",\n en.getId());\n }\n }\n // once all are valid, add bundle and all engines\n for (EngineDef en : b.getEngines()) {\n engineDefs.put(en.getId(), en);\n }\n bundleDefs.put(key, b);\n }\n }\n\n // PIPELINES\n pipelineDefs = map(); // reinit\n for (PipelineDef pd : pipelines) {\n pd.validate(pd.toString());\n\n // all engines must have been previousely added above\n for (String pengineId : pd.getEnginesFromScript()) {\n\n validateId(pengineId, \"engine id '\" + pengineId\n + \"' in pipeline '\" + pd + \"'\");\n\n validateArgument(engineDefs.containsKey(pengineId),\n \"engine not found in any registered bundle\",\n format(\"'%s' defined in pipeline '%s'\", pengineId, pd),\n \"you might want to check the engine's name spelling\");\n }\n // no duplicate pipeline ids\n if (pipelineDefs.containsKey(pd.getId())) {\n throw new SherlokException(\"duplicate pipeline id\", pd.getId());\n } else {\n pipelineDefs.put(pd.getId(), pd);\n }\n }\n\n return this;\n }\n\n // /////////////////////////////////////////////////////////////////////\n // access API, package visibility\n\n // LIST all /////////////////////////////////////////////////////////////\n Collection<BundleDef> listBundles() {\n return bundleDefs.values();\n }\n\n Collection<PipelineDef> listPipelines() throws SherlokException {\n return pipelineDefs.values();\n }\n\n Collection<String> listResources() throws SherlokException {\n return FileBased.allResources();\n }\n\n // LIST all names /////////////////////////////////////////////////////////\n Set<String> listBundleDefNames() {\n return bundleDefs.keySet();\n }\n\n Set<String> listPipelineDefNames() {\n return pipelineDefs.keySet();\n }\n\n // GET by name /////////////////////////////////////////////////////////\n BundleDef getBundleDef(String bundleId) {\n return bundleDefs.get(bundleId);\n }\n\n EngineDef getEngineDef(String engineId) {\n return engineDefs.get(engineId);\n }\n\n PipelineDef getPipelineDef(String pipelineId) throws SherlokException {\n return pipelineDefs.get(pipelineId);\n }\n\n InputStream getResource(String path) throws SherlokException {\n return FileBased.getResource(path);\n }\n\n // PUT /////////////////////////////////////////////////////////////\n /** @return the put'ed {@link BundleDef}'s id */\n String putBundle(String bundleStr) throws SherlokException {\n BundleDef b = FileBased.putBundle(bundleStr);\n // update cached bundles and engines\n bundleDefs.put(b.getId(), b);\n for (EngineDef e : b.getEngines()) {\n e.setBundle(b);\n engineDefs.put(e.getId(), e);\n }\n return b.getId();\n }\n\n /** @return the put'ed {@link PipelineDef}'s id */\n String putPipeline(String pipelineStr) throws SherlokException {\n PipelineDef p = FileBased.putPipeline(pipelineStr, engineDefs.keySet());\n pipelineDefs.put(p.getId(), p);\n return p.getId();\n }\n\n void putResource(String path, Part part) throws SherlokException {\n FileBased.putResource(path, part);\n }\n\n // DELETE /////////////////////////////////////////////////////////////\n void deleteBundleDef(String bundleId) throws SherlokException {\n if (!bundleDefs.containsKey(bundleId)) {\n throw new SherlokException(\"bundle not found\", bundleId);\n } else {\n bundleDefs.remove(bundleId);\n FileBased.deleteBundle(bundleId);\n }\n }\n\n void deletePipelineDef(String pipelineId) throws SherlokException {\n if (!pipelineDefs.containsKey(pipelineId)) {\n throw new SherlokException(\"pipeline not found\", pipelineId);\n } else {\n String domain = pipelineDefs.get(pipelineId).getDomain();\n pipelineDefs.remove(pipelineId);\n FileBased.deletePipeline(pipelineId, domain);\n }\n }\n\n void deleteResource(String path) throws SherlokException {\n FileBased.deleteResource(path);\n }\n}",
"@JsonPropertyOrder({ \"name\", \"class\", \"description\", \"parameters\" })\n@JsonInclude(JsonInclude.Include.NON_DEFAULT)\npublic static class EngineDef {\n\n /**\n * an optional unique name for this bundle. Letters, numbers and\n * underscore only\n */\n private String name,\n\n /** (optional) */\n description;\n\n /** the Java UIMA class name of this engine. */\n @JsonProperty(\"class\")\n private String classz;\n\n /** UIMA parameters. To overwrite default parameters */\n // TODO serialize without [ ], by creating custom\n // serializer, see Def.LineSerializer\n private Map<String, List<String>> parameters = map();\n\n /** TRANSITIVE (JsonIgnore), dynamically set by the bundle. */\n @JsonIgnore\n private BundleDef bundle;\n\n // get/set\n\n /** @return the engine name. Falls back on {@link #classz's simple name}. */\n public String getName() {\n if (name != null) {\n return name;\n } else if (classz != null) {\n if (classz.contains(\".\")) {\n return classz.substring(classz.lastIndexOf(\".\") + 1,\n classz.length());\n } else { // no dot in class name --> just return it\n return classz;\n }\n }\n return null;\n }\n\n public EngineDef setName(String name) {\n this.name = name;\n return this;\n }\n\n public String getDescription() {\n return description;\n }\n\n public EngineDef setDescription(String description) {\n this.description = description;\n return this;\n }\n\n public String getClassz() {\n return classz;\n }\n\n public EngineDef setClassz(String classz) {\n this.classz = classz;\n return this;\n }\n\n public Map<String, List<String>> getParameters() {\n return parameters;\n }\n\n public EngineDef setParameters(Map<String, List<String>> parameters) {\n this.parameters = parameters;\n return this;\n }\n\n public EngineDef addParameter(String key, List<String> value) {\n this.parameters.put(key, value);\n return this;\n }\n\n public List<String> getParameter(String key) {\n return this.parameters.get(key);\n }\n\n public boolean validate() throws SherlokException {\n checkOnlyAlphanumDotUnderscore(name,\n \"EngineDef '\" + this.toString() + \"'' id\");\n return true;\n }\n\n public BundleDef getBundle() {\n return bundle;\n }\n\n /** Is set at load time by {@link Controller#_load()}. */\n public EngineDef setBundle(final BundleDef bundle) {\n this.bundle = bundle;\n return this;\n }\n\n /** Needs bundle to be set (see {@link #setBundle()}). */\n @JsonIgnore\n public String getId() {\n return createId(name, bundle.getVersion());\n }\n\n /** @return the id without non-alphanumeric, separated by separator */\n public String getIdForDescriptor(final String separator) {\n return getName().replaceAll(\"[^A-Za-z0-9]\", \"_\") + separator\n + bundle.getVersion().replaceAll(\"[^A-Za-z0-9]\", \"_\");\n }\n\n @Override\n public String toString() {\n return name;\n }\n}"
] | import static com.fasterxml.jackson.annotation.JsonInclude.Include.ALWAYS;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_DEFAULT;
import static org.sherlok.utils.CheckThat.validateArgument;
import static org.sherlok.utils.CheckThat.validateDomain;
import static org.sherlok.utils.CheckThat.validateTypeIdentifier;
import static org.sherlok.utils.Create.list;
import static org.sherlok.utils.Create.map;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.sherlok.Controller;
import org.sherlok.mappings.BundleDef.EngineDef;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize; | /**
* Copyright (C) 2014-2015 Renaud Richardet
*
* 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 org.sherlok.mappings;
/**
* A pipeline describes the steps to perform a text mining analysis. This
* analysis consists of a script that defines a list of steps to be performed on
* text (e.g. split words, remove determinants, annotate locations, ...).
*
* @author [email protected]
*/
// ensure property output order
@JsonPropertyOrder(value = { "name", "version", "description", "language",
"domain", "loadOnStartup", "scriptLines", "config", "output", "tests" }, alphabetic = true)
@JsonInclude(NON_DEFAULT)
public class PipelineDef extends Def {
/** Which language this pipeline works for (ISO code). Defaults to 'en' */
private String language = "en";
/** The list of engine definitions */
@JsonProperty("script")
@JsonSerialize(using = ListSerializer.class)
private List<String> scriptLines = list();
/** Controls the output of this pipeline */
private PipelineOutput output = new PipelineOutput();
/** Embedded (integration) tests */
@JsonInclude(ALWAYS)
private List<PipelineTest> tests = list();
/** Defines what kind of annotation this pipeline outputs */
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public static class PipelineOutput {
@JsonProperty("filter_annotations")
private List<String> annotationFilters = list();
@JsonProperty("include_annotations")
private List<String> annotationIncludes = list();
public List<String> getAnnotationFilters() {
return annotationFilters;
}
public PipelineOutput setAnnotationFilters(
List<String> annotationFilters) {
this.annotationFilters = annotationFilters;
return this;
}
public List<String> getAnnotationIncludes() {
return annotationIncludes;
}
public PipelineOutput setAnnotationIncludes(
List<String> annotationIncludes) {
this.annotationIncludes = annotationIncludes;
return this;
}
}
/**
* Tests one single input string against a list of expected
* {@link JsonAnnotation}s
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(NON_DEFAULT)
@JsonPropertyOrder(value = { "comment", "input", "expected", "comparison" }, alphabetic = true)
public static class PipelineTest {
public enum Comparison {
/** all expected {@link JsonAnnotation}s are present in system */
atLeast,
/** expected and system {@link JsonAnnotation}s are exactly equals */
exact;
}
private String comment;
private String input; | private Map<String, List<JsonAnnotation>> expected = map(); | 4 |
nkarasch/ChessGDX | core/src/nkarasch/chessgdx/view/renderers/OverlayRenderer.java | [
"public class GameCore implements ApplicationListener {\n\n\tpublic static final String TITLE = \"ChessGDX\";\n\n\tprivate Camera mCameraController;\n\tprivate ChessLogicController mLogicController;\n\tprivate BoardController mBoardController;\n\tprivate PerspectiveRenderer mPerspectiveRenderer;\n\tprivate OverlayRenderer mOverlayRenderer;\n\n\tprivate static Runnable rebootHook;\n\n\t/**\n\t * @param rebootHook\n\t * game restart hook\n\t */\n\tpublic GameCore(final Runnable rebootHook) {\n\t\tGameCore.rebootHook = rebootHook;\n\t}\n\n\t@Override\n\tpublic void create() {\n\t\tGraphicsSettings.setGraphics();\n\t\tmCameraController = new Camera();\n\t\tmOverlayRenderer = new OverlayRenderer(this);\n\t\tmLogicController = new ChessLogicController(mOverlayRenderer);\n\t\tmBoardController = new BoardController(mCameraController, mLogicController, mOverlayRenderer);\n\t\tmPerspectiveRenderer = new PerspectiveRenderer(mCameraController, mBoardController, mLogicController.getPlacement());\n\n\t\tGdx.input.setInputProcessor(new InputMultiplexer(mOverlayRenderer, mBoardController, mCameraController.getOrbitController()));\n\t}\n\n\t@Override\n\tpublic void render() {\n\t\tGdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);\n\t\tmCameraController.update();\n\t\tmPerspectiveRenderer.render();\n\t\tmOverlayRenderer.render();\n\t}\n\n\t@Override\n\tpublic void resize(int width, int height) {\n\t\t// requiring restart on resize instead, this would be tedious to set up\n\t}\n\n\t@Override\n\tpublic void pause() {\n\t\t// not supporting mobile\n\t}\n\n\t@Override\n\tpublic void resume() {\n\t\t// not supporting mobile\n\t}\n\n\t@Override\n\tpublic void dispose() {\n\t\tAssetHandler.getInstance().dispose();\n\t\tmLogicController.dispose();\n\t\tmOverlayRenderer.dispose();\n\t}\n\n\t/**\n\t * Restarts game client\n\t */\n\tpublic static void restart() {\n\t\tGdx.app.postRunnable(GameCore.rebootHook);\n\t}\n\n\t/**\n\t * Restores board back to the new game state\n\t * \n\t * @param isWhite\n\t * player color\n\t */\n\tpublic void newGame(boolean isWhite) {\n\t\tmBoardController.setPlayerColor(isWhite);\n\t\tmBoardController.resetList();\n\t\tmLogicController.resetPosition();\n\t\tmOverlayRenderer.getCheckmateDialog().setState(false, false);\n\t\tmOverlayRenderer.getMoveHistory().resetHistory();\n\t}\n}",
"public class MenuSkin extends Skin {\n\n\tpublic final static String TEX_LOW_ALPHA_GREY = \"low_alpha\";\n\n\tpublic final static String IB_KNIGHT_PROMOTION = \"knight_promotion\";\n\tpublic final static String IB_BISHOP_PROMOTION = \"bishop_promotion\";\n\tpublic final static String IB_ROOK_PROMOTION = \"rook_promotion\";\n\tpublic final static String IB_QUEEN_PROMOTION = \"queen_promotion\";\n\tpublic final static String IMG_LOADING_ICON = \"loading_icon\";\n\tpublic final static String IB_SETTINGS = \"settings_button\";\n\tpublic final static String IB_SLIDER = \"slider_button\";\n\tpublic final static String IB_EXIT = \"exit_button\";\n\tpublic final static String IB_NEW = \"new_button\";\n\tpublic final static String LB_LARGE = \"large_label\";\n\tpublic final static String LB_LARGE_NOBG = \"large_label_nobg\";\n\tpublic final static String LB_LARGE_WHITE = \"large_white_label\";\n\tpublic final static String LB_SMALL_WHITE = \"small_white_label\";\n\tpublic final static String LS_COLOR_CHOOSER = \"color_chooser_list\";\n\n\tprivate final Pixmap mHighAlphaGrey;\n\tprivate final Pixmap mLowAlphaGrey;\n\tprivate final Pixmap mFullWhite;\n\tprivate final Texture mLowAlphaGreyTexture;\n\tprivate final Texture mHighAlphaGreyTexture;\n\tprivate final Texture mFullWhiteTexture;\n\n\tpublic MenuSkin() {\n\n\t\tAssetHandler ah = AssetHandler.getInstance();\n\n\t\tmHighAlphaGrey = new Pixmap(4, 4, Format.RGBA8888);\n\t\tmHighAlphaGrey.setColor(0.0f, 0.0f, 0.0f, 0.8f);\n\t\tmHighAlphaGrey.fill();\n\n\t\tmLowAlphaGrey = new Pixmap(4, 4, Format.RGBA8888);\n\t\tmLowAlphaGrey.setColor(0.0f, 0.0f, 0.0f, 0.5f);\n\t\tmLowAlphaGrey.fill();\n\n\t\tmFullWhite = new Pixmap(4, 4, Format.RGBA8888);\n\t\tmFullWhite.setColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\tmFullWhite.fill();\n\n\t\tmLowAlphaGreyTexture = new Texture(mLowAlphaGrey);\n\t\tmHighAlphaGreyTexture = new Texture(mHighAlphaGrey);\n\n\t\tTextureRegionDrawable lowAlpha = new TextureRegionDrawable(new TextureRegion(mLowAlphaGreyTexture));\n\t\tadd(TEX_LOW_ALPHA_GREY, lowAlpha);\n\n\t\tTextureRegionDrawable highAlpha = new TextureRegionDrawable(new TextureRegion(mHighAlphaGreyTexture));\n\n\t\tFreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal(\"UI/Tuffy.ttf\"));\n\t\tFreeTypeFontParameter parameter = new FreeTypeFontParameter();\n\t\tparameter.size = 20;\n\n\t\tBitmapFont smallFont = generator.generateFont(parameter);\n\t\tparameter.size = 36;\n\n\t\tBitmapFont largeFont = generator.generateFont(parameter);\n\t\tgenerator.dispose();\n\t\tadd(\"default\", largeFont);\n\n\t\tImageButtonStyle settingsButtonStyle = new ImageButtonStyle();\n\t\tsettingsButtonStyle.imageUp = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/settings-unclicked.jpg\")));\n\t\tsettingsButtonStyle.imageDown = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/settings-clicked.jpg\")));\n\t\tadd(IB_SETTINGS, settingsButtonStyle);\n\n\t\tImageButtonStyle sliderStyle = new ImageButtonStyle();\n\t\tsliderStyle.imageUp = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/slide-unclicked.jpg\")));\n\t\tsliderStyle.imageDown = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/slide-clicked.jpg\")));\n\t\tadd(IB_SLIDER, sliderStyle);\n\n\t\tImageButtonStyle exitStyle = new ImageButtonStyle();\n\t\texitStyle.imageUp = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/exit.jpg\")));\n\t\tadd(IB_EXIT, exitStyle);\n\n\t\tTextButtonStyle newGameStyle = new TextButtonStyle(); \n\t\tnewGameStyle.up = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/button-down.jpg\")));\n\t\tnewGameStyle.down = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/button-down.jpg\")));\n\t\tnewGameStyle.font = largeFont;\n\t\tnewGameStyle.fontColor = Color.WHITE;\n\t\tadd(IB_NEW, newGameStyle);\n\n\t\tImageButtonStyle knightButton = new ImageButtonStyle();\n\t\tknightButton.up = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/knight-silhouette.png\")));\n\t\tadd(IB_KNIGHT_PROMOTION, knightButton);\n\n\t\tImageButtonStyle bishopButton = new ImageButtonStyle();\n\t\tbishopButton.up = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/bishop-silhouette.png\")));\n\t\tadd(IB_BISHOP_PROMOTION, bishopButton);\n\n\t\tImageButtonStyle rookButton = new ImageButtonStyle();\n\t\trookButton.up = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/rook-silhouette.png\")));\n\t\tadd(IB_ROOK_PROMOTION, rookButton);\n\n\t\tImageButtonStyle queenButton = new ImageButtonStyle();\n\t\tqueenButton.up = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/queen-silhouette.png\")));\n\t\tadd(IB_QUEEN_PROMOTION, queenButton);\n\n\t\tadd(IMG_LOADING_ICON, ah.getTexture(\"UI/loading.png\"));\n\n\t\tLabelStyle largeLabel = new LabelStyle();\n\t\tlargeLabel.background = lowAlpha;\n\t\tlargeLabel.font = largeFont;\n\t\tlargeLabel.fontColor = Color.WHITE;\n\t\tadd(LB_LARGE, largeLabel);\n\n\t\tLabelStyle largeLabelNoBackground = new LabelStyle();\n\t\tlargeLabelNoBackground.font = largeFont;\n\t\tlargeLabelNoBackground.fontColor = Color.WHITE;\n\t\tadd(LB_LARGE_NOBG, largeLabelNoBackground);\n\n\t\tLabelStyle smallLabel = new LabelStyle();\n\t\tsmallLabel.font = smallFont;\n\t\tsmallLabel.fontColor = Color.WHITE;\n\t\tadd(\"default\", smallLabel);\n\n\t\tLabelStyle largeWhiteLabel = new LabelStyle();\n\t\tlargeWhiteLabel.font = largeFont;\n\t\tlargeWhiteLabel.fontColor = Color.WHITE;\n\t\tlargeWhiteLabel.background = highAlpha;\n\t\tadd(LB_LARGE_WHITE, largeWhiteLabel);\n\n\t\tLabelStyle smallWhiteLabel = new LabelStyle();\n\t\tsmallWhiteLabel.font = smallFont;\n\t\tsmallWhiteLabel.fontColor = Color.WHITE;\n\t\tadd(LB_SMALL_WHITE, smallWhiteLabel);\n\n\t\tScrollPaneStyle scrollPane = new ScrollPaneStyle();\n\t\tscrollPane.background = lowAlpha;\n\t\tadd(\"default\", scrollPane);\n\n\t\tListStyle listStyle = new ListStyle();\n\t\tlistStyle.background = lowAlpha;\n\t\tlistStyle.font = smallFont;\n\t\tlistStyle.selection = highAlpha;\n\t\tlistStyle.fontColorSelected = Color.WHITE;\n\t\tlistStyle.fontColorUnselected = Color.WHITE;\n\t\tadd(\"default\", listStyle);\n\n\t\tmFullWhiteTexture = new Texture(mFullWhite);\n\t\tListStyle colorListStyle = new ListStyle();\n\t\tcolorListStyle.background = lowAlpha;\n\t\tcolorListStyle.font = smallFont;\n\t\tcolorListStyle.selection = new TextureRegionDrawable(new TextureRegion(mFullWhiteTexture));\n\t\tcolorListStyle.fontColorSelected = Color.BLACK;\n\t\tcolorListStyle.fontColorUnselected = Color.WHITE;\n\t\tadd(LS_COLOR_CHOOSER, colorListStyle);\n\n\t\tSelectBoxStyle selectBoxStyle = new SelectBoxStyle();\n\t\tselectBoxStyle.font = largeFont;\n\t\tselectBoxStyle.fontColor = Color.WHITE;\n\t\tselectBoxStyle.scrollStyle = scrollPane;\n\t\tselectBoxStyle.listStyle = listStyle;\n\t\tadd(\"default\", selectBoxStyle);\n\n\t\tCheckBoxStyle checkboxStyle = new CheckBoxStyle();\n\t\tcheckboxStyle.font = smallFont;\n\t\tcheckboxStyle.checkboxOff = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/checkbox-unchecked.jpg\")));\n\t\tcheckboxStyle.checkboxOn = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/checkbox-checked.jpg\")));\n\t\tadd(\"default\", checkboxStyle);\n\n\t\tTextButtonStyle ibStyle = new TextButtonStyle();\n\t\tibStyle.up = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/button-up.jpg\")));\n\t\tibStyle.down = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/button-down.jpg\")));\n\t\tibStyle.font = smallFont;\n\t\tibStyle.fontColor = Color.WHITE;\n\t\tadd(\"default\", ibStyle);\n\n\t\tWindowStyle window = new WindowStyle();\n\t\twindow.titleFont = largeFont;\n\t\twindow.stageBackground = new TextureRegionDrawable(new TextureRegion(mLowAlphaGreyTexture));\n\t\tadd(\"default\", window);\n\n\t\tTextFieldStyle textField = new TextFieldStyle();\n\t\ttextField.font = smallFont;\n\t\ttextField.fontColor = Color.WHITE;\n\t\ttextField.background = lowAlpha;\n\t\ttextField.disabledBackground = highAlpha;\n\t\ttextField.cursor = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/text-cursor.png\")));\n\t\tadd(\"default\", textField);\n\n\t\tSliderStyle slider = new SliderStyle();\n\t\tslider.background = highAlpha;\n\t\tslider.knob = new TextureRegionDrawable(new TextureRegion(ah.getTexture(\"UI/slider-knob.png\")));\n\t\tadd(\"default-horizontal\", slider);\n\t}\n\n\t/**\n\t * Destroys the Pixmap and Textures created with them, all non-generated\n\t * textures that are used are destroyed by AssetHandler\n\t */\n\tpublic void dispose() {\n\t\tmHighAlphaGrey.dispose();\n\t\tmLowAlphaGrey.dispose();\n\t\tmFullWhite.dispose();\n\t\tmLowAlphaGreyTexture.dispose();\n\t\tmHighAlphaGreyTexture.dispose();\n\t\tmFullWhiteTexture.dispose();\n\n\t\tsuper.dispose();\n\t}\n}",
"public class CheckMateTable extends Table {\n\n\tprivate final Label mCheckmate;\n\n\t/**\n\t * A label stored in a table that updates the user to whether the board is\n\t * in a check or checkmate state.\n\t * \n\t * @param skin\n\t */\n\tpublic CheckMateTable(Skin skin) {\n\t\tmCheckmate = new Label(\"\", skin, MenuSkin.LB_LARGE_NOBG);\n\t\tadd(mCheckmate);\n\t\tpack();\n\t\tsetPosition(Gdx.graphics.getWidth() / 2 - getWidth() / 2, Gdx.graphics.getHeight() - getHeight());\n\t}\n\n\t/**\n\t * Called every time a move is made to update the label informing the user\n\t * the board is either in check or checkmate.\n\t * \n\t * @param mate\n\t * is the board in a checkmate state\n\t * @param check\n\t * is the board in a check state\n\t */\n\tpublic void setState(boolean mate, boolean check) {\n\n\t\tint screenWidth = Gdx.graphics.getWidth();\n\t\tint screenHeight = Gdx.graphics.getHeight();\n\n\t\tif (!check && !mate) {\n\t\t\tsetPosition(screenWidth / 2 - getWidth() / 2, screenHeight - getHeight());\n\t\t\taddAction(Actions.fadeOut(0.5f));\n\t\t}\n\n\t\tif (check && !mate) {\n\t\t\tmCheckmate.setText(\"Check\");\n\t\t\tpack();\n\t\t\tsetPosition(screenWidth / 2 - getWidth() / 2, screenHeight - getHeight());\n\t\t\taddAction(Actions.fadeIn(0.5f));\n\t\t}\n\n\t\tif (mate) {\n\t\t\tmCheckmate.setText(\"Checkmate\");\n\t\t\tpack();\n\t\t\tsetPosition(screenWidth / 2 - getWidth() / 2, screenHeight - getHeight());\n\t\t\tsetTransform(true);\n\t\t\tsetOrigin(getWidth() / 2, getHeight() / 2);\n\t\t\taddAction(Actions.fadeIn(0.5f));\n\t\t\taddAction(Actions.moveTo(screenWidth / 2 - getWidth() / 2, screenHeight / 2 - getHeight() / 2, 1.0f));\n\t\t\taddAction(Actions.scaleTo(1.5f, 1.5f, 2.0f));\n\t\t}\n\t}\n}",
"public class EngineThinkingImage extends Image {\n\n\t/**\n\t * A spinning icon that tells the user the engine is currently processing\n\t * the next move.\n\t * \n\t * @param skin\n\t */\n\tpublic EngineThinkingImage(Skin skin) {\n\t\tsuper(skin, MenuSkin.IMG_LOADING_ICON);\n\t\tRepeatAction mSpinAction = new RepeatAction();\n\t\tmSpinAction.setCount(RepeatAction.FOREVER);\n\t\tmSpinAction.setAction(Actions.rotateBy(-360.0f, 1.0f));\n\n\t\tsetOrigin(getWidth() / 2, getHeight() / 2);\n\t\taddAction(mSpinAction);\n\n\t\tsetVisible(false);\n\t}\n}",
"public class ExitConfirmTable extends Table {\n\n\t/**\n\t * Asks the user if they are sure they want to exit.\n\t * @param skin\n\t */\n\tpublic ExitConfirmTable(Skin skin) {\n\t\tint screenWidth = Gdx.graphics.getWidth();\n\t\tint screenHeight = Gdx.graphics.getHeight();\n\t\t\n\t\tadd(new Label(\"Are you sure?\", skin, MenuSkin.LB_LARGE)).fill().colspan(2);\n\t\trow().fill();\n\n\t\tTextButton btYes = new TextButton(\"Yes\", skin, \"default\");\n\t\tbtYes.addListener(new ChangeListener() {\n\t\t\t@Override\n\t\t\tpublic void changed(ChangeEvent event, Actor actor) {\n\t\t\t\tGdx.app.exit();\n\t\t\t}\n\t\t});\n\t\tTextButton btNo = new TextButton(\"No\", skin, \"default\");\n\t\tbtNo.addListener(new ChangeListener() {\n\t\t\t@Override\n\t\t\tpublic void changed(ChangeEvent event, Actor actor) {\n\t\t\t\tsetVisible(false);\n\t\t\t}\n\t\t});\n\n\t\tadd(btYes).left();\n\t\tadd(btNo).left();\n\n\t\tsetVisible(false);\n\t\tpack();\n\t\tsetPosition(screenWidth / 2 - getWidth() / 2, screenHeight / 2 - getHeight() / 2);\n\t\tbackground(new TextureRegionDrawable(skin.get(MenuSkin.TEX_LOW_ALPHA_GREY, TextureRegionDrawable.class)));\n\t}\n}",
"public class PromotionTable extends Table {\n\n\tprivate short mSelected;\n\n\t/**\n\t * GUI element allowing the user to select queen, bishop, knight, or rook to\n\t * promote a pawn to.\n\t * \n\t * @param skin\n\t */\n\tpublic PromotionTable(Skin skin) {\n\n\t\tmSelected = Chess.NO_PIECE;\n\n\t\tint screenWidth = Gdx.graphics.getWidth();\n\t\tint screenHeight = Gdx.graphics.getHeight();\n\n\t\tImageButton queenButton = new ImageButton(skin, MenuSkin.IB_QUEEN_PROMOTION);\n\t\tImageButton bishopButton = new ImageButton(skin, MenuSkin.IB_BISHOP_PROMOTION);\n\t\tImageButton knightButton = new ImageButton(skin, MenuSkin.IB_KNIGHT_PROMOTION);\n\t\tImageButton rookButton = new ImageButton(skin, MenuSkin.IB_ROOK_PROMOTION);\n\n\t\tqueenButton.addListener(new ChangeListener() {\n\t\t\t@Override\n\t\t\tpublic void changed(ChangeEvent event, Actor actor) {\n\t\t\t\tmSelected = Chess.QUEEN;\n\t\t\t}\n\t\t});\n\n\t\tbishopButton.addListener(new ChangeListener() {\n\t\t\t@Override\n\t\t\tpublic void changed(ChangeEvent event, Actor actor) {\n\t\t\t\tmSelected = Chess.BISHOP;\n\t\t\t}\n\t\t});\n\n\t\tknightButton.addListener(new ChangeListener() {\n\t\t\t@Override\n\t\t\tpublic void changed(ChangeEvent event, Actor actor) {\n\t\t\t\tmSelected = Chess.KNIGHT;\n\t\t\t}\n\t\t});\n\n\t\trookButton.addListener(new ChangeListener() {\n\t\t\t@Override\n\t\t\tpublic void changed(ChangeEvent event, Actor actor) {\n\t\t\t\tmSelected = Chess.ROOK;\n\t\t\t}\n\t\t});\n\n\t\tadd(queenButton).width(screenHeight / 12).height(screenHeight / 6);\n\t\tadd(bishopButton).width(screenHeight / 12).height(screenHeight / 6);\n\t\tadd(knightButton).width(screenHeight / 12).height(screenHeight / 6);\n\t\tadd(rookButton).width(screenHeight / 12).height(screenHeight / 6);\n\t\trow();\n\t\tadd(new Label(\"Choose Promotion\", skin, MenuSkin.LB_LARGE)).colspan(4);\n\n\t\tpack();\n\t\tsetPosition(screenWidth / 2 - getWidth() / 2, screenHeight / 2 - getHeight() / 2);\n\n\t\tsetVisible(false);\n\t}\n\n\t/**\n\t * @return Chesspresso notation short representing the piece type the user\n\t * chose to promote their pawn to\n\t */\n\tpublic short getSelected() {\n\t\treturn mSelected;\n\t}\n\n\t/**\n\t * Hides the promotion dialogs\n\t */\n\tpublic void disable() {\n\t\tmSelected = Chess.NO_PIECE;\n\t\tsetVisible(false);\n\t}\n}",
"public class SettingsMenuGroup extends Group {\n\n\tprivate final SoundSettingsTable mSoundSettings;\n\tprivate final GraphicsSettingsTable mGraphicsSettings;\n\tprivate final EngineSettingsTable mEngineSettings;\n\tprivate final SettingsRootTable mSettingsRoot;\n\n\t/**\n\t * A group containing the settings dialog root menu, sound settings root\n\t * menu, engine settings root menu, and graphics settings root menu\n\t * \n\t * @param skin\n\t */\n\tpublic SettingsMenuGroup(Skin skin) {\n\t\tmGraphicsSettings = new GraphicsSettingsTable(skin);\n\t\tmEngineSettings = new EngineSettingsTable(skin);\n\t\tmSoundSettings = new SoundSettingsTable(skin);\n\t\tmSettingsRoot = new SettingsRootTable(skin, this);\n\n\t\taddActor(mGraphicsSettings);\n\t\taddActor(mEngineSettings);\n\t\taddActor(mSoundSettings);\n\t\taddActor(mSettingsRoot);\n\t}\n\n\t/**\n\t * @return sound settings dialog box\n\t */\n\tSoundSettingsTable getSoundSettings() {\n\t\treturn mSoundSettings;\n\t}\n\n\t/**\n\t * @return graphics settings dialog box\n\t */\n\tGraphicsSettingsTable getGraphicsSettings() {\n\t\treturn mGraphicsSettings;\n\t}\n\n\t/**\n\t * @return engine settings dialog box\n\t */\n\tEngineSettingsTable getEngineSettings() {\n\t\treturn mEngineSettings;\n\t}\n\n\t/**\n\t * @return root menu that lets the user select Graphics Settings, Engine\n\t * Settings, or Sound Settings\n\t */\n\tpublic SettingsRootTable getSettingsRoot() {\n\t\treturn mSettingsRoot;\n\t}\n}",
"public class MoveHistoryTable extends Table {\n\n\tprivate final static int SMALL_LABEL_SIZE = 27;\n\tprivate final static int BUTTON_SIZE = 64;\n\n\tprivate final Array<ChessPieceMove> mWhiteHistory;\n\tprivate final Array<ChessPieceMove> mBlackHistory;\n\n\tprivate final Array<Label> mWhiteMoves;\n\tprivate final Array<Label> mBlackMoves;\n\n\t/**\n\t * Displays the move history for both black and white.\n\t * \n\t * @param skin\n\t */\n\tMoveHistoryTable(Skin skin) {\n\n\t\tmWhiteHistory = new Array<ChessPieceMove>();\n\t\tmBlackHistory = new Array<ChessPieceMove>();\n\t\tmWhiteMoves = new Array<Label>();\n\t\tmBlackMoves = new Array<Label>();\n\n\t\tint screenHeight = Gdx.graphics.getHeight();\n\n\t\tsetWidth(screenHeight / 3);\n\t\tint numRows = ((screenHeight - BUTTON_SIZE * 3) / SMALL_LABEL_SIZE) - 1;\n\n\t\tfor (int i = 0; i < numRows; i++) {\n\t\t\tLabel blackLabel = new Label(\" \", skin, MenuSkin.LB_SMALL_WHITE);\n\t\t\tLabel whiteLabel = new Label(\" \", skin, MenuSkin.LB_SMALL_WHITE);\n\n\t\t\tblackLabel.setAlignment(Align.center);\n\t\t\twhiteLabel.setAlignment(Align.center);\n\n\t\t\tmWhiteMoves.add(whiteLabel);\n\t\t\tmBlackMoves.add(blackLabel);\n\t\t}\n\n\t\tLabel whiteHeader = new Label(\"White\", skin, MenuSkin.LB_LARGE_WHITE);\n\t\tLabel blackHeader = new Label(\"Black\", skin, MenuSkin.LB_LARGE_WHITE);\n\n\t\twhiteHeader.setAlignment(Align.center);\n\t\tblackHeader.setAlignment(Align.center);\n\n\t\tadd(whiteHeader).width(screenHeight / 6);\n\t\tadd(blackHeader).width(screenHeight / 6);\n\n\t\tfor (int i = 0; i < numRows; i++) {\n\t\t\trow();\n\t\t\tadd(mWhiteMoves.get(i)).center().fillX();\n\t\t\tadd(mBlackMoves.get(i)).center().fillX();\n\t\t}\n\n\t\tpack();\n\t\tsetHeight(screenHeight - BUTTON_SIZE * 3);\n\t\tsetPosition(Gdx.graphics.getWidth(), (screenHeight - getHeight() - BUTTON_SIZE * 4));\n\t}\n\n\t/**\n\t * Adds a move to the list.\n\t * \n\t * @param move\n\t * ChessPieceMove instance that contains information about the\n\t * players color, pieces starting position, and move destination.\n\t */\n\tpublic void addMove(ChessPieceMove move) {\n\t\tif (move.isWhite()) {\n\t\t\tmWhiteHistory.add(move);\n\t\t} else {\n\t\t\tmBlackHistory.add(move);\n\t\t}\n\n\t\tint j = 0;\n\t\tfor (int i = mWhiteHistory.size - 1; i >= 0; i--) {\n\t\t\tmWhiteMoves.get(j).setText(mWhiteHistory.get(i).toString());\n\t\t\tj++;\n\t\t\tif (j > mWhiteMoves.size - 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tj = 0;\n\t\tfor (int i = mBlackHistory.size - 1; i >= 0; i--) {\n\t\t\tmBlackMoves.get(j).setText(mBlackHistory.get(i).toString());\n\t\t\tj++;\n\t\t\tif (j > mBlackMoves.size - 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Clears move history list and removes the displayed text. Called when a\n\t * new game is made.\n\t */\n\tpublic void resetHistory() {\n\t\tmWhiteHistory.clear();\n\t\tmBlackHistory.clear();\n\n\t\tfor (Label label : mBlackMoves) {\n\t\t\tlabel.setText(\" \");\n\t\t}\n\n\t\tfor (Label label : mWhiteMoves) {\n\t\t\tlabel.setText(\" \");\n\t\t}\n\t}\n}",
"public class SlidingMenuGroup extends Group {\n\n\tprivate boolean mOpen;\n\tprivate final MoveHistoryTable mMoveHistory;\n\n\t/**\n\t * Group of all of the components that are part of the sliding menu and side\n\t * panel.\n\t * \n\t * @param skin\n\t * @param exitConfirm\n\t * exit confirmation dialog\n\t * @param settings\n\t * settings menu group\n\t * @param core\n\t * base of game, used by the NewGameTable for resetting the game\n\t * back to the launch state.\n\t */\n\tpublic SlidingMenuGroup(Skin skin, final ExitConfirmTable exitConfirm, final SettingsMenuGroup settings, GameCore core) {\n\n\t\tint screenWidth = Gdx.graphics.getWidth();\n\t\tfinal int screenHeight = Gdx.graphics.getHeight();\n\n\t\tfinal Image background = new Image(skin.get(MenuSkin.TEX_LOW_ALPHA_GREY, TextureRegionDrawable.class));\n\t\tfinal SliderMenuTable sliderMenu = new SliderMenuTable(skin);\n\t\tmMoveHistory = new MoveHistoryTable(skin);\n\t\tfinal NewGameTable newGameDialog = new NewGameTable(skin, core);\n\n\t\tbackground.setSize(screenHeight / 3, screenHeight);\n\t\tbackground.setPosition(screenWidth, 0);\n\n\t\taddActor(background);\n\t\taddActor(sliderMenu);\n\t\taddActor(mMoveHistory);\n\t\taddActor(newGameDialog);\n\n\t\tsliderMenu.getSliderButton().addListener(new ChangeListener() {\n\t\t\tpublic void changed(ChangeEvent event, Actor actor) {\n\t\t\t\tif (!mOpen) {\n\t\t\t\t\taddAction(Actions.moveBy(-screenHeight / 3, 0, 0.5f));\n\t\t\t\t\tmOpen = true;\n\t\t\t\t} else {\n\t\t\t\t\taddAction(Actions.moveBy(screenHeight / 3, 0, 0.5f));\n\t\t\t\t\tmOpen = false;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tsliderMenu.getSettingsButton().addListener(new ChangeListener() {\n\t\t\t@Override\n\t\t\tpublic void changed(ChangeEvent event, Actor actor) {\n\t\t\t\tif (settings.getSettingsRoot().isVisible()) {\n\t\t\t\t\tsettings.getSettingsRoot().setVisible(false);\n\t\t\t\t} else {\n\t\t\t\t\tsettings.getSettingsRoot().setVisible(true);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tsliderMenu.getExitButton().addListener(new ChangeListener() {\n\t\t\t@Override\n\t\t\tpublic void changed(ChangeEvent event, Actor actor) {\n\t\t\t\texitConfirm.setVisible(true);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * @return dialog that displays the move history of the current game\n\t */\n\tpublic MoveHistoryTable getMoveHistory() {\n\t\treturn mMoveHistory;\n\t}\n}"
] | import nkarasch.chessgdx.GameCore;
import nkarasch.chessgdx.gui.MenuSkin;
import nkarasch.chessgdx.gui.other.CheckMateTable;
import nkarasch.chessgdx.gui.other.EngineThinkingImage;
import nkarasch.chessgdx.gui.other.ExitConfirmTable;
import nkarasch.chessgdx.gui.other.PromotionTable;
import nkarasch.chessgdx.gui.settings.SettingsMenuGroup;
import nkarasch.chessgdx.gui.slider.MoveHistoryTable;
import nkarasch.chessgdx.gui.slider.SlidingMenuGroup;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin; | package nkarasch.chessgdx.view.renderers;
public class OverlayRenderer extends Stage {
private final Skin mSkin;
private final PromotionTable mPromotionDialog;
private final CheckMateTable mCheckmateDialog; | private final EngineThinkingImage mEngineThinking; | 3 |
sfPlayer1/Matcher | src/matcher/mapping/MappedElementComparators.java | [
"public enum NameType {\n\tPLAIN(true, false, false, 0),\n\tMAPPED(false, true, false, 0),\n\tAUX(false, false, false, 1),\n\tAUX2(false, false, false, 2),\n\n\tMAPPED_PLAIN(true, true, false, 0),\n\tMAPPED_AUX_PLAIN(true, true, false, 1),\n\tMAPPED_AUX2_PLAIN(true, true, false, 2),\n\tMAPPED_TMP_PLAIN(true, true, true, 0),\n\tMAPPED_LOCTMP_PLAIN(true, true, false, 0),\n\n\tUID_PLAIN(true, false, false, 0),\n\tTMP_PLAIN(true, false, true, 0),\n\tLOCTMP_PLAIN(true, false, false, 0),\n\tAUX_PLAIN(true, false, false, 1),\n\tAUX2_PLAIN(true, false, false, 2);\n\n\tNameType(boolean plain, boolean mapped, boolean tmp, int aux) {\n\t\tthis.plain = plain;\n\t\tthis.mapped = mapped;\n\t\tthis.tmp = tmp;\n\t\tthis.aux = aux;\n\t}\n\n\tpublic NameType withPlain(boolean value) {\n\t\tif (plain == value) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return MAPPED_PLAIN;\n\n\t\t\treturn VALUES[AUX_PLAIN.ordinal() + aux - 1];\n\t\t} else if (this == MAPPED_PLAIN) {\n\t\t\treturn MAPPED;\n\t\t} else if (aux > 0 && !mapped && !tmp) {\n\t\t\treturn VALUES[AUX.ordinal() + aux - 1];\n\t\t} else {\n\t\t\tthrow new UnsupportedOperationException();\n\t\t}\n\t}\n\n\tpublic NameType withMapped(boolean value) {\n\t\tif (mapped == value) return this;\n\n\t\tif (value) {\n\t\t\tif (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];\n\t\t\tif (tmp) return MAPPED_TMP_PLAIN;\n\t\t\tif (plain) return MAPPED_PLAIN;\n\n\t\t\treturn MAPPED;\n\t\t} else {\n\t\t\tif (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];\n\t\t\tif (tmp) return TMP_PLAIN;\n\t\t\tif (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;\n\n\t\t\treturn PLAIN;\n\t\t}\n\t}\n\n\tpublic NameType withAux(int index, boolean value) {\n\t\tif ((aux - 1 == index) == value) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];\n\t\t\tif (plain) return VALUES[AUX_PLAIN.ordinal() + index];\n\n\t\t\treturn VALUES[AUX.ordinal() + index];\n\t\t} else {\n\t\t\tif (mapped) return MAPPED_PLAIN;\n\n\t\t\treturn PLAIN;\n\t\t}\n\t}\n\n\tpublic NameType withTmp(boolean value) {\n\t\tif (tmp == value) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return MAPPED_TMP_PLAIN;\n\n\t\t\treturn TMP_PLAIN;\n\t\t} else {\n\t\t\tif (mapped) return MAPPED_PLAIN;\n\n\t\t\treturn PLAIN;\n\t\t}\n\t}\n\n\t// transform between tmp <-> loctmp\n\tpublic NameType withUnmatchedTmp(boolean value) {\n\t\tboolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;\n\n\t\tif (value == locTmp || !tmp && !locTmp) return this;\n\n\t\tif (value) {\n\t\t\tif (mapped) return MAPPED_LOCTMP_PLAIN;\n\n\t\t\treturn LOCTMP_PLAIN;\n\t\t} else {\n\t\t\tif (mapped) return MAPPED_TMP_PLAIN;\n\n\t\t\treturn TMP_PLAIN;\n\t\t}\n\t}\n\n\tpublic boolean isAux() {\n\t\treturn aux > 0;\n\t}\n\n\tpublic int getAuxIndex() {\n\t\tif (aux == 0) throw new NoSuchElementException();\n\n\t\treturn aux - 1;\n\t}\n\n\tpublic static NameType getAux(int index) {\n\t\tObjects.checkIndex(index, AUX_COUNT);\n\n\t\treturn VALUES[NameType.AUX.ordinal() + index];\n\t}\n\n\tpublic static final int AUX_COUNT = 2;\n\n\tprivate static final NameType[] VALUES = values();\n\n\tpublic final boolean plain;\n\tpublic final boolean mapped;\n\tpublic final boolean tmp;\n\tprivate final int aux;\n}",
"public final class ClassInstance implements Matchable<ClassInstance> {\n\t/**\n\t * Create a shared unknown class.\n\t */\n\tClassInstance(String id, ClassEnv env) {\n\t\tthis(id, null, env, null, false, false, null);\n\n\t\tassert id.indexOf('[') == -1 : id;\n\t}\n\n\t/**\n\t * Create a known class (class path).\n\t */\n\tpublic ClassInstance(String id, URI origin, ClassEnv env, ClassNode asmNode) {\n\t\tthis(id, origin, env, asmNode, false, false, null);\n\n\t\tassert id.indexOf('[') == -1 : id;\n\t}\n\n\t/**\n\t * Create an array class.\n\t */\n\tClassInstance(String id, ClassInstance elementClass) {\n\t\tthis(id, null, elementClass.env, null, elementClass.nameObfuscated, false, elementClass);\n\n\t\tassert id.startsWith(\"[\") : id;\n\t\tassert id.indexOf('[', getArrayDimensions()) == -1 : id;\n\t\tassert !elementClass.isArray();\n\n\t\telementClass.addArray(this);\n\t}\n\n\t/**\n\t * Create a non-array class.\n\t */\n\tClassInstance(String id, URI origin, ClassEnv env, ClassNode asmNode, boolean nameObfuscated) {\n\t\tthis(id, origin, env, asmNode, nameObfuscated, true, null);\n\n\t\tassert id.startsWith(\"L\") : id;\n\t\tassert id.indexOf('[') == -1 : id;\n\t\tassert asmNode != null;\n\t}\n\n\tprivate ClassInstance(String id, URI origin, ClassEnv env, ClassNode asmNode, boolean nameObfuscated, boolean input, ClassInstance elementClass) {\n\t\tif (id.isEmpty()) throw new IllegalArgumentException(\"empty id\");\n\t\tif (env == null) throw new NullPointerException(\"null env\");\n\n\t\tthis.id = id;\n\t\tthis.origin = origin;\n\t\tthis.env = env;\n\t\tthis.asmNodes = asmNode == null ? null : new ClassNode[] { asmNode };\n\t\tthis.nameObfuscated = nameObfuscated;\n\t\tthis.input = input;\n\t\tthis.elementClass = elementClass;\n\n\t\tif (env.isShared()) matchedClass = this;\n\t}\n\n\t@Override\n\tpublic MatchableKind getKind() {\n\t\treturn MatchableKind.CLASS;\n\t}\n\n\t@Override\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t@Override\n\tpublic String getName() {\n\t\treturn getName(id);\n\t}\n\n\t@Override\n\tpublic String getName(NameType type) {\n\t\treturn getName(type, true);\n\t}\n\n\tpublic String getName(NameType type, boolean includeOuter) {\n\t\tif (type == NameType.PLAIN) {\n\t\t\treturn includeOuter ? getName() : getInnerName0(getName());\n\t\t} else if (elementClass != null) {\n\t\t\tboolean isPrimitive = elementClass.isPrimitive();\n\t\t\tStringBuilder ret = new StringBuilder();\n\n\t\t\tret.append(id, 0, getArrayDimensions());\n\n\t\t\tif (!isPrimitive) ret.append('L');\n\t\t\tret.append(elementClass.getName(type, includeOuter));\n\t\t\tif (!isPrimitive) ret.append(';');\n\n\t\t\treturn ret.toString();\n\t\t} else if (type == NameType.UID_PLAIN) {\n\t\t\tint uid = getUid();\n\t\t\tif (uid >= 0) return env.getGlobal().classUidPrefix+uid;\n\t\t}\n\n\t\tboolean locTmp = type == NameType.MAPPED_LOCTMP_PLAIN || type == NameType.LOCTMP_PLAIN;\n\t\tString ret;\n\t\tboolean fromMatched; // name retrieved from matched class\n\n\t\tif (type.mapped && mappedName != null) {\n\t\t\t// MAPPED_*, local name available\n\t\t\tret = mappedName;\n\t\t\tfromMatched = false;\n\t\t} else if (type.mapped && matchedClass != null && matchedClass.mappedName != null) {\n\t\t\t// MAPPED_*, remote name available\n\t\t\tret = matchedClass.mappedName;\n\t\t\tfromMatched = true;\n\t\t} else if (type.mapped && !nameObfuscated) {\n\t\t\t// MAPPED_*, local deobf\n\t\t\tret = getInnerName0(getName());\n\t\t\tfromMatched = false;\n\t\t} else if (type.mapped && matchedClass != null && !matchedClass.nameObfuscated) {\n\t\t\t// MAPPED_*, remote deobf\n\t\t\tret = matchedClass.getInnerName0(matchedClass.getName());\n\t\t\tfromMatched = true;\n\t\t} else if (type.isAux() && auxName != null && auxName.length > type.getAuxIndex() && auxName[type.getAuxIndex()] != null) {\n\t\t\tret = auxName[type.getAuxIndex()];\n\t\t\tfromMatched = false;\n\t\t} else if (type.isAux() && matchedClass != null && matchedClass.auxName != null && matchedClass.auxName.length > type.getAuxIndex() && matchedClass.auxName[type.getAuxIndex()] != null) {\n\t\t\tret = matchedClass.auxName[type.getAuxIndex()];\n\t\t\tfromMatched = true;\n\t\t} else if (type.tmp && matchedClass != null && matchedClass.tmpName != null) {\n\t\t\t// MAPPED_TMP_* with obf name or TMP_*, remote name available\n\t\t\tret = matchedClass.tmpName;\n\t\t\tfromMatched = true;\n\t\t} else if ((type.tmp || locTmp) && tmpName != null) {\n\t\t\t// MAPPED_TMP_* or MAPPED_LOCTMP_* with obf name or TMP_* or LOCTMP_*, local name available\n\t\t\tret = tmpName;\n\t\t\tfromMatched = false;\n\t\t} else if (type.plain) {\n\t\t\tret = getInnerName0(getName());\n\t\t\tfromMatched = false;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\n\t\tassert ret == null || !hasOuterName(ret) : ret;\n\n\t\tif (!includeOuter) return ret;\n\n\t\t/*\n\t\t * ret-outer: whether ret's source has an outer class\n\t\t * this-outer: whether this has an outer class\n\t\t * has outer class -> assume not normal name with pkg, but plain inner class name\n\t\t *\n\t\t * ret-outer this-outer action ret-example this-example result-example\n\t\t * n n ret a/b d/e a/b\n\t\t * n y this.outer+ret.strip-pkg a/b d/e$f d/e$b\n\t\t * y n ret.outer.pkg+ret a/b$c d/e a/c\n\t\t * y y this.outer+ret a/b$c d/e$f d/e$c\n\t\t */\n\n\t\tif (!fromMatched || (outerClass == null) == (matchedClass.outerClass == null)) { // ret-outer == this-outer\n\t\t\treturn outerClass != null ? getNestedName(outerClass.getName(type), ret) : ret;\n\t\t} else if (outerClass != null) { // ret is normal name, strip package from ret before concatenating\n\t\t\treturn getNestedName(outerClass.getName(type), ret.substring(ret.lastIndexOf('/') + 1));\n\t\t} else { // ret is an outer name, restore pkg\n\t\t\tString matchedOuterName = matchedClass.outerClass.getName(type);\n\t\t\tint pkgEnd = matchedOuterName.lastIndexOf('/');\n\t\t\tif (pkgEnd > 0) ret = matchedOuterName.substring(0, pkgEnd + 1).concat(ret);\n\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\tprivate String getInnerName0(String name) {\n\t\tif (outerClass == null && (isReal() || !hasOuterName(name))) {\n\t\t\treturn name;\n\t\t} else {\n\t\t\treturn getInnerName(name);\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getDisplayName(NameType type, boolean full) {\n\t\tchar lastChar = id.charAt(id.length() - 1);\n\t\tString ret;\n\n\t\tif (lastChar != ';') { // primitive or primitive array\n\t\t\tswitch (lastChar) {\n\t\t\tcase 'B': ret = \"byte\"; break;\n\t\t\tcase 'C': ret = \"char\"; break;\n\t\t\tcase 'D': ret = \"double\"; break;\n\t\t\tcase 'F': ret = \"float\"; break;\n\t\t\tcase 'I': ret = \"int\"; break;\n\t\t\tcase 'J': ret = \"long\"; break;\n\t\t\tcase 'S': ret = \"short\"; break;\n\t\t\tcase 'V': ret = \"void\"; break;\n\t\t\tcase 'Z': ret = \"boolean\"; break;\n\t\t\tdefault: throw new IllegalStateException(\"invalid class desc: \"+id);\n\t\t\t}\n\t\t} else {\n\t\t\tret = getName(type).replace('/', '.');\n\t\t}\n\n\t\tint dims = getArrayDimensions();\n\n\t\tif (dims > 0) {\n\t\t\tStringBuilder sb;\n\n\t\t\tif (lastChar != ';') { // primitive array, ret is in plain name form from above\n\t\t\t\tassert !ret.startsWith(\"[\") && !ret.endsWith(\";\");\n\n\t\t\t\tsb = new StringBuilder(ret.length() + 2 * dims);\n\t\t\t\tsb.append(ret);\n\t\t\t} else { // reference array, in dot separated id form\n\t\t\t\tassert ret.startsWith(\"[\") && ret.endsWith(\";\");\n\n\t\t\t\tsb = new StringBuilder(ret.length() + dims - 2);\n\t\t\t\tsb.append(ret, dims + 1, ret.length() - 1);\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < dims; i++) {\n\t\t\t\tsb.append(\"[]\");\n\t\t\t}\n\n\t\t\tret = sb.toString();\n\t\t}\n\n\t\treturn full ? ret : ret.substring(ret.lastIndexOf('.') + 1);\n\t}\n\n\tpublic boolean isReal() {\n\t\treturn origin != null;\n\t}\n\n\tpublic URI getOrigin() {\n\t\treturn origin;\n\t}\n\n\t@Override\n\tpublic Matchable<?> getOwner() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic ClassEnv getEnv() {\n\t\treturn env;\n\t}\n\n\tpublic ClassNode[] getAsmNodes() {\n\t\treturn asmNodes;\n\t}\n\n\tpublic URI getAsmNodeOrigin(int index) {\n\t\tif (index < 0 || index > 0 && (asmNodeOrigins == null || index >= asmNodeOrigins.length)) throw new IndexOutOfBoundsException(index);\n\n\t\treturn index == 0 ? origin : asmNodeOrigins[index];\n\t}\n\n\tpublic ClassNode getMergedAsmNode() {\n\t\tif (asmNodes == null) return null;\n\t\tif (asmNodes.length == 1) return asmNodes[0];\n\n\t\treturn asmNodes[0]; // TODO: actually merge\n\t}\n\n\tvoid addAsmNode(ClassNode node, URI origin) {\n\t\tif (!input) throw new IllegalStateException(\"not mergeable\");\n\n\t\tasmNodes = Arrays.copyOf(asmNodes, asmNodes.length + 1);\n\t\tasmNodes[asmNodes.length - 1] = node;\n\n\t\tif (asmNodeOrigins == null) {\n\t\t\tasmNodeOrigins = new URI[2];\n\t\t\tasmNodeOrigins[0] = this.origin;\n\t\t} else {\n\t\t\tasmNodeOrigins = Arrays.copyOf(asmNodeOrigins, asmNodeOrigins.length + 1);\n\t\t}\n\n\t\tasmNodeOrigins[asmNodeOrigins.length - 1] = origin;\n\t}\n\n\t@Override\n\tpublic boolean hasPotentialMatch() {\n\t\tif (matchedClass != null) return true;\n\t\tif (!isMatchable()) return false;\n\n\t\tfor (ClassInstance o : env.getOther().getClasses()) {\n\t\t\tif (o.isReal() && ClassifierUtil.checkPotentialEquality(this, o)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isMatchable() {\n\t\treturn matchable;\n\t}\n\n\t@Override\n\tpublic boolean setMatchable(boolean matchable) {\n\t\tif (!matchable && matchedClass != null) return false;\n\n\t\tthis.matchable = matchable;\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic ClassInstance getMatch() {\n\t\treturn matchedClass;\n\t}\n\n\tpublic void setMatch(ClassInstance cls) {\n\t\tassert cls == null || isMatchable();\n\t\tassert cls == null || cls.getEnv() != env && !cls.getEnv().isShared();\n\n\t\tthis.matchedClass = cls;\n\t}\n\n\t@Override\n\tpublic boolean isFullyMatched(boolean recursive) {\n\t\tif (matchedClass == null) return false;\n\n\t\tfor (MethodInstance m : methods) {\n\t\t\tif (m.hasPotentialMatch() && (!m.hasMatch() || recursive && !m.isFullyMatched(true))) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (FieldInstance m : fields) {\n\t\t\tif (m.hasPotentialMatch() && (!m.hasMatch() || recursive && !m.isFullyMatched(true))) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic float getSimilarity() {\n\t\tif (matchedClass == null) return 0;\n\n\t\treturn SimilarityChecker.compare(this, matchedClass);\n\t}\n\n\t@Override\n\tpublic boolean isNameObfuscated() {\n\t\treturn nameObfuscated;\n\t}\n\n\tpublic boolean isInput() {\n\t\treturn input;\n\t}\n\n\tpublic ClassInstance getElementClass() {\n\t\tif (!isArray()) throw new IllegalStateException(\"not applicable to non-array\");\n\n\t\treturn elementClass;\n\t}\n\n\tpublic ClassInstance getElementClassShallow(boolean create) {\n\t\tif (!isArray()) throw new IllegalStateException(\"not applicable to non-array\");\n\n\t\tint dims = getArrayDimensions();\n\t\tif (dims <= 1) return elementClass;\n\n\t\tString retId = id.substring(1);\n\n\t\treturn create ? env.getCreateClassInstance(retId) : env.getClsById(retId);\n\t}\n\n\tpublic ClassSignature getSignature() {\n\t\treturn signature;\n\t}\n\n\tvoid setSignature(ClassSignature signature) {\n\t\tthis.signature = signature;\n\t}\n\n\tpublic boolean isPrimitive() {\n\t\tchar start = id.charAt(0);\n\n\t\treturn start != 'L' && start != '[';\n\t}\n\n\tpublic int getSlotSize() {\n\t\tchar start = id.charAt(0);\n\n\t\treturn (start == 'D' || start == 'J') ? 2 : 1;\n\t}\n\n\tpublic boolean isArray() {\n\t\treturn elementClass != null;\n\t}\n\n\tpublic int getArrayDimensions() {\n\t\tif (elementClass == null) return 0;\n\n\t\tfor (int i = 0; i < id.length(); i++) {\n\t\t\tif (id.charAt(i) != '[') return i;\n\t\t}\n\n\t\tthrow new IllegalStateException(\"invalid id: \"+id);\n\t}\n\n\tpublic ClassInstance[] getArrays() {\n\t\treturn arrays;\n\t}\n\n\tprivate void addArray(ClassInstance cls) {\n\t\tassert !Arrays.asList(arrays).contains(cls);\n\n\t\tarrays = Arrays.copyOf(arrays, arrays.length + 1);\n\t\tarrays[arrays.length - 1] = cls;\n\t}\n\n\tpublic int getAccess() {\n\t\tint ret;\n\n\t\tif (asmNodes != null) {\n\t\t\tret = asmNodes[0].access;\n\n\t\t\tif (superClass != null && superClass.id.equals(\"Ljava/lang/Record;\")) { // ACC_RECORD is added by ASM through Record component attribute presence, don't trust the flag to handle stripping of the attribute\n\t\t\t\tret |= Opcodes.ACC_RECORD;\n\t\t\t}\n\t\t} else {\n\t\t\tret = Opcodes.ACC_PUBLIC;\n\n\t\t\tif (!implementers.isEmpty()) {\n\t\t\t\tret |= Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT;\n\t\t\t} else if (superClass != null && superClass.id.equals(\"Ljava/lang/Enum;\")) {\n\t\t\t\tret |= Opcodes.ACC_ENUM;\n\t\t\t\tif (childClasses.isEmpty()) ret |= Opcodes.ACC_FINAL;\n\t\t\t} else if (superClass != null && superClass.id.equals(\"Ljava/lang/Record;\")) {\n\t\t\t\tret |= Opcodes.ACC_RECORD;\n\t\t\t\tif (childClasses.isEmpty()) ret |= Opcodes.ACC_FINAL;\n\t\t\t} else if (interfaces.size() == 1 && interfaces.iterator().next().id.equals(\"Ljava/lang/annotation/Annotation;\")) {\n\t\t\t\tret |= Opcodes.ACC_ANNOTATION | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT;\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tpublic boolean isInterface() {\n\t\treturn (getAccess() & Opcodes.ACC_INTERFACE) != 0;\n\t}\n\n\tpublic boolean isEnum() {\n\t\treturn (getAccess() & Opcodes.ACC_ENUM) != 0;\n\t}\n\n\tpublic boolean isAnnotation() {\n\t\treturn (getAccess() & Opcodes.ACC_ANNOTATION) != 0;\n\t}\n\n\tpublic boolean isRecord() {\n\t\treturn (getAccess() & Opcodes.ACC_RECORD) != 0 || superClass != null && superClass.id.equals(\"Ljava/lang/Record;\");\n\t}\n\n\tpublic MethodInstance getMethod(String id) {\n\t\treturn methodIdx.get(id);\n\t}\n\n\tpublic FieldInstance getField(String id) {\n\t\treturn fieldIdx.get(id);\n\t}\n\n\tpublic MethodInstance getMethod(String name, String desc) {\n\t\tif (desc != null) {\n\t\t\treturn methodIdx.get(MethodInstance.getId(name, desc));\n\t\t} else {\n\t\t\tMethodInstance ret = null;\n\n\t\t\tfor (MethodInstance method : methods) {\n\t\t\t\tif (method.origName.equals(name)) {\n\t\t\t\t\tif (ret != null) return null; // non-unique\n\n\t\t\t\t\tret = method;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\tpublic MethodInstance getMethod(String name, String desc, NameType nameType) {\n\t\tif (nameType == NameType.PLAIN) return getMethod(name, desc);\n\n\t\tMethodInstance ret = null;\n\n\t\tmethodLoop: for (MethodInstance method : methods) {\n\t\t\tString mappedName = method.getName(nameType);\n\n\t\t\tif (mappedName == null || !name.equals(mappedName)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (desc != null) {\n\t\t\t\tassert desc.startsWith(\"(\");\n\t\t\t\tint idx = 0;\n\t\t\t\tint pos = 1;\n\t\t\t\tboolean last = false;\n\n\t\t\t\tdo {\n\t\t\t\t\tchar c = desc.charAt(pos);\n\t\t\t\t\tClassInstance match;\n\n\t\t\t\t\tif (c == ')') {\n\t\t\t\t\t\tif (idx != method.args.length) continue methodLoop;\n\t\t\t\t\t\tlast = true;\n\t\t\t\t\t\tpos++;\n\t\t\t\t\t\tc = desc.charAt(pos);\n\t\t\t\t\t\tmatch = method.retType;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (idx >= method.args.length) continue methodLoop;\n\t\t\t\t\t\tmatch = method.args[idx].type;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c == '[') { // array cls\n\t\t\t\t\t\tint dims = 1;\n\t\t\t\t\t\twhile ((c = desc.charAt(++pos)) == '[') dims++;\n\n\t\t\t\t\t\tif (match.getArrayDimensions() != dims) continue methodLoop;\n\t\t\t\t\t\tmatch = match.elementClass;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (match.isArray()) continue methodLoop;\n\t\t\t\t\t}\n\n\t\t\t\t\tint end;\n\n\t\t\t\t\tif (c != 'L') { // primitive cls\n\t\t\t\t\t\tend = pos + 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tend = desc.indexOf(';', pos + 1) + 1;\n\t\t\t\t\t\tassert end != 0;\n\t\t\t\t\t}\n\n\t\t\t\t\tString clsMappedName = match.getName(nameType);\n\t\t\t\t\tif (clsMappedName == null) continue methodLoop;\n\n\t\t\t\t\tif (c != 'L') {\n\t\t\t\t\t\tif (clsMappedName.length() != end - pos || !desc.startsWith(clsMappedName, pos)) continue methodLoop;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (clsMappedName.length() != end - pos - 2 || !desc.startsWith(clsMappedName, pos + 1)) continue methodLoop;\n\t\t\t\t\t}\n\n\t\t\t\t\tpos = end;\n\t\t\t\t\tidx++;\n\t\t\t\t} while (!last);\n\t\t\t}\n\n\t\t\tif (ret != null) return null; // non-unique\n\n\t\t\tret = method;\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tpublic FieldInstance getField(String name, String desc) {\n\t\tif (desc != null) {\n\t\t\treturn fieldIdx.get(FieldInstance.getId(name, desc));\n\t\t} else {\n\t\t\tFieldInstance ret = null;\n\n\t\t\tfor (FieldInstance field : fields) {\n\t\t\t\tif (field.origName.equals(name)) {\n\t\t\t\t\tif (ret != null) return null; // non-unique\n\n\t\t\t\t\tret = field;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\tpublic FieldInstance getField(String name, String desc, NameType nameType) {\n\t\tif (nameType == NameType.PLAIN) return getField(name, desc);\n\n\t\tFieldInstance ret = null;\n\n\t\tfor (FieldInstance field : fields) {\n\t\t\tString mappedName = field.getName(nameType);\n\n\t\t\tif (mappedName == null || !name.equals(mappedName)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (desc != null) {\n\t\t\t\tString clsMappedName = field.type.getName(nameType);\n\t\t\t\tif (clsMappedName == null) continue;\n\n\t\t\t\tif (desc.startsWith(\"[\") || !desc.endsWith(\";\")) {\n\t\t\t\t\tif (!desc.equals(clsMappedName)) continue;\n\t\t\t\t} else {\n\t\t\t\t\tif (desc.length() != clsMappedName.length() + 2 || !desc.startsWith(clsMappedName, 1)) continue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (ret != null) return null; // non-unique\n\n\t\t\tret = field;\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tpublic MethodInstance resolveMethod(String name, String desc, boolean toInterface) {\n\t\t// toInterface = false: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.4.3.3\n\t\t// toInterface = true: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.4.3.4\n\t\t// TODO: access check after resolution\n\n\t\tassert asmNodes == null || isInterface() == toInterface;\n\n\t\tif (!toInterface) {\n\t\t\tMethodInstance ret = resolveSignaturePolymorphicMethod(name);\n\t\t\tif (ret != null) return ret;\n\n\t\t\tret = getMethod(name, desc);\n\t\t\tif (ret != null) return ret; // <this> is unconditional\n\n\t\t\tClassInstance cls = this;\n\n\t\t\twhile ((cls = cls.superClass) != null) {\n\t\t\t\tret = cls.resolveSignaturePolymorphicMethod(name);\n\t\t\t\tif (ret != null) return ret;\n\n\t\t\t\tret = cls.getMethod(name, desc);\n\t\t\t\tif (ret != null) return ret;\n\t\t\t}\n\n\t\t\treturn resolveInterfaceMethod(name, desc);\n\t\t} else {\n\t\t\tMethodInstance ret = getMethod(name, desc);\n\t\t\tif (ret != null) return ret; // <this> is unconditional\n\n\t\t\tif (superClass != null) {\n\t\t\t\tassert superClass.id.equals(\"Ljava/lang/Object;\");\n\n\t\t\t\tret = superClass.getMethod(name, desc);\n\t\t\t\tif (ret != null && (!ret.isReal() || (ret.access & (Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC)) == Opcodes.ACC_PUBLIC)) return ret;\n\t\t\t}\n\n\t\t\treturn resolveInterfaceMethod(name, desc);\n\t\t}\n\t}\n\n\tprivate MethodInstance resolveSignaturePolymorphicMethod(String name) {\n\t\tif (id.equals(\"Ljava/lang/invoke/MethodHandle;\")) { // check for signature polymorphic method - jvms-2.9\n\t\t\tMethodInstance ret = getMethod(name, \"([Ljava/lang/Object;)Ljava/lang/Object;\");\n\t\t\tfinal int reqFlags = Opcodes.ACC_VARARGS | Opcodes.ACC_NATIVE;\n\n\t\t\tif (ret != null && (!ret.isReal() || (ret.access & reqFlags) == reqFlags)) {\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tprivate MethodInstance resolveInterfaceMethod(String name, String desc) {\n\t\tQueue<ClassInstance> queue = new ArrayDeque<>();\n\t\tSet<ClassInstance> queued = Util.newIdentityHashSet();\n\t\tClassInstance cls = this;\n\n\t\tdo {\n\t\t\tfor (ClassInstance ifCls : cls.interfaces) {\n\t\t\t\tif (queued.add(ifCls)) queue.add(ifCls);\n\t\t\t}\n\t\t} while ((cls = cls.superClass) != null);\n\n\t\tif (queue.isEmpty()) return null;\n\n\t\tSet<MethodInstance> matches = Util.newIdentityHashSet();\n\t\tboolean foundNonAbstract = false;\n\n\t\twhile ((cls = queue.poll()) != null) {\n\t\t\tMethodInstance ret = cls.getMethod(name, desc);\n\n\t\t\tif (ret != null\n\t\t\t\t\t&& (!ret.isReal() || (ret.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC)) == 0)) {\n\t\t\t\tmatches.add(ret);\n\n\t\t\t\tif (ret.isReal() && (ret.access & Opcodes.ACC_ABSTRACT) == 0) { // jvms prefers the closest non-abstract method\n\t\t\t\t\tfoundNonAbstract = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (ClassInstance ifCls : cls.interfaces) {\n\t\t\t\tif (queued.add(ifCls)) queue.add(ifCls);\n\t\t\t}\n\t\t}\n\n\t\tif (matches.isEmpty()) return null;\n\t\tif (matches.size() == 1) return matches.iterator().next();\n\n\t\t// non-abstract methods take precedence over non-abstract methods, remove all abstract ones if there's at least 1 non-abstract\n\n\t\tif (foundNonAbstract) {\n\t\t\tfor (Iterator<MethodInstance> it = matches.iterator(); it.hasNext(); ) {\n\t\t\t\tMethodInstance m = it.next();\n\n\t\t\t\tif (!m.isReal() || (m.access & Opcodes.ACC_ABSTRACT) != 0) {\n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tassert !matches.isEmpty();\n\t\t\tif (matches.size() == 1) return matches.iterator().next();\n\t\t}\n\n\t\t// eliminate not maximally specific method declarations, i.e. those that have a child method in matches\n\n\t\tfor (Iterator<MethodInstance> it = matches.iterator(); it.hasNext(); ) {\n\t\t\tMethodInstance m = it.next();\n\n\t\t\tcmpLoop: for (MethodInstance m2 : matches) {\n\t\t\t\tif (m2 == m) continue;\n\n\t\t\t\tif (m2.cls.interfaces.contains(m.cls)) { // m2 is a direct child of m, so m isn't maximally specific\n\t\t\t\t\tit.remove();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tqueue.addAll(m2.cls.interfaces);\n\n\t\t\t\twhile ((cls = queue.poll()) != null) {\n\t\t\t\t\tif (cls.interfaces.contains(m.cls)) { // m2 is an indirect child of m, so m isn't maximally specific\n\t\t\t\t\t\tit.remove();\n\t\t\t\t\t\tqueue.clear();\n\t\t\t\t\t\tbreak cmpLoop;\n\t\t\t\t\t}\n\n\t\t\t\t\tqueue.addAll(cls.interfaces);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// return an arbitrary choice\n\n\t\treturn matches.iterator().next();\n\t}\n\n\tpublic FieldInstance resolveField(String name, String desc) {\n\t\tFieldInstance ret = getField(name, desc);\n\t\tif (ret != null) return ret;\n\n\t\tif (!interfaces.isEmpty()) {\n\t\t\tDeque<ClassInstance> queue = new ArrayDeque<>();\n\t\t\tqueue.addAll(interfaces);\n\t\t\tClassInstance cls;\n\n\t\t\twhile ((cls = queue.pollFirst()) != null) {\n\t\t\t\tret = cls.getField(name, desc);\n\t\t\t\tif (ret != null) return ret;\n\n\t\t\t\tfor (ClassInstance iface : cls.interfaces) {\n\t\t\t\t\tqueue.addFirst(iface);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tClassInstance cls = superClass;\n\n\t\twhile (cls != null) {\n\t\t\tret = cls.getField(name, desc);\n\t\t\tif (ret != null) return ret;\n\n\t\t\tcls = cls.superClass;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic MethodInstance getMethod(int pos) {\n\t\tif (pos < 0 || pos >= methods.length) throw new IndexOutOfBoundsException();\n\t\tif (asmNodes == null) throw new UnsupportedOperationException();\n\n\t\treturn methods[pos];\n\t}\n\n\tpublic FieldInstance getField(int pos) {\n\t\tif (pos < 0 || pos >= fields.length) throw new IndexOutOfBoundsException();\n\t\tif (asmNodes == null) throw new UnsupportedOperationException();\n\n\t\treturn fields[pos];\n\t}\n\n\tpublic MethodInstance[] getMethods() {\n\t\treturn methods;\n\t}\n\n\tpublic FieldInstance[] getFields() {\n\t\treturn fields;\n\t}\n\n\tpublic ClassInstance getOuterClass() {\n\t\treturn outerClass;\n\t}\n\n\tpublic Set<ClassInstance> getInnerClasses() {\n\t\treturn innerClasses;\n\t}\n\n\tpublic ClassInstance getSuperClass() {\n\t\treturn superClass;\n\t}\n\n\tpublic Set<ClassInstance> getChildClasses() {\n\t\treturn childClasses;\n\t}\n\n\tpublic Set<ClassInstance> getInterfaces() {\n\t\treturn interfaces;\n\t}\n\n\tpublic Set<ClassInstance> getImplementers() {\n\t\treturn implementers;\n\t}\n\n\tpublic Set<MethodInstance> getMethodTypeRefs() {\n\t\treturn methodTypeRefs;\n\t}\n\n\tpublic Set<FieldInstance> getFieldTypeRefs() {\n\t\treturn fieldTypeRefs;\n\t}\n\n\tpublic Set<String> getStrings() {\n\t\treturn strings;\n\t}\n\n\tpublic boolean isShared() {\n\t\treturn matchedClass == this;\n\t}\n\n\t@Override\n\tpublic boolean hasLocalTmpName() {\n\t\treturn tmpName != null;\n\t}\n\n\tpublic void setTmpName(String tmpName) {\n\t\tthis.tmpName = tmpName;\n\t}\n\n\t@Override\n\tpublic int getUid() {\n\t\tif (uid >= 0) {\n\t\t\tif (matchedClass != null && matchedClass.uid >= 0) {\n\t\t\t\treturn Math.min(uid, matchedClass.uid);\n\t\t\t} else {\n\t\t\t\treturn uid;\n\t\t\t}\n\t\t} else if (matchedClass != null) {\n\t\t\treturn matchedClass.uid;\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic void setUid(int uid) {\n\t\tthis.uid = uid;\n\t}\n\n\t@Override\n\tpublic boolean hasMappedName() {\n\t\treturn mappedName != null\n\t\t\t\t|| matchedClass != null && matchedClass.mappedName != null\n\t\t\t\t|| elementClass != null && elementClass.hasMappedName()\n\t\t\t\t/*|| outerClass != null && outerClass.hasMappedName() TODO: for anonymous only?*/;\n\t}\n\n\tpublic boolean hasNoFullyMappedName() {\n\t\tassert elementClass == null || outerClass == null; // array classes can't have an outer class\n\n\t\treturn outerClass != null\n\t\t\t\t&& mappedName == null\n\t\t\t\t&& (matchedClass == null || matchedClass.mappedName == null);\n\t}\n\n\tpublic void setMappedName(String mappedName) {\n\t\tassert mappedName == null || !hasOuterName(mappedName);\n\n\t\tthis.mappedName = mappedName;\n\t}\n\n\t@Override\n\tpublic String getMappedComment() {\n\t\tif (mappedComment != null) {\n\t\t\treturn mappedComment;\n\t\t} else if (matchedClass != null) {\n\t\t\treturn matchedClass.mappedComment;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setMappedComment(String comment) {\n\t\tif (comment != null && comment.isEmpty()) comment = null;\n\n\t\tthis.mappedComment = comment;\n\t}\n\n\t@Override\n\tpublic boolean hasAuxName(int index) {\n\t\treturn auxName != null && auxName.length > index && auxName[index] != null;\n\t}\n\n\tpublic void setAuxName(int index, String name) {\n\t\tassert name == null || !hasOuterName(name);\n\n\t\tif (this.auxName == null) this.auxName = new String[NameType.AUX_COUNT];\n\t\tthis.auxName[index] = name;\n\t}\n\n\tpublic boolean isAssignableFrom(ClassInstance c) {\n\t\tif (c == this) return true;\n\t\tif (isPrimitive()) return false;\n\n\t\tif (!isInterface()) {\n\t\t\tClassInstance sc = c;\n\n\t\t\twhile ((sc = sc.superClass) != null) {\n\t\t\t\tif (sc == this) return true;\n\t\t\t}\n\t\t} else {\n\t\t\tif (implementers.isEmpty()) return false;\n\n\t\t\t// check if c directly implements this\n\t\t\tif (implementers.contains(c)) return true;\n\n\t\t\t// check if a superclass of c directly implements this\n\t\t\tClassInstance sc = c;\n\n\t\t\twhile ((sc = sc.superClass) != null) {\n\t\t\t\tif (implementers.contains(sc)) return true; // cls -> this\n\t\t\t}\n\n\t\t\t// check if c or a superclass of c implements this with one indirection\n\t\t\tsc = c;\n\t\t\tQueue<ClassInstance> toCheck = null;\n\n\t\t\tdo {\n\t\t\t\tfor (ClassInstance iface : sc.getInterfaces()) {\n\t\t\t\t\tassert iface != this; // already checked iface directly\n\t\t\t\t\tif (iface.interfaces.isEmpty()) continue;\n\t\t\t\t\tif (implementers.contains(iface)) return true; // cls -> if -> this\n\n\t\t\t\t\tif (toCheck == null) toCheck = new ArrayDeque<>();\n\n\t\t\t\t\ttoCheck.addAll(iface.interfaces);\n\t\t\t\t}\n\t\t\t} while ((sc = sc.superClass) != null);\n\n\t\t\t// check if c or a superclass of c implements this with multiple indirections\n\t\t\tif (toCheck != null) {\n\t\t\t\twhile ((sc = toCheck.poll()) != null) {\n\t\t\t\t\tfor (ClassInstance iface : sc.getInterfaces()) {\n\t\t\t\t\t\tassert iface != this; // already checked\n\n\t\t\t\t\t\tif (implementers.contains(iface)) return true;\n\n\t\t\t\t\t\ttoCheck.addAll(iface.interfaces);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic ClassInstance getCommonSuperClass(ClassInstance o) {\n\t\tif (o == this) return this;\n\t\tif (isPrimitive() || o.isPrimitive()) return null;\n\t\tif (isAssignableFrom(o)) return this;\n\t\tif (o.isAssignableFrom(this)) return o;\n\n\t\tClassInstance objCls = env.getCreateClassInstance(\"Ljava/lang/Object;\");\n\n\t\tif (!isInterface() && !o.isInterface()) {\n\t\t\tClassInstance sc = this;\n\n\t\t\twhile ((sc = sc.superClass) != null && sc != objCls) {\n\t\t\t\tif (sc.isAssignableFrom(o)) return sc;\n\t\t\t}\n\t\t}\n\n\t\tif (!interfaces.isEmpty() || !o.interfaces.isEmpty()) {\n\t\t\tList<ClassInstance> ret = new ArrayList<>();\n\t\t\tQueue<ClassInstance> toCheck = new ArrayDeque<>();\n\t\t\tSet<ClassInstance> checked = Util.newIdentityHashSet();\n\t\t\ttoCheck.addAll(interfaces);\n\t\t\ttoCheck.addAll(o.interfaces);\n\n\t\t\tClassInstance cls;\n\n\t\t\twhile ((cls = toCheck.poll()) != null) {\n\t\t\t\tif (!checked.add(cls)) continue;\n\n\t\t\t\tif (cls.isAssignableFrom(o)) {\n\t\t\t\t\tret.add(cls);\n\t\t\t\t} else {\n\t\t\t\t\ttoCheck.addAll(cls.interfaces);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!ret.isEmpty()) {\n\t\t\t\tif (ret.size() >= 1) {\n\t\t\t\t\tfor (Iterator<ClassInstance> it = ret.iterator(); it.hasNext(); ) {\n\t\t\t\t\t\tcls = it.next();\n\n\t\t\t\t\t\tfor (ClassInstance cls2 : ret) {\n\t\t\t\t\t\t\tif (cls != cls2 && cls.isAssignableFrom(cls2)) {\n\t\t\t\t\t\t\t\tit.remove();\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// TODO: multiple options..\n\t\t\t\t}\n\n\t\t\t\treturn ret.get(0);\n\t\t\t}\n\t\t}\n\n\t\treturn objCls;\n\t}\n\n\tpublic void accept(ClassVisitor visitor, NameType nameType) {\n\t\tClassNode cn = getMergedAsmNode();\n\t\tif (cn == null) throw new IllegalArgumentException(\"cls without asm node: \"+this);\n\n\t\tsynchronized (Util.asmNodeSync) {\n\t\t\tif (nameType != NameType.PLAIN) {\n\t\t\t\tAsmClassRemapper.process(cn, new AsmRemapper(env, nameType), visitor);\n\t\t\t} else {\n\t\t\t\tcn.accept(visitor);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic byte[] serialize(NameType nameType) {\n\t\tClassWriter writer = new ClassWriter(0);\n\t\taccept(writer, nameType);\n\n\t\treturn writer.toByteArray();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn getDisplayName(NameType.PLAIN, true);\n\t}\n\n\tvoid addMethod(MethodInstance method) {\n\t\tif (method == null) throw new NullPointerException(\"null method\");\n\n\t\tmethodIdx.put(method.id, method);\n\t\tmethods = Arrays.copyOf(methods, methods.length + 1);\n\t\tmethods[methods.length - 1] = method;\n\t}\n\n\tvoid addField(FieldInstance field) {\n\t\tif (field == null) throw new NullPointerException(\"null field\");\n\n\t\tfieldIdx.put(field.id, field);\n\t\tfields = Arrays.copyOf(fields, fields.length + 1);\n\t\tfields[fields.length - 1] = field;\n\t}\n\n\tpublic static String getId(String name) {\n\t\tif (name.isEmpty()) throw new IllegalArgumentException(\"empty class name\");\n\t\tassert name.charAt(name.length() - 1) != ';' || name.charAt(0) == '[' : name;\n\n\t\tif (name.charAt(0) == '[') {\n\t\t\tassert name.charAt(name.length() - 1) == ';' || name.lastIndexOf('[') == name.length() - 2;\n\n\t\t\treturn name;\n\t\t}\n\n\t\treturn \"L\"+name+\";\";\n\t}\n\n\tpublic static String getName(String id) {\n\t\treturn id.startsWith(\"L\") ? id.substring(1, id.length() - 1) : id;\n\t}\n\n\tpublic static boolean hasOuterName(String name) {\n\t\tint pos = name.indexOf('$');\n\n\t\treturn pos > 0 && name.charAt(pos - 1) != '/'; // ignore names starting with $\n\t}\n\n\tpublic static String getInnerName(String name) {\n\t\treturn name.substring(name.lastIndexOf('$') + 1);\n\t}\n\n\tpublic static String getNestedName(String outerName, String innerName) {\n\t\tif (outerName == null || innerName == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn outerName + '$' + innerName;\n\t\t}\n\t}\n\n\tpublic static final Comparator<ClassInstance> nameComparator = Comparator.comparing(ClassInstance::getName);\n\n\tprivate static final ClassInstance[] noArrays = new ClassInstance[0];\n\tprivate static final MethodInstance[] noMethods = new MethodInstance[0];\n\tprivate static final FieldInstance[] noFields = new FieldInstance[0];\n\n\tfinal String id;\n\tprivate final URI origin;\n\tfinal ClassEnv env;\n\tprivate ClassNode[] asmNodes;\n\tprivate URI[] asmNodeOrigins;\n\tfinal boolean nameObfuscated;\n\tprivate final boolean input;\n\tfinal ClassInstance elementClass; // 0-dim class TODO: improve handling of array classes (references etc.)\n\tprivate ClassSignature signature;\n\n\tMethodInstance[] methods = noMethods;\n\tFieldInstance[] fields = noFields;\n\tfinal Map<String, MethodInstance> methodIdx = new HashMap<>();\n\tfinal Map<String, FieldInstance> fieldIdx = new HashMap<>();\n\n\tprivate ClassInstance[] arrays = noArrays;\n\n\tClassInstance outerClass;\n\tfinal Set<ClassInstance> innerClasses = Util.newIdentityHashSet();\n\n\tClassInstance superClass;\n\tfinal Set<ClassInstance> childClasses = Util.newIdentityHashSet();\n\tfinal Set<ClassInstance> interfaces = Util.newIdentityHashSet();\n\tfinal Set<ClassInstance> implementers = Util.newIdentityHashSet();\n\n\tfinal Set<MethodInstance> methodTypeRefs = Util.newIdentityHashSet();\n\tfinal Set<FieldInstance> fieldTypeRefs = Util.newIdentityHashSet();\n\n\tfinal Set<String> strings = new HashSet<>();\n\n\tprivate String tmpName;\n\tprivate int uid = -1;\n\n\tprivate String mappedName;\n\tprivate String mappedComment;\n\n\tprivate String[] auxName;\n\n\tprivate boolean matchable = true;\n\tprivate ClassInstance matchedClass;\n}",
"public interface Matchable<T extends Matchable<T>> {\n\tMatchableKind getKind();\n\n\tString getId();\n\tString getName();\n\tString getName(NameType type);\n\n\tdefault String getDisplayName(NameType type, boolean full) {\n\t\treturn getName(type);\n\t}\n\n\tboolean hasMappedName();\n\tboolean hasLocalTmpName();\n\tboolean hasAuxName(int index);\n\n\tString getMappedComment();\n\tvoid setMappedComment(String comment);\n\n\tMatchable<?> getOwner();\n\tClassEnv getEnv();\n\n\tint getUid();\n\n\tboolean hasPotentialMatch();\n\n\tboolean isMatchable();\n\tboolean setMatchable(boolean matchable);\n\n\tdefault boolean hasMatch() {\n\t\treturn getMatch() != null;\n\t}\n\n\tT getMatch();\n\tboolean isFullyMatched(boolean recursive);\n\tfloat getSimilarity();\n\tboolean isNameObfuscated();\n}",
"public abstract class MemberInstance<T extends MemberInstance<T>> implements Matchable<T> {\n\t@SuppressWarnings(\"unchecked\")\n\tprotected MemberInstance(ClassInstance cls, String id, String origName, boolean nameObfuscated, int position, boolean isStatic) {\n\t\tthis.cls = cls;\n\t\tthis.id = id;\n\t\tthis.origName = origName;\n\t\tthis.nameObfuscatedLocal = nameObfuscated;\n\t\tthis.position = position;\n\t\tthis.isStatic = isStatic;\n\n\t\tif (cls.isShared()) {\n\t\t\tmatchedInstance = (T) this;\n\t\t}\n\t}\n\n\tpublic final ClassInstance getCls() {\n\t\treturn cls;\n\t}\n\n\t@Override\n\tpublic final String getId() {\n\t\treturn id;\n\t}\n\n\t@Override\n\tpublic final String getName() {\n\t\treturn origName;\n\t}\n\n\t@Override\n\tpublic String getName(NameType type) {\n\t\tif (type == NameType.PLAIN) {\n\t\t\treturn origName;\n\t\t} else if (type == NameType.UID_PLAIN) {\n\t\t\tint uid = getUid();\n\t\t\tif (uid >= 0) return getUidString();\n\t\t}\n\n\t\tboolean locTmp = type == NameType.MAPPED_LOCTMP_PLAIN || type == NameType.LOCTMP_PLAIN;\n\t\tString ret;\n\n\t\tif (type.mapped && cls.isInput() && (ret = getMappedName()) != null) {\n\t\t\t// MAPPED_*, mapped name available\n\t\t} else if (type.mapped && !isNameObfuscated()) {\n\t\t\t// MAPPED_*, local deobf\n\t\t\tret = origName;\n\t\t} else if (type.mapped && matchedInstance != null && !matchedInstance.isNameObfuscated()) {\n\t\t\t// MAPPED_*, remote deobf\n\t\t\tret = matchedInstance.origName;\n\t\t} else if (type.isAux() && cls.isInput() && (ret = getAuxName(type.getAuxIndex())) != null) {\n\t\t\t// *_AUX*, aux available\n\t\t} else if (type.tmp && cls.isInput() && (ret = getTmpName()) != null) {\n\t\t\t// MAPPED_TMP_* with obf name or TMP_*, remote name available\n\t\t} else if ((type.tmp || locTmp) && hierarchyData != null && hierarchyData.tmpName != null) {\n\t\t\t// MAPPED_TMP_* or MAPPED_LOCTMP_* with obf name or TMP_* or LOCTMP_*, local name available\n\t\t\tret = hierarchyData.tmpName;\n\t\t} else if (type.plain) {\n\t\t\tret = origName;\n\t\t} else {\n\t\t\tret = null;\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\t@Override\n\tpublic String getDisplayName(NameType type, boolean full) {\n\t\tString name = getName(type);\n\n\t\tif (full) {\n\t\t\treturn cls.getDisplayName(type, full) + \".\" + name;\n\t\t} else {\n\t\t\treturn name;\n\t\t}\n\t}\n\n\tpublic abstract String getDesc();\n\tpublic abstract String getDesc(NameType type);\n\tpublic abstract boolean isReal();\n\n\t@Override\n\tpublic Matchable<?> getOwner() {\n\t\treturn cls;\n\t}\n\n\t@Override\n\tpublic ClassEnv getEnv() {\n\t\treturn cls.getEnv();\n\t}\n\n\t@Override\n\tpublic boolean isNameObfuscated() {\n\t\treturn hierarchyData == null ? nameObfuscatedLocal : hierarchyData.nameObfuscated;\n\t}\n\n\tpublic int getPosition() {\n\t\treturn position;\n\t}\n\n\tpublic abstract int getAccess();\n\n\tpublic boolean isStatic() {\n\t\treturn isStatic;\n\t}\n\n\tpublic boolean isPublic() {\n\t\treturn (getAccess() & Opcodes.ACC_PUBLIC) != 0;\n\t}\n\n\tpublic boolean isProtected() {\n\t\treturn (getAccess() & Opcodes.ACC_PROTECTED) != 0;\n\t}\n\n\tpublic boolean isPrivate() {\n\t\treturn (getAccess() & Opcodes.ACC_PRIVATE) != 0;\n\t}\n\n\tpublic boolean isFinal() {\n\t\treturn (getAccess() & Opcodes.ACC_FINAL) != 0;\n\t}\n\n\tpublic boolean isSynthetic() {\n\t\treturn (getAccess() & Opcodes.ACC_SYNTHETIC) != 0;\n\t}\n\n\tpublic abstract boolean canBeRecordComponent();\n\tpublic abstract MemberInstance<?> getLinkedRecordComponent(NameType nameType);\n\n\tvoid addParent(T parent) {\n\t\tassert parent.getCls() != getCls();\n\t\tassert parent != this;\n\t\tassert !children.contains(parent);\n\n\t\tif (parents.isEmpty()) parents = Util.newIdentityHashSet();\n\n\t\tparents.add(parent);\n\t}\n\n\tpublic Set<T> getParents() {\n\t\treturn parents;\n\t}\n\n\tvoid addChild(T child) {\n\t\tassert child.getCls() != getCls();\n\t\tassert child != this;\n\t\tassert !parents.contains(child);\n\n\t\tif (children.isEmpty()) children = Util.newIdentityHashSet();\n\n\t\tchildren.add(child);\n\t}\n\n\tpublic Set<T> getChildren() {\n\t\treturn children;\n\t}\n\n\tpublic T getHierarchyMatch() {\n\t\tassert hierarchyData != null; // only available for input classes\n\n\t\tif (hierarchyData.matchedHierarchy == null) return null;\n\n\t\tT ret = getMatch();\n\t\tif (ret != null) return ret;\n\n\t\tClassEnv reqEnv = cls.getEnv();\n\n\t\tfor (T m : hierarchyData.getMembers()) {\n\t\t\tret = m.getMatch();\n\n\t\t\tif (ret != null) {\n\t\t\t\tClassEnv env = m.cls.getEnv();\n\n\t\t\t\tif (env.isShared() || env == reqEnv) {\n\t\t\t\t\treturn ret;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic Set<T> getAllHierarchyMembers() {\n\t\tassert hierarchyData != null; // only available for input classes\n\n\t\treturn hierarchyData.getMembers();\n\t}\n\n\t@Override\n\tpublic boolean hasLocalTmpName() {\n\t\treturn hierarchyData != null && hierarchyData.tmpName != null;\n\t}\n\n\tprivate String getTmpName() {\n\t\tassert hierarchyData != null; // only available for input classes\n\n\t\tif (hierarchyData.tmpName != null) {\n\t\t\treturn hierarchyData.tmpName;\n\t\t} else if (hierarchyData.matchedHierarchy != null && hierarchyData.matchedHierarchy.tmpName != null) {\n\t\t\treturn hierarchyData.matchedHierarchy.tmpName;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic void setTmpName(String tmpName) {\n\t\thierarchyData.tmpName = tmpName;\n\t}\n\n\t@Override\n\tpublic int getUid() {\n\t\tassert hierarchyData != null; // only available for input classes\n\n\t\tif (hierarchyData.uid >= 0) {\n\t\t\tif (hierarchyData.matchedHierarchy != null && hierarchyData.matchedHierarchy.uid >= 0) {\n\t\t\t\treturn Math.min(hierarchyData.uid, hierarchyData.matchedHierarchy.uid);\n\t\t\t} else {\n\t\t\t\treturn hierarchyData.uid;\n\t\t\t}\n\t\t} else if (hierarchyData.matchedHierarchy != null) {\n\t\t\treturn hierarchyData.matchedHierarchy.uid;\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic void setUid(int uid) {\n\t\thierarchyData.matchedHierarchy.uid = uid;\n\t}\n\n\tprotected abstract String getUidString();\n\n\t@Override\n\tpublic boolean hasMappedName() {\n\t\treturn getMappedName() != null;\n\t}\n\n\tprivate String getMappedName() {\n\t\tassert hierarchyData != null; // only available for input classes\n\n\t\tif (hierarchyData.mappedName != null) {\n\t\t\treturn hierarchyData.mappedName;\n\t\t} else if (hierarchyData.matchedHierarchy != null && hierarchyData.matchedHierarchy.mappedName != null) {\n\t\t\treturn hierarchyData.matchedHierarchy.mappedName;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic void setMappedName(String mappedName) {\n\t\thierarchyData.mappedName = mappedName;\n\t}\n\n\t@Override\n\tpublic String getMappedComment() {\n\t\tif (mappedComment != null) {\n\t\t\treturn mappedComment;\n\t\t} else if (matchedInstance != null) {\n\t\t\treturn matchedInstance.mappedComment;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setMappedComment(String comment) {\n\t\tif (comment != null && comment.isEmpty()) comment = null;\n\n\t\tthis.mappedComment = comment;\n\t}\n\n\t@Override\n\tpublic boolean hasAuxName(int index) {\n\t\treturn getAuxName(index) != null;\n\t}\n\n\tprivate String getAuxName(int index) {\n\t\tassert hierarchyData != null; // only available for input classes\n\n\t\tif (hierarchyData.auxName != null && hierarchyData.auxName.length > index && hierarchyData.auxName[index] != null) {\n\t\t\treturn hierarchyData.auxName[index];\n\t\t} else if (hierarchyData.matchedHierarchy != null\n\t\t\t\t&& hierarchyData.matchedHierarchy.auxName != null\n\t\t\t\t&& hierarchyData.matchedHierarchy.auxName.length > index\n\t\t\t\t&& hierarchyData.matchedHierarchy.auxName[index] != null) {\n\t\t\treturn hierarchyData.matchedHierarchy.auxName[index];\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic void setAuxName(int index, String name) {\n\t\tif (hierarchyData.auxName == null) hierarchyData.auxName = new String[NameType.AUX_COUNT];\n\t\thierarchyData.auxName[index] = name;\n\t}\n\n\t@Override\n\tpublic boolean isMatchable() {\n\t\treturn hierarchyData != null && hierarchyData.matchable && cls.isMatchable();\n\t}\n\n\t@Override\n\tpublic boolean setMatchable(boolean matchable) {\n\t\tif (!matchable && matchedInstance != null) return false;\n\t\tif (matchable && !cls.isMatchable()) return false;\n\t\tif (hierarchyData == null) return !matchable;\n\t\tif (!matchable && hierarchyData.matchedHierarchy != null) return false;\n\n\t\thierarchyData.matchable = matchable;\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic T getMatch() {\n\t\treturn matchedInstance;\n\t}\n\n\tpublic void setMatch(T match) {\n\t\tassert match == null || isMatchable();\n\t\tassert match == null || cls == match.cls.getMatch();\n\n\t\tthis.matchedInstance = match;\n\t\tthis.hierarchyData.matchedHierarchy = match != null ? match.hierarchyData : null;\n\t}\n\n\t@Override\n\tpublic float getSimilarity() {\n\t\tif (matchedInstance == null) return 0;\n\n\t\treturn SimilarityChecker.compare(this, matchedInstance);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn getDisplayName(NameType.PLAIN, true);\n\t}\n\n\tpublic static final Comparator<MemberInstance<?>> nameComparator = Comparator.<MemberInstance<?>, String>comparing(MemberInstance::getName).thenComparing(m -> m.getDesc());\n\n\tfinal ClassInstance cls;\n\tfinal String id;\n\tfinal String origName;\n\tboolean nameObfuscatedLocal;\n\tfinal int position;\n\tfinal boolean isStatic;\n\n\tprivate Set<T> parents = Collections.emptySet();\n\tprivate Set<T> children = Collections.emptySet();\n\tMemberHierarchyData<T> hierarchyData;\n\n\tString mappedComment;\n\n\tT matchedInstance;\n}",
"public final class MethodVarInstance implements Matchable<MethodVarInstance> {\n\tMethodVarInstance(MethodInstance method, boolean isArg, int index, int lvIndex, int asmIndex,\n\t\t\tClassInstance type, int startInsn, int endInsn, int startOpIdx,\n\t\t\tString origName, boolean nameObfuscated) {\n\t\tthis.method = method;\n\t\tthis.isArg = isArg;\n\t\tthis.index = index;\n\t\tthis.lvIndex = lvIndex;\n\t\tthis.asmIndex = asmIndex;\n\t\tthis.type = type;\n\t\tthis.startInsn = startInsn;\n\t\tthis.endInsn = endInsn;\n\t\tthis.startOpIdx = startOpIdx;\n\t\tthis.origName = origName;\n\t\tthis.nameObfuscated = nameObfuscated;\n\t}\n\n\t@Override\n\tpublic MatchableKind getKind() {\n\t\treturn isArg ? MatchableKind.METHOD_ARG : MatchableKind.METHOD_VAR;\n\t}\n\n\tpublic MethodInstance getMethod() {\n\t\treturn method;\n\t}\n\n\tpublic boolean isArg() {\n\t\treturn isArg;\n\t}\n\n\tpublic int getIndex() {\n\t\treturn index;\n\t}\n\n\tpublic int getLvIndex() {\n\t\treturn lvIndex;\n\t}\n\n\tpublic int getAsmIndex() {\n\t\treturn asmIndex;\n\t}\n\n\tpublic ClassInstance getType() {\n\t\treturn type;\n\t}\n\n\tpublic int getStartInsn() {\n\t\treturn startInsn;\n\t}\n\n\tpublic int getEndInsn() {\n\t\treturn endInsn;\n\t}\n\n\tpublic int getStartOpIdx() {\n\t\treturn startOpIdx;\n\t}\n\n\t@Override\n\tpublic String getId() {\n\t\treturn Integer.toString(index);\n\t}\n\n\tpublic String getTypedId() {\n\t\treturn (isArg ? \"arg\" : \"lv\").concat(getId());\n\t}\n\n\t@Override\n\tpublic String getName() {\n\t\treturn origName;\n\t}\n\n\t@Override\n\tpublic String getName(NameType type) {\n\t\tif (type == NameType.PLAIN) {\n\t\t\treturn hasValidOrigName() ? origName : getTypedId();\n\t\t} else if (type == NameType.UID_PLAIN) {\n\t\t\tClassEnvironment env = method.cls.env.getGlobal();\n\t\t\tint uid = getUid();\n\t\t\tif (uid >= 0) return (isArg ? env.argUidPrefix : env.varUidPrefix)+uid;\n\t\t}\n\n\t\tboolean locTmp = type == NameType.MAPPED_LOCTMP_PLAIN || type == NameType.LOCTMP_PLAIN;\n\t\tString ret;\n\n\t\tif (type.mapped && mappedName != null) {\n\t\t\t// MAPPED_*, local name available\n\t\t\tret = mappedName;\n\t\t} else if (type.mapped && matchedInstance != null && matchedInstance.mappedName != null) {\n\t\t\t// MAPPED_*, remote name available\n\t\t\tret = matchedInstance.mappedName;\n\t\t} else if (type.mapped && !nameObfuscated && hasValidOrigName()) {\n\t\t\t// MAPPED_*, local deobf\n\t\t\tret = origName;\n\t\t} else if (type.mapped && matchedInstance != null && !matchedInstance.nameObfuscated) {\n\t\t\t// MAPPED_*, remote deobf\n\t\t\tret = matchedInstance.origName;\n\t\t} else if (type.isAux() && auxName != null && auxName.length > type.getAuxIndex() && auxName[type.getAuxIndex()] != null) {\n\t\t\tret = auxName[type.getAuxIndex()];\n\t\t} else if (type.isAux() && matchedInstance != null && matchedInstance.auxName != null && matchedInstance.auxName.length > type.getAuxIndex() && matchedInstance.auxName[type.getAuxIndex()] != null) {\n\t\t\tret = matchedInstance.auxName[type.getAuxIndex()];\n\t\t} else if (type.tmp && matchedInstance != null && matchedInstance.tmpName != null) {\n\t\t\t// MAPPED_TMP_* with obf name or TMP_*, remote name available\n\t\t\tret = matchedInstance.tmpName;\n\t\t} else if ((type.tmp || locTmp) && tmpName != null) {\n\t\t\t// MAPPED_TMP_* or MAPPED_LOCTMP_* with obf name or TMP_* or LOCTMP_*, local name available\n\t\t\tret = tmpName;\n\t\t} else if (type.plain) {\n\t\t\tret = hasValidOrigName() ? origName : getTypedId();\n\t\t} else {\n\t\t\tret = null;\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tprivate boolean hasValidOrigName() {\n\t\tif (origName == null\n\t\t\t\t|| !Util.isValidJavaIdentifier(origName)\n\t\t\t\t|| origName.startsWith(\"arg\") && origName.length() > 3 && origName.charAt(3) >= '0' && origName.charAt(3) <= '9' // conflicts with argX typed id\n\t\t\t\t|| origName.startsWith(\"lv\") && origName.length() > 2 && origName.charAt(2) >= '0' && origName.charAt(2) <= '9') { // conflicts with lvX typed id\n\t\t\treturn false;\n\t\t}\n\n\t\t// check if unique\n\n\t\tfor (MethodVarInstance var : method.getArgs()) {\n\t\t\tif (var != this && origName.equals(var.origName)) return false;\n\t\t}\n\n\t\tfor (MethodVarInstance var : method.getVars()) {\n\t\t\tif (var != this && origName.equals(var.origName)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic Matchable<?> getOwner() {\n\t\treturn method;\n\t}\n\n\t@Override\n\tpublic ClassEnv getEnv() {\n\t\treturn method.getEnv();\n\t}\n\n\t@Override\n\tpublic boolean isNameObfuscated() {\n\t\treturn nameObfuscated;\n\t}\n\n\t@Override\n\tpublic boolean hasLocalTmpName() {\n\t\treturn tmpName != null;\n\t}\n\n\tpublic void setTmpName(String tmpName) {\n\t\tthis.tmpName = tmpName;\n\t}\n\n\t@Override\n\tpublic int getUid() {\n\t\treturn uid;\n\t}\n\n\tpublic void setUid(int uid) {\n\t\tthis.uid = uid;\n\t}\n\n\t@Override\n\tpublic boolean hasMappedName() {\n\t\treturn mappedName != null || matchedInstance != null && matchedInstance.mappedName != null;\n\t}\n\n\tpublic void setMappedName(String mappedName) {\n\t\tthis.mappedName = mappedName;\n\t}\n\n\t@Override\n\tpublic String getMappedComment() {\n\t\tif (mappedComment != null) {\n\t\t\treturn mappedComment;\n\t\t} else if (matchedInstance != null) {\n\t\t\treturn matchedInstance.mappedComment;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setMappedComment(String comment) {\n\t\tif (comment != null && comment.isEmpty()) comment = null;\n\n\t\tthis.mappedComment = comment;\n\t}\n\n\t@Override\n\tpublic boolean hasAuxName(int index) {\n\t\treturn auxName != null && auxName.length > index && auxName[index] != null;\n\t}\n\n\tpublic void setAuxName(int index, String name) {\n\t\tif (this.auxName == null) this.auxName = new String[NameType.AUX_COUNT];\n\t\tthis.auxName[index] = name;\n\t}\n\n\t@Override\n\tpublic boolean hasPotentialMatch() {\n\t\tif (matchedInstance != null) return true;\n\t\tif (!method.hasMatch() || !isMatchable()) return false;\n\n\t\tfor (MethodVarInstance o : (isArg ? method.getMatch().getArgs() : method.getMatch().getVars())) {\n\t\t\tif (ClassifierUtil.checkPotentialEquality(this, o)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isMatchable() {\n\t\treturn matchable && method.isMatchable();\n\t}\n\n\t@Override\n\tpublic boolean setMatchable(boolean matchable) {\n\t\tif (!matchable && matchedInstance != null) return false;\n\t\tif (matchable && !method.isMatchable()) return false;\n\n\t\tthis.matchable = matchable;\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic MethodVarInstance getMatch() {\n\t\treturn matchedInstance;\n\t}\n\n\tpublic void setMatch(MethodVarInstance match) {\n\t\tassert match == null || isMatchable();\n\t\tassert match == null || method == match.method.getMatch();\n\n\t\tthis.matchedInstance = match;\n\t}\n\n\t@Override\n\tpublic boolean isFullyMatched(boolean recursive) {\n\t\treturn matchedInstance != null;\n\t}\n\n\t@Override\n\tpublic float getSimilarity() {\n\t\tif (matchedInstance == null) return 0;\n\n\t\treturn SimilarityChecker.compare(this, matchedInstance);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn method+\":\"+getTypedId();\n\t}\n\n\tfinal MethodInstance method;\n\tfinal boolean isArg;\n\tfinal int index;\n\tfinal int lvIndex;\n\tfinal int asmIndex;\n\tfinal ClassInstance type;\n\tprivate final int startInsn; // inclusive\n\tprivate final int endInsn; // exclusive\n\tprivate final int startOpIdx;\n\tfinal String origName;\n\tfinal boolean nameObfuscated;\n\n\tprivate String tmpName;\n\tprivate int uid = -1;\n\n\tprivate String mappedName;\n\tString mappedComment;\n\n\tString[] auxName;\n\n\tprivate boolean matchable = true;\n\tprivate MethodVarInstance matchedInstance;\n}"
] | import java.util.Comparator;
import java.util.Objects;
import matcher.NameType;
import matcher.type.ClassInstance;
import matcher.type.Matchable;
import matcher.type.MemberInstance;
import matcher.type.MethodVarInstance; | package matcher.mapping;
public final class MappedElementComparators {
public static <T extends MemberInstance<T>> Comparator<T> byName(NameType ns) {
return new Comparator<T>() {
@Override
public int compare(T a, T b) {
return compareNullLast(a.getName(ns), b.getName(ns));
}
};
}
public static <T extends Matchable<T>> Comparator<T> byNameShortFirst(NameType ns) {
return new Comparator<T>() {
@Override
public int compare(T a, T b) {
String nameA = a.getName(ns);
String nameB = b.getName(ns);
if (nameA == null || nameB == null) {
return compareNullLast(nameA, nameB);
} else {
return compareNameShortFirst(nameA, 0, nameA.length(), nameB, 0, nameB.length());
}
}
};
}
public static Comparator<ClassInstance> byNameShortFirstNestaware(NameType ns) {
return new Comparator<ClassInstance>() {
@Override
public int compare(ClassInstance a, ClassInstance b) {
String nameA = a.getName(ns);
String nameB = b.getName(ns);
if (nameA == null || nameB == null) {
return compareNullLast(nameA, nameB);
}
int pos = 0;
do {
int endA = nameA.indexOf('$', pos);
int endB = nameB.indexOf('$', pos);
int ret = compareNameShortFirst(nameA, pos, endA >= 0 ? endA : nameA.length(),
nameB, pos, endB >= 0 ? endB : nameB.length());
if (ret != 0) {
return ret;
} else if ((endA < 0) != (endB < 0)) {
return endA < 0 ? -1 : 1;
}
pos = endA + 1;
} while (pos > 0);
return 0;
}
};
}
private static int compareNameShortFirst(String nameA, int startA, int endA, String nameB, int startB, int endB) {
int lenA = endA - startA;
int ret = Integer.compare(lenA, endB - startB);
if (ret != 0) return ret;
for (int i = 0; i < lenA; i++) {
char a = nameA.charAt(startA + i);
char b = nameB.charAt(startB + i);
if (a != b) {
return a - b;
}
}
return 0;
}
public static <T extends MemberInstance<?>> Comparator<T> byNameDescConcat(NameType ns) {
return new Comparator<T>() {
@Override
public int compare(T a, T b) {
String valA = Objects.toString(a.getName(ns)).concat(Objects.toString(a.getDesc(ns)));
String valB = Objects.toString(b.getName(ns)).concat(Objects.toString(b.getDesc(ns)));
return valA.compareTo(valB);
}
};
}
| public static Comparator<MethodVarInstance> byLvIndex() { | 4 |
kdgregory/pathfinder | lib-servlet/src/main/java/com/kdgregory/pathfinder/servlet/ServletInspector.java | [
"public enum HttpMethod\n{\n ALL(\"\"),\n GET(\"GET\"),\n POST(\"POST\"),\n PUT(\"PUT\"),\n DELETE(\"DELETE\");\n\n private String stringValue;\n\n HttpMethod(String stringValue)\n {\n this.stringValue = stringValue;\n }\n\n @Override\n public String toString()\n {\n return stringValue;\n }\n}",
"public interface Inspector\n{\n /**\n * Inspects the passed WAR and updates the path repository with any\n * paths found. Note that existing paths may be replaced as part of\n * this process.\n */\n public void inspect(WarMachine war, PathRepo paths);\n}",
"public interface PathRepo\nextends Iterable<String>\n{\n /**\n * Returns the number of URLs in the repository. Note that multiple actions\n * for the same URL are only counted once.\n */\n public int urlCount();\n\n\n /**\n * Stores a destination that responds to all request methods. Will replace\n * all existing destinations for the URL.\n */\n public void put(String url, Destination dest);\n\n\n /**\n * Stores a destination that responds to a specific request method. If\n * there is an existing \"all\" entry, it will be overridden for just the\n * method stored.\n */\n public void put(String url, HttpMethod method, Destination dest);\n\n\n /**\n * Stores a map of destinations, replacing the existing map for that URL.\n */\n public void put(String url, Map<HttpMethod,Destination> destMap);\n\n\n /**\n * Retrieves the destination for a given URL and method. If the URL has\n * been stored with \"ALL\" methods, will return that destination unless\n * the URL has also been stored with a specific method. Returns null if\n * there's no destination for a URL and method.\n */\n public Destination get(String url, HttpMethod method);\n\n\n /**\n * Retrieves an unmodifiable view of the destination map for a given URL.\n * The returned map will be sorted by method.\n * <p>\n * Note 1: this method will never return null, but the map may be empty.\n * <p>\n * Note 2: the map may contain a single mapping, for \"ALL\"; the caller\n * is responsible for translating this to individual mappings\n * if desired.\n */\n public Map<HttpMethod,Destination> get(String url);\n\n\n /**\n * Removes the destination(s) associated with the given URL and method.\n * If the passed method is \"ALL\", will remove all destinations (even if\n * they were added individually).\n */\n public void remove(String url, HttpMethod method);\n\n\n /**\n * Returns an iterator over the URLs in this repository. These URLs\n * will be sorted in alphanumeric order. Only those URLs that have active\n * mappings are returned.\n */\n @Override\n public Iterator<String> iterator();\n}",
"public interface WarMachine\n{\n /**\n * Returns the <code>web.xml</code> as a parsed XML DOM. Implementations\n * may return a shared, modifiable instance of the DOM; callers must not\n * modify the returned object.\n * <p>\n * Note: the method {@link getWebXmlPath} should be used to retrieve data\n * from this DOM.\n */\n public Document getWebXml();\n\n\n /**\n * Returns an XPath that may be used to retrieve content from this WAR's\n * <code>web.xml</code>. Elements within the file must be prefixed with\n * the \"j2ee\" namespace prefix; the actual namespace will depend on the\n * version of the servlet spec in use.\n */\n public XPathWrapper getWebXmlPath(String path);\n\n\n /**\n * Joins the <code>servlet</code> and <code>servlet-mapping</code> entries from\n * <code>web.xml</code>. The result is ordered alphabetically.\n */\n public List<ServletMapping> getServletMappings();\n\n\n /**\n * Returns a list of all entries in the WAR, prefixed with a leading slash.\n */\n public List<String> getAllFiles();\n\n\n /**\n * Returns a list of the \"public\" entries in the WAR: those not under\n * META-INF or WEB-INF. This is where you'll find the JSPs.\n */\n public List<String> getPublicFiles();\n\n\n /**\n * Returns a list of the \"private\" entries in the WAR: those under META-INF\n * and WEB-INF.\n */\n public List<String> getPrivateFiles();\n\n\n /**\n * Returns a list of all files on the classpath: those under WEB-INF/classes\n * and those contained in JARfiles. Note that the return is a Set; if there\n * are multiple classpath files with the same name, one will be chosen\n * arbitrarily.\n */\n public Set<String> getFilesOnClasspath();\n\n\n /**\n * Searches the classpath for classes in a given package, optionally recursing\n * into descendent packages.\n */\n public Set<String> getClassesInPackage(String packageName, boolean recurse);\n\n\n /**\n * Returns a stream for the named file, <code>null</code> if the file doesn't\n * exist. You are encouraged to close this stream, but as it isn't a physical\n * file handle, there isn't a penalty to pay for not closing it.\n */\n public InputStream openFile(String filename)\n throws IOException;\n\n\n /**\n * Opens a file on the WAR's classpath. First looks in <code>WEB-INF/classes</code>,\n * then in each of the JARs in <code>lib</code>.\n */\n public InputStream openClasspathFile(String filename)\n throws IOException;\n\n\n /**\n * Attempts to find the specified class on the classpath, and loads it\n * using BCEL. Returns <code>null</code> if unable to find the classfile.\n */\n public JavaClass loadClass(String classname);\n\n\n\n//----------------------------------------------------------------------------\n// Supporting Objects\n//----------------------------------------------------------------------------\n\n /**\n * Servlet mappings are parsed into objects that implement this interface.\n * Method names are simple translations of the corresponding element name.\n * <p>\n * The natural ordering of this interface is the URL pattern.\n */\n public interface ServletMapping\n extends Comparable<ServletMapping>\n {\n public String getUrlPattern();\n\n public String getServletName();\n\n public String getServletClass();\n\n public Map<String,String> getInitParams();\n }\n}",
"public interface ServletMapping\nextends Comparable<ServletMapping>\n{\n public String getUrlPattern();\n\n public String getServletName();\n\n public String getServletClass();\n\n public Map<String,String> getInitParams();\n}"
] | import org.apache.log4j.Logger;
import com.kdgregory.pathfinder.core.HttpMethod;
import com.kdgregory.pathfinder.core.Inspector;
import com.kdgregory.pathfinder.core.PathRepo;
import com.kdgregory.pathfinder.core.WarMachine;
import com.kdgregory.pathfinder.core.WarMachine.ServletMapping; | // Copyright (c) Keith D Gregory
//
// 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.kdgregory.pathfinder.servlet;
public class ServletInspector
implements Inspector
{
private Logger logger = Logger.getLogger(getClass());
//----------------------------------------------------------------------------
// Inspector
//----------------------------------------------------------------------------
@Override | public void inspect(WarMachine war, PathRepo paths) | 3 |
WojciechZankowski/iextrading4j-hist | iextrading4j-hist-test/src/test/java/pl/zankowski/iextrading4j/hist/test/message/IEXSecurityDirectoryMessageTest.java | [
"public enum IEXMessageType implements IEXByteEnum {\n\n QUOTE_UPDATE((byte) 0x51),\n TRADE_REPORT((byte) 0x54),\n TRADE_BREAK((byte) 0x42),\n SYSTEM_EVENT((byte) 0x53),\n SECURITY_DIRECTORY((byte) 0x44),\n TRADING_STATUS((byte) 0x48),\n OPERATIONAL_HALT_STATUS((byte) 0x4f),\n SHORT_SALE_PRICE_TEST_STATUS((byte) 0x50),\n SECURITY_EVENT((byte) 0x45),\n PRICE_LEVEL_UPDATE_BUY((byte) 0x38),\n PRICE_LEVEL_UPDATE_SELL((byte) 0x35),\n OFFICIAL_PRICE_MESSAGE((byte) 0x58),\n AUCTION_INFORMATION((byte) 0x41),\n RETAIL_LIQUIDITY_INDICATOR((byte) 0x49);\n\n private static final Map<Byte, IEXMessageType> LOOKUP = new HashMap<>();\n\n static {\n for (final IEXMessageType value : EnumSet.allOf(IEXMessageType.class))\n LOOKUP.put(value.getCode(), value);\n }\n\n private final byte code;\n\n IEXMessageType(final byte code) {\n this.code = code;\n }\n\n public static IEXMessageType getMessageType(final byte code) {\n return lookup(IEXMessageType.class, LOOKUP, code);\n }\n\n @Override\n public byte getCode() {\n return code;\n }\n\n}",
"public class IEXPrice implements Comparable<IEXPrice>, Serializable {\n\n private static final int SCALE = 4;\n\n private final long number;\n\n public IEXPrice(final long number) {\n this.number = number;\n }\n\n public long getNumber() {\n return number;\n }\n\n public BigDecimal toBigDecimal() {\n return BigDecimal.valueOf(number)\n .scaleByPowerOfTen(-SCALE);\n }\n\n @Override\n public int compareTo(final IEXPrice iexPrice) {\n return compare(this.getNumber(), iexPrice.getNumber());\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n IEXPrice iexPrice = (IEXPrice) o;\n return number == iexPrice.number;\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(number);\n }\n\n @Override\n public String toString() {\n return toBigDecimal()\n .toString();\n }\n}",
"public class IEXSecurityDirectoryMessage extends IEXMessage {\n\n public static final int LENGTH = 31;\n\n private final byte flag;\n private final long timestamp;\n private final String symbol;\n private final int roundLotSize;\n private final IEXPrice adjustedPOCPrice;\n private final IEXLULDTier luldTier;\n\n private IEXSecurityDirectoryMessage(\n final byte flag,\n final long timestamp,\n final String symbol,\n final int roundLotSize,\n final IEXPrice adjustedPOCPrice,\n final IEXLULDTier luldTier) {\n super(SECURITY_DIRECTORY);\n this.flag = flag;\n this.timestamp = timestamp;\n this.symbol = symbol;\n this.roundLotSize = roundLotSize;\n this.adjustedPOCPrice = adjustedPOCPrice;\n this.luldTier = luldTier;\n }\n\n public boolean isTestSecurity() {\n return (flag & 0x80) != 0;\n }\n\n public boolean isWhenIssuedSecurity() {\n return (flag & 0x40) != 0;\n }\n\n public boolean isETP() {\n return (flag & 0x20) != 0;\n }\n\n public long getTimestamp() {\n return timestamp;\n }\n\n public String getSymbol() {\n return symbol;\n }\n\n public int getRoundLotSize() {\n return roundLotSize;\n }\n\n public IEXPrice getAdjustedPOCPrice() {\n return adjustedPOCPrice;\n }\n\n public IEXLULDTier getLuldTier() {\n return luldTier;\n }\n\n public static IEXSecurityDirectoryMessage createIEXMessage(final byte[] bytes) {\n final byte iexSecurityDirectoryFlag = bytes[1];\n final long timestamp = IEXByteConverter.convertBytesToLong(Arrays.copyOfRange(bytes, 2, 10));\n final String symbol = IEXByteConverter.convertBytesToString(Arrays.copyOfRange(bytes, 10, 18));\n final int roundLotSize = IEXByteConverter.convertBytesToInt(Arrays.copyOfRange(bytes, 18, 22));\n final IEXPrice adjustedPOCPrice = IEXByteConverter.convertBytesToIEXPrice(Arrays.copyOfRange(bytes, 22, 30));\n final IEXLULDTier iexluldTier = IEXLULDTier.getLULDTier(bytes[30]);\n\n return new IEXSecurityDirectoryMessage(iexSecurityDirectoryFlag, timestamp, symbol, roundLotSize,\n adjustedPOCPrice, iexluldTier);\n }\n\n @Override\n public boolean equals(final Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n if (!super.equals(o)) return false;\n final IEXSecurityDirectoryMessage that = (IEXSecurityDirectoryMessage) o;\n return timestamp == that.timestamp &&\n roundLotSize == that.roundLotSize &&\n flag == that.flag &&\n Objects.equals(symbol, that.symbol) &&\n Objects.equals(adjustedPOCPrice, that.adjustedPOCPrice) &&\n luldTier == that.luldTier;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), flag, timestamp, symbol, roundLotSize, adjustedPOCPrice, luldTier);\n }\n\n @Override\n public String toString() {\n return \"IEXSecurityDirectoryMessage{\" +\n \"flag=\" + flag +\n \", timestamp=\" + timestamp +\n \", symbol='\" + symbol + '\\'' +\n \", roundLotSize=\" + roundLotSize +\n \", adjustedPOCPrice=\" + adjustedPOCPrice +\n \", luldTier=\" + luldTier +\n \"} \" + super.toString();\n }\n}",
"public enum IEXLULDTier implements IEXByteEnum {\n\n NOT_APPLICABLE((byte) 0x0),\n TIER_1_NMS((byte) 0x1),\n TIER_2_NMS((byte) 0x2);\n\n private static final Map<Byte, IEXLULDTier> LOOKUP = new HashMap<>();\n\n static {\n for (final IEXLULDTier value : EnumSet.allOf(IEXLULDTier.class))\n LOOKUP.put(value.getCode(), value);\n }\n\n private final byte code;\n\n IEXLULDTier(final byte code) {\n this.code = code;\n }\n\n public static IEXLULDTier getLULDTier(final byte code) {\n return lookup(IEXLULDTier.class, LOOKUP, code);\n }\n\n @Override\n public byte getCode() {\n return code;\n }\n}",
"public abstract class ExtendedUnitTestBase {\n\n protected byte[] loadPacket(final String fileName) throws IOException {\n return ByteStreams.toByteArray(ExtendedUnitTestBase.class.getClassLoader().getResourceAsStream(fileName));\n }\n\n}",
"public static IEXSecurityDirectoryMessage createIEXMessage(final byte[] bytes) {\n final byte iexSecurityDirectoryFlag = bytes[1];\n final long timestamp = IEXByteConverter.convertBytesToLong(Arrays.copyOfRange(bytes, 2, 10));\n final String symbol = IEXByteConverter.convertBytesToString(Arrays.copyOfRange(bytes, 10, 18));\n final int roundLotSize = IEXByteConverter.convertBytesToInt(Arrays.copyOfRange(bytes, 18, 22));\n final IEXPrice adjustedPOCPrice = IEXByteConverter.convertBytesToIEXPrice(Arrays.copyOfRange(bytes, 22, 30));\n final IEXLULDTier iexluldTier = IEXLULDTier.getLULDTier(bytes[30]);\n\n return new IEXSecurityDirectoryMessage(iexSecurityDirectoryFlag, timestamp, symbol, roundLotSize,\n adjustedPOCPrice, iexluldTier);\n}"
] | import org.junit.jupiter.api.Test;
import pl.zankowski.iextrading4j.hist.api.IEXMessageType;
import pl.zankowski.iextrading4j.hist.api.field.IEXPrice;
import pl.zankowski.iextrading4j.hist.api.message.administrative.IEXSecurityDirectoryMessage;
import pl.zankowski.iextrading4j.hist.api.message.administrative.field.IEXLULDTier;
import pl.zankowski.iextrading4j.hist.test.ExtendedUnitTestBase;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static pl.zankowski.iextrading4j.hist.api.message.administrative.IEXSecurityDirectoryMessage.createIEXMessage; | package pl.zankowski.iextrading4j.hist.test.message;
class IEXSecurityDirectoryMessageTest extends ExtendedUnitTestBase {
@Test
void testIEXSecurityDirectoryMessage() throws IOException {
final byte[] packet = loadPacket("IEXSecurityDirectoryMessage.dump");
final IEXSecurityDirectoryMessage message = createIEXMessage(packet);
assertThat(message.getMessageType()).isEqualTo(IEXMessageType.SECURITY_DIRECTORY);
assertThat(message.getTimestamp()).isEqualTo(1509795046090464161L);
assertThat(message.getSymbol()).isEqualTo("ZEXIT");
assertThat(message.getRoundLotSize()).isEqualTo(100); | assertThat(message.getAdjustedPOCPrice()).isEqualTo(new IEXPrice(100000)); | 1 |
presidentio/teamcity-plugin-jmh | teamcity-plugin-jmh-common/src/main/java/com/presidentio/teamcity/jmh/runner/common/param/RunnerParamProvider.java | [
"public class TimeUnitConst {\n\n public static final String DEFAULT = \"default\";\n public static final String MINUTES = \"m\";\n public static final String SECONDS = \"s\";\n public static final String MILLISECONDS = \"ms\";\n public static final String MICROSECONDS = \"us\";\n public static final String NANOSECONDS = \"ns\";\n\n public static final List<String> TIME_UNITS = Arrays.asList(DEFAULT, MINUTES, SECONDS, MILLISECONDS,\n MICROSECONDS, NANOSECONDS);\n\n public static final Map<String, String> TIME_UNITS_WITH_DESCRIPTION = new LinkedHashMap<>();\n\n static {\n TIME_UNITS_WITH_DESCRIPTION.put(DEFAULT, \"<Default>\");\n TIME_UNITS_WITH_DESCRIPTION.put(NANOSECONDS, \"Nanoseconds\");\n TIME_UNITS_WITH_DESCRIPTION.put(MICROSECONDS, \"Microseconds\");\n TIME_UNITS_WITH_DESCRIPTION.put(MILLISECONDS, \"Milliseconds\");\n TIME_UNITS_WITH_DESCRIPTION.put(SECONDS, \"Seconds\");\n TIME_UNITS_WITH_DESCRIPTION.put(MINUTES, \"Minutes\");\n }\n\n public String getDEFAULT() {\n return DEFAULT;\n }\n\n public String getMINUTES() {\n return MINUTES;\n }\n\n public String getSECONDS() {\n return SECONDS;\n }\n\n public String getMILLISECONDS() {\n return MILLISECONDS;\n }\n\n public String getMICROSECONDS() {\n return MICROSECONDS;\n }\n\n public String getNANOSECONDS() {\n return NANOSECONDS;\n }\n}",
"public class VerboseModeConst {\n\n public static final String DEFAULT = \"default\";\n public static final String SILENT = \"SILENT\";\n public static final String NORMAL = \"NORMAL\";\n public static final String EXTRA = \"EXTRA\";\n\n public static final List<String> ALL = Arrays.asList(DEFAULT, SILENT, NORMAL, EXTRA);\n\n public static final Map<String, String> ALL_WITH_DESCRIPTION = new LinkedHashMap<>();\n\n static {\n ALL_WITH_DESCRIPTION.put(DEFAULT, \"<Default>\");\n ALL_WITH_DESCRIPTION.put(SILENT, \"Silent\");\n ALL_WITH_DESCRIPTION.put(NORMAL, \"Normal\");\n ALL_WITH_DESCRIPTION.put(EXTRA, \"Extra\");\n }\n\n}",
"public class WarmupModeConst {\n\n public static final String DEFAULT = \"default\";\n public static final String INDI = \"INDI\";\n public static final String BULK = \"BULK\";\n public static final String BULK_INDI = \"BULK_INDI\";\n\n public static final List<String> ALL = Arrays.asList(DEFAULT, INDI, BULK, BULK_INDI);\n\n public static final Map<String, String> ALL_WITH_DESCRIPTION = new LinkedHashMap<>();\n\n static {\n ALL_WITH_DESCRIPTION.put(DEFAULT, \"<Default>\");\n ALL_WITH_DESCRIPTION.put(INDI, \"INDI\");\n ALL_WITH_DESCRIPTION.put(BULK, \"BULK\");\n ALL_WITH_DESCRIPTION.put(BULK_INDI, \"BULK_INDI\");\n }\n\n}",
"public static final Map<String, String> MODES_WITH_DESCRIPTION = new LinkedHashMap<>();",
"public class SettingsConst {\n\n public static final String PROP_RUN_FROM = \"run_from\";\n public static final String PROP_MAVEN_MODULE_LOCATION = \"maven_module_location\";\n public static final String PROP_GRADLE_MODULE_LOCATION = \"gradle_module_location\";\n public static final String PROP_GRADLE_USE_WRAPPER = \"gradle_use_wrapper\";\n public static final String PROP_GRADLE_WRAPPER_PATH = \"gradle_wrapper_path\";\n public static final String PROP_JAR_PATH = \"jar_path\";\n public static final String PROP_BENCHMARKS = \"benchmarks\";\n public static final String PROP_MODE = \"mode\";\n public static final String PROP_BATCH_SIZE = \"batch_size\";\n public static final String PROP_EXCLUDE = \"exclude\";\n public static final String PROP_FORKS = \"forks\";\n public static final String PROP_FAIL_ON_ERROR = \"fail_on_error\";\n public static final String PROP_GC = \"gc\";\n public static final String PROP_MEASUREMENT_ITERATIONS = \"measurement_iterations\";\n public static final String PROP_JVM = \"jvm\";\n public static final String PROP_JVM_ARGS = \"jvm_args\";\n public static final String PROP_JVM_ARGS_APPEND = \"jvm_args_append\";\n public static final String PROP_JVM_ARGS_PREPEND = \"jvm_args_prepend\";\n public static final String PROP_OPERATIONS_PER_INVOCATION = \"operations_per_invocation\";\n public static final String PROP_BENCHMARK_PARAMETERS = \"benchmark_parameters\";\n public static final String PROP_PROFILERS = \"profilers\";\n public static final String PROP_TIME_PER_MEASUREMENT = \"time_per_measurement\";\n public static final String PROP_SYNCHRONIZE = \"synchronize\";\n public static final String PROP_THREADS = \"threads\";\n public static final String PROP_THREAD_DISTRIBUTION = \"thread_distribution\";\n public static final String PROP_TIMEOUT = \"timeout\";\n public static final String PROP_TIME_UNIT = \"time_unit\";\n public static final String PROP_VERBOSITY = \"verbosity\";\n public static final String PROP_TIME_PER_WARMUP = \"warmup\";\n public static final String PROP_WARMUP_BATCH_SIZE = \"warmup_batch_size\";\n public static final String PROP_WARMUP_FORKS = \"warmup_forks\";\n public static final String PROP_WARMUP_ITERATIONS = \"warmup_iterations\";\n public static final String PROP_WARMUP_MODE = \"warmup_mode\";\n public static final String PROP_WARMUP_BENCHMARKS = \"warmup_benchmarks\";\n\n public String getPROP_RUN_FROM() {\n return PROP_RUN_FROM;\n }\n\n public String getPROP_MAVEN_MODULE_LOCATION() {\n return PROP_MAVEN_MODULE_LOCATION;\n }\n\n public String getPROP_GRADLE_MODULE_LOCATION() {\n return PROP_GRADLE_MODULE_LOCATION;\n }\n\n public String getPROP_GRADLE_USE_WRAPPER() {\n return PROP_GRADLE_USE_WRAPPER;\n }\n\n public String getPROP_GRADLE_WRAPPER_PATH() {\n return PROP_GRADLE_WRAPPER_PATH;\n }\n\n public String getPROP_JAR_PATH() {\n return PROP_JAR_PATH;\n }\n\n public String getPROP_BENCHMARKS() {\n return PROP_BENCHMARKS;\n }\n\n public String getPROP_MODE() {\n return PROP_MODE;\n }\n\n public String getPROP_TIME_UNIT() {\n return PROP_TIME_UNIT;\n }\n\n public String getPROP_BATCH_SIZE() {\n return PROP_BATCH_SIZE;\n }\n\n public String getPROP_EXCLUDE() {\n return PROP_EXCLUDE;\n }\n\n public String getPROP_FORKS() {\n return PROP_FORKS;\n }\n\n public String getPROP_FAIL_ON_ERROR() {\n return PROP_FAIL_ON_ERROR;\n }\n\n public String getPROP_GC() {\n return PROP_GC;\n }\n\n public String getPROP_MEASUREMENT_ITERATIONS() {\n return PROP_MEASUREMENT_ITERATIONS;\n }\n\n public String getPROP_JVM() {\n return PROP_JVM;\n }\n\n public String getPROP_JVM_ARGS() {\n return PROP_JVM_ARGS;\n }\n\n public String getPROP_JVM_ARGS_APPEND() {\n return PROP_JVM_ARGS_APPEND;\n }\n\n public String getPROP_JVM_ARGS_PREPEND() {\n return PROP_JVM_ARGS_PREPEND;\n }\n\n public String getPROP_OPERATIONS_PER_INVOCATION() {\n return PROP_OPERATIONS_PER_INVOCATION;\n }\n\n public String getPROP_BENCHMARK_PARAMETERS() {\n return PROP_BENCHMARK_PARAMETERS;\n }\n\n public String getPROP_PROFILERS() {\n return PROP_PROFILERS;\n }\n\n public String getPROP_TIME_PER_MEASUREMENT() {\n return PROP_TIME_PER_MEASUREMENT;\n }\n\n public String getPROP_SYNCHRONIZE() {\n return PROP_SYNCHRONIZE;\n }\n\n public String getPROP_THREADS() {\n return PROP_THREADS;\n }\n\n public String getPROP_THREAD_DISTRIBUTION() {\n return PROP_THREAD_DISTRIBUTION;\n }\n\n public String getPROP_TIMEOUT() {\n return PROP_TIMEOUT;\n }\n\n public String getPROP_VERBOSITY() {\n return PROP_VERBOSITY;\n }\n\n public String getPROP_TIME_PER_WARMUP() {\n return PROP_TIME_PER_WARMUP;\n }\n\n public String getPROP_WARMUP_BATCH_SIZE() {\n return PROP_WARMUP_BATCH_SIZE;\n }\n\n public String getPROP_WARMUP_FORKS() {\n return PROP_WARMUP_FORKS;\n }\n\n public String getPROP_WARMUP_ITERATIONS() {\n return PROP_WARMUP_ITERATIONS;\n }\n\n public String getPROP_WARMUP_MODE() {\n return PROP_WARMUP_MODE;\n }\n\n public String getPROP_WARMUP_BENCHMARKS() {\n return PROP_WARMUP_BENCHMARKS;\n }\n}"
] | import com.presidentio.teamcity.jmh.runner.common.cons.TimeUnitConst;
import com.presidentio.teamcity.jmh.runner.common.cons.VerboseModeConst;
import com.presidentio.teamcity.jmh.runner.common.cons.WarmupModeConst;
import java.util.Collection;
import java.util.HashMap;
import static com.presidentio.teamcity.jmh.runner.common.cons.ModeConst.MODES_WITH_DESCRIPTION;
import static com.presidentio.teamcity.jmh.runner.common.cons.SettingsConst.*; | /**
* Copyright 2015 presidentio
* 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.presidentio.teamcity.jmh.runner.common.param;
/**
* Created by presidentio on 12.05.15.
*/
public class RunnerParamProvider {
private static final HashMap<String, RunnerParam> ALL = new HashMap<>();
static {
ALL.put(PROP_BENCHMARKS, new BaseRunnerParam(PROP_BENCHMARKS, "", false, "Benchmarks", "Benchmarks to run (regexp+)."));
ALL.put(PROP_MODE, new SelectRunnerParameter(MODES_WITH_DESCRIPTION, PROP_MODE, "-bm", false, "Benchmark mode",
"Benchmark mode."));
ALL.put(PROP_BATCH_SIZE, new IntRunnerParam(PROP_BATCH_SIZE, "-bs", false, "Batch size",
"Number of benchmark method calls per operation. (some benchmark modes can ignore this setting)", 0));
ALL.put(PROP_EXCLUDE, new BaseRunnerParam(PROP_EXCLUDE, "-e", false, "Exclude",
"Benchmarks to exclude from the run."));
ALL.put(PROP_FORKS, new IntRunnerParam(PROP_FORKS, "-f", false, "Forks",
"How many times to forks a single benchmark. Use 0 to disable forking altogether (WARNING: disabling " +
"forking may have detrimental impact on benchmark and infrastructure reliability, you might want " +
"to use different warmup mode instead).", 0));
ALL.put(PROP_FAIL_ON_ERROR, new BoolRunnerParam(PROP_FAIL_ON_ERROR, "-foe", false, "Fail on error",
"Should JMH fail immediately if any benchmark had experienced the unrecoverable error?"));
ALL.put(PROP_GC, new BoolRunnerParam(PROP_GC, "-gc", false, "Force GC", "Should JMH force GC between iterations?"));
ALL.put(PROP_MEASUREMENT_ITERATIONS, new IntRunnerParam(PROP_MEASUREMENT_ITERATIONS, "-i", false,
"Iterations", "Number of measurement iterations to do.", 0));
ALL.put(PROP_JVM, new BaseRunnerParam(PROP_JVM, "-jvm", false, "Custom JVM",
"Custom JVM to use when forking (path to JVM executable)."));
ALL.put(PROP_JVM_ARGS, new BaseRunnerParam(PROP_JVM_ARGS, "-jvmArgs", false, "Custom JVM args",
"Custom JVM args to use when forking."));
ALL.put(PROP_JVM_ARGS_APPEND, new BaseRunnerParam(PROP_JVM_ARGS_APPEND, "-jvmArgsAppend", false,
"Custom JVM args append", "Custom JVM args to use when forking (append these)"));
ALL.put(PROP_JVM_ARGS_PREPEND, new BaseRunnerParam(PROP_JVM_ARGS_PREPEND, "-jvmArgsPrepend", false,
"Custom JVM args prepend", "Custom JVM args to use when forking (prepend these)"));
ALL.put(PROP_OPERATIONS_PER_INVOCATION, new IntRunnerParam(PROP_OPERATIONS_PER_INVOCATION, "-opi", false,
"Operations", "Operations per invocation.", 0));
ALL.put(PROP_BENCHMARK_PARAMETERS, new BaseRunnerParam(PROP_BENCHMARK_PARAMETERS, "-p", false,
"Benchmark parameters", "This option is expected to be used once per parameter. Parameter name and " +
"parameter values should be separated with equals sign. Parameter values should be separated with commas."));
ALL.put(PROP_PROFILERS, new BaseRunnerParam(PROP_PROFILERS, "-prof", false, "Profilers",
"Use profilers to collect additional data."));
ALL.put(PROP_TIME_PER_MEASUREMENT, new BaseRunnerParam(PROP_TIME_PER_MEASUREMENT, "-r", false,
"Measurement time", "Time to spend at each measurement iteration. Arguments accept time suffixes, like \"100ms\"."));
ALL.put(PROP_SYNCHRONIZE, new BoolRunnerParam(PROP_SYNCHRONIZE, "-si", false, "Synchronized",
"Synchronize iterations?"));
ALL.put(PROP_THREADS, new IntRunnerParam(PROP_THREADS, "-t", false, "Threads",
"Number of worker threads to run with.", 0));
ALL.put(PROP_THREAD_DISTRIBUTION, new BaseRunnerParam(PROP_THREAD_DISTRIBUTION, "-tg", false,
"Thread group distribution", "Override thread group distribution for asymmetric benchmarks."));
ALL.put(PROP_TIMEOUT, new BaseRunnerParam(PROP_TIMEOUT, "-to", false, "Timeout",
"Timeout for benchmark iteration. Arguments accept time suffixes, like \"100ms\"."));
ALL.put(PROP_TIME_UNIT, new SelectRunnerParameter(TimeUnitConst.TIME_UNITS_WITH_DESCRIPTION, PROP_TIME_UNIT,
"-tu", false, "Time unit", "Output time unit. Available time units are: [m, s, ms, us, ns]."));
ALL.put(PROP_VERBOSITY, new SelectRunnerParameter(VerboseModeConst.ALL_WITH_DESCRIPTION, PROP_VERBOSITY, "-v",
false, "Verbosity", "Verbosity mode. Available modes are: [SILENT, NORMAL, EXTRA]"));
ALL.put(PROP_TIME_PER_WARMUP, new BaseRunnerParam(PROP_TIME_PER_WARMUP, "-w", false, "Warmup time",
"Time to spend at each warmup iteration. Arguments accept time suffixes, like \"100ms\"."));
ALL.put(PROP_WARMUP_BATCH_SIZE, new IntRunnerParam(PROP_WARMUP_BATCH_SIZE, "-wbs", false,
"Warmup batch size", "Warmup batch size: number of benchmark method calls per operation. " +
"(some benchmark modes can ignore this setting)", 0));
ALL.put(PROP_WARMUP_FORKS, new IntRunnerParam(PROP_WARMUP_FORKS, "-wf", false, "Warmup forks",
"How many warmup forks to make for a single benchmark. 0 to disable warmup forks.", 0));
ALL.put(PROP_WARMUP_ITERATIONS, new IntRunnerParam(PROP_WARMUP_ITERATIONS, "-wi", false, "Warmup iterations",
"Number of warmup iterations to do.", 0)); | ALL.put(PROP_WARMUP_MODE, new SelectRunnerParameter(WarmupModeConst.ALL_WITH_DESCRIPTION, PROP_WARMUP_MODE, | 2 |
vert-x3/vertx-jdbc-client | src/main/java/examples/JDBCTypeExamples.java | [
"@VertxGen\npublic interface JDBCClient extends SQLClient {\n\n /**\n * The default data source provider is C3P0\n */\n String DEFAULT_PROVIDER_CLASS = \"io.vertx.ext.jdbc.spi.impl.C3P0DataSourceProvider\";\n\n /**\n * The name of the default data source\n */\n String DEFAULT_DS_NAME = \"DEFAULT_DS\";\n\n /**\n * Create a JDBC client which maintains its own data source.\n *\n * @param vertx the Vert.x instance\n * @param config the configuration\n * @return the client\n */\n static JDBCClient create(Vertx vertx, JsonObject config) {\n return new JDBCClientImpl(vertx, config, UUID.randomUUID().toString());\n }\n\n /**\n * Create a JDBC client which shares its data source with any other JDBC clients created with the same\n * data source name\n *\n * @param vertx the Vert.x instance\n * @param config the configuration\n * @param dataSourceName the data source name\n * @return the client\n */\n static JDBCClient createShared(Vertx vertx, JsonObject config, String dataSourceName) {\n return new JDBCClientImpl(vertx, config, dataSourceName);\n }\n\n /**\n * Like {@link #createShared(io.vertx.core.Vertx, JsonObject, String)} but with the default data source name\n * @param vertx the Vert.x instance\n * @param config the configuration\n * @return the client\n */\n static JDBCClient createShared(Vertx vertx, JsonObject config) {\n return new JDBCClientImpl(vertx, config, DEFAULT_DS_NAME);\n }\n\n /**\n * Create a client using a pre-existing data source\n *\n * @param vertx the Vert.x instance\n * @param dataSource the datasource\n * @return the client\n */\n @GenIgnore\n static JDBCClient create(Vertx vertx, DataSource dataSource) {\n return new JDBCClientImpl(vertx, dataSource);\n }\n\n /**\n * Create a client using a data source provider\n *\n * @param vertx the Vert.x instance\n * @param dataSourceProvider the datasource provider\n * @return the client\n * @since 4.2.0\n */\n @GenIgnore\n static JDBCClient create(Vertx vertx, DataSourceProvider dataSourceProvider) {\n return new JDBCClientImpl(vertx, dataSourceProvider);\n }\n\n}",
"public interface DataSourceProvider {\n\n /**\n * Init provider with specific configuration\n *\n * @param sqlConfig SQL connection configuration\n * @return a reference to this for fluent API\n * @apiNote Use it conjunction with {@link #create(JsonObject)}\n * @since 4.2.0\n */\n default DataSourceProvider init(JsonObject sqlConfig) {\n return this;\n }\n\n /**\n * Get the SQL initial configuration\n *\n * @return an initial configuration\n * @apiNote Use it conjunction with {@link #init(JsonObject)}\n * @since 4.2.0\n */\n default JsonObject getInitialConfig() {\n return new JsonObject();\n }\n\n int maximumPoolSize(DataSource dataSource, JsonObject config) throws SQLException;\n\n DataSource getDataSource(JsonObject config) throws SQLException;\n\n void close(DataSource dataSource) throws SQLException;\n\n static DataSourceProvider create(JsonObject config) {\n String providerClass = config.getString(\"provider_class\");\n if (providerClass == null) {\n providerClass = JDBCClient.DEFAULT_PROVIDER_CLASS;\n }\n\n if (Thread.currentThread().getContextClassLoader() != null) {\n try {\n // Try with the TCCL\n Class clazz = Thread.currentThread().getContextClassLoader().loadClass(providerClass);\n return ((DataSourceProvider) clazz.newInstance()).init(config);\n } catch (ClassNotFoundException e) {\n // Next try.\n } catch (InstantiationException | IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }\n\n try {\n // Try with the classloader of the current class.\n Class clazz = DataSourceProvider.class.getClassLoader().loadClass(providerClass);\n return ((DataSourceProvider) clazz.newInstance()).init(config);\n } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Init provider with specific {@link DataSource} and config. The config expects that several properties are set:\n *\n * <ul>\n * <li>{@code url} - the connection string</li>\n * <li>{@code user} - the connection user name</li>\n * <li>{@code database} - the database name</li>\n * <li>{@code maxPoolSize} - the max allowed number of connections in the pool</li>\n * </ul>\n *\n * @param dataSource a pre initialized data source\n * @param config the configuration for the datasource\n * @return a reference to this for fluent API\n * @since 4.2.0\n */\n static DataSourceProvider create(final DataSource dataSource, final JsonObject config) {\n Objects.requireNonNull(config, \"config must not be null\");\n\n return new DataSourceProvider() {\n\n @Override\n public JsonObject getInitialConfig() {\n return config;\n }\n\n @Override\n public int maximumPoolSize(DataSource arg0, JsonObject arg1) {\n return config.getInteger(\"maxPoolSize\", -1);\n }\n\n @Override\n public DataSource getDataSource(JsonObject arg0) {\n return dataSource;\n }\n\n @Override\n public void close(DataSource arg0) throws SQLException {\n if (dataSource instanceof AutoCloseable) {\n try {\n ((AutoCloseable) dataSource).close();\n } catch (Exception e) {\n throw new SQLException(\"Failed to close data source\", e);\n }\n }\n }\n };\n }\n}",
"public interface JDBCDecoder {\n\n /**\n * Parse SQL value to Java value\n *\n * @param rs JDBC result set\n * @param pos the Database column position\n * @param jdbcTypeLookup JDBCType provider\n * @return java value\n * @throws SQLException if any error in parsing\n * @see ResultSet\n * @see JDBCColumnDescriptorProvider\n * @since 4.2.2\n */\n Object parse(ResultSet rs, int pos, JDBCColumnDescriptorProvider jdbcTypeLookup) throws SQLException;\n\n /**\n * Parse SQL value to Java value\n *\n * @param cs JDBC callable statement\n * @param pos the parameter column position\n * @param jdbcTypeLookup JDBCType provider\n * @return java value\n * @throws SQLException if any error in parsing\n * @see CallableStatement\n * @see JDBCColumnDescriptorProvider\n * @since 4.2.2\n */\n Object parse(CallableStatement cs, int pos, JDBCColumnDescriptorProvider jdbcTypeLookup) throws SQLException;\n\n /**\n * Convert the SQL value to Java value based on jdbc type\n *\n * @param descriptor the JDBC column descriptor\n * @param valueProvider the value provider\n * @return java value\n * @see SQLValueProvider\n * @see JDBCColumnDescriptor\n * @since 4.2.2\n */\n Object decode(JDBCColumnDescriptor descriptor, SQLValueProvider valueProvider) throws SQLException;\n\n /**\n * Try cast SQL value to standard Java value depends on standard JDBC 4.2 type mapping and compatible with Vertx\n * <p>\n * For example: - java.sql.Time -> java.time.LocalTime - java.sql.Timestamp -> java.time.LocalDateTime\n *\n * @param value value\n * @return a presenter value\n * @throws SQLException if any error when casting\n */\n Object cast(Object value) throws SQLException;\n\n}",
"public interface JDBCEncoder {\n\n /**\n * Convert Java input value to SQL value\n *\n * @param input array input\n * @param pos column position\n * @param provider JDBCType provider\n * @return SQL value\n * @throws SQLException if any error when convert\n * @see JDBCColumnDescriptorProvider\n */\n Object encode(JsonArray input, int pos, JDBCColumnDescriptorProvider provider) throws SQLException;\n\n}",
"public class JDBCEncoderImpl implements JDBCEncoder {\n\n private static final Logger LOG = LoggerFactory.getLogger(JDBCEncoder.class);\n\n @Override\n public Object encode(JsonArray input, int pos, JDBCColumnDescriptorProvider provider) throws SQLException {\n return doEncode(provider.apply(pos), input.getValue(pos - 1));\n }\n\n protected Object doEncode(JDBCColumnDescriptor descriptor, Object javaValue) {\n if (javaValue == null) {\n return null;\n }\n if (descriptor.jdbcTypeWrapper().isDateTimeType()) {\n return debug(descriptor, encodeDateTime(descriptor, javaValue));\n }\n if (descriptor.jdbcTypeWrapper().isSpecificVendorType()) {\n return debug(descriptor, encodeSpecificVendorType(descriptor, javaValue));\n }\n return debug(descriptor, encodeData(descriptor, javaValue));\n }\n\n /**\n * Convert the parameter {@code Java datetime} value to the {@code SQL datetime} value\n *\n * @param descriptor the column descriptor\n * @param value the java value in parameter\n * @return the compatible SQL value\n */\n protected Object encodeDateTime(JDBCColumnDescriptor descriptor, Object value) {\n JDBCType jdbcType = descriptor.jdbcType();\n if (jdbcType == JDBCType.DATE) {\n if (value instanceof String) {\n return LocalDate.parse((String) value);\n }\n if (value instanceof java.util.Date) {\n return ((java.util.Date) value).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();\n }\n return value;\n }\n if (jdbcType == JDBCType.TIME_WITH_TIMEZONE) {\n if (value instanceof String) {\n return OffsetTime.parse((String) value);\n }\n return value;\n }\n if (jdbcType == JDBCType.TIME) {\n if (value instanceof String) {\n try {\n return LocalTime.parse((String) value);\n } catch (DateTimeParseException e) {\n return OffsetTime.parse((String) value).withOffsetSameInstant(ZoneOffset.UTC).toLocalTime();\n }\n }\n return value;\n }\n if (jdbcType == JDBCType.TIMESTAMP_WITH_TIMEZONE) {\n if (value instanceof String) {\n return OffsetDateTime.parse((String) value);\n }\n return value;\n }\n if (jdbcType == JDBCType.TIMESTAMP) {\n if (value instanceof String) {\n try {\n return LocalDateTime.parse((String) value);\n } catch (DateTimeParseException e) {\n return OffsetDateTime.parse((String) value).withOffsetSameInstant(ZoneOffset.UTC).toLocalDateTime();\n }\n }\n return value;\n }\n throw new IllegalArgumentException(\"Invalid Date Time JDBC Type\");\n }\n\n /**\n * Convert the parameter {@code Java} value to the {@code specific SQL vendor data type}\n *\n * @param descriptor the column descriptor\n * @param javaValue the java value in parameter\n * @return the compatible SQL value\n */\n protected Object encodeSpecificVendorType(JDBCColumnDescriptor descriptor, Object javaValue) {\n return javaValue;\n }\n\n /**\n * Convert any the parameter {@code Java} value expect {@link #encodeDateTime(JDBCColumnDescriptor, Object)} and\n * {@link #encodeSpecificVendorType(JDBCColumnDescriptor, Object)} to the {@code SQL value}\n *\n * @param descriptor the column descriptor\n * @param javaValue the java value in parameter\n * @return the compatible SQL value\n */\n protected Object encodeData(JDBCColumnDescriptor descriptor, Object javaValue) {\n if (descriptor.jdbcTypeWrapper().isAbleAsUUID() && javaValue instanceof String && JDBCStatementHelper.UUID.matcher((String) javaValue).matches()) {\n return UUID.fromString((String) javaValue);\n }\n return javaValue;\n }\n\n private Object debug(JDBCColumnDescriptor descriptor, Object javaValue) {\n LOG.debug(\"Convert JDBC column [\" + descriptor + \"][\" + javaValue.getClass().getName() + \"]\");\n return javaValue;\n }\n\n}",
"@DataObject(generateConverter = true)\npublic class JDBCConnectOptions extends SQLOptions {\n\n private String dataSourceImplementation = \"AGROAL\";\n private boolean metricsEnabled;\n private String jdbcUrl;\n private String user;\n private String password;\n private String database;\n private int connectTimeout = 60000;\n private int idleTimeout;\n private TracingPolicy tracingPolicy = TracingPolicy.PROPAGATE;\n\n public JDBCConnectOptions() {}\n\n public JDBCConnectOptions(JsonObject json) {\n JDBCConnectOptionsConverter.fromJson(json, this);\n }\n\n public String getDataSourceImplementation() {\n return dataSourceImplementation;\n }\n\n public JDBCConnectOptions setDataSourceImplementation(String dataSourceImplementation) {\n this.dataSourceImplementation = dataSourceImplementation;\n return this;\n }\n\n public boolean isMetricsEnabled() {\n return metricsEnabled;\n }\n\n public JDBCConnectOptions setMetricsEnabled(boolean metricsEnabled) {\n this.metricsEnabled = metricsEnabled;\n return this;\n }\n\n public String getJdbcUrl() {\n return jdbcUrl;\n }\n\n public JDBCConnectOptions setJdbcUrl(String jdbcUrl) {\n this.jdbcUrl = jdbcUrl;\n return this;\n }\n\n public String getUser() {\n return user;\n }\n\n public JDBCConnectOptions setUser(String user) {\n this.user = user;\n return this;\n }\n\n public String getPassword() {\n return password;\n }\n\n public JDBCConnectOptions setPassword(String password) {\n this.password = password;\n return this;\n }\n\n public String getDatabase() {\n return database;\n }\n\n public JDBCConnectOptions setDatabase(String database) {\n this.database = database;\n return this;\n }\n\n public int getConnectTimeout() {\n return connectTimeout;\n }\n\n public JDBCConnectOptions setConnectTimeout(int connectTimeout) {\n this.connectTimeout = connectTimeout;\n return this;\n }\n\n public int getIdleTimeout() {\n return idleTimeout;\n }\n\n public JDBCConnectOptions setIdleTimeout(int idleTimeout) {\n this.idleTimeout = idleTimeout;\n return this;\n }\n\n /**\n * @return the tracing policy\n */\n public TracingPolicy getTracingPolicy() {\n return tracingPolicy;\n }\n\n /**\n * Set the tracing policy for the client behavior when Vert.x has tracing enabled.\n *\n * @param tracingPolicy the tracing policy\n * @return a reference to this, so the API can be used fluently\n */\n public JDBCConnectOptions setTracingPolicy(TracingPolicy tracingPolicy) {\n this.tracingPolicy = tracingPolicy;\n return this;\n }\n\n // overrides\n\n @Override\n public JDBCConnectOptions setReadOnly(boolean readOnly) {\n super.setReadOnly(readOnly);\n return this;\n }\n\n @Override\n public JDBCConnectOptions setCatalog(String catalog) {\n super.setCatalog(catalog);\n return this;\n }\n\n @Override\n public JDBCConnectOptions setTransactionIsolation(TransactionIsolation transactionIsolation) {\n super.setTransactionIsolation(transactionIsolation);\n return this;\n }\n\n @Override\n public JDBCConnectOptions setResultSetType(ResultSetType resultSetType) {\n super.setResultSetType(resultSetType);\n return this;\n }\n\n @Override\n public JDBCConnectOptions setResultSetConcurrency(ResultSetConcurrency resultSetConcurrency) {\n super.setResultSetConcurrency(resultSetConcurrency);\n return this;\n }\n\n @Override\n public JDBCConnectOptions setAutoGeneratedKeys(boolean autoGeneratedKeys) {\n super.setAutoGeneratedKeys(autoGeneratedKeys);\n return this;\n }\n\n @Override\n public JDBCConnectOptions setSchema(String schema) {\n super.setSchema(schema);\n return this;\n }\n\n @Override\n public JDBCConnectOptions setQueryTimeout(int queryTimeout) {\n super.setQueryTimeout(queryTimeout);\n return this;\n }\n\n @Override\n public JDBCConnectOptions setFetchDirection(FetchDirection fetchDirection) {\n super.setFetchDirection(fetchDirection);\n return this;\n }\n\n @Override\n public JDBCConnectOptions setFetchSize(int fetchSize) {\n super.setFetchSize(fetchSize);\n return this;\n }\n\n @Override\n public JDBCConnectOptions setAutoGeneratedKeysIndexes(JsonArray autoGeneratedKeysIndexes) {\n super.setAutoGeneratedKeysIndexes(autoGeneratedKeysIndexes);\n return this;\n }\n\n @Override\n public JDBCConnectOptions setMaxRows(int maxRows) {\n super.setMaxRows(maxRows);\n return this;\n }\n\n public JsonObject toJson() {\n final JsonObject json = new JsonObject();\n JDBCConnectOptionsConverter.toJson(this, json);\n return json;\n }\n}",
"@VertxGen\npublic interface JDBCPool extends Pool {\n\n /**\n * The property to be used to retrieve the generated keys\n */\n PropertyKind<Row> GENERATED_KEYS = PropertyKind.create(\"generated-keys\", Row.class);\n\n /**\n * The property to be used to retrieve the output of the callable statement\n */\n PropertyKind<Boolean> OUTPUT = PropertyKind.create(\"callable-statement-output\", Boolean.class);\n\n /**\n * Create a JDBC pool which maintains its own data source.\n *\n * @param vertx the Vert.x instance\n * @param connectOptions the options to configure the connection\n * @param poolOptions the connection pool options\n * @return the client\n */\n static JDBCPool pool(Vertx vertx, JDBCConnectOptions connectOptions, PoolOptions poolOptions) {\n final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();\n\n return new JDBCPoolImpl(\n vertx,\n new JDBCClientImpl(vertx, new AgroalCPDataSourceProvider(connectOptions, poolOptions)),\n connectOptions,\n context.tracer() == null ?\n null :\n new QueryTracer(context.tracer(), connectOptions.getTracingPolicy(), connectOptions.getJdbcUrl(), connectOptions.getUser(), connectOptions.getDatabase()));\n }\n\n /**\n * Create a JDBC pool which maintains its own data source.\n *\n * @param vertx the Vert.x instance\n * @param config the options to configure the client using the same format as {@link io.vertx.ext.jdbc.JDBCClient}\n * @return the client\n */\n static JDBCPool pool(Vertx vertx, JsonObject config) {\n final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();\n String jdbcUrl = config.getString(\"jdbcUrl\", config.getString(\"url\"));\n String user = config.getString(\"username\", config.getString(\"user\"));\n return new JDBCPoolImpl(\n vertx,\n new JDBCClientImpl(vertx, config, UUID.randomUUID().toString()),\n new SQLOptions(config),\n context.tracer() == null ?\n null :\n new QueryTracer(context.tracer(), TracingPolicy.PROPAGATE, jdbcUrl, user, config.getString(\"database\")));\n }\n\n /**\n * Create a JDBC pool which maintains its own data source.\n *\n * @param vertx the Vert.x instance\n * @param dataSourceProvider the options to configure the client using the same format as {@link io.vertx.ext.jdbc.JDBCClient}\n * @return the client\n * @since 4.2.0\n */\n @GenIgnore(GenIgnore.PERMITTED_TYPE)\n static JDBCPool pool(Vertx vertx, DataSourceProvider dataSourceProvider) {\n final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();\n final JsonObject config = dataSourceProvider.getInitialConfig();\n String jdbcUrl = config.getString(\"jdbcUrl\", config.getString(\"url\"));\n String user = config.getString(\"username\", config.getString(\"user\"));\n String database = config.getString(\"database\");\n if (context.tracer() != null) {\n Objects.requireNonNull(jdbcUrl, \"data source url config cannot be null\");\n Objects.requireNonNull(user, \"data source user config cannot be null\");\n Objects.requireNonNull(database, \"data source database config cannot be null\");\n }\n return new JDBCPoolImpl(\n vertx,\n new JDBCClientImpl(vertx, dataSourceProvider),\n new SQLOptions(config),\n context.tracer() == null ?\n null :\n new QueryTracer(context.tracer(), TracingPolicy.PROPAGATE, jdbcUrl, user, database));\n }\n\n /**\n * Create a JDBC pool using a pre-initialized data source.\n *\n * @param vertx the Vert.x instance\n * @param dataSource a pre-initialized data source\n * @return the client\n * @since 4.2.0\n */\n @GenIgnore(GenIgnore.PERMITTED_TYPE)\n static JDBCPool pool(Vertx vertx, DataSource dataSource) {\n return pool(vertx, DataSourceProvider.create(dataSource, new JsonObject()));\n }\n\n /**\n * Create a JDBC pool using a pre-initialized data source. The config expects that at least the following properties\n * are set:\n *\n * <ul>\n * <li>{@code url} - the connection string</li>\n * <li>{@code user} - the connection user name</li>\n * <li>{@code database} - the database name</li>\n * <li>{@code maxPoolSize} - the max allowed number of connections in the pool</li>\n * </ul>\n *\n * @param vertx the Vert.x instance\n * @param dataSource a pre-initialized data source\n * @param config the pool configuration\n * @return the client\n * @since 4.2.0\n */\n @GenIgnore(GenIgnore.PERMITTED_TYPE)\n static JDBCPool pool(Vertx vertx, DataSource dataSource, JsonObject config) {\n return pool(vertx, DataSourceProvider.create(dataSource, config));\n }\n}",
"public class AgroalCPDataSourceProvider implements DataSourceProvider {\n\n private final JDBCConnectOptions connectOptions;\n private final PoolOptions poolOptions;\n private JsonObject initConfig;\n\n public AgroalCPDataSourceProvider(JDBCConnectOptions connectOptions, PoolOptions poolOptions) {\n this.connectOptions = connectOptions;\n this.poolOptions = poolOptions;\n }\n\n @Override\n public DataSourceProvider init(JsonObject sqlConfig) {\n this.initConfig = sqlConfig;\n return this;\n }\n\n @Override\n public JsonObject getInitialConfig() {\n return Optional.ofNullable(initConfig).orElseGet(DataSourceProvider.super::getInitialConfig);\n }\n\n @Override\n public int maximumPoolSize(DataSource dataSource, JsonObject config) {\n return poolOptions.getMaxSize();\n }\n\n @Override\n public DataSource getDataSource(JsonObject config) throws SQLException {\n\n AgroalDataSourceConfigurationSupplier dataSourceConfigurationBuilder = new AgroalDataSourceConfigurationSupplier()\n .dataSourceImplementation(AgroalDataSourceConfiguration.DataSourceImplementation.valueOf(connectOptions.getDataSourceImplementation()))\n .metricsEnabled(connectOptions.isMetricsEnabled())\n .connectionPoolConfiguration(cp ->\n cp\n .validationTimeout(Duration.ofMillis(connectOptions.getConnectTimeout()))\n .minSize(0)\n .maxSize(poolOptions.getMaxSize())\n .initialSize(1)\n .acquisitionTimeout(Duration.ofMillis(connectOptions.getConnectTimeout()))\n .reapTimeout(Duration.ofMillis(connectOptions.getIdleTimeout()))\n .leakTimeout(Duration.ofMillis(connectOptions.getIdleTimeout()))\n .connectionFactoryConfiguration(cf ->\n cf\n .jdbcUrl(connectOptions.getJdbcUrl())\n .principal(connectOptions.getUser() != null ? new NamePrincipal(connectOptions.getUser()) : null)\n .credential(connectOptions.getPassword() != null ? new SimplePassword(connectOptions.getPassword()) : null)\n )\n );\n\n return AgroalDataSource.from(dataSourceConfigurationBuilder);\n }\n\n @Override\n public void close(DataSource dataSource) throws SQLException {\n if (dataSource instanceof AgroalDataSource) {\n ((AgroalDataSource) dataSource).close();\n }\n }\n}",
"public class JDBCColumnDescriptor implements ColumnDescriptor {\n\n private final String columnLabel;\n private final JDBCTypeWrapper jdbcTypeWrapper;\n\n private JDBCColumnDescriptor(String columnLabel, JDBCTypeWrapper jdbcTypeWrapper) {\n this.columnLabel = columnLabel;\n this.jdbcTypeWrapper = jdbcTypeWrapper;\n }\n\n @Override\n public String name() {\n return columnLabel;\n }\n\n @Override\n public boolean isArray() {\n return jdbcType() == JDBCType.ARRAY;\n }\n\n @Override\n public String typeName() {\n return jdbcTypeWrapper.vendorTypeName();\n }\n\n /**\n * Use {@link #jdbcTypeWrapper()} when converting an advanced data type depending on the specific database\n *\n * @return the most appropriate {@code JDBCType} or {@code null} if it is advanced type of specific database\n */\n @Override\n public JDBCType jdbcType() {\n return jdbcTypeWrapper.jdbcType();\n }\n\n /**\n * @return the jdbc type wrapper\n * @see JDBCTypeWrapper\n */\n public JDBCTypeWrapper jdbcTypeWrapper() {\n return this.jdbcTypeWrapper;\n }\n\n @Override\n public String toString() {\n return \"JDBCColumnDescriptor[columnName=(\" + columnLabel + \"), jdbcTypeWrapper=(\" + jdbcTypeWrapper + \")]\";\n }\n\n public static JDBCColumnDescriptor create(JDBCPropertyAccessor<String> columnLabel,\n JDBCPropertyAccessor<Integer> vendorTypeNumber,\n JDBCPropertyAccessor<String> vendorTypeName,\n JDBCPropertyAccessor<String> vendorTypeClassName) throws SQLException {\n return new JDBCColumnDescriptor(columnLabel.get(), JDBCTypeWrapper.of(vendorTypeNumber.get(), vendorTypeName.get(),\n vendorTypeClassName.get()));\n }\n\n public static JDBCColumnDescriptor wrap(JDBCType jdbcType) {\n return new JDBCColumnDescriptor(null, JDBCTypeWrapper.of(jdbcType));\n }\n\n}"
] | import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.docgen.Source;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.jdbc.spi.DataSourceProvider;
import io.vertx.ext.jdbc.spi.JDBCDecoder;
import io.vertx.ext.jdbc.spi.JDBCEncoder;
import io.vertx.ext.jdbc.spi.impl.JDBCEncoderImpl;
import io.vertx.jdbcclient.JDBCConnectOptions;
import io.vertx.jdbcclient.JDBCPool;
import io.vertx.jdbcclient.impl.AgroalCPDataSourceProvider;
import io.vertx.jdbcclient.impl.actions.JDBCColumnDescriptor;
import io.vertx.sqlclient.PoolOptions;
import java.sql.Date;
import java.sql.JDBCType;
import java.time.LocalDate; | package examples;
@Source
public class JDBCTypeExamples {
public static class DerbyEncoder extends JDBCEncoderImpl {
@Override
protected Object encodeDateTime(JDBCColumnDescriptor descriptor, Object value) {
Object v = super.encodeDateTime(descriptor, value);
if (descriptor.jdbcType() == JDBCType.DATE) {
return Date.valueOf((LocalDate) v);
}
return v;
}
}
public JDBCClient createJDBCClient(Vertx vertx, Class<JDBCEncoder> encoderClass, Class<JDBCDecoder> decoderClass) {
JsonObject options = new JsonObject().put("url", "your_jdbc_url")
.put("user", "your_database_user")
.put("password", "your_database_password")
.put("encoderCls", encoderClass.getName())
.put("decoderCls", decoderClass.getName());
return JDBCClient.createShared(vertx, options);
}
public JDBCPool createJDBCPool(Vertx vertx, Class<JDBCEncoder> encoderClass, Class<JDBCDecoder> decoderClass) {
JsonObject extraOptions = new JsonObject()
.put("encoderCls", encoderClass.getName())
.put("decoderCls", decoderClass.getName());
JDBCConnectOptions options = new JDBCConnectOptions().setJdbcUrl("your_jdbc_url")
.setUser("your_database_user")
.setPassword("your_database_password");
PoolOptions poolOptions = new PoolOptions().setMaxSize(1); | DataSourceProvider provider = new AgroalCPDataSourceProvider(options, poolOptions).init(extraOptions); | 7 |
yuqirong/NewsPublish | src/com/cjlu/newspublish/services/impl/AdminServiceImpl.java | [
"@Repository(\"adminDao\")\npublic class AdminDaoImpl extends BaseDaoImpl<Admin> {\n\n\tpublic Admin isAdmin(String username, String password) {\n\t\tString hql = \"FROM Admin WHERE username = ? AND password= ?\";\n\t\tAdmin admin = (Admin) getSession().createQuery(hql).setString(0, username)\n\t\t\t\t.setString(1, DataUtils.md5(password)).uniqueResult();\n\t\treturn admin;\n\t}\n\n\tpublic Admin findAdminByUsername(String username) {\n\t\tString hql = \"FROM Admin a where a.username = ?\";\n\t\treturn (Admin) this.uniqueResult(hql, username);\n\t}\n\n}",
"public class Admin extends BaseEntity {\n\n\tprivate static final long serialVersionUID = -2754043214810493011L;\n\t// Óû§Ãû\n\tprivate String username;\n\t// ÃÜÂë\n\tprivate String password;\n\t// Email\n\tprivate String email;\n\t// ÊÇ·ñÆôÓÃ\n\tprivate boolean enabled;\n\t// Á¬ÐøµÇ¼ʧ°Ü´ÎÊý\n\tprivate Integer loginFailureCount;\n\t// Ëø¶¨ÈÕÆÚ\n\tprivate Date lockedTime;\n\t// ×îºóµÇ¼ÈÕÆÚ\n\tprivate Date loginTime;\n\t// ×îºóµÇ¼IP\n\tprivate String ipAddress;\n\t// ´´½¨Ê±¼ä\n\tprivate Date createTime = new Date();\n\t// ÓµÓеÄȨÏÞ\n\tprivate Set<Role> roles = new HashSet<Role>();\n\t// ȨÏÞ×ܺÍ\n\tprivate long[] rightSum;\n\n\tpublic Integer getLoginFailureCount() {\n\t\treturn loginFailureCount;\n\t}\n\n\tpublic void setLoginFailureCount(Integer loginFailureCount) {\n\t\tthis.loginFailureCount = loginFailureCount;\n\t}\n\n\tpublic Date getLockedTime() {\n\t\treturn lockedTime;\n\t}\n\n\tpublic void setLockedTime(Date lockedTime) {\n\t\tthis.lockedTime = lockedTime;\n\t}\n\n\tpublic Date getLoginTime() {\n\t\treturn loginTime;\n\t}\n\n\tpublic void setLoginTime(Date loginTime) {\n\t\tthis.loginTime = loginTime;\n\t}\n\n\tpublic String getIpAddress() {\n\t\treturn ipAddress;\n\t}\n\n\tpublic void setIpAddress(String ipAddress) {\n\t\tthis.ipAddress = ipAddress;\n\t}\n\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic boolean isEnabled() {\n\t\treturn enabled;\n\t}\n\n\tpublic void setEnabled(boolean enabled) {\n\t\tthis.enabled = enabled;\n\t}\n\n\tpublic Date getCreateTime() {\n\t\treturn createTime;\n\t}\n\n\tpublic void setCreateTime(Date createTime) {\n\t\tthis.createTime = createTime;\n\t}\n\n\tpublic long[] getRightSum() {\n\t\treturn rightSum;\n\t}\n\n\tpublic void setRightSum(long[] rightSum) {\n\t\tthis.rightSum = rightSum;\n\t}\n\n\t/**\n\t * ÅжÏÓû§ÊÇ·ñ¾ßÓÐÖ¸¶¨È¨ÏÞ\n\t */\n\tpublic boolean hasRight(Right r) {\n\t\tint pos = r.getRightPos();\n\t\tlong code = r.getRightCode();\n\t\treturn !((rightSum[pos] & code) == 0);\n\t}\n\n\tpublic Set<Role> getRoles() {\n\t\treturn roles;\n\t}\n\n\tpublic void setRoles(Set<Role> roles) {\n\t\tthis.roles = roles;\n\t}\n\n\t/**\n\t * ¼ÆËãÓû§È¨ÏÞ×ܺÍ\n\t */\n\tpublic void calculateRightSum() {\n\t\tint pos = 0;\n\t\tlong code = 0;\n\t\tfor (Role role : roles) {\n\t\t\tfor (Right r : role.getRights()) {\n\t\t\t\tpos = r.getRightPos();\n\t\t\t\tcode = r.getRightCode();\n\t\t\t\trightSum[pos] = rightSum[pos] | code;\n\t\t\t}\n\t\t}\n\t\t// ÊÍ·Å×ÊÔ´\n\t\troles = null;\n\t}\n\n}",
"public class Role extends BaseEntity{\n\t\n\tprivate static final long serialVersionUID = 596760102394542763L;\n\tprivate String roleName;\n\tprivate String roleValue;\n\tprivate String roleDesc;\n\tprivate Set<Right> rights = new HashSet<Right>();\n\t\n\tpublic String getRoleName() {\n\t\treturn roleName;\n\t}\n\tpublic void setRoleName(String roleName) {\n\t\tthis.roleName = roleName;\n\t}\n\tpublic String getRoleValue() {\n\t\treturn roleValue;\n\t}\n\tpublic void setRoleValue(String roleValue) {\n\t\tthis.roleValue = roleValue;\n\t}\n\tpublic String getRoleDesc() {\n\t\treturn roleDesc;\n\t}\n\tpublic void setRoleDesc(String roleDesc) {\n\t\tthis.roleDesc = roleDesc;\n\t}\n\tpublic Set<Right> getRights() {\n\t\treturn rights;\n\t}\n\tpublic void setRights(Set<Right> rights) {\n\t\tthis.rights = rights;\n\t}\n\t\n}",
"public interface AdminService extends BaseService<Admin> {\n\n\tpublic void updateAuthorize(Admin model, Integer[] ownRoleIds);\n\n\tpublic void loginFailure(String username);\n\n\tpublic Admin findByUsername(String username);\n\n\tpublic Admin isAdmin(String username, String password);\n\n}",
"public interface RoleService extends BaseService<Role>{\n\n\tpublic void saveOrUpdateRole(Role model, Integer[] ownRightIds);\n\n\tpublic List<Role> findRolesNotInRange(Set<Role> set);\n\n\tpublic List<Role> findRolesInRange(Integer[] ownRoleIds);\n\n}",
"public final class ValidateUtils {\n\t\n\tprivate ValidateUtils(){\n\t\t\n\t}\n\n\t/**\n\t * ÅжÏ×Ö·û´®µÄÓÐЧÐÔ\n\t */\n\tpublic static boolean isValid(String str) {\n\t\tif (str == null || \"\".equals(str.trim())) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Åжϼ¯ºÏµÄÓÐЧÐÔ\n\t */\n\t@SuppressWarnings(\"rawtypes\")\n\tpublic static boolean isValid(Collection collection) {\n\t\tif (collection == null || collection.isEmpty()) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * ÅжÏÊý×éÊÇ·ñÓÐЧ\n\t */\n\tpublic static boolean isValid(Object[] arr) {\n\t\tif (arr == null || arr.length == 0) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n\tpublic static boolean hasRight(String nameSpace, String actionName,\n\t\t\tHttpServletRequest req, BaseAction baseAction) {\n\t\tif (!ValidateUtils.isValid(nameSpace) || \"/\".equals(nameSpace)) {\n\t\t\tnameSpace = \"\";\n\t\t}\n\t\t// ½«³¬Á´½ÓµÄ²ÎÊý²¿·ÖÂ˵ô ?xxxx\n\t\tif (actionName != null && actionName.contains(\"?\")) {\n\t\t\tactionName = actionName.substring(0, actionName.indexOf(\"?\"));\n\t\t}\n\t\tString url = nameSpace + \"/\" + actionName;\n\t\tHttpSession session = req.getSession();\n\n\t\tServletContext sc = session.getServletContext();\n\t\tMap<String, Right> map = (Map<String, Right>) sc\n\t\t\t\t.getAttribute(\"all_rights_map\");\n\t\tRight r = map.get(url);\n\t\t// ¹«¹²×ÊÔ´?\n\t\tif (r == null || r.isCommon()) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\tAdmin admin = (Admin) session.getAttribute(\"admin\");\n\t\t\t// µÇ½?\n\t\t\tif (admin == null) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\t// userAware´¦Àí\n\t\t\t\tif (baseAction != null && baseAction instanceof AdminAware) {\n\t\t\t\t\t((AdminAware) baseAction).setAdmin(admin);\n\t\t\t\t}\n\t\t\t\t// ÓÐȨÏÞ?\n\t\t\t\tif (admin.hasRight(r)) {\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"
] | import java.util.Date;
import java.util.HashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cjlu.newspublish.daos.impl.AdminDaoImpl;
import com.cjlu.newspublish.models.security.Admin;
import com.cjlu.newspublish.models.security.Role;
import com.cjlu.newspublish.services.AdminService;
import com.cjlu.newspublish.services.RoleService;
import com.cjlu.newspublish.utils.ValidateUtils; | package com.cjlu.newspublish.services.impl;
@Service("adminService")
public class AdminServiceImpl extends BaseServiceImpl<Admin> implements
AdminService {
@Autowired | private AdminDaoImpl adminDao; | 0 |
mattbrejza/rtty_modem | rtty_dev/src/rttywin.java | [
"public class Gps_coordinate implements java.io.Serializable {\r\n\r\n\tprivate static final long serialVersionUID = 0x5901fa8c0e38abb4L;\r\n\t\r\n\tpublic double latitude = 0;\r\n\tpublic double longitude = 0;\r\n\tpublic boolean latlong_valid = false;\r\n\t\r\n\tpublic double altitude = 0;\r\n\tpublic boolean alt_valid = false;\r\n\t\r\n\tpublic Gps_coordinate(){\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic Gps_coordinate(double lat, double longi, double alt) {\r\n\t\tSet_altitude(alt);\r\n\t\tSet_decimal(lat, longi);\r\n\t}\r\n\t\r\n\tpublic Gps_coordinate(int lat, int longi, int alt) {\r\n\t\tSet_altitude(alt);\r\n\t\tSet_decimal((double)lat*1e-7, (double)longi*1e-7);\r\n\t}\r\n\t\r\n\tpublic Gps_coordinate(int lat, int longi) {\r\n\t\tSet_decimal((double)lat*1e-7, (double)longi*1e-7);\r\n\t}\r\n\t\r\n\tpublic Gps_coordinate(String lat, String longi, String alt)\r\n\t{\r\n\t\tSet_str(lat,longi);\r\n\t\tSet_altitude(alt);\r\n\t\t\r\n\t}\r\n\t\r\n\t//uses meters\r\n\tpublic void Set_altitude(double alt)\r\n\t{\r\n\t\tif (alt > -500 && alt < 50000000)\r\n\t\t{\r\n\t\t\taltitude = alt;\r\n\t\t\talt_valid = true;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\talt_valid = false;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void Set_altitude(String alt)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tdouble a = Double.parseDouble(alt);\r\n\t\t\tSet_altitude(a);\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\talt_valid = false;\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic void Set_str(String lat, String longi)\r\n\t{\r\n\t\t\r\n\t\t//different formats:\r\n\t\t//NMEA: (-)DDMM.mmm... (-)DDDMM.mmm...\r\n\t\t//decimal: (-)(D)D.ddd... (-)(DD)D.ddd...\r\n\t\t//int: something else, no decimal places\r\n\r\n\t\tint offset_lat=0;\r\n\t\tint offset_long=0;\r\n\t\t\r\n\t\tif (lat.length() < 3 || lat.length() < 3)\r\n\t\t{\r\n\t\t\tlatlong_valid = false;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tif (lat.charAt(0) == '-')\r\n\t\t\toffset_lat = 1;\r\n\t\telse if (lat.charAt(0) == '+')\r\n\t\t\tlat = lat.substring(1);\r\n\t\t\r\n\t\tif (longi.charAt(0) == '-')\r\n\t\t\toffset_long = 1;\r\n\t\telse if (longi.charAt(0) == '+')\r\n\t\t\tlongi = longi.substring(1);\r\n\t\t\r\n\t\tint i,j;\r\n\t\t\r\n\t\ti = lat.indexOf('.');\r\n\t\tj = longi.indexOf('.');\r\n\r\n\t\t\r\n\t\ttry\r\n\t\t{\r\n\t\t\tif (i < 0 || j < 0) // 1/10s of a microdegree\r\n\t\t\t{\r\n\r\n\t\t\t\tSet_decimal(Double.parseDouble(lat)/1e7, Double.parseDouble(longi)/1e7);\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\telse if (i == 4+offset_lat) //NMEA\r\n\t\t\t{\r\n\t\t\t\tif (j == 5 + offset_long) //confirmed NMEA\r\n\t\t\t\t{\r\n\t\t\t\t\tint la1 = Integer.parseInt(lat.substring(0, offset_lat+2)); //get the (-)DD part\r\n\t\t\t\t\tint lo1 = Integer.parseInt(longi.substring(0, offset_long+3)); //get the (-)DDD part\r\n\t\t\t\t\tdouble la2 = Double.parseDouble(lat.substring(offset_lat+2,lat.length())); //get the MM.mmmm part\r\n\t\t\t\t\tdouble lo2 = Double.parseDouble(longi.substring(offset_long+3,longi.length())); //get the MM.mmmm part\r\n\t\r\n\t\t\t\t\tif (offset_lat > 0)\r\n\t\t\t\t\t\tla2 = -1 * la2;\r\n\t\t\t\t\tif (offset_long > 0)\r\n\t\t\t\t\t\tlo2 = -1 * lo2;\r\n\t\t\t\t\t\r\n\t\t\t\t\tSet_decimal((double)la1 + la2/60,(double)lo1 + lo2/60);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tlatlong_valid = false;\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if (i > 4+offset_lat || j > 5+offset_lat) //junk\r\n\t\t\t{\r\n\t\t\t\tlatlong_valid = false;\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\telse //decimal\r\n\t\t\t{\r\n\t\t\t\tSet_decimal(Double.parseDouble(lat), Double.parseDouble(longi));\r\n\t\t\t}\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\tlatlong_valid = false;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t}\r\n\t\t\r\n\tpublic void Set_decimal(double lat, double longi)\r\n\t{\r\n\t\tif (verify(lat,longi))\r\n\t\t{\r\n\t\t\tlatitude = lat;\r\n\t\t\tlongitude = longi;\r\n\t\t\tlatlong_valid = true;\t\t\t\r\n\t\t}\r\n\t\telse\r\n\t\t\tlatlong_valid = false;\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic void Set_NMEA(String lat, String longi)\r\n\t{\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic void Set_NMEA(String lat, String longi, char NS, char EW)\r\n\t{\r\n\t\t\r\n\t}\r\n\t\r\n\tprivate boolean verify(double lat, double longi)\r\n\t{\r\n\t\tif (lat < 90 && lat > -90 && longi > -180 && longi < 180)\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\r\n}\r",
"public class Habitat_interface {\r\n\r\n\tprivate String _habitat_url = \"habitat.habhub.org\";\r\n\tprivate String _habitat_db = \"habitat\";\r\n\tprivate Listener _listener_info;\r\n\tprivate String _listener_telem_UUID=\"\";\r\n\tprivate String _listener_info_UUID=\"\";\r\n\t\r\n\tprotected ArrayList<HabitatRxEvent> _listeners = new ArrayList<HabitatRxEvent>();\r\n\t\r\n\tpublic ConcurrentHashMap<String,String> payload_configs = new ConcurrentHashMap<String,String>();\r\n\tpublic ConcurrentHashMap<String,String> flight_configs = new ConcurrentHashMap<String,String>();\r\n\tprivate ConcurrentHashMap<String,TelemetryConfig> telem_configs = new ConcurrentHashMap<String,TelemetryConfig>();\r\n\t\r\n\tprivate boolean _newTelemConfigs = false;\r\n\t\r\n\tprivate Session s;\r\n\tprivate Database db;\r\n\tprivate Thread sdThread;\r\n\t\r\n\tpublic String device = \"device\";//\"XOOM\";\r\n\tpublic String device_software = \"\";//\"4.0.x\";\r\n\tpublic String application = \"HAB Modem\";\r\n\tpublic String application_version = \"pre-alpha\";\r\n\t\r\n\tprivate int _prev_query_time = 5 * 60 * 60;\r\n\t\r\n\tprivate boolean _queried_current_flights = false;\r\n \r\n\t//TODO: if failed due to connection error, identify error and dont clear the list.\r\n\t\r\n\tprivate Queue<Telemetry_string> out_buff = new LinkedBlockingQueue<Telemetry_string>();\r\n\tprivate Queue<QueueItem> _operations = new LinkedBlockingQueue<QueueItem>();\r\n\t\r\n\t\r\n\t\r\n\tpublic Habitat_interface(String callsign) {\t\t\r\n\t\t_listener_info = new Listener(callsign,false);\r\n\t}\r\n\t\r\n\tpublic Habitat_interface(String habitat_url, String habitat_db, Listener listener_info) {\r\n\t\t_habitat_url = habitat_url;\r\n\t\t_habitat_db = habitat_db;\r\n\t\t_listener_info = listener_info;\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic Habitat_interface(String habitat_url, String habitat_db) {\r\n\t\t_habitat_url = habitat_url;\r\n\t\t_habitat_db = habitat_db;\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic void Test()\r\n\t{\t\t\r\n\t\t s = new Session(_habitat_url,80);\r\n\t\t db = s.getDatabase(_habitat_db);\r\n\t\t List<Document> foodoc;\r\n\t\t View v = new View(\"payload_configuration/callsign_time_created_index\");\r\n\t\t //View v = new View(\"payload_configuration/callsign_time_created_index&startkey%3D[%22APEX%22]\");\r\n\t\t// v.setKey(\"startkey=APEX\");\r\n\t\t v.setStartKey(\"[%22APEX%22]\");\r\n\t\t v.setLimit(1);\r\n\t\t//foodoc = db.view(\"flight/end_start_including_payloads\").getResults();\r\n\t\t foodoc = db.view(v).getResults();\r\n\t\tfoodoc.toString();\t\t\r\n\t}\r\n\t\r\n\tpublic void addHabitatRecievedListener(HabitatRxEvent listener)\r\n\t{\t\r\n\t\t_listeners.add(listener);\r\n\t}\r\n\t\r\n\tpublic void addDataFetchTask(String callsign, long startTime, long stopTime, int limit)\r\n\t{\r\n\t\t_operations.offer(new QueueItem(1,callsign, startTime, stopTime, limit));\r\n\t\tStartThread();\r\n\t}\r\n\t\r\n\tpublic void updateChaseCar(Listener newlocation)\r\n\t{\r\n\t\t_listener_info = newlocation;\r\n\t\t_operations.offer(new QueueItem(3,0));\r\n\t\tStartThread();\r\n\t}\r\n\t\r\n\tpublic void updateListener(Listener newlistener)\r\n\t{\r\n\t\t_listener_info = newlistener;\r\n\t}\r\n\t\r\n\tpublic void addGetActiveFlightsTask()\r\n\t{\r\n\t\t_operations.offer(new QueueItem(2,0));\r\n\t\tStartThread();\r\n\t}\r\n\t\r\n\tprivate String resolvePayloadID(String callsign)\r\n\t{\r\n\t\tString c = callsign.toUpperCase();\r\n\t\tif (payload_configs.containsKey(c))\r\n\t\t\treturn payload_configs.get(c);\r\n\t\telse if (!_queried_current_flights)\r\n\t\t\t_queried_current_flights = queryActiveFlights();\r\n\t\t\t\r\n\t\tif (payload_configs.containsKey(c))\r\n\t\t\treturn payload_configs.get(c);\r\n\t\telse\r\n\t\t{\r\n\t\t\tqueryAllPayloadDocs(c);\r\n\t\t\tif (payload_configs.containsKey(c))\r\n\t\t\t\treturn payload_configs.get(c);\r\n\t\t\telse\r\n\t\t\t\treturn null; //TODO: add list of non payloads\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic boolean queryAllPayloadDocs(String callsign)\r\n\t{\r\n\t\tString docid = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\t//open DB connection\r\n\t\t\tif (s == null)\r\n\t\t\t{\r\n\t\t\t\t s = new Session(_habitat_url,80);\r\n\t\t\t\t db = s.getDatabase(_habitat_db);// + \"/_design/payload_telemetry/_update/add_listener\");\r\n\t\t\t}\r\n\t\t\telse if (db == null)\r\n\t\t\t\tdb = s.getDatabase(_habitat_db);\r\n\t\t\r\n\t\t\tList<Document> docsout;\r\n\t\t\tView v = new View(\"payload_configuration/callsign_time_created_index\");\r\n\t\t\t//startkey=[\"CRAAG1\",1357396479]&endkey=[\"CRAAG1\",0]&descending=true\r\n\t\t\tv.setStartKey(\"[%22\" + callsign.toUpperCase() + \"%22,\" + Long.toString((System.currentTimeMillis() / 1000L)) + \"]\");\r\n\t\t\tv.setEndKey(\"[%22\" + callsign.toLowerCase() + \"%22,0]\");\r\n\t\t\t//v.setWithDocs(true);\r\n\t\t\tv.setLimit(1);\r\n\t\t\tv.setDescending(true);\r\n\t\t\tViewResults r = db.view(v);\r\n\t\t\tdocsout = r.getResults();\r\n\t\t\t\r\n\t\t\t//docsout.toString();\r\n \r\n\r\n\t\t\t//docsout.get(0).getJSONObject().getJSONObject(\"doc\").getString(\"type\")\r\n\t\t\t//docsout.get(1).getJSONObject().getJSONObject(\"doc\").getJSONArray(\"sentences\").getJSONObject(0).getString(\"callsign\")\r\n\t\t\t\r\n\t\t\tif (docsout.size() > 0)\r\n\t\t\t{\r\n\t\t\t\tJSONArray ja = docsout.get(0).getJSONArray(\"key\");\r\n\t\t\t\tString ss = docsout.get(0).getId();\r\n\t\t\t\tif (ja.getString(0).equals(callsign))\r\n\t\t\t\t\tdocid = ss;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\tSystem.out.println(\"ERROR: \"+ e.toString());\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t\t\r\n\t\tif (docid != null)\r\n\t\t\tpayload_configs.put(callsign.toUpperCase(),docid);\r\n\t\t\r\n\t\t\r\n\t\treturn true;\r\n\t\r\n\t}\r\n\t\r\n\tprivate boolean queryPayloadConfig(String docID)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\t//open DB connection\r\n\t\t\tif (s == null)\r\n\t\t\t{\r\n\t\t\t\t s = new Session(_habitat_url,80);\r\n\t\t\t\t db = s.getDatabase(_habitat_db);// + \"/_design/payload_telemetry/_update/add_listener\");\r\n\t\t\t}\r\n\t\t\telse if (db == null)\r\n\t\t\t\tdb = s.getDatabase(_habitat_db);\r\n\t\t\r\n\t\t\t\r\n\t\t\tDocument doc = db.getDocument(docID);\r\n\r\n\t\t\tif (doc == null)\r\n\t\t\t\treturn false;\t\t\t\r\n\t\t\tCouchResponse cr = s.getLastResponse();\t\t\r\n\t\t\tif (!cr.isOk())\r\n\t\t\t\treturn false;\t\t\r\n\t\t\t\r\n\t\t\tJSONObject obj;\r\n\t\t\tJSONArray sentences;\r\n\t\t\tJSONArray fields;\r\n\t\t\tJSONArray filters;\r\n\t\t\t\r\n\t\t\tTelemetryConfig tc = new TelemetryConfig();\r\n\t\t\t\r\n\t\t\tobj = doc.getJSONObject();\r\n\t\t\tif (obj.containsKey(\"sentences\")){\r\n\t\t\t\tsentences = obj.getJSONArray(\"sentences\");\r\n\t\t\t\tfor (int i = 0; i < sentences.size(); i++){\r\n\t\t\t\t\tString call = \"\";\r\n\t\t\t\t\tif (sentences.getJSONObject(i).containsKey(\"callsign\")){\r\n\t\t\t\t\t\tcall = sentences.getJSONObject(i).getString(\"callsign\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (sentences.getJSONObject(i).containsKey(\"fields\")){\r\n\t\t\t\t\t\tfields = sentences.getJSONObject(i).getJSONArray(\"fields\");\r\n\t\t\t\t\t\tfor (int j = 0; j < fields.size(); j++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tString name = fields.getJSONObject(j).getString(\"name\");\r\n\t\t\t\t\t\t\tString sensor = \"\";\r\n\t\t\t\t\t\t\tString format = \"\";\r\n\t\t\t\t\t\t\tTelemetryConfig.DataType dt = TelemetryConfig.DataType.IGNORE;\r\n\t\t\t\t\t\t\tif (fields.getJSONObject(j).containsKey(\"sensor\"))\r\n\t\t\t\t\t\t\t\tsensor = fields.getJSONObject(j).getString(\"sensor\");\r\n\t\t\t\t\t\t\tif (fields.getJSONObject(j).containsKey(\"format\"))\r\n\t\t\t\t\t\t\t\tformat = fields.getJSONObject(j).getString(\"format\");\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tif (name.equals(\"sentence_id\")){\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (name.equals(\"time\")){\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (name.equals(\"latitude\" )){\r\n\t\t\t\t\t\t\t\tif (sensor.equals(\"base.ascii_int\"))\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t//TODO\r\n\t\t\t\t\t\t\t\t\ttc.gpsFormat = TelemetryConfig.GPSFormat.INT;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (name.equals(\"longitude\" )){\r\n\t\t\t\t\t\t\t\tif (sensor.equals(\"base.ascii_int\"))\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t//TODO\r\n\t\t\t\t\t\t\t\t\ttc.gpsFormat = TelemetryConfig.GPSFormat.INT;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (name.equals(\"altitude\" )){\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\tif (sensor.equals(\"base.ascii_int\"))\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tdt = TelemetryConfig.DataType.INT;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\telse if (sensor.equals(\"base.string\"))\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tdt = TelemetryConfig.DataType.STRING;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\telse if (sensor.equals(\"base.ascii_float\"))\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tdt = TelemetryConfig.DataType.FLOAT;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\ttc.addField(name, dt);\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif (sentences.getJSONObject(i).containsKey(\"filters\")){\r\n\t\t\t\t\t\t\tif (sentences.getJSONObject(i).getJSONObject(\"filters\").containsKey(\"post\")){\r\n\t\t\t\t\t\t\t\tfilters = sentences.getJSONObject(i).getJSONObject(\"filters\").getJSONArray(\"post\");\r\n\t\t\t\t\t\t\t\tfor (int j = 0; j < filters.size(); j++)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tString filtertype = \"\";\r\n\t\t\t\t\t\t\t\t\tString source = \"\";\r\n\t\t\t\t\t\t\t\t\tString factor = \"\";\r\n\t\t\t\t\t\t\t\t\tString offset = \"\";\r\n\t\t\t\t\t\t\t\t\tString round = \"\";\r\n\t\t\t\t\t\t\t\t\tString type = \"\";\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\tif (filters.getJSONObject(j).containsKey(\"filter\"))\r\n\t\t\t\t\t\t\t\t\t\tfiltertype = filters.getJSONObject(j).getString(\"filter\");\r\n\t\t\t\t\t\t\t\t\tif (filters.getJSONObject(j).containsKey(\"source\"))\r\n\t\t\t\t\t\t\t\t\t\tsource = filters.getJSONObject(j).getString(\"source\");\r\n\t\t\t\t\t\t\t\t\tif (filters.getJSONObject(j).containsKey(\"factor\"))\r\n\t\t\t\t\t\t\t\t\t\tfactor = filters.getJSONObject(j).getString(\"factor\");\r\n\t\t\t\t\t\t\t\t\tif (filters.getJSONObject(j).containsKey(\"type\"))\r\n\t\t\t\t\t\t\t\t\t\ttype = filters.getJSONObject(j).getString(\"type\");\r\n\t\t\t\t\t\t\t\t\tif (filters.getJSONObject(j).containsKey(\"offset\"))\r\n\t\t\t\t\t\t\t\t\t\toffset = filters.getJSONObject(j).getString(\"offset\");\r\n\t\t\t\t\t\t\t\t\tif (filters.getJSONObject(j).containsKey(\"round\"))\r\n\t\t\t\t\t\t\t\t\t\tround = filters.getJSONObject(j).getString(\"round\");\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\tif (filtertype.equals(\"common.numeric_scale\")){\r\n\t\t\t\t\t\t\t\t\t\ttc.addFilter(source,factor,offset,round);\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\t//save tc to some sort of data structure\r\n\t\t\t\t\ttelem_configs.put(call.toUpperCase(), tc);\r\n\t\t\t\t\t_newTelemConfigs = true;\r\n\t\t\t\t}\t\t\t\t\r\n\t\t\t}\t\t\t\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\tSystem.out.println(\"ERROR: \"+ e.toString());\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t\t\r\n\t\t\t\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tprivate boolean queryActiveFlights()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\t//open DB connection\r\n\t\t\tif (s == null)\r\n\t\t\t{\r\n\t\t\t\t s = new Session(_habitat_url,80);\r\n\t\t\t\t db = s.getDatabase(_habitat_db);// + \"/_design/payload_telemetry/_update/add_listener\");\r\n\t\t\t}\r\n\t\t\telse if (db == null)\r\n\t\t\t\tdb = s.getDatabase(_habitat_db);\r\n\t\t\r\n\t\t\tList<Document> docsout;\r\n\t\t\tView v = new View(\"flight/end_start_including_payloads\");\r\n\t\t\t\r\n\t\t\tv.setStartKey(\"[\" + Long.toString((System.currentTimeMillis() / 1000L)-(2*60*60)) + \"]\");\r\n\t\t\t\r\n\t\t\tv.setWithDocs(true);\r\n\t\t\tv.setLimit(30);\r\n\t\t\t\r\n\t\t\tViewResults r = db.view(v);\r\n\t\t\tdocsout = r.getResults();\r\n\t\t\t\r\n\t\t\t//docsout.toString();\r\n \r\n\r\n\t\t\t//docsout.get(0).getJSONObject().getJSONObject(\"doc\").getString(\"type\")\r\n\t\t\t//docsout.get(1).getJSONObject().getJSONObject(\"doc\").getJSONArray(\"sentences\").getJSONObject(0).getString(\"callsign\")\r\n\t\t\t \r\n\t\t\tfor (int i = 0; i < docsout.size(); i++)\r\n\t\t\t{\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tJSONObject obj;\r\n\t\t\t\t\r\n\t\t\t\tobj = docsout.get(i).getJSONObject().getJSONObject(\"doc\");\r\n\t\t\t\tif (obj != null) {\r\n\t\t\t\t\tif (obj.containsKey(\"type\")) {\r\n\t\t\t\t\t\tif (obj.getString(\"type\").equals(\"payload_configuration\")) {\r\n\t\t\t\t\t\t\tif (obj.containsKey(\"sentences\")){\t\r\n\t\t\t\t\t\t\t\tJSONArray jar = obj.getJSONArray(\"sentences\");\r\n\t\t\t\t\t\t\t\tfor (int j = 0; j < jar.size(); j++){\r\n\t\t\t\t\t\t\t\t\tif (jar.getJSONObject(j).containsKey(\"callsign\")){\r\n\t\t\t\t\t\t\t\t\t\tString call = jar.getJSONObject(j).getString(\"callsign\");\r\n\t\t\t\t\t\t\t\t\t\tif (!flight_configs.containsKey(call.toUpperCase()))\r\n\t\t\t\t\t\t\t\t\t\t\tflight_configs.put(call.toUpperCase(), docsout.get(i).getId());\r\n\t\t\t\t\t\t\t\t\t\tif (obj.containsKey(\"_id\"))\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\tpayload_configs.put(call.toUpperCase(),obj.getString(\"_id\"));\r\n\t\t\t\t\t\t\t\t\t}\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\t\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\t\r\n\t//TODO: if flight doc exists, query that view instead\r\n\tprivate boolean getPayloadDataSince(long timestampStart, long timestampStop, int limit, String payloadID, String callsign)\r\n\t{\r\n\t\tdouble prevAltitude = -99999999;\r\n\t\tdouble maxAltitude = -99999999;\r\n\t\t long prevtime = -1;\r\n\t\ttry\r\n\t\t{\r\n\r\n\t\t\t//open DB connection\r\n\t\t\tif (s == null)\r\n\t\t\t{\r\n\t\t\t\t s = new Session(_habitat_url,80);\r\n\t\t\t\t db = s.getDatabase(_habitat_db);// + \"/_design/payload_telemetry/_update/add_listener\");\r\n\t\t\t}\r\n\t\t\telse if (db == null)\r\n\t\t\t\tdb = s.getDatabase(_habitat_db);\r\n\r\n\t\t\t View v = new View(\"payload_telemetry/payload_time\");\r\n\r\n\t\t\t long starttime;\r\n\t\t\t if (timestampStart > 0)\r\n\t\t\t\t starttime = timestampStart;\r\n\t\t\t else\r\n\t\t\t\t starttime = (System.currentTimeMillis() / 1000L)-_prev_query_time;\r\n\t\t\t \r\n\t\t\t v.setStartKey(\"[%22\" + payloadID + \"%22,\" +Long.toString(starttime) + \"]\");\r\n\t\t\t v.setEndKey(\"[%22\" + payloadID + \"%22,\" +Long.toString(timestampStop)+ \"]\");\r\n\r\n\t\t\t v.setWithDocs(true);\r\n\t\t\t v.setLimit(limit);\r\n\r\n\r\n\t\t\t System.out.println(\"DEBUG: DATABASE GOT QUERY\");\r\n\t\t\t \r\n\t\t\t TreeMap<Long,Telemetry_string> out = new TreeMap<Long,Telemetry_string>();\r\n\t\t\t \r\n\t\t\t JsonFactory fac = new JsonFactory();\r\n\t\t\t InputStream is = db.view_dont_parse(v);\r\n\t\t\t long lasttime = 0;\r\n\t\t\t \r\n\t\t\t if (is != null)\r\n\t\t\t {\r\n\t\t\t\t \r\n\t\t\t\t JsonParser jp = fac.createJsonParser(is);\r\n\r\n\t\t\t\t String str,str1;\r\n\t\t\t\t boolean gotkey = false;\r\n\t\t\t\t boolean keypt1 = false;\r\n\t\t\t\t \r\n\t\t\t\t \r\n\t\t\t\t TelemetryConfig tc = null;\r\n\t\t\t\t if (telem_configs.containsKey(callsign))\r\n\t\t\t\t {\r\n\t\t\t\t\t tc = telem_configs.get(callsign);\r\n\t\t\t\t }\r\n\t\t\t\t \r\n\t\t\t\twhile(jp.nextToken() != null )// || (jp.getCurrentLocation().getCharOffset() < body.length()-50)) && nullcount < 20) //100000 > out.size())\r\n\t\t\t\t {\r\n\t\t\t\t\t//jp.nextToken();\r\n\t\r\n\t\t\t\t\tstr = jp.getCurrentName();\r\n\t\t\t\t\tstr1 = jp.getText();\r\n\t\t\t\t\tif (str == \"key\" && str1 == \"[\")\r\n\t\t\t\t\t\tgotkey = true;\r\n\t\t\t\t\telse if (gotkey){\r\n\t\t\t\t\t\tkeypt1 = true;\r\n\t\t\t\t\t\tgotkey = false;\r\n\t\t\t\t\t} else if (keypt1) {\r\n\t\t\t\t\t\tkeypt1 = false;\r\n\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\tlasttime = Long.parseLong(str1); }\t\t\t\t\t\r\n\t\t\t\t\t\tcatch (NumberFormatException e) {\r\n\t\t\t\t\t\t\tSystem.out.println(\"ERROR PARSING - NUMBER FORMAT EXCEPTION!!!\"); }\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (str != null && str1 != null)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t if (str.equals(\"_sentence\") && !str1.equals(\"_sentence\")){\r\n\t\t\t\t\t\t Telemetry_string ts = new Telemetry_string(str1,lasttime, tc);\r\n\t\t\t\t\t\t if (!ts.isZeroGPS() && ts.time != null) {\r\n\t\t\t\t\t\t\t if (out.size() > 0){\r\n\t\t\t\t\t\t\t\t if (out.lastEntry().getValue().coords.alt_valid) {\r\n\t\t\t\t\t\t\t\t\t prevAltitude = out.lastEntry().getValue().coords.altitude;\t\t\t\t\t\t\t\t\t \r\n\t\t\t\t\t\t\t\t\t prevtime = out.lastEntry().getValue().time.getTime();\r\n\t\t\t\t\t\t\t\t }\r\n\t\t\t\t\t\t\t }\r\n\t\t\t\t\t\t\t out.put(new Long(ts.time.getTime()),ts); \t\t\r\n\t\t\t\t\t\t\t if (ts.coords.alt_valid)\r\n\t\t\t\t\t\t\t\t maxAltitude = Math.max(ts.coords.altitude, maxAltitude);\r\n\t\t\t\t\t\t }\r\n\t\t\t\t\t }\r\n\t\t\t\t\t \r\n\t\t\t\t\t \t//nullcount = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t//else\r\n\t\t\t\t\t//\tnullcount++;\r\n\t\t\t\t }\r\n\t\t\t\tjp.close();\r\n\t\t\t\tis.close();\r\n\t\t\t\t\r\n\t\t\t }\r\n\t\t\ts.clearCouchResponse();\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tSystem.out.println(\"DEBUG: DATABASE PROCESSING DONE\");\r\n\t\t\t\r\n\t\t\tAscentRate as = new AscentRate();\r\n\t\t\t\r\n\t\t\tif (out.size() >= 2 && prevAltitude > -9999){\r\n\t\t\t\tas = new AscentRate();\r\n\t\t\t\tas.addData(prevtime, prevAltitude);\r\n\t\t\t\t if (out.lastEntry().getValue().coords.alt_valid) {\r\n\t\t\t\t\t as.addData(out.lastEntry().getValue().time.getTime(),\r\n\t\t\t\t\t\t\t out.lastEntry().getValue().coords.altitude);\r\n\r\n\t\t\t\t }\r\n\t\t\t\t else\r\n\t\t\t\t\t as = new AscentRate();\r\n\t\t\t}\r\n\t\t\tlasttime += 1000;\r\n\t\t\tif (lasttime >= timestampStart && lasttime <= timestampStop)\r\n\t\t\t\tfireDataReceived(out,true,callsign,timestampStart, lasttime,as,maxAltitude); \r\n\t\t\telse\r\n\t\t\t\tfireDataReceived(out,true,callsign,timestampStart, timestampStop,as,maxAltitude); \r\n\t\t\t\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\t\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\tfireDataReceived(null,false,e.toString(),timestampStart, timestampStop,null,-99999999);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void getActivePayloads()\r\n\t{\r\n\t\t\r\n\t\ttry\r\n\t\t{\r\n\t\t\t//open DB connection\r\n\t\t\tif (s == null)\r\n\t\t\t{\r\n\t\t\t\t s = new Session(_habitat_url,80);\r\n\t\t\t\t db = s.getDatabase(_habitat_db);// + \"/_design/payload_telemetry/_update/add_listener\");\r\n\t\t\t}\r\n\t\t\telse if (db == null)\r\n\t\t\t\tdb = s.getDatabase(_habitat_db);\r\n\t\t\t\r\n\t\t\t List<Document> foodoc;\r\n\t\t\t View v = new View(\"payload_telemetry/time\");\r\n\t\r\n\t\t\t v.setStartKey(Long.toString((System.currentTimeMillis() / 1000L)-_prev_query_time));\r\n\t\t\t v.setWithDocs(true);\r\n\t\t\t v.setLimit(40);\r\n\r\n\t\t\t ViewResults r = db.view(v);\r\n\t\t\t foodoc = r.getResults();\r\n\t\t\t// foodoc = db.view(v).getResults();\r\n\t\t\tfoodoc.toString();\r\n\t\t\t//((JSONObject)((JSONObject)foodoc.get(1).getJSONObject().get(\"doc\")).get(\"data\")).get(\"payload\")\r\n\t\t\t\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void upload_payload_telem(Telemetry_string input)\r\n\t{\r\n\t\tboolean added=false;\t\t\r\n\t\tadded=out_buff.offer(input);\t\r\n\r\n\t\tif (added)\r\n\t\t{\r\n\t\t\t_operations.offer(new QueueItem(0,1));\r\n\t\t\tStartThread();\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate synchronized void StartThread()\r\n\t{\r\n\t\tif (sdThread == null)\r\n\t\t{\r\n\t\t\tsdThread = new SendThread();\r\n\t\t\tsdThread.start();\r\n\t\t}\r\n\t\telse if (!sdThread.isAlive())\t\t\t\r\n\t\t{\r\n\t\t\tsdThread = new SendThread();\r\n\t\t\tsdThread.start();\r\n\t\t}\r\n\t}\r\n\r\n\t\r\n\tprivate boolean _update_chasecar()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\t//open DB connection\r\n\t\t\tif (s == null)\r\n\t\t\t{\r\n\t\t\t\t s = new Session(_habitat_url,80);\r\n\t\t\t\t db = s.getDatabase(_habitat_db);// + \"/_design/payload_telemetry/_update/add_listener\");\r\n\t\t\t}\r\n\t\t\telse if (db == null)\r\n\t\t\t\tdb = s.getDatabase(_habitat_db);\r\n\t\t\t\r\n\t\t\tif (_listener_info != null)\r\n\t\t\t{\r\n\t\t\t\tupdate_listener_telem();\r\n\t\t\t\t/*\r\n\t\t\t\tDocument doc = new Document ();\r\n\t\t\t\tDocument doc_info = new Document ();\r\n\t\t\t\t\r\n\t\t\t\t//date uploaded\r\n\t\t\t\tDate time = new Date();\r\n\t\t\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZ\");\r\n\t\t\t\tString t = dateFormat.format(time);\r\n\t\t\t\tt = t.substring(0, t.length()-2) + \":\" + t.substring(t.length()-2, t.length());\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tdoc.put(\"type\", \"listener_telemetry\");\r\n\t\t\t\tdoc.put(\"time_created\", t);\r\n\t\t\t\tdoc.put(\"time_uploaded\", t);\r\n\t\t\t\tdoc_info.put(\"type\", \"listener_information\");\r\n\t\t\t\tdoc_info.put(\"time_created\", t);\r\n\t\t\t\tdoc_info.put(\"time_uploaded\", t);\r\n\t\t\t\t\r\n\t\t\t\tJSONObject client = new JSONObject();\r\n\t\t\t\tJSONObject l_info = new JSONObject();\r\n\t\t\t\tclient.put(\"device\", device);\r\n\t\t\t\tclient.put(\"device_software\", device_software);\r\n\t\t\t\tclient.put(\"application\", application);\r\n\t\t\t\tclient.put(\"application_version\", application_version);\r\n\t\t\t\tl_info.put(\"callsign\", _listener_info.CallSign());\r\n\t\t\t\t\r\n\t\t\t\tJSONObject data = _listener_info.getJSONDataField();\r\n\t\t\t\tdata.put(\"client\", client);\r\n\t\t\t\t\t\t\r\n\t\t\t\tdoc.put(\"data\", data);\r\n\t\t\t\t\r\n\t\t\t\tdoc_info.put(\"data\",l_info);\r\n\t\t\t\t\r\n\t\t\t\tString sha = _listener_info.toSha256();\r\n\t\t\t\tString sha_info = _listener_info.toSha256();\r\n\t\t\t\t\r\n\t\t\t\tdb.saveDocument(doc,sha);\t\r\n\t\t\t\tCouchResponse cr = s.getLastResponse();\r\n\t\t\t\tSystem.out.println(cr);\t\t\t\t\r\n\t\t\t\tif (cr.isOk())\r\n\t\t\t\t\t_listener_telem_UUID = sha;\t\t\r\n\t\t\t\t\r\n\t\t\t\tdb.saveDocument(doc_info,sha_info);\t\r\n\t\t\t\tcr = s.getLastResponse();\r\n\t\t\t\tSystem.out.println(cr);\t\t\t\t\r\n\t\t\t\tif (cr.isOk())\r\n\t\t\t\t\t_listener_info_UUID = sha_info;\t\r\n\t\t\t\t*/\r\n\t\t\t}\t\t\t\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate boolean _upload(Telemetry_string input)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\t//open DB connection\r\n\t\t\tif (s == null)\r\n\t\t\t{\r\n\t\t\t\t s = new Session(_habitat_url,80);\r\n\t\t\t\t db = s.getDatabase(_habitat_db);// + \"/_design/payload_telemetry/_update/add_listener\");\r\n\t\t\t}\r\n\t\t\telse if (db == null)\r\n\t\t\t\tdb = s.getDatabase(_habitat_db);\r\n\t\t\t\r\n\t\t\tif (_listener_info != null)\r\n\t\t\t{\r\n\t\t\t\tif (_listener_info.data_changed_info())\r\n\t\t\t\t\tupdate_listener_info();\r\n\t\t\t\t\r\n\t\t\t\tif (_listener_info.data_changed_telem()) //upload listeners location\r\n\t\t\t\t{\r\n\t\t\t\t\tupdate_listener_telem();\r\n\t\t\t\t\t/*\r\n\t\t\t\t\tDocument doc = new Document ();\r\n\t\t\t\t\t\r\n\t\t\t\t\t//date uploaded\r\n\t\t\t\t\tDate time = new Date();\r\n\t\t\t\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZ\");\r\n\t\t\t\t\tString t = dateFormat.format(time);\r\n\t\t\t\t\tt = t.substring(0, t.length()-2) + \":\" + t.substring(t.length()-2, t.length());\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tdoc.put(\"type\", \"listener_telemetry\");\r\n\t\t\t\t\tdoc.put(\"time_created\", t);\r\n\t\t\t\t\tdoc.put(\"time_uploaded\", t);\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tJSONObject client = new JSONObject();\r\n\t\t\t\t\tclient.put(\"device\", device);\r\n\t\t\t\t\tclient.put(\"device_software\", device_software);\r\n\t\t\t\t\tclient.put(\"application\", application);\r\n\t\t\t\t\tclient.put(\"application_version\", application_version);\r\n\t\t\t\t\t\r\n\t\t\t\t\tJSONObject data = _listener_info.getJSONDataField();\r\n\t\t\t\t\tdata.put(\"client\", client);\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\tdoc.put(\"data\", data);\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tString sha = _listener_info.toSha256(); \r\n\t\t\t\t\t\r\n\t\t\t\t\tdb.saveDocument(doc,sha);\r\n\t\t\t\t\tCouchResponse cr = s.getLastResponse();\r\n\t\t\t\t\tSystem.out.println(cr);\r\n\t\t\t\t\tif (cr.isOk())\r\n\t\t\t\t\t\t_listener_telem_UUID = sha;\r\n\t\t\t\t\t*/\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\tDocument doc = new Document();\r\n\t\t\tJSONObject data = new JSONObject();\r\n\t\t\tJSONObject receivers = new JSONObject();\r\n\t\t\tJSONObject receiver = new JSONObject();\r\n\t\t\t\r\n\t\t\t//date uploaded\r\n\t\t\tDate time = new Date();\r\n\t\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZ\");\r\n\t\t\tString t = dateFormat.format(time);\r\n\t\t\tt = t.substring(0, t.length()-2) + \":\" + t.substring(t.length()-2, t.length());\r\n\t\t\t\r\n\t\t\tString str64 = input.raw_64_str();\r\n\t\t\t\r\n\t\t\tdata.put(\"_raw\", str64);\r\n\t\t\treceiver.put(\"time_created\", input.doc_time_created);\r\n\t\t\treceiver.put(\"time_uploaded\",t);\r\n\t\t\tif (input.habitat_metadata != null)\r\n\t\t\t\treceiver.putAll(input.habitat_metadata);\r\n\t\t\tif (_listener_telem_UUID != \"\")\r\n\t\t\t\treceiver.put(\"latest_listener_telemtry\",_listener_telem_UUID);\r\n\t\t\tif (_listener_info_UUID != \"\")\r\n\t\t\t\treceiver.put(\"latest_listener_information\",_listener_info_UUID);\r\n\t\t\treceivers.put(_listener_info.CallSign(),receiver);\r\n\t\t\t\r\n\t\t\r\n\t\t\tdoc.put(\"type\",\"payload_telemetry\");\r\n\t\t\tdoc.put(\"data\",data.toString());\r\n\t\t\tdoc.put(\"receivers\",receivers.toString());\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tString sha = input.toSha256();\r\n\t\t\r\n\t\t\t//System.out.println(doc.toString());\r\n\t\t\t\r\n\t\t\tdb.saveDocument(doc,sha); \t\t\t\t//try to upload as only listener\r\n\t\t\tCouchResponse cr = s.getLastResponse(); //see if successful\r\n\t\t\t\r\n\t\t\tif (cr.isOk())\r\n\t\t\t{\t\t//addition went well, but get the payload config ID if not already\r\n\t\t\t\tif (payload_configs.containsKey(input.callsign))\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t\r\n\t\t\t\t//if not already existing, query the now parsed document\r\n\t\t\t\tDocument result = db.getDocument(sha);\r\n\t\t\t\t\r\n\t\t\t\tif (result != null)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (result.getJSONObject().containsKey(\"data\"))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tJSONObject objdata = result.getJSONObject().getJSONObject(\"data\");\r\n\t\t\t\t\t\tif (objdata.containsKey(\"_parsed\"))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tobjdata = objdata.getJSONObject(\"_parsed\");\r\n\t\t\t\t\t\t\tif (objdata.containsKey(\"payload_configuration\"))\r\n\t\t\t\t\t\t\t\tpayload_configs.put(input.callsign, objdata.getString(\"payload_configuration\"));\r\n\t\t\t\t\t\t\tif (objdata.containsKey(\"flight\"))\r\n\t\t\t\t\t\t\t\tflight_configs.put(input.callsign, objdata.getString(\"flight\"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\treturn true;\t\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (!cr.getErrorId().equals(\"conflict\"))\r\n\t\t\t{\r\n\t\t\t\t//throw error but continue\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tDocument result = db.getDocument(sha);\r\n\t\t\t\r\n\t\t\t//if payload configs does not contain the payload config ID, get it\r\n\t\t\tif (!payload_configs.containsKey(input.callsign))\r\n\t\t\t{\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tif (result != null)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (result.getJSONObject().containsKey(\"data\"))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tJSONObject objdata = (JSONObject)(result.getJSONObject().get(\"data\"));\r\n\t\t\t\t\t\tif (objdata.containsKey(\"_parsed\"))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tJSONObject obparse = (JSONObject)objdata.get(\"_parsed\");\r\n\t\t\t\t\t\t\tif (obparse.containsKey(\"payload_configuration\"))\r\n\t\t\t\t\t\t\t\tpayload_configs.put(input.callsign, obparse.get(\"payload_configuration\").toString());\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tint its = 0;\r\n\t\t\t//start of main loop\r\n\t\t\twhile(its < 30)\r\n\t\t\t{\r\n\t\t\t\tits++;\r\n\r\n\t\t\t\tif (result == null) \r\n\t\t\t\t\treturn false; //somethings gone wrong\r\n\t\t\t\t\r\n\t\t\t\t//instead try to append document\r\n\t\r\n\t\t\t\tJSONObject existing_receivers = new JSONObject();\r\n\t\t\t\t\r\n\t\t\t\tJSONObject _dat_a = (JSONObject) result.get(\"data\");\r\n\t\t\t\tif (_dat_a == null)\r\n\t\t\t\t{\r\n\t\t\t\t\tSystem.out.println(\"DID NOT PARSE DATA SECTION\");\r\n\t\t\t\t}\r\n\t\t\t\t/*\r\n\t\t\t\tdouble gf = 4.3600000000000003197;\r\n\t\t\t\tdouble ss = 0.0000000000000003197;\r\n\t\t\t\tdouble p = gf - 4.36;\r\n\t\t\t\tSystem.out.println(_dat_a.get(\"battery\") + \" \" + gf + \" \" + ss + \" \" + p); */\r\n\t\t\t\tif (!result.containsKey(\"receivers\"))\r\n\t\t\t\t\treturn false; //somethings gone wrong\r\n\t\t\t\t\r\n\t\t\t\texisting_receivers = (JSONObject) result.remove(\"receivers\");\r\n\t\t\t\texisting_receivers.put(_listener_info.CallSign(),receiver);\r\n\t\t\t\tresult.put(\"receivers\", existing_receivers);\r\n\t\t\t\t\r\n\t\t\t\tdb.saveDocument(result,sha);\r\n\t\t\t\tcr = s.getLastResponse(); \r\n\t\t\t\t//System.out.println(cr.statusCode);\r\n\t\t\t\tif (cr.isOk())\r\n\t\t\t\t\treturn true;\r\n\t\t\t\tif (cr.getErrorId() == null)\r\n\t\t\t\t{\r\n\t\t\t\t\t//throw error but continue\r\n\t\t\t\t\tits += 9;\r\n\t\t\t\t}\r\n\t\t\t\telse if (!cr.getErrorId().equals(\"conflict\"))\r\n\t\t\t\t{\r\n\t\t\t\t\t//throw error but continue\r\n\t\t\t\t\tits += 9;\r\n\t\t\t\t}\r\n\t\t\t\t//get document for next run through\r\n\t\t\t\tresult = db.getDocument(sha);\r\n\t\t\t}\r\n\t\t\t//System.out.println(cr.isOk() + \" \" + cr.getErrorId() + \" \" + cr.getErrorReason());\r\n\t\t\t//System.out.println(s.getLastResponse());\r\n\t\t\t\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\tprotected void fireDataReceived(TreeMap<Long, Telemetry_string> out, boolean success, String callsign, long startTime, long endTime, AscentRate as, double maxAltitude)\r\n\t{\r\n\t\tfor (int i = 0; i < _listeners.size(); i++)\r\n\t\t{\r\n\t\t\t_listeners.get(i).HabitatRx(out, success, callsign, startTime, endTime,as,maxAltitude);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void addStringRecievedListener(HabitatRxEvent listener)\r\n\t{\t\r\n\t\t_listeners.add(listener);\r\n\t}\r\n\t\r\n\tclass SendThread extends Thread\r\n\t{\r\n\t\t \r\n\t\t public void run()\r\n\t\t {\r\n\t\t\t boolean buff_empty = false;\r\n\t\t\t while(!buff_empty)\r\n\t\t\t {\r\n\t\t\t\t\r\n\t\t\t\t \r\n\t\t\t\t if (!_operations.isEmpty())\r\n\t\t\t\t {\r\n\t\t\t\t\t QueueItem qi = _operations.poll();\r\n\t\t\t\t\t if (qi != null)\r\n\t\t\t\t\t {\r\n\t\t\t\t\t\t if (qi.type == 0)\r\n\t\t\t\t\t\t {\t\t\t//upload telem\r\n\t\t\t\t\t\t\t \r\n\t\t\t\t\t\t\t Telemetry_string tosend = out_buff.peek();\r\n\t\t\t\t\t\t\t boolean res = true;\r\n\t\t\t\t\t\t\t if (tosend != null)\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t res = _upload(tosend); //now we have some telem, lets send it\t\t\t\t\t\t\t \r\n\t\t\t\t\t\t\t if (!res)\r\n\t\t\t\t\t\t\t\t System.out.println(\"UPLOAD FAILED :(\");\r\n\t\t\t\t\t\t\t else //success, remove data from queue\r\n\t\t\t\t\t\t\t\t out_buff.poll();\r\n\t\t\t\t\t\t }\r\n\t\t\t\t\t\t else if (qi.type == 1)\r\n\t\t\t\t\t\t {\t\t\t//get data\r\n\t\t\t\t\t\t\t String id = resolvePayloadID(qi.callsign);\r\n\t\t\t\t\t\t\t if (!telem_configs.containsKey(qi.callsign.toUpperCase()))\r\n\t\t\t\t\t\t\t\t queryPayloadConfig(id);\r\n\t\t\t\t\t\t\t if (id != null)\r\n\t\t\t\t\t\t\t\t getPayloadDataSince(qi.startTime, qi.stopTime,qi.count, id, qi.callsign);\r\n\t\t\t\t\t\t }\r\n\t\t\t\t\t\t else if (qi.type == 2) //update list of active flights\r\n\t\t\t\t\t\t {\r\n\t\t\t\t\t\t\t _queried_current_flights = queryActiveFlights();\r\n\t\t\t\t\t\t }\r\n\t\t\t\t\t\t else //upload chasecar\r\n\t\t\t\t\t\t {\r\n\t\t\t\t\t\t\t _update_chasecar();\r\n\t\t\t\t\t\t }\r\n\t\t\t\t\t }\r\n\t\t\t\t\t else\r\n\t\t\t\t\t\t buff_empty = true;\r\n\t\t\t\t }\r\n\t\t\t\t else\r\n\t\t\t\t\t buff_empty = true;\r\n\t\t\t\t \r\n\t\t\t }\r\n\t\t\t\r\n\t\t\t //deal with any items in the send queue which are left over\r\n\t\t\t buff_empty = false;\r\n\t\t\t while(!buff_empty)\r\n\t\t\t {\r\n\t\t\t\t \r\n\t\t\t\t if (out_buff.isEmpty())\r\n\t\t\t\t {\r\n\t\t\t\t\t buff_empty = true;\r\n\t\t\t\t }\r\n\t\t\t\t else\r\n\t\t\t\t {\r\n\t\t\t\t\t Telemetry_string tosend = out_buff.poll();\r\n\r\n\t\t\t\t\t boolean res = true;\r\n\t\t\t\t\t if (tosend == null)\r\n\t\t\t\t\t\t buff_empty = true;\r\n\t\t\t\t\t else\r\n\t\t\t\t\t\t res = _upload(tosend); //now we have some telem, lets send it\r\n\t\t\t\t\t \r\n\t\t\t\t\t if (!res)\r\n\t\t\t\t\t\t System.out.println(\"UPLOAD FAILED :(\");\r\n\t\t\t\t }\r\n\t\t\t }\r\n\t\t }\r\n\t}\r\n\t\r\n\tprivate boolean update_listener_telem()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\tDocument doc = new Document ();\r\n\t\t\tDocument doc_info = new Document ();\r\n\t\t\t\r\n\t\t\t//date uploaded\r\n\t\t\tDate time = new Date();\r\n\t\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZ\");\r\n\t\t\tString t = dateFormat.format(time);\r\n\t\t\tt = t.substring(0, t.length()-2) + \":\" + t.substring(t.length()-2, t.length());\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tdoc.put(\"type\", \"listener_telemetry\");\r\n\t\t\tdoc.put(\"time_created\", t);\r\n\t\t\tdoc.put(\"time_uploaded\", t);\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tJSONObject client = new JSONObject();\r\n\t\t\tJSONObject l_info = new JSONObject();\r\n\t\t\tclient.put(\"device\", device);\r\n\t\t\tclient.put(\"device_software\", device_software);\r\n\t\t\tclient.put(\"application\", application);\r\n\t\t\tclient.put(\"application_version\", application_version);\r\n\r\n\t\t\t\r\n\t\t\tJSONObject data = _listener_info.getJSONDataFieldTelem();\r\n\t\t\tdata.put(\"client\", client);\r\n\t\t\t\t\t\r\n\t\t\tdoc.put(\"data\", data);\r\n\t\t\t\r\n\t\t\tdoc_info.put(\"data\",l_info);\r\n\t\t\t\r\n\t\t\tString sha = _listener_info.toSha256();\r\n\r\n\t\t\t\r\n\t\t\tdb.saveDocument(doc,sha);\t\r\n\t\t\tCouchResponse cr = s.getLastResponse();\r\n\t\t\tSystem.out.println(cr);\t\t\t\t\r\n\t\t\tif (cr.isOk())\r\n\t\t\t\t_listener_telem_UUID = sha;\t\t\r\n\t\t\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tprivate boolean update_listener_info()\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\r\n\t\t\tDocument doc_info = new Document ();\r\n\t\t\t\r\n\t\t\t//date uploaded\r\n\t\t\tDate time = new Date();\r\n\t\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZ\");\r\n\t\t\tString t = dateFormat.format(time);\r\n\t\t\tt = t.substring(0, t.length()-2) + \":\" + t.substring(t.length()-2, t.length());\r\n\t\t\t\r\n\r\n\t\t\tdoc_info.put(\"type\", \"listener_information\");\r\n\t\t\tdoc_info.put(\"time_created\", t);\r\n\t\t\tdoc_info.put(\"time_uploaded\", t);\t\r\n\t\t\t\r\n\t\t\tdoc_info.put(\"data\",_listener_info.getJSONDataFieldInfo());\r\n\t\t\t\r\n\t\t\tString sha_info = toSha256(doc_info.toString());\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\tdb.saveDocument(doc_info,sha_info);\t\r\n\t\t\tCouchResponse cr = s.getLastResponse();\r\n\t\t\tSystem.out.println(cr);\t\t\t\t\r\n\t\t\tif (cr.isOk())\r\n\t\t\t\t_listener_info_UUID = sha_info;\t\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tpublic boolean newTelemConfigs()\r\n\t{\r\n\t\treturn _newTelemConfigs;\r\n\t}\r\n\t\r\n\tpublic ConcurrentHashMap<String,TelemetryConfig> getTelemConfigs()\r\n\t{\r\n\t\t_newTelemConfigs = false;\r\n\t\treturn telem_configs;\r\n\t}\r\n\t\r\n\tclass QueueItem\r\n\t{\r\n\t\tpublic int type;\t\t\t\t//0: upload payload, 1: get payload telem, 2: update active flight list, 3: update chase car\r\n\t\tpublic String callsign = \"\";\r\n\t\tpublic long startTime = 0;\r\n\t\tpublic long stopTime = 0;\r\n\t\tpublic int count = 0;\r\n\t\tpublic QueueItem(int _type,int _count)\r\n\t\t{\r\n\t\t\ttype = _type;\r\n\t\t\tcount = _count;\r\n\t\t}\r\n\t\tpublic QueueItem(int _type, String _callsign, long _startTime, long _stopTime, int _count)\r\n\t\t{\r\n\t\t\ttype = _type;\r\n\t\t\tcallsign = _callsign;\r\n\t\t\tstartTime = _startTime;\r\n\t\t\tstopTime = _stopTime;\r\n\t\t\tcount = _count;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static String toSha256(String str)\r\n\t{\r\n\r\n\t\tbyte [] enc = Base64.encodeBase64(str.getBytes());\r\n\t\tbyte[] sha = null;\r\n\t\t\r\n\t\tMessageDigest md;\r\n\t\ttry {\r\n\t\t\tmd = MessageDigest.getInstance(\"SHA-256\");\r\n\t\t\tmd.update(enc); \r\n\t\t\tsha = md.digest();\r\n\t\t} catch (NoSuchAlgorithmException e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\t\r\n\t\treturn bytesToHexStr(sha);\r\n\t}\r\n\t\r\n\t//ref: http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java\r\n\tpublic static String bytesToHexStr(byte[] bytes) {\r\n\t final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};\r\n\t char[] hexChars = new char[bytes.length * 2];\r\n\t int v;\r\n\t for ( int j = 0; j < bytes.length; j++ ) {\r\n\t v = bytes[j] & 0xFF;\r\n\t hexChars[j * 2] = hexArray[v >>> 4];\r\n\t hexChars[j * 2 + 1] = hexArray[v & 0x0F];\r\n\t }\r\n\t return new String(hexChars);\r\n\t}\r\n}\r",
"public class Listener {\r\n\r\n\tprivate String _callsign;\r\n\tprivate Gps_coordinate _coords;\r\n\tprivate float _speed = 0.0f;\r\n\tprivate boolean _speedValid = false;\r\n\tprivate Date _time_created;\r\n\tprivate boolean _changed_telem;\r\n\tprivate boolean _changed_info;\r\n\tprivate boolean _isChase = false;\r\n\tprivate String _radio = \"\";\r\n\tprivate String _antenna = \"\";\r\n\t\r\n\tpublic Listener(String callsign, boolean isChase) {\r\n\t\t_callsign = callsign;\r\n\t\t_coords = new Gps_coordinate();\r\n\t\t_time_created = new Date();\r\n\t\t_changed_info = true;\r\n\t\t_changed_telem = true;\r\n\t\t_isChase = isChase;\r\n\t}\r\n\t\r\n\tpublic Listener(String callsign, Gps_coordinate coords, boolean isChase) {\r\n\t\t// TODO Auto-generated constructor stub\r\n\t\t_callsign = callsign;\r\n\t\t_coords = coords;\r\n\t\t_time_created = new Date();\r\n\t\t_changed_info = true;\r\n\t\t_changed_telem = true;\r\n\t\t_isChase = isChase;\r\n\t}\r\n\tpublic Listener(String callsign, Gps_coordinate coords, float speed, boolean isChase) {\r\n\t\t// TODO Auto-generated constructor stub\r\n\t\t_callsign = callsign;\r\n\t\t_coords = coords;\r\n\t\t_time_created = new Date();\r\n\t\t_changed_info = true;\r\n\t\t_changed_telem = true;\r\n\t\t_isChase = isChase;\r\n\t\t_speed = speed;\r\n\t\t_speedValid = true;\r\n\t}\r\n\r\n\tpublic JSONObject getJSONDataFieldTelem()\r\n\t{\r\n\t\t_changed_telem = false;\r\n\t\t\r\n\t\tJSONObject data = new JSONObject();\r\n\t\ttry\r\n\t\t{\r\n\t\t\tdata.put(\"callsign\", _callsign);\r\n\t\t\tif (_coords.latlong_valid){\r\n\t\t\t\tdata.put(\"latitude\", _coords.latitude);\r\n\t\t\t\tdata.put(\"longitude\", _coords.longitude);\r\n\t\t\t\tif (_isChase)\r\n\t\t\t\t\tdata.put(\"chase\", true);\r\n\t\t\t}\r\n\t\t\tif (_coords.alt_valid)\r\n\t\t\t\tdata.put(\"altitude\",_coords.altitude);\r\n\t\t\tif (_speedValid)\r\n\t\t\t\tdata.put(\"speed\",_speed);\r\n\t\t\t\r\n\t\t\t\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\treturn data;\r\n\t}\r\n\t\r\n\tpublic JSONObject getJSONDataFieldInfo()\r\n\t{\r\n\t\t_changed_info = false;\r\n\t\t\r\n\t\tJSONObject data = new JSONObject();\r\n\t\ttry\r\n\t\t{\r\n\t\t\tdata.put(\"callsign\", _callsign);\r\n\t\t\tdata.put(\"antenna\", _antenna);\r\n\t\t\tdata.put(\"radio\", _radio);\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\treturn data;\r\n\t}\r\n\t\r\n\tpublic String CallSign()\r\n\t{\r\n\t\treturn _callsign;\r\n\t}\r\n\tpublic String getRadio()\r\n\t{\r\n\t\treturn _radio;\r\n\t}\r\n\tpublic String getAntenna()\r\n\t{\r\n\t\treturn _antenna;\r\n\t}\r\n\t\r\n\tpublic boolean data_changed_telem()\r\n\t{\r\n\t\treturn _changed_telem;\r\n\t}\r\n\t\r\n\tpublic boolean data_changed_info()\r\n\t{\r\n\t\treturn _changed_info;\r\n\t}\r\n\t\r\n\tpublic void SetCallSign(String callsign)\r\n\t{\r\n\t\t_time_created = new Date();\r\n\t\t_callsign = callsign;\r\n\t\t_changed_telem = true;\r\n\t\t_changed_info = true;\r\n\t}\r\n\t\r\n\tpublic Gps_coordinate Coordinates()\r\n\t{\r\n\t\treturn _coords;\r\n\t}\r\n\t\r\n\tpublic void set_Gps_coordinates(Gps_coordinate coords)\r\n\t{\r\n\t\t_time_created = new Date();\r\n\t\t_coords = coords;\r\n\t\t_changed_telem = true;\r\n\t}\r\n\t\r\n\tpublic void setRadio(String in)\r\n\t{\r\n\t\t_radio = in;\r\n\t\t_changed_info = true;\r\n\t}\r\n\t\r\n\tpublic void setAntenna(String in)\r\n\t{\r\n\t\t_antenna = in;\r\n\t\t_changed_info = true;\r\n\t}\r\n\t\r\n\tpublic String get_time_created()\r\n\t{\r\n\t\t\r\n\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZ\");\r\n\t\tString t = dateFormat.format(_time_created);\r\n\t\tt = t.substring(0, t.length()-2) + \":\" + t.substring(t.length()-2, t.length());\r\n\t\treturn t;\r\n\t}\r\n\t\r\n\tpublic String toSha256()\r\n\t{\r\n\t\tString str = _callsign + get_time_created();\r\n\t\tbyte [] enc = Base64.encodeBase64(str.getBytes());\r\n\t\tbyte[] sha = null;\r\n\t\t\r\n\t\tMessageDigest md;\r\n\t\ttry {\r\n\t\t\tmd = MessageDigest.getInstance(\"SHA-256\");\r\n\t\t\tmd.update(enc); \r\n\t\t\tsha = md.digest();\r\n\t\t} catch (NoSuchAlgorithmException e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\t\r\n\t\treturn bytesToHexStr(sha);\r\n\t}\r\n\t\r\n\t//ref: http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java\r\n\t\tpublic static String bytesToHexStr(byte[] bytes) {\r\n\t\t final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};\r\n\t\t char[] hexChars = new char[bytes.length * 2];\r\n\t\t int v;\r\n\t\t for ( int j = 0; j < bytes.length; j++ ) {\r\n\t\t v = bytes[j] & 0xFF;\r\n\t\t hexChars[j * 2] = hexArray[v >>> 4];\r\n\t\t hexChars[j * 2 + 1] = hexArray[v & 0x0F];\r\n\t\t }\r\n\t\t return new String(hexChars);\r\n\t\t}\r\n\t\r\n}\r",
"public interface StringRxEvent extends EventListener\r\n{\r\n\tvoid StringRx(String strrx, boolean checksum);\r\n\tvoid StringRx(byte[] strrx, boolean checksum, int length, int flags, int fixed);\r\n}\r",
"public class fsk_receiver implements StringRxEvent {\r\n\t\r\n\tpublic int FFT_half_len = 512; \r\n private DoubleFFT_1D ft_obj = new DoubleFFT_1D(FFT_half_len*2);\r\n \r\n //int FFT_follow_half_len = 512;\r\n //private DoubleFFT_1D ft_follow = new DoubleFFT_1D(FFT_follow_half_len*2);\r\n \r\n private fsk_demodulator decoder = new fsk_demodulator(1200,1800);\r\n \r\n\r\n ConfidenceCalculator cc = new ConfidenceCalculator(8000);\r\n \r\n private Telemetry_handler telem_hand_7 = new Telemetry_handler();\r\n private Telemetry_handler telem_hand_8 = new Telemetry_handler();\r\n private Telemetry_handler telem_hand_f = new Telemetry_handler();\r\n private Binary_frame_handler telem_hand_bin = \r\n \t\tnew Binary_frame_handler(new boolean[]\r\n \t\t\t\t//{true, false,true, false,true, false,true, false,true, false,true, false});\r\n \t\t\t\t{true, false, false, true, true, false, true, false, false, true, false, true, false, false, true, false, true, true, true, false, false, true, true, true, false, false, false, true, false, true, true, false});\r\n \t\t\t\t//{true,true,false,false,false,true,false,true,true,false,false});//{true,false,false,false,true,false,false,true,false,false,true,true});\r\n \r\n private String last_sha = \"\";\r\n \r\n public boolean enableFFT = true;\r\n \r\n private moving_average av_shift = new moving_average(10);\r\n \r\n public int search_range_rtty = 14;\r\n\r\n public enum Mode { BINARY, RTTY };\r\n public enum Modulation { FSK, AFSK };\r\n public enum State { INACTIVE, IDLE, FOUND_SIG, BAUD_KNOWN };\r\n \r\n public State current_state = State.INACTIVE;\r\n public Mode current_mode = Mode.RTTY;\r\n public Modulation current_modulation = Modulation.FSK;\r\n public int current_data_bits = 7;\r\n public int current_stop_bits = 1;\r\n public int current_baud = 300;\r\n public boolean auto_rtty_finding = true;\r\n public boolean enable_afc = true;\r\n \r\n public int afc_update_freq = 8000;\r\n private int samples_since_afc = 0;\r\n \r\n public int search_freq = 8000;\r\n private int samples_since_search = 0;\r\n \r\n public int fft_update_freq = 2000;\r\n private int samples_since_fft = 0;\r\n \r\n public int samples_since_last_valid = 0;\r\n\r\n \r\n private double[] _samples;\r\n private double[] _fft;\r\n private boolean _fft_updated = false;\r\n \r\n private int[] _peaklocs;\r\n \r\n private Bits_to_chars bit2char_7 = new Bits_to_chars(7,Bits_to_chars.Method.WAIT_FOR_START_BIT);\r\n private Bits_to_chars bit2char_8 = new Bits_to_chars(8,Bits_to_chars.Method.WAIT_FOR_START_BIT);\r\n private Bits_to_chars bit2char_fixed = new Bits_to_chars(7,2,Bits_to_chars.Method.FIXED_POSITION);\r\n \r\n //used for 'string received' event\r\n protected ArrayList<StringRxEvent> _listeners = new ArrayList<StringRxEvent>();\r\n\r\n\tpublic fsk_receiver() {\r\n\t\t// TODO Auto-generated constructor stub\r\n\t\ttelem_hand_7.addStringRecievedListener(this);\r\n\t\ttelem_hand_8.addStringRecievedListener(this);\r\n\t\ttelem_hand_f.addStringRecievedListener(this);\r\n\t\ttelem_hand_bin.addStringRecievedListener(this);\r\n\t}\r\n\t\r\n\tpublic void addStringRecievedListener(StringRxEvent listener)\r\n\t{\t\r\n\t\t_listeners.add(listener);\r\n\t}\r\n\t\r\n\tprotected void fireStringReceived(String str, boolean checksum)\r\n\t{\r\n\t\tfor (int i = 0; i < _listeners.size(); i++)\r\n\t\t{\r\n\t\t\t_listeners.get(i).StringRx(str,checksum);\r\n\t\t}\r\n\t}\r\n\tprotected void fireStringReceived(byte[] str, boolean checksum, int length, int flags, int fixed)\r\n\t{\r\n\t\tfor (int i = 0; i < _listeners.size(); i++)\r\n\t\t{\r\n\t\t\t_listeners.get(i).StringRx(str,checksum, length, flags, fixed);\r\n\t\t}\r\n\t}\r\n\t\r\n\r\n\t\r\n\tpublic double[] find_fsk(double[] samples)\r\n\t{\r\n\t\t_samples = samples;\r\n\t\t_fft_updated = false;\r\n\t\treturn find_fsk(false);\r\n\t}\r\n\t\r\n\t//note: gives the square of the FFT\r\n\tprivate boolean calcuate_FFT()\r\n\t{\r\n\t\tif (_fft_updated)\r\n\t\t\treturn true;\r\n\t\t\r\n\t\t\r\n\t\tif (_samples.length < FFT_half_len*2)\r\n\t\t\treturn false;\r\n\t\t\r\n\t\t//get 256 (useful) FFT bins\r\n\t\tdouble[] fftar = new double[_samples.length];\r\n\t\tSystem.arraycopy(_samples,0,fftar,0,_samples.length);\r\n\t\tft_obj.realForward(fftar);\r\n\t\t\r\n\t\t_fft = (new double[FFT_half_len]);\r\n\t\t\r\n\t\t//calculate abs(.)\r\n for (int i = 0; i < FFT_half_len; i++)\r\n {\r\n \t_fft[i] = Math.pow(fftar[i*2], 2) + Math.pow(fftar[i*2 +1], 2);\r\n }\r\n \r\n _fft_updated = true;\r\n return true;\r\n\t}\r\n\t\r\n\tprivate double[] find_fsk(boolean update)\r\n\t{\r\n\t\t//returns array where [0] is f1 and [1] is f2\r\n\r\n\t\t\r\n\t\tdouble[] out = new double[] {0,0};\r\n\t\t\r\n\t\t\r\n\t\tif (!calcuate_FFT())\r\n\t\t\treturn out;\r\n\t\t\r\n int windows = 15;\r\n int win_size = (int)FFT_half_len/windows;\r\n \r\n double[][] peak = new double[windows][2];\t//0: loc; 1: val\r\n //int[] peak_loc = new int[windows];\r\n //double[] peak_val = new double[windows];\r\n int peak_count = 0;\r\n \r\n // TODO each peak should be y dB higher than the min in the window (kinda done)\r\n //peak search\r\n double win_min_c=1e20; //current minimum\r\n double win_min_p=1e20;\t //previous minimum\r\n int min_win_cnt = 0;\r\n for (int i = 1; i < FFT_half_len-1; i++)\r\n {\r\n \t//used to get minimum values for 2 windows in advance\r\n \tif (_fft[i] < win_min_c)\r\n \t\twin_min_c = _fft[i];\r\n \tmin_win_cnt++;\r\n \tif (min_win_cnt >= win_size)\r\n \t{\r\n \t\twin_min_p = win_min_c;\r\n \t\twin_min_c = 1e20;\r\n \t\tmin_win_cnt=0;\r\n \t}\r\n \t\r\n \tif ((_fft[i-1] < _fft[i]) && (_fft[i] > _fft[i+1]) && (_fft[i] > win_min_c*10 || _fft[i] > win_min_p*10))\t\t//if found peak\r\n \t{\r\n \t\tif (i < peak[peak_count][0]+win_size) //if another peak in the same window\r\n \t\t{\r\n \t\t\tif (peak[peak_count][1] < _fft[i] )\r\n \t\t\t{\r\n \t\t\t\tpeak[peak_count][0] = i;\r\n \t\t\t\tpeak[peak_count][1] = _fft[i];\r\n \t\t\t}\r\n \t\t}\r\n \t\telse\r\n \t\t{\r\n \t\t\tpeak_count++;\r\n \t\t\t\tpeak[peak_count][0] = i;\r\n \t\t\t\tpeak[peak_count][1] = _fft[i];\r\n \t\t}\r\n \t}\r\n }\r\n _peaklocs = (new int[peak_count]);\r\n for (int i = 0; i < peak_count; i++)\r\n {\r\n \tpeak[peak_count][1] = Math.sqrt(peak[peak_count][1]); //sqrt the peaks\r\n \t_peaklocs[i] = (int)peak[i][0];\t\t\t\t\t//copy to variable to allow for debug access\r\n }\r\n //now have a list of peaks in the fft\r\n //sort peaks by amplitude of peak\r\n \r\n java.util.Arrays.sort(peak, new java.util.Comparator<double[]>() {\r\n \tpublic int compare(double[]a, double[]b) {\r\n \t\treturn (int)(b[1] - a[1]);\r\n \t}\r\n });\r\n \r\n int bb_len = Math.min(2000, _samples.length);\r\n double bb[][] = new double [peak_count][bb_len];\r\n double maxs[] = new double [peak_count];\r\n double mins[] = new double [peak_count];\r\n double means[] = new double [peak_count];\r\n double upthre[] = new double [peak_count];\r\n double lothre[] = new double [peak_count];\r\n \r\n // TODO demod and check in order of highest amplitude to reduce the need to demod every signal\r\n \r\n \r\n \r\n //demodulate at each peak\r\n for (int i = 0; i < peak_count; i++)\r\n {\r\n \t//fir_filter filts = new fir_filter(new double[] {-0.00903981521632955, -0.0176057278961508, -0.0214888217308206, -0.00894080820836387, 0.0281449413985572, 0.0880962336584224, 0.156738932301488, 0.211778824066603, 0.232865400131940, 0.211778824066603, 0.156738932301488, 0.0880962336584224, 0.0281449413985572, -0.00894080820836387, -0.0214888217308206, -0.0176057278961508, -0.00903981521632955});\r\n \t//fir_filter filtc = new fir_filter(new double[] {-0.00903981521632955, -0.0176057278961508, -0.0214888217308206, -0.00894080820836387, 0.0281449413985572, 0.0880962336584224, 0.156738932301488, 0.211778824066603, 0.232865400131940, 0.211778824066603, 0.156738932301488, 0.0880962336584224, 0.0281449413985572, -0.00894080820836387, -0.0214888217308206, -0.0176057278961508, -0.00903981521632955});\r\n \tfir_filter filts = new fir_filter(new double[] {0.0856108043700266,\t0.0887368103506232,\t0.0912267090885950,\t0.0930370874042555,\t0.0941362126682943,\t0.0945047522364111,\t0.0941362126682943,\t0.0930370874042555,\t0.0912267090885950,\t0.0887368103506232,\t0.0856108043700266});\r\n \tfir_filter filtc = new fir_filter(new double[] {0.0856108043700266,\t0.0887368103506232,\t0.0912267090885950,\t0.0930370874042555,\t0.0941362126682943,\t0.0945047522364111,\t0.0941362126682943,\t0.0930370874042555,\t0.0912267090885950,\t0.0887368103506232,\t0.0856108043700266});\r\n\r\n \tdouble lo_phase = 0;\r\n \tdouble freq = ((double)peak[i][0])/((double)(FFT_half_len*2));\r\n \r\n\r\n \tfor (int j = 0; j< bb_len;j++)\r\n \t{\r\n \t\t//multiply, filter, square and add\r\n \t\tbb[i][j] = Math.pow(filts.step(_samples[j] * Math.sin(2*Math.PI*lo_phase)),2) + Math.pow(filtc.step(_samples[j] * Math.cos(2*Math.PI*lo_phase)),2);\r\n\r\n \t\tlo_phase = lo_phase + freq;\r\n \t\tif (j >= 30)\r\n \t\t{\r\n\t \t\t//maxs[i] = Math.max(maxs[i], bb[i][j]);\r\n\t \t\tif (bb[i][j]> maxs[i] && j > 60)\r\n\t \t\t{\r\n\t \t\t\tmaxs[i] = bb[i][j];\r\n\t \t\t}\r\n\t \t\tmins[i] = Math.min(mins[i], bb[i][j]);\r\n\t \t\tmeans[i] = means[i] + bb[i][j];\r\n \t\t}\r\n \t}\r\n \tmeans[i] = means[i] / (bb_len-30);\r\n \tupthre[i] = means[i]*1.2; //(maxs[i]-means[i])*0.3 + means[i];\r\n \tlothre[i] = means[i]*0.8; //-(maxs[i]-means[i])*0.3 + means[i];\r\n }\r\n \r\n // grtty.clearMarkers();\r\n // System.out.println();\r\n // System.out.println();\r\n peak_count=Math.min(4, peak_count);\r\n //iterate through all combinations of peaks to find a signal\r\n for (int i = 0; i < peak_count-1; i++)\r\n {\r\n \tfor (int j=i+1; j< peak_count; j++)\r\n \t{ \t\t\r\n \t\tif ((peak[i][1] > peak[j][1]*.16 ) && (peak[i][1] < peak[j][1]*7 ))\r\n \t\t{\r\n \t\t\tif ((means[i] > mins[j]) && (means[j] > mins[i]))\r\n \t\t\t{\r\n \t\t\t\t\r\n \t\t\t\t//count the number of transitions between the two potential signals\r\n \t\t\t\tint transitionsl = 0;\r\n \t\t\t\tint transitionsh = 0;\r\n \t\t\t\tint highs = 0;\r\n \t\t\t\tboolean last_state = bb[i][40] > bb[j][40];\r\n \t\t\t\tboolean last_state1 = bb[i][40] > bb[j][40];\r\n \t\t\t\tfor (int k = 50; k < bb_len-10; k=k+10)\r\n \t\t\t\t{\r\n \t\t\t\t\t//Transition checker\r\n \t\t\t\t\tboolean current_state = (bb[i][k] > bb[j][k]);\r\n \t\t\t\t\tif (last_state1 != current_state)\r\n\t\t\t\t\t\t\t{ \t\t\t\t\t\t\r\n \t\t\t\t\t\tif ( (current_state == (bb[i][k-5] > bb[j][k-5])) || (current_state == (bb[i][k+5] > bb[j][k+5])) )\t\r\n \t\t\t\t\t\t{\r\n \t\t\t\t\t\t\tif (current_state)\r\n \t\t\t\t\t\t\t{\r\n \t\t\t\t\t\t\t\tif ( (bb[i][k] > upthre[i]) && (bb[j][k] < lothre[j]) )\r\n \t\t\t\t\t\t\t\t{\r\n \t\t\t\t\t\t\t\t\ttransitionsh++;\r\n \t\t\t\t\t\t\t\t}\r\n \t\t\t\t\t\t\t}\r\n \t\t\t\t\t\t\telse\r\n \t\t\t\t\t\t\t{\r\n \t\t\t\t\t\t\t\tif ( (bb[j][k] > upthre[j]) && (bb[i][k] < lothre[i]) )\r\n \t\t\t\t\t\t\t\t{\r\n \t\t\t\t\t\t\t\t\ttransitionsl++;\r\n \t\t\t\t\t\t\t\t}\r\n \t\t\t\t\t\t\t} \t\t\t\t\t\t\t\r\n \t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n \t\t\t\t\tlast_state1 = last_state; //test c \r\n \t\t\t\t\tlast_state = current_state;\r\n \t\t\t\t\t\r\n \t\t\t\t\t//both not high at same time check\r\n \t\t\t\t\tif (!(bb[j][k]>maxs[j]/4) && !(bb[i][k]>maxs[i]/4))\r\n \t\t\t\t\t{\r\n \t\t\t\t\t\tif (!(bb[j][k+5]>maxs[j]/4) && !(bb[i][k+5]>maxs[i]/4))\r\n \t\t\t\t\t\t{\r\n \t\t\t\t\t\t\tif (!(bb[j][k-5]>maxs[j]/4) && !(bb[i][k-5]>maxs[i]/4))\r\n \t\t\t\t\t\t\t\thighs++;\r\n \t\t\t\t\t\t}\r\n \t\t\t\t\t} \r\n \t\t\t\t}\r\n \t\t\t\t\r\n \t\t\t//\tSystem.out.println(transitionsh + \" \" + transitionsl + \" \" + highs);\r\n \t\t\t\t\r\n \t\t\t\t\r\n \t\t\t\t\r\n \t\t\t\t//TODO: look at reinstating this\r\n \t\t\t\tif ( /*(transitionsh+transitionsl > 2) && (transitionsh >0) && (transitionsl > 0) && */(highs < 12)) \t\t\t\t\t\r\n \t\t\t\t{\r\n \t\t\t\t\t \t\t\t\t\t\r\n \t\t\t\t\r\n\t \t\t\t\t//TODO check there are some transitions in the data\r\n \t\t\t\t\tif (peak[i][0] > peak[j][0])\r\n \t\t\t\t\t{\r\n \t\t\t\t\t\tout[1] = peak[i][0]*8000/(FFT_half_len*2);\r\n \t \t\t\t\tout[0] = peak[j][0]*8000/(FFT_half_len*2);\r\n \t\t\t\t\t}\r\n \t\t\t\t\telse\r\n \t\t\t\t\t{\r\n \t\t\t\t\t\tout[0] = peak[i][0]*8000/(FFT_half_len*2);\r\n \t \t\t\t\tout[1] = peak[j][0]*8000/(FFT_half_len*2);\r\n \t\t\t\t\t}\r\n\t \t\t\t\t\r\n\t \t\t\t\t\r\n\t \t\t\t\r\n\t//\t \t\t\t\tgrtty.drawfft(_fft);\r\n\t//\t \t\t\t\tgrtty.addMarkers(peak[i][0],peak[j][0]);\r\n\t//\t \t\t\t\t//grtty.addMarkers(peak[][0]);\r\n\t//\t \t\t\t\tfor (int z = 0; z < peak_count; z++)\r\n\t//\t \t\t\t\t\tgrtty.addMarkers(peak[z][0]);\r\n\t\t \t\t\t\t\r\n\t\t \t\t\t\tif (update)\r\n\t\t \t\t\t\t{\r\n\t\t\t \t\t\t\tdecoder._f1=out[0]/8000;\r\n\t\t\t \t\t\t\tdecoder._f2=out[1]/8000;\r\n\t\t \t\t\t\t}\r\n\t\t \t\t\t\t\t\t \t\t\t\t\t \r\n\t \t\t\t\treturn out;\r\n \t\t\t\t}\r\n \t\t\t}\r\n \t\t} \t\t\r\n \t} \t\r\n }\r\n\t\treturn out;\r\n\t}\r\n\r\n\tprivate void follow_fsk(boolean initial_solution)\r\n\t{\r\n\t\t//calls follow RTTY, then updates the demod by first making sure the shift is averaged.\r\n\t\t//if initial solution, the update is applied without any averaging\r\n\t\r\n\t\tdouble[] new_pos = follow_fsk_getpos( search_range_rtty);\r\n\t\r\n\t\tif (av_shift.getMA() == 0 || initial_solution)\r\n\t\t{\r\n\t\t\tav_shift.init(decoder._f2 - decoder._f1);\r\n\t\t}\r\n\t\t\r\n\t\tif (new_pos[0] < 0)\r\n\t\t{ //update position based only on upper freq\r\n\t\t\tdecoder._f2 = new_pos[1];\r\n\t\t\tdecoder._f1 = new_pos[1] - av_shift.getMA();\r\n\t\t}\r\n\t\telse if (new_pos[1] < 0)\r\n\t\t{ //update position based only on lower freq\r\n\t\t\tdecoder._f1 = new_pos[0];\r\n\t\t\tdecoder._f2 = new_pos[0] + av_shift.getMA();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif (new_pos[1]-new_pos[0] < 50/8000)\r\n\t\t\t\tav_shift.update(50);\r\n\t\t\telse\r\n\t\t\t\tav_shift.update(new_pos[1]-new_pos[0]);\r\n\t\t\t\r\n\t\t\tdouble centre = (new_pos[1]-new_pos[0])/2 + new_pos[0];\r\n\t\t\tdecoder._f1 = centre - av_shift.getMA()/2;\r\n\t\t\tdecoder._f2 = centre + av_shift.getMA()/2;\r\n\t\t}\t\t\r\n\t}\r\n\t\r\n\tprivate double[] follow_fsk_getpos(int search_range)\r\n\t{\r\n\t\t//search range is number of fft bins each side of old_Fx\r\n\t\t\r\n\t\tdouble[] out = new double[] {0,0};\r\n\t\t\r\n\t\t\r\n\t\tdouble old_f1=decoder._f1;\r\n\t\tdouble old_f2=decoder._f2;\r\n\t\t\r\n\t\t\r\n\t\tif (!calcuate_FFT())\r\n\t\t\treturn out;\r\n \r\n double[] int_f1 = new double[2*search_range -1];\r\n double[] int_f2 = new double[2*search_range -1];\r\n int bin_f1 = (int)(old_f1 * 1024);\r\n int bin_f2 = (int)(old_f2 * 1024);\r\n \r\n int j=0;\r\n //now integrate the FFT plot around each old freq\r\n for (int i = bin_f1-search_range+1; i < bin_f1+search_range; i++)\r\n {\r\n \tif ((i >= 0) && (i < FFT_half_len))\r\n \t{\r\n \t\tif (j==0)\r\n \t\t\tint_f1[0]=Math.sqrt(_fft[i]);\r\n \t\telse\r\n \t\t\tint_f1[j]=int_f1[j-1]+Math.sqrt(_fft[i]);\r\n \t}\r\n \telse\r\n \t{\r\n \t\tif (j==0)\r\n \t\t\tint_f1[0]=0;\r\n \t\telse\r\n \t\t\tint_f1[j]=int_f1[j-1];\r\n \t}\t\r\n \tj++;\r\n }\r\n j=0;\r\n for (int i = bin_f2-search_range+1; i < bin_f2+search_range; i++)\r\n {\r\n \tif ((i >= 0) && (i < FFT_half_len))\r\n \t{\r\n \t\tif (j==0)\r\n \t\t\tint_f2[0]=Math.sqrt(_fft[i]);\r\n \t\telse\r\n \t\t\tint_f2[j]=int_f2[j-1]+Math.sqrt(_fft[i]);\r\n \t}\r\n \telse\r\n \t{\r\n \t\tif (j==0)\r\n \t\t\tint_f2[0]=0;\r\n \t\telse\r\n \t\t\tint_f2[j]=int_f2[j-1];\r\n \t}\t\r\n \tj++;\r\n }\r\n \r\n int midbin_1=0;\r\n int midbin_2=0;\r\n //look for midpoint of integration curve - where the middle of the peak is\r\n for (int i=0; i < 2*search_range -2; i++)\r\n {\r\n \tif ((midbin_1 ==0) && (int_f1[i] > int_f1[2*search_range -2]/2))\r\n \t{\r\n \t\tmidbin_1=i+bin_f1-search_range+1;\r\n \t}\r\n \tif ((midbin_2 ==0) && (int_f2[i] > int_f2[2*search_range -2]/2))\r\n \t{\r\n \t\tmidbin_2=i+bin_f2-search_range+1;\r\n \t}\r\n }\r\n\r\n\t\t//return -1 if one peak is somewhat less then the other\r\n\t\t//this indicates that carrier wasnt present in the fft range\r\n\t\tdouble peak = Math.max(int_f1[2*search_range -2], int_f2[2*search_range -2]);\r\n\t\t\r\n\t\tif ( int_f1[2*search_range -2] < peak/3 )\r\n\t\t\tout[0] = (double)-1;\r\n\t\telse\r\n\t\t\tout[0] = (double)(midbin_1)/(2*FFT_half_len);\r\n\t\t\r\n\t\tif ( int_f2[2*search_range -2] < peak/3 )\r\n\t\t\tout[1] = (double)-1;\r\n\t\telse\r\n\t\t\tout[1] = (double)(midbin_2)/(2*FFT_half_len);\r\n\t\r\n return out;\r\n\t}\r\n\t\t\r\n\tpublic String processBlock (double[] samples, int baud)\r\n\t{\r\n\t\t\r\n\t\t//TODO: consider writing samples as a class wide variable rather than passing to each method\r\n\t\t//TODO: search and afc both fft but dont share results\r\n\t\t\r\n\t\t_samples = samples;\r\n\t\t_fft_updated = false;\r\n\t\t\r\n\t\tsamples_since_afc += _samples.length;\r\n\t\tsamples_since_search += _samples.length;\r\n\t\tsamples_since_fft += _samples.length;\r\n\t\t\r\n\t\tcc.samplesElapsed(samples.length);\r\n\t\t\r\n\t\tConfidenceCalculator.State initialState = cc.state;\r\n\t\t\r\n\t\tif (auto_rtty_finding && cc.fullSearchDue())\r\n\t\t{\r\n\t\t\tsamples_since_fft = 0;\r\n\t\t\tdouble[] loc = find_fsk(false);\r\n\t\t\tboolean up = cc.putFrequencies(loc[0]/8000, loc[1]/8000);\r\n\t\t\tif (up){\r\n\t\t\t\tdecoder._f1 = cc.getFrequencies(0);\r\n\t\t\t\tdecoder._f2 = cc.getFrequencies(1); }\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\tif (enable_afc && samples_since_afc >= afc_update_freq) //step 2 : follow signal if afc is set\r\n\t\t{\r\n\t\t\tsamples_since_fft = 0;\r\n\t\t\tsamples_since_afc = 0;\r\n\t\t\tfollow_fsk(initialState != ConfidenceCalculator.State.SIG_DROPPED);\r\n\t\t\t\r\n\t\t\tcc.AFCUpdate(decoder._f1,decoder._f2);\r\n\t\t}\r\n\t\t\r\n\t\tif (samples_since_fft >= fft_update_freq && enableFFT)\r\n\t\t{\r\n\t\t\tcalcuate_FFT();\r\n\t\t\tsamples_since_fft = 0;\r\n\t\t}\r\n\t\t\r\n\t\t/*\r\n\t\t//step 1 : find rtty signal if needed\r\n\t\tif (auto_rtty_finding && current_state == State.INACTIVE && samples_since_search >= search_freq)\r\n\t\t{\r\n\t\t\tsamples_since_fft = 0;\r\n\t\t\tsamples_since_search = 0;\r\n\t\t\tdouble[] loc = findRTTY(true);\r\n\t\t\tif (loc[0] > 0)\r\n\t\t\t{\r\n\t\t\t\tcurrent_state = State.FOUND_SIG;\r\n\t\t\t\tfollowRTTY(true);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (enable_afc && samples_since_afc >= afc_update_freq) //step 2 : follow signal if afc is set\r\n\t\t{\r\n\t\t\tsamples_since_fft = 0;\r\n\t\t\tsamples_since_afc = 0;\r\n\t\t\tfollowRTTY(false);\r\n\t\t}\r\n\t\t\r\n\t\tif (samples_since_fft >= fft_update_freq)\r\n\t\t{\r\n\t\t\tcalcuate_FFT();\r\n\t\t\tsamples_since_fft = 0;\r\n\t\t}\r\n\t\t\r\n\t\t*/\r\n\t\t\r\n\t\t//step 3 : demodulate the signal\t\t\r\n\t\t\r\n\t\tString str = \"\";\t\r\n\t\t\r\n\t\tif (current_mode == Mode.RTTY)\r\n\t\t{\r\n\t\t\tboolean[] bits = decoder.processBlock_2bits(samples,baud);\r\n\t\t\tcc.putPowerLevels(decoder.getLastMaxPower(),decoder.getLastAveragePower());\r\n\t\t\t\t\t\t\r\n\t\t\t//step 4 : convert a bitstream to telemetry\t\t\r\n\t\t\t\t\r\n\t\t\tboolean valid7 = false,valid8 = false; \t\r\n\t\t\t\r\n\t\t\tif (current_state == State.IDLE)\t\t//if data /stops are known then used fixed stops decoder too\r\n\t\t\t{\r\n\t\t\t\tbit2char_fixed.DataBits(current_data_bits);\r\n\t\t\t\tbit2char_fixed.StopBits(current_stop_bits);\r\n\t\t\t\tstr = bit2char_fixed.bits2chars(bits);\r\n\t\t\t\ttelem_hand_f.ExtractPacket(str);\r\n\t\t\t\tif (current_data_bits ==7)\r\n\t\t\t\t{\r\n\t\t\t\t\tstr = bit2char_8.bits2chars(bits);\r\n\t\t\t\t\tvalid8 = telem_hand_8.ExtractPacket(str);\r\n\t\t\t\t\tstr = bit2char_7.bits2chars(bits);\r\n\t\t\t\t\tvalid7 = telem_hand_7.ExtractPacket(str);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tstr = bit2char_7.bits2chars(bits);\r\n\t\t\t\t\tvalid7 = telem_hand_7.ExtractPacket(str);\r\n\t\t\t\t\tstr = bit2char_8.bits2chars(bits);\r\n\t\t\t\t\tvalid8 = telem_hand_8.ExtractPacket(str);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif (cc.getState() == ConfidenceCalculator.State.SIG_DROPPED)\r\n\t\t\t\t\tcurrent_state = State.INACTIVE;\r\n\t\t\t}\r\n\t\t\telse if (current_data_bits ==7)\t\t\t//if data / stops not known try 7nX and 8nX, returning the results of whatever setting was used last\r\n\t\t\t{\r\n\t\t\t\tstr = bit2char_8.bits2chars(bits);\r\n\t\t\t\tvalid8 = telem_hand_8.ExtractPacket(str);\r\n\t\t\t\tstr = bit2char_7.bits2chars(bits);\r\n\t\t\t\tvalid7 = telem_hand_7.ExtractPacket(str);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tstr = bit2char_7.bits2chars(bits);\r\n\t\t\t\tvalid7 = telem_hand_7.ExtractPacket(str);\r\n\t\t\t\tstr = bit2char_8.bits2chars(bits);\r\n\t\t\t\tvalid8 = telem_hand_8.ExtractPacket(str);\r\n\t\t\t}\r\n\t\t\t//System.out.println(bit2char_7.Average_bit_period());\r\n\t\t\t\r\n\t\t\t//at this stage, if valid7/8 is high, then the databits info is known, and the fixed extractor can be used\r\n\t\t\tif (valid7)\r\n\t\t\t{\r\n\t\t\t\tcurrent_state = State.IDLE;\r\n\t\t\t\tcc.gotDecode();\r\n\t\t\t\tcurrent_data_bits = 7;\r\n\t\t\t\tcurrent_stop_bits = (int) Math.round(bit2char_7.average_stop_bits());\r\n\t\t\t}\r\n\t\t\telse if (valid8)\r\n\t\t\t{\r\n\t\t\t\tcurrent_state = State.IDLE;\r\n\t\t\t\tcc.gotDecode();\r\n\t\t\t\tcurrent_data_bits = 8;\r\n\t\t\t\tcurrent_stop_bits = (int) Math.round(bit2char_8.average_stop_bits());\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tdouble[] bits = decoder.processBlock_2bits_llr(samples,baud);\r\n\t\t\tboolean valid_bin = false;\r\n\t\t\tstr = telem_hand_bin.bits2chars(bits);\r\n\t\t\tvalid_bin = telem_hand_bin.get_last_valid();\r\n\t\t\t\r\n\t\t\t//if (current_modulation == Modulation.AFSK)\r\n\t\t\t//{\r\n\t\t\t\tif (cc.getState() == ConfidenceCalculator.State.SIG_DROPPED)\r\n\t\t\t\t\tcurrent_state = State.INACTIVE;\r\n\t\t\t\tif (valid_bin)\r\n\t\t\t\t{\r\n\t\t\t\t\tcc.gotDecode();\r\n\t\t\t\t\tcurrent_state = State.IDLE;\r\n\t\t\t\t}\r\n\t\t\t//}\r\n\t\t}\r\n\t\t\r\n\t\treturn str;\r\n\t}\r\n\r\n\tpublic void StringRx(byte[] str, boolean checksum, int length, int flags, int fixed)\r\n\t{\r\n\t\tif (_listeners.size() > 0)\r\n\t\t{\r\n\t\t\tfireStringReceived(str, checksum, length, flags, fixed);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void StringRx(String str, boolean checksum)\r\n\t{\r\n\r\n\t\tif (!last_sha.equals(str))\r\n\t\t{\r\n\t\t\tlast_sha = str;\t\t\r\n\t\t\tif (_listeners.size() > 0)\r\n\t\t\t{\r\n\t\t\t\tfireStringReceived(str, checksum);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t\r\n\tpublic double[] get_fft() {\r\n\t\treturn _fft;\r\n\t}\r\n\t\r\n\tpublic double get_fft(int i)\r\n\t{\r\n\t\tif (_fft == null)\r\n\t\t\treturn 0;\r\n\t\tif (i < _fft.length)\r\n\t\t\treturn _fft[i];\r\n\t\telse\r\n\t\t\treturn 0;\r\n\t\t\r\n\t}\r\n\r\n\tpublic int[] get_peaklocs() {\r\n\t\treturn _peaklocs;\r\n\t}\r\n\r\n\r\n\tpublic double get_f1() {\r\n\t\treturn decoder._f1;\r\n\t}\r\n\t\r\n\tpublic double get_f2() {\r\n\t\treturn decoder._f2;\r\n\t}\r\n\t\r\n\tpublic void setFreq(double f1, double f2)\r\n\t{\r\n\t\tdecoder.setFreq(f1, f2);\r\n\t}\r\n\t\r\n\tpublic boolean get_fft_updated()\r\n\t{\r\n\t\treturn _fft_updated;\r\n\t}\r\n\t//IG_LOST,SIG_JUST_FOUND,SIG_TRACKING,SIG_DROPPED};\r\n\tpublic String statusToString()\r\n\t{\r\n\t\tif (current_modulation == Modulation.AFSK)\r\n\t\t\treturn \"Tracking Signal\";\r\n\t\tswitch (cc.state)\r\n\t\t{\r\n\t\t\tcase SIG_LOST : \r\n\t\t\t\treturn \"Searching\";\t\t\r\n\t\t\tcase SIG_JUST_FOUND :\r\n\t\t\t\treturn \"Found Signal\";\r\n\t\t\tcase SIG_TRACKING :\r\n\t\t\t\treturn \"Tracking Signal\";\r\n\t\t\tcase SIG_DROPPED :\r\n\t\t\t\treturn \"Dropped Signal\";\r\n\t\t\tdefault : \r\n\t\t\t\treturn \"Inactive\";\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void setModulation(Modulation set)\r\n\t{\r\n\t\tcurrent_modulation = set;\r\n\t\tif (current_modulation == Modulation.AFSK)\r\n\t\t{\r\n\t\t\tauto_rtty_finding = false;\r\n\t\t\tenable_afc = false;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tauto_rtty_finding = true;\r\n\t\t\tenable_afc = true;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void setMode(Mode set)\r\n\t{\r\n\t\tcurrent_mode = set;\r\n\t}\r\n\t\r\n\tpublic boolean paramsValid()\r\n\t{\r\n\t\treturn (current_state == State.IDLE);\r\n\t}\r\n\r\n\tpublic void provide_binary_sync_helper(byte[] data, byte[] mask, String id, int len)\r\n\t{\r\n\t\ttelem_hand_bin.provide_binary_sync_helper(data, mask, id, len);\r\n\t}\r\n\t\r\n\t\r\n\t\r\n}",
"public class Telemetry_string implements java.io.Serializable {\r\n\r\n\t/**\r\n\t * \r\n\t */\r\n\tprivate static final long serialVersionUID = 0x5901fa8c0e38abb1L;\r\n\r\n\tpublic String callsign = \"\";\r\n\t\r\n\tpublic Date time = null;\r\n\t\r\n\tpublic int packetID=0;\r\n\t\r\n\tpublic Gps_coordinate coords;\r\n\t\r\n\tprivate String raw_string = \"\";\r\n\tpublic String[] user_fields;\r\n\t\r\n\tpublic double frequency = 0;\r\n\t\r\n\tpublic boolean checksum_valid;\r\n\t\r\n\tpublic Map<String,String> habitat_metadata = null;\r\n\t\r\n\tprivate double[] extraFields;\r\n\t\r\n\tpublic String doc_time_created;\r\n\t\r\n\tpublic String getSentence()\r\n\t{\r\n\t\t\r\n\t\treturn raw_string + \"\\n\";\r\n\t}\r\n\t\r\n\t\r\n\tpublic Telemetry_string(byte[] telem, TelemetryConfig tc) {\r\n\t\tparse_telem(telem, System.currentTimeMillis() / 1000L, tc);\r\n\t\tchecksum_valid = true;\r\n\t\t\r\n\t\t//get time created\r\n\t\tDate time = new Date();\r\n\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZ\");\r\n\t\tString t = dateFormat.format(time);\r\n\t\tt = t.substring(0, t.length()-2) + \":\" + t.substring(t.length()-2, t.length());\r\n\t\tdoc_time_created = t;\r\n\t}\r\n\tpublic Telemetry_string(String telem, TelemetryConfig tc) {\r\n\t\tparse_telem(telem, System.currentTimeMillis() / 1000L, tc);\r\n\t\tchecksum_valid = check_checksum(telem,0);\r\n\t\t\r\n\t\t//get time created\r\n\t\tDate time = new Date();\r\n\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZ\");\r\n\t\tString t = dateFormat.format(time);\r\n\t\tt = t.substring(0, t.length()-2) + \":\" + t.substring(t.length()-2, t.length());\r\n\t\tdoc_time_created = t;\r\n\t}\r\n\tpublic Telemetry_string(String telem, long timerx, TelemetryConfig tc) {\r\n\t\tparse_telem(telem,timerx, tc);\r\n\t\tchecksum_valid = check_checksum(telem,0);\r\n\t\t\r\n\t\t//get time created\r\n\t\tDate time = new Date();\r\n\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZ\");\r\n\t\tString t = dateFormat.format(time);\r\n\t\tt = t.substring(0, t.length()-2) + \":\" + t.substring(t.length()-2, t.length());\r\n\t\tdoc_time_created = t;\r\n\t}\r\n\t\r\n\tpublic Telemetry_string(String telem, boolean _checksum_valid, TelemetryConfig tc) {\r\n\t\tparse_telem(telem, System.currentTimeMillis() / 1000L, tc);\r\n\t\tchecksum_valid = _checksum_valid;\r\n\t\t\r\n\t\t//get time created\r\n\t\tDate time = new Date();\r\n\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZ\");\r\n\t\tString t = dateFormat.format(time);\r\n\t\tt = t.substring(0, t.length()-2) + \":\" + t.substring(t.length()-2, t.length());\r\n\t\tdoc_time_created = t;\r\n\t}\r\n\t\r\n\tprivate void parse_telem(byte[] str, long timerx, TelemetryConfig tc)\r\n\t{\r\n\t\t\r\n\t\tMessagePack msgpack = new MessagePack();\r\n\t\t\r\n\t\tByteArrayInputStream in = new ByteArrayInputStream(str);\r\n Unpacker unpacker = msgpack.createUnpacker(in);\r\n\t\t\r\n\t\tbyte[] base64enc = Base64.encodeBase64(str);\r\n\t\t\r\n\t\tMap<Integer, String> telemmap = new HashMap<Integer, String>();\r\n \r\n try {\r\n \twhile(in.available()>0) //TODO: handle multiple messages\r\n \t{\r\n \t\tValue v = unpacker.readValue();\r\n \t\tif (v.isMapValue())\r\n \t\t{\r\n \t\t\t//raw_string = v.toString();\r\n \t\t\t\r\n \t\t\tboolean valid_lock = true;\r\n \t\t\t\r\n \t\t\tfor (Value s : v.asMapValue().keySet()) \r\n \t\t\t{\r\n \t\t\t\tValue item = v.asMapValue().get(s); \r\n \t\t\t\tif (s.isIntegerValue()){\r\n \t\t\t\t\tswitch (s.asIntegerValue().intValue())\r\n \t\t\t\t\t{\r\n \t\t\t\t\tcase 0: \t\t\t//CALLSIGN\t\r\n \t\t\t\t\t\tcallsign = item.toString();\r\n \t\t\t\t\t\tif (callsign.startsWith(\"\\\"\")) //TODO: this is horrible\r\n \t\t\t\t\t\t\tcallsign = callsign.substring(1);\r\n \t\t\t\t\t\tif (callsign.endsWith(\"\\\"\"))\r\n \t\t\t\t\t\t\tcallsign = callsign.substring(0, callsign.length() -1);\r\n \t\t\t\t\t\ttelemmap.put(new Integer(0), callsign);\r\n \t\t\t\t\t\t//callsign = callsign + \"_b\";\r\n \t\t\t\t\t\t//raw_string = raw_string + callsign + \",\";\r\n \t\t\t\t\t\tbreak;\r\n \t\t\t\t\tcase 2:\t\t\t\t\t//TIME\r\n \t\t\t\t\t\tif (item.isIntegerValue())\r\n \t\t\t\t\t\t{ \t\t\t\t\t\t\t\r\n \t\t\t\t\t\t\t//Date time_in = new Date(item.asIntegerValue().getInt()*1000);\r\n \t\t\t\t\t\t\t//setTime(time_in,timerx); \r\n \t\t\t\t\t\t\t//SimpleDateFormat dateFormat = new SimpleDateFormat(\"HH:mm:ss\");\r\n \t\t\t\t\t\t\tint time_in = item.asIntegerValue().getInt();\r\n\t\t\t\t\t\t\t\t\tint hours = (int)Math.floor(time_in/(60*60));\r\n\t\t\t\t\t\t\t\t\ttime_in = time_in - (hours*60*60);\r\n\t\t\t\t\t\t\t\t\tint mins = (int)Math.floor(time_in/60);\r\n\t\t\t\t\t\t\t\t\tint secs = time_in-mins*60;\r\n\t\t\t\t\t\t\t\t\tString timestr = String.format(\"%02d:%02d:%02d\",hours,mins,secs);\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\tSimpleDateFormat ft = new SimpleDateFormat (\"HH:mm:ss\");\r\n\t\t\t\t\t\t\t\t\tft.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\r\n\t\t\t\t\t\t\t\t\tDate time_;\r\n\t\t\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\t\t\ttime_ = ft.parse(timestr);\r\n\t\t\t\t\t\t\t\t\t\tsetTime(time_,timerx); \r\n\t\t\t\t\t\t\t\t\t} catch (ParseException e) {\r\n\t\t\t\t\t\t\t\t\t\tSystem.out.println(\"Error parsing - \" + e.toString());\r\n\t\t\t\t\t\t\t\t\t}\t\r\n\t\t\t\t\t\t\t\t\t//raw_string = raw_string + String.format(\"%02d:%02d:%02d\",hours,mins,secs) + \",\";\r\n\t\t\t\t\t\t\t\t\ttelemmap.put(new Integer(2), timestr);\r\n \t\t\t\t\t\t}\r\n \t\t\t\t\t\tbreak; \t\t\t\t\t\t\r\n \t\t\t\t\tcase 1:\t\t\t\t\t//PACKET COUNT\r\n \t\t\t\t\t\tif (item.isIntegerValue()){\r\n \t\t\t\t\t\t\tpacketID = item.asIntegerValue().getInt();\r\n \t\t\t\t\t\t\t//raw_string = raw_string + packetID + \",\";\r\n \t\t\t\t\t\t\ttelemmap.put(new Integer(1), Integer.toString(packetID));\r\n \t\t\t\t\t\t}\r\n \t\t\t\t\t\tbreak; \t\t\t\t\t\t\r\n \t\t\t\t\tcase 3:\t\t\t\t\t//POSITION\r\n \t\t\t\t\t\tif (item.isArrayValue())\r\n \t\t\t\t\t\t{\r\n \t\t\t\t\t\t\tString pos = \"\";\r\n \t\t\t\t\t\t\tif (item.asArrayValue().size() >= 2)\r\n \t\t\t\t\t\t\t{\r\n \t\t\t\t\t\t\t\tif (item.asArrayValue().get(0).isIntegerValue()\r\n \t\t\t\t\t\t\t\t && item.asArrayValue().get(1).isIntegerValue())\r\n \t\t\t\t\t\t\t\t{\r\n \t\t\t\t\t\t\t\t\tcoords = new Gps_coordinate(item.asArrayValue().get(0).asIntegerValue().intValue(),\r\n \t\t\t\t\t\t\t\t\t\t\titem.asArrayValue().get(1).asIntegerValue().intValue());\r\n \t\t\t\t\t\t\t\t\tpos = Integer.toString(item.asArrayValue().get(0).asIntegerValue().intValue()) + \",\"\r\n \t\t\t\t\t\t\t\t\t\t\t+ Integer.toString(item.asArrayValue().get(1).asIntegerValue().intValue());\r\n \t\t\t\t\t\t\t\t}\r\n \t\t\t\t\t\t\t\tif (item.asArrayValue().size() >= 3){\r\n\t \t\t\t\t\t\t\t\tif (item.asArrayValue().get(2).isIntegerValue())\r\n\t \t\t\t\t\t\t\t\t{\r\n\t \t\t\t\t\t\t\t\t\tcoords.Set_altitude(item.asArrayValue().get(2).asIntegerValue().getInt());\r\n\t \t\t\t\t\t\t\t\t\tpos = pos + \",\" + Integer.toString(item.asArrayValue().get(2).asIntegerValue().intValue());\r\n\t \t\t\t\t\t\t\t\t}\r\n \t\t\t\t\t\t\t\t}\r\n \t\t\t\t\t\t\t\t//raw_string = raw_string + coords.latitude + \",\" + coords.longitude + \",\" + coords.altitude + \",\";\r\n \t\t\t\t\t\t\t}\r\n \t\t\t\t\t\t\ttelemmap.put(new Integer(3), pos);\r\n \t\t\t\t\t\t}\r\n \t\t\t\t\t\tbreak;\r\n \t\t\t\t\t//case 4:\t\t\t\t\t//SATS\r\n \t\t\t\t\t//\t\r\n \t\t\t\t\t//\tbreak;\r\n \t\t\t\t\t//case 5: \t\t\t\t\t\t\r\n \t\t\t\t\t//\t\r\n \t\t\t\t\t//\tbreak; \t\t\t\t\t\t\r\n \t\t\t\t\t//case 6:\r\n \t\t\t\t\t//\t\r\n \t\t\t\t\t//\tbreak;\r\n \t\t\t\t\tdefault:\r\n \t\t\t\t\t\tif (item.isIntegerValue()){ \t\t\t\t\t\t\t\r\n \t\t\t\t\t\t\t//raw_string = raw_string + packetID + \",\";\r\n \t\t\t\t\t\t\ttelemmap.put(new Integer(s.asIntegerValue().intValue()),\r\n \t\t\t\t\t\t\t\t\tInteger.toString(item.asIntegerValue().getInt()));\r\n \t\t\t\t\t\t}\r\n \t\t\t\t\t\telse if (item.isArrayValue()){\r\n \t\t\t\t\t\t\tString s_out = \"\";\r\n \t\t\t\t\t\t\tInteger first = 1;\r\n \t\t\t\t\t\t\tfor (Value item2 : item.asArrayValue()){\r\n \t\t\t\t\t\t\t\tif (item2.isIntegerValue()){ \r\n \t\t\t\t\t\t\t\t\tif (first>0)\r\n \t\t\t\t\t\t\t\t\t\ts_out = s_out + item2.toString();\r\n \t\t\t\t\t\t\t\t\telse\r\n \t\t\t\t\t\t\t\t\t\ts_out = s_out + \",\" + item2.toString();\r\n \t\t\t\t\t\t\t\t\t\tfirst = 0;\r\n \t\t\t\t\t\t}\r\n \t\t\t\t\t\t\t}\r\n \t\t\t\t\t\t\tif (first == 0)\r\n \t\t\t\t\t\t\t\ttelemmap.put(new Integer(s.asIntegerValue().intValue()),s_out); \t\t\t\t\t\t\t \t\t\t\t\t\t\t\r\n \t\t\t\t\t\t}\r\n \t\t\t\t\t\tbreak;\r\n \t\t\t\t\t}\r\n \t\t\t\t}\r\n \t\t\t \r\n \t\t\t}\r\n \t\t\t\r\n \t\t\tif (coords != null)\r\n \t\t\t\tcoords.latlong_valid = valid_lock;\r\n \t\t\t\r\n \t\t\tbreak;\r\n \t\t}\r\n \t}\r\n \t\r\n \t//if (raw_string.length() > 0)\r\n \tif(telemmap.size()>0)\r\n \t{\r\n \t\tfor (int i = 0; i <128; i++){ //TODO: fix this\r\n \t\t\tif (telemmap.containsKey(i)){\r\n \t\t\t\traw_string = raw_string + telemmap.get(i) + ',';\r\n \t\t\t}\r\n \t\t}\r\n \t\tif (raw_string.length() > 0){\r\n\t\t\t\t\traw_string = raw_string + new String(base64enc) + \"*\";;\r\n\t \t\t//raw_string = raw_string.substring(0,raw_string.length()-1) + \"*\";\r\n\t \t\tint crc = calculate_checksum(raw_string,0);\r\n\t \t\traw_string = raw_string + String.format(\"%04x\", crc);\r\n \t\t}\r\n \t}\r\n \t\r\n\t\t\t//Map<Integer, String> dstMap = unpacker.read(mapTmpl);\r\n\t\t} catch (IOException e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n catch (MessageTypeException e){\r\n \te.printStackTrace();\r\n }\r\n\r\n\t}\r\n\t\r\n\tpublic static byte[][] gen_telem_mask(byte[] input)\r\n\t{\r\n\t\t//generates an expected bit pattern and mask based on callsign and markers\r\n\t\t\r\n\t\tbyte[][] output = new byte[2][input.length];\r\n\t\t\r\n\t\tif (input.length < 3)\r\n\t\t\treturn null;\r\n\t\t\r\n\t\tif ( (input[0] & 0xF0) == 0x80 &&\r\n\t\t\t (input[1] & 0xFF) == 0x00 &&\r\n\t\t\t (input[2] & 0xE0) == 0xA0 )\r\n\t\t{\r\n\t\t\tint calllen = input[2] & 0x1F;\r\n\t\t\t\r\n\t\t\toutput[0][0] = input[0];\r\n\t\t\toutput[0][1] = input[1];\r\n\t\t\toutput[0][2] = input[2];\r\n\t\t\toutput[1][0] = (byte) 0xFF;\r\n\t\t\toutput[1][1] = (byte) 0xFF;\r\n\t\t\toutput[1][2] = (byte) 0xFF;\r\n\t\t\tif (input.length > 4+calllen){\r\n\t\t\t\tfor (int i = 0; i < calllen + 1; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\toutput[0][i+3] = input[3+i];\r\n\t\t\t\t\toutput[1][i+3] = (byte) 0xFF;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t//i began to do something that would work for pretty much everything but settled on one that just does the callsign\r\n\t\t/*\r\n\t\t\t\t\r\n\t\tboolean incall = false;\r\n\t\tint infield_len = 0;\r\n\t\tint infield_count = 0;\r\n\t\tboolean inmap = false;\r\n\t\tboolean map_val = false;\r\n\t\t\r\n\t\t\r\n\t\tfor (int i = 0; i < input.length; i++)\r\n\t\t{\r\n\t\t\tif (infield_count == 0)\r\n\t\t\t{\r\n\t\t\t\tif ((input[i] & 0xF0)== 0x80) //map <16 elements\r\n\t\t\t\t{\r\n\t\t\t\t\toutput[0][i] = input[i];\r\n\t\t\t\t\toutput[1][i] = (byte) 0xFF;\r\n\t\t\t\t\tinmap = true;\r\n\t\t\t\t}\r\n\t\t\t\telse if ((input[i] & 0xFF)== 0xde && input.length > i+2) //map <65536 elements\r\n\t\t\t\t{\r\n\t\t\t\t\toutput[0][i] = input[i];\r\n\t\t\t\t\toutput[1][i] = (byte) 0xFF;\r\n\t\t\t\t\toutput[0][i+1] = input[i];\r\n\t\t\t\t\toutput[1][i+1] = (byte) 0xFF;\r\n\t\t\t\t\toutput[0][i+2] = input[i];\r\n\t\t\t\t\toutput[1][i+2] = (byte) 0xFF;\r\n\t\t\t\t\tinmap = true;\r\n\t\t\t\t\ti += 2;\r\n\t\t\t\t}\r\n\t\t\t\telse if ()\r\n\t\t\t}\r\n\t\t}\r\n\t\t*/\r\n\t\treturn output;\r\n\t\t\r\n\t}\r\n\t\r\n\tprivate void parse_telem(String str, long timerx, TelemetryConfig tc)\r\n\t{\r\n\t\tint start = str.lastIndexOf('$');\r\n\t\t\r\n\t\tif (start < 0)\r\n\t\t\tstart = 0;\r\n\t\telse\r\n\t\t\tstart++;\r\n\t\t\r\n\t\traw_string = str.substring(start, str.length()).trim();\r\n\t\t\r\n\t\tString[] fields;\r\n\t\tString[] cksplit = raw_string.split(\"\\\\*\",0); //remove checksum\r\n\t\t\r\n\t\tif (cksplit.length>0)\t\t\t\r\n\t\t\tfields = cksplit[0].split(\"\\\\,\",-1);\r\n\t\telse\r\n\t\t\tfields = raw_string.split(\"\\\\,\",-1);\r\n\t\t\r\n\t\tif (fields.length > 6)\r\n\t\t{\r\n\t\t\tuser_fields = new String[fields.length-6];\r\n\t\t\tSystem.arraycopy(fields, 6, user_fields, 0, fields.length-6);\t\t\r\n\t\t} \r\n\t\t\r\n\t\tint ci = 0;\r\n\t\tint offset = 0;\r\n\t\t\r\n\t\tif (fields.length > 1)\r\n\t\t{\r\n\t\t\t//see if counter exists\r\n\t\t\tci = fields[1].indexOf(':');\r\n\t\t\toffset = 0;\r\n\t\t\tif (ci > 0)\r\n\t\t\t\toffset = -1;\t\r\n\t\t}\r\n\t\t\r\n\t\tif (fields.length >= 6+offset)\r\n\t\t{\r\n\t\t\tcallsign = fields[0];\r\n\t\t\t\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tif (offset == 0)\r\n\t\t\t\t\tpacketID = Integer.parseInt(fields[1]);\r\n\t\t\t\t\t\t\r\n\t\t\t\t//handle time\t\t\t\r\n\t\t\t\tString format = \"\";\r\n\t\t\t\tif (fields[2+offset].length() > 6)\r\n\t\t\t\t\tformat = \"HH:mm:ss\";\r\n\t\t\t\telse\r\n\t\t\t\t\tformat = \"HHmmss\";\t\t\t\t\r\n\t\t\t\tSimpleDateFormat ft = new SimpleDateFormat (format);\r\n\t\t\t\tft.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\r\n\t\t\t\tDate time_in = ft.parse(fields[2+offset]);\t\r\n\t\t\t\t\r\n\t\t\t\tsetTime(time_in,timerx); \r\n\t\t\t\r\n\t\t\t\tcoords = new Gps_coordinate(fields[3+offset],fields[4+offset],fields[5+offset]);\r\n\t\t\t}\r\n\t\t\tcatch (Exception e)\r\n\t\t\t{\r\n\t\t\t\tSystem.out.println(\"Error parsing - \" + e.toString());\r\n\t\t\t}\r\n\r\n\t\t\t\r\n\t\t\t//now parse extra data\r\n\t\t\textraFields = new double[fields.length-1];\r\n\t\t\t\r\n\t\t\tfor (int j = 6+offset; j < fields.length; j++)\r\n\t\t\t{\r\n\t\t\t\tif (tc == null)\r\n\t\t\t\t{\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\textraFields[j-1] = Double.parseDouble(fields[j]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (Exception e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse if (tc.getTotalFields() <= j-1)\r\n\t\t\t\t{\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\textraFields[j-1] = Double.parseDouble(fields[j]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (Exception e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif (tc.getFieldDataType(j-1) == TelemetryConfig.DataType.FLOAT)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\ttry\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\textraFields[j-1] = Double.parseDouble(fields[j]);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tcatch (Exception e)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (tc.getFieldDataType(j-1) == TelemetryConfig.DataType.INT)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\ttry\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\textraFields[j-1] = (double)Integer.parseInt(fields[j]);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tcatch (Exception e)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\t\t\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic boolean getExtraFieldExists(int index)\r\n\t{\r\n\t\tif (extraFields == null)\r\n\t\t\treturn false;\r\n\t\tif (!(index < extraFields.length))\r\n\t\t\treturn false;\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\tpublic double getExtraFields(int index)\r\n\t{\r\n\t\tif (index < 0)\r\n\t\t\treturn 0;\r\n\t\tif (extraFields == null)\r\n\t\t\treturn 0;\r\n\t\tif (!(index < extraFields.length))\r\n\t\t\treturn 0;\r\n\t\treturn extraFields[index];\r\n\t}\r\n\t\r\n\tpublic String toSha256()\r\n\t{\r\n\t\tString str = \"$$\" + raw_string + \"\\n\";\r\n\t\tbyte [] enc = Base64.encodeBase64(str.getBytes());\r\n\t\tbyte[] sha = null;\r\n\t\t\r\n\t\tMessageDigest md;\r\n\t\ttry {\r\n\t\t\tmd = MessageDigest.getInstance(\"SHA-256\");\r\n\t\t\tmd.update(enc); \r\n\t\t\tsha = md.digest();\r\n\t\t} catch (NoSuchAlgorithmException e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\t\r\n\t\treturn bytesToHexStr(sha);\r\n\t\t\r\n\t}\r\n\t\t\r\n\t//ref: http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java\r\n\tpublic static String bytesToHexStr(byte[] bytes) {\r\n\t final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};\r\n\t char[] hexChars = new char[bytes.length * 2];\r\n\t int v;\r\n\t for ( int j = 0; j < bytes.length; j++ ) {\r\n\t v = bytes[j] & 0xFF;\r\n\t hexChars[j * 2] = hexArray[v >>> 4];\r\n\t hexChars[j * 2 + 1] = hexArray[v & 0x0F];\r\n\t }\r\n\t return new String(hexChars);\r\n\t}\r\n\t\r\n\tpublic String raw_64_str()\r\n\t{\r\n\t\tString str = \"$$\" + raw_string + \"\\n\";\r\n\t\tbyte [] enc = Base64.encodeBase64(str.getBytes());\r\n\t\tString out = new String(enc);\r\n\t\r\n\t\treturn out;\r\n\t}\r\n\t\r\n\tpublic static int calculate_checksum(String in, int start)\r\n\t{\r\n\t\tint crc = 0xFFFF;\r\n\t\tint i=0;\r\n\t\twhile (i < in.length() && in.charAt(i) != '*')\r\n\t\t{\r\n\t\t\tif (in.charAt(i) != '$')\r\n\t\t\t{\r\n\t\t\t\tint j;\r\n\t\t\t\t\r\n\t\t\t\tcrc = (crc ^ (in.charAt(i) << 8 ));\r\n\t\t\t\tfor (j=0; j< 8; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif ((crc & 0x8000) != 0)\r\n\t\t\t\t\t\tcrc = ((crc << 1) ^ 0x1021);\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tcrc = (crc << 1);\r\n\t\t\t\t}\r\n\t\t\t}\t\r\n\t\t\ti++;\r\n\t\t}\r\n\t\treturn crc & 0xFFFF;\r\n\t}\r\n\t\r\n\tpublic static boolean check_checksum(String in, int start)\r\n\t{\r\n\t\tint i;\r\n\t\tint crc = calculate_checksum(in,start);\r\n\t\t\r\n\t\tint ckloc = in.indexOf((int)'*',start);\r\n\t\tif (ckloc < 0)\r\n\t\t\treturn false;\r\n\t\t\r\n\t\tif (ckloc + 4 >= in.length())\r\n\t\t\treturn false;\r\n\t\t\r\n\t\t//now extract checksum based on its known location and compare\r\n\t\tString crcstr = in.substring(ckloc+1, ckloc+5);\r\n\t\tcrcstr = crcstr.toLowerCase();\r\n\t\tfor (i = 0; i < crcstr.length(); i++)\r\n\t\t{\t\t\t\r\n\t\t\tint c = (int)crcstr.charAt(i);\r\n\t\t\tif (c < 48 || c > 102 || (c<97 && c >57))\r\n\t\t\t\treturn false;\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\tint rccrc = Integer.parseInt(crcstr, 16);\r\n\t\t\r\n\t\tif (rccrc == (crc & 0xFFFF))\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t\t\r\n\t}\r\n\t\r\n\tprivate void setTime(Date time_in, long timerx)\r\n\t{\r\n\t\t\r\n\t\ttry //this is all a bit horrible :(\r\n\t\t{\r\n\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t//get time rx @ 12am\r\n\t\t\tCalendar cal = Calendar.getInstance(TimeZone.getTimeZone(\"UTC\"));\r\n\t\t\tCalendar cal2 = Calendar.getInstance(TimeZone.getTimeZone(\"UTC\"));\r\n\r\n\t\t\t\t\r\n\t\t\tcal2.setTime(time_in);\r\n\t\t\t\r\n\t\t\tcal.setTimeInMillis(timerx*1000);\r\n\t\t\tcal.set(Calendar.HOUR_OF_DAY, cal2.get(Calendar.HOUR_OF_DAY));\r\n\t\t\tcal.set(Calendar.MINUTE, cal2.get(Calendar.MINUTE));\r\n\t\t\tcal.set(Calendar.SECOND, cal2.get(Calendar.SECOND));\r\n\t\t\t\r\n\t\t\t//long best_guess = cal2.getTimeInMillis();\r\n\t\t\t\r\n\t\t\t\t\t\r\n\r\n\t\t\tif (cal.getTimeInMillis() < timerx*1000 - 1*60*60*1000)\r\n\t\t\t\tcal.roll(Calendar.DAY_OF_YEAR, 1);\r\n\t\t\tif (cal.getTimeInMillis() < timerx*1000 + 12*60*60*1000)\r\n\t\t\t\t;\r\n\t\t\telse\t\t\t\t\t\r\n\t\t\t\tcal.roll(Calendar.DAY_OF_YEAR, -1);\r\n\t\t\t\r\n\t\t\ttime = cal.getTime(); \r\n\t\t\t\r\n\t\t\t\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\tSystem.out.println(\"Error parsing - \" + e.toString());\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic boolean isZeroGPS(){\r\n\t\tif (coords == null)\r\n\t\t\treturn true;\r\n\t\treturn (coords.latitude == 0.0 || coords.longitude == 0.0);\r\n\t}\r\n\r\n}\r"
] | import java.awt.EventQueue;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import org.math.plot.*;
import edu.emory.mathcs.jtransforms.fft.*;
import graphics.Waterfall;
import ukhas.Gps_coordinate;
import ukhas.Habitat_interface;
import ukhas.Listener;
import rtty.StringRxEvent;
import rtty.fsk_receiver;
import ukhas.Telemetry_string;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.SwingConstants; |
//
// 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.
//import rtty.Mappoint_interface;
public class rttywin extends JFrame implements StringRxEvent {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
AudioFormat audioFormat;
TargetDataLine targetDataLine;
private String _habitat_url = "habitat.habhub.org";
private String _habitat_db = "habitat";
boolean stopCapture = false;
ByteArrayOutputStream byteArrayOutputStream;
Waterfall wf;
AudioInputStream audioInputStream;
SourceDataLine sourceDataLine;
//rtty_decode decoder = new rtty_decode(1200,1800,7);
fsk_receiver rcv = new fsk_receiver();
DoubleFFT_1D ft = new DoubleFFT_1D(512);
//private graph_line grtty = new graph_line();
Plot2DPanel plot = new Plot2DPanel();
int plotint;
JLabel lb_freqs;
JTextArea txtDecode;
JLabel lbfreq;
JScrollPane scrollPane;
JCheckBox ckFreeze;
@SuppressWarnings("rawtypes")
JComboBox cbSoundCard;
JCheckBox ck300b;
JLabel lbStatus;
JLabel lbimage;
JCheckBox chkOnline;
private JCheckBox ckPause;
Habitat_interface hi;// = new Habitat_interface("MATT");
private JTextField txtcall = new JTextField();
private JTextField txtLat;
private JTextField txtLong;;
// graph_line grtty = new graph_line();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
rttywin frame = new rttywin();
frame.setVisible(true);
Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
//Output Available Mixers
System.out.println("Available mixers:");
for(int cnt = 0; cnt < mixerInfo.length; cnt++){
System.out.println(cnt + ": " + mixerInfo[cnt].getName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void StringRx(Telemetry_string str, boolean checksum)
{
}
/**
* Create the frame.
*/
public rttywin() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 546, 628);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
rcv.addStringRecievedListener(this);
try
{
Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
//Output Available Mixers
System.out.println("Available mixers:");
String[] devices = new String[mixerInfo.length];
for(int cnt = 0; cnt < mixerInfo.length; cnt++){
devices[cnt] = mixerInfo[cnt].getName();
}
cbSoundCard = new JComboBox<Object>(devices);
cbSoundCard.setBounds(269, 27, 208, 20);
contentPane.add(cbSoundCard);
BufferedImage grad;
grad = ImageIO.read(new File("C:/grad.png"));
wf = new Waterfall(grad,200);
} catch (Exception e) {
e.printStackTrace();
}
JButton btnStart = new JButton("New button");
btnStart.setEnabled(false);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnStart.setBounds(50, 103, 89, 23);
contentPane.add(btnStart);
JButton btnStop = new JButton("New button");
btnStop.setEnabled(false);
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
targetDataLine.stop();
targetDataLine.close();
}
});
btnStop.setBounds(149, 103, 89, 23);
contentPane.add(btnStop);
JButton btnStartst = new JButton("GO!");
btnStartst.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { | hi = new Habitat_interface(_habitat_url, _habitat_db, new Listener(txtcall.getText(), new Gps_coordinate(txtLat.getText(), txtLong.getText(),"0"),false)); | 0 |
Vrael/eManga | app/src/main/java/com/emanga/emanga/app/adapters/MangaItemListAdapter.java | [
"public class ImageCacheManager {\n\n /**\n * Volley recommends in-memory L1 cache but both a disk and memory cache are provided.\n * Volley includes a L2 disk cache out of the box but you can technically use a disk cache as an L1 cache provided\n * you can live with potential i/o blocking.\n *\n */\n public enum CacheType {\n DISK\n , MEMORY\n }\n\n private static ImageCacheManager mInstance;\n\n /**\n * Volley image loader\n */\n private ImageLoader mImageLoader;\n\n /**\n * Image cache implementation\n */\n private ImageCache mImageCache;\n\n /**\n * @return\n * \t\tinstance of the cache manager\n */\n public static ImageCacheManager getInstance(){\n if(mInstance == null)\n mInstance = new ImageCacheManager();\n\n return mInstance;\n }\n\n /**\n * Initializer for the manager. Must be called prior to use.\n *\n * @param context\n * \t\t\tapplication context\n * @param uniqueName\n * \t\t\tname for the cache location\n * @param cacheSize\n * \t\t\tmax size for the cache\n * @param compressFormat\n * \t\t\tfile type compression format.\n * @param quality\n * compression rate\n */\n public void init(Context context, String uniqueName, int cacheSize, CompressFormat compressFormat, int quality, CacheType type){\n switch (type) {\n case DISK:\n mImageCache= new DiskLruImageCache(context, uniqueName, cacheSize, compressFormat, quality);\n break;\n case MEMORY:\n mImageCache = new BitmapLruImageCache(cacheSize);\n default:\n mImageCache = new BitmapLruImageCache(cacheSize);\n break;\n }\n\n mImageLoader = new ImageLoader(App.getInstance().mRequestQueue, mImageCache);\n }\n\n public Bitmap getBitmap(String url) {\n try {\n return mImageCache.getBitmap(createKey(url));\n } catch (NullPointerException e) {\n throw new IllegalStateException(\"Disk Cache Not initialized\");\n }\n }\n\n public void putBitmap(String url, Bitmap bitmap) {\n try {\n mImageCache.putBitmap(createKey(url), bitmap);\n } catch (NullPointerException e) {\n throw new IllegalStateException(\"Disk Cache Not initialized\");\n }\n }\n\n\n /**\n * \tExecutes and image load\n * @param url\n * \t\tlocation of image\n * @param listener\n * \t\tListener for completion\n */\n public void getImage(String url, ImageListener listener){\n mImageLoader.get(url, listener);\n }\n\n /**\n * \tExecutes and image load\n * @param url\n * \t\tlocation of image\n * @param listener\n * \t\tListener for completion\n */\n public void getImage(String url, final ImageView imageView, final ImageListener listener){\n mImageLoader.get(url, new ImageListener() {\n @Override\n public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {\n if(response.getBitmap() != null) {\n imageView.setImageBitmap(response.getBitmap());\n }\n listener.onResponse(response,isImmediate);\n }\n\n @Override\n public void onErrorResponse(VolleyError error) {\n listener.onErrorResponse(error);\n }\n });\n }\n\n /**\n * @return\n * \t\tinstance of the image loader\n */\n public ImageLoader getImageLoader() {\n return mImageLoader;\n }\n\n /**\n * Creates a unique cache key based on a url value\n * @param url\n * \t\turl to be used in key creation\n * @return\n * \t\tcache key value\n */\n private String createKey(String url){\n return String.valueOf(url.hashCode());\n }\n\n\n}",
"public class DatabaseHelper extends OrmLiteSqliteOpenHelper {\n\n\tprivate static final String DATABASE_NAME = \"emanga.db\";\n\tprivate static final int DATABASE_VERSION = 6;\n\n\tprivate RuntimeExceptionDao<Genre, String> genreRuntimeDao = null;\n private RuntimeExceptionDao<Author, String> authorRuntimeDao = null;\n\tprivate RuntimeExceptionDao<Manga, String> mangaRuntimeDao = null;\n\tprivate RuntimeExceptionDao<GenreManga, String> genremangaRuntimeDao = null;\n private RuntimeExceptionDao<AuthorManga, String> authormangaRuntimeDao = null;\n private RuntimeExceptionDao<Chapter, String> chapterRuntimeDao = null;\n\tprivate RuntimeExceptionDao<Page, String> pageRuntimeDao = null;\n\n\tpublic DatabaseHelper(Context context) {\n\t\tsuper(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);\n\t}\n\n\t/**\n\t * This is called when the database is first created. Usually you should call createTable statements here to create\n\t * the tables that will store your data.\n\t */\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {\n\t\ttry {\n\t\t\tLog.i(DatabaseHelper.class.getName(), \"onCreate\");\n\t\t\tTableUtils.createTable(connectionSource, GenreManga.class);\n\t\t\tTableUtils.createTable(connectionSource, Genre.class);\n TableUtils.createTable(connectionSource, AuthorManga.class);\n TableUtils.createTable(connectionSource, Author.class);\n\t\t\tTableUtils.createTable(connectionSource, Manga.class);\n\t\t\tTableUtils.createTable(connectionSource, Chapter.class);\n TableUtils.createTable(connectionSource, Page.class);\n\t\t\t\n\t\t\t// Table for search using fts3: Ormlite doesn't support it yet\n\t\t\t// The table has same data that cursor manga list on library tab\n if (android.os.Build.VERSION.SDK_INT >= 11) {\n db.execSQL(\"CREATE VIRTUAL TABLE manga_fts USING fts4(_id, title, cover, name)\");\n } else {\n db.execSQL(\"CREATE VIRTUAL TABLE manga_fts USING fts3(_id, title, cover, name)\");\n }\n\t\t\t\n\t\t} catch (SQLException e) {\n\t\t\tLog.e(DatabaseHelper.class.getName(), \"Can't create database\", e);\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t/**\n\t * This is called when your application is upgraded and it has a higher version number. This allows you to adjust\n\t * the various data to match the new version number.\n\t */\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {\n\t\ttry {\n\t\t\tLog.i(DatabaseHelper.class.getName(), \"onUpgrade\");\n\t\t\tTableUtils.dropTable(connectionSource, Page.class, true);\n\t\t\tTableUtils.dropTable(connectionSource, Chapter.class, true);\n\t\t\tTableUtils.dropTable(connectionSource, Manga.class, true);\n\t\t\tTableUtils.dropTable(connectionSource, Genre.class, true);\n\t\t\tTableUtils.dropTable(connectionSource, GenreManga.class, true);\n TableUtils.dropTable(connectionSource, Author.class, true);\n TableUtils.dropTable(connectionSource, AuthorManga.class, true);\n\t\t\t\n\t\t\tdb.execSQL(\"DROP TABLE manga_fts\");\n\t\t\t\n\t\t\t// after we drop the old databases, we create the new ones\n\t\t\tonCreate(db, connectionSource);\n\t\t} catch (SQLException e) {\n\t\t\tLog.e(DatabaseHelper.class.getName(), \"Can't drop databases\", e);\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\t\n\t/**\n\t * Returns the RuntimeExceptionDao, a version of a Dao for our classes. It will\n\t * create it or just give the cached value. \n\t * RuntimeExceptionDao only through RuntimeExceptions.\n\t */\n\tpublic RuntimeExceptionDao<Genre, String> getGenreRunDao() {\n\t\tif (genreRuntimeDao == null)\n\t\t\tgenreRuntimeDao = getRuntimeExceptionDao(Genre.class);\n\t\treturn genreRuntimeDao;\n\t}\n\n public RuntimeExceptionDao<Author, String> getAuthorRunDao() {\n if (authorRuntimeDao == null)\n authorRuntimeDao = getRuntimeExceptionDao(Author.class);\n return authorRuntimeDao;\n }\n\t\n\tpublic RuntimeExceptionDao<Manga, String> getMangaRunDao() {\n\t\tif (mangaRuntimeDao == null) \n\t\t\tmangaRuntimeDao = getRuntimeExceptionDao(Manga.class);\n\t\treturn mangaRuntimeDao;\n\t}\n\n\tpublic RuntimeExceptionDao<GenreManga, String> getGenreMangaRunDao() {\n\t\tif (genremangaRuntimeDao == null)\n\t\t\tgenremangaRuntimeDao = getRuntimeExceptionDao(GenreManga.class);\n\t\treturn genremangaRuntimeDao;\n\t}\n\n public RuntimeExceptionDao<AuthorManga, String> getAuthorMangaRunDao() {\n if (authormangaRuntimeDao == null)\n authormangaRuntimeDao = getRuntimeExceptionDao(AuthorManga.class);\n return authormangaRuntimeDao;\n }\n\t\n\tpublic RuntimeExceptionDao<Chapter, String> getChapterRunDao() {\n\t\tif (chapterRuntimeDao == null) \n\t\t\tchapterRuntimeDao = getRuntimeExceptionDao(Chapter.class);\n\t\treturn chapterRuntimeDao;\n\t}\n\n public RuntimeExceptionDao<Page, String> getPageRunDao() {\n if (pageRuntimeDao == null)\n pageRuntimeDao = getRuntimeExceptionDao(Page.class);\n return pageRuntimeDao;\n }\n\n\t/**\n\t * Close the database connections and clear any cached DAOs.\n\t */\n\t@Override\n\tpublic void close() {\n\t\tsuper.close();\n\t\tgenreRuntimeDao = null;\n\t\tmangaRuntimeDao = null;\n\t\tchapterRuntimeDao = null;\n\t\tpageRuntimeDao = null;\n\t}\n\t\n\tprivate static String mangasWithGenresQuery =\n\t\t\t\"SELECT manga._id, manga.title, manga.cover, GROUP_CONCAT(\" + GenreManga.CATEGORY_COLUMN_NAME + \", ', ')\"\n\t\t\t+ \" AS \" + Genre.NAME_COLUMN_NAME + \" FROM manga\"\n\t\t\t+ \" LEFT OUTER JOIN genremanga ON genremanga.manga_id = manga._id\"\n\t\t\t+ \" GROUP BY manga._id\"\n\t\t\t+ \" ORDER BY manga.title ASC\";\n\t\t\t\n\tpublic Cursor getMangasWithGenres(){\n\t\treturn this.getReadableDatabase().rawQuery(mangasWithGenresQuery, null);\n\t}\n\t\n\t/**\n\t * Repopulate the table of search\n\t */\n\tpublic void updateMangaFTS(){\n\t\tthis.getReadableDatabase().execSQL(\"DELETE FROM manga_fts\");\n\t\tthis.getReadableDatabase().execSQL(\"INSERT INTO manga_fts (_id,title,cover,name)\"\n + \" SELECT manga._id, manga.title, manga.cover, GROUP_CONCAT(genremanga.genre_id, ', ')\"\n\t\t+ \" AS name FROM manga\"\n\t\t+ \" INNER JOIN genremanga ON genremanga.manga_id = manga._id\"\n\t\t+ \" GROUP BY manga._id\"\n\t\t+ \" ORDER BY manga.title ASC\");\n\t\tthis.getReadableDatabase().execSQL(\"INSERT INTO manga_fts(manga_fts) VALUES(?)\", new String[]{\"optimize\"});\n\t\t\t\t\n\t}\n\n public String lastMangaDate(){\n Cursor cursor = this.getReadableDatabase().rawQuery(\n \"SELECT MAX(\" + Manga.DATE_COLUMN_NAME + \") AS last FROM manga\", null);\n cursor.moveToFirst();\n String date = cursor.getString(cursor.getColumnIndex(\"last\"));\n cursor.close();\n return date != null? date : \"\";\n }\n\n public String lastChapterDate(){\n Cursor cursor = this.getReadableDatabase().rawQuery(\n \"SELECT MAX(\" + Chapter.DATE_COLUMN_NAME + \") AS last FROM chapter\", null);\n cursor.moveToFirst();\n String date = cursor.getString(cursor.getColumnIndex(\"last\"));\n cursor.close();\n return date != null? date : \"\";\n }\n\n\tpublic Cursor searchOnLibrary(String text){\n if(text.length() == 0)\n return this.getReadableDatabase().rawQuery(\"SELECT * FROM manga_fts\", null);\n else\n return this.getReadableDatabase().rawQuery(\n \"SELECT * FROM manga_fts WHERE manga_fts MATCH ?\", new String[]{text + \"*\"});\n\n\t}\n\n\tpublic void saveMangas(final Manga[] mangas){\n\t\tfinal RuntimeExceptionDao<Manga, String> mangaDao = getMangaRunDao();\n final RuntimeExceptionDao<Chapter, String> chapterDao = getChapterRunDao();\n\t\tfinal RuntimeExceptionDao<Genre, String> genreDao = getGenreRunDao();\n\t\tfinal RuntimeExceptionDao<GenreManga, String> genremangaDao = getGenreMangaRunDao();\n final RuntimeExceptionDao<Author, String> authorDao = getAuthorRunDao();\n final RuntimeExceptionDao<AuthorManga, String> authormangaDao = getAuthorMangaRunDao();\n\n\t\tmangaDao.callBatchTasks(\n\t\t\t\tnew Callable<Void>(){\n\t\t\t\t\tpublic Void call() throws Exception {\n\t\t\t\t\t\tfor(Manga m : mangas){\n\t\t\t\t\t\t\tmangaDao.createIfNotExists(m);\n if(m.chapters != null){\n for(Chapter c: m.chapters){\n c.manga = m;\n chapterDao.createIfNotExists(c);\n }\n }\n\t\t\t\t\t\t\tif(m.genres != null){\n\t\t\t\t\t\t\t\tfor(Genre g : m.genres) {\n\t\t\t\t\t\t\t\t\tgenreDao.createIfNotExists(g);\n\t\t\t\t\t\t\t\t\tgenremangaDao.createIfNotExists(new GenreManga(g,m));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n if(m.authors != null){\n for(Author a : m.authors){\n authorDao.createIfNotExists(a);\n authormangaDao.createIfNotExists(new AuthorManga(a,m));\n }\n }\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t}\n\n public void save(final Manga m){\n final RuntimeExceptionDao<Manga, String> dao = getMangaRunDao();\n dao.createOrUpdate(m);\n }\n\n private PreparedQuery<Genre> genresForMangaQuery = null;\n\n public List<Genre> genresForManga(Manga manga) throws SQLException{\n if (genresForMangaQuery == null) {\n genresForMangaQuery = makeGenresForMangaQuery();\n }\n genresForMangaQuery.setArgumentHolderValue(0, manga);\n return genreRuntimeDao.query(genresForMangaQuery);\n }\n\n public void genresForMangas(List<Manga> mangas){\n Iterator<Manga> it = mangas.iterator();\n while(it.hasNext()){\n Manga m = it.next();\n try {\n m.genres = genresForManga(m);\n } catch(SQLException e){\n e.printStackTrace();\n }\n }\n }\n\n /**\n * Build our query for Genre objects that match a Manga.\n */\n private PreparedQuery<Genre> makeGenresForMangaQuery() throws SQLException {\n\n QueryBuilder<GenreManga, String> mangaGenreQb = getGenreMangaRunDao().queryBuilder();\n mangaGenreQb.selectColumns(GenreManga.CATEGORY_COLUMN_NAME);\n SelectArg userSelectArg = new SelectArg();\n mangaGenreQb.where().eq(GenreManga.MANGA_COLUMN_NAME, userSelectArg);\n\n QueryBuilder<Genre, String> genreQb = getGenreRunDao().queryBuilder();\n genreQb.where().in(Genre.NAME_COLUMN_NAME, mangaGenreQb);\n\n return genreQb.prepare();\n }\n\n}",
"public class CoverListener implements ImageLoader.ImageListener {\n private String TAG = CoverListener.class.getSimpleName();\n\n private Manga mManga;\n private HashSet<String> mUrlError;\n private int mRetries = 3;\n private ImageView mImageView;\n\n public CoverListener(Manga manga, ImageView imageView){\n mManga = manga;\n mImageView = imageView;\n }\n\n public CoverListener(Manga manga, ImageView imageView, int retries){\n this(manga,imageView);\n mRetries = retries;\n }\n\n public CoverListener(String url, ImageView imageView){\n this(searchMangaByCover(url),imageView);\n }\n\n private static Manga searchMangaByCover(String cover){\n\n DatabaseHelper dbs = OpenHelperManager.getHelper(\n App.getInstance().getApplicationContext(),\n DatabaseHelper.class);\n Manga manga = null;\n try {\n manga = dbs.getMangaRunDao().queryBuilder().where().eq(Manga.COVER_COLUMN_NAME, cover)\n .queryForFirst();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n OpenHelperManager.releaseHelper();\n }\n\n return manga;\n }\n\n @Override\n public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {\n }\n\n @Override\n public void onErrorResponse(VolleyError error) {\n final CoverListener listenerReference = this;\n new AsyncTask<Void,Void,Void>(){\n\n @Override\n protected Void doInBackground(Void... voids) {\n if(mManga != null) {\n if (mUrlError == null) {\n mUrlError = new HashSet<String>(3);\n }\n\n mUrlError.add(mManga.cover);\n\n if (mRetries > 0) {\n Log.d(TAG, \"Cover: \" + mManga.cover + \"\\nAsk to: \" + Internet.HOST + \"manga/\" + mManga._id + \"/cover?\" + Internet.arrayParams(mUrlError, \"e\"));\n App.getInstance().addToRequestQueue(\n new MangaRequest(\n JsonRequest.Method.GET,\n Internet.HOST + \"manga/\" + mManga._id + \"/cover?\" + Internet.arrayParams(mUrlError, \"e\"),\n new Response.Listener<Manga>() {\n @Override\n public void onResponse(Manga response) {\n Log.d(TAG, response.toString());\n if (response.cover != null) {\n Log.d(TAG, \"New cover received: \" + response.title + \" \" + response.cover);\n mManga.cover = response.cover;\n\n // Reload image\n ImageCacheManager.getInstance().getImage(mManga.cover, mImageView, listenerReference);\n\n // Update database\n DatabaseHelper dbs = OpenHelperManager.getHelper(\n App.getInstance().getApplicationContext(),\n DatabaseHelper.class);\n dbs.getMangaRunDao().update(mManga);\n OpenHelperManager.releaseHelper();\n } else {\n Log.d(TAG, \"There aren't new covers for: \" + mManga.title);\n }\n }\n },\n null\n ),\n \"New Cover\"\n );\n mRetries--;\n } else {\n Log.d(TAG, \"Reached maximum intents number for ask a new cover with: \" + mManga.cover);\n }\n }\n return null;\n }\n\n }.execute();\n }\n}",
"@DatabaseTable\npublic class Genre implements Parcelable {\n\n\tpublic static final String NAME_COLUMN_NAME = \"name\";\n\n\t@DatabaseField(id = true, columnName = NAME_COLUMN_NAME)\n\tpublic String name;\n\t\n\tpublic Genre() {\n\t\t// needed by ormlite\n\t}\n\n public Genre(Parcel p){\n name = p.readString();\n }\n\t\n\tpublic Genre(String title) {\n\t\tname = title.toLowerCase(Locale.ENGLISH);\n\t}\n\n\t@Override\n\tpublic String toString(){\n\t\treturn Character.toUpperCase(name.charAt(0)) + name.substring(1);\n\t}\n\n public static final Parcelable.Creator<Genre> CREATOR = new Creator<Genre>() {\n @Override\n public Genre createFromParcel(Parcel p){\n return new Genre(p);\n }\n\n @Override\n public Genre[] newArray(int size) {\n return new Genre[size];\n }\n };\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel p, int i) {\n p.writeString(name);\n }\n}",
"@JsonDeserialize(using = MangaDeserializer.class)\n@DatabaseTable\npublic class Manga implements Parcelable{\n public static final String MODEL_NAME = \"manga\";\n\tpublic static final String ID_COLUMN_NAME = \"_id\";\n\tpublic static final String TITLE_COLUMN_NAME = \"title\";\n\tpublic static final String COVER_COLUMN_NAME = \"cover\";\n\tpublic static final String DESCRIPTION_COLUMN_NAME = \"summary\";\n public static final String DATE_COLUMN_NAME = \"created_at\";\n public static final String MODIFY_COLUMN_NAME = \"modified_at\";\n public static final String CHAPTERS_COLUMN_NAME = \"chapters\";\n public static final String NUMBER_CHAPTERS_COLUMN_NAME = \"number_chapters\";\n public static final String FAVOURITE_COLUMN_NNAME = \"manga\";\n\n @DatabaseField(id = true, columnName = ID_COLUMN_NAME)\n public String _id;\n\t@DatabaseField(columnName = TITLE_COLUMN_NAME)\n\tpublic String title;\n @DatabaseField(columnName = COVER_COLUMN_NAME)\n @JsonProperty(\"covers\")\n public String cover;\n\t@DatabaseField(columnName = DESCRIPTION_COLUMN_NAME)\n\tpublic String summary;\n @DatabaseField(columnName = DATE_COLUMN_NAME)\n public Date created_at;\n @DatabaseField(columnName = MODIFY_COLUMN_NAME)\n public Date modified_at;\n\t@ForeignCollectionField(columnName = CHAPTERS_COLUMN_NAME)\n\tpublic Collection<Chapter> chapters;\n @DatabaseField(columnName = NUMBER_CHAPTERS_COLUMN_NAME)\n public int numberChapters;\n @DatabaseField(columnName = FAVOURITE_COLUMN_NNAME)\n public boolean favourite = false;\n\n\t\n\t// Handle genres for N - N relationship in GenreManga\n\tpublic List<Genre> genres;\n\n // Handle authors for N - N relationship in AuthorManga\n public List<Author> authors;\n\t\n\tpublic Manga() {\n\t\t// needed by ormlite\n\t}\n\n public Manga(Parcel p){\n this._id = p.readString();\n this.title = p.readString();\n this.cover = p.readString();\n this.summary = p.readString();\n this.created_at = new Date(p.readLong());\n this.modified_at = new Date(p.readLong());\n // this.chapters = unparcelCollection(p, Chapter.CREATOR);\n // p.readList(this.genres, Genre.class.getClassLoader());\n }\n\n public Manga(String _id, String title, String cover, Date created_at, Date modified_at){\n this._id = _id;\n this.title = title != null? title.replaceAll(\"[^a-zñ0-9 ]\",\"\") : null;\n this.cover = cover;\n this.created_at = created_at;\n this.modified_at = modified_at;\n this.numberChapters = 0;\n }\n\n\tpublic Manga(String _id, String title, String cover, String summary, Date created_at,\n Date modified_at, List<Genre> genres) {\n this(_id, title, cover, created_at, modified_at);\n this.summary = summary;\n\t\tthis.genres = genres;\n\t}\n\n public Manga(String _id, String title, List<Author> authors, String cover, String summary,\n Date created_at, Date modified_at, List<Genre> genres, int nChapters){\n this(_id, title, cover, summary, created_at, modified_at, genres);\n this.numberChapters = nChapters;\n this.authors = authors;\n }\n\n public String toString(){\n return _id + \"\\n\"\n + ((title != null)? title + \"\\n\": \"\")\n + ((cover != null)? cover + \"\\n\": \"\")\n + ((summary != null)? summary + \"\\n\": \"\")\n + ((created_at != null)? created_at.toString() + \"\\n\": \"\")\n + ((genres != null)? genres: \"\") + \"\\n\"\n + numberChapters + \"\\n\";\n }\n\n public static final Parcelable.Creator<Manga> CREATOR = new Creator<Manga>() {\n @Override\n public Manga createFromParcel(Parcel p){\n return new Manga(p);\n }\n\n @Override\n public Manga[] newArray(int size) {\n return new Manga[size];\n }\n };\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel p, int i) {\n p.writeString(_id);\n p.writeString(title);\n p.writeString(cover);\n p.writeString(summary);\n if(created_at != null)\n p.writeLong(created_at.getTime());\n if(modified_at != null)\n p.writeLong(modified_at.getTime());\n // parcelCollection(p, null);\n // p.writeList(genres);\n }\n\n protected final static <T extends Chapter> void parcelCollection(final Parcel out, final Collection<T> collection) {\n if (collection != null) {\n out.writeInt(collection.size());\n out.writeTypedList(new ArrayList<T>(collection));\n } else {\n out.writeInt(-1);\n }\n }\n\n protected final static <T extends Chapter> Collection<T> unparcelCollection(final Parcel in, final Creator<T> creator) {\n final int size = in.readInt();\n if (size >= 0) {\n final List<T> list = new ArrayList<T>(size);\n in.readTypedList(list, creator);\n return list;\n } else {\n return null;\n }\n }\n}",
"public class CustomNetworkImageView extends ImageView {\n /** The URL of the network image to load */\n protected String mUrl;\n\n /**\n * Resource ID of the image to be used as a placeholder until the network image is loaded.\n */\n protected int mDefaultImageId;\n\n /**\n * Resource ID of the image to be used if the network response fails.\n */\n protected int mErrorImageId;\n\n /** Local copy of the ImageLoader. */\n protected ImageLoader mImageLoader;\n\n /** Local copy of the ImageListener */\n private ImageLoader.ImageListener mListener;\n\n /** Current ImageContainer. (either in-flight or finished) */\n protected ImageLoader.ImageContainer mImageContainer;\n\n public CustomNetworkImageView(Context context) {\n this(context, null);\n }\n\n public CustomNetworkImageView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public CustomNetworkImageView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n }\n\n /**\n * Sets URL of the image that should be loaded into this view. Note that calling this will\n * immediately either set the cached image (if available) or the default image specified by\n * {@link CustomNetworkImageView#setDefaultImageResId(int)} on the view.\n *\n * NOTE: If applicable, {@link CustomNetworkImageView#setDefaultImageResId(int)} and\n * {@link CustomNetworkImageView#setErrorImageResId(int)} should be called prior to calling\n * this function.\n *\n * @param url The URL that should be loaded into this ImageView.\n * @param imageLoader ImageLoader that will be used to make the request.\n */\n public void setImageUrl(String url, ImageLoader imageLoader, ImageLoader.ImageListener listener) {\n mUrl = url;\n mImageLoader = imageLoader;\n mListener = listener;\n // The URL has potentially changed. See if we need to load it.\n loadImageIfNecessary(false, listener);\n }\n\n public void setImageUrl(String url, ImageLoader imageLoader) {\n mUrl = url;\n mImageLoader = imageLoader;\n // The URL has potentially changed. See if we need to load it.\n loadImageIfNecessary(false);\n }\n\n /**\n * Sets the default image resource ID to be used for this view until the attempt to load it\n * completes.\n */\n public void setDefaultImageResId(int defaultImage) {\n mDefaultImageId = defaultImage;\n }\n\n /**\n * Sets the error image resource ID to be used for this view in the event that the image\n * requested fails to load.\n */\n public void setErrorImageResId(int errorImage) {\n mErrorImageId = errorImage;\n }\n\n /**\n * Loads the image for the view if it isn't already loaded.\n * @param isInLayoutPass True if this was invoked from a layout pass, false otherwise.\n */\n void loadImageIfNecessary(final boolean isInLayoutPass) {\n loadImageIfNecessary(isInLayoutPass, null);\n }\n\n /**\n * Loads the image for the view if it isn't already loaded.\n * @param isInLayoutPass True if this was invoked from a layout pass, false otherwise.\n */\n void loadImageIfNecessary(final boolean isInLayoutPass, final ImageLoader.ImageListener listener) {\n int width = getWidth();\n int height = getHeight();\n\n boolean wrapWidth = false, wrapHeight = false;\n if (getLayoutParams() != null) {\n wrapWidth = getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT;\n wrapHeight = getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT;\n }\n\n // if the view's bounds aren't known yet, and this is not a wrap-content/wrap-content\n // view, hold off on loading the image.\n boolean isFullyWrapContent = wrapWidth && wrapHeight;\n if (width == 0 && height == 0 && !isFullyWrapContent) {\n return;\n }\n\n // if the URL to be loaded in this view is empty, cancel any old requests and clear the\n // currently loaded image.\n if (TextUtils.isEmpty(mUrl)) {\n if (mImageContainer != null) {\n mImageContainer.cancelRequest();\n mImageContainer = null;\n }\n setDefaultImageOrNull();\n return;\n }\n\n // if there was an old request in this view, check if it needs to be canceled.\n if (mImageContainer != null && mImageContainer.getRequestUrl() != null) {\n if (mImageContainer.getRequestUrl().equals(mUrl)) {\n // if the request is from the same URL, return.\n return;\n } else {\n // if there is a pre-existing request, cancel it if it's fetching a different URL.\n mImageContainer.cancelRequest();\n setDefaultImageOrNull();\n }\n }\n\n // Calculate the max image width / height to use while ignoring WRAP_CONTENT dimens.\n int maxWidth = wrapWidth ? 0 : width;\n int maxHeight = wrapHeight ? 0 : height;\n\n // The pre-existing content of this view didn't match the current URL. Load the new image\n // from the network.\n // ImageLoader.ImageContainer newContainer = mImageLoader.get(mUrl, listener, maxWidth, maxHeight);\n\n // The pre-existing content of this view didn't match the current URL. Load the new image\n // from the network.\n ImageLoader.ImageContainer newContainer = mImageLoader.get(mUrl,\n new ImageLoader.ImageListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n if (mErrorImageId != 0) {\n setImageResource(mErrorImageId);\n }\n\n if (listener != null){\n listener.onErrorResponse(error);\n }\n }\n\n @Override\n public void onResponse(final ImageLoader.ImageContainer response, final boolean isImmediate) {\n // If this was an immediate response that was delivered inside of a layout\n // pass do not set the image immediately as it will trigger a requestLayout\n // inside of a layout. Instead, defer setting the image by posting back to\n // the main thread.\n\n if(isImmediate && isInLayoutPass) {\n post(new Runnable() {\n @Override\n public void run() {\n onResponse(response, false);\n }\n });\n return ;\n }\n\n if(response.getBitmap() != null) {\n setImageBitmap(response.getBitmap());\n } else if(mDefaultImageId!=0) {\n setImageResource(mDefaultImageId);\n }\n\n if(listener != null) {\n listener.onResponse(response, isImmediate);\n }\n }\n }, maxWidth, maxHeight);\n\n // update the ImageContainer to be the new bitmap container.\n mImageContainer = newContainer;\n\n // update the ImageContainer to be the new bitmap container.\n mImageContainer = newContainer;\n }\n\n private void setDefaultImageOrNull() {\n if(mDefaultImageId != 0) {\n setImageResource(mDefaultImageId);\n }\n else {\n setImageBitmap(null);\n }\n }\n\n @Override\n protected void onLayout(boolean changed, int left, int top, int right, int bottom) {\n super.onLayout(changed, left, top, right, bottom);\n loadImageIfNecessary(true);\n }\n\n @Override\n protected void onDetachedFromWindow() {\n if (mImageContainer != null) {\n // If the view was bound to an image request, cancel it and clear\n // out the image from the view.\n mImageContainer.cancelRequest();\n setImageBitmap(null);\n // also clear out the container so we can reload the image if necessary.\n mImageContainer = null;\n }\n super.onDetachedFromWindow();\n }\n\n @Override\n protected void drawableStateChanged() {\n super.drawableStateChanged();\n invalidate();\n }\n}"
] | import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AlphabetIndexer;
import android.widget.BaseAdapter;
import android.widget.SectionIndexer;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.emanga.emanga.app.R;
import com.emanga.emanga.app.cache.ImageCacheManager;
import com.emanga.emanga.app.database.DatabaseHelper;
import com.emanga.emanga.app.listeners.CoverListener;
import com.emanga.emanga.app.models.Genre;
import com.emanga.emanga.app.models.Manga;
import com.emanga.emanga.app.utils.CustomNetworkImageView;
import com.j256.ormlite.android.AndroidDatabaseResults;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import org.apache.commons.lang.WordUtils;
import java.sql.SQLException;
import java.util.List; | package com.emanga.emanga.app.adapters;
/**
* Created by Ciro on 25/05/2014.
*/
public class MangaItemListAdapter extends BaseAdapter implements SectionIndexer{
private static String sections = " -0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private AlphabetIndexer mAlphabetIndexer;
private Context mContext;
private ImageLoader mImageLoader;
private DatabaseHelper databaseHelper;
private CloseableIterator<Manga> itMangas;
private AndroidDatabaseResults mMangas;
private PreparedQuery<Manga> mangaQuery = null;
public MangaItemListAdapter(Context context){
super();
mContext = context;
mImageLoader = ImageCacheManager.getInstance().getImageLoader();
databaseHelper = OpenHelperManager.getHelper(mContext, DatabaseHelper.class);
try{
mangaQuery = makeMangasQuery();
reload();
} catch (SQLException e){
e.printStackTrace();
}
}
private PreparedQuery<Manga> makeMangasQuery() throws SQLException {
QueryBuilder<Manga,String> mangaQb = databaseHelper.getMangaRunDao().queryBuilder();
mangaQb.orderBy(Manga.TITLE_COLUMN_NAME, true);
return mangaQb.prepare();
}
public void reload(){
if(itMangas != null){
itMangas.closeQuietly();
}
try{
itMangas = databaseHelper.getMangaRunDao().iterator(mangaQuery);
mMangas = (AndroidDatabaseResults) itMangas.getRawResults();
mAlphabetIndexer = new AlphabetIndexer(mMangas.getRawCursor(),
mMangas.findColumn(Manga.TITLE_COLUMN_NAME), sections);
} catch (SQLException e){
e.printStackTrace();
}
}
public void destroy(){
if(databaseHelper != null) {
OpenHelperManager.releaseHelper();
databaseHelper = null;
}
if(itMangas != null){
itMangas.closeQuietly();
itMangas = null;
mMangas = null;
}
}
@Override
public int getPositionForSection(int section) {
return mAlphabetIndexer.getPositionForSection(section);
}
@Override
public int getSectionForPosition(int position) {
return mAlphabetIndexer.getSectionForPosition(position);
}
@Override
public Object[] getSections() {
String[] sectionsArr = new String[sections.length()];
for (int i=0; i < sections.length(); i++)
sectionsArr[i] = "" + sections.charAt(i);
return sectionsArr;
}
@Override
public int getCount() {
return mMangas.getCount();
}
@Override
public Manga getItem(int position) {
mMangas.moveAbsolute(position);
try {
return itMangas.current();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
Manga manga = getItem(position);
// if it's not recycled, initialize some attributes
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.manga_item_list, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.manga_list_title);
holder.cover = (CustomNetworkImageView) convertView.findViewById(R.id.manga_list_cover);
holder.categories = (TextView) convertView.findViewById(R.id.manga_list_categories);
holder.cover.setErrorImageResId(R.drawable.empty_cover);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(manga.title.toUpperCase());
new AsyncTask<Manga, Void, Manga>(){
@Override
protected Manga doInBackground(Manga... manga) {
try {
manga[0].genres = databaseHelper.genresForManga(manga[0]);
} catch (SQLException e) {
e.printStackTrace();
}
return manga[0];
}
@Override
protected void onPostExecute(Manga manga){
holder.categories.setText(manga.genres != null? MangaItemListAdapter.toString(manga.genres) : "");
}
}.execute(manga);
| holder.cover.setImageUrl(manga.cover, mImageLoader, new CoverListener(manga.cover, holder.cover)); | 2 |
cdancy/artifactory-rest | src/test/java/com/cdancy/artifactory/rest/features/ArtifactApiLiveTest.java | [
"public static void assertFalse(boolean value) {\n assertThat(value).isFalse();\n}",
"public static void assertNotNull(Object value) {\n assertThat(value).isNotNull();\n}",
"public static void assertTrue(boolean value) {\n assertThat(value).isTrue();\n}",
"@Test(groups = \"live\")\npublic class BaseArtifactoryApiLiveTest extends BaseApiLiveTest<ArtifactoryApi> {\n protected final ArtifactoryAuthentication artifactoryAuthentication;\n\n public BaseArtifactoryApiLiveTest() {\n provider = \"artifactory\";\n this.artifactoryAuthentication = TestUtilities.inferTestAuthentication();\n }\n\n @Override\n protected Iterable<Module> setupModules() {\n final ArtifactoryAuthenticationModule credsModule = new ArtifactoryAuthenticationModule(this.artifactoryAuthentication);\n return ImmutableSet.<Module> of(getLoggingModule(), credsModule);\n }\n\n @Override\n protected Properties setupProperties() {\n Properties overrides = super.setupProperties();\n overrides.setProperty(Constants.PROPERTY_MAX_RETRIES, \"0\");\n return overrides;\n }\n\n public String randomUUID() {\n return UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n }\n\n public String randomPath() {\n return UUID.randomUUID().toString().replaceAll(\"-\", \"/\");\n }\n\n public String randomString() {\n char[] chars = \"abcdefghijklmnopqrstuvwxyz\".toCharArray();\n StringBuilder sb = new StringBuilder();\n Random random = new Random();\n for (int i = 0; i < 10; i++) {\n char c = chars[random.nextInt(chars.length)];\n sb.append(c);\n }\n return sb.toString();\n }\n\n public File randomFile() {\n File randomFile = null;\n PrintWriter writer = null;\n try {\n randomFile = new File(System.getProperty(\"java.io.tmpdir\"), randomUUID() + \".txt\");\n if (!randomFile.createNewFile()) {\n throw new RuntimeException(\"Could not create temporary file at \" + randomFile.getAbsolutePath());\n }\n\n writer = new PrintWriter(randomFile, \"UTF-8\");\n writer.println(\"Hello, World!\");\n writer.close();\n } catch (IOException e) {\n if (randomFile != null) {\n randomFile.delete();\n }\n throw Throwables.propagate(e);\n } finally {\n if (writer != null)\n writer.close();\n }\n return randomFile;\n }\n\n public static String getFileChecksum(MessageDigest digest, File file) throws IOException {\n //Get file input stream for reading the file content\n FileInputStream fis = new FileInputStream(file);\n\n //Create byte array to read data in chunks\n byte[] byteArray = new byte[1024];\n int bytesCount = 0;\n\n //Read file data and update in message digest\n while ((bytesCount = fis.read(byteArray)) != -1) {\n digest.update(byteArray, 0, bytesCount);\n };\n\n //close the stream; We don't need it now.\n fis.close();\n\n //Get the hash's bytes\n byte[] bytes = digest.digest();\n\n //This bytes[] has bytes in decimal format;\n //Convert it to hexadecimal format\n StringBuilder sb = new StringBuilder();\n for(int i=0; i< bytes.length ;i++) {\n sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));\n }\n\n //return complete hash\n return sb.toString();\n }\n}",
"@AutoValue\npublic abstract class Artifact {\n\n public abstract String uri();\n\n @Nullable\n public abstract String downloadUri();\n\n @Nullable\n public abstract String repo();\n\n @Nullable\n public abstract String path();\n\n @Nullable\n public abstract String remoteUrl();\n\n @Nullable\n public abstract String created();\n\n @Nullable\n public abstract String createdBy();\n\n public abstract String size();\n\n @Nullable\n public abstract String lastModified();\n\n @Nullable\n public abstract String modifiedBy();\n\n @Nullable\n public abstract String folder();\n\n @Nullable\n public abstract String mimeType();\n\n @Nullable\n public abstract CheckSum checksums();\n\n @Nullable\n public abstract CheckSum originalChecksums();\n\n Artifact() {\n }\n\n @SerializedNames({ \"uri\", \"downloadUri\", \"repo\", \"path\", \"remoteUrl\", \"created\", \"createdBy\",\n \"size\", \"lastModified\", \"modifiedBy\", \"folder\", \"mimeType\", \"checksums\", \"originalChecksums\" })\n public static Artifact create(String uri, String downloadUri, String repo,\n String path, String remoteUrl, String created, String createdBy,\n String size, String lastModified, String modifiedBy, String folder,\n String mimeType, CheckSum checksums, CheckSum originalChecksums) {\n return new AutoValue_Artifact(uri, downloadUri, repo, path, remoteUrl,\n created, createdBy, size, lastModified, modifiedBy,\n folder, mimeType, checksums, originalChecksums);\n }\n}",
"@AutoValue\npublic abstract class RequestStatus {\n\n public abstract List<Message> messages();\n\n public abstract List<Error> errors();\n\n RequestStatus() {\n }\n\n @SerializedNames({ \"messages\", \"errors\" })\n public static RequestStatus create(List<Message> messages, List<Error> errors) {\n return new AutoValue_RequestStatus(messages != null ? ImmutableList.copyOf(messages) : ImmutableList.<Message>of(),\n errors != null ? ImmutableList.copyOf(errors) : ImmutableList.<Error>of());\n }\n}"
] | import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static com.cdancy.artifactory.rest.TestUtilities.assertFalse;
import static com.cdancy.artifactory.rest.TestUtilities.assertNotNull;
import static com.cdancy.artifactory.rest.TestUtilities.assertTrue;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.cdancy.artifactory.rest.BaseArtifactoryApiLiveTest;
import com.cdancy.artifactory.rest.domain.artifact.Artifact;
import com.cdancy.artifactory.rest.domain.error.RequestStatus;
import com.google.common.collect.Lists;
import org.jclouds.io.Payloads; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cdancy.artifactory.rest.features;
@Test(groups = "live", testName = "ArtifactApiLiveTest")
public class ArtifactApiLiveTest extends BaseArtifactoryApiLiveTest {
private File tempArtifact;
private String repoKey = "libs-snapshot-local";
private String repoReleaseKey = "ext-snapshot-local";
private String itemPath;
private String itemPathWithProperties;
private Map<String, List<String>> itemProperties = new HashMap<>();
@BeforeClass
public void testInitialize() {
tempArtifact = randomFile();
itemPath = randomPath();
itemPathWithProperties = randomPath();
itemProperties.put("key1", Lists.newArrayList("value1"));
itemProperties.put("key2", Lists.newArrayList("value2"));
itemProperties.put("key3", Lists.newArrayList("value3"));
}
@Test
public void testDeployArtifact() {
Artifact artifact = api().deployArtifact(repoKey, itemPath + "/" + tempArtifact.getName(),
Payloads.newPayload(tempArtifact), null);
assertNotNull(artifact); | assertTrue(artifact.repo().equals(repoKey)); | 2 |
tobyweston/tempus-fugit | src/test/java/com/google/code/tempusfugit/concurrency/AbstractConcurrentTestRunnerTest.java | [
"public interface Condition {\n boolean isSatisfied();\n}",
"protected final static int CONCURRENT_COUNT = 3;",
"public static Duration seconds(long seconds) {\n validate(seconds, TimeUnit.SECONDS);\n return new Duration(seconds, TimeUnit.SECONDS);\n}",
"public static Timeout timeout(Duration duration) {\n return new Timeout(duration);\n}",
"public static void waitOrTimeout(Condition condition, Timeout timeout) throws InterruptedException, TimeoutException {\n waitOrTimeout(condition, timeout, new ThreadSleep(SLEEP_PERIOD));\n}"
] | import static java.util.Collections.synchronizedSet;
import static junit.framework.Assert.fail;
import com.google.code.tempusfugit.concurrency.annotations.Concurrent;
import com.google.code.tempusfugit.temporal.Condition;
import junit.framework.AssertionFailedError;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import static com.google.code.tempusfugit.concurrency.AbstractConcurrentTestRunnerTest.CONCURRENT_COUNT;
import static com.google.code.tempusfugit.temporal.Duration.seconds;
import static com.google.code.tempusfugit.temporal.Timeout.timeout;
import static com.google.code.tempusfugit.temporal.WaitFor.waitOrTimeout; | /*
* Copyright (c) 2009-2018, toby weston & tempus-fugit committers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.code.tempusfugit.concurrency;
@RunWith(ConcurrentTestRunner.class)
@Concurrent(count = CONCURRENT_COUNT)
public abstract class AbstractConcurrentTestRunnerTest {
protected final static int CONCURRENT_COUNT = 3;
protected static final Set<String> THREADS = synchronizedSet(new HashSet<>());
@Test
public void shouldRunInParallel1() throws TimeoutException, InterruptedException {
logCurrentThread();
}
@Test
public void shouldRunInParallel2() throws TimeoutException, InterruptedException {
logCurrentThread();
}
@Test
public void shouldRunInParallel3() throws TimeoutException, InterruptedException {
logCurrentThread();
}
@Test
public void shouldRunInParallel4() throws TimeoutException, InterruptedException {
logCurrentThread();
}
@Test
public void shouldRunInParallel5() throws TimeoutException, InterruptedException {
logCurrentThread();
}
private void logCurrentThread() throws TimeoutException, InterruptedException {
THREADS.add(Thread.currentThread().getName());
waitToForceCachedThreadPoolToCreateNewThread();
}
private void waitToForceCachedThreadPoolToCreateNewThread() throws InterruptedException, TimeoutException { | waitOrTimeout(() -> THREADS.size() == getConcurrentCount(), timeout(seconds(1))); | 2 |
52North/SensorPlanningService | 52n-sps-api/src/test/java/org/n52/sps/util/nodb/InMemorySensorConfigurationRepositoryTest.java | [
"public abstract class SensorPlugin implements ResultAccessAvailabilityDescriptor, ResultAccessServiceReference {\r\n\r\n protected SensorConfiguration configuration;\r\n\r\n protected SensorTaskService sensorTaskService;\r\n \r\n protected SensorPlugin() {\r\n // allow default constructor for decoration\r\n }\r\n\r\n public SensorPlugin(SensorTaskService sensorTaskService, SensorConfiguration configuration) throws InternalServiceException {\r\n this.configuration = configuration;\r\n this.sensorTaskService = sensorTaskService;\r\n sensorTaskService.setProcedure(this);\r\n }\r\n\r\n public final String getProcedure() {\r\n return configuration.getProcedure();\r\n }\r\n\r\n public SensorTaskService getSensorTaskService() {\r\n return sensorTaskService;\r\n }\r\n\r\n public void setSensorTaskService(SensorTaskService sensorTaskService) {\r\n this.sensorTaskService = sensorTaskService;\r\n }\r\n\r\n /**\r\n * Delegate submit tasking request to sensor instance for execution. The execution can fail for many\r\n * reasons so implementors may consider exception handling by adding each occuring exception to the passed\r\n * {@link OwsExceptionReport} which will be thrown by the SPS framework afterwards.<br>\r\n * <br>\r\n * A {@link SensorTask} instance shall be created by the plugin's {@link SensorTaskService} which takes\r\n * care of storing the task instance into the SPS's {@link SensorTaskRepository}. Once a sensor task is\r\n * created, the task service can be used to continously update the task within the underlying\r\n * {@link SensorTaskRepository}.\r\n * \r\n * @param submit\r\n * the tasking request\r\n * @param owsExceptionReport\r\n * a container collecting {@link OwsException}s to be thrown together as OWS Exception Report\r\n * (according to chapter 8 of [OGC 06-121r3]).\r\n * @return a SensorTask instance as a result of the Submit task\r\n * @throws OwsException\r\n * if an OwsException is thrown without execption reporting intent.\r\n */\r\n public abstract SensorTask submit(SubmitTaskingRequest submit, OwsExceptionReport owsExceptionReport) throws OwsException;\r\n\r\n /*\r\n * Let the SPS manage this kinds of functionality! Extend SensorPlugin interface only with those \r\n * kind of methods a SensorPlugin implementation can provide only!\r\n * \r\n * TODO add abstract getUpdateDescription mehthod\r\n * TODO add abstract cancel mehod\r\n * TODO add abstract feasibility method\r\n * TODO add abstract reservation methods\r\n * TODO add absrtact update methods\r\n */\r\n\r\n /**\r\n * Qualifies sensor's tasking characteristics accordingly. <br>\r\n * <br>\r\n * The SPS has to ask a {@link SensorPlugin} instance for a full qualified data component describing its\r\n * tasking parameters (e.g. AbstractDataComponentType must be qualified to a concrete type implementation\r\n * like DataRecordType). Implementors can make use of\r\n * {@link XMLBeansTools#qualifySubstitutionGroup(org.apache.xmlbeans.XmlObject, javax.xml.namespace.QName)}\r\n * <br>\r\n * <b>Example:</b>\r\n * \r\n * <pre>\r\n * {@code\r\n * public void getQualifiedDataComponent(AbstractDataComponentType componentToQualify) {\r\n * QName qname = new QName(\"http://www.opengis.net/swe/2.0\", \"DataRecord\");\r\n * XMLBeansTools.qualifySubstitutionGroup(componentToQualify, qname);\r\n * }\r\n * </pre>\r\n * \r\n * @param the\r\n * abstract data component to qualify\r\n */\r\n public abstract void qualifyDataComponent(AbstractDataComponentType componentToQualify);\r\n \r\n public abstract Availability getResultAccessibilityFor(SensorTask sensorTask);\r\n\r\n public String getSensorPluginType() {\r\n return configuration.getSensorPluginType();\r\n }\r\n\r\n public SensorConfiguration getSensorConfiguration() {\r\n return configuration;\r\n }\r\n\r\n public ResultAccessDataServiceReference getResultAccessDataServiceReference() {\r\n return configuration.getResultAccessDataService();\r\n }\r\n\r\n public SensorConfiguration mergeSensorConfigurations(SensorConfiguration sensorConfiguration) {\r\n // TODO Auto-generated method stub\r\n throw new UnsupportedOperationException(\"Not yet implemented.\");\r\n }\r\n\r\n @Override\r\n public final int hashCode() {\r\n final int prime = 31;\r\n int result = 1;\r\n result = prime * result + ( (getProcedure() == null) ? 0 : getProcedure().hashCode());\r\n return result;\r\n }\r\n\r\n @Override\r\n public final boolean equals(Object obj) {\r\n if (this == obj)\r\n return true;\r\n if (obj == null)\r\n return false;\r\n if (getClass() != obj.getClass())\r\n return false;\r\n SensorPlugin other = (SensorPlugin) obj;\r\n if (getProcedure() == null) {\r\n if (other.getProcedure() != null)\r\n return false;\r\n }\r\n else if ( !getProcedure().equals(other.getProcedure()))\r\n return false;\r\n return true;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"SensorPluginType: \").append(configuration.getSensorPluginType()).append(\", \");\r\n sb.append(\"Procedure: \").append(configuration.getProcedure());\r\n return sb.toString();\r\n }\r\n\r\n}\r",
"public class SimpleSensorPluginTestInstance extends SensorPlugin {\r\n\r\n private static final Logger LOGGER = LoggerFactory.getLogger(SimpleSensorPluginTestInstance.class);\r\n \r\n private static final String PROCEDURE_DESCRIPTION_FORMAT = \"http://www.opengis.net/sensorML/2.0\";\r\n \r\n private static final String PROCEDURE = \"http://my.namespace.org/procedure/\";\r\n \r\n private static int procedureNumber = 0;\r\n \r\n private static final String PLUGIN_TYPE = \"test_procedure\";\r\n\r\n /**\r\n * Creates a plugin instance for testing. It creates its {@link InMemorySensorTaskRepository} instance.\r\n * \r\n * @return a very simple instance of {@link SensorPlugin} for testing purposes.\r\n * @throws InternalServiceException if instance creation fails\r\n */\r\n public static SensorPlugin createInstance() throws InternalServiceException {\r\n SensorTaskRepository taskRepository = new InMemorySensorTaskRepository();\r\n SensorTaskService taskService = new SensorTaskService(taskRepository);\r\n return new SimpleSensorPluginTestInstance(taskService, createSensorConfiguration());\r\n }\r\n \r\n /**\r\n * Creates a plugin instance for testing which is coupled to a {@link SensorInstanceProvider}'s configuration, \r\n * i.e. reuses the {@link SensorTaskRepository} instance from the instance provider to interact with tasks.\r\n * \r\n * @param sensorInstanceProvider a sensorProvider which provides access to a {@link SensorTaskRepository}\r\n * @return an instance of {@link SensorPlugin} for testing purposes.\r\n * @throws InternalServiceException if instance creation fails\r\n */\r\n public static SensorPlugin createInstance(SensorInstanceProvider sensorInstanceProvider) throws InternalServiceException {\r\n SensorTaskRepository taskRepository = sensorInstanceProvider.getSensorTaskRepository();\r\n SensorTaskService taskService = new SensorTaskService(taskRepository);\r\n return new SimpleSensorPluginTestInstance(taskService, createSensorConfiguration());\r\n }\r\n \r\n private static SensorConfiguration createSensorConfiguration() {\r\n SensorConfiguration configuration = new SensorConfiguration();\r\n configuration.setProcedure(PROCEDURE + ++procedureNumber);\r\n configuration.setSensorPluginType(PLUGIN_TYPE);\r\n SensorDescription sensorDescription = new SensorDescription(PROCEDURE_DESCRIPTION_FORMAT, \"http://my.link.com/\");\r\n configuration.addSensorDescription(sensorDescription);\r\n return configuration;\r\n }\r\n\r\n public static SensorPlugin createInstance(SensorTaskService sensorTaskService, SensorConfiguration sensorConfiguration) throws InternalServiceException {\r\n return new SimpleSensorPluginTestInstance(sensorTaskService, sensorConfiguration);\r\n }\r\n\r\n private SimpleSensorPluginTestInstance(SensorTaskService sensorTaskService, SensorConfiguration configuration) throws InternalServiceException {\r\n super(sensorTaskService, configuration);\r\n }\r\n\r\n public Availability getResultAccessibility() {\r\n LanguageStringType testMessage = LanguageStringType.Factory.newInstance();\r\n testMessage.setStringValue(\"no data available for testing purposes.\");\r\n return new DataNotAvailable(testMessage).getResultAccessibility();\r\n }\r\n\r\n public boolean isDataAvailable() {\r\n return false;\r\n }\r\n\r\n @Override\r\n public SensorTask submit(SubmitTaskingRequest submit, OwsExceptionReport owsExceptionReport) throws OwsException {\r\n LOGGER.warn(\"method does not contain test code.\");\r\n return null;\r\n }\r\n\r\n @Override\r\n public void qualifyDataComponent(AbstractDataComponentType componentToQualify) {\r\n LOGGER.warn(\"method does not contain test code.\");\r\n }\r\n\r\n @Override\r\n public Availability getResultAccessibilityFor(SensorTask sensorTask) {\r\n // TODO Auto-generated method stub\r\n return null;\r\n \r\n }\r\n \r\n public void setSensorConfiguration(SensorConfiguration sensorConfiguration) {\r\n this.configuration = sensorConfiguration;\r\n }\r\n\r\n}\r",
"public class SensorConfiguration {\r\n\r\n private Long id; // database id\r\n\r\n private List<SensorOfferingType> sensorOfferings = new ArrayList<SensorOfferingType>();\r\n\r\n private List<SensorDescription> sensorDescriptions = new ArrayList<SensorDescription>();\r\n\r\n private String procedure;\r\n\r\n private String sensorPluginType;\r\n \r\n private XmlObject sensorSetup;\r\n\r\n private AbstractDataComponentType taskingParametersTemplate;\r\n\r\n private ResultAccessDataServiceReference resultAccessDataServiceTemplate;\r\n\r\n public SensorConfiguration() {\r\n // db serialization\r\n }\r\n\r\n Long getId() {\r\n return id;\r\n }\r\n\r\n void setId(Long id) {\r\n this.id = id;\r\n }\r\n \r\n public List<String> getSensorOfferingsAsString() {\r\n List<String> offerings = new ArrayList<String>();\r\n for (SensorOfferingType offeringType : sensorOfferings) {\r\n offerings.add(offeringType.xmlText());\r\n }\r\n return offerings;\r\n }\r\n\r\n public List<SensorOfferingType> getSensorOfferings() {\r\n return sensorOfferings;\r\n }\r\n \r\n public void setSensorOfferingsAsString(List<String> sensorOfferings) throws XmlException {\r\n this.sensorOfferings.clear();\r\n for (String sensorOffering : sensorOfferings) {\r\n this.sensorOfferings.add(SensorOfferingType.Factory.parse(sensorOffering));\r\n }\r\n }\r\n\r\n public void setSensorOfferings(List<SensorOfferingType> sensorOfferings) {\r\n this.sensorOfferings = sensorOfferings;\r\n }\r\n\r\n public boolean addSensorOffering(SensorOfferingType sensorOfferingType) {\r\n return sensorOfferings.add(sensorOfferingType);\r\n }\r\n\r\n public boolean removeSensorOffering(String offeringIdentifier) {\r\n for (SensorOfferingType sensorOffering : sensorOfferings) {\r\n if (sensorOffering.getIdentifier().equals(offeringIdentifier)) {\r\n return sensorOfferings.remove(sensorOffering);\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n public String getProcedure() {\r\n return procedure;\r\n }\r\n\r\n public void setProcedure(String procedure) {\r\n this.procedure = procedure;\r\n }\r\n\r\n public String getSensorPluginType() {\r\n return sensorPluginType;\r\n }\r\n\r\n public void setSensorPluginType(String sensorPluginType) {\r\n this.sensorPluginType = sensorPluginType;\r\n }\r\n\r\n public XmlObject getSensorSetup() {\r\n return sensorSetup;\r\n }\r\n \r\n public void setSensorSetup(XmlObject sensorSetup) {\r\n this.sensorSetup = sensorSetup;\r\n }\r\n \r\n public String getSensorSetupAsString() {\r\n return sensorSetup != null ? sensorSetup.xmlText(): null;\r\n }\r\n \r\n public void setSensorSetupAsString(String sensorSetup) throws XmlException {\r\n if (sensorSetup != null) {\r\n this.sensorSetup = XmlObject.Factory.parse(sensorSetup);\r\n }\r\n }\r\n \r\n public List<SensorDescription> getSensorDescriptions() {\r\n return sensorDescriptions;\r\n }\r\n\r\n public void setSensorDescriptions(List<SensorDescription> sensorDescriptions) {\r\n this.sensorDescriptions = sensorDescriptions;\r\n }\r\n\r\n public List<String> getSensorDescriptionUrisFor(String procedureDescriptionFormat) {\r\n List<String> descriptionUris = new ArrayList<String>();\r\n for (SensorDescription sensorDescription : sensorDescriptions) {\r\n if (sensorDescription.getProcedureDescriptionFormat().equals(procedureDescriptionFormat)) {\r\n descriptionUris.add(sensorDescription.getDownloadLink());\r\n }\r\n }\r\n return descriptionUris;\r\n }\r\n\r\n public boolean addSensorDescription(SensorDescription sensorDescription) {\r\n return sensorDescriptions.add(sensorDescription);\r\n }\r\n\r\n public boolean removeSensorDescription(SensorDescription sensorDescription) {\r\n return sensorDescriptions.remove(sensorDescription);\r\n }\r\n\r\n /**\r\n * @param procedureDescriptionFormat\r\n * the format of SensorDescription\r\n * @return <code>true</code> if the given format is available, <code>false</code> otherwise.\r\n */\r\n public boolean supportsProcedureDescriptionFormat(String procedureDescriptionFormat) {\r\n for (SensorDescription sensorDescription : sensorDescriptions) {\r\n if (sensorDescription.getProcedureDescriptionFormat().equals(procedureDescriptionFormat)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n public void setTaskingParametersTemplate(AbstractDataComponentType taskingParameters) {\r\n this.taskingParametersTemplate = taskingParameters;\r\n }\r\n\r\n /**\r\n * @return deep copy of configured tasking parameters to be used as template. The caller has to qualify\r\n * the returned {@link AbstractDataComponentType} to a corresponding Substitution type.\r\n */\r\n public AbstractDataComponentType getTaskingParametersTemplate() {\r\n return (AbstractDataComponentType) taskingParametersTemplate.copy();\r\n }\r\n\r\n public String getTaskingParameters() {\r\n return taskingParametersTemplate.xmlText();\r\n }\r\n\r\n public void setTaskingParameters(String taskingParameters) throws XmlException {\r\n this.taskingParametersTemplate = AbstractDataComponentType.Factory.parse(taskingParameters);\r\n }\r\n\r\n public ResultAccessDataServiceReference getResultAccessDataService() {\r\n return resultAccessDataServiceTemplate;\r\n }\r\n\r\n public void setResultAccessDataService(ResultAccessDataServiceReference resultAccessDataService) {\r\n this.resultAccessDataServiceTemplate = resultAccessDataService;\r\n }\r\n\r\n}\r",
"public abstract class InternalServiceException extends Exception {\r\n \r\n private static final long serialVersionUID = -1598594769157092219L;\r\n \r\n public static final int BAD_REQUEST = 400;\r\n \r\n private List<String> detailedMessages = new ArrayList<String>();\r\n private String exceptionCode;\r\n private String locator;\r\n\r\n public InternalServiceException(String exceptionCode, String locator) {\r\n this.exceptionCode = exceptionCode;\r\n this.locator = locator;\r\n }\r\n\r\n public String getExceptionCode() {\r\n return exceptionCode;\r\n }\r\n\r\n public void setExceptionCode(String exceptionCode) {\r\n this.exceptionCode = exceptionCode;\r\n }\r\n\r\n public String getLocator() {\r\n return locator;\r\n }\r\n\r\n public void setLocator(String locator) {\r\n this.locator = locator;\r\n }\r\n\r\n public void addDetailedMessage(String detailedMessage) {\r\n detailedMessages.add(detailedMessage);\r\n }\r\n \r\n public Iterable<String> getDetailedMessages() {\r\n return detailedMessages;\r\n }\r\n\r\n public abstract int getHttpStatusCode();\r\n\r\n \r\n}\r",
"public interface SensorConfigurationRepository {\r\n\r\n public void storeNewSensorConfiguration(SensorConfiguration sensorConfiguration);\r\n \r\n public void saveOrUpdateSensorConfiguration(SensorConfiguration sensorConfiguration);\r\n \r\n public void removeSensorConfiguration(SensorConfiguration sensorConfiguration);\r\n\r\n public SensorConfiguration getSensorConfiguration(String procedure);\r\n\r\n public Iterable<SensorConfiguration> getSensorConfigurations();\r\n\r\n public boolean containsSensorConfiguration(String procedure);\r\n\r\n}\r",
"public class InMemorySensorConfigurationRepository implements SensorConfigurationRepository {\r\n \r\n private Map<String, SensorConfiguration> sensors = new HashMap<String, SensorConfiguration>();\r\n\r\n public void storeNewSensorConfiguration(SensorConfiguration sensorInstance) {\r\n sensors.put(sensorInstance.getProcedure(), sensorInstance);\r\n }\r\n \r\n public void saveOrUpdateSensorConfiguration(SensorConfiguration sensorInstance) {\r\n sensors.put(sensorInstance.getProcedure(), sensorInstance);\r\n }\r\n\r\n public void removeSensorConfiguration(SensorConfiguration sensorInstance) {\r\n sensors.remove(sensorInstance.getProcedure());\r\n }\r\n\r\n public SensorConfiguration getSensorConfiguration(String procedure) {\r\n return sensors.get(procedure);\r\n }\r\n\r\n public boolean containsSensorConfiguration(String procedure) {\r\n return sensors.containsKey(procedure);\r\n }\r\n \r\n public Iterable<SensorConfiguration> getSensorConfigurations() {\r\n return sensors.values();\r\n }\r\n\r\n}\r"
] | import org.junit.Test;
import org.n52.sps.sensor.SensorPlugin;
import org.n52.sps.sensor.SimpleSensorPluginTestInstance;
import org.n52.sps.sensor.model.SensorConfiguration;
import org.n52.sps.service.InternalServiceException;
import org.n52.sps.store.SensorConfigurationRepository;
import org.n52.sps.util.nodb.InMemorySensorConfigurationRepository;
import static org.junit.Assert.*;
import org.junit.Before;
| /**
* Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as publishedby the Free
* Software Foundation.
*
* If the program is linked with libraries which are licensed under one of the
* following licenses, the combination of the program with the linked library is
* not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed under
* the aforementioned licenses, is permitted by the copyright holders if the
* distribution is compliant with both the GNU General Public License version 2
* and the aforementioned licenses.
*
* 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.
*/
package org.n52.sps.util.nodb;
public class InMemorySensorConfigurationRepositoryTest {
private SensorConfigurationRepository repository;
@Before
public void setUp() {
repository = new InMemorySensorConfigurationRepository();
}
@Test
public void testCreateNewInstance() throws InternalServiceException {
SensorPlugin testInstance = SimpleSensorPluginTestInstance.createInstance();
| SensorConfiguration sensorConfiguration = testInstance.getSensorConfiguration();
| 2 |
apradanas/prismoji-android | prismoji/src/main/java/com/apradanas/prismoji/PrismojiPopup.java | [
"public final class Emoji implements Serializable {\n private static final long serialVersionUID = 3L;\n\n @NonNull\n private final String unicode;\n @DrawableRes\n private final int resource;\n @NonNull\n private List<Emoji> variants;\n @SuppressWarnings(\"PMD.ImmutableField\")\n @Nullable\n private Emoji base;\n\n public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) {\n this(codePoints, resource, new Emoji[0]);\n }\n\n public Emoji(final int codePoint, @DrawableRes final int resource) {\n this(codePoint, resource, new Emoji[0]);\n }\n\n public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) {\n this.unicode = new String(codePoints, 0, codePoints.length);\n this.resource = resource;\n this.variants = Arrays.asList(variants);\n\n for (final Emoji variant : variants) {\n variant.base = this;\n }\n }\n\n public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) {\n this(new int[]{codePoint}, resource, variants);\n }\n\n @NonNull\n public String getUnicode() {\n return unicode;\n }\n\n @DrawableRes\n public int getResource() {\n return resource;\n }\n\n @NonNull\n public List<Emoji> getVariants() {\n return new ArrayList<>(variants);\n }\n\n @NonNull\n public Emoji getBase() {\n Emoji result = this;\n\n while (result.base != null) {\n result = result.base;\n }\n\n return result;\n }\n\n public int getLength() {\n return unicode.length();\n }\n\n public boolean hasVariants() {\n return !variants.isEmpty();\n }\n\n @Override\n public boolean equals(final Object o) {\n if (this == o) {\n return true;\n }\n\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n final Emoji emoji = (Emoji) o;\n\n return resource == emoji.resource\n && unicode.equals(emoji.unicode)\n && variants.equals(emoji.variants);\n }\n\n @Override\n public int hashCode() {\n int result = unicode.hashCode();\n result = 31 * result + resource;\n result = 31 * result + variants.hashCode();\n return result;\n }\n}",
"public interface OnEmojiBackspaceClickListener {\n void onEmojiBackspaceClicked(final View v);\n}",
"public interface OnEmojiClickedListener {\n void onEmojiClicked(final Emoji emoji);\n}",
"public interface OnEmojiLongClickedListener {\n void onEmojiLongClicked(final View view, final Emoji emoji);\n}",
"public interface OnEmojiPopupDismissListener {\n void onEmojiPopupDismiss();\n}",
"public interface OnEmojiPopupShownListener {\n void onEmojiPopupShown();\n}",
"public interface OnSoftKeyboardCloseListener {\n void onKeyboardClose();\n}",
"public interface OnSoftKeyboardOpenListener {\n void onKeyboardOpen(int keyBoardHeight);\n}",
"@NonNull\nstatic <T> T checkNotNull(@Nullable final T reference, final String message) {\n if (reference == null) {\n throw new IllegalArgumentException(message);\n }\n\n return reference;\n}"
] | import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;
import com.apradanas.prismoji.emoji.Emoji;
import com.apradanas.prismoji.listeners.OnEmojiBackspaceClickListener;
import com.apradanas.prismoji.listeners.OnEmojiClickedListener;
import com.apradanas.prismoji.listeners.OnEmojiLongClickedListener;
import com.apradanas.prismoji.listeners.OnEmojiPopupDismissListener;
import com.apradanas.prismoji.listeners.OnEmojiPopupShownListener;
import com.apradanas.prismoji.listeners.OnSoftKeyboardCloseListener;
import com.apradanas.prismoji.listeners.OnSoftKeyboardOpenListener;
import static com.apradanas.prismoji.Utils.checkNotNull; | package com.apradanas.prismoji;
public final class PrismojiPopup {
private static final int MIN_KEYBOARD_HEIGHT = 100;
final View rootView;
final Context context;
@NonNull
final RecentEmoji recentEmoji;
@NonNull
final PrismojiVariantPopup variantPopup;
final PopupWindow popupWindow;
private final PrismojiEditText prismojiEditText;
private final PrismojiAutocompleteTextView prismojiAutocompleteTextView;
int keyBoardHeight;
boolean isPendingOpen;
boolean isKeyboardOpen;
@Nullable
OnEmojiPopupShownListener onEmojiPopupShownListener;
@Nullable
OnSoftKeyboardCloseListener onSoftKeyboardCloseListener;
@Nullable | OnSoftKeyboardOpenListener onSoftKeyboardOpenListener; | 7 |
TalkingData/Myna | Android/lib-Myna/src/main/java/com/talkingdata/myna/MynaTrainTest.java | [
"public class Feature {\n private int batchSize;\n private SensorFeature feature;\n\n public Feature() {\n feature = new SensorFeature();\n batchSize = 0;\n }\n\n /**\n * Get selected feature\n * @return selected feature\n */\n public SensorFeature getSelectedFeatures(){\n return feature;\n }\n\n /**\n * Extract feature from raw sensor data\n */\n public void extractFeatures(SensorData[] sensorData, final int sampleFreq, final int sampleCount) {\n batchSize = sensorData.length;\n float[][] input = new float[3][batchSize];\n for (int i = 0; i < batchSize; i++){\n input[0][i] = sensorData[i].world_accelerometer[0];\n input[1][i] = sensorData[i].world_accelerometer[1];\n input[2][i] = sensorData[i].world_accelerometer[2];\n }\n// Statistics.normalize(input[0]);\n// Statistics.normalize(input[1]);\n// Statistics.normalize(input[2]);\n getFeaturesInternally(input, sampleFreq, sampleCount);\n }\n\n /**\n * Internal implementation of extracting feature from raw sensor data\n */\n private void getFeaturesInternally(float[][] dataset, final int sampleFreq, final int sampleCount) {\n feature.maxX = Statistics.getMax(dataset[0]);\n feature.maxY = Statistics.getMax(dataset[1]);\n feature.maxZ = Statistics.getMax(dataset[2]);\n\n feature.minX = Statistics.getMin(dataset[0]);\n feature.minY = Statistics.getMin(dataset[1]);\n feature.minZ = Statistics.getMin(dataset[2]);\n\n feature.meanX = Statistics.getMean(dataset[0]);\n feature.meanY = Statistics.getMean(dataset[1]);\n feature.meanZ = Statistics.getMean(dataset[2]);\n\n feature.stdDevX = Statistics.getStdDev(dataset[0]);\n feature.stdDevY = Statistics.getStdDev(dataset[1]);\n feature.stdDevZ = Statistics.getStdDev(dataset[2]);\n\n calculateWaveletApproximation(dataset, 0);\n calculateWaveletApproximation(dataset, 1);\n calculateWaveletApproximation(dataset, 2);\n\n calculateFreqAndMagnitude(dataset, sampleFreq, sampleCount, 0);\n calculateFreqAndMagnitude(dataset, sampleFreq, sampleCount, 1);\n calculateFreqAndMagnitude(dataset, sampleFreq, sampleCount, 2);\n }\n\n private void calculateFreqAndMagnitude(float[][] dataset, final int sampleFreq, final int sampleCount, int axis){\n float[] freqAndMag = Statistics.getFreqAndMagnitudeViaFFT(dataset[axis], sampleFreq, sampleCount);\n if(axis == 0){\n feature.freqX = freqAndMag[0];\n feature.magnitudeX = freqAndMag[1];\n }else if(axis == 1){\n feature.freqY = freqAndMag[0];\n feature.magnitudeY = freqAndMag[1];\n }else if(axis == 2){\n feature.freqZ = freqAndMag[0];\n feature.magnitudeZ = freqAndMag[1];\n }\n }\n\n private void calculateWaveletApproximation(float[][] dataset, int axis){\n float[] approximation = Statistics.getWaveletApproximation(dataset[axis]);\n if(axis == 0){\n feature.meanApproximationX = Statistics.getMean(approximation);\n feature.stdDevApproximationX = Statistics.getStdDev(approximation);\n }else if(axis == 1){\n feature.meanApproximationY = Statistics.getMean(approximation);\n feature.stdDevApproximationY = Statistics.getStdDev(approximation);\n }else if(axis == 2){\n feature.meanApproximationZ = Statistics.getMean(approximation);\n feature.stdDevApproximationZ = Statistics.getStdDev(approximation);\n }\n }\n\n public double[] getFeaturesAsArray(){\n double[] array = new double[SensorFeature.FEATURE_COUNT];\n int index = 0;\n array[index++] = feature.minX;\n array[index++] = feature.maxX;\n array[index++] = feature.meanX;\n array[index++] = feature.stdDevX;\n array[index++] = feature.meanApproximationX;\n array[index++] = feature.stdDevApproximationX;\n array[index++] = feature.magnitudeX;\n array[index++] = feature.freqX;\n\n array[index++] = feature.minY;\n array[index++] = feature.maxY;\n array[index++] = feature.meanY;\n array[index++] = feature.stdDevY;\n array[index++] = feature.meanApproximationY;\n array[index++] = feature.stdDevApproximationY;\n array[index++] = feature.magnitudeY;\n array[index++] = feature.freqY;\n\n array[index++] = feature.minZ;\n array[index++] = feature.maxZ;\n array[index++] = feature.meanZ;\n array[index++] = feature.stdDevZ;\n array[index++] = feature.meanApproximationZ;\n array[index++] = feature.stdDevApproximationZ;\n array[index++] = feature.magnitudeZ;\n array[index] = feature.freqZ;\n return array;\n }\n}",
"public class SensorData {\n /**\n * Sensor data\n */\n public float[] accelerate, gyroscope, gravity, magnetic, game_rotation_vector, orientation;\n\n\n /**\n * Calculated accelerometer values in real world coordination system.\n */\n public float[] world_accelerometer;\n\n public float light, pressure, temperature;\n\n /**\n * Time when recording the data of these sensors\n */\n public long timestamp;\n\n public SensorData() {\n accelerate = new float[3];\n gyroscope = new float[3];\n gravity = new float[3];\n magnetic = new float[3];\n game_rotation_vector = new float[3];\n orientation = new float[3];\n world_accelerometer = new float[3];\n timestamp = System.currentTimeMillis();\n }\n\n /**\n * Reset the value of all fields with the given instance\n * @param sd Source instance with the sensor data waiting to be cloned.\n */\n public void clone(SensorData sd) {\n System.arraycopy(sd.accelerate, 0, this.accelerate, 0, 3);\n System.arraycopy(sd.gyroscope, 0, this.gyroscope, 0, 3);\n System.arraycopy(sd.gravity, 0, this.gravity, 0, 3);\n System.arraycopy(sd.magnetic, 0, this.magnetic, 0, 3);\n System.arraycopy(sd.game_rotation_vector, 0, this.game_rotation_vector, 0, 3);\n System.arraycopy(sd.orientation, 0, this.orientation, 0, 3);\n System.arraycopy(sd.world_accelerometer, 0, this.world_accelerometer, 0, 3);\n\n this.light = sd.light;\n this.temperature = sd.temperature;\n this.pressure = sd.pressure;\n\n\n // Update the timestamp\n this.timestamp = sd.timestamp;\n }\n\n @Override\n public String toString(){\n return toCSVString();\n }\n\n private String getValues(float[] array) {\n return String.valueOf(array[0]) + \",\"\n + String.valueOf(array[1]) + \",\"\n + String.valueOf(array[2]);\n }\n\n /**\n * Get all sensor data in JSON format\n * @return JSONObject object of all sensor data in JSON format\n */\n JSONObject toJsonObj() {\n try {\n JSONObject obj = new JSONObject();\n obj.put(\"accelerate\", getXYZJsonObj(accelerate[0], accelerate[1], accelerate[2]));\n obj.put(\"gyroscope\", getXYZJsonObj(gyroscope[0], gyroscope[1], gyroscope[2]));\n obj.put(\"gravity\", getXYZJsonObj(gravity[0], gravity[1], gravity[2]));\n obj.put(\"magnetic\", getXYZJsonObj(magnetic[0], magnetic[1], magnetic[2]));\n obj.put(\"game_rotation_vector\", getXYZJsonObj(game_rotation_vector[0], game_rotation_vector[1], game_rotation_vector[2]));\n obj.put(\"orientation\", getXYZJsonObj(orientation[0], orientation[1], orientation[2]));\n obj.put(\"world_accelerometer\", getXYZJsonObj(world_accelerometer[0], world_accelerometer[1], world_accelerometer[2]));\n obj.put(\"light\", light);\n obj.put(\"pressure\", pressure);\n obj.put(\"temperature\", temperature);\n obj.put(\"timestamp\", timestamp);\n return obj;\n } catch (Throwable e) {\n e.printStackTrace();\n }\n return null;\n }\n\n /**\n * Get all sensor data in CSV format\n * @return String object of all sensor data in CSV format\n */\n private String toCSVString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getValues(accelerate));\n sb.append(\",\");\n sb.append(getValues(gyroscope));\n sb.append(\",\");\n sb.append(getValues(gravity));\n sb.append(\",\");\n sb.append(getValues(magnetic));\n sb.append(\",\");\n sb.append(getValues(game_rotation_vector));\n sb.append(\",\");\n sb.append(getValues(orientation));\n sb.append(\",\");\n sb.append(getValues(world_accelerometer));\n sb.append(\",\");\n sb.append(String.valueOf(light));\n sb.append(\",\");\n sb.append(String.valueOf(pressure));\n sb.append(\",\");\n sb.append(String.valueOf(temperature));\n sb.append(\",\");\n sb.append(String.valueOf(timestamp));\n return sb.toString();\n }\n\n private JSONObject getXYZJsonObj(final float x, final float y, final float z) {\n try {\n JSONObject jsonObj = new JSONObject();\n jsonObj.put(\"x\", x);\n jsonObj.put(\"y\", y);\n jsonObj.put(\"z\", z);\n return jsonObj;\n\n } catch (Throwable e) {\n e.printStackTrace();\n return null;\n }\n }\n}",
"public class SensorFeature {\n public static final int FEATURE_COUNT = 24;\n public float minX = 10000, minY = 10000, minZ = 10000;\n public float maxX = -10000, maxY = -10000, maxZ = -10000;\n public float meanX = 0, meanY = 0, meanZ = 0;\n public float stdDevX = 0, stdDevY = 0, stdDevZ = 0;\n public float meanApproximationX = 0, meanApproximationY = 0, meanApproximationZ = 0;\n public float stdDevApproximationX = 0, stdDevApproximationY = 0, stdDevApproximationZ = 0;\n public float magnitudeX = 0, magnitudeY = 0, magnitudeZ = 0;\n public float freqX = 0, freqY = 0, freqZ = 0;\n\n}",
"public class Utils {\n\n public static final String TAG = \"Myna\";\n\n\n public static void calculateWorldAcce(SensorData sd){\n float[] Rotate = new float[16];\n float[] I = new float[16];\n float[] currOrientation = new float[3];\n if((int)(sd.game_rotation_vector[0]) == 0\n && (int)(sd.game_rotation_vector[1]) == 0\n && (int)(sd.game_rotation_vector[2]) == 0){\n SensorManager.getRotationMatrix(Rotate, I, sd.accelerate, sd.magnetic);\n }else{\n SensorManager.getRotationMatrixFromVector(Rotate, sd.game_rotation_vector);\n }\n SensorManager.getOrientation(Rotate, currOrientation);\n System.arraycopy(currOrientation, 0, sd.orientation, 0, 3);\n\n float[] relativeAcc = new float[4];\n float[] earthAcc = new float[4];\n float[] inv = new float[16];\n System.arraycopy(sd.accelerate, 0, relativeAcc, 0, 3);\n relativeAcc[3] = 0;\n android.opengl.Matrix.invertM(inv, 0, Rotate, 0);\n android.opengl.Matrix.multiplyMV(earthAcc, 0, inv, 0, relativeAcc, 0);\n System.arraycopy(earthAcc, 0, sd.world_accelerometer, 0, 3);\n }\n\n public static String loadFeaturesFromAssets(Context ctx, String fileName){\n String content = null;\n if(ctx == null || fileName == null || fileName.isEmpty()){\n return content;\n }\n try {\n InputStream file = ctx.getAssets().open(fileName);\n byte[] formArray = new byte[file.available()];\n file.read(formArray);\n file.close();\n content = new String(formArray);\n } catch (Throwable t) {\n t.printStackTrace();\n }\n\n return content;\n }\n\n /** Read the object from Base64 string. */\n public static Object fromString( String s ) throws IOException,\n ClassNotFoundException {\n byte [] data = Base64.decode(s, Base64.DEFAULT);\n ObjectInputStream ois = new ObjectInputStream(\n new ByteArrayInputStream( data ) );\n Object o = ois.readObject();\n ois.close();\n return o;\n }\n\n /** Write the object to a Base64 string. */\n public static String toString( Serializable o ) throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream( baos );\n oos.writeObject( o );\n oos.close();\n return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);\n }\n\n public static double get3AxisDistance(final float x, final float y, final float z){\n return Math.sqrt(x * x + y * y + z * z);\n }\n\n\n /**\n * Check the device to make sure it has the Google Play Services APK. If\n * it doesn't, display a dialog that allows users to download the APK from\n * the Google Play Store or enable it in the device's system settings.\n */\n public static boolean isGooglePlayServiceSupported(Context ctx) {\n GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();\n int resultCode = apiAvailability.isGooglePlayServicesAvailable(ctx);\n return resultCode == ConnectionResult.SUCCESS;\n }\n\n public static void deleteFile(final String fileName){\n File file = new File(Environment.getExternalStorageDirectory(), \"/rHAR/\" + fileName);\n if(file.exists())\n {\n Log.i(TAG, String.valueOf(file.delete()));\n }\n }\n\n public static SparseArray<File> getDataFiles(final String folderSubPath){\n if(folderSubPath == null || folderSubPath.trim().isEmpty()){\n return null;\n }\n SparseArray<File> files = new SparseArray<>();\n File file = new File(Environment.getExternalStorageDirectory() + folderSubPath);\n if(!file.exists() || !file.isDirectory())\n return null;\n\n File[] tempFiles = file.listFiles();\n if(tempFiles == null)\n return null;\n int count = 0;\n for(File tempFile : tempFiles){\n if(!tempFile.isDirectory()){\n files.append(count++, tempFile);\n }\n }\n return files;\n }\n\n public static void saveAsAppend(final Context ctx, final String content, final String fileName) {\n if(ctx == null || content.isEmpty() || fileName == null || fileName.isEmpty()){\n return;\n }\n File dir = new File(Environment.getExternalStorageDirectory() + \"/rHAR/\");\n if(!dir.exists()){\n dir.mkdir();\n }\n File file = new File(dir, fileName);\n Log.i(TAG, \"Append saving, saved path: \" + file.getAbsolutePath());\n try {\n FileWriter fWriter = new FileWriter(file, true);\n BufferedWriter writer = new BufferedWriter(fWriter);\n writer.write(content);\n writer.close();\n fWriter.close();\n } catch (Throwable e) {\n e.printStackTrace();\n }\n }\n\n public static String save(final Context ctx, final String content, final String fileName, final int label) {\n if(ctx == null || content.isEmpty() || fileName == null || fileName.isEmpty()){\n return null;\n }\n\n File file = new File(ctx.getFilesDir(), fileName);\n String sdState = Environment.getExternalStorageState();\n if (Environment.MEDIA_MOUNTED.equals(sdState)){\n File dir = new File(Environment.getExternalStorageDirectory() + \"/rHAR/\");\n if(label > 0){\n dir = new File(Environment.getExternalStorageDirectory() + \"/rHAR/data/\" + String.valueOf(label));\n }\n if(!dir.exists()){\n dir.mkdir();\n }\n file = new File(dir, fileName);\n }\n String savedPath = file.getAbsolutePath();\n Log.i(TAG, \"Save path: \" + savedPath);\n if (file.exists())\n Log.i(TAG, \"Existing file deleting result: \"+ String.valueOf(file.delete()));\n try {\n FileWriter fWriter = new FileWriter(file);\n BufferedWriter writer = new BufferedWriter(fWriter);\n writer.write(content);\n writer.close();\n fWriter.close();\n return savedPath;\n } catch (Throwable e) {\n e.printStackTrace();\n return null;\n }\n }\n\n public static boolean isFileExists(Context ctx, String fileName){\n if(ctx == null || fileName == null || fileName.isEmpty()){\n return false;\n }\n File file = new File(Environment.getExternalStorageDirectory() + \"/rHAR/\" + fileName);\n return file.exists();\n }\n\n public static String load(Context ctx, String fileName) {\n if(ctx == null || fileName == null || fileName.isEmpty()){\n return null;\n }\n File file = new File(ctx.getFilesDir(), fileName);\n String sdState = Environment.getExternalStorageState();\n if (Environment.MEDIA_MOUNTED.equals(sdState)){\n File dir = new File(Environment.getExternalStorageDirectory() + \"/rHAR/\");\n if(!dir.exists()){\n dir.mkdir();\n }\n file = new File(dir, fileName);\n }\n if (file.exists()) {\n try {\n StringBuilder text = new StringBuilder();\n BufferedReader br = new BufferedReader(new FileReader(file));\n String line;\n while ((line = br.readLine()) != null) {\n text.append(line);\n text.append('\\n');\n }\n br.close();\n return text.toString();\n } catch (Throwable e) {\n e.printStackTrace();\n }\n }\n return null;\n }\n}",
"public interface Instances extends Serializable {\n\n /**\n * Get the arrays, whose elements indicate the types of attributes.\n * 0 indicates the attribute is numeric or real attribute.\n * The number is greater than 0 indicate the numbers of values of each attributes.\n *\n * @return The attribute type indicator array.\n */\n int[] getAttributes();\n\n /**\n * Return a Iterator of the {@link dice.data.Instance}\n * @return The iteraotr of Instance.\n */\n Iterator<Instance> iterator();\n\n /**\n * Get the number of {@link dice.data.Instance}s.\n * @return The number of {@link dice.data.Instance}s.\n */\n int size();\n\n /**\n * Get the number of attributes.\n * @return The number of attributes.\n */\n int getAttrSize();\n\n /**\n * Get the relation name of the data set.\n * @return The relation name of the data set.\n */\n String getRelation();\n\n /**\n * Get an instance by the assigned index or position.\n * @param index The index or position of the {@link Instance} wanted.\n * @return The instance wanted.\n */\n Instance get(int index);\n\n /**\n * Get the storage status of the Instances.\n * @return If the data storage form is sparse, then return true. Otherwise, return false.\n */\n boolean isSparse();\n\n /**\n * Get the index matrix.\n * @return The index matrix. If the {@link #isSparse()} return\n * false, the return will be null.\n */\n int[][] getIds();\n\n /**\n * Get the data matrix.\n * @return The data matrix.\n */\n double[][] getMat();\n\n\n /**\n * Put the index and data matrix into it.\n * @param ids The index matrix.\n * @param mat The data matrix.\n */\n void setData(int[][] ids, double[][] mat);\n\n /**\n * Set the default value for the ignored element\n * in the sparse storage form.\n * @param miss\n */\n void setMiss(double miss);\n\n}",
"public class ArffReader implements DataReader {\n\n /**\n * The constant for \"@relation\" label of arff file.\n */\n private final String RELATION = \"@relation\";\n\n /**\n * The constant for \"@attribute\" label of arff file.\n */\n private final String ATTRIBUTE = \"@attribute\";\n\n /**\n * The constant for \"@data\" label of arff file.\n */\n private final String DATA = \"@data\";\n\n /**\n * The constant for \"numeric\" label of arff file, which indicates the attribute is numeric type.\n */\n private final String NUMERIC = \"numeric\";\n\n /**\n * The constant for \"real\" label of arff file, which indicates the attribute is real type.\n */\n private final String REAL = \"real\";\n\n /**\n * In memory, the numeric attribute is represent as \"-1\".\n */\n private final int N_NUMERIC = -1;\n\n /**\n * In memory, the numeric attribute is represent as \"0\".\n */\n private final int N_REAL = 0;\n\n /**\n * In arff file, \"?\" means the missing data.\n */\n private final String UNKNOWN = \"?\";\n\n /**\n * Split character.\n */\n private final String SPLIT = \"\\t| \";\n\n /**\n * Comma character.\n */\n private final String COMM = \",\";\n\n /**\n * The data source file.\n */\n private String filePath;\n\n /**\n * The number of attributes.\n */\n private int attrSize;\n\n /**\n * The flag indicate whether the data source is sparse of dense. True means sparse.\n */\n private boolean isSparse;\n\n /**\n * Check the data storage form in the source file. If it is sparse, the function will set\n * {@link #isSparse} to true, otherwise to false.\n */\n private static Map<Integer, Map<String, Integer>> globalNominalAttrs;\n private static int[] globalAttributes;\n\n private void checkData() {\n try {\n BufferedReader br = new BufferedReader(new FileReader(filePath));\n String ln;\n boolean flag = false;\n while ((ln = br.readLine()) != null) {\n if (flag) {\n if (ln.startsWith(\"{\")) {\n isSparse = true;\n } else {\n isSparse = false;\n }\n flag = false;\n }\n if (ln.equals(DATA)) {\n flag = true;\n }\n }\n br.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n @Override\n /**\n * Get the data instances from the source file.\n */\n public SimpleInstances getInstances() {\n checkData();\n if (isSparse) {\n return getSparseInstances();\n } else {\n return getDenseInstances();\n }\n }\n\n /**\n * Get the instances from sparse source file.\n * \n * @return\n */\n private SimpleInstances getSparseInstances() {\n BufferedReader br;\n try {\n String relation = \"relation\";\n Map<Integer, Map<String, Integer>> nominalAttrs = new HashMap<Integer, Map<String, Integer>>();\n\n String ln;\n int c = 0;\n int instSize = 0;\n int vSize = 0;\n boolean isHeader = true;\n br = new BufferedReader(new FileReader(filePath));\n while ((ln = br.readLine()) != null) {\n if (ln.length() < 1 || ln.startsWith(\"%\")) {\n continue;\n }\n if (ln.equals(DATA)) {\n isHeader = false;\n\n continue;\n }\n if (isHeader) {\n String[] s = ln.split(SPLIT, 3);\n for (int i = 0; i < s.length; i++) {\n s[i] = s[i].trim();\n }\n if (s.length > 1) {\n if (s[0].equalsIgnoreCase(RELATION)) {\n relation = s[1];\n } else if (s.length >= 3 && s[0].equalsIgnoreCase(ATTRIBUTE)) {\n if (s[2].startsWith(\"{\")) {\n s[2] = s[2].substring(1, s[2].length() - 1);\n String[] ss = s[2].split(COMM);\n int t = 0;\n Map<String, Integer> nMap = new HashMap<String, Integer>();\n for (String e : ss) {\n nMap.put(e.trim(), t);\n t++;\n }\n nominalAttrs.put(c, nMap);\n }\n c++;\n }\n }\n } else {\n\n ln = ln.substring(1, ln.length() - 1);\n\n String[] s = ln.split(COMM);\n\n vSize += s.length;\n\n instSize++;\n\n }\n }\n\n br.close();\n\n int[] attributes = new int[attrSize];\n int[][] ids = new int[instSize][];\n double[][] mat = new double[instSize][];\n\n isHeader = true;\n c = 0;\n int ic = 0;\n br = new BufferedReader(new FileReader(filePath));\n while ((ln = br.readLine()) != null) {\n if (ln.length() < 1 || ln.startsWith(\"%\")) {\n continue;\n }\n if (ln.equals(DATA)) {\n isHeader = false;\n continue;\n }\n if (isHeader) {\n String[] s = ln.split(SPLIT, 3);\n for (int i = 0; i < s.length; i++) {\n s[i] = s[i].trim();\n }\n if (s.length >= 3 && s[0].equals(ATTRIBUTE)) {\n if (c < attributes.length) {\n if (s[2].equalsIgnoreCase(NUMERIC)) {\n attributes[c] = N_NUMERIC;\n } else if (s[2].equalsIgnoreCase(REAL)) {\n attributes[c] = N_REAL;\n } else if (s[2].startsWith(\"{\")) {\n attributes[c] = nominalAttrs.get(c).size();\n }\n c++;\n }\n }\n } else {\n\n ln = ln.substring(1, ln.length() - 1);\n\n String[] s = ln.split(COMM);\n int[] indexs = new int[s.length];\n double[] values = new double[s.length];\n for (int i = 0; i < s.length; i++) {\n\n String[] ss = s[i].split(SPLIT);\n\n indexs[i] = Integer.parseInt(ss[0]);\n\n if (indexs[i] < attributes.length) {\n if (attributes[indexs[i]] < 1) {\n values[i] = Double.parseDouble(ss[1]);\n } else {\n values[i] = nominalAttrs.get(indexs[i]).get(ss[1]);\n }\n }\n }\n mat[ic] = values;\n ids[ic] = indexs;\n ic++;\n }\n }\n\n br.close();\n\n return new SimpleInstances(attributes, mat, ids, relation);\n\n } catch (IOException e) {\n\n e.printStackTrace();\n }\n\n return null;\n }\n\n // //////////////////////////////////add by Ye////////////////////////////////////////////////\n @SuppressLint(\"UseSparseArrays\")\n public SimpleInstances getTestInstances(String testStr) {\n\n int[] attributes;\n double[][] matrix;\n\n String relation = \"relation\";\n Map<Integer, Map<String, Integer>> nominalAttrs = new HashMap<Integer, Map<String, Integer>>();\n nominalAttrs = ArffReader.globalNominalAttrs;\n attributes = ArffReader.globalAttributes;\n\n String ln = \"\";\n matrix = new double[1][attrSize];\n\n ln = testStr;\n\n String[] s = ln.split(COMM);\n for (int i = 0; i < s.length; i++) {\n s[i] = s[i].trim();\n }\n for (int i = 0; i < s.length; i++) {\n if(i >= attributes.length)\n break;\n if (attributes[i] < 1) {// Numeric or Real attributes\n if (s[i].equals(UNKNOWN)) {\n matrix[0][i] = Double.MAX_VALUE;\n } else {\n matrix[0][i] = Double.parseDouble(s[i]);\n }\n } else {\n if (s[i].equals(UNKNOWN)) {\n matrix[0][i] = 0;\n } else {\n Map<String, Integer> temp = nominalAttrs.get(i);\n if(temp == null){\n matrix[0][i] = 0;\n }\n else{\n// Log.i(\"rHAR\", String.format(\"i = %d, s[i] = %s\", i, s[i]));\n Integer tempInt = temp.get(s[i].trim());\n if(tempInt != null){\n matrix[0][i] = tempInt;\n }\n }\n }\n }\n }\n\n Log.i(\"rHAR\", \"attributes\" + Arrays.toString(attributes));\n Log.i(\"rHAR\", \"matrix\" + Arrays.toString(matrix[0]));\n return new SimpleInstances(attributes, matrix, null, relation);\n\n }\n\n /**\n * Get instances from dense source file.\n * \n * @return\n */\n private SimpleInstances getDenseInstances() {\n BufferedReader br;\n try {\n\n int[] attributes;\n double[][] matrix;\n\n String relation = \"relation\";\n Map<Integer, Map<String, Integer>> nominalAttrs = new HashMap<Integer, Map<String, Integer>>();\n\n String ln;\n int c = 0;\n int instSize = 0;\n boolean isHeader = true;\n br = new BufferedReader(new FileReader(filePath));\n while ((ln = br.readLine()) != null) {\n if (ln.length() < 1 || ln.startsWith(\"%\")) {\n continue;\n }\n if (ln.equalsIgnoreCase(DATA)) {\n isHeader = false;\n continue;\n }\n if (isHeader) {\n String[] s = ln.split(SPLIT, 3);\n for (int i = 0; i < s.length; i++) {\n s[i] = s[i].trim();\n }\n if (s.length > 1) {\n if (s[0].equalsIgnoreCase(RELATION)) {\n relation = s[1];\n } else if (s.length >= 3 && s[0].equalsIgnoreCase(ATTRIBUTE)) {\n\n if (s[2].startsWith(\"{\")) {\n\n s[2] = s[2].substring(1, s[2].length() - 1);\n String[] ss = s[2].split(COMM);\n int t = 0;\n Map<String, Integer> nMap = new HashMap<String, Integer>();\n for (String e : ss) {\n nMap.put(e.trim(), t);\n t++;\n\n }\n nominalAttrs.put(c, nMap);\n }\n c++;\n }\n }\n } else {\n instSize++;\n }\n }\n\n br.close();\n matrix = new double[instSize][attrSize];\n attributes = new int[attrSize];\n\n c = 0;\n int ic = 0;\n instSize = 0;\n isHeader = true;\n br = new BufferedReader(new FileReader(filePath));\n while ((ln = br.readLine()) != null) {\n if (ln.length() < 1 || ln.startsWith(\"%\")) {\n continue;\n }\n if (ln.equalsIgnoreCase(DATA)) {\n isHeader = false;\n c = 0;\n continue;\n }\n if (isHeader) {\n String[] s = ln.split(SPLIT, 3);\n for (int i = 0; i < s.length; i++) {\n s[i] = s[i].trim();\n }\n if (s.length >= 3 && s[0].equalsIgnoreCase(ATTRIBUTE) && c < attrSize) {\n if (s[2].equalsIgnoreCase(NUMERIC)) {\n attributes[c] = N_NUMERIC;\n } else if (s[2].equalsIgnoreCase(REAL)) {\n attributes[c] = N_REAL;\n } else if (s[2].startsWith(\"{\")) {\n attributes[c] = nominalAttrs.get(c).size();\n }\n c++;\n }\n } else {\n String[] s = ln.split(COMM);\n for (int i = 0; i < s.length; i++) {\n s[i] = s[i].trim();\n }\n System.out.print(Arrays.toString(s));\n for (int i = 0; i < (s.length > attributes.length ? attributes.length\n : s.length); i++) {\n\n if (attributes[i] < 1) {// Numeric or Real attributes\n if (s[i].equals(UNKNOWN)) {\n matrix[ic][i] = Double.MAX_VALUE;\n } else {\n matrix[ic][i] = Double.parseDouble(s[i]);\n }\n } else {\n if (s[i].equals(UNKNOWN)) {\n matrix[ic][i] = 0;\n } else {\n matrix[ic][i] = nominalAttrs\n .get(i)\n .get(s[i].trim());\n }\n }\n }\n\n if (instSize % 1000 == 0) {\n // System.out.println(\"2:\"+instSize);\n }\n\n ic++;\n instSize++;\n\n /*\n * if(instSize>=num){ break; }\n */\n }\n }\n\n br.close();\n globalNominalAttrs = nominalAttrs;\n globalAttributes = attributes;\n return new SimpleInstances(attributes, matrix, null, relation);\n\n } catch (IOException e) {\n\n e.printStackTrace();\n }\n\n return null;\n }\n\n /**\n * Get current source file path.\n * \n * @return the filePath\n */\n public String getFilePath() {\n return filePath;\n }\n\n /**\n * Set current source file path.\n * \n * @param filePath the filePath to set\n */\n public void setFilePath(String filePath) {\n this.filePath = filePath;\n }\n\n /**\n * Set the size of attributes.\n * \n * @param attrSize\n */\n public void setAttrSize(int attrSize) {\n this.attrSize = attrSize;\n }\n\n}",
"public class TreeBuilder {\n\n /**\n * @see #type\n */\n public static final byte CLASSIFICATION = 0;\n\n /**\n * @see #type\n */\n public static final byte REGRESSION = 1;\n\n /**\n * @see #type\n */\n public static final byte CBR_RDT = 2;\n\n /**\n * Random number generator.\n */\n private Random rd;\n\n /**\n * The type indicate what kind of tree will be built. 0: classification, 1:\n * regression, 2: CBR-RDT\n */\n private byte type;\n\n /**\n * The max depth of the tree. When an branch achieve the threshold, the\n * branch will stop grow.\n */\n private int maxDeep;\n\n /**\n * The max number of instances should be in a leaf node. It is not a hard\n * threshold. When a branch's number of instances are less than or equals to\n * the property, the branch will stop grow.\n */\n private int maxS;\n\n /**\n * The class number of the data. Note, the class attributes can only in the\n * tail of each instance attribute vector.\n */\n private int clsSize;\n\n /**\n * The training data set.\n */\n private Instances insts;\n\n /**\n * Current level of nodes of the trees.\n */\n private List<Node> level;\n\n /**\n * The instance ids belong to the nodes in current {@link #level}\n */\n private List<int[]> ions;\n\n /**\n * The parent nodes of the nodes in current {@link #level}\n */\n private Map<Node, Node> parents;\n\n /**\n * Create the object.\n *\n * @param randomSeed\n * Random seed.\n * @param type\n * The {@link #type} of the tree builder.\n *\n */\n public TreeBuilder(long randomSeed, byte type) {\n rd = new Random(randomSeed);\n this.type = type;\n this.clsSize = 1;// default = 1\n\n }\n\n /**\n * Set the number of classes.\n *\n * @param clsSize\n * Number of classes.\n */\n public void setClsSize(int clsSize) {\n this.clsSize = clsSize;\n }\n\n /**\n * Get the training data set.\n *\n * @return the instances\n */\n public Instances getInstances() {\n return insts;\n }\n\n /**\n * Set the training data set.\n *\n * @param instances\n * the instances to set\n */\n public void setInstances(Instances instances) {\n this.insts = instances;\n }\n\n /**\n * @return the maxDeep\n */\n public int getMaxDeep() {\n return maxDeep;\n }\n\n /**\n * Set the max depth of the tree to build. Should be used after set a\n * instances\n *\n * @param maxDeep\n * the maxDeep to set\n */\n public void setMaxDeep(int maxDeep) {\n this.maxDeep = maxDeep < insts.getAttrSize() - clsSize + 1 ? maxDeep : insts.getAttrSize() - clsSize + 1;\n }\n\n /**\n * @see #maxS\n * @return the maxS\n */\n public int getMaxS() {\n return maxS;\n }\n\n /**\n * @see #maxS\n * @param maxS\n */\n public void setMaxS(int maxS) {\n this.maxS = maxS;\n }\n\n /**\n * @see #clsSize\n * @return The number of classes.\n */\n public int getClsSize() {\n return clsSize;\n }\n\n /**\n * @param randomSeed\n */\n public void setRandomSeed(long randomSeed) {\n rd = new Random(randomSeed);\n }\n\n /**\n * Initialize the tree builder.\n */\n public void init() {\n\n level = new LinkedList<Node>();\n ions = new LinkedList<int[]>();\n parents = new HashMap<Node, Node>();\n }\n\n /**\n * Clear the tree builder.\n */\n public void clear() {\n level = null;\n ions = null;\n parents = null;\n }\n\n /**\n * Build trees.\n *\n * @param treeNum\n * The number of trees to build.\n * @return\n */\n public Node[] buildTrees(int treeNum) {\n // setInstances(insts);\n Node[] trees = new Node[treeNum];\n for (int i = 0; i < trees.length; i++) {\n trees[i] = build();\n }\n clear();\n return trees;\n }\n\n /**\n * Build a tree.\n *\n * @return\n */\n private Node build() {\n init();\n\n InnerNode root = null;\n if (maxDeep == 1 || insts.size() <= maxS) {\n return null;\n }\n\n root = new InnerNode();\n\n int[] ion = new int[insts.size()];\n for (int i = 0; i < insts.size(); i++) {\n ion[i] = i;\n }\n level.add(root);\n ions.add(ion);\n\n for (int i = 0; i < maxDeep; i++) {\n incLevel(root);\n if (level.isEmpty()) {\n break;\n }\n }\n\n Iterator<int[]> itor = ions.iterator();\n for (Node node : level) {\n ion = itor.next();\n InnerNode parent = (InnerNode) parents.get(node);\n for (int i = 0; i < parent.children.length; i++) {\n if (parent.children[i].equals(node)) {\n parent.children[i] = closeNode(node, ion);\n parents.remove(node);\n break;\n }\n }\n }\n return root;\n }\n\n /**\n * Build a level of a tree.\n *\n * @param root\n * The root of the tree. It is just used for attribute selection.\n * @return\n */\n\n private void incLevel(Node root) {\n\n int[] attrs = insts.getAttributes();\n\n List<Node> nextLevel = new LinkedList<Node>();\n List<int[]> nextions = new LinkedList<int[]>();\n\n Iterator<int[]> itor = ions.iterator();\n for (Node e : level) {\n\n InnerNode node = (InnerNode) e;\n int[] ion = itor.next();\n if (ion.length <= maxS) {\n InnerNode parent = (InnerNode) parents.get(e);\n for (int i = 0; i < parent.children.length; i++) {\n if (parent.children[i].equals(e)) {\n parent.children[i] = closeNode(node, ion);\n parents.remove(e);\n break;\n }\n }\n node.clear();\n continue;\n }\n\n int attr = selectAttr(node, (InnerNode) root, insts.get(ion[0]));\n\n if (attr == -1) {\n InnerNode parent = (InnerNode) parents.get(e);\n for (int i = 0; i < parent.children.length; i++) {\n if (parent.children[i].equals(e)) {\n parent.children[i] = closeNode(node, ion);\n parents.remove(e);\n break;\n }\n }\n node.clear();\n continue;\n }\n\n node.attr = attr;\n if (attrs[attr] > 0) {// nominal attribute\n node.addChildren(attrs[attr]);\n int[] tmp = new int[ion.length];\n for (int i = 0; i < ion.length; i++) {\n tmp[i] = (int) insts.get(ion[i]).getValue(attr);\n }\n BiArrays.sort(tmp, ion);\n List<Integer> splits = new ArrayList<Integer>();\n double t = tmp[0];\n for (int i = 0; i < tmp.length; i++) {\n if (tmp[i] != t) {\n t = tmp[i];\n splits.add(i);\n }\n }\n splits.add(tmp.length);\n\n int psp = 0;\n for (int sp : splits) {\n int[] ioc = new int[sp - psp];\n System.arraycopy(ion, psp, ioc, 0, sp - psp);\n if (ioc.length <= maxS) {\n Leaf leaf = new Leaf();\n closeNode(leaf, ioc);\n node.addChild(tmp[sp - 1], leaf);\n } else {\n InnerNode nNode = new InnerNode();\n // nNode.parent = node;\n node.addChild(tmp[sp - 1], nNode);\n nextLevel.add(nNode);\n nextions.add(ioc);\n parents.put(nNode, e);\n }\n psp = sp;\n }\n\n node.clear();\n } else {// numerical attribute\n\n node.addChildren(2);\n double[] tmp = new double[ion.length];\n int c = 0;\n Set<Double> values = new HashSet<Double>();\n for (int i = 0; i < ion.length; i++) {\n double value = insts.get(ion[i]).getValue(attr);\n if (value == Double.MAX_VALUE) {\n c++;\n }\n tmp[i] = value;\n values.add(value);\n }\n\n if (values.size() == 1) {\n if (ion.length <= maxS) {\n InnerNode parent = (InnerNode) parents.get(e);\n if (parent == null) {\n root = closeNode(node, ion);\n } else {\n for (int i = 0; i < parent.children.length; i++) {\n if (parent.children[i].equals(e)) {\n parent.children[i] = closeNode(node, ion);\n parents.remove(e);\n break;\n }\n }\n }\n node.clear();\n continue;\n } else {\n node.attr = -1;\n nextLevel.add(node);\n nextions.add(ion);\n continue;\n }\n }\n\n List<Double> valueList = new ArrayList<Double>(values);\n Collections.sort(valueList);\n if (values.size() <= 2) {\n node.split = valueList.get(0);\n } else {\n node.split = valueList.get(rd.nextInt(valueList.size() - 2) + 1);\n }\n\n BiArrays.sort(tmp, ion);\n int splitInst = Arrays.binarySearch(tmp, node.split);\n while (splitInst < tmp.length\n && tmp[splitInst] == tmp[splitInst + 1]) {\n splitInst++;\n }\n\n int[] ioc = new int[splitInst + 1];\n System.arraycopy(ion, 0, ioc, 0, splitInst + 1);\n if (ioc.length <= maxS) {\n Leaf leaf = new Leaf();\n closeNode(leaf, ioc);\n node.addChild(1, leaf);\n } else {\n InnerNode nNode = new InnerNode();\n // nNode.parent = node;\n node.addChild(1, nNode);\n nextLevel.add(nNode);\n nextions.add(ioc);\n parents.put(nNode, e);\n }\n\n int t = tmp.length - c - splitInst - 1;\n if (t > 0) {\n ioc = new int[t];\n System.arraycopy(ion, splitInst + 1, ioc, 0, t);\n if (ioc.length <= maxS) {\n Leaf leaf = new Leaf();\n closeNode(leaf, ioc);\n node.addChild(2, leaf);\n } else {\n InnerNode nNode = new InnerNode();\n // nNode.parent = node;\n node.addChild(2, nNode);\n nextLevel.add(nNode);\n nextions.add(ioc);\n parents.put(nNode, e);\n }\n }\n\n if (c > 0) {\n ioc = new int[c];\n System.arraycopy(ion, tmp.length - c, ioc, 0, c);\n if (ioc.length <= maxS) {\n Leaf leaf = new Leaf();\n closeNode(leaf, ioc);\n node.addChild(0, leaf);\n } else {\n InnerNode nNode = new InnerNode();\n // nNode.parent = node;\n node.addChild(0, nNode);\n nextLevel.add(nNode);\n nextions.add(ioc);\n parents.put(nNode, e);\n }\n }\n\n node.clear();\n }\n parents.remove(e);\n }\n level = nextLevel;\n ions = nextions;\n }\n\n /**\n * Close a node to the leaf node.\n *\n * @param node\n * The node to be closed.\n * @param ion\n * The instance ids on the node.\n * @return Leaf node.\n */\n private Leaf closeNode(Node node, int[] ion) {\n switch (type) {\n case CLASSIFICATION:\n return closeClassificationNode(node, ion);\n case REGRESSION:\n return closeRegressionNode(node, ion);\n case CBR_RDT:\n return closeCBRNode(node, ion);\n\n }\n return null;\n }\n\n /**\n * Close a node for classification.\n *\n * @param node\n * The node to be closed.\n * @param ion\n * The instance ids on the node.\n * @return Leaf node.\n */\n private Leaf closeClassificationNode(Node node, int[] ion) {\n Leaf leaf;\n if (node instanceof Leaf) {\n leaf = (Leaf) node;\n } else {\n leaf = new Leaf();\n }\n\n leaf.addDists(insts.getAttributes()[insts.getAttrSize() - clsSize]);//clsSize should be 1\n for (int i = 0; i < ion.length; i++) {\n int instId = ion[i];\n for (int j = 0; j < clsSize; j++) {\n leaf.incDist((int) insts.get(instId).getValue(\n insts.getAttrSize() - 1));\n }\n }\n leaf.clear();\n for (int i = 0; i < leaf.dist.length; i++) {\n leaf.dist[i] /= ion.length;\n }\n leaf.size = ion.length;\n node = null;\n return leaf;\n }\n\n\n private Leaf closeRegressionNode(Node node, int[] ion) {\n\n Leaf leaf;\n if (node instanceof Leaf) {\n leaf = (Leaf) node;\n } else {\n leaf = new Leaf();\n }\n\n\n for (int i = 0; i < ion.length; i++) {\n leaf.addValue(insts.get(ion[i]).getValue(insts.getAttrSize() - clsSize));//clsSize should be 1\n\n }\n leaf.clear();\n\n leaf.v /= ion.length;\n leaf.size = ion.length;\n node = null;\n\n return leaf;\n }\n\n /**\n * Close a node for multi-label classification.\n *\n * @param node\n * The node to be closed.\n * @param ion\n * The instance ids on the node.\n * @return Leaf node.\n */\n private Leaf closeCBRNode(Node node, int[] ion) {\n Leaf leaf;\n if (node instanceof Leaf) {\n leaf = (Leaf) node;\n } else {\n leaf = new Leaf();\n }\n\n leaf.addDists(clsSize);\n for (int i = 0; i < ion.length; i++) {\n int instId = ion[i];\n int lnum = 0;\n for (int j = 0; j < clsSize; j++) {\n double t = insts.get(instId).getValue(\n insts.getAttrSize() - clsSize + j);\n if (t == 1.0) {\n leaf.incDist(j);\n lnum++;\n }\n }\n leaf.addValue(lnum);\n }\n leaf.clear();\n for (int i = 0; i < leaf.dist.length; i++) {\n leaf.dist[i] /= ion.length;\n }\n leaf.v /= ion.length;\n leaf.size = ion.length;\n node = null;\n return leaf;\n }\n\n /**\n * Randomly select a attribute.\n *\n * @param node\n * @param root\n * @param inst\n * @return\n */\n private int selectAttr(InnerNode node, InnerNode root, Instance inst) {\n\n int[] attributes = insts.getAttributes();\n int attrSize = insts.getAttrSize() - clsSize;\n int t0 = rd.nextInt(attrSize);\n\n Node tNode = root;\n Set<Integer> usedAttrs = new HashSet<Integer>();\n while (tNode instanceof InnerNode) {\n InnerNode tn = (InnerNode) tNode;\n if (tn.attr == -1) {\n break;\n }\n if (attributes[tn.attr] > 0) {// nonominal attribute\n usedAttrs.add(tn.attr);\n tNode = tn.getChild((int) inst.getValue(tn.attr));\n } else {// numerical attribute\n double t = inst.getValue(tn.attr);\n if (t == Double.NaN) {\n tNode = tn.getChild(0);\n } else if (t <= tn.split) {\n tNode = tn.getChild(1);\n } else if (t > tn.split) {\n tNode = tn.getChild(2);\n }\n }\n }\n\n boolean flag = true;\n int t1 = t0;\n while (usedAttrs.contains(t0)) {\n t0++;\n t0 %= attrSize;\n if (t0 == t1) {\n flag = false;\n break;\n }\n }\n\n return flag ? t0 : -1;\n }\n\n}",
"public interface Node extends Serializable {\n\n /**\n * An parameter for claiming or reclaiming the\n * space of the arrays may be used in <code>Node</code>\n */\n double frac = 0.75;\n\n /**\n * Clear the node to reduce the space consumption.\n */\n void clear();\n\n}"
] | import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import com.talkingdata.myna.sensor.Feature;
import com.talkingdata.myna.sensor.SensorData;
import com.talkingdata.myna.sensor.SensorFeature;
import com.talkingdata.myna.tools.Utils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Locale;
import dice.data.Instances;
import dice.data.io.ArffReader;
import dice.tree.builder.TreeBuilder;
import dice.tree.structure.Node; | package com.talkingdata.myna;
class MynaTrainTest {
private MynaTrainTestCallback ttcallback;
private Context context;
private int attrSize = 30;
private int labelNum = 6;
private int maxS = 10;
private int treeNum = 3;
private int maxTreeDepth = 15;
private Node[] trees = new Node[treeNum];
private SparseArray<Feature> rfFeatures = new SparseArray<>();
private SparseIntArray rfLabels = new SparseIntArray(); | private SensorData[] periodVal; | 1 |
Spedge/hangar | hangar-api/src/main/java/com/spedge/hangar/index/memory/InMemoryIndex.java | [
"@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = \"index\")\n@JsonSubTypes(\n { \n @JsonSubTypes.Type(value = InMemoryIndex.class, name = \"in-memory\"),\n @JsonSubTypes.Type(value = ZooKeeperIndex.class, name = \"zookeeper\"), \n })\npublic interface IIndex\n{\n\n /**\n * Confirms that this particular artifact is registered\n * @param key IndexKey for Artifact\n * @return True is Artifact is registered\n * @throws IndexException If this check cannot be performed.\n */\n boolean isArtifact(IndexKey key) throws IndexException;\n\n /**\n * Add an Artifact to the Index.\n * @param key IndexKey for Artifact\n * @param artifact Artifact to be registered with Index\n * @throws IndexConfictException If this artifact exists and can't be overwritten\n * @throws IndexException If this artifact cannot be registered for another reason\n */\n void addArtifact(IndexKey key, IndexArtifact artifact)\n throws IndexConfictException, IndexException;\n\n // Once we're happy with the artifact we want to get,\n // we need details of where to stream it from.\n IndexArtifact getArtifact(IndexKey key) throws IndexException;\n\n // When the index is empty on startup, we load it\n // from the appropriate storage.\n void load(RepositoryType type, IStorage storage, String uploadPath)\n throws StorageException, IndexException;\n\n // This allows a upload to reserve a path before uploading to it.\n ReservedArtifact addReservationKey(IndexKey key) throws IndexException;\n\n // This allows the update to the reservation to the completed location.\n void addReservedArtifact(IndexKey key, ReservedArtifact reservation, IndexArtifact ia)\n throws IndexConfictException, IndexException;\n}",
"public abstract class IndexArtifact implements Serializable\n{\n private static final long serialVersionUID = -5720959937441417671L;\n private String location;\n\n public IndexArtifact(String location)\n {\n this.location = location;\n }\n\n public String getLocation()\n {\n return this.location;\n }\n\n /**\n * Checks if this type of file (on postfix)\n * has been stored in the storage layer.\n * \n * @param filename Full filename to check\n * @return True if file has been stored\n */\n public boolean isStoredFile(String filename)\n {\n for (String key : getFileTypes().keySet())\n {\n if (filename.endsWith(key))\n {\n return getFileTypes().get(key);\n }\n }\n return false;\n }\n\n /**\n * Sets that this particular type of file has been stored\n * within the storage layer for later reference.\n * \n * @param filename Full filename to check\n */\n public void setStoredFile(String filename)\n {\n for (String key : getFileTypes().keySet())\n {\n if (filename.endsWith(key))\n {\n getFileTypes().put(key, true);\n }\n }\n }\n\n protected abstract Map<String, Boolean> getFileTypes();\n}",
"public class IndexConfictException extends Exception\n{\n\n private static final long serialVersionUID = -4856615780463752787L;\n\n}",
"public class IndexException extends Exception\n{\n private static final long serialVersionUID = 6617225189161552873L;\n \n public IndexException(Exception ie)\n {\n super(ie);\n }\n\n public IndexException(String message)\n {\n super(message);\n }\n}",
"public class IndexKey\n{\n private String key;\n private RepositoryType type = RepositoryType.UNKNOWN;\n\n public IndexKey(RepositoryType type, String key)\n {\n this.key = key;\n this.type = type;\n }\n\n public RepositoryType getType()\n {\n return type;\n }\n\n public String toPath()\n {\n return key;\n }\n\n public String toString()\n {\n return type.getLanguage() + \":\" + key;\n }\n\n /* (non-Javadoc)\n * @see java.lang.Object#hashCode()\n */\n @Override\n public int hashCode()\n {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((key == null) ? 0 : key.hashCode());\n result = prime * result + ((type.getLanguage() == null) ? 0 : type.getLanguage().hashCode());\n return result;\n }\n\n /* (non-Javadoc)\n * @see java.lang.Object#equals(java.lang.Object)\n */\n @Override\n public boolean equals(Object obj)\n {\n if (this == obj)\n {\n return true;\n }\n if (obj == null)\n {\n return false;\n }\n if (getClass() != obj.getClass())\n {\n return false;\n }\n IndexKey other = (IndexKey) obj;\n if (key == null)\n {\n if (other.key != null)\n {\n return false;\n }\n }\n else if (!key.equals(other.key))\n {\n return false;\n }\n if (type.getLanguage() != other.type.getLanguage())\n {\n return false;\n }\n return true;\n }\n}",
"public class ReservedArtifact extends IndexArtifact\n{\n private static final long serialVersionUID = -5676826253822808582L;\n private final UUID id;\n private Map<String, Boolean> files = new HashMap<String, Boolean>();\n\n public ReservedArtifact(String location)\n {\n super(location);\n id = UUID.randomUUID();\n }\n\n @Override\n protected Map<String, Boolean> getFileTypes()\n {\n return files;\n }\n\n public UUID getId()\n {\n return id;\n }\n\n @Override\n public boolean equals(Object object)\n {\n // self check\n if (this == object)\n {\n return true;\n }\n // null check\n if (object == null)\n {\n return false;\n }\n // type check and cast\n if (getClass() != object.getClass())\n {\n return false;\n }\n \n ReservedArtifact ra = (ReservedArtifact) object;\n\n return Objects.equals(getLocation(), ra.getLocation())\n && Objects.equals(getId(), ra.getId())\n && Objects.equals(getFileTypes(), ra.getFileTypes());\n }\n}",
"public enum RepositoryType\n{\n RELEASE_JAVA(RepositoryLanguage.JAVA), \n SNAPSHOT_JAVA(RepositoryLanguage.JAVA), \n PROXY_JAVA(RepositoryLanguage.JAVA), \n PROXY_PYTHON(RepositoryLanguage.PYTHON),\n UNKNOWN(RepositoryLanguage.UNKNOWN);\n\n private RepositoryLanguage lang;\n\n RepositoryType(RepositoryLanguage lang)\n {\n this.lang = lang;\n }\n\n public RepositoryLanguage getLanguage()\n {\n return lang;\n }\n}",
"@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = \"store\")\n@JsonSubTypes(\n { @JsonSubTypes.Type(value = LocalStorage.class, name = \"local\"),\n @JsonSubTypes.Type(value = S3Storage.class, name = \"s3\"), \n })\npublic interface IStorage\n{\n void initialiseStorage(IStorageTranslator st, String uploadPath) throws StorageException;\n \n HealthCheck getHealthcheck();\n\n IStorageTranslator getStorageTranslator(String prefixPath);\n \n List<IndexKey> getArtifactKeys(String uploadPath) throws StorageException;\n\n StreamingOutput getArtifactStream(IndexArtifact key, String filename);\n \n IndexArtifact getIndexArtifact(IndexKey key, String uploadPath) throws IndexException;\n\n void uploadReleaseArtifactStream(IndexArtifact ia, StorageRequest sr) throws StorageException;\n\n void uploadSnapshotArtifactStream(IndexArtifact ia, StorageRequest sr) throws StorageException;\n \n String getPath();\n}",
"public abstract class StorageException extends Exception\n{\n public StorageException(Exception exception)\n {\n super(exception);\n }\n\n private static final long serialVersionUID = -4510536728418574349L;\n}"
] | import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.spedge.hangar.index.IIndex;
import com.spedge.hangar.index.IndexArtifact;
import com.spedge.hangar.index.IndexConfictException;
import com.spedge.hangar.index.IndexException;
import com.spedge.hangar.index.IndexKey;
import com.spedge.hangar.index.ReservedArtifact;
import com.spedge.hangar.repo.RepositoryType;
import com.spedge.hangar.storage.IStorage;
import com.spedge.hangar.storage.StorageException; | package com.spedge.hangar.index.memory;
public class InMemoryIndex implements IIndex
{
private Map<String, IndexArtifact> index;
protected final Logger logger = LoggerFactory.getLogger(InMemoryIndex.class);
public InMemoryIndex()
{
this.index = new HashMap<String, IndexArtifact>();
}
public boolean isArtifact(IndexKey key)
{
return index.containsKey(key.toString());
}
/**
* Registers an Artifact with the Index.
*/
public void addArtifact(IndexKey key, IndexArtifact artifact) throws IndexConfictException
{
if (index.containsKey(key.toString()))
{ | if (!(index.get(key.toString()) instanceof ReservedArtifact)) | 5 |
xuxueli/xxl-api | xxl-api-admin/src/main/java/com/xxl/api/admin/controller/XxlApiDocumentController.java | [
"public class RequestConfig {\n\n /**\n * Request Method\n */\n public enum RequestMethodEnum {\n POST,GET,PUT,DELETE,HEAD,OPTIONS,PATCH;\n }\n\n /**\n * Request Headers\n */\n public static List<String> requestHeadersEnum = new LinkedList<String>();\n static {\n requestHeadersEnum.add(\"Accept\");\n requestHeadersEnum.add(\"Accept-Charset\");\n requestHeadersEnum.add(\"Accept-Encoding\");\n requestHeadersEnum.add(\"Accept-Language\");\n requestHeadersEnum.add(\"Accept-Ranges\");\n requestHeadersEnum.add(\"Authorization\");\n requestHeadersEnum.add(\"Cache-Control\");\n requestHeadersEnum.add(\"Connection\");\n requestHeadersEnum.add(\"Cookie\");\n requestHeadersEnum.add(\"Content-Length\");\n requestHeadersEnum.add(\"Content-Type\");\n requestHeadersEnum.add(\"Date\");\n requestHeadersEnum.add(\"Expect\");\n requestHeadersEnum.add(\"From\");\n requestHeadersEnum.add(\"Host\");\n requestHeadersEnum.add(\"If-Match\");\n requestHeadersEnum.add(\"If-Modified-Since\");\n requestHeadersEnum.add(\"If-None-Match\");\n requestHeadersEnum.add(\"If-Range\");\n requestHeadersEnum.add(\"If-Unmodified-Since\");\n requestHeadersEnum.add(\"Max-Forwards\");\n requestHeadersEnum.add(\"Pragma\");\n requestHeadersEnum.add(\"Proxy-Authorization\");\n requestHeadersEnum.add(\"Range\");\n requestHeadersEnum.add(\"Referer\");\n requestHeadersEnum.add(\"TE\");\n requestHeadersEnum.add(\"Upgrade\");\n requestHeadersEnum.add(\"User-Agent\");\n requestHeadersEnum.add(\"Via\");\n requestHeadersEnum.add(\"Warning\");\n }\n\n /**\n * Query Param, Type\n */\n public enum QueryParamTypeEnum {\n\n STRING(\"string\"),\n BOOLEAN(\"boolean\"),\n SHORT(\"short\"),\n INT(\"int\"),\n LONG(\"long\"),\n FLOAT(\"float\"),\n DOUBLE(\"double\"),\n DATE(\"date\"),\n DATETIME(\"datetime\"),\n JSON(\"json\"),\n BYTE(\"byte\");\n\n public String title;\n QueryParamTypeEnum(String title) {\n this.title = title;\n }\n }\n\n /**\n * Query Param\n */\n public static class QueryParam {\n\n private boolean notNull; // 是否必填\n private String name; // 参数名称\n private String type; // 参数类型\n private String desc; // 参数说明\n\n public boolean isNotNull() {\n return notNull;\n }\n\n public void setNotNull(boolean notNull) {\n this.notNull = notNull;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getDesc() {\n return desc;\n }\n\n public void setDesc(String desc) {\n this.desc = desc;\n }\n }\n\n /**\n * Reponse Headers, Content-Type\n */\n public enum ResponseContentType{\n JSON(\"application/json;charset=UTF-8\"),\n XML(\"text/xml\"),\n HTML(\"text/html;\"),\n TEXT(\"text/plain\"),\n JSONP(\"application/javascript\");\n\n public final String type;\n ResponseContentType(String type) {\n this.type = type;\n }\n public static ResponseContentType match(String name){\n if (name != null) {\n for (ResponseContentType item: ResponseContentType.values()) {\n if (item.name().equals(name)) {\n return item;\n }\n }\n }\n return null;\n }\n }\n\n}",
"public class ArrayTool {\n\n public static final int INDEX_NOT_FOUND = -1;\n\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n public static boolean isEmpty(final Object[] array) {\n return getLength(array) == 0;\n }\n\n public static boolean isNotEmpty(final Object[] array) {\n return !isEmpty(array);\n }\n\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return indexOf(array, objectToFind) != INDEX_NOT_FOUND;\n }\n\n public static int indexOf(final Object[] array, final Object objectToFind) {\n if (isEmpty(array)) {\n return INDEX_NOT_FOUND;\n }\n for (int i = 0; i < array.length; i++) {\n if ((objectToFind == null && array[i] == null)\n || (objectToFind != null && objectToFind.equals(array[i]) )\n ) {\n return i;\n }\n }\n return INDEX_NOT_FOUND;\n }\n\n public static void main(String[] args) {\n System.out.println(isEmpty(new String[]{\"a\", \"b\", \"c\"}));\n System.out.println(contains(StringTool.split(\"1,2,3\", \",\"), String.valueOf(1)));\n System.out.println(contains(StringTool.split(\"1,2,3\", \",\"), String.valueOf(11)));\n }\n}",
"public class JacksonUtil {\n\tprivate static Logger logger = LoggerFactory.getLogger(JacksonUtil.class);\n\n private final static ObjectMapper objectMapper = new ObjectMapper();\n public static ObjectMapper getInstance() {\n return objectMapper;\n }\n\n /**\n * bean、array、List、Map --> json\n * \n * @param obj\n * @return json string\n * @throws Exception\n */\n public static String writeValueAsString(Object obj) {\n \ttry {\n\t\t\treturn getInstance().writeValueAsString(obj);\n\t\t} catch (JsonGenerationException e) {\n\t\t\tlogger.error(e.getMessage(), e);\n\t\t} catch (JsonMappingException e) {\n\t\t\tlogger.error(e.getMessage(), e);\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(e.getMessage(), e);\n\t\t}\n return null;\n }\n\n /**\n * string --> bean、Map、List(array)\n * \n * @param jsonStr\n * @param clazz\n * @return obj\n * @throws Exception\n */\n public static <T> T readValue(String jsonStr, Class<T> clazz) {\n \ttry {\n\t\t\treturn getInstance().readValue(jsonStr, clazz);\n\t\t} catch (JsonParseException e) {\n\t\t\tlogger.error(e.getMessage(), e);\n\t\t} catch (JsonMappingException e) {\n\t\t\tlogger.error(e.getMessage(), e);\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(e.getMessage(), e);\n\t\t}\n \treturn null;\n }\n public static <T> T readValueRefer(String jsonStr, TypeReference typeReference) {\n \ttry {\n\t\t\treturn getInstance().readValue(jsonStr, typeReference);\t\t// new TypeReference<T>() { }\n\t\t} catch (JsonParseException e) {\n\t\t\tlogger.error(e.getMessage(), e);\n\t\t} catch (JsonMappingException e) {\n\t\t\tlogger.error(e.getMessage(), e);\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(e.getMessage(), e);\n\t\t}\n \treturn null;\n }\n\n public static void main(String[] args) {\n\t\ttry {\n\t\t\tMap<String, String> map = new HashMap<String, String>();\n\t\t\tmap.put(\"aaa\", \"111\");\n\t\t\tmap.put(\"bbb\", \"222\");\n\t\t\tString json = writeValueAsString(map);\n\t\t\tSystem.out.println(json);\n\t\t\tSystem.out.println(readValue(json, Map.class));\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(e.getMessage(), e);\n\t\t}\n\t}\n}",
"public class StringTool {\n\n public static final String EMPTY = \"\";\n\n public static boolean isBlank(final String str) {\n return str==null || str.trim().length()==0;\n }\n\n public static boolean isNotBlank(final String str) {\n return !isBlank(str);\n }\n\n\n public static String[] split(final String str, final String separatorChars) {\n if (isBlank(str)) {\n return null;\n }\n if (isBlank(separatorChars)) {\n return new String[]{str.trim()};\n }\n List<String> list = new ArrayList<>();\n for (String item : str.split(separatorChars)) {\n if (isNotBlank(item)) {\n list.add(item.trim());\n }\n }\n return list.toArray(new String[list.size()]);\n }\n\n public static String join(final String[] array, String separator) {\n if (array == null) {\n return null;\n }\n if (separator == null) {\n separator = EMPTY;\n }\n final StringBuilder buf = new StringBuilder();\n\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buf.append(separator);\n }\n if (array[i] != null) {\n buf.append(array[i]);\n }\n }\n return buf.toString();\n }\n\n\n public static void main(String[] args) {\n System.out.println(isBlank(\" \"));\n System.out.println(isNotBlank(\"qwe\"));\n System.out.println(split(\"a,b,cc,\", \",\"));\n System.out.println(join(new String[]{\"a\",\"b\",\"c\"},\",\"));\n }\n\n}",
"public interface IXxlApiDataTypeService {\n\t\n\tpublic XxlApiDataType loadDataType(int dataTypeId);\n\n}",
"@Configuration\npublic class LoginService {\n\n public static final String LOGIN_IDENTITY = \"XXL_API_LOGIN_IDENTITY\";\n\n @Resource\n private IXxlApiUserDao xxlApiUserDao;\n\n private String makeToken(XxlApiUser xxlApiUser){\n String tokenJson = JacksonUtil.writeValueAsString(xxlApiUser);\n String tokenHex = new BigInteger(tokenJson.getBytes()).toString(16);\n return tokenHex;\n }\n private XxlApiUser parseToken(String tokenHex){\n XxlApiUser xxlApiUser = null;\n if (tokenHex != null) {\n String tokenJson = new String(new BigInteger(tokenHex, 16).toByteArray()); // username_password(md5)\n xxlApiUser = JacksonUtil.readValue(tokenJson, XxlApiUser.class);\n }\n return xxlApiUser;\n }\n\n\n /**\n * login\n *\n * @param response\n * @param usernameParam\n * @param passwordParam\n * @param ifRemember\n * @return\n */\n public ReturnT<String> login(HttpServletResponse response, String usernameParam, String passwordParam, boolean ifRemember){\n\n XxlApiUser xxlApiUser = xxlApiUserDao.findByUserName(usernameParam);\n if (xxlApiUser == null) {\n return new ReturnT<String>(500, \"账号或密码错误\");\n }\n\n String passwordParamMd5 = DigestUtils.md5DigestAsHex(passwordParam.getBytes());\n if (!xxlApiUser.getPassword().equals(passwordParamMd5)) {\n return new ReturnT<String>(500, \"账号或密码错误\");\n }\n\n String loginToken = makeToken(xxlApiUser);\n\n // do login\n CookieUtil.set(response, LOGIN_IDENTITY, loginToken, ifRemember);\n return ReturnT.SUCCESS;\n }\n\n /**\n * logout\n *\n * @param request\n * @param response\n */\n public void logout(HttpServletRequest request, HttpServletResponse response){\n CookieUtil.remove(request, response, LOGIN_IDENTITY);\n }\n\n /**\n * logout\n *\n * @param request\n * @return\n */\n public XxlApiUser ifLogin(HttpServletRequest request){\n String cookieToken = CookieUtil.getValue(request, LOGIN_IDENTITY);\n if (cookieToken != null) {\n XxlApiUser cookieUser = parseToken(cookieToken);\n if (cookieUser != null) {\n XxlApiUser dbUser = xxlApiUserDao.findByUserName(cookieUser.getUserName());\n if (dbUser != null) {\n if (cookieUser.getPassword().equals(dbUser.getPassword())) {\n return dbUser;\n }\n }\n }\n }\n return null;\n }\n\n}"
] | import com.xxl.api.admin.core.consistant.RequestConfig;
import com.xxl.api.admin.core.model.*;
import com.xxl.api.admin.core.util.tool.ArrayTool;
import com.xxl.api.admin.core.util.JacksonUtil;
import com.xxl.api.admin.core.util.tool.StringTool;
import com.xxl.api.admin.dao.*;
import com.xxl.api.admin.service.IXxlApiDataTypeService;
import com.xxl.api.admin.service.impl.LoginService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List; | package com.xxl.api.admin.controller;
/**
* @author xuxueli 2017-03-31 18:10:37
*/
@Controller
@RequestMapping("/document")
public class XxlApiDocumentController {
@Resource
private IXxlApiDocumentDao xxlApiDocumentDao;
@Resource
private IXxlApiProjectDao xxlApiProjectDao;
@Resource
private IXxlApiGroupDao xxlApiGroupDao;
@Resource
private IXxlApiMockDao xxlApiMockDao;
@Resource
private IXxlApiTestHistoryDao xxlApiTestHistoryDao;
@Resource
private IXxlApiDataTypeService xxlApiDataTypeService;
private boolean hasBizPermission(HttpServletRequest request, int bizId){
XxlApiUser loginUser = (XxlApiUser) request.getAttribute(LoginService.LOGIN_IDENTITY);
if ( loginUser.getType()==1 ||
ArrayTool.contains(StringTool.split(loginUser.getPermissionBiz(), ","), String.valueOf(bizId))
) {
return true;
} else {
return false;
}
}
@RequestMapping("/markStar")
@ResponseBody
public ReturnT<String> markStar(HttpServletRequest request, int id, int starLevel) {
XxlApiDocument document = xxlApiDocumentDao.load(id);
if (document == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "操作失败,接口ID非法");
}
// 权限
XxlApiProject apiProject = xxlApiProjectDao.load(document.getProjectId());
if (!hasBizPermission(request, apiProject.getBizId())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "您没有相关业务线的权限,请联系管理员开通");
}
document.setStarLevel(starLevel);
int ret = xxlApiDocumentDao.update(document);
return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL;
}
@RequestMapping("/delete")
@ResponseBody
public ReturnT<String> delete(HttpServletRequest request, int id) {
XxlApiDocument document = xxlApiDocumentDao.load(id);
if (document == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "操作失败,接口ID非法");
}
// 权限
XxlApiProject apiProject = xxlApiProjectDao.load(document.getProjectId());
if (!hasBizPermission(request, apiProject.getBizId())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "您没有相关业务线的权限,请联系管理员开通");
}
// 存在Test记录,拒绝删除
List<XxlApiTestHistory> historyList = xxlApiTestHistoryDao.loadByDocumentId(id);
if (historyList!=null && historyList.size()>0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "拒绝删除,该接口下存在Test记录,不允许删除");
}
// 存在Mock记录,拒绝删除
List<XxlApiMock> mockList = xxlApiMockDao.loadAll(id);
if (mockList!=null && mockList.size()>0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "拒绝删除,该接口下存在Mock记录,不允许删除");
}
int ret = xxlApiDocumentDao.delete(id);
return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL;
}
/**
* 新增,API
*
* @param projectId
* @return
*/
@RequestMapping("/addPage")
public String addPage(HttpServletRequest request, Model model, int projectId, @RequestParam(required = false, defaultValue = "0") int groupId) {
// project
XxlApiProject project = xxlApiProjectDao.load(projectId);
if (project == null) {
throw new RuntimeException("操作失败,项目ID非法");
}
model.addAttribute("projectId", projectId);
model.addAttribute("groupId", groupId);
// 权限
if (!hasBizPermission(request, project.getBizId())) {
throw new RuntimeException("您没有相关业务线的权限,请联系管理员开通");
}
// groupList
List<XxlApiGroup> groupList = xxlApiGroupDao.loadAll(projectId);
model.addAttribute("groupList", groupList);
// enum
model.addAttribute("RequestMethodEnum", RequestConfig.RequestMethodEnum.values());
model.addAttribute("requestHeadersEnum", RequestConfig.requestHeadersEnum);
model.addAttribute("QueryParamTypeEnum", RequestConfig.QueryParamTypeEnum.values());
model.addAttribute("ResponseContentType", RequestConfig.ResponseContentType.values());
return "document/document.add";
}
@RequestMapping("/add")
@ResponseBody
public ReturnT<Integer> add(HttpServletRequest request, XxlApiDocument xxlApiDocument) {
XxlApiProject project = xxlApiProjectDao.load(xxlApiDocument.getProjectId());
if (project == null) {
return new ReturnT<Integer>(ReturnT.FAIL_CODE, "操作失败,项目ID非法");
}
// 权限
if (!hasBizPermission(request, project.getBizId())) {
return new ReturnT<Integer>(ReturnT.FAIL_CODE, "您没有相关业务线的权限,请联系管理员开通");
}
int ret = xxlApiDocumentDao.add(xxlApiDocument);
return (ret>0)?new ReturnT<Integer>(xxlApiDocument.getId()):new ReturnT<Integer>(ReturnT.FAIL_CODE, null);
}
/**
* 更新,API
* @return
*/
@RequestMapping("/updatePage")
public String updatePage(HttpServletRequest request, Model model, int id) {
// document
XxlApiDocument xxlApiDocument = xxlApiDocumentDao.load(id);
if (xxlApiDocument == null) {
throw new RuntimeException("操作失败,接口ID非法");
}
model.addAttribute("document", xxlApiDocument); | model.addAttribute("requestHeadersList", (StringTool.isNotBlank(xxlApiDocument.getRequestHeaders()))?JacksonUtil.readValue(xxlApiDocument.getRequestHeaders(), List.class):null ); | 2 |
AfterLifeLochie/fontbox | src/main/java/net/afterlifelochie/fontbox/document/Paragraph.java | [
"public interface ITracer {\r\n\r\n\t/**\r\n\t * <p>\r\n\t * Called by Fontbox to trace a particular event to the tracer.\r\n\t * </p>\r\n\t * <p>\r\n\t * Events triggered usually take the following parameter forms:\r\n\t * <ol>\r\n\t * <li>The method name being invoked (the source)</li>\r\n\t * <li>The return argument (can be null) <i>or</i> the name of the phase\r\n\t * being recorded</li>\r\n\t * <li>Any other debugging parameters if the call is for a phase</li>\r\n\t * </ol>\r\n\t * See the location of invocation for more information about the details of\r\n\t * the parameters passed.\r\n\t * </p>\r\n\t *\r\n\t * @param params\r\n\t * The parameters from the invoked method\r\n\t */\r\n\tpublic void trace(Object... params);\r\n\r\n\t/**\r\n\t * <p>\r\n\t * Called by Fontbox to trace a particular warning notification to the\r\n\t * tracer.\r\n\t * </p>\r\n\t * <p>\r\n\t * Events triggered usually take the following parameter forms:\r\n\t * <ol>\r\n\t * <li>The method name being invoked (the source)</li>\r\n\t * <li>The reason for the warning message</li>\r\n\t * <li>Any other debugging parameters where appropriate</li>\r\n\t * </ol>\r\n\t * See the location of invocation for more information about the details of\r\n\t * the parameters passed.\r\n\t * </p>\r\n\t *\r\n\t * @param params\r\n\t * The parameters from the invoked method\r\n\t */\r\n\tpublic void warn(Object... params);\r\n\r\n\t/**\r\n\t * <p>\r\n\t * Called by Fontbox to ask if Fontbox assertions are enabled.\r\n\t * </p>\r\n\t *\r\n\t * @return If Fontbox internal assertions are enabled\r\n\t */\r\n\tpublic boolean enableAssertion();\r\n\r\n}\r",
"public class FormattedString {\r\n\r\n\tpublic final String string;\r\n\tpublic final TextFormat[] format;\r\n\r\n\tpublic FormattedString(String string) {\r\n\t\tthis.string = string;\r\n\t\tformat = new TextFormat[string.length()];\r\n\t}\r\n\r\n\tpublic FormattedString applyFormat(TextFormat format, int index) {\r\n\t\tthis.format[index] = format;\r\n\t\treturn this;\r\n\t}\r\n\r\n}\r",
"public enum AlignmentMode {\r\n\tLEFT, CENTER, RIGHT, JUSTIFY;\r\n}\r",
"public class LayoutException extends Exception {\r\n\r\n\t/**\r\n\t * Serializer version ID\r\n\t */\r\n\tprivate static final long serialVersionUID = 1437904113154741479L;\r\n\r\n\t/**\r\n\t * Initializes the layout exception\r\n\t *\r\n\t * @param reason\r\n\t * The reason for the exception\r\n\t */\r\n\tpublic LayoutException(String reason) {\r\n\t\tsuper(reason);\r\n\t}\r\n\r\n\t/**\r\n\t * Initializes the layout exception\r\n\t *\r\n\t * @param reason\r\n\t * The reason for the exception\r\n\t * @param cause\r\n\t * The parent cause exception\r\n\t */\r\n\tpublic LayoutException(String reason, Throwable cause) {\r\n\t\tsuper(reason, cause);\r\n\t}\r\n\r\n}\r",
"public class PageWriter {\r\n\r\n\tprivate ArrayList<Page> pages = new ArrayList<Page>();\r\n\tprivate ArrayList<PageCursor> cursors = new ArrayList<PageCursor>();\r\n\tprivate PageProperties attributes;\r\n\tprivate PageIndex index;\r\n\tprivate Object lock = new Object();\r\n\tprivate boolean closed = false;\r\n\tprivate int ptr = 0;\r\n\r\n\tpublic PageWriter(PageProperties attributes) {\r\n\t\tthis.attributes = attributes;\r\n\t\tindex = new PageIndex();\r\n\t}\r\n\r\n\tpublic void close() {\r\n\t\tsynchronized (lock) {\r\n\t\t\tclosed = true;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void checkOpen() throws IOException {\r\n\t\tsynchronized (lock) {\r\n\t\t\tif (closed)\r\n\t\t\t\tthrow new IOException(\"Writer closed!\");\r\n\t\t}\r\n\t}\r\n\r\n\tpublic Page previous() throws IOException {\r\n\t\tsynchronized (lock) {\r\n\t\t\tcheckOpen();\r\n\t\t\tseek(-1);\r\n\t\t\treturn pages.get(ptr);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic Page next() throws IOException {\r\n\t\tsynchronized (lock) {\r\n\t\t\tcheckOpen();\r\n\t\t\tseek(1);\r\n\t\t\treturn pages.get(ptr);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic Page current() throws IOException {\r\n\t\tsynchronized (lock) {\r\n\t\t\tcheckOpen();\r\n\t\t\tseek(0);\r\n\t\t\treturn pages.get(ptr);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic boolean write(Element element) throws IOException {\r\n\t\tsynchronized (lock) {\r\n\t\t\tcheckOpen();\r\n\t\t\tPage what = current();\r\n\t\t\tif (element.bounds() == null)\r\n\t\t\t\tthrow new IOException(\"Cannot write unbounded object to page.\");\r\n\t\t\tFontbox.doAssert(what.insidePage(element.bounds()), \"Element outside page boundary.\");\r\n\t\t\tElement intersect = what.intersectsElement(element.bounds());\r\n\t\t\tFontbox.doAssert(intersect == null, \"Element intersects existing element \" + intersect + \": box \"\r\n\t\t\t\t\t+ ((intersect != null && intersect.bounds() != null) ? intersect.bounds() : \"<null>\") + \" and \"\r\n\t\t\t\t\t+ element.bounds() + \"!\");\r\n\r\n\t\t\tif (element.identifier() != null)\r\n\t\t\t\tindex.push(element.identifier(), ptr);\r\n\r\n\t\t\twhat.push(element);\r\n\r\n\t\t\tPageCursor current = cursor();\r\n\t\t\tfor (Element e : what.allElements()) {\r\n\t\t\t\tif (e.bounds().floating())\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\tObjectBounds bb = e.bounds();\r\n\t\t\t\tif (bb.y + bb.height + 1 > current.y())\r\n\t\t\t\t\tcurrent.top(bb.y + bb.height + 1);\r\n\t\t\t}\r\n\r\n\t\t\tIntegerExclusionStream window = new IntegerExclusionStream(0, what.width);\r\n\t\t\tfor (Element e : what.allElements()) {\r\n\t\t\t\tObjectBounds bb = e.bounds();\r\n\t\t\t\tif (current.y() >= bb.y && bb.y + bb.height >= current.y())\r\n\t\t\t\t\twindow.excludeRange(0, bb.x + bb.width);\r\n\t\t\t}\r\n\t\t\tcurrent.left(window.largest());\r\n\r\n\t\t\tFontbox.tracer().trace(\"PageWriter.write\", \"pushCursor\", current);\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic PageCursor cursor() throws IOException {\r\n\t\tsynchronized (lock) {\r\n\t\t\tcheckOpen();\r\n\t\t\treturn cursors.get(ptr);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void seek(int which) throws IOException {\r\n\t\tsynchronized (lock) {\r\n\t\t\tptr += which;\r\n\t\t\tif (0 > ptr)\r\n\t\t\t\tptr = 0;\r\n\t\t\tif (ptr > pages.size())\r\n\t\t\t\tptr = pages.size();\r\n\t\t\tif (ptr == pages.size()) {\r\n\t\t\t\tpages.add(new Page(attributes.copy()));\r\n\t\t\t\tcursors.add(new PageCursor());\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic ArrayList<Page> pages() {\r\n\t\tsynchronized (lock) {\r\n\t\t\tif (!closed)\r\n\t\t\t\treturn (ArrayList<Page>) pages.clone();\r\n\t\t\treturn pages;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic PageIndex index() throws IOException {\r\n\t\tsynchronized (lock) {\r\n\t\t\tif (!closed)\r\n\t\t\t\tthrow new IOException(\"Writing not finished!\");\r\n\t\t\treturn index;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic ArrayList<PageCursor> cursors() {\r\n\t\tsynchronized (lock) {\r\n\t\t\tif (!closed)\r\n\t\t\t\treturn (ArrayList<PageCursor>) cursors.clone();\r\n\t\t\treturn cursors;\r\n\t\t}\r\n\t}\r\n}\r",
"public class Page extends Container {\n\n\t/** The page layout properties container */\n\tpublic PageProperties properties;\n\n\t/** The list of static elements on the page */\n\tprivate ArrayList<Element> staticElements = new ArrayList<Element>();\n\t/** The list of dynamic elements on the page */\n\tprivate ArrayList<Element> dynamicElements = new ArrayList<Element>();\n\n\t/**\n\t * Initialize a new Page with a specified set of page layout properties.\n\t *\n\t * @param properties\n\t * The page layout properties.\n\t */\n\tpublic Page(PageProperties properties) {\n\t\tsuper(properties.width, properties.height);\n\t\tthis.properties = properties;\n\t}\n\n\tpublic ArrayList<Element> allElements() {\n\t\tArrayList<Element> all = new ArrayList<Element>();\n\t\tall.addAll(staticElements);\n\t\tall.addAll(dynamicElements);\n\t\treturn all;\n\t}\n\n\t/**\n\t * Get a list of all static elements on the page\n\t *\n\t * @return The list of static elements on the page\n\t */\n\tpublic ArrayList<Element> staticElements() {\n\t\treturn staticElements;\n\t}\n\n\t/**\n\t * Get a list of all dynamic elements on the page\n\t *\n\t * @return The list of dynamic elements on the page\n\t */\n\tpublic ArrayList<Element> dynamicElements() {\n\t\treturn dynamicElements;\n\t}\n\n\t/**\n\t * Push an element onto the page, unchecked.\n\t *\n\t * @param element\n\t * The element to push\n\t */\n\tpublic void push(Element element) {\n\t\tif (!element.canCompileRender())\n\t\t\tdynamicElements.add(element);\n\t\telse\n\t\t\tstaticElements.add(element);\n\t}\n\n\t/**\n\t * Determine if the provided bounding box intersects with an existing\n\t * element on the page. Returns true if an intersection occurs, false if\n\t * not.\n\t *\n\t * @param bounds\n\t * The bounding box to check\n\t * @return If an intersection occurs\n\t */\n\tpublic Element intersectsElement(ObjectBounds bounds) {\n\t\tfor (Element element : staticElements)\n\t\t\tif (element.bounds() != null && element.bounds().intersects(bounds))\n\t\t\t\treturn element;\n\t\treturn null;\n\t}\n\n\t/**\n\t * Determine if the provided bounding box fits entirely on the page. Returns\n\t * true if the bounding box fits inside the page, false if not.\n\t *\n\t * @param bounds\n\t * The bounding box to check\n\t * @return If the bounding box fits inside the page\n\t */\n\tpublic boolean insidePage(ObjectBounds bounds) {\n\t\tif (bounds.x < 0 || bounds.y < 0 || bounds.x > width || bounds.y > height)\n\t\t\treturn false;\n\t\tif (bounds.x + bounds.width > width || bounds.y + bounds.height > height)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n}",
"public abstract class BookGUI extends GuiScreen {\r\n\r\n\t/**\r\n\t * The page-up mode.\r\n\t *\r\n\t * @author AfterLifeLochie\r\n\t */\r\n\tpublic static enum UpMode {\r\n\t\t/** One-up (one page) mode */\r\n\t\tONEUP(1),\r\n\t\t/** Two-up (two page) mode */\r\n\t\tTWOUP(2);\r\n\r\n\t\t/** The number of pages in this mode */\r\n\t\tpublic final int pages;\r\n\r\n\t\tUpMode(int pages) {\r\n\t\t\tthis.pages = pages;\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Page layout container\r\n\t *\r\n\t * @author AfterLifeLochie\r\n\t *\r\n\t */\r\n\tpublic static class Layout {\r\n\t\tpublic int x, y;\r\n\r\n\t\t/**\r\n\t\t * Create a new Layout container for rendering the page on screen.\r\n\t\t *\r\n\t\t * @param x\r\n\t\t * The x-coordinate to render at\r\n\t\t * @param y\r\n\t\t * The y-coordinate to render at\r\n\t\t */\r\n\t\tpublic Layout(int x, int y) {\r\n\t\t\tthis.x = x;\r\n\t\t\tthis.y = y;\r\n\t\t}\r\n\t}\r\n\r\n\t/** The renderer's UpMode */\r\n\tprotected final UpMode mode;\r\n\t/** The page layout grid */\r\n\tprotected final Layout[] layout;\r\n\r\n\t/** The list of pages */\r\n\tprotected ArrayList<Page> pages;\r\n\t/** The list of cursors */\r\n\tprotected ArrayList<PageCursor> cursors;\r\n\t/** The data index */\r\n\tprotected PageIndex index;\r\n\t/** The current page pointer */\r\n\tprotected int ptr = 0;\r\n\r\n\t/** The current opengl display list state */\r\n\tprotected boolean useDisplayList = false;\r\n\t/** The current opengl buffer list */\r\n\tprotected int[] glDisplayLists;\r\n\t/** The current buffer dirty state */\r\n\tprotected boolean glBufferDirty[];\r\n\r\n\t/**\r\n\t * <p>\r\n\t * Create a new Book rendering context on top of the existing Minecraft GUI\r\n\t * system. The book rendering properties are set through the constructor and\r\n\t * control how many and where pages are rendered.\r\n\t * </p>\r\n\t *\r\n\t * @param mode\r\n\t * The page mode, usually ONEUP or TWOUP.\r\n\t * @param layout\r\n\t * The layout array which specifies where the pages should be\r\n\t * rendered. The number of elements in the array must match the\r\n\t * number of pages required by the UpMode specified.\r\n\t */\r\n\tpublic BookGUI(UpMode mode, Layout[] layout) {\r\n\t\tif (layout == null)\r\n\t\t\tthrow new IllegalArgumentException(\"Layout cannot be null!\");\r\n\t\tif (mode == null)\r\n\t\t\tthrow new IllegalArgumentException(\"Mode cannot be null!\");\r\n\t\tif (layout.length != mode.pages)\r\n\t\t\tthrow new IllegalArgumentException(\"Expected \" + mode.pages + \" pages for mode \" + mode);\r\n\t\tthis.mode = mode;\r\n\t\tthis.layout = layout;\r\n\t\tprepareGraphics();\r\n\t}\r\n\r\n\t/**\r\n\t * <p>\r\n\t * Updates the pages currently being rendered.\r\n\t * </p>\r\n\t * <p>\r\n\t * If the page read pointer is currently beyond the end of the new page\r\n\t * count (ie, the number of pages has reduced), the pointer will be reset to\r\n\t * the beginning of the book.\r\n\t * </p>\r\n\t *\r\n\t * @param pages\r\n\t * The new list of pages\r\n\t * @param index\r\n\t * The new page index\r\n\t */\r\n\tpublic void changePages(ArrayList<Page> pages, PageIndex index) {\r\n\t\tif (ptr >= pages.size()) {\r\n\t\t\tptr = 0;\r\n\t\t\tinternalOnPageChanged(this, ptr);\r\n\t\t}\r\n\t\tthis.pages = pages;\r\n\t\tthis.index = index;\r\n\t}\r\n\r\n\t/**\r\n\t * <p>\r\n\t * Updates the cursors currently being rendered. Used for debugging only.\r\n\t * </p>\r\n\t * <p>\r\n\t * If the cursor parameter is not null, the matching cursor for each page\r\n\t * will be displayed. If the cursor parameter is null, no cursors will be\r\n\t * rendered on the page.\r\n\t * </p>\r\n\t *\r\n\t * @param cursors\r\n\t * The list of cursors, or null if no cursors should be rendered\r\n\t */\r\n\tpublic void changeCursors(ArrayList<PageCursor> cursors) {\r\n\t\tthis.cursors = cursors;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean doesGuiPauseGame() {\r\n\t\treturn false;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void initGui() {\r\n\t\tsuper.initGui();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void onGuiClosed() {\r\n\t\tif (useDisplayList) {\r\n\t\t\tuseDisplayList = false;\r\n\t\t\tGL11.glDeleteLists(glDisplayLists[0], glDisplayLists.length);\r\n\t\t\tfor (int i = 0; i < glDisplayLists.length; i++)\r\n\t\t\t\tglDisplayLists[i] = -1;\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void updateScreen() {\r\n\t\tsuper.updateScreen();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void drawScreen(int mx, int my, float frames) {\r\n\t\tsuper.drawScreen(mx, my, frames);\r\n\t\tdrawBackground(mx, my, frames);\r\n\t\ttry {\r\n\t\t\tif (pages != null)\r\n\t\t\t\tfor (int i = 0; i < mode.pages; i++) {\r\n\t\t\t\t\tLayout where = layout[i];\r\n\t\t\t\t\tint what = ptr + i;\r\n\t\t\t\t\tif (pages.size() <= what)\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tPage page = pages.get(ptr + i);\r\n\t\t\t\t\tGL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);\r\n\r\n\t\t\t\t\tif (cursors != null && what < cursors.size()) {\r\n\t\t\t\t\t\tPageCursor cursor = cursors.get(what);\r\n\t\t\t\t\t\tGL11.glDisable(GL11.GL_TEXTURE_2D);\r\n\t\t\t\t\t\tGL11.glEnable(GL11.GL_BLEND);\r\n\t\t\t\t\t\tGL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);\r\n\t\t\t\t\t\tGL11.glColor4f(1.0f, 0.0f, 0.0f, 0.5f);\r\n\t\t\t\t\t\tGLUtils.drawDefaultRect(where.x, where.y, page.width * 0.44f, page.height * 0.44f, zLevel);\r\n\t\t\t\t\t\tGL11.glColor4f(0.0f, 1.0f, 0.0f, 1.0f);\r\n\t\t\t\t\t\tGLUtils.drawDefaultRect(where.x + (cursor.x() * 0.44f), where.y + (cursor.y() * 0.44f), 1.0,\r\n\t\t\t\t\t\t\t\t1.0, zLevel);\r\n\t\t\t\t\t\tGL11.glDisable(GL11.GL_BLEND);\r\n\t\t\t\t\t\tGL11.glEnable(GL11.GL_TEXTURE_2D);\r\n\t\t\t\t\t}\r\n\t\t\t\t\trenderPage(i, page, where.x, where.y, zLevel, mx, my, frames);\r\n\r\n\t\t\t\t}\r\n\t\t} catch (RenderException err) {\r\n\t\t\terr.printStackTrace();\r\n\t\t}\r\n\t\tdrawForeground(mx, my, frames);\r\n\t}\r\n\r\n\t/**\r\n\t * Called when the current page is changed\r\n\t *\r\n\t * @param gui\r\n\t * The current GUI\r\n\t * @param whatPtr\r\n\t * The new page pointer value\r\n\t */\r\n\tpublic abstract void onPageChanged(BookGUI gui, int whatPtr);\r\n\r\n\t/**\r\n\t * <p>\r\n\t * Draw the background layer of the interface. You must leave the opengl\r\n\t * state such that the layout (0, 0) will be drawn in the current place.\r\n\t * </p>\r\n\t *\r\n\t * @param mx\r\n\t * The mouse x-coordinate\r\n\t * @param my\r\n\t * The mouse y-coordinate\r\n\t * @param frame\r\n\t * The partial frames rendered\r\n\t */\r\n\tpublic abstract void drawBackground(int mx, int my, float frame);\r\n\r\n\t/**\r\n\t * <p>\r\n\t * Draw the foreground layer of the interface. The opengl state is such that\r\n\t * the layout coordinates (0, 0) are in the top-left corner of the written\r\n\t * text.\r\n\t * </p>\r\n\t *\r\n\t * @param mx\r\n\t * The mouse x-coordinate\r\n\t * @param my\r\n\t * The mouse y-coordinate\r\n\t * @param frame\r\n\t * The partial frames rendered\r\n\t */\r\n\tpublic abstract void drawForeground(int mx, int my, float frame);\r\n\r\n\t/**\r\n\t * Called internally when the page is changed. Don't override this, use\r\n\t * {@link #onPageChanged(BookGUI, int)} instead.\r\n\t *\r\n\t * @param gui\r\n\t * The book GUI\r\n\t * @param whatPtr\r\n\t * The new page pointer\r\n\t */\r\n\tprotected void internalOnPageChanged(BookGUI gui, int whatPtr) {\r\n\t\tfor (int i = 0; i < mode.pages; i++)\r\n\t\t\tglBufferDirty[i] = true;\r\n\t\tonPageChanged(gui, whatPtr);\r\n\t}\r\n\r\n\t/**\r\n\t * Called internally to set up the display lists.\r\n\t */\r\n\tprotected void prepareGraphics() {\r\n\t\ttry {\r\n\t\t\tUtil.checkGLError();\r\n\t\t} catch (OpenGLException glex) {\r\n\t\t\tFontbox.tracer().warn(\"BookGUI.prepareGraphics\", \"Bad OpenGL operation detected, check GL history!\");\r\n\t\t\tglex.printStackTrace();\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tglDisplayLists = new int[mode.pages];\r\n\t\tglBufferDirty = new boolean[mode.pages];\r\n\t\tint glList = GL11.glGenLists(glDisplayLists.length);\r\n\r\n\t\ttry {\r\n\t\t\tUtil.checkGLError();\r\n\t\t} catch (OpenGLException glex) {\r\n\t\t\tFontbox.tracer().warn(\"BookGUI.prepareGraphics\",\r\n\t\t\t\t\t\"Unable to allocate display-list buffers, using immediate mode.\");\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (glList <= 0)\r\n\t\t\tFontbox.tracer().warn(\"BookGUI.prepareGraphics\", \"No display-lists available, using immediate mode.\");\r\n\t\telse {\r\n\t\t\tfor (int i = 0; i < glDisplayLists.length; i++) {\r\n\t\t\t\tglDisplayLists[i] = glList + i;\r\n\t\t\t\tglBufferDirty[i] = true;\r\n\t\t\t}\r\n\t\t\tFontbox.tracer()\r\n\t\t\t.trace(\"BookGUI.prepareGraphics\", \"Displaylist initialized.\", glList, glDisplayLists.length);\r\n\t\t\tuseDisplayList = true;\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Advance to the next page\r\n\t */\r\n\tprotected void next() {\r\n\t\tif (ptr + mode.pages < pages.size()) {\r\n\t\t\tptr += mode.pages;\r\n\t\t\tinternalOnPageChanged(this, ptr);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Go to a page in the index; if the item doesn't exist, no navigation\r\n\t * occurs\r\n\t *\r\n\t * @param id\r\n\t * The ID of the anchor to go to\r\n\t */\r\n\tprotected void go(String id) {\r\n\t\tint where = index.find(id);\r\n\t\tif (where != -1)\r\n\t\t\tgo(where);\r\n\t}\r\n\r\n\t/**\r\n\t * Go to a page\r\n\t *\r\n\t * @param where\r\n\t * The page pointer\r\n\t */\r\n\tprotected void go(int where) {\r\n\t\twhere = where - (where % mode.pages);\r\n\t\tif (ptr != where && 0 <= where - mode.pages && where + mode.pages < pages.size()) {\r\n\t\t\tptr = where;\r\n\t\t\tinternalOnPageChanged(this, ptr);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Reverse to the previous page\r\n\t */\r\n\tprotected void previous() {\r\n\t\tif (0 <= ptr - mode.pages) {\r\n\t\t\tptr -= mode.pages;\r\n\t\t\tinternalOnPageChanged(this, ptr);\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tprotected void keyTyped(char val, int code) {\r\n\t\tsuper.keyTyped(val, code);\r\n\t\tif (code == Keyboard.KEY_LEFT)\r\n\t\t\tprevious();\r\n\t\tif (code == Keyboard.KEY_RIGHT)\r\n\t\t\tnext();\r\n\t}\r\n\r\n\t@Override\r\n\tprotected void mouseClicked(int mx, int my, int button) {\r\n\t\tsuper.mouseClicked(mx, my, button);\r\n\t\tfor (int i = 0; i < mode.pages; i++) {\r\n\t\t\tLayout where = layout[i];\r\n\t\t\tint which = ptr + i;\r\n\t\t\tif (pages.size() <= which)\r\n\t\t\t\tbreak;\r\n\t\t\tPage page = pages.get(ptr + i);\r\n\t\t\tint mouseX = mx - where.x, mouseY = my - where.y;\r\n\t\t\tif (mouseX >= 0 && mouseY >= 0 && mouseX <= page.width && mouseY <= page.height) {\r\n\t\t\t\tElement elem = DocumentProcessor.getElementAt(page, mouseX, mouseY);\r\n\t\t\t\tif (elem != null)\r\n\t\t\t\t\telem.clicked(this, mouseX, mouseY);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tprotected void mouseMovedOrUp(int mx, int my, int button) {\r\n\t\tsuper.mouseMovedOrUp(mx, my, button);\r\n\t}\r\n\r\n\t@Override\r\n\tprotected void mouseClickMove(int mx, int my, int button, long ticks) {\r\n\t\tsuper.mouseClickMove(mx, my, button, ticks);\r\n\t}\r\n\r\n\tprivate void renderPage(int index, Page page, float x, float y, float z, int mx, int my, float frame)\r\n\t\t\tthrows RenderException {\r\n\t\tif (!useDisplayList) {\r\n\t\t\trenderPageStaticsImmediate(index, page, x, y, z, mx, my, frame);\r\n\t\t\trenderPageDynamics(index, page, x, y, z, mx, my, frame);\r\n\t\t} else {\r\n\t\t\trenderPageStaticsBuffered(index, page, x, y, z, mx, my, frame);\r\n\t\t\trenderPageDynamics(index, page, x, y, z, mx, my, frame);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void renderPageDynamics(int index, Page page, float x, float y, float z, int mx, int my, float frame)\r\n\t\t\tthrows RenderException {\r\n\t\tGL11.glPushMatrix();\r\n\t\tGL11.glTranslatef(x, y, z);\r\n\t\trendeElementGroupImmediate(page.dynamicElements(), mx, my, frame);\r\n\t\tGL11.glPopMatrix();\r\n\t}\r\n\r\n\tprivate void renderPageStaticsBuffered(int index, Page page, float x, float y, float z, int mx, int my, float frame)\r\n\t\t\tthrows RenderException {\r\n\t\tif (glBufferDirty[index]) {\r\n\t\t\tGL11.glNewList(glDisplayLists[index], GL11.GL_COMPILE);\r\n\t\t\trenderPageStaticsImmediate(index, page, x, y, z, mx, my, frame);\r\n\t\t\tGL11.glEndList();\r\n\t\t\tglBufferDirty[index] = false;\r\n\t\t}\r\n\t\tGL11.glCallList(glDisplayLists[index]);\r\n\t}\r\n\r\n\tprivate void renderPageStaticsImmediate(int index, Page page, float x, float y, float z, int mx, int my, float frame)\r\n\t\t\tthrows RenderException {\r\n\t\tGL11.glPushMatrix();\r\n\t\tGL11.glTranslatef(x, y, z);\r\n\t\trendeElementGroupImmediate(page.staticElements(), mx, my, frame);\r\n\t\tGL11.glPopMatrix();\r\n\t}\r\n\r\n\tprivate void rendeElementGroupImmediate(ArrayList<Element> elements, int mx, int my, float frame)\r\n\t\t\tthrows RenderException {\r\n\t\tint count = elements.size();\r\n\t\tfor (int i = 0; i < count; i++) {\r\n\t\t\telements.get(i).render(this, mx, my, frame);\r\n\t\t\tif (cursors != null) {\r\n\t\t\t\tObjectBounds bounds = elements.get(i).bounds();\r\n\t\t\t\tif (bounds != null) {\r\n\t\t\t\t\tGL11.glDisable(GL11.GL_TEXTURE_2D);\r\n\t\t\t\t\tGL11.glEnable(GL11.GL_BLEND);\r\n\t\t\t\t\tGL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);\r\n\t\t\t\t\tGL11.glColor4f(0.0f, 0.0f, 1.0f, 0.5f);\r\n\t\t\t\t\tGL11.glPushMatrix();\r\n\t\t\t\t\tGL11.glTranslatef(bounds.x * 0.44f, bounds.y * 0.44f, 0);\r\n\t\t\t\t\tGLUtils.drawDefaultRect(0, 0, bounds.width * 0.44f, bounds.height * 0.44f, zLevel);\r\n\t\t\t\t\tGL11.glPopMatrix();\r\n\t\t\t\t\tGL11.glDisable(GL11.GL_BLEND);\r\n\t\t\t\t\tGL11.glEnable(GL11.GL_TEXTURE_2D);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n}\r"
] | import java.io.IOException;
import net.afterlifelochie.fontbox.api.ITracer;
import net.afterlifelochie.fontbox.data.FormattedString;
import net.afterlifelochie.fontbox.document.property.AlignmentMode;
import net.afterlifelochie.fontbox.layout.LayoutException;
import net.afterlifelochie.fontbox.layout.PageWriter;
import net.afterlifelochie.fontbox.layout.components.Page;
import net.afterlifelochie.fontbox.render.BookGUI;
| package net.afterlifelochie.fontbox.document;
public class Paragraph extends Element {
public FormattedString text;
public AlignmentMode align;
/**
* Create a new paragraph with a specified text and the default alignment
* (justified).
*
* @param text
* The text
*/
public Paragraph(FormattedString text) {
this(text, AlignmentMode.JUSTIFY);
}
/**
* Create a new paragraph with the specified properties.
*
* @param text
* The text
* @param align
* The alignment mode
*/
public Paragraph(FormattedString text, AlignmentMode align) {
this.text = text;
this.align = align;
}
@Override
| public void layout(ITracer trace, PageWriter writer) throws IOException, LayoutException {
| 4 |
erlymon/erlymon-monitor-android | erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/StorageService.java | [
"public class DbOpenHelper extends SQLiteOpenHelper {\n\n public DbOpenHelper(@NonNull Context context) {\n super(context, \"erlymondb\", null, 1);\n }\n\n @Override\n public void onCreate(@NonNull SQLiteDatabase db) {\n db.execSQL(ServersTable.getCreateTableQuery());\n db.execSQL(UsersTable.getCreateTableQuery());\n db.execSQL(DevicesTable.getCreateTableQuery());\n db.execSQL(PositionsTable.getCreateTableQuery());\n }\n\n @Override\n public void onUpgrade(@NonNull SQLiteDatabase db, int oldVersion, int newVersion) {\n // no impl\n }\n}",
"@StorIOSQLiteType(table = DevicesTable.TABLE)\npublic class Device implements Parcelable {\n @StorIOSQLiteColumn(name = DevicesTable.COLUMN_ID, key = true)\n long id;\n\n @StorIOSQLiteColumn(name = DevicesTable.COLUMN_NAME)\n @Since(3.0)\n @SerializedName(\"name\")\n @Expose\n String name;\n\n @StorIOSQLiteColumn(name = DevicesTable.COLUMN_UNIQUE_ID)\n @Since(3.0)\n @SerializedName(\"uniqueId\")\n @Expose\n String uniqueId;\n\n @StorIOSQLiteColumn(name = DevicesTable.COLUMN_STATUS)\n @Since(3.3)\n @SerializedName(\"status\")\n @Expose\n String status;\n\n //@StorIOSQLiteColumn(name = DevicesTable.COLUMN_LAST_UPDATE)\n @Since(3.3)\n @SerializedName(\"lastUpdate\")\n @Expose\n Date lastUpdate;\n\n\n @StorIOSQLiteColumn(name = DevicesTable.COLUMN_POSITION_ID)\n @Since(3.4)\n @SerializedName(\"positionId\")\n @Expose\n Long positionId;\n\n public Device() {}\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getUniqueId() {\n return uniqueId;\n }\n\n public void setUniqueId(String uniqueId) {\n this.uniqueId = uniqueId;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n public Date getLastUpdate() {\n return lastUpdate;\n }\n\n public void setLastUpdate(Date lastUpdate) {\n this.lastUpdate = lastUpdate;\n }\n\n public Long getPositionId() {\n return positionId;\n }\n\n public void setPositionId(Long positionId) {\n this.positionId = positionId;\n }\n\n protected Device(Parcel in) {\n id = in.readLong();\n name = in.readString();\n uniqueId = in.readString();\n status = in.readString();\n long tmpLastUpdate = in.readLong();\n lastUpdate = tmpLastUpdate != -1 ? new Date(tmpLastUpdate) : null;\n positionId = in.readByte() == 0x00 ? null : in.readLong();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeLong(id);\n dest.writeString(name);\n dest.writeString(uniqueId);\n dest.writeString(status);\n dest.writeLong(lastUpdate != null ? lastUpdate.getTime() : -1L);\n if (positionId == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeLong(positionId);\n }\n }\n\n @SuppressWarnings(\"unused\")\n public static final Creator<Device> CREATOR = new Creator<Device>() {\n @Override\n public Device createFromParcel(Parcel in) {\n return new Device(in);\n }\n\n @Override\n public Device[] newArray(int size) {\n return new Device[size];\n }\n };\n\n @Override\n public String toString() {\n return \"Device{\" +\n \"id=\" + id +\n \", name='\" + name + '\\'' +\n \", uniqueId='\" + uniqueId + '\\'' +\n \", status='\" + status + '\\'' +\n \", lastUpdate=\" + lastUpdate +\n \", positionId=\" + positionId +\n '}';\n }\n}",
"public class DevicesTable {\n\n @NonNull\n public static final String TABLE = \"devices\";\n\n @NonNull\n public static final String COLUMN_ID = \"_id\";\n\n @NonNull\n public static final String COLUMN_NAME = \"name\";\n\n @NonNull\n public static final String COLUMN_UNIQUE_ID = \"unique_id\";\n\n @NonNull\n public static final String COLUMN_STATUS = \"status\";\n\n @NonNull\n public static final String COLUMN_LAST_UPDATE = \"last_update\";\n\n @NonNull\n public static final String COLUMN_POSITION_ID = \"position_id\";\n\n\n // Yep, with StorIO you can safely store queries as objects and reuse them, they are immutable\n @NonNull\n public static final Query QUERY_ALL = Query.builder()\n .table(TABLE)\n .orderBy(\"name\")\n .build();\n\n @NonNull\n public static final RawQuery QUERY_DROP = RawQuery.builder()\n .query(\"DELETE FROM \" + TABLE + \";\")\n .build();\n\n // This is just class with Meta Data, we don't need instances\n private DevicesTable() {\n throw new IllegalStateException(\"No instances please\");\n }\n\n @NonNull\n public static String getCreateTableQuery() {\n return \"CREATE TABLE \" + TABLE + \"(\"\n + COLUMN_ID + \" INTEGER NOT NULL PRIMARY KEY, \"\n + COLUMN_NAME + \" TEXT NOT NULL, \"\n + COLUMN_UNIQUE_ID + \" TEXT NOT NULL, \"\n + COLUMN_STATUS + \" TEXT DEFAULT NULL, \"\n + COLUMN_LAST_UPDATE + \" NUMERIC DEFAULT NULL, \"\n + COLUMN_POSITION_ID + \" INTEGER DEFAULT NULL\"\n + \");\";\n }\n\n public static class DeviceSQLiteTypeMapping extends SQLiteTypeMapping<Device> {\n public DeviceSQLiteTypeMapping() {\n super(new DeviceStorIOSQLitePutResolver(),\n new DeviceStorIOSQLiteGetResolver(),\n new DeviceStorIOSQLiteDeleteResolver());\n }\n }\n\n private static class DeviceStorIOSQLitePutResolver extends DefaultPutResolver<Device> {\n /**\n * {@inheritDoc}\n */\n @Override\n @NonNull\n public InsertQuery mapToInsertQuery(@NonNull Device object) {\n return InsertQuery.builder()\n .table(\"devices\")\n .build();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n @NonNull\n public UpdateQuery mapToUpdateQuery(@NonNull Device object) {\n return UpdateQuery.builder()\n .table(\"devices\")\n .where(\"_id = ?\")\n .whereArgs(object.id)\n .build();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n @NonNull\n public ContentValues mapToContentValues(@NonNull Device object) {\n ContentValues contentValues = new ContentValues(6);\n\n contentValues.put(\"_id\", object.id);\n contentValues.put(\"name\", object.name);\n contentValues.put(\"unique_id\", object.uniqueId);\n contentValues.put(\"status\", object.status);\n contentValues.put(\"last_update\", object.lastUpdate == null ? null : object.lastUpdate.getTime());\n contentValues.put(\"position_id\", object.positionId);\n\n return contentValues;\n }\n }\n\n private static class DeviceStorIOSQLiteGetResolver extends DefaultGetResolver<Device> {\n /**\n * {@inheritDoc}\n */\n @Override\n @NonNull\n public Device mapFromCursor(@NonNull Cursor cursor) {\n Device object = new Device();\n\n if(!cursor.isNull(cursor.getColumnIndex(\"_id\"))) {\n object.id = cursor.getLong(cursor.getColumnIndex(\"_id\"));\n }\n object.name = cursor.getString(cursor.getColumnIndex(\"name\"));\n object.uniqueId = cursor.getString(cursor.getColumnIndex(\"unique_id\"));\n object.status = cursor.getString(cursor.getColumnIndex(\"status\"));\n if(!cursor.isNull(cursor.getColumnIndex(\"last_update\"))) {\n object.lastUpdate = new Date(cursor.getLong(cursor.getColumnIndex(\"last_update\")));\n }\n if(!cursor.isNull(cursor.getColumnIndex(\"position_id\"))) {\n object.positionId = cursor.getLong(cursor.getColumnIndex(\"position_id\"));\n }\n\n return object;\n }\n }\n\n private static class DeviceStorIOSQLiteDeleteResolver extends DefaultDeleteResolver<Device> {\n /**\n * {@inheritDoc}\n */\n @Override\n @NonNull\n public DeleteQuery mapToDeleteQuery(@NonNull Device object) {\n return DeleteQuery.builder()\n .table(\"devices\")\n .where(\"_id = ?\")\n .whereArgs(object.id)\n .build();\n }\n }\n}",
"@StorIOSQLiteType(table = PositionsTable.TABLE)\npublic class Position implements Parcelable {\n @StorIOSQLiteColumn(name = PositionsTable.COLUMN_ID, key = true)\n Long id;\n\n @StorIOSQLiteColumn(name = PositionsTable.COLUMN_PROTOCOL)\n @Since(3.0)\n String protocol;\n\n @StorIOSQLiteColumn(name = PositionsTable.COLUMN_DEVICE_ID)\n @Since(3.0)\n Long deviceId;\n\n //@StorIOSQLiteColumn(name = PositionsTable.COLUMN_SERVER_TIME)\n @Since(3.0)\n Date serverTime;\n\n //@StorIOSQLiteColumn(name = PositionsTable.COLUMN_DEVICE_TIME)\n @Since(3.0)\n Date deviceTime;\n\n //@StorIOSQLiteColumn(name = PositionsTable.COLUMN_FIX_TIME)\n @Since(3.0)\n Date fixTime;\n\n @StorIOSQLiteColumn(name = PositionsTable.COLUMN_OUTDATED)\n Boolean outdated;\n\n @StorIOSQLiteColumn(name = PositionsTable.COLUMN_VALID)\n @Since(3.0)\n Boolean valid;\n\n @StorIOSQLiteColumn(name = PositionsTable.COLUMN_LATITUDE)\n @Since(3.0)\n Double latitude;\n\n @StorIOSQLiteColumn(name = PositionsTable.COLUMN_LONGITUDE)\n @Since(3.0)\n Double longitude;\n\n @StorIOSQLiteColumn(name = PositionsTable.COLUMN_ALTITUDE)\n @Since(3.0)\n Double altitude;\n\n @StorIOSQLiteColumn(name = PositionsTable.COLUMN_SPEED)\n @Since(3.0)\n Float speed;\n\n @StorIOSQLiteColumn(name = PositionsTable.COLUMN_COURSE)\n @Since(3.0)\n Float course;\n\n @StorIOSQLiteColumn(name = PositionsTable.COLUMN_ADDRESS)\n @Since(3.0)\n String address;\n\n //@StorIOSQLiteColumn(name = PositionsTable.COLUMN_ATTRIBUTES)\n @Since(3.2)\n Map<String, Object> attributes;\n\n public Position() {\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getProtocol() {\n return protocol;\n }\n\n public void setProtocol(String protocol) {\n this.protocol = protocol;\n }\n\n public Long getDeviceId() {\n return deviceId;\n }\n\n public void setDeviceId(Long deviceId) {\n this.deviceId = deviceId;\n }\n\n public Date getServerTime() {\n return serverTime;\n }\n\n public void setServerTime(Date serverTime) {\n this.serverTime = serverTime;\n }\n\n public Date getDeviceTime() {\n return deviceTime;\n }\n\n public void setDeviceTime(Date deviceTime) {\n this.deviceTime = deviceTime;\n }\n\n public Date getFixTime() {\n return fixTime;\n }\n\n public void setFixTime(Date fixTime) {\n this.fixTime = fixTime;\n }\n\n public Boolean getOutdated() {\n return outdated;\n }\n\n public void setOutdated(Boolean outdated) {\n this.outdated = outdated;\n }\n\n public Boolean getValid() {\n return valid;\n }\n\n public void setValid(Boolean valid) {\n this.valid = valid;\n }\n\n public Double getLatitude() {\n return latitude;\n }\n\n public void setLatitude(Double latitude) {\n this.latitude = latitude;\n }\n\n public Double getLongitude() {\n return longitude;\n }\n\n public void setLongitude(Double longitude) {\n this.longitude = longitude;\n }\n\n public Double getAltitude() {\n return altitude;\n }\n\n public void setAltitude(Double altitude) {\n this.altitude = altitude;\n }\n\n public Float getSpeed() {\n return speed;\n }\n\n public void setSpeed(Float speed) {\n this.speed = speed;\n }\n\n public Float getCourse() {\n return course;\n }\n\n public void setCourse(Float course) {\n this.course = course;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public Map<String, Object> getAttributes() {\n return attributes;\n }\n\n public void setAttributes(Map<String, Object> attributes) {\n this.attributes = attributes;\n }\n\n protected Position(Parcel in) {\n id = in.readByte() == 0x00 ? null : in.readLong();\n protocol = in.readString();\n deviceId = in.readByte() == 0x00 ? null : in.readLong();\n long tmpServerTime = in.readLong();\n serverTime = tmpServerTime != -1 ? new Date(tmpServerTime) : null;\n long tmpDeviceTime = in.readLong();\n deviceTime = tmpDeviceTime != -1 ? new Date(tmpDeviceTime) : null;\n long tmpFixTime = in.readLong();\n fixTime = tmpFixTime != -1 ? new Date(tmpFixTime) : null;\n byte outdatedVal = in.readByte();\n outdated = outdatedVal == 0x02 ? null : outdatedVal != 0x00;\n byte realVal = in.readByte();\n valid = realVal == 0x02 ? null : realVal != 0x00;\n latitude = in.readByte() == 0x00 ? null : in.readDouble();\n longitude = in.readByte() == 0x00 ? null : in.readDouble();\n altitude = in.readByte() == 0x00 ? null : in.readDouble();\n speed = in.readByte() == 0x00 ? null : in.readFloat();\n course = in.readByte() == 0x00 ? null : in.readFloat();\n address = in.readString();\n //attributes = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n if (id == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeLong(id);\n }\n dest.writeString(protocol);\n if (deviceId == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeLong(deviceId);\n }\n dest.writeLong(serverTime != null ? serverTime.getTime() : -1L);\n dest.writeLong(deviceTime != null ? deviceTime.getTime() : -1L);\n dest.writeLong(fixTime != null ? fixTime.getTime() : -1L);\n if (outdated == null) {\n dest.writeByte((byte) (0x02));\n } else {\n dest.writeByte((byte) (outdated ? 0x01 : 0x00));\n }\n if (valid == null) {\n dest.writeByte((byte) (0x02));\n } else {\n dest.writeByte((byte) (valid ? 0x01 : 0x00));\n }\n if (latitude == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeDouble(latitude);\n }\n if (longitude == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeDouble(longitude);\n }\n if (altitude == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeDouble(altitude);\n }\n if (speed == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeFloat(speed);\n }\n if (course == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeFloat(course);\n }\n dest.writeString(address);\n //dest.writeString(attributes);\n }\n\n @SuppressWarnings(\"unused\")\n public static final Creator<Position> CREATOR = new Creator<Position>() {\n @Override\n public Position createFromParcel(Parcel in) {\n return new Position(in);\n }\n\n @Override\n public Position[] newArray(int size) {\n return new Position[size];\n }\n };\n\n public static List<String> createList(Position position) {\n List<String> array = new ArrayList<>();\n array.add(\"\" + position.getValid());\n array.add(\"\" + position.getFixTime().toString());\n array.add(\"\" + position.getLatitude());\n array.add(\"\" + position.getLongitude());\n array.add(\"\" + position.getAltitude());\n array.add(\"\" + position.getSpeed());\n array.add(\"\" + position.getCourse());\n return array;\n }\n\n @Override\n public String toString() {\n return \"Position{\" +\n \"id=\" + id +\n \", protocol='\" + protocol + '\\'' +\n \", deviceId=\" + deviceId +\n \", serverTime=\" + serverTime +\n \", deviceTime=\" + deviceTime +\n \", fixTime=\" + fixTime +\n \", outdated=\" + outdated +\n \", valid=\" + valid +\n \", latitude=\" + latitude +\n \", longitude=\" + longitude +\n \", altitude=\" + altitude +\n \", speed=\" + speed +\n \", course=\" + course +\n \", address='\" + address + '\\'' +\n '}';\n }\n}",
"public class PositionsTable {\n\n @NonNull\n public static final String TABLE = \"positions\";\n\n @NonNull\n public static final String COLUMN_ID = \"_id\";\n\n @NonNull\n public static final String COLUMN_PROTOCOL = \"protocol\";\n\n @NonNull\n public static final String COLUMN_DEVICE_ID = \"device_id\";\n\n @NonNull\n public static final String COLUMN_SERVER_TIME = \"server_time\";\n\n @NonNull\n public static final String COLUMN_DEVICE_TIME = \"device_time\";\n\n @NonNull\n public static final String COLUMN_FIX_TIME = \"fix_time\";\n\n @NonNull\n public static final String COLUMN_OUTDATED = \"outdated\";\n\n @NonNull\n public static final String COLUMN_VALID = \"valid\";\n\n @NonNull\n public static final String COLUMN_LATITUDE = \"latitude\";\n\n @NonNull\n public static final String COLUMN_LONGITUDE = \"longitude\";\n\n @NonNull\n public static final String COLUMN_ALTITUDE = \"altitude\";\n\n @NonNull\n public static final String COLUMN_SPEED = \"speed\";\n\n @NonNull\n public static final String COLUMN_COURSE = \"course\";\n\n @NonNull\n public static final String COLUMN_ADDRESS = \"address\";\n\n @NonNull\n public static final String COLUMN_ATTRIBUTES = \"attributes\";\n\n @NonNull\n public static final Query QUERY_ALL = Query.builder()\n .table(TABLE)\n .build();\n\n @NonNull\n public static final RawQuery QUERY_DROP = RawQuery.builder()\n .query(\"DELETE FROM \" + TABLE + \";\")\n .build();\n\n // This is just class with Meta Data, we don't need instances\n private PositionsTable() {\n throw new IllegalStateException(\"No instances please\");\n }\n\n @NonNull\n public static String getCreateTableQuery() {\n return \"CREATE TABLE \" + TABLE + \"(\"\n + COLUMN_ID + \" INTEGER NOT NULL PRIMARY KEY, \"\n + COLUMN_PROTOCOL + \" TEXT NOT NULL, \"\n + COLUMN_DEVICE_ID + \" INTEGER NOT NULL, \"\n + COLUMN_SERVER_TIME + \" NUMERIC DEFAULT NULL, \"\n + COLUMN_DEVICE_TIME + \" NUMERIC DEFAULT NULL, \"\n + COLUMN_FIX_TIME + \" NUMERIC DEFAULT NULL, \"\n + COLUMN_OUTDATED + \" INTEGER DEFAULT NULL, \"\n + COLUMN_VALID + \" INTEGER DEFAULT NULL, \"\n + COLUMN_LATITUDE + \" REAL DEFAULT NULL, \"\n + COLUMN_LONGITUDE + \" REAL DEFAULT NULL, \"\n + COLUMN_ALTITUDE + \" REAL DEFAULT NULL, \"\n + COLUMN_SPEED + \" REAL DEFAULT NULL, \"\n + COLUMN_COURSE + \" REAL DEFAULT NULL, \"\n + COLUMN_ADDRESS + \" TEXT DEFAULT NULL, \"\n + COLUMN_ATTRIBUTES + \" TEXT DEFAULT NULL\"\n + \");\";\n }\n\n public static class PositionSQLiteTypeMapping extends SQLiteTypeMapping<Position> {\n public PositionSQLiteTypeMapping() {\n super(new PositionStorIOSQLitePutResolver(),\n new PositionStorIOSQLiteGetResolver(),\n new PositionStorIOSQLiteDeleteResolver());\n }\n }\n\n private static class PositionStorIOSQLitePutResolver extends DefaultPutResolver<Position> {\n /**\n * {@inheritDoc}\n */\n @Override\n @NonNull\n public InsertQuery mapToInsertQuery(@NonNull Position object) {\n return InsertQuery.builder()\n .table(\"positions\")\n .build();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n @NonNull\n public UpdateQuery mapToUpdateQuery(@NonNull Position object) {\n return UpdateQuery.builder()\n .table(\"positions\")\n .where(\"_id = ?\")\n .whereArgs(object.id)\n .build();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n @NonNull\n public ContentValues mapToContentValues(@NonNull Position object) {\n ContentValues contentValues = new ContentValues(14);\n\n contentValues.put(\"_id\", object.id);\n contentValues.put(\"protocol\", object.protocol);\n contentValues.put(\"device_id\", object.deviceId);\n contentValues.put(\"server_time\", object.serverTime == null ? null : object.serverTime.getTime());\n contentValues.put(\"device_time\", object.deviceTime == null ? null : object.deviceTime.getTime());\n contentValues.put(\"fix_time\", object.fixTime == null ? null : object.fixTime.getTime());\n contentValues.put(\"outdated\", object.outdated);\n contentValues.put(\"valid\", object.valid);\n contentValues.put(\"latitude\", object.latitude);\n contentValues.put(\"longitude\", object.longitude);\n contentValues.put(\"altitude\", object.altitude);\n contentValues.put(\"speed\", object.speed);\n contentValues.put(\"course\", object.course);\n contentValues.put(\"address\", object.address);\n\n return contentValues;\n }\n }\n\n private static class PositionStorIOSQLiteGetResolver extends DefaultGetResolver<Position> {\n /**\n * {@inheritDoc}\n */\n @Override\n @NonNull\n public Position mapFromCursor(@NonNull Cursor cursor) {\n Position object = new Position();\n\n if(!cursor.isNull(cursor.getColumnIndex(\"_id\"))) {\n object.id = cursor.getLong(cursor.getColumnIndex(\"_id\"));\n }\n object.protocol = cursor.getString(cursor.getColumnIndex(\"protocol\"));\n if(!cursor.isNull(cursor.getColumnIndex(\"device_id\"))) {\n object.deviceId = cursor.getLong(cursor.getColumnIndex(\"device_id\"));\n }\n if(!cursor.isNull(cursor.getColumnIndex(\"server_time\"))) {\n object.serverTime = new Date(cursor.getLong(cursor.getColumnIndex(\"server_time\")));\n }\n if(!cursor.isNull(cursor.getColumnIndex(\"device_time\"))) {\n object.deviceTime = new Date(cursor.getLong(cursor.getColumnIndex(\"device_time\")));\n }\n if(!cursor.isNull(cursor.getColumnIndex(\"fix_time\"))) {\n object.fixTime = new Date(cursor.getLong(cursor.getColumnIndex(\"fix_time\")));\n }\n if(!cursor.isNull(cursor.getColumnIndex(\"outdated\"))) {\n object.outdated = cursor.getInt(cursor.getColumnIndex(\"outdated\")) == 1;\n }\n if(!cursor.isNull(cursor.getColumnIndex(\"valid\"))) {\n object.valid = cursor.getInt(cursor.getColumnIndex(\"valid\")) == 1;\n }\n if(!cursor.isNull(cursor.getColumnIndex(\"latitude\"))) {\n object.latitude = cursor.getDouble(cursor.getColumnIndex(\"latitude\"));\n }\n if(!cursor.isNull(cursor.getColumnIndex(\"longitude\"))) {\n object.longitude = cursor.getDouble(cursor.getColumnIndex(\"longitude\"));\n }\n if(!cursor.isNull(cursor.getColumnIndex(\"altitude\"))) {\n object.altitude = cursor.getDouble(cursor.getColumnIndex(\"altitude\"));\n }\n if(!cursor.isNull(cursor.getColumnIndex(\"speed\"))) {\n object.speed = cursor.getFloat(cursor.getColumnIndex(\"speed\"));\n }\n if(!cursor.isNull(cursor.getColumnIndex(\"course\"))) {\n object.course = cursor.getFloat(cursor.getColumnIndex(\"course\"));\n }\n object.address = cursor.getString(cursor.getColumnIndex(\"address\"));\n\n return object;\n }\n }\n\n private static class PositionStorIOSQLiteDeleteResolver extends DefaultDeleteResolver<Position> {\n /**\n * {@inheritDoc}\n */\n @Override\n @NonNull\n public DeleteQuery mapToDeleteQuery(@NonNull Position object) {\n return DeleteQuery.builder()\n .table(\"positions\")\n .where(\"_id = ?\")\n .whereArgs(object.id)\n .build();\n }\n }\n\n}",
"@StorIOSQLiteType(table = ServersTable.TABLE)\npublic class Server implements Parcelable {\n\n @StorIOSQLiteColumn(name = ServersTable.COLUMN_ID, key = true)\n @SerializedName(\"id\")\n @Expose\n long id;\n\n @StorIOSQLiteColumn(name = ServersTable.COLUMN_REGISTRATION)\n @Since(3.0)\n @SerializedName(\"registration\")\n @Expose\n Boolean registration;\n\n @StorIOSQLiteColumn(name = ServersTable.COLUMN_LATITUDE)\n @Since(3.0)\n @SerializedName(\"latitude\")\n @Expose\n Double latitude;\n\n @StorIOSQLiteColumn(name = ServersTable.COLUMN_LONGITUDE)\n @Since(3.0)\n @SerializedName(\"longitude\")\n @Expose\n Double longitude;\n\n @StorIOSQLiteColumn(name = ServersTable.COLUMN_ZOOM)\n @Since(3.0)\n @SerializedName(\"zoom\")\n @Expose\n Integer zoom;\n\n @StorIOSQLiteColumn(name = ServersTable.COLUMN_MAP)\n @Since(3.1)\n @SerializedName(\"map\")\n @Expose\n String map;\n\n @StorIOSQLiteColumn(name = ServersTable.COLUMN_LANGUAGE)\n @Since(3.1)\n @SerializedName(\"language\")\n @Expose\n String language;\n\n @StorIOSQLiteColumn(name = ServersTable.COLUMN_DISTANCE_UNIT)\n @Since(3.1)\n @SerializedName(\"distanceUnit\")\n @Expose\n String distanceUnit;\n\n @StorIOSQLiteColumn(name = ServersTable.COLUMN_SPEED_UNIT)\n @Since(3.1)\n @SerializedName(\"speedUnit\")\n @Expose\n String speedUnit;\n\n @StorIOSQLiteColumn(name = ServersTable.COLUMN_BING_KEY)\n @Since(3.2)\n @SerializedName(\"bingKey\")\n @Expose\n String bingKey;\n\n @StorIOSQLiteColumn(name = ServersTable.COLUMN_MAP_URL)\n @Since(3.2)\n @SerializedName(\"mapUrl\")\n @Expose\n String mapUrl;\n\n @StorIOSQLiteColumn(name = ServersTable.COLUMN_READONLY)\n @Since(3.4)\n @SerializedName(\"readonly\")\n @Expose\n Boolean readonly;\n\n @StorIOSQLiteColumn(name = ServersTable.COLUMN_TWELVE_HOUR_FORMAT)\n @Since(3.5)\n @SerializedName(\"twelveHourFormat\")\n @Expose\n Boolean twelveHourFormat;\n\n public Server() {}\n /**\n * @return The id\n */\n public long getId() {\n return id;\n }\n\n /**\n * @param id The id\n */\n public void setId(long id) {\n this.id = id;\n }\n\n /**\n * @return The registration\n */\n public Boolean getRegistration() {\n return registration;\n }\n\n /**\n * @param registration The registration\n */\n public void setRegistration(Boolean registration) {\n this.registration = registration;\n }\n\n /**\n * @return The readonly\n */\n public Boolean getReadonly() {\n return readonly;\n }\n\n /**\n * @param readonly The readonly\n */\n public void setReadonly(Boolean readonly) {\n this.readonly = readonly;\n }\n\n /**\n * @return The map\n */\n public String getMap() {\n return map;\n }\n\n /**\n * @param map The map\n */\n public void setMap(String map) {\n this.map = map;\n }\n\n /**\n * @return The language\n */\n public String getLanguage() {\n return language;\n }\n\n /**\n * @param language The map\n */\n public void setLanguage(String language) {\n this.language = language;\n }\n\n /**\n * @return The bingKey\n */\n public String getBingKey() {\n return bingKey;\n }\n\n /**\n * @param bingKey The bingKey\n */\n public void setBingKey(String bingKey) {\n this.bingKey = bingKey;\n }\n\n /**\n * @return The mapUrl\n */\n public String getMapUrl() {\n return mapUrl;\n }\n\n /**\n * @param mapUrl The mapUrl\n */\n public void setMapUrl(String mapUrl) {\n this.mapUrl = mapUrl;\n }\n\n /**\n * @return The distanceUnit\n */\n public String getDistanceUnit() {\n return distanceUnit;\n }\n\n /**\n * @param distanceUnit The distanceUnit\n */\n public void setDistanceUnit(String distanceUnit) {\n this.distanceUnit = distanceUnit;\n }\n\n /**\n * @return The speedUnit\n */\n public String getSpeedUnit() {\n return speedUnit;\n }\n\n /**\n * @param speedUnit The speedUnit\n */\n public void setSpeedUnit(String speedUnit) {\n this.speedUnit = speedUnit;\n }\n\n /**\n * @return The latitude\n */\n public Double getLatitude() {\n return latitude;\n }\n\n /**\n * @param latitude The latitude\n */\n public void setLatitude(Double latitude) {\n this.latitude = latitude;\n }\n\n /**\n * @return The longitude\n */\n public Double getLongitude() {\n return longitude;\n }\n\n /**\n * @param longitude The longitude\n */\n public void setLongitude(Double longitude) {\n this.longitude = longitude;\n }\n\n /**\n * @return The zoom\n */\n public Integer getZoom() {\n return zoom;\n }\n\n /**\n * @param zoom The zoom\n */\n public void setZoom(Integer zoom) {\n this.zoom = zoom;\n }\n\n /**\n * @return The twelveHourFormat\n */\n public Boolean getTwelveHourFormat() {\n return twelveHourFormat;\n }\n\n /**\n * @param twelveHourFormat The twelveHourFormat\n */\n public void setTwelveHourFormat(Boolean twelveHourFormat) {\n this.twelveHourFormat = twelveHourFormat;\n }\n\n\n @Override\n public String toString() {\n return \"Server{\" +\n \"id=\" + id +\n \", registration=\" + registration +\n \", latitude=\" + latitude +\n \", longitude=\" + longitude +\n \", zoom=\" + zoom +\n \", map='\" + map + '\\'' +\n \", language='\" + language + '\\'' +\n \", distanceUnit='\" + distanceUnit + '\\'' +\n \", speedUnit='\" + speedUnit + '\\'' +\n \", bingKey='\" + bingKey + '\\'' +\n \", mapUrl='\" + mapUrl + '\\'' +\n \", readonly=\" + readonly +\n \", twelveHourFormat=\" + twelveHourFormat +\n '}';\n }\n\n protected Server(Parcel in) {\n id = in.readLong();\n byte registrationVal = in.readByte();\n registration = registrationVal == 0x02 ? null : registrationVal != 0x00;\n byte readonlyVal = in.readByte();\n readonly = readonlyVal == 0x02 ? null : readonlyVal != 0x00;\n map = in.readString();\n language = in.readString();\n bingKey = in.readString();\n mapUrl = in.readString();\n distanceUnit = in.readString();\n speedUnit = in.readString();\n latitude = in.readByte() == 0x00 ? null : in.readDouble();\n longitude = in.readByte() == 0x00 ? null : in.readDouble();\n zoom = in.readByte() == 0x00 ? null : in.readInt();\n byte twelveHourFormatVal = in.readByte();\n twelveHourFormat = twelveHourFormatVal == 0x02 ? null : twelveHourFormatVal != 0x00;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeLong(id);\n if (registration == null) {\n dest.writeByte((byte) (0x02));\n } else {\n dest.writeByte((byte) (registration ? 0x01 : 0x00));\n }\n if (readonly == null) {\n dest.writeByte((byte) (0x02));\n } else {\n dest.writeByte((byte) (readonly ? 0x01 : 0x00));\n }\n dest.writeString(map);\n dest.writeString(language);\n dest.writeString(bingKey);\n dest.writeString(mapUrl);\n dest.writeString(distanceUnit);\n dest.writeString(speedUnit);\n if (latitude == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeDouble(latitude);\n }\n if (longitude == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeDouble(longitude);\n }\n if (zoom == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeInt(zoom);\n }\n if (twelveHourFormat == null) {\n dest.writeByte((byte) (0x02));\n } else {\n dest.writeByte((byte) (twelveHourFormat ? 0x01 : 0x00));\n }\n }\n\n @SuppressWarnings(\"unused\")\n public static final Creator<Server> CREATOR = new Creator<Server>() {\n @Override\n public Server createFromParcel(Parcel in) {\n return new Server(in);\n }\n\n @Override\n public Server[] newArray(int size) {\n return new Server[size];\n }\n };\n}",
"public class ServersTable {\n\n @NonNull\n public static final String TABLE = \"servers\";\n\n @NonNull\n public static final String COLUMN_ID = \"_id\";\n\n @NonNull\n public static final String COLUMN_REGISTRATION = \"registration\";\n\n @NonNull\n public static final String COLUMN_LATITUDE = \"latitude\";\n\n @NonNull\n public static final String COLUMN_LONGITUDE = \"longitude\";\n\n @NonNull\n public static final String COLUMN_ZOOM = \"zoom\";\n\n @NonNull\n public static final String COLUMN_MAP = \"map\";\n\n @NonNull\n public static final String COLUMN_LANGUAGE = \"language\";\n\n @NonNull\n public static final String COLUMN_DISTANCE_UNIT = \"distance_unit\";\n\n @NonNull\n public static final String COLUMN_SPEED_UNIT = \"speed_unit\";\n\n @NonNull\n public static final String COLUMN_BING_KEY = \"bing_key\";\n\n @NonNull\n public static final String COLUMN_MAP_URL = \"map_url\";\n\n @NonNull\n public static final String COLUMN_READONLY = \"readonly\";\n\n @NonNull\n public static final String COLUMN_TWELVE_HOUR_FORMAT = \"twelve_hour_format\";\n\n\n // Yep, with StorIO you can safely store queries as objects and reuse them, they are immutable\n @NonNull\n public static final Query QUERY_ALL = Query.builder()\n .table(TABLE)\n .build();\n\n @NonNull\n public static final RawQuery QUERY_DROP = RawQuery.builder()\n .query(\"DELETE FROM \" + TABLE + \";\")\n .build();\n\n // This is just class with Meta Data, we don't need instances\n private ServersTable() {\n throw new IllegalStateException(\"No instances please\");\n }\n\n @NonNull\n public static String getCreateTableQuery() {\n return \"CREATE TABLE \" + TABLE + \"(\"\n + COLUMN_ID + \" INTEGER NOT NULL PRIMARY KEY, \"\n + COLUMN_REGISTRATION + \" INTEGER NOT NULL, \"\n + COLUMN_LATITUDE + \" REAL NOT NULL, \"\n + COLUMN_LONGITUDE + \" REAL NOT NULL, \"\n + COLUMN_ZOOM + \" INTEGER NOT NULL, \"\n + COLUMN_MAP + \" TEXT DEFAULT NULL, \"\n + COLUMN_LANGUAGE + \" TEXT DEFAULT NULL, \"\n + COLUMN_DISTANCE_UNIT + \" TEXT DEFAULT NULL, \"\n + COLUMN_SPEED_UNIT + \" TEXT DEFAULT NULL, \"\n + COLUMN_BING_KEY + \" TEXT DEFAULT NULL, \"\n + COLUMN_MAP_URL + \" TEXT DEFAULT NULL, \"\n + COLUMN_READONLY + \" INTEGER NOT NULL, \"\n + COLUMN_TWELVE_HOUR_FORMAT + \" INTEGER DEFAULT NULL\"\n + \");\";\n }\n}",
"@StorIOSQLiteType(table = UsersTable.TABLE)\npublic class User implements Parcelable {\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_ID, key = true)\n @SerializedName(\"id\")\n @Expose\n long id;\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_NAME)\n @Since(3.0)\n @SerializedName(\"name\")\n @Expose\n String name;\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_EMAIL)\n @Since(3.0)\n @SerializedName(\"email\")\n @Expose\n String email;\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_PASSWORD)\n @Since(3.0)\n @SerializedName(\"password\")\n @Expose\n String password;\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_ADMIN)\n @Since(3.0)\n @SerializedName(\"admin\")\n @Expose\n Boolean admin;\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_MAP)\n @Since(3.1)\n @SerializedName(\"map\")\n @Expose\n String map;\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_LANGUAGE)\n @Since(3.1)\n @SerializedName(\"language\")\n @Expose\n String language;\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_DISTANCE_UNIT)\n @Since(3.1)\n @SerializedName(\"distanceUnit\")\n @Expose\n String distanceUnit;\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_SPEED_UNIT)\n @Since(3.1)\n @SerializedName(\"speedUnit\")\n @Expose\n String speedUnit;\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_LATITUDE)\n @Since(3.1)\n @SerializedName(\"latitude\")\n @Expose\n Double latitude;\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_LONGITUDE)\n @Since(3.1)\n @SerializedName(\"longitude\")\n @Expose\n Double longitude;\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_ZOOM)\n @Since(3.1)\n @SerializedName(\"zoom\")\n @Expose\n Integer zoom;\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_READONLY)\n @Since(3.4)\n @SerializedName(\"readonly\")\n @Expose\n Boolean readonly;\n\n @StorIOSQLiteColumn(name = UsersTable.COLUMN_TWELVE_HOUR_FORMAT)\n @Since(3.5)\n @SerializedName(\"twelveHourFormat\")\n @Expose\n Boolean twelveHourFormat;\n\n public User() {}\n /**\n *\n * @return\n * The id\n */\n public long getId() {\n return id;\n }\n\n /**\n *\n * @param id\n * The id\n */\n public void setId(long id) {\n this.id = id;\n }\n\n /**\n *\n * @return\n * The name\n */\n public String getName() {\n return name;\n }\n\n /**\n *\n * @param name\n * The name\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n *\n * @return\n * The email\n */\n public String getEmail() {\n return email;\n }\n\n /**\n *\n * @param email\n * The email\n */\n public void setEmail(String email) {\n this.email = email;\n }\n\n /**\n *\n * @return\n * The readonly\n */\n public Boolean getReadonly() {\n return readonly;\n }\n\n /**\n *\n * @param readonly\n * The readonly\n */\n public void setReadonly(Boolean readonly) {\n this.readonly = readonly;\n }\n\n /**\n *\n * @return\n * The admin\n */\n public Boolean getAdmin() {\n return admin;\n }\n\n /**\n *\n * @param admin\n * The admin\n */\n public void setAdmin(Boolean admin) {\n this.admin = admin;\n }\n\n /**\n *\n * @return\n * The map\n */\n public String getMap() {\n return map;\n }\n\n /**\n *\n * @param map\n * The map\n */\n public void setMap(String map) {\n this.map = map;\n }\n\n public String getLanguage() {\n return language;\n }\n\n public void setLanguage(String language) {\n this.language = language;\n }\n\n /**\n *\n * @return\n * The distanceUnit\n */\n public String getDistanceUnit() {\n return distanceUnit;\n }\n\n /**\n *\n * @param distanceUnit\n * The distanceUnit\n */\n public void setDistanceUnit(String distanceUnit) {\n this.distanceUnit = distanceUnit;\n }\n\n /**\n *\n * @return\n * The speedUnit\n */\n public String getSpeedUnit() {\n return speedUnit;\n }\n\n /**\n *\n * @param speedUnit\n * The speedUnit\n */\n public void setSpeedUnit(String speedUnit) {\n this.speedUnit = speedUnit;\n }\n\n /**\n *\n * @return\n * The latitude\n */\n public Double getLatitude() {\n return latitude;\n }\n\n /**\n *\n * @param latitude\n * The latitude\n */\n public void setLatitude(Double latitude) {\n this.latitude = latitude;\n }\n\n /**\n *\n * @return\n * The longitude\n */\n public Double getLongitude() {\n return longitude;\n }\n\n /**\n *\n * @param longitude\n * The longitude\n */\n public void setLongitude(Double longitude) {\n this.longitude = longitude;\n }\n\n /**\n *\n * @return\n * The zoom\n */\n public Integer getZoom() {\n return zoom;\n }\n\n /**\n *\n * @param zoom\n * The zoom\n */\n public void setZoom(Integer zoom) {\n this.zoom = zoom;\n }\n\n /**\n *\n * @return\n * The twelveHourFormat\n */\n public Boolean getTwelveHourFormat() {\n return twelveHourFormat;\n }\n\n /**\n *\n * @param twelveHourFormat\n * The twelveHourFormat\n */\n public void setTwelveHourFormat(Boolean twelveHourFormat) {\n this.twelveHourFormat = twelveHourFormat;\n }\n\n /**\n *\n * @return\n * The password\n */\n public String getPassword() {\n return password;\n }\n\n /**\n *\n * @param password\n * The password\n */\n public void setPassword(String password) {\n this.password = password;\n }\n\n @Override\n public String toString() {\n return \"User{\" +\n \"id=\" + id +\n \", name='\" + name + '\\'' +\n \", email='\" + email + '\\'' +\n \", password='\" + password + '\\'' +\n \", admin=\" + admin +\n \", map='\" + map + '\\'' +\n \", language='\" + language + '\\'' +\n \", distanceUnit='\" + distanceUnit + '\\'' +\n \", speedUnit='\" + speedUnit + '\\'' +\n \", latitude=\" + latitude +\n \", longitude=\" + longitude +\n \", zoom=\" + zoom +\n \", readonly=\" + readonly +\n \", twelveHourFormat=\" + twelveHourFormat +\n '}';\n }\n\n protected User(Parcel in) {\n id = in.readLong();\n name = in.readString();\n email = in.readString();\n byte readonlyVal = in.readByte();\n readonly = readonlyVal == 0x02 ? null : readonlyVal != 0x00;\n byte adminVal = in.readByte();\n admin = adminVal == 0x02 ? null : adminVal != 0x00;\n map = in.readString();\n language = in.readString();\n distanceUnit = in.readString();\n speedUnit = in.readString();\n latitude = in.readByte() == 0x00 ? null : in.readDouble();\n longitude = in.readByte() == 0x00 ? null : in.readDouble();\n zoom = in.readByte() == 0x00 ? null : in.readInt();\n byte twelveHourFormatVal = in.readByte();\n twelveHourFormat = twelveHourFormatVal == 0x02 ? null : twelveHourFormatVal != 0x00;\n password = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeLong(id);\n dest.writeString(name);\n dest.writeString(email);\n if (readonly == null) {\n dest.writeByte((byte) (0x02));\n } else {\n dest.writeByte((byte) (readonly ? 0x01 : 0x00));\n }\n if (admin == null) {\n dest.writeByte((byte) (0x02));\n } else {\n dest.writeByte((byte) (admin ? 0x01 : 0x00));\n }\n dest.writeString(map);\n dest.writeString(language);\n dest.writeString(distanceUnit);\n dest.writeString(speedUnit);\n if (latitude == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeDouble(latitude);\n }\n if (longitude == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeDouble(longitude);\n }\n if (zoom == null) {\n dest.writeByte((byte) (0x00));\n } else {\n dest.writeByte((byte) (0x01));\n dest.writeInt(zoom);\n }\n if (twelveHourFormat == null) {\n dest.writeByte((byte) (0x02));\n } else {\n dest.writeByte((byte) (twelveHourFormat ? 0x01 : 0x00));\n }\n dest.writeString(password);\n }\n\n @SuppressWarnings(\"unused\")\n public static final Creator<User> CREATOR = new Creator<User>() {\n @Override\n public User createFromParcel(Parcel in) {\n return new User(in);\n }\n\n @Override\n public User[] newArray(int size) {\n return new User[size];\n }\n };\n\n public static User newUser(String name, String email, String password) {\n User user = new User();\n user.setName(name);\n user.setEmail(email);\n user.setPassword(password);\n return user;\n }\n}",
"public class UsersTable {\n\n @NonNull\n public static final String TABLE = \"users\";\n\n @NonNull\n public static final String COLUMN_ID = \"_id\";\n\n @NonNull\n public static final String COLUMN_NAME = \"name\";\n\n @NonNull\n public static final String COLUMN_EMAIL = \"email\";\n\n @NonNull\n public static final String COLUMN_PASSWORD = \"password\";\n\n @NonNull\n public static final String COLUMN_ADMIN = \"admin\";\n\n @NonNull\n public static final String COLUMN_MAP = \"map\";\n\n @NonNull\n public static final String COLUMN_LANGUAGE = \"language\";\n\n @NonNull\n public static final String COLUMN_DISTANCE_UNIT = \"distance_unit\";\n\n @NonNull\n public static final String COLUMN_SPEED_UNIT = \"speed_unit\";\n\n @NonNull\n public static final String COLUMN_LATITUDE = \"latitude\";\n\n @NonNull\n public static final String COLUMN_LONGITUDE = \"longitude\";\n\n @NonNull\n public static final String COLUMN_ZOOM = \"zoom\";\n\n @NonNull\n public static final String COLUMN_READONLY = \"readonly\";\n\n @NonNull\n public static final String COLUMN_TWELVE_HOUR_FORMAT = \"twelve_hour_format\";\n\n\n // Yep, with StorIO you can safely store queries as objects and reuse them, they are immutable\n @NonNull\n public static final Query QUERY_ALL = Query.builder()\n .table(TABLE)\n .orderBy(\"name\")\n .build();\n\n @NonNull\n public static final RawQuery QUERY_DROP = RawQuery.builder()\n .query(\"DELETE FROM \" + TABLE + \";\")\n .build();\n\n // This is just class with Meta Data, we don't need instances\n private UsersTable() {\n throw new IllegalStateException(\"No instances please\");\n }\n\n @NonNull\n public static String getCreateTableQuery() {\n return \"CREATE TABLE \" + TABLE + \"(\"\n + COLUMN_ID + \" INTEGER NOT NULL PRIMARY KEY, \"\n + COLUMN_NAME + \" TEXT NOT NULL, \"\n + COLUMN_EMAIL + \" TEXT NOT NULL, \"\n + COLUMN_PASSWORD + \" TEXT DEFAULT NULL, \"\n + COLUMN_ADMIN + \" INTEGER NOT NULL, \"\n + COLUMN_MAP+ \" TEXT DEFAULT NULL, \"\n + COLUMN_LANGUAGE + \" TEXT DEFAULT NULL, \"\n + COLUMN_DISTANCE_UNIT + \" TEXT DEFAULT NULL, \"\n + COLUMN_SPEED_UNIT + \" TEXT DEFAULT NULL, \"\n + COLUMN_LATITUDE + \" REAL NOT NULL, \"\n + COLUMN_LONGITUDE + \" REAL NOT NULL, \"\n + COLUMN_ZOOM + \" INTEGER NOT NULL, \"\n + COLUMN_READONLY + \" INTEGER NOT NULL, \"\n + COLUMN_TWELVE_HOUR_FORMAT + \" INTEGER DEFAULT NULL\"\n + \");\";\n }\n}"
] | import android.content.Context;
import android.database.Cursor;
import com.fernandocejas.frodo.annotation.RxLogObservable;
import com.pushtorefresh.storio.sqlite.StorIOSQLite;
import com.pushtorefresh.storio.sqlite.impl.DefaultStorIOSQLite;
import com.pushtorefresh.storio.sqlite.operations.put.PutResults;
import com.pushtorefresh.storio.sqlite.queries.DeleteQuery;
import com.pushtorefresh.storio.sqlite.queries.Query;
import org.erlymon.monitor.mvp.model.DbOpenHelper;
import org.erlymon.monitor.mvp.model.Device;
import org.erlymon.monitor.mvp.model.DevicesTable;
import org.erlymon.monitor.mvp.model.Position;
import org.erlymon.monitor.mvp.model.PositionsTable;
import org.erlymon.monitor.mvp.model.Server;
import org.erlymon.monitor.mvp.model.ServerSQLiteTypeMapping;
import org.erlymon.monitor.mvp.model.ServersTable;
import org.erlymon.monitor.mvp.model.User;
import org.erlymon.monitor.mvp.model.UserSQLiteTypeMapping;
import org.erlymon.monitor.mvp.model.UsersTable;
import java.util.Arrays;
import java.util.List;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func3; | /*
* Copyright (c) 2016, Sergey Penkovsky <[email protected]>
*
* This file is part of Erlymon Monitor.
*
* Erlymon Monitor 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.
*
* Erlymon Monitor 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 Erlymon Monitor. If not, see <http://www.gnu.org/licenses/>.
*/
package org.erlymon.monitor.mvp;
/**
* Created by sergey on 21.03.17.
*/
public class StorageService {
private StorIOSQLite storIOSQLite;
public StorageService(Context context) {
storIOSQLite = DefaultStorIOSQLite.builder()
.sqliteOpenHelper(new DbOpenHelper(context))
.addTypeMapping(Server.class, new ServerSQLiteTypeMapping())
.addTypeMapping(User.class, new UserSQLiteTypeMapping()) | .addTypeMapping(Device.class, new DevicesTable.DeviceSQLiteTypeMapping()) | 1 |
idega/se.idega.idegaweb.commune.accounting | src/java/se/idega/idegaweb/commune/accounting/posting/business/PostingBusinessBean.java | [
"public interface ExportDataMapping extends IDOEntity {\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getPrimaryKeyClass\n\t */\n\tpublic Class getPrimaryKeyClass();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getOperationalField\n\t */\n\tpublic SchoolCategory getOperationalField();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getJournalNumber\n\t */\n\tpublic String getJournalNumber();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getAccount\n\t */\n\tpublic String getAccount();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getCounterAccount\n\t */\n\tpublic String getCounterAccount();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getPayableAccount\n\t */\n\tpublic String getPayableAccount();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getCustomerClaimAccount\n\t */\n\tpublic String getCustomerClaimAccount();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getAccountSettlementType\n\t */\n\tpublic int getAccountSettlementType();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getStandardPaymentDay\n\t */\n\tpublic int getStandardPaymentDay();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getCashFlowIn\n\t */\n\tpublic boolean getCashFlowIn();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getCashFlowOut\n\t */\n\tpublic boolean getCashFlowOut();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getProviderAuthorization\n\t */\n\tpublic boolean getProviderAuthorization();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getFileCreationFolder\n\t */\n\tpublic String getFileCreationFolder();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getIFSFileFolder\n\t */\n\tpublic String getIFSFileFolder();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getFileBackupFolder\n\t */\n\tpublic String getFileBackupFolder();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getListCreationFolder\n\t */\n\tpublic String getListCreationFolder();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getListBackupFolder\n\t */\n\tpublic String getListBackupFolder();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getUseSpecifiedNumberOfDaysPrMonth\n\t */\n\tpublic boolean getUseSpecifiedNumberOfDaysPrMonth();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getSpecifiedNumberOfDaysPrMonth\n\t */\n\tpublic int getSpecifiedNumberOfDaysPrMonth();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getCreatePaymentsForCommuneProvidersOutsideCommune\n\t */\n\tpublic boolean getCreatePaymentsForCommuneProvidersOutsideCommune();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setOperationalField\n\t */\n\tpublic void setOperationalField(String operationalField);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setOperationalField\n\t */\n\tpublic void setOperationalField(SchoolCategory operationalField);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setJournalNumber\n\t */\n\tpublic void setJournalNumber(String journalNumber);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setAccount\n\t */\n\tpublic void setAccount(String account);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setCounterAccount\n\t */\n\tpublic void setCounterAccount(String counterAccount);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setPayableAccount\n\t */\n\tpublic void setPayableAccount(String payableAccount);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setCustomerClaimAccount\n\t */\n\tpublic void setCustomerClaimAccount(String customerClaimAccount);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setAccountSettlementType\n\t */\n\tpublic void setAccountSettlementType(int accountSettlementType);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setStandardPaymentDay\n\t */\n\tpublic void setStandardPaymentDay(int standardPaymentDay);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setCashFlowIn\n\t */\n\tpublic void setCashFlowIn(boolean cashFlowIn);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setCashFlowOut\n\t */\n\tpublic void setCashFlowOut(boolean cashFlowOut);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setProviderAuthorization\n\t */\n\tpublic void setProviderAuthorization(boolean providerAuthorization);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setFileCreationFolder\n\t */\n\tpublic void setFileCreationFolder(String folder);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setIFSFileFolder\n\t */\n\tpublic void setIFSFileFolder(String folder);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setFileBackupFolder\n\t */\n\tpublic void setFileBackupFolder(String folder);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setListCreationFolder\n\t */\n\tpublic void setListCreationFolder(String folder);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setListBackupFolder\n\t */\n\tpublic void setListBackupFolder(String folder);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setUseSpecifiedNumberOfDaysPrMonth\n\t */\n\tpublic void setUseSpecifiedNumberOfDaysPrMonth(boolean useSpecifiedDays);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setSpecifiedNumberOfDaysPrMonth\n\t */\n\tpublic void setSpecifiedNumberOfDaysPrMonth(int specifiedDays);\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#setCreatePaymentsForCommuneProvidersOutsideCommune\n\t */\n\tpublic void setCreatePaymentsForCommuneProvidersOutsideCommune(boolean createPayments);\n\n}",
"public interface PostingParameters extends com.idega.data.IDOEntity\n{\n public com.idega.block.school.data.SchoolType getActivity();\n public java.sql.Timestamp getChangedDate();\n public java.lang.String getChangedSign();\n public se.idega.idegaweb.commune.accounting.regulations.data.CommuneBelongingType getCommuneBelonging();\n public com.idega.block.school.data.SchoolManagementType getCompanyType();\n public java.lang.String getDoublePostingString();\n public java.sql.Date getPeriodFrom();\n public java.sql.Date getPeriodTo();\n public java.lang.String getPostingString();\n public se.idega.idegaweb.commune.accounting.regulations.data.RegulationSpecType getRegSpecType();\n public com.idega.block.school.data.SchoolYear getSchoolYear1();\n public com.idega.block.school.data.SchoolYear getSchoolYear2();\n public com.idega.block.school.data.SchoolStudyPath getStudyPath();\n public void setActivity(int p0);\n public void setChangedDate(java.sql.Timestamp p0);\n public void setChangedSign(java.lang.String p0);\n public void setCommuneBelonging(int p0);\n public void setCompanyType(java.lang.String p0);\n public void setDoublePostingString(java.lang.String p0);\n public void setPeriodFrom(java.sql.Date p0);\n public void setPeriodTo(java.sql.Date p0);\n public void setPostingString(java.lang.String p0);\n public void setRegSpecType(int p0);\n public void setSchoolYear1(int p0);\n public void setSchoolYear2(int p0);\n public void setStudyPath(int p0);\n}",
"public interface PostingParametersHome extends com.idega.data.IDOHome\n{\n public PostingParameters create() throws javax.ejb.CreateException;\n public PostingParameters findByPrimaryKey(Object pk) throws javax.ejb.FinderException;\n public java.util.Collection findAllPostingParameters()throws javax.ejb.FinderException;\n public PostingParameters findPostingParameter(java.sql.Date p0,int p1,int p2,java.lang.String p3,int p4,int p5,int p6)throws javax.ejb.FinderException;\n public PostingParameters findPostingParameter(int p0)throws javax.ejb.FinderException;\n public PostingParameters findPostingParameter(int p0,int p1,int p2,int p3)throws javax.ejb.FinderException;\n public PostingParameters findPostingParameter(java.sql.Date p0,int p1,int p2,java.lang.String p3,int p4,int p5,int p6,boolean p7)throws javax.ejb.FinderException;\n public PostingParameters findPostingParameter(java.sql.Date p0,java.sql.Date p1,java.lang.String p2,java.lang.String p3,int p4,int p5,java.lang.String p6,int p7,int p8,int p9,int p10)throws javax.ejb.FinderException;\n public java.util.Collection findPostingParametersByDate(java.sql.Date p0)throws javax.ejb.FinderException;\n public java.util.Collection findPostingParametersByPeriod(java.sql.Date p0,java.sql.Date p1)throws javax.ejb.FinderException;\n public java.util.Collection findPostingParametersByPeriodAndOperationalID(java.sql.Date p0,java.sql.Date p1,String opID)throws javax.ejb.FinderException;\n\n}",
"public interface PostingString extends com.idega.data.IDOEntity\n{\n public java.sql.Date getValidFrom();\n public java.sql.Date getValidTo();\n public void initializeAttributes();\n public void setValidFrom(java.sql.Date p0);\n public void setValidTo(java.sql.Date p0);\n}",
"public class Provider {\n\n\tprivate School school = null;\n\tprivate ProviderAccountingProperties properties = null;\n\t\t\t\n\t/**\n\t * Constructs a new provider object with the specified school\n\t * @param school the school for the provider\n\t */\n\tpublic Provider(School school) {\n\t\ttry {\n\t\t\tthis.school = school;\n\t\t\tif (school != null) {\n\t\t\t\tProviderAccountingPropertiesHome h = (ProviderAccountingPropertiesHome) com.idega.data.IDOLookup.getHome(ProviderAccountingProperties.class);\n\t\t\t\tthis.properties = h.findByPrimaryKey(school.getPrimaryKey()); \n\t\t\t}\n\t\t} catch (RemoteException e) {\n\t\t} catch (FinderException e) {}\n\t}\n\t\t\t\n\t/**\n\t * Constructs a new provider object by retrieving the school\n\t * and accounting properties for the provider.\n\t * @param schoolId the school id for the provider\n\t */\n\tpublic Provider(int schoolId) {\n\t\ttry {\n\t\t\tSchoolHome home = (SchoolHome) com.idega.data.IDOLookup.getHome(School.class);\n\t\t\tthis.school = home.findByPrimaryKey(new Integer(schoolId));\n\t\t\tif (this.school != null) {\n\t\t\t\tProviderAccountingPropertiesHome h = (ProviderAccountingPropertiesHome) com.idega.data.IDOLookup.getHome(ProviderAccountingProperties.class);\n\t\t\t\tthis.properties = h.findByPrimaryKey(new Integer(schoolId)); \n\t\t\t}\n\t\t} catch (RemoteException e) {\n\t\t} catch (FinderException e) {}\n\t}\n\t\n\t/**\n\t * Returns the school object for this provider.\n\t */\n\tpublic School getSchool() {\n\t\treturn this.school;\n\t}\n\t\n\t/**\n\t * Returns the accounting properties for this provider.\n\t */\n\tpublic ProviderAccountingProperties getAccountingProperties() {\n\t\treturn this.properties;\n\t}\n\t\n\tpublic int getProviderTypeId() {\n\t\tif (this.properties != null) {\n\t\t\treturn this.properties.getProviderTypeId();\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic ProviderType getProviderType() {\n\t\tif (this.properties != null) {\n\t\t\treturn this.properties.getProviderType();\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic String getStatisticsType() {\n\t\tif (this.properties != null) {\n\t\t\tString s = this.properties.getStatisticsType();\n\t\t\tif (s != null) {\n\t\t\t\treturn s;\n\t\t\t} else {\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t} else {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\n\tpublic boolean getPaymentByInvoice() {\n\t\tif (this.properties != null) {\n\t\t\treturn this.properties.getPaymentByInvoice();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic boolean getStateSubsidyGrant() {\n\t\tif (this.properties != null) {\n\t\t\treturn this.properties.getStateSubsidyGrant();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic String getPostgiro() {\n\t\tif (this.properties != null) {\n\t\t\treturn this.properties.getPostgiro();\n\t\t} else {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\n\tpublic String getBankgiro() {\n\t\tif (this.properties != null) {\n\t\t\treturn this.properties.getBankgiro();\n\t\t} else {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\t\n\tpublic String getGiroText() {\n\t\tif (this.properties != null) {\n\t\t\treturn this.properties.getGiroText();\n\t\t} else {\n\t\t\treturn \"\";\n\t\t}\t\t\n\t}\n\n\tpublic String getOwnPosting() {\n\t\tif (this.properties != null) {\n\t\t\treturn this.properties.getOwnPosting();\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic String getDoublePosting() {\n\t\tif (this.properties != null) {\n\t\t\treturn this.properties.getDoublePosting();\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\tpublic String toString(){\n\t\treturn getSchool().getName();\n\t}\n}"
] | import java.rmi.RemoteException;
import java.sql.Date;
import java.util.Collection;
import java.util.Iterator;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import se.idega.idegaweb.commune.accounting.export.data.ExportDataMapping;
import se.idega.idegaweb.commune.accounting.posting.data.PostingField;
import se.idega.idegaweb.commune.accounting.posting.data.PostingFieldHome;
import se.idega.idegaweb.commune.accounting.posting.data.PostingParameters;
import se.idega.idegaweb.commune.accounting.posting.data.PostingParametersHome;
import se.idega.idegaweb.commune.accounting.posting.data.PostingString;
import se.idega.idegaweb.commune.accounting.posting.data.PostingStringHome;
import se.idega.idegaweb.commune.accounting.regulations.data.ActivityType;
import se.idega.idegaweb.commune.accounting.regulations.data.ActivityTypeHome;
import se.idega.idegaweb.commune.accounting.regulations.data.CommuneBelongingType;
import se.idega.idegaweb.commune.accounting.regulations.data.CommuneBelongingTypeHome;
import se.idega.idegaweb.commune.accounting.school.data.Provider;
import com.idega.block.school.data.SchoolCategory;
import com.idega.block.school.data.SchoolType;
import com.idega.core.location.data.Commune;
import com.idega.data.IDOLookup;
import com.idega.util.IWTimestamp; | }
/**
* Validates that all the required fields have been set. If they are not
* set, a MissingMandatoryFieldException will be thrown.
*
* @param postingString
* @param date
* @throws MissingMandatoryFieldException
* @throws PostingException
*
* @author Joakim
*/
public void validateString(String postingString, Date date) throws PostingException {
int fieldLength, readPointer = 0;
try {
PostingStringHome ksHome = getPostingStringHome();
PostingFieldHome kfHome = getPostingFieldHome();
PostingString posting = ksHome.findPostingStringByDate(date);
Collection list = kfHome.findAllFieldsByPostingString(Integer.parseInt(posting.getPrimaryKey().toString()));
Iterator iter = list.iterator();
// Go through all fields
while (iter.hasNext()) {
PostingField field = (PostingField) iter.next();
fieldLength = field.getLen();
if (field.getIsMandatory()) {
// Check if mandatory field is empty
if (trim(postingString.substring(readPointer, readPointer + fieldLength), field).length() == 0) {
throw new MissingMandatoryFieldException(field.getFieldTitle());
}
}
readPointer += fieldLength;
}
}
catch (Exception e) {
System.out.println("Error: The postingt definition and the posting strings did not match.");
System.out.println("First posting string: '" + postingString + "'");
System.out.println("Date for posting rule: " + date.toString());
e.printStackTrace();
throw new PostingException("posting.exception", "malformated posting field encountered");
}
}
/**
* extractField Retrieves portion of a PostingString
*
* @param ps
* posting string
* @param readPointer
* index in string
* @param postingField
* The field itself
* @return an extracted part of the ps string
*/
public String extractField(String ps, int readPointer, int fieldLength, PostingField field) {
if (ps == null) {
return "";
}
try {
return trim(ps.substring(readPointer, readPointer + fieldLength), field);
}
catch (StringIndexOutOfBoundsException e) {
return "";
}
}
/**
* Hämta konteringsinformation Retrieves accounting default information.
* Matching on the main rules like Verksamhet, Regspectyp, Bolagstyp,
* kommuntill.hörighet is done via primary keys
*
* @param date
* Date when the transaction took place
*
* @param act_id
* Verksamhet. Related to:
* @see com.idega.block.school.data.SchoolType#
*
* @param reg_id
* Reg.Spec type. Related to:
* @see se.idega.idegaweb.commune.accounting.regulations.data.RegulationSpecType#
*
* @param com_id
* Company type
* @see se.idega.idegaweb.commune.accounting.regulations.data.CompanyType#
* This bean will be moved later to the Idega
* school:com.idega.block.school.data
*
* @param com_bel_id
* Commmune belonging type
* @see se.idega.idegaweb.commune.accounting.regulations.data.CommuneBelongingType#
* This will probably be moved into the accounting.data
*
* make parameter 0 for macthing of all
*
* @return PostingParameters
* @see se.idega.idegaweb.commune.accounting.posting.data.PostingParameters#
* @throws PostingParametersException
*
* @author Kjell
*/
public PostingParameters getPostingParameter(Date date, int act_id, int reg_id, String com_id, int com_bel_id)
throws PostingParametersException {
return getPostingParameter(date, act_id, reg_id, com_id, com_bel_id, 0, 0);
}
public PostingParameters getPostingParameter(Date date, int act_id, int reg_id, String com_id, int com_bel_id,
int schoolYear1_id, int schoolYear2_id) throws PostingParametersException {
logDebug("date: " + date);
logDebug("act_id: " + act_id);
logDebug("reg_id: " + reg_id);
logDebug("com_id: " + com_id);
logDebug("com_bel_id: " + com_bel_id);
logDebug("schoolYear1_id: " + schoolYear1_id);
logDebug("schoolYear2_id: " + schoolYear2_id);
PostingParameters pp = null;
try { | PostingParametersHome home = getPostingParametersHome(); | 2 |
excelsior-oss/excelsior-jet-api | src/main/java/com/excelsiorjet/api/tasks/PackagerArgsGenerator.java | [
"public class ExcelsiorJet {\n\n private final JetHome jetHome;\n private final Log logger;\n\n private JetEdition edition;\n private OS targetOS;\n private CpuArch targetCpu;\n\n public ExcelsiorJet(JetHome jetHome, Log logger) throws JetHomeException {\n this.jetHome = jetHome;\n this.logger = logger;\n detectEditionAndTargetPlatform();\n }\n\n public ExcelsiorJet(String jetHome) throws JetHomeException {\n this(Utils.isEmpty(jetHome) ? new JetHome() : new JetHome(jetHome), Log.logger);\n }\n\n /**\n * Invokes the {@code jc} command line tool in the given {@code workingDirectory} with a logger specified at construction time, passing\n * {@code args} to it.\n *\n * @param workingDirectory working directory for {@code jc}. May be null, in which case the working directory of the current process is used.\n * @param args command line arguments that will be passed to {@code jc}.\n */\n public int compile(File workingDirectory, String... args) throws CmdLineToolException {\n return new JetCompiler(jetHome, args)\n .workingDirectory(workingDirectory)\n .withLog(logger)\n .execute();\n }\n\n /**\n * Invokes the {@code xpack} command line tool in the given {@code workingDirectory} with a logger specified at construction time, passing\n * {@code args} to it.\n *\n * @param workingDirectory working directory for {@code xpack}. May be null, in which case the working directory of the current process is used.\n * @param args command line arguments that will be passed to {@code xpack}.\n */\n public int pack(File workingDirectory, String... args) throws CmdLineToolException {\n return new JetPackager(jetHome, args)\n .workingDirectory(workingDirectory)\n .withLog(logger)\n .execute();\n }\n\n /**\n * Invokes the {@code xjava} command line tool in the given {@code workingDirectory} with a logger specified at construction time, passing\n * {@code args} to it.\n *\n * @param workingDirectory working directory for {@code xjava}. May be null, in which case the working directory of the current process is used.\n * @param args command line arguments that will be passed to {@code xjava}.\n */\n public int testRun(File workingDirectory, String... args) throws CmdLineToolException {\n return testRun(workingDirectory, logger, false, args);\n }\n\n /**\n * Invokes the {@code xjava} command line tool in the given {@code workingDirectory} with the specified {@code logger}, passing\n * {@code args} to it.\n *\n * @param workingDirectory working directory for {@code xjava}. May be null, in this case current process's working directory is used.\n * @param logger logger to which the output of {@code xjava} should be redirected.\n * @param errToOut specifies whether the stderr of xjava should be redirected with info level.\n * @param args command line arguments that will be passed to {@code xjava}.\n */\n public int testRun(File workingDirectory, Log logger, boolean errToOut, String... args) throws CmdLineToolException {\n return new XJava(jetHome, args)\n .workingDirectory(workingDirectory)\n .withLog(logger, errToOut)\n .execute();\n }\n\n private String obtainVersionString() throws JetHomeException {\n try {\n String[] result = {null};\n CmdLineTool jetCompiler = new JetCompiler(this.jetHome).withLog(new StdOutLog() {\n public void info(String info) {\n if (result[0] == null) {\n if (info.contains(\"Excelsior JET \")) {\n result[0] = info;\n }\n }\n }\n\n });\n if ((jetCompiler.execute() != 0) || result[0] == null) {\n throw new JetHomeException(Txt.s(\"JetHome.UnableToDetectEdition.Error\"));\n }\n return result[0];\n } catch (CmdLineToolException e) {\n throw new JetHomeException(e.getMessage());\n }\n }\n\n private void detectEditionAndTargetPlatform() throws JetHomeException {\n if (edition == null) {\n String version = obtainVersionString();\n edition = JetEdition.retrieveEdition(version);\n if (edition == null) {\n throw new JetHomeException(Txt.s(\"JetHome.UnableToDetectEdition.Error\"));\n }\n\n targetOS = Host.getOS();\n\n if (version.contains(\"64-bit\")) {\n targetCpu = CpuArch.AMD64;\n } else if (version.contains(\"ARM\")) {\n targetCpu = CpuArch.ARM32;\n //currently Excelsior JET supports only ARM Linux\n targetOS = OS.LINUX;\n } else {\n targetCpu = CpuArch.X86;\n }\n }\n }\n\n public JetEdition getEdition() {\n return edition;\n }\n\n public OS getTargetOS() {\n return targetOS;\n }\n\n private boolean isX86() {\n return targetCpu == CpuArch.X86;\n }\n\n public boolean isGlobalOptimizerSupported() {\n return (isX86() || since12_0()) && (getEdition() != JetEdition.STANDARD);\n }\n\n public boolean isSlimDownSupported() {\n return isGlobalOptimizerSupported() && isX86();\n }\n\n public boolean isUsageListGenerationSupported() {\n return isX86() || since12_0();\n }\n\n public boolean isStartupProfileGenerationSupported() {\n return getEdition() != JetEdition.STANDARD;\n }\n\n private boolean isFullFeaturedEdition() {\n return (edition == JetEdition.EVALUATION) || (edition == JetEdition.ENTERPRISE);\n }\n\n private boolean isEmbedded() {\n return (edition == JetEdition.EMBEDDED) || (edition == JetEdition.EMBEDDED_EVALUATION);\n }\n\n public boolean isTomcatSupported() {\n return isFullFeaturedEdition() ||\n since11_3() && isEmbedded();\n }\n\n public boolean isSpringBootSupported() {\n return since15_3() &&\n (isFullFeaturedEdition() || isEmbedded());\n }\n\n public boolean isPDBConfigurationSupported() {\n return since15_0();\n }\n\n public boolean isSmartSupported() {\n return since15_0() && !isX86();\n }\n public boolean since11_3() {\n return jetHome.getJetVersion() >= 1130;\n }\n\n public boolean since12_0() {\n return jetHome.getJetVersion() >= 1200;\n }\n\n public boolean since15_0() {\n return jetHome.getJetVersion() >= 1500;\n }\n\n public boolean since15_3() {\n return jetHome.getJetVersion() >= 1530;\n }\n\n public boolean isCrossCompilation() {\n //currently only ARM32 is supported in cross compilation mode\n return targetCpu == CpuArch.ARM32;\n }\n\n public boolean isTestRunSupported() {\n return !isCrossCompilation();\n }\n\n public boolean isExcelsiorInstallerSupported() {\n return !getTargetOS().isOSX() && !(isEmbedded());\n }\n\n public boolean isAdvancedExcelsiorInstallerFeaturesSupported() {\n return isExcelsiorInstallerSupported() && since11_3() && (edition != JetEdition.STANDARD);\n }\n\n public boolean isStartupAcceleratorSupported() {\n return !getTargetOS().isOSX() && !isCrossCompilation() && (edition != JetEdition.STANDARD);\n }\n\n public boolean isWindowsServicesSupported() {\n return targetOS.isWindows() && (edition != JetEdition.STANDARD);\n }\n\n public boolean isWindowsServicesInExcelsiorInstallerSupported() {\n return isWindowsServicesSupported() && isExcelsiorInstallerSupported() && since11_3();\n }\n\n public boolean isCompactProfilesSupported() {\n return since11_3() && (edition != JetEdition.STANDARD);\n }\n\n public boolean isMultiAppSupported() {\n return edition != JetEdition.STANDARD;\n }\n\n public boolean isTrialSupported() {\n return edition != JetEdition.STANDARD;\n }\n\n public boolean isDataProtectionSupported() {\n return edition != JetEdition.STANDARD;\n }\n\n public boolean isDiskFootprintReductionSupported() {\n return since11_3() && isGlobalOptimizerSupported();\n }\n\n public boolean isHighDiskFootprintReductionSupported() {\n return isDiskFootprintReductionSupported() && isX86();\n }\n\n public boolean isWindowsVersionInfoSupported() {\n return targetOS.isWindows() && (edition != JetEdition.STANDARD);\n }\n\n public boolean isRuntimeSupported(RuntimeFlavorType flavor) {\n switch (flavor) {\n case SERVER:\n return isFullFeaturedEdition() ||\n (since11_3() && isEmbedded());\n case DESKTOP:\n return edition != JetEdition.STANDARD;\n case CLASSIC:\n return true;\n default:\n throw new AssertionError(\"Unknown runtime flavor:\" + flavor);\n }\n }\n\n public boolean isChangeRTLocationAvailable() {\n return since11_3();\n }\n\n public boolean isPGOSupported() {\n return since12_0() && !isX86() && (edition != JetEdition.STANDARD) && (edition != JetEdition.PROFESSIONAL);\n }\n\n /**\n * @return home directory of this Excelsior JET instance\n */\n public String getJetHome() {\n return jetHome.getJetHome();\n }\n\n}",
"public class Host {\n\n private static final OS hostOS;\n\n static {\n //detect Host OS\n String osName = System.getProperty(\"os.name\");\n if (osName.contains(\"Windows\")) {\n hostOS = OS.WINDOWS;\n } else if (osName.contains(\"Linux\")) {\n hostOS = OS.LINUX;\n } else if (osName.contains(\"OS X\")) {\n hostOS = OS.OSX;\n } else {\n throw new AssertionError(\"Unknown OS: \" + osName);\n }\n }\n\n public static boolean isWindows() {\n return hostOS.isWindows();\n }\n\n public static boolean isLinux() {\n return hostOS.isLinux();\n }\n\n public static boolean isOSX() {\n return hostOS.isOSX();\n }\n\n public static boolean isUnix() {\n return hostOS.isUnix();\n }\n\n public static String mangleExeName(String exe) {\n return hostOS.mangleExeName(exe);\n }\n\n public static OS getOS() {\n return hostOS;\n }\n}",
"public enum ApplicationType {\n\n /**\n * Plain Java application that runs standalone.\n */\n PLAIN,\n\n /**\n * Spring Boot application that runs as Spring Boot executable jar.\n */\n SPRING_BOOT,\n\n /**\n * Servlet-based Java application that runs within the Tomcat servlet container.\n */\n TOMCAT,\n\n /**\n * Dynamic library callable from a non-Java environment.\n */\n DYNAMIC_LIBRARY,\n\n /**\n * Windows service (Windows only).\n */\n WINDOWS_SERVICE\n ;\n\n public String toString() {\n return Utils.enumConstantNameToParameter(name());\n }\n\n public static ApplicationType validate(String appType) throws JetTaskFailureException {\n try {\n return ApplicationType.valueOf(Utils.parameterToEnumConstantName(appType));\n } catch (Exception e) {\n throw new JetTaskFailureException(s(\"JetApi.UnknownAppType.Failure\", appType));\n }\n }\n}",
"public class PackageFile {\n\n /**\n * Package file type. Valid values are: {@code auto} (default), {@code file}, {@code folder}.\n */\n public String type = PackageFileType.AUTO.toString();\n\n /**\n * Path to the file on the host system.\n */\n public File path;\n\n /**\n * Location of the file in the resulting package.\n * If not set, the file will be added to the root installation directory.\n */\n public String packagePath;\n\n public PackageFile() {\n }\n\n public PackageFile(PackageFileType type) {\n this.type = type.toString();\n }\n\n public PackageFile(PackageFileType type, File path) {\n this.type = type.toString();\n this.path = path;\n }\n\n public PackageFile(PackageFileType type, File path, String packagePath) {\n this.type = type.toString();\n this.path = path;\n this.packagePath = packagePath;\n }\n\n public PackageFile(File path, String packagePath) {\n this.path = path;\n this.packagePath = packagePath;\n }\n\n public boolean isDefined() {\n return (path != null) || (packagePath != null);\n }\n\n /**\n * @return location of this file in the package including file name, or empty string if the file is not {@link #isDefined()}}\n */\n public String getLocationInPackage() {\n if (!isDefined()) {\n return \"\";\n } else if (path != null) {\n assert packagePath != null: \"validate() must be called before\";\n return packagePath.endsWith(\"/\") ? packagePath + path.getName() : packagePath + \"/\" + path.getName();\n } else {\n return packagePath;\n }\n }\n\n public void validate(String notExistErrorKey, String errorParam) throws JetTaskFailureException {\n if (!isDefined())\n return;\n\n if (path != null) {\n if (!path.exists()) {\n throw new JetTaskFailureException(s(notExistErrorKey, path.getAbsolutePath(), errorParam));\n }\n switch (PackageFileType.validate(type)) {\n case FILE:\n if (!path.isFile()) {\n throw new JetTaskFailureException(s(\"JetApi.PackageFileNotFile.Error\", path.getAbsolutePath()));\n }\n break;\n case FOLDER:\n if (!path.isDirectory()) {\n throw new JetTaskFailureException(s(\"JetApi.PackageFileNotFolder.Error\", path.getAbsolutePath()));\n }\n break;\n case AUTO:\n break;\n default:\n throw new AssertionError(\"Unknown file type: \" + type);\n }\n\n }\n\n if (packagePath == null) {\n packagePath = \"/\";\n }\n }\n\n public void validate(String notExistErrorKey) throws JetTaskFailureException {\n validate(notExistErrorKey, null);\n }\n}",
"public class RuntimeConfig {\n\n /**\n * Excelsior JET Runtime flavor.\n * <p>\n * Excelsior JET comes with multiple implementations of the runtime system,\n * optimized for different hardware configurations and application types.\n * For details, refer to the Excelsior JET User's Guide, Chapter \"Application\n * Considerations\", section \"Runtime Selection\".\n * </p>\n * <p>\n * Available runtime flavors: {@code desktop}, {@code server}, {@code classic}\n * </p>\n */\n public String flavor;\n\n /**\n * Location of Excelsior JET runtime files in the installation package.\n * By default, Excelsior JET places its runtime files required for the \n * generated executable to work in a folder named {@code \"rt\"} located next to that executable.\n * You may change that default location with this parameter.\n * <p>\n * This functionality is only available in Excelsior JET 11.3 and above.\n * </p>\n */\n public String location;\n\n /**\n * Optional JET Runtime components that have to be added to the package.\n * By default, only the {@code jce} component (Java Crypto Extension) is added.\n * You may pass a special value {@code all} to include all available optional components at once\n * or {@code none} to not include any of them.\n * <p>\n * Available optional components:\n * {@code runtime_utilities}, {@code fonts}, {@code awt_natives}, {@code api_classes}, {@code jce},\n * {@code accessibility}, {@code javafx}, {@code javafx-webkit}, {@code nashorn}, {@code cldr}\n * </p>\n */\n public String[] components;\n\n /**\n * Locales and charsets that have to be included in the package.\n * By default only {@code European} locales are added.\n * You may pass a special value {@code all} to include all available locales at once\n * or {@code none} to not include any additional locales.\n * <p>\n * Available locales and charsets:\n * {@code European}, {@code Indonesian}, {@code Malay}, {@code Hebrew}, {@code Arabic},\n * {@code Chinese}, {@code Japanese}, {@code Korean}, {@code Thai}, {@code Vietnamese}, {@code Hindi},\n * {@code Extended_Chinese}, {@code Extended_Japanese}, {@code Extended_Korean}, {@code Extended_Thai},\n * {@code Extended_IBM}, {@code Extended_Macintosh}, {@code Latin_3}\n * </p>\n */\n public String[] locales;\n\n /**\n * Java SE API subset to be included in the package.\n * Java SE 8 defines three subsets of the standard Platform API called compact profiles.\n * Excelsior JET enables you to deploy your application with one of those subsets.\n * You may set this parameter to specify a particular profile.\n * Valid values are: {@code auto} (default), {@code compact1}, {@code compact2}, {@code compact3}, {@code full}\n * <p>\n * {@code auto} value (default) forces Excelsior JET to detect which parts of the Java SE Platform API\n * are referenced by the application and select the smallest compact profile that includes them all,\n * or the entire Platform API if there is no such profile.\n * </p>\n * This functionality is available for Excelsior JET 11.3 and above.\n */\n public String profile;\n\n /**\n * Disk footprint reduction mode.\n * Excelsior JET can reduce the disk footprint of the application by including the supposedly\n * unused Java SE API classes in the resulting package in a compressed form.\n * Valid values are: {@code none}, {@code medium} (default), {@code high-memory}, {@code high-disk}.\n * <p>\n * This feature is only available if {@link JetProject#globalOptimizer} is enabled.\n * In this mode, the Java SE classes that were not compiled into the resulting executable are placed\n * into the resulting package in bytecode form, possibly compressed depending on the mode:\n * </p>\n * <dl>\n * <dt>none</dt>\n * <dd>Disable compression</dd>\n * <dt>medium</dt>\n * <dd>Use a simple compression algorithm that has minimal run time overheads and permits\n * selective decompression.</dd>\n * <dt>high-memory</dt>\n * <dd>(32-bit only) Compress all unused Java SE API classes as a whole. This results in more significant disk\n * footprint reduction compared to the {@code medium} compression. However, if one of the compressed classes\n * is needed at run time, the entire bundle must be decompressed to retrieve it.\n * In the {@code high-memory} reduction mode the bundle is decompressed\n * onto the heap and can be garbage collected later.</dd>\n * <dt>high-disk</dt>\n * <dd>(32-bit only) Same as {@code high-memory}, but decompress to the temp directory.</dd>\n * </dl>\n */\n public String diskFootprintReduction;\n\n /**\n * (32-bit only) Java Runtime Slim-Down configuration parameters.\n *\n * @see SlimDownConfig#detachedBaseURL\n * @see SlimDownConfig#detachComponents\n * @see SlimDownConfig#detachedPackage\n */\n public SlimDownConfig slimDown;\n\n public void fillDefaults(JetProject jetProject, ExcelsiorJet excelsiorJet) throws JetTaskFailureException {\n\n if (flavor != null) {\n RuntimeFlavorType flavorType = RuntimeFlavorType.validate(flavor);\n if (!excelsiorJet.isRuntimeSupported(flavorType)) {\n throw new JetTaskFailureException(s(\"JetApi.RuntimeKindNotSupported.Failure\", flavor));\n }\n }\n\n if (location != null) {\n if (!excelsiorJet.isChangeRTLocationAvailable()) {\n throw new JetTaskFailureException(s(\"JetApi.RuntimeLocationNotAvailable.Failure\", flavor));\n }\n }\n\n if (profile == null) {\n profile = CompactProfileType.AUTO.toString();\n } else {\n CompactProfileType compactProfile = CompactProfileType.validate(profile);\n if (!excelsiorJet.isCompactProfilesSupported()) {\n switch (compactProfile) {\n case COMPACT1: case COMPACT2: case COMPACT3:\n throw new JetTaskFailureException(s(\"JetApi.CompactProfilesNotSupported.Failure\", profile));\n case AUTO: case FULL:\n break;\n default: throw new AssertionError(\"Unknown compact profile: \" + compactProfile);\n }\n }\n }\n\n if ((slimDown != null) && !slimDown.isDefined()) {\n slimDown = null;\n }\n\n if (slimDown != null) {\n if (!excelsiorJet.isSlimDownSupported()) {\n logger.warn(s(\"JetApi.NoSlimDown.Warning\"));\n slimDown = null;\n } else {\n if (slimDown.detachedBaseURL == null) {\n throw new JetTaskFailureException(s(\"JetApi.DetachedBaseURLMandatory.Failure\"));\n }\n\n if (slimDown.detachedPackage == null) {\n slimDown.detachedPackage = jetProject.artifactName() + \".pkl\";\n }\n\n jetProject.globalOptimizer(true);\n }\n\n }\n\n if (diskFootprintReduction != null) {\n DiskFootprintReductionType dfrType = DiskFootprintReductionType.validate(diskFootprintReduction);\n if (!excelsiorJet.isDiskFootprintReductionSupported()) {\n logger.warn(s(\"JetApi.NoDiskFootprintReduction.Warning\"));\n diskFootprintReduction = null;\n } else if (!jetProject.globalOptimizer()) {\n logger.warn(s(\"JetApi.DiskFootprintReductionForGlobalOnly.Warning\"));\n diskFootprintReduction = null;\n } else if (!excelsiorJet.isHighDiskFootprintReductionSupported() &&\n ((dfrType == DiskFootprintReductionType.HIGH_DISK) ||\n (dfrType == DiskFootprintReductionType.HIGH_MEMORY))) {\n logger.warn(s(\"JetApi.NoHighDiskFootprintReduction.Warning\", diskFootprintReduction));\n diskFootprintReduction = DiskFootprintReductionType.MEDIUM.toString();\n }\n }\n\n }\n}",
"public class WindowsServiceConfig {\n\n /**\n * The <em>system</em> name of the service,\n * used to install, remove and otherwise manage the service.\n * It can also be used to recognize messages from this service in the system event log.\n * The system name is set during the creation of the service executable.\n * It is displayed for reference so you cannot edit it.\n * <p>\n * By default, {@link JetProject#outputName} is used for the name.\n * </p>\n */\n public String name;\n\n /**\n * The <em>descriptive</em> name of the service.\n * It is shown in the Event Viewer system tool and in the Services applet of the Windows Control Panel.\n * <p>\n * By default, the value of {@link #name} is re-used as the display name.\n * </p>\n */\n public String displayName;\n\n /**\n * The user description of the service. It must not exceed 1,000 characters.\n */\n public String description;\n\n /**\n * The command-line arguments passed to the service upon startup.\n */\n public String[] arguments;\n\n /**\n * Specifies the account to be used by the service. Valid values are: \"local-system-account\" (default), \"user-account\".\n * <p>\n * {@code local-system-account} - run the service under the built-in system account.\n * </p>\n * <p>\n * {@code user-account} - run the service under a user account.\n * When installing the package, the user will be prompted for an account name\n * and password necessary to run the service.\n * </p>\n */\n public String logOnType;\n\n /**\n * Specifies if the service needs to interact with the system desktop,\n * e.g. open/close other windows, etc. This option is only available if {@link #logOnType}\n * is set to {@code local-system-account}.\n */\n public boolean allowDesktopInteraction;\n\n /**\n * Specify how to start the service. Valid values are \"automatic\" (default), \"manual\", and \"disabled\".\n * <p>\n * {@code automatic} - specifies that the service should start automatically when the system starts.\n * </p>\n * <p>\n * {@code manual} - specifies that a user or a dependent service can start the service.\n * Services with Manual startup type do not start automatically when the system starts.\n * </p>\n * <p>\n * {@code disabled} - prevents the service from being started by the system, a user, or any dependent service.\n * </p>\n */\n public String startupType;\n\n /**\n * Specifies if the service should be started immediately after installation.\n *\n * Available only for {@link PackagingType#EXCELSIOR_INSTALLER} packaging type.\n *\n */\n public boolean startServiceAfterInstall = true;\n\n /**\n * List of other service names on which the service depends.\n */\n public String[] dependencies;\n\n public void fillDefaults(JetProject jetProject) throws JetTaskFailureException {\n if (Utils.isEmpty(name)) {\n name = jetProject.outputName();\n }\n\n if (Utils.isEmpty(displayName)) {\n displayName = jetProject.appType() == ApplicationType.TOMCAT ? \"Apache Tomcat\": name;\n }\n\n if (description == null) {\n description = jetProject.appType() == ApplicationType.TOMCAT ?\n \"Apache Tomcat Server - http://tomcat.apache.org/\": displayName;\n }\n\n if (logOnType == null) {\n logOnType = LogOnType.LOCAL_SYSTEM_ACCOUNT.toString();\n } else {\n LogOnType.validate(logOnType);\n }\n if (startupType == null) {\n startupType = StartupType.AUTOMATIC.toString();\n } else {\n StartupType.validate(startupType);\n }\n\n if (allowDesktopInteraction && (LogOnType.fromString(logOnType) != LogOnType.LOCAL_SYSTEM_ACCOUNT)) {\n throw new JetTaskFailureException(s(\"JetApi.IntractiveSeviceForNonLocalSystem.Failure\", startupType));\n }\n }\n\n public LogOnType getLogOnType() {\n return LogOnType.fromString(logOnType);\n }\n\n public StartupType getStartupType() {\n return StartupType.fromString(startupType);\n }\n}",
"public class Utils {\n\n public static void cleanDirectory(File f) throws IOException {\n Files.walkFileTree(f.toPath(), new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n private void deleteFile(File f) throws IOException {\n if (!f.delete()) {\n if (f.exists()) {\n throw new IOException(Txt.s(\"JetApi.UnableToDelete.Error\", f.getAbsolutePath()));\n }\n }\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n deleteFile(file.toFile());\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n if (file.toFile().exists()) {\n throw new IOException(Txt.s(\"JetApi.UnableToDelete.Error\", f.getAbsolutePath()));\n }\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n deleteFile(dir.toFile());\n return FileVisitResult.CONTINUE;\n }\n });\n }\n\n public static void cleanDirectorySilently(File f) {\n try {\n cleanDirectory(f);\n } catch (IOException ignore) {\n }\n }\n\n public static void copyFile(Path source, Path target) throws IOException {\n if (!target.toFile().exists()) {\n Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES);\n } else if (source.toFile().lastModified() != target.toFile().lastModified()) {\n //copy only files that were changed\n Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);\n }\n\n }\n\n public static void copyDirectory(Path source, Path target) throws IOException {\n Files.walkFileTree(source, new FileVisitor<Path>() {\n\n @Override\n public FileVisitResult preVisitDirectory(Path subfolder, BasicFileAttributes attrs) throws IOException {\n Files.createDirectories(target.resolve(source.relativize(subfolder)));\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path sourceFile, BasicFileAttributes attrs) throws IOException {\n Path targetFile = target.resolve(source.relativize(sourceFile));\n copyFile(sourceFile, targetFile);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path sourceFile, IOException e) throws IOException {\n throw new IOException(Txt.s(\"Utils.CannotCopyFile.Error\", sourceFile.toString(), e.getMessage()), e);\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path source, IOException ioe) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n });\n }\n\n public static boolean isEmpty(String s) {\n return (s == null) || s.isEmpty();\n }\n\n public static boolean isEmpty(String[] strings) {\n return (strings == null) || (strings.length == 0);\n }\n\n public static String randomAlphanumeric(int count) {\n char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};\n StringBuilder res = new StringBuilder();\n for (int i = 0; i < count; i++) {\n res.append(chars[(int) (chars.length * Math.random())]);\n }\n return res.toString();\n }\n\n public static void copy(InputStream in, OutputStream out) throws IOException {\n byte[] buffer = new byte[1024 * 1024];\n int len;\n while ((len = in.read(buffer)) > 0) {\n out.write(buffer, 0, len);\n }\n }\n\n public static void mkdir(File dir) throws JetTaskFailureException {\n if (!dir.exists() && !dir.mkdirs()) {\n if (!dir.exists()) {\n throw new JetTaskFailureException(s(\"JetApi.DirCreate.Error\", dir.getAbsolutePath()));\n }\n logger.warn(s(\"JetApi.DirCreate.Warning\", dir.getAbsolutePath()));\n }\n }\n\n @FunctionalInterface\n private interface CreateArchiveEntry {\n ArchiveEntry createEntry(String name, long size, int mode);\n }\n\n private static ArchiveEntry createZipEntry(String name, long size, int mode) {\n ZipArchiveEntry entry = new ZipArchiveEntry(name);\n if (Host.isUnix()) {\n entry.setUnixMode(mode);\n }\n return entry;\n }\n\n private static ArchiveEntry createTarEntry(String name, long size, int mode) {\n TarArchiveEntry entry = new TarArchiveEntry(name);\n entry.setSize(size);\n if (Host.isUnix()) {\n entry.setMode(mode);\n }\n return entry;\n }\n\n private static void compressDirectoryToArchive(String rootDir, String sourceDir, ArchiveOutputStream out, CreateArchiveEntry cae) throws IOException {\n File[] files = new File(sourceDir).listFiles();\n assert files != null;\n for (File file : files) {\n if (file.isDirectory()) {\n compressDirectoryToArchive(rootDir, sourceDir + File.separator + file.getName(), out, cae);\n } else {\n ArchiveEntry entry = cae.createEntry(\n file.getAbsolutePath().substring(rootDir.length() + 1),\n file.length(),\n file.canExecute() ? /*-rwxr-xr-x*/ 0100755 : /*-rw-r--r--*/ 0100644\n );\n out.putArchiveEntry(entry);\n try (InputStream in = new BufferedInputStream(new FileInputStream(sourceDir + File.separator + file.getName()))) {\n copy(in, out);\n }\n out.closeArchiveEntry();\n }\n }\n }\n\n public static void compressToZipFile(File sourceDir, File outputFile) throws IOException {\n try (ZipArchiveOutputStream zipFile = new ZipArchiveOutputStream(\n new BufferedOutputStream(new FileOutputStream(outputFile)))) {\n compressDirectoryToArchive(sourceDir.getAbsolutePath(), sourceDir.getAbsolutePath(), zipFile,\n Utils::createZipEntry);\n }\n }\n\n public static void compressToTarGzFile(File sourceDir, File outputFile) throws IOException {\n try (TarArchiveOutputStream tarFile = new TarArchiveOutputStream(new GzipCompressorOutputStream(\n new BufferedOutputStream(new FileOutputStream(outputFile))))) {\n compressDirectoryToArchive(sourceDir.getAbsolutePath(), sourceDir.getAbsolutePath(), tarFile,\n Utils::createTarEntry);\n }\n }\n\n public static void copyQuietly(Path source, Path target) {\n // We could just use Maven FileUtils.copyDirectory method but it copies a directory as a whole\n // while here we copy only those files that were changed from previous build.\n try {\n copyDirectory(source, target);\n } catch (IOException e) {\n logger.warn(s(\"TestRunTask.ErrorWhileCopying.Warning\", source.toString(), target.toString(), e.getMessage()), e);\n }\n }\n\n public static String parameterToEnumConstantName(String parameter) {\n return parameter.toUpperCase().replace('-', '_');\n }\n\n public static String enumConstantNameToParameter(String constantName) {\n return constantName.toLowerCase().replace('_', '-');\n }\n\n /**\n * Encloses string in double quotes (\") if it contains space.\n */\n public static String quoteCmdLineArgument(String arg) {\n return arg.contains(\" \") ? '\"' + arg + '\"' : arg;\n }\n\n /**\n * Splits a string containing value for {@link com.excelsiorjet.api.tasks.JetProject#runArgs},\n * where arguments are separated by commas and commas within an argument are escaped with '\\'.\n * <p>\n * For example, \"value1,value2.1\\, value2.2\"\n * is parsed into 2 arguments: [\"value1\", \"value2.1, value2.2\"]\n */\n public static String[] parseRunArgs(String runArgs) {\n List<String> res = new ArrayList<>();\n StringBuilder buff = new StringBuilder();\n for (int i = 0; i < runArgs.length(); i++) {\n char c = runArgs.charAt(i);\n if (c == ',') {\n if (i > 0 && runArgs.charAt(i - 1) == '\\\\') {\n // replace \"\\,\" with \",\"\n buff.setCharAt(buff.length() - 1, c);\n } else {\n // split args\n res.add(buff.toString());\n buff = new StringBuilder();\n }\n } else {\n buff.append(c);\n }\n }\n res.add(buff.toString());\n return res.toArray(new String[res.size()]);\n }\n\n public static String[] prepend(String firstElement, String[] remaining) {\n if (remaining == null) {\n return new String[]{firstElement};\n }\n ArrayList<String> res = new ArrayList<>();\n res.add(firstElement);\n res.addAll(Arrays.asList(remaining));\n return res.toArray(new String[remaining.length + 1]);\n }\n\n public static String getCanonicalPath(File path) {\n try {\n return path.getCanonicalPath();\n } catch (IOException e) {\n // getCanonicalPath throws IOException,\n // so just return absolute path in a very rare case of IOException as there is no other\n // appropriate way to handle this situation.\n return path.getAbsolutePath();\n }\n }\n\n /**\n * @return String in format \"([groupId],[artifactId],[version], [path])\" (all fields are optional)\n */\n public static String idStr(String groupId, String artifactId, String version, File path) {\n return Stream.of(groupId, artifactId, version, path == null? null: getCanonicalPath(path)).\n filter(item -> item != null).\n collect(Collectors.joining(\":\", \"(\", \")\"));\n }\n\n public static void linesToFile(List<String> lines, File file) throws FileNotFoundException {\n try (PrintWriter out = new PrintWriter(new OutputStreamWriter(\n new FileOutputStream(file)))) {\n lines.forEach(out::println);\n }\n }\n\n public static String deriveFourDigitVersion(String version) {\n String[] versions = version.split(\"\\\\.\");\n String[] finalVersions = new String[]{\"0\", \"0\", \"0\", \"0\"};\n for (int i = 0; i < Math.min(versions.length, 4); ++i) {\n try {\n finalVersions[i] = Integer.decode(versions[i]).toString();\n } catch (NumberFormatException e) {\n int minusPos = versions[i].indexOf('-');\n if (minusPos > 0) {\n String v = versions[i].substring(0, minusPos);\n try {\n finalVersions[i] = Integer.decode(v).toString();\n } catch (NumberFormatException ignore) {\n }\n }\n }\n }\n return String.join(\".\", (CharSequence[]) finalVersions);\n }\n\n public static File checkFileWithDefault(File file, File defaultFile, String notExistKey, String notExistParam) throws JetTaskFailureException {\n if (file == null) {\n if (defaultFile.exists()) {\n return defaultFile;\n }\n } else if (!file.exists()) {\n throw new JetTaskFailureException(s(notExistKey, file.getAbsolutePath(), notExistParam));\n }\n return file;\n }\n}",
"public static String s(String id, Object... params) {\n String str = null;\n if (altMessages != null) {\n str = altMessages.format(id, params);\n }\n if (str == null) {\n str = messages.format(id, params);\n }\n if (str != null) {\n return str;\n } else {\n if (log != null) {\n log.error(\"JET message file broken: key = \" + id);\n } else {\n throw new IllegalStateException(\"No log to issue error. JET message file broken: key = \" + id);\n }\n return id;\n }\n}"
] | import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static com.excelsiorjet.api.util.Txt.s;
import com.excelsiorjet.api.ExcelsiorJet;
import com.excelsiorjet.api.platform.Host;
import com.excelsiorjet.api.tasks.config.ApplicationType;
import com.excelsiorjet.api.tasks.config.excelsiorinstaller.*;
import com.excelsiorjet.api.tasks.config.packagefile.PackageFile;
import com.excelsiorjet.api.tasks.config.runtime.RuntimeConfig;
import com.excelsiorjet.api.tasks.config.windowsservice.WindowsServiceConfig;
import com.excelsiorjet.api.util.Utils; | argsToString(config.afterInstallRunnable.arguments)));
}
if (config.compressionLevel != null) {
xpackOptions.add(new XPackOption("-compression-level", config.compressionLevel));
}
if (config.installationDirectory.isDefined()) {
if (!Utils.isEmpty(config.installationDirectory.path)) {
xpackOptions.add(new XPackOption("-installation-directory", config.installationDirectory.path));
}
if (config.installationDirectory.type != null) {
xpackOptions.add(new XPackOption("-installation-directory-type", config.installationDirectory.type));
}
if (config.installationDirectory.fixed) {
xpackOptions.add(new XPackOption("-installation-directory-fixed"));
}
}
if (excelsiorJet.getTargetOS().isWindows()) {
//handle windows only parameters
xpackOptions.addAll(getWindowsOnlyExcelsiorInstallerOptions(config));
}
if (config.installCallback != null) {
xpackOptions.add(new XPackOption("-install-callback", config.installCallback.getAbsolutePath()));
}
if (config.uninstallCallback.isDefined()) {
if (config.uninstallCallback.path != null) {
xpackOptions.add(new XPackOption("-add-file",
config.uninstallCallback.path.getAbsolutePath(), config.uninstallCallback.packagePath));
}
xpackOptions.add(new XPackOption("-uninstall-callback", config.uninstallCallback.getLocationInPackage()));
}
if ((project.appType() == ApplicationType.TOMCAT) && project.tomcatConfiguration().allowUserToChangeTomcatPort) {
xpackOptions.add(new XPackOption("-allow-user-to-change-tomcat-port"));
}
xpackOptions.add(new XPackOption("-backend", "excelsior-installer"));
xpackOptions.add(new XPackOption("-company", project.vendor()));
xpackOptions.add(new XPackOption("-product", project.product()));
xpackOptions.add(new XPackOption("-version", project.version()));
xpackOptions.add(new XPackOption("-target", target.getAbsolutePath()));
return xpackOptions;
}
private ArrayList<XPackOption> getWindowsOnlyExcelsiorInstallerOptions(ExcelsiorInstallerConfig config) {
ArrayList<XPackOption> xpackOptions = new ArrayList<>();
if (config.registryKey != null) {
xpackOptions.add(new XPackOption("-registry-key", config.registryKey));
}
for (Shortcut shortcut: config.shortcuts) {
if (shortcut.icon.path != null) {
xpackOptions.add(new XPackOption("-add-file", shortcut.icon.path.getAbsolutePath(), shortcut.icon.packagePath));
}
xpackOptions.add(new XPackOption("-shortcut", argsValidForRsp(shortcut.arguments),
shortcut.location, shortcut.target, shortcut.name, shortcut.icon.getLocationInPackage(),
shortcut.workingDirectory, argsToString(shortcut.arguments)));
}
if (config.noDefaultPostInstallActions) {
xpackOptions.add(new XPackOption("-no-default-post-install-actions"));
}
for (PostInstallCheckbox postInstallCheckbox: config.postInstallCheckboxes) {
switch (postInstallCheckbox.type()) {
case RUN:
xpackOptions.add(new XPackOption("-post-install-checkbox-run",
argsValidForRsp(postInstallCheckbox.arguments),
postInstallCheckbox.target, postInstallCheckbox.workingDirectory,
argsToString(postInstallCheckbox.arguments),
postInstallCheckbox.checkedArg()));
break;
case OPEN:
xpackOptions.add(new XPackOption("-post-install-checkbox-open",
postInstallCheckbox.target, postInstallCheckbox.checkedArg()));
break;
case RESTART:
xpackOptions.add(new XPackOption("-post-install-checkbox-restart", postInstallCheckbox.checkedArg()));
break;
default:
throw new AssertionError("Unknown PostInstallCheckBox type: " + postInstallCheckbox.type);
}
}
for (FileAssociation fileAssociation: config.fileAssociations) {
if (fileAssociation.icon.path != null) {
xpackOptions.add(new XPackOption("-add-file", fileAssociation.icon.path.getAbsolutePath(), fileAssociation.icon.packagePath));
}
xpackOptions.add(new XPackOption("-file-association", argsValidForRsp(fileAssociation.arguments),
fileAssociation.extension, fileAssociation.target, fileAssociation.description,
fileAssociation.targetDescription,fileAssociation.icon.getLocationInPackage(),
argsToString(fileAssociation.arguments), fileAssociation.checked? "checked" : "unchecked"));
}
if (config.welcomeImage != null) {
xpackOptions.add(new XPackOption("-welcome-image", config.welcomeImage.getAbsolutePath()));
}
if (config.installerImage != null) {
xpackOptions.add(new XPackOption("-installer-image", config.installerImage.getAbsolutePath()));
}
if (config.uninstallerImage != null) {
xpackOptions.add(new XPackOption("-uninstaller-image", config.uninstallerImage.getAbsolutePath()));
}
return xpackOptions;
}
//Surprisingly Windows just removes empty argument from list of arguments if we do not pass "" instead.
private static String escapeEmptyArgForWindows(String arg) {
return arg.isEmpty() ? "\"\"" : arg;
}
private ArrayList<XPackOption> getWindowsServiceArgs() {
ArrayList<XPackOption> xpackOptions = new ArrayList<>();
String exeRelPath = project.exeRelativePath(excelsiorJet); | WindowsServiceConfig serviceConfig = project.windowsServiceConfiguration(); | 5 |
CodeAndMagic/android-deferred-object | core/src/test/java/org/codeandmagic/promise/tests/PipePromisesTests.java | [
"public class DeferredObject<Success> extends AbstractPromise<Success> {\n\n public static <S> DeferredObject<S> successful(S value) {\n final DeferredObject<S> deferredObject = new DeferredObject<S>();\n deferredObject.success(value);\n return deferredObject;\n }\n\n public static <S> DeferredObject<S> failed(Throwable value) {\n final DeferredObject<S> deferredObject = new DeferredObject<S>();\n deferredObject.failure(value);\n return deferredObject;\n }\n\n public static <T, S extends T> DeferredObject<T[]> merge(Class<T> clazz, Promise<S>... promises) {\n return new MergePromise<T, S>(clazz, 0, promises);\n }\n\n public static <T, S extends T> DeferredObject<T[]> merge(Class<T> clazz, int allowedFailures, Promise<S>... promises) {\n return new MergePromise<T, S>(clazz, allowedFailures, promises);\n }\n\n @Override\n public void success(Success resolved) {\n super.success(resolved);\n }\n\n @Override\n public void failure(Throwable throwable) {\n super.failure(throwable);\n }\n\n @Override\n public void progress(Float progress) {\n super.progress(progress);\n }\n\n public static class MergePromise<T, S extends T> extends DeferredObject<T[]> {\n\n private final Promise<S>[] mPromises;\n private final int mLength;\n private final int mAllowedFailures;\n\n private final Throwable[] mFailures;\n private final T[] mSuccesses;\n private int mCountCompleted = 0;\n private int mCountFailures = 0;\n\n\n private Callback<Throwable> newFailureCallback(final int index) {\n return new Callback<Throwable>() {\n @Override\n public void onCallback(Throwable result) {\n synchronized (MergePromise.this) {\n mFailures[index] = result;\n mCountCompleted++;\n mCountFailures++;\n MergePromise.this.progress((float) mCountCompleted);\n\n if (mCountFailures > mAllowedFailures) {\n MergePromise.this.failure(new MergeFailure(\"Failed MergePromise because more than '\"\n + mAllowedFailures + \"' promises have failed.\", mFailures));\n }\n }\n }\n };\n }\n\n private Callback<S> newSuccessCallback(final int index) {\n return new Callback<S>() {\n @Override\n public void onCallback(S result) {\n synchronized (MergePromise.this) {\n mSuccesses[index] = result;\n mCountCompleted++;\n MergePromise.this.progress((float) mCountCompleted);\n\n if (mCountCompleted == mLength) {\n MergePromise.this.success(mSuccesses);\n }\n }\n }\n };\n }\n\n public MergePromise(Class<T> clazz, int allowedFailures, Promise<S>... promises) {\n if (promises.length < 1) {\n throw new IllegalArgumentException(\"You need at least one promise.\");\n }\n\n mPromises = promises;\n mLength = promises.length;\n mAllowedFailures = allowedFailures < 0 ? promises.length : allowedFailures;\n\n mFailures = new Throwable[mLength];\n mSuccesses = (T[]) Array.newInstance(clazz, mLength);\n\n for (int i = 0; i < mLength; ++i) {\n final Promise<S> promise = promises[i];\n promise.onSuccess(newSuccessCallback(i));\n promise.onFailure(newFailureCallback(i));\n }\n }\n }\n}",
"public interface Pipe<T1, T2> {\n\n Promise<T2> transform(T1 value);\n}",
"public interface Promise<Success> extends Promise3<Success, Throwable, Float> {\n\n @Override\n public Promise<Success> onSuccess(Callback<Success> onSuccess);\n\n @Override\n public Promise<Success> onFailure(Callback<Throwable> onFailure);\n\n @Override\n public Promise<Success> onProgress(Callback<Float> onProgress);\n\n @Override\n public Promise<Success> onComplete(Callback<Either<Throwable, Success>> onComplete);\n\n @Override\n public <Success2> Promise<Success2> map(final Transformation<Success, Success2> transform);\n\n @Override\n public <Success2> Promise<Success2> flatMap(final Transformation<Success, Either<Throwable, Success2>> transform);\n\n @Override\n public Promise<Success> andThen(Callback<Success> onSuccess,\n Callback<Throwable> onFailure,\n Callback<Float> onProgress);\n\n @Override\n public Promise<Success> flatRecover(final Transformation<Throwable, Either<Throwable, Success>> transform);\n\n @Override\n public Promise<Success> recover(final Transformation<Throwable, Success> transform);\n\n\n public <Success2> Promise<Success2> pipe(final Pipe<Success, Success2> transform);\n\n public Promise<Success> recoverWith(final Pipe<Throwable, Success> transform);\n\n @Override\n public Promise<Success> runOnUiThread();\n\n /**\n * <b>IMPORTANT NOTE</b>\n * This method operates on the assumption that the Success of this Promise is an {@link java.util.Collection<T1>}.\n * If not, it will fail with a {@link ClassCastException}.\n * <p/>\n * This method creates a list of Promises by applying a {@link Pipe} to each\n * element in the {@link java.util.Collection<T1>}.\n * <p/>\n *\n * @param transform the {@link Transformation} to be applied to each element\n * @param <T1>\n * @param <T2>\n * @return\n */\n public <T1, T2> Promises<T2> split(Pipe<T1, T2> transform);\n}",
"public interface Pipe3<T1, T2, Failure> {\n\n Promise3<T2, Failure, Void> transform(T1 value);\n}",
"public class DeferredObject3<Success, Failure, Progress> extends AbstractPromise3<Success, Failure, Progress> {\n\n public static <S, F, P> DeferredObject3<S, F, P> successful(S value) {\n final DeferredObject3<S, F, P> deferredObject = new DeferredObject3<S, F, P>();\n deferredObject.success(value);\n return deferredObject;\n }\n\n public static <S, F, P> DeferredObject3<S, F, P> failed(F value) {\n final DeferredObject3<S, F, P> deferredObject = new DeferredObject3<S, F, P>();\n deferredObject.failure(value);\n return deferredObject;\n }\n\n @Override\n public final void progress(Progress progress) {\n super.progress(progress);\n }\n\n @Override\n public final void success(Success resolved) {\n super.success(resolved);\n }\n\n @Override\n public final void failure(Failure failure) {\n super.failure(failure);\n }\n}"
] | import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
import org.codeandmagic.promise.*;
import org.codeandmagic.promise.impl.DeferredObject;
import org.codeandmagic.promise.Pipe;
import org.codeandmagic.promise.Promise;
import org.codeandmagic.promise.Pipe3;
import org.codeandmagic.promise.impl.DeferredObject3;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static java.lang.System.currentTimeMillis; | /*
* Copyright (c) 2014 Cristian Vrabie, Evelina Vrabie.
*
* This file is part of android-promise.
* android-deferred-object is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License,or (at your option)
* any later version.
*
* android-promise is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with android-promise
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.codeandmagic.promise.tests;
/**
* Created by cristian on 11/02/2014.
*/
@RunWith(JUnit4.class)
public class PipePromisesTests {
public Promise<Integer> deferredInt(final int number) {
final DeferredObject<Integer> deferredObject = new DeferredObject<Integer>();
new Thread() {
@Override
public void run() {
try {
Thread.sleep(1000);
deferredObject.success(number);
} catch (InterruptedException e) {
deferredObject.failure(e);
}
}
}.start();
return deferredObject;
}
public Promise<Integer> deferredException() {
final DeferredObject<Integer> deferredObject = new DeferredObject<Integer>();
new Thread() {
@Override
public void run() {
try {
Thread.sleep(1000);
deferredObject.failure(new Exception("Failed!"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
return deferredObject;
}
@Test
public void testPipe() {
Callback<String> onSuccess = mock(Callback.class);
Callback<Throwable> onFailure = mock(Callback.class);
| DeferredObject3.<Integer, Throwable, Void>successful(3).pipe(new Pipe3<Integer, String, Throwable>() { | 4 |
turn/camino | src/main/java/com/turn/camino/render/functions/TimeFunctions.java | [
"public interface Context {\n\n\t/**\n\t * Get system environment\n\t *\n\t * @return system environment\n\t */\n\tEnv getEnv();\n\n\t/**\n\t * Creates child context\n\t *\n\t * @return new context\n\t */\n\tContext createChild();\n\n\t/**\n\t * Gets parent context\n\t *\n\t * Returns a parent context, or null if current context is global\n\t *\n\t * @return parent context\n\t */\n\tContext getParent();\n\n\t/**\n\t * Gets global context\n\t *\n\t * Returns the global (ancestral) context\n\t *\n\t * @return global context\n\t */\n\tContext getGlobal();\n\n\t/**\n\t * Puts name and value of property into the current context\n\t *\n\t * @param name name of property\n\t * @param value value of property\n\t */\n\tvoid setProperty(String name, Object value);\n\n\t/**\n\t * Gets a value of a property given a name\n\t *\n\t * Note that if name is not found in the current context, the expected behavior is to\n\t * recursively search in paren context. Null is returned only if name is not found in\n\t * any context.\n\t *\n\t * @param name name of property\n\t * @return value of property\n\t */\n\tObject getProperty(String name);\n\n\t/**\n\t * Gets a value of a property given a name\n\t *\n\t * Note that if name is not found in the current context, the expected behavior is to\n\t * recursively search in paren context. Null is returned only if name is not found in\n\t * any context.\n\t *\n\t * @param name name of value\n\t * @param type type of value\n\t * @return value\n\t * @throws WrongTypeException\n\t */\n\t<T> T getProperty(String name, Class<T> type) throws WrongTypeException;\n\n\t/**\n\t * Gets time the global instance was created\n\t *\n\t * The time supplied by Env.getCurrentTime() will become the value of global instance time\n\t * when the global context is created from Env. All child contexts under this global context\n\t * will inherit the same global instance time.\n\t *\n\t * @return UTC time in milliseconds\n\t */\n\tlong getGlobalInstanceTime();\n\n}",
"public interface Function {\n\n\t/**\n\t * Invokes function with given parameters and context\n\t *\n\t * @param params actual parameters to function call\n\t * @param context context in which the function operates\n\t * @return return value of function\n\t * @throws FunctionCallException\n\t */\n\tObject invoke(List<?> params, Context context) throws FunctionCallException;\n\n}",
"public class FunctionCallException extends RenderException {\n\n\tpublic FunctionCallException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic FunctionCallException(Throwable throwable) {\n\t\tsuper(throwable);\n\t}\n\n}",
"public class FunctionCallExceptionFactory extends MessageExceptionFactory<FunctionCallException> {\n\n\t@Override\n\tpublic FunctionCallException newException(String message) {\n\t\treturn new FunctionCallException(message);\n\t}\n\n}",
"public class TimeValue {\n\n\tpublic final static String DATE_FORMAT_STRING = \"yyyy/MM/dd HH:mm:ss.SSS z\";\n\n\tprivate final TimeZone timeZone;\n\tprivate final long time;\n\tprivate final transient String stringValue;\n\n\t/**\n\t * Constructor\n\t *\n\t * @param timeZone time zone\n\t * @param time time in UTC milliseconds\n\t */\n\tpublic TimeValue(TimeZone timeZone, long time) {\n\t\tthis.timeZone = timeZone;\n\t\tthis.time = time;\n\n\t\t// compute string representation\n\t\tDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_STRING);\n\t\tdateFormat.setTimeZone(timeZone);\n\t\tthis.stringValue = dateFormat.format(new Date(time));\n\t}\n\n\tpublic TimeZone getTimeZone() {\n\t\treturn timeZone;\n\t}\n\n\t@Member(\"timeMillis\")\n\tpublic long getTime() {\n\t\treturn time;\n\t}\n\n\t@Member(\"timeZone\")\n\tpublic String getTimeZoneId() {\n\t\treturn timeZone.getID();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn this.stringValue;\n\t}\n}",
"public class Validation<E extends Throwable> {\n\n\tprivate ExceptionFactory<E> exceptionFactory;\n\n\t/**\n\t * Constructor\n\t *\n\t * @param exceptionFactory factory to create exception\n\t */\n\tpublic Validation(ExceptionFactory<E> exceptionFactory) {\n\t\tthis.exceptionFactory = exceptionFactory;\n\t}\n\n\t/**\n\t * Requires object to cast to type\n\t *\n\t * @param object object to cast\n\t * @param type target class to cast object to\n\t * @param message error message\n\t * @param <T> object type\n\t * @return object cast into instance of T\n\t * @throws E when object cannot be cast as T\n\t */\n\tpublic <T> T requireType(Object object, Class<T> type, Message message) throws E {\n\t\tif (type.isAssignableFrom(object.getClass())) {\n\t\t\treturn type.cast(object);\n\t\t}\n\t\tthrow exceptionFactory.newException(message.reformat(\"Expected type %s but got %s\",\n\t\t\t\ttype, object.getClass()).toString());\n\t}\n\n\t/**\n\t * Request that object be cast to type\n\t * @param object object to cast\n\t * @param type target class to cast object to\n\t * @param <T> object type\n\t * @return optional containing cast object if type is assignable from object,\n\t * \tor absent optional otherwise\n\t */\n\tpublic <T> Optional<T> requestType(Object object, Class<T> type) {\n\t\tif (type.isAssignableFrom(object.getClass())) {\n\t\t\treturn Optional.of(type.cast(object));\n\t\t} else {\n\t\t\treturn Optional.empty();\n\t\t}\n\t}\n\n\t/**\n\t * Requires object to be not null\n\t *\n\t * @param object object to check\n\t * @param message error message\n\t * @param <T> object type\n\t * @return object itself\n\t * @throws E when object is null\n\t */\n\tpublic <T> T requireNotNull(T object, Message message) throws E {\n\t\tif (object == null) {\n\t\t\tthrow exceptionFactory.newException(message.reformat(\"Cannot be null\").toString());\n\t\t}\n\t\treturn object;\n\t}\n\n\t/**\n\t * Requires list to be between min and max size\n\t *\n\t * @param list list to check\n\t * @param minSize minimum size of list\n\t * @param maxSize maximum size of list\n\t * @param message error message\n\t * @return list itself\n\t * @throws E when list is not between min and max size\n\t */\n\tpublic List<?> requireListSize(List<?> list, int minSize, int maxSize, Message message)\n\t\t\tthrows E {\n\t\tif (list.size() < minSize) {\n\t\t\tthrow exceptionFactory.newException(message.reformat(\"Has too few elements\")\n\t\t\t\t\t.toString());\n\t\t}\n\t\tif (list.size() > maxSize) {\n\t\t\tthrow exceptionFactory.newException(message.reformat(\"Has too many elements\")\n\t\t\t\t\t.toString());\n\t\t}\n\t\treturn list;\n\t}\n\n}",
"public abstract class Message {\n\n\t/**\n\t * Reformats message to specific exception\n\t *\n\t * @param formatString format string\n\t * @param arguments arguments\n\t * @return new message\n\t */\n\tpublic abstract Message reformat(String formatString, Object...arguments);\n\n\t/**\n\t * Creates message with specific prefix\n\t *\n\t * On reformat, the message contain prefix in the start of text\n\t *\n\t * @param prefix prefix of message\n\t * @return message instance\n\t */\n\tpublic static Message prefix(final String prefix) {\n\t\treturn new Message() {\n\t\t\tprivate String text = prefix;\n\t\t\t@Override\n\t\t\tpublic Message reformat(String formatString, Object...arguments) {\n\t\t\t\treturn Message.full(String.format(\"%s: %s\", prefix,\n\t\t\t\t\t\tString.format(formatString, arguments)));\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn text;\n\t\t\t}\n\t\t};\n\t}\n\n\t/**\n\t * Creates fully-formed message\n\t *\n\t * The message is immutable. Reformat does not affect the message.\n\t *\n\t * @param text text of message\n\t * @return message instance\n\t */\n\tpublic static Message full(final String text) {\n\t\treturn new Message() {\n\t\t\t@Override\n\t\t\tpublic Message reformat(String formatString, Object...arguments) {\n\t\t\t\treturn this;\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn text;\n\t\t\t}\n\t\t};\n\t}\n\n}"
] | import com.turn.camino.Context;
import com.turn.camino.render.Function;
import com.turn.camino.render.FunctionCallException;
import com.turn.camino.render.FunctionCallExceptionFactory;
import com.turn.camino.render.TimeValue;
import com.turn.camino.util.Validation;
import static com.turn.camino.util.Message.*;
import com.google.common.collect.ImmutableMap;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*; | /*
* Copyright (C) 2014-2018, Amobee 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
*/
package com.turn.camino.render.functions;
/**
* Time functions
*
* @author llo
*/
public class TimeFunctions {
private final static Validation<FunctionCallException> VALIDATION =
new Validation<>(new FunctionCallExceptionFactory());
private final static long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000L;
/**
* Supported time units
*/
public enum Unit {
YEAR("y", Calendar.YEAR),
MONTH("M", Calendar.MONTH),
DAY("D", Calendar.DATE),
HOUR("h", Calendar.HOUR),
MINUTE("m", Calendar.MINUTE),
SECOND("s", Calendar.SECOND),
MILLISECOND("S", Calendar.MILLISECOND);
private final String symbol;
private final int unit;
Unit(String symbol, int unit) {
this.symbol = symbol;
this.unit = unit;
}
public String getSymbol() {
return symbol;
}
public int getUnit() {
return unit;
}
}
/**
* Time units
*/
private final static Map<String, Unit> TIME_UNITS = ImmutableMap.<String, Unit>builder()
.put(Unit.YEAR.getSymbol(), Unit.YEAR)
.put(Unit.MONTH.getSymbol(), Unit.MONTH)
.put(Unit.DAY.getSymbol(), Unit.DAY)
.put(Unit.HOUR.getSymbol(), Unit.HOUR)
.put(Unit.MINUTE.getSymbol(), Unit.MINUTE)
.put(Unit.SECOND.getSymbol(), Unit.SECOND)
.put(Unit.MILLISECOND.getSymbol(), Unit.MILLISECOND)
.build();
/**
* Function to returns current time
*
* Function returns current time in either system default time zone if no argument is
* given, or in specified time zone.
*
* @author llo
*/
public static class Now implements Function {
@Override | public Object invoke(List<?> params, Context context) throws FunctionCallException { | 0 |
chudooder/FEMultiplayer | src/net/fe/network/FEServer.java | [
"public class Player implements Serializable {\n\tprivate static final long serialVersionUID = -7461827659473965623L;\n\tprivate Party party;\n\tprivate byte clientID;\n\tprivate String nickname;\n\tprivate int team;\n\tpublic boolean ready;\n\t\n//\tpublic static final int TEAM_UNASSIGNED = 0;\n\tpublic static final int TEAM_SPECTATOR = 0;\n\tpublic static final int TEAM_BLUE = 1;\n\tpublic static final int TEAM_RED = 2;\n\t\n\tpublic Player(String name, byte id) {\n\t\tparty = new Party();\n\t\tclientID = id;\n\t\tnickname = name;\n\t\tteam = 0;\n\t\tready = false;\n\t}\n\t\n\tpublic boolean isSpectator() {\n\t\treturn team == TEAM_SPECTATOR;\n\t}\n\t\n\tpublic Party getParty() {\n\t\treturn party;\n\t}\n\t\n\tpublic byte getID() {\n\t\treturn clientID;\n\t}\n\t\n\tpublic String getName() {\n\t\treturn nickname;\n\t}\n\n\tpublic void setClientID(byte id) {\n\t\tclientID = id;\n\t}\n\n\tpublic int getTeam() {\n\t\treturn team;\n\t}\n\n\tpublic void setTeam(int team2) {\n\t\tteam = team2;\n\t}\n\n\tpublic void joinTeam(int team) {\n\t\tFEMultiplayer.getClient().sendMessage(new JoinTeam(clientID, team));\n\t}\n\t\n\tpublic boolean equals(Player p) {\n\t\treturn p.clientID == clientID;\n\t}\n\n\tpublic void setName(String nickname) {\n\t\tthis.nickname = nickname;\n\t}\n}",
"public class LobbyStage extends Stage {\n\tprotected Chat chat;\n\tprotected Session session;\n\t\n\tpublic LobbyStage(Session s) {\n\t\tsuper(\"main_theme\");\n\t\tsession = s;\n\t\tchat = new Chat();\n\t}\n\t@Override\n\tpublic void beginStep() {\n\t\tfor(Message message : Game.getMessages()) {\n\t\t\tif(message instanceof JoinLobby) {\n\t\t\t\tJoinLobby join = (JoinLobby)message;\n\t\t\t\tsession.addPlayer((byte) join.origin, join.player);\n\t\t\t}\n\t\t\telse if(message instanceof JoinTeam) {\n\t\t\t\tJoinTeam join = (JoinTeam)message;\n\t\t\t\tsession.getPlayer(join.origin).setTeam(join.team);\n\t\t\t\tif(join.team == Player.TEAM_BLUE) {\n\t\t\t\t\tsession.getPlayer(join.origin).getParty().setColor(Party.TEAM_BLUE);\n\t\t\t\t} else if(join.team == Player.TEAM_RED) {\n\t\t\t\t\tsession.getPlayer(join.origin).getParty().setColor(Party.TEAM_RED);\n\t\t\t\t}\n\t\t\t\tsession.getPlayer(join.origin).ready = false;\n\t\t\t}\n\t\t\telse if(message instanceof ClientInit) {\t\t// Only clients will get this\n\t\t\t\tClientInit init = (ClientInit)message;\n\t\t\t\tsession = init.session;\n\t\t\t}\n\t\t\telse if(message instanceof QuitMessage) {\n\t\t\t\tQuitMessage quit = (QuitMessage)message;\n\t\t\t\tsession.removePlayer(quit.origin);\n\t\t\t}\n\t\t\telse if(message instanceof ChatMessage) {\n\t\t\t\tChatMessage chatMsg = (ChatMessage)message;\n\t\t\t\tchat.add(session.getPlayer(chatMsg.origin), chatMsg.text);\n\t\t\t}\n\t\t\telse if(message instanceof ReadyMessage) {\n\t\t\t\tboolean ready = !session.getPlayer(message.origin).ready;\n\t\t\t\tsession.getPlayer(message.origin).ready = ready;\n\t\t\t\tif(ready)\n\t\t\t\t\tchat.add(session.getPlayer(message.origin), \"Ready!\");\n\t\t\t\telse\n\t\t\t\t\tchat.add(session.getPlayer(message.origin), \"Not ready!\");\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onStep() {\n\t\t\n\t}\n\n\t@Override\n\tpublic void endStep() {\n\t\tif(session.numPlayers() == 0) return;\n\t\tfor(Player p : session.getPlayers()) {\n\t\t\tif(!p.ready) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tFEServer.getServer().broadcastMessage(new StartPicking((byte)0));\n\t\tFEServer.getServer().allowConnections = false;\n\t\tsession.getPickMode().setUpServer(session);\n\t}\n\n}",
"public class SuddenDeath implements Modifier{\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = -4684401842583775643L;\n\n\t@Override\n\tpublic void modifyTeam(TeamBuilderStage stage) {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\t@Override\n\tpublic void modifyShop(ShopMenu shop) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void modifyUnits(TeamSelectionStage stage) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void initOverworld(OverworldStage stage) {\n\t\tfor(Unit u : stage.getAllUnits()) {\n\t\t\tu.setHp(1);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void endOfTurn(OverworldStage stage) {\n\t\t\n\t}\n\n\t@Override\n\tpublic String getDescription() {\n\t\treturn \"All units start at 1 HP.\";\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Sudden Death\";\n\t}\n\n}",
"public class Veterans implements Modifier {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 8924524348358477808L;\n\n\t@Override\n\tpublic void modifyTeam(TeamBuilderStage stage) {\n\t\tstage.setExp(999999999);\n\t}\n\n\t@Override\n\tpublic void modifyShop(ShopMenu shop) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void modifyUnits(TeamSelectionStage stage) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void initOverworld(OverworldStage stage) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void endOfTurn(OverworldStage stage) {\n\t\t\n\t}\n\n\t@Override\n\tpublic String getDescription() {\n\t\treturn \"Unlimited starting EXP.\";\n\t}\n\t\n\tpublic String toString() {\n\t\treturn \"Veterans\";\n\t}\n\t\n}",
"public interface Objective extends Serializable {\n\t/**\n\t * Returns the client ID of the winner, \n\t * or -1 if there is no winner\n\t * @param stage\n\t * @return\n\t */\n\tpublic int evaluate(OverworldStage stage);\n\tpublic String getDescription();\n}",
"public class Seize implements Objective {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1608192440668201886L;\n\t@Override\n\tpublic int evaluate(OverworldStage stage) {\n\t\t\n\t\t// If a player has a Lord on the other player's throne, they win\n\t\t// Alternatively, if a player's Lord dies, they lose\n\t\tbyte winner = -1;\n\t\tfor(Player p : stage.getNonSpectators()) {\n\t\t\tboolean hasLord = false;\n\t\t\tfor(int i=0; i<p.getParty().size(); i++) {\n\t\t\t\tUnit u = p.getParty().getUnit(i);\n\t\t\t\tif(u.getTheClass().name.equals(\"Lord\") && u.getHp() > 0) {\n\t\t\t\t\thasLord = true;\n\t\t\t\t\tSystem.out.println(p.getName()+\" has a Lord!\");\n\t\t\t\t}\n\t\t\t\tif(stage.grid.canSeize(u)) {\n\t\t\t\t\treturn p.getID();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(hasLord) {\n\t\t\t\tif(winner == -1) {\n\t\t\t\t\twinner = p.getID();\n\t\t\t\t} else {\n\t\t\t\t\twinner = -2;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(winner > 0) {\n\t\t\tSystem.out.println(winner+\" has a Lord and wins!\");\n\t\t\treturn winner;\n\t\t}\n\t\telse return -1;\n\t}\n;\n\t@Override\n\tpublic String getDescription() {\n\t\treturn \"Seize the throne\";\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Seize\";\n\t}\n\n}",
"public class UnitIdentifier implements Serializable{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\tpublic String name;\r\n\tpublic org.newdawn.slick.Color partyColor;\r\n\t\r\n\tpublic UnitIdentifier(Unit u){\r\n\t\tname = u.name;\r\n\t\tpartyColor = u.getPartyColor();\r\n\t}\r\n\t\r\n\tpublic int hashCode(){\r\n\t\treturn name.hashCode() + partyColor.hashCode();\r\n\t}\r\n\t\r\n\tpublic boolean equals(Object o){\r\n\t\tif(!(o instanceof UnitIdentifier)) return false;\r\n\t\tUnitIdentifier other = (UnitIdentifier) o;\r\n\t\treturn name.equals(other.name) && partyColor.equals(other.partyColor);\r\n\t}\r\n\t\r\n\tpublic String toString(){\r\n\t\treturn name;\r\n\t}\r\n}\r",
"public abstract class Game {\n\t\n\tprotected static int windowWidth = 640;\n\tprotected static int windowHeight = 480;\n\tprotected static int scaleX = 2;\n\tprotected static int scaleY = 2;\n\tprotected boolean paused = false;\n\tprotected static List<KeyboardEvent> keys;\n\tprotected static List<MouseEvent> mouseEvents;\n\tprotected static CopyOnWriteArrayList<Message> messages;\n\tprotected long time;\n\tprotected static long timeDelta;\n\tprotected static boolean glContextExists;\n\t\n\tpublic void init(int width, int height, String name) {\n\t\ttime = System.nanoTime();\n\t\t\n\t\twindowWidth = width*scaleX;\n\t\twindowHeight = height*scaleY;\n\n\t\ttry {\n\t\t\tDisplay.setDisplayMode(new DisplayMode(windowWidth, windowHeight));\n\t\t\tDisplay.create();\n\t\t\tDisplay.setTitle(name);\n\t\t\tKeyboard.create();\n\t\t\tKeyboard.enableRepeatEvents(true);\n\t\t\tMouse.create();\n\t\t\tglContextExists = true;\n\t\t} catch (LWJGLException e) {\n\t\t\te.printStackTrace();\n\t\t\tSystem.exit(0);\n\t\t}\n\t\t\n\t\t//init OpenGL\n\t\tglEnable(GL_DEPTH_TEST);\n\t\tglDepthFunc(GL_LEQUAL);\n\t\tglEnable(GL_ALPHA_TEST);\n\t\tglAlphaFunc(GL_GREATER, 0.01f);\n\t\tglEnable(GL_TEXTURE_2D);\n\t\tglShadeModel(GL_SMOOTH);\n\t\tglClearDepth(1.0f);\n\t\tglClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n\t\tglEnable(GL_BLEND);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\t\tglViewport(0, 0, windowWidth, windowHeight);\n\t\tglMatrixMode(GL_PROJECTION);\n\t\tglLoadIdentity();\n\t\tglOrtho(0, windowWidth/scaleX, windowHeight/scaleY, 0, 1, -1);\t\t//It's basically a camera\n\t\tglMatrixMode(GL_MODELVIEW);\n\t\t\n\t\tkeys = new ArrayList<KeyboardEvent>();\n\t\tmouseEvents = new ArrayList<MouseEvent>();\n\t}\n\t\n\tpublic abstract void loop();\n\n\n\tpublic static void getInput() {\n\t\tKeyboard.poll();\n\t\tkeys.clear();\n\t\twhile(Keyboard.next()) {\n\t\t\tKeyboardEvent ke = new KeyboardEvent(\n\t\t\t\t\tKeyboard.getEventKey(),\n\t\t\t\t\tKeyboard.getEventCharacter(),\n\t\t\t\t\tKeyboard.isRepeatEvent(),\n\t\t\t\t\tKeyboard.getEventKeyState());\n\t\t\tkeys.add(ke);\n\t\t}\n\t\tMouse.poll();\n\t\tmouseEvents.clear();\n\t\twhile(Mouse.next()) {\n\t\t\tMouseEvent me = new MouseEvent(\n\t\t\t\t\tMouse.getEventX(),\n\t\t\t\t\tMouse.getEventY(),\n\t\t\t\t\tMouse.getEventDWheel(),\n\t\t\t\t\tMouse.getEventButton(),\n\t\t\t\t\tMouse.getEventButtonState());\n\t\t\tmouseEvents.add(me);\n\t\t}\n\t}\n\t\n\tpublic static List<KeyboardEvent> getKeys() {\n\t\treturn keys;\n\t}\n\t\n\tpublic static List<MouseEvent> getMouseEvents() {\n\t\treturn mouseEvents;\n\t}\n\t\n\tpublic static List<Message> getMessages() {\n\t\treturn messages;\n\t}\n\n\tpublic static long getDelta() {\n\t\treturn timeDelta;\n\t}\n\t\n\tpublic static float getDeltaMillis() {\n\t\treturn timeDelta/1000000.0f;\n\t}\n\t\n\tpublic static float getDeltaSeconds() {\n\t\treturn timeDelta/1000000000.0f;\n\t}\n\t\n\tpublic static int getWindowWidth() {\n\t\treturn windowWidth;\n\t}\n\t\n\tpublic static int getWindowHeight() {\n\t\treturn windowHeight;\n\t}\n\n\tpublic static boolean glContextExists() {\n\t\treturn glContextExists;\n\t}\n\t\n\tpublic static int getScaleX() {\n\t\treturn scaleX;\n\t}\n\t\n\tpublic static int getScaleY() {\n\t\treturn scaleY;\n\t}\n}"
] | import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SpinnerNumberModel;
import net.fe.Player;
import net.fe.Session;
import net.fe.lobbystage.LobbyStage;
import net.fe.modifier.DivineIntervention;
import net.fe.modifier.MadeInChina;
import net.fe.modifier.Modifier;
import net.fe.modifier.SuddenDeath;
import net.fe.modifier.Treasury;
import net.fe.modifier.Vegas;
import net.fe.modifier.Veterans;
import net.fe.overworldStage.objective.Objective;
import net.fe.overworldStage.objective.Rout;
import net.fe.overworldStage.objective.Seize;
import net.fe.pick.AllPick;
import net.fe.pick.Draft;
import net.fe.pick.PickMode;
import net.fe.unit.Unit;
import net.fe.unit.UnitIdentifier;
import chu.engine.Game;
import chu.engine.Stage; | package net.fe.network;
/**
* A game that does not render anything. Manages logic only
* @author Shawn
*
*/
public class FEServer extends Game {
private static Server server;
private static Stage currentStage;
public static LobbyStage lobby;
private static Map<String, Objective[]> maps;
public static void main(String[] args) {
final JFrame frame = new JFrame("FEServer");
Rout rout = new Rout(); | Seize seize = new Seize(); | 5 |
roybailey/research-graphql | research-graphql-server/src/main/java/me/roybailey/springboot/graphql/domain/schema/OrderItemResolver.java | [
"@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"id\",\n \"userId\",\n \"items\",\n \"status\"\n})\[email protected]\[email protected]\[email protected]\npublic class OrderDto {\n\n @JsonProperty(\"id\")\n private String id;\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"userId\")\n private String userId;\n @JsonProperty(\"items\")\n @lombok.Builder.Default\nprivate List<OrderItemDto> items = new ArrayList<OrderItemDto>();\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"status\")\n private OrderDto.Status status;\n\n @JsonProperty(\"id\")\n public String getId() {\n return id;\n }\n\n @JsonProperty(\"id\")\n public void setId(String id) {\n this.id = id;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"userId\")\n public String getUserId() {\n return userId;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"userId\")\n public void setUserId(String userId) {\n this.userId = userId;\n }\n\n @JsonProperty(\"items\")\n public List<OrderItemDto> getItems() {\n return items;\n }\n\n @JsonProperty(\"items\")\n public void setItems(List<OrderItemDto> items) {\n this.items = items;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"status\")\n public OrderDto.Status getStatus() {\n return status;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"status\")\n public void setStatus(OrderDto.Status status) {\n this.status = status;\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this);\n }\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder().append(id).append(userId).append(items).append(status).toHashCode();\n }\n\n @Override\n public boolean equals(Object other) {\n if (other == this) {\n return true;\n }\n if ((other instanceof OrderDto) == false) {\n return false;\n }\n OrderDto rhs = ((OrderDto) other);\n return new EqualsBuilder().append(id, rhs.id).append(userId, rhs.userId).append(items, rhs.items).append(status, rhs.status).isEquals();\n }\n\n public enum Status {\n\n SUBMITTED(\"SUBMITTED\"),\n PAYED(\"PAYED\"),\n DISPATCHED(\"DISPATCHED\");\n private final String value;\n private final static Map<String, OrderDto.Status> CONSTANTS = new HashMap<String, OrderDto.Status>();\n\n static {\n for (OrderDto.Status c: values()) {\n CONSTANTS.put(c.value, c);\n }\n }\n\n private Status(String value) {\n this.value = value;\n }\n\n @Override\n public String toString() {\n return this.value;\n }\n\n @JsonValue\n public String value() {\n return this.value;\n }\n\n @JsonCreator\n public static OrderDto.Status fromValue(String value) {\n OrderDto.Status constant = CONSTANTS.get(value);\n if (constant == null) {\n throw new IllegalArgumentException(value);\n } else {\n return constant;\n }\n }\n\n }\n\n}",
"@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"productId\",\n \"quantity\"\n})\[email protected]\[email protected]\[email protected]\npublic class OrderItemDto {\n\n @JsonProperty(\"productId\")\n private String productId;\n @JsonProperty(\"quantity\")\n private Integer quantity;\n\n @JsonProperty(\"productId\")\n public String getProductId() {\n return productId;\n }\n\n @JsonProperty(\"productId\")\n public void setProductId(String productId) {\n this.productId = productId;\n }\n\n @JsonProperty(\"quantity\")\n public Integer getQuantity() {\n return quantity;\n }\n\n @JsonProperty(\"quantity\")\n public void setQuantity(Integer quantity) {\n this.quantity = quantity;\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this);\n }\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder().append(productId).append(quantity).toHashCode();\n }\n\n @Override\n public boolean equals(Object other) {\n if (other == this) {\n return true;\n }\n if ((other instanceof OrderItemDto) == false) {\n return false;\n }\n OrderItemDto rhs = ((OrderItemDto) other);\n return new EqualsBuilder().append(productId, rhs.productId).append(quantity, rhs.quantity).isEquals();\n }\n\n}",
"@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"id\",\n \"name\",\n \"brand\",\n \"category\",\n \"description\",\n \"price\"\n})\[email protected]\[email protected]\[email protected]\npublic class ProductDto {\n\n @JsonProperty(\"id\")\n private String id;\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"name\")\n private String name;\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"brand\")\n private String brand;\n @JsonProperty(\"category\")\n @lombok.Builder.Default\nprivate List<String> category = new ArrayList<String>();\n @JsonProperty(\"description\")\n private String description;\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"price\")\n private BigDecimal price;\n\n @JsonProperty(\"id\")\n public String getId() {\n return id;\n }\n\n @JsonProperty(\"id\")\n public void setId(String id) {\n this.id = id;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"name\")\n public String getName() {\n return name;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"name\")\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"brand\")\n public String getBrand() {\n return brand;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"brand\")\n public void setBrand(String brand) {\n this.brand = brand;\n }\n\n @JsonProperty(\"category\")\n public List<String> getCategory() {\n return category;\n }\n\n @JsonProperty(\"category\")\n public void setCategory(List<String> category) {\n this.category = category;\n }\n\n @JsonProperty(\"description\")\n public String getDescription() {\n return description;\n }\n\n @JsonProperty(\"description\")\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"price\")\n public BigDecimal getPrice() {\n return price;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"price\")\n public void setPrice(BigDecimal price) {\n this.price = price;\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this);\n }\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder().append(id).append(name).append(brand).append(category).append(description).append(price).toHashCode();\n }\n\n @Override\n public boolean equals(Object other) {\n if (other == this) {\n return true;\n }\n if ((other instanceof ProductDto) == false) {\n return false;\n }\n ProductDto rhs = ((ProductDto) other);\n return new EqualsBuilder().append(id, rhs.id).append(name, rhs.name).append(brand, rhs.brand).append(category, rhs.category).append(description, rhs.description).append(price, rhs.price).isEquals();\n }\n\n}",
"@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"id\",\n \"title\",\n \"given-name\",\n \"family-name\",\n \"bday\",\n \"email\"\n})\[email protected]\[email protected]\[email protected]\npublic class UserDto {\n\n @JsonProperty(\"id\")\n private String id;\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"title\")\n private String title;\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"given-name\")\n private String givenName;\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"family-name\")\n private String familyName;\n @JsonProperty(\"bday\")\n private java.time.LocalDateTime bday;\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"email\")\n private String email;\n\n @JsonProperty(\"id\")\n public String getId() {\n return id;\n }\n\n @JsonProperty(\"id\")\n public void setId(String id) {\n this.id = id;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"title\")\n public String getTitle() {\n return title;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"title\")\n public void setTitle(String title) {\n this.title = title;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"given-name\")\n public String getGivenName() {\n return givenName;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"given-name\")\n public void setGivenName(String givenName) {\n this.givenName = givenName;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"family-name\")\n public String getFamilyName() {\n return familyName;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"family-name\")\n public void setFamilyName(String familyName) {\n this.familyName = familyName;\n }\n\n @JsonProperty(\"bday\")\n public java.time.LocalDateTime getBday() {\n return bday;\n }\n\n @JsonProperty(\"bday\")\n public void setBday(java.time.LocalDateTime bday) {\n this.bday = bday;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"email\")\n public String getEmail() {\n return email;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"email\")\n public void setEmail(String email) {\n this.email = email;\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this);\n }\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder().append(id).append(title).append(givenName).append(familyName).append(bday).append(email).toHashCode();\n }\n\n @Override\n public boolean equals(Object other) {\n if (other == this) {\n return true;\n }\n if ((other instanceof UserDto) == false) {\n return false;\n }\n UserDto rhs = ((UserDto) other);\n return new EqualsBuilder().append(id, rhs.id).append(title, rhs.title).append(givenName, rhs.givenName).append(familyName, rhs.familyName).append(bday, rhs.bday).append(email, rhs.email).isEquals();\n }\n\n}",
"@Slf4j\n@Service()\npublic class ProductAdaptor {\n\n @Autowired\n DataSourceProperties properties;\n\n @Headers(\"Accept: application/json\")\n private interface ProductApi {\n\n @RequestLine(\"GET /product-api/v1/product\")\n List<ProductDto> getAllProducts();\n\n @RequestLine(\"GET /product-api/v1/product/{id}\")\n ProductDto getProductById(@Param(\"id\") String id);\n\n @Headers(\"Content-Type: application/json\")\n @RequestLine(\"POST /product-api/v1/product\")\n ProductDto upsertProduct(ProductDto product);\n\n @RequestLine(\"DELETE /product-api/v1/product/{id}\")\n ProductDto deleteProductById(@Param(\"id\") String id);\n\n }\n\n private ProductApi api;\n\n @PostConstruct\n public void apiSetup() {\n log.info(\"Connecting {} to {}\", ProductApi.class.getSimpleName(), properties.getUrlProductService());\n this.api = Feign.builder()\n .encoder(new JacksonEncoder())\n .decoder(new JacksonDecoder())\n .logLevel(Logger.Level.BASIC)\n .target(ProductApi.class, properties.getUrlProductService());\n }\n\n\n public List<ProductDto> getAllProducts() {\n List<ProductDto> allProducts = api.getAllProducts();\n log.info(\"getAllProducts() : {}\", allProducts);\n return allProducts;\n }\n\n public ProductDto getProduct(String productId) {\n ProductDto product = api.getProductById(productId);\n log.info(\"getProduct({}) : {}\", productId, product);\n return product;\n }\n\n public ProductDto upsertProduct(ProductDto product) {\n ProductDto updatedProduct = api.upsertProduct(product);\n log.info(\"createProduct({}) : {}\", product, updatedProduct);\n return updatedProduct;\n }\n\n public ProductDto deleteProduct(String productId) {\n ProductDto deletedProduct = api.deleteProductById(productId);\n log.info(\"deleteProduct({}) : {}\", productId, deletedProduct);\n return deletedProduct;\n }\n\n}",
"@Slf4j\n@Service\npublic class UserAdaptor {\n\n @Autowired\n DataSourceProperties properties;\n\n @Autowired\n ObjectMapper jacksonMapper;\n\n @Headers(\"Accept: application/json\")\n private interface UserApi {\n\n @RequestLine(\"GET /user-api/v1/user\")\n List<UserDto> getAllUsers();\n\n @RequestLine(\"GET /user-api/v1/user/{id}\")\n UserDto getUserById(@Param(\"id\") String id);\n\n @RequestLine(\"POST /user-api/v1/user\")\n UserDto createUser(UserDto user);\n }\n\n private UserApi api;\n\n @PostConstruct\n public void apiSetup() {\n log.info(\"Connecting {} to {}\", UserApi.class.getSimpleName(), properties.getUrlUserService());\n this.api = Feign.builder()\n .encoder(new JacksonEncoder(jacksonMapper))\n .decoder(new JacksonDecoder(jacksonMapper))\n .logLevel(Logger.Level.BASIC)\n .target(UserApi.class, properties.getUrlUserService());\n }\n\n\n public List<UserDto> getAllUsers() {\n List<UserDto> allUsers = api.getAllUsers();\n log.info(\"getAllUsers() : {}\", allUsers);\n return allUsers;\n }\n\n public UserDto getUser(String userId) {\n UserDto user = api.getUserById(userId);\n log.info(\"getUser({}) : {}\", userId, user);\n return user;\n }\n\n\n public UserDto createUser(UserDto user) {\n UserDto newUser = api.createUser(user);\n log.info(\"createUser({}) : {}\", user, newUser);\n return newUser;\n }\n}"
] | import com.coxautodev.graphql.tools.GraphQLResolver;
import me.roybailey.data.schema.OrderDto;
import me.roybailey.data.schema.OrderItemDto;
import me.roybailey.data.schema.ProductDto;
import me.roybailey.data.schema.UserDto;
import me.roybailey.springboot.service.ProductAdaptor;
import me.roybailey.springboot.service.UserAdaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; | package me.roybailey.springboot.graphql.domain.schema;
/**
* This class contains resolver methods for the "Data Class" type
*/
@Service
public class OrderItemResolver implements GraphQLResolver<OrderItemDto> {
@Autowired | ProductAdaptor productAdaptor; | 4 |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/sensors/HardwareSensor_OLD.java | [
"public class DataAcquisitor {\n\n\tprivate static final String LOG_TAG = DataAcquisitor.class.getSimpleName();\n\tprivate String folderName;\n\tprivate String fileName;\n\t//private Context context;\n\tprivate ArrayList<String> dataBuffer;\n\n\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tpublic static ArrayList<String> dataBuff = new ArrayList();\n\n\n\tpublic String getFolderName() {\n\t\treturn folderName;\n\t}\n\n\tpublic DataAcquisitor() {\n\n\t}\n\n\tpublic DataAcquisitor(String folderName, String fileName) {\n\t\t//this.context = context;\n\t\tthis.folderName = folderName;\n\t\tdataBuffer = new ArrayList<String>();\n\t\tthis.fileName = fileName;\n\t}\n\n\tpublic void removeData(Long timeinms) {\n\n\t}\n\n\tpublic ArrayList<String> getDataBuffer() {\n\t\treturn dataBuffer;\n\t}\n\n\tpublic String getCurrrentFileName() {\n\t\treturn fileName;\n\t}\n\n\n\tpublic void insert(String s, boolean append, int maxBuffSize) {\n\t\t//Log.d(LOG_TAG, \"Inserting into dBuff\");\n\t\tdataBuffer.add(s);\n\t\tif (dataBuffer.size() >= maxBuffSize) {\n\t\t\tflush(append);\n\t\t}\n\t}\n\n\tpublic void flush(boolean append) {\n\t\t//Log.d(LOG_TAG, \"Flushing buffer\" + this.getFolderName());\n\t\tIOManager dataLogger = new IOManager(getCurrrentFileName(), getFolderName());\n\t\tdataLogger.logData(this, append);\n\t\tgetDataBuffer().clear();\n\t}\n}",
"public class IOManager {\n\tString datenow = new String();\n\tprivate String currentFileName = new String();\n\tprivate String strPath;\n\n\tpublic IOManager() {\n\t\tthis.strPath = Environment.getExternalStorageDirectory().getAbsolutePath() + \"/\" + Setting.DEFAULT_FOLDER;\n\t}\n\n\tpublic IOManager(String filename, String homeFolder) {\n\t\tthis.strPath = Environment.getExternalStorageDirectory().getAbsolutePath() + \"/\" + homeFolder;\n\t\tthis.currentFileName = filename;\n\t}\n\n\tpublic String getPath() {\n\t\treturn strPath;\n\t}\n\n\tpublic String getCurrentFilename() {\n\t\treturn currentFileName + \".txt\";\n\t}\n\n\n\n\tpublic void logData(ArrayList<String> inArr) {\n\t\tFileWriter writer;\n\t\tdatenow = DateFormat.getDateInstance(DateFormat.SHORT).format(System.currentTimeMillis());\n\t\tSimpleDateFormat dateformat = new SimpleDateFormat(\"M-d-yyyy\");\n\t\t//datenow = DateFormat.getDateInstance(DateFormat.SHORT).format(System.currentTimeMillis());\n\t\t//datenow = datenow.replace(\"/\", \"-\");\n\t\ttry {\n\t\t\tFile logFile = new File(Setting.Instance(null).getLogFolder() + \"/\" + \"log_\" + dateformat.format(new Date()) + \".txt\"); //datenow+ \".txt\");\n\t\t\twriter = new FileWriter(logFile, true);\n\t\t\tif (!logFile.exists()) {\n\t\t\t\tlogFile.createNewFile();\n\t\t\t}\n\t\t\tIterator<String> it = inArr.iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tString aaa = it.next();\n\t\t\t\twriter.append(aaa+ System.getProperty(\"line.separator\"));\n\t\t\t}\n\t\t\twriter.flush();\n\t\t\twriter.close();\n\t\t\twriter = null;\n\n\t\t} catch (Exception e) {\n\t\t\t\n\t\t\t Log.e(\"DataAggregator\", \"--------Failed to write in a file-----\" + e.getMessage() + \"; Stack: \" + Log.getStackTraceString(e));\n\t\t\t\n\t\t}\n\t}\n\n\n\t// Added by AP\n\t// Uses a file name passed into the IOManager\n\tpublic boolean logData(DataAcquisitor dataAcq, boolean append) {\n\t\tif (dataAcq.getDataBuffer().size() <= 0) {\n\t\t\treturn false;\n\t\t}\n\t\t//File dirs = new File(getPath() + dataAcq.getFolderName());\n\t\tFile dirs = new File(getPath());\n\t\tif (!dirs.exists()) {\n\t\t\tdirs.mkdirs();\n\t\t}\n\n\t\tString fileName = Setting.filenameFormat.format(new Date()) + \"_\" + getCurrentFilename();\n\t\tFile logFile = new File(dirs, fileName);\n\t\ttry {\n\t\t\tFileWriter writer = new FileWriter(logFile, append);\n\t\t\tfor (String s : dataAcq.getDataBuffer()) {\n\t\t\t\twriter.append(s + System.getProperty(\"line.separator\"));\n\t\t\t}\n\t\t\twriter.flush();\n\t\t\twriter.close();\n\t\t\treturn true;\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic void logError(String msg) {\n\t\tPrintWriter printWr;\n\t\tDate a = new Date (System.currentTimeMillis());\n\t\tString errorDate = a.getDate()+\"-\"+a.getMonth()+\"-\"+a.getYear();\n\t\tFile errorFile = new File(Setting.Instance(null).getLogFolder(), \"error_\"+errorDate+\".txt\");\n\t\ttry {\n\t\t\tprintWr = new PrintWriter(new FileWriter(errorFile, true));\n\t\t\tprintWr.append(msg + System.getProperty(\"line.separator\"));\n\t\t\tprintWr.flush();\n\t\t\tprintWr.close();\n\t\t\tprintWr = null;\n\t\t} catch (Exception ex) {\n\t\t\tLog.e(\"IOManager.logError\", ex.getMessage(), ex);\n\t\t}\n\t}\n\n}",
"public class JsonEncodeDecode \n{\n\tpublic static String EncodeBluetooth(String deviceName, String deviceAddress, String bindState, Date timeStamp) \n\t{\n\t\tStringBuilder encodedString = new StringBuilder(\"\");\n\t\tencodedString = encodedString.append(\"{\\\"Bluetooth\\\":{\\\"name\\\":\\\"\"\n\t\t\t\t+ deviceName\n\t\t\t\t+ \"\\\",\\\"address\\\":\\\"\"\n\t\t\t\t+ deviceAddress\n\t\t\t\t+ \"\\\",\\\"bond status\\\":\\\"\"\n\t\t\t\t+ bindState\n\t\t\t\t+ \"\\\",\\\"time\\\":\\\"\"\n\t\t\t\t+ DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timeStamp) \n\t\t\t\t+ \"\\\"}}\");\n\n\t\treturn encodedString.toString();\n\t}\n\n\tpublic static String[] DecodeBluetooth(String jsonString) \n\t{\n\t\tString[] split = jsonString.split(\"\\\"\");\n\n\t\tString[] decodedString = new String[4];\n\n\t\tdecodedString[0] = split[5];\n\t\tdecodedString[1] = split[9];\n\t\tdecodedString[2] = split[13];\n\t\tdecodedString[3] = split[17];\n\n\t\treturn decodedString;\n\t}\n\n\tpublic static String EncodeMovement(Date timestampStart, Date timestampEnd, Movement movementState) \n\t{\n\t\tStringBuilder encodedString = new StringBuilder(\"\");\n\t\tencodedString = encodedString.append(\"{\\\"Movement\\\":{\\\"start\\\":\\\"\"\n\t\t\t\t+ DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampStart)\n\t\t\t\t+ \"\\\",\\\"end\\\":\\\"\"\n\t\t\t\t+ DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampEnd)\n\t\t\t\t+ \"\\\",\\\"state\\\":\\\"\"\n\t\t\t\t+ movementState\n\t\t\t\t+ \"\\\"}}\");\n\n\t\treturn encodedString.toString();\n\t}\n\t\n\tpublic static String[] DecodeMovement(String jsonString) \n\t{\n\t\tString[] split = jsonString.split(\"\\\"\");\n\n\t\tString[] decodedString = new String[3];\n\n\t\tdecodedString[0] = split[5];\n\t\tdecodedString[1] = split[9];\n\t\tdecodedString[2] = split[13];\n\n\t\treturn decodedString;\n\t}\n}",
"public class SensorState \n{\n\tpublic static enum Bluetooth \n\t{\n\t\tNONE(\"none\"),\n\t\tBONDING(\"bonding\"),\n\t\tBONDED(\"bonded\");\n\t\t\n\t\tprivate String state;\n\t\t\n\t\tBluetooth(String state)\n\t\t{\n\t\t\tthis.state = state;\n\t\t}\n\t\t\n\t\tpublic String getState()\n\t\t{\n\t\t\treturn state;\n\t\t}\n\t}\n\t\n\tpublic static enum Movement \n\t{\n\t\tFAST(\"fast\"),\n\t\tSLOW(\"slow\"),\n\t\tSTEADY(\"steady\");\n\t\t\n\t\tprivate String state;\n\t\t\n\t\tMovement(String state)\n\t\t{\n\t\t\tthis.state = state;\n\t\t}\n\t\t\n\t\tpublic String getState()\n\t\t{\n\t\t\treturn state;\n\t\t}\n\t}\n}",
"public static enum Movement \n{\n\tFAST(\"fast\"),\n\tSLOW(\"slow\"),\n\tSTEADY(\"steady\");\n\t\t\n\tprivate String state;\n\t\t\n\tMovement(String state)\n\t{\n\t\tthis.state = state;\n\t}\n\t\t\n\tpublic String getState()\n\t{\n\t\treturn state;\n\t}\n}"
] | import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import com.ubiqlog.core.DataAcquisitor;
import com.ubiqlog.utils.IOManager;
import com.ubiqlog.vis.utils.JsonEncodeDecode;
import com.ubiqlog.vis.utils.SensorState;
import com.ubiqlog.vis.utils.SensorState.Movement;
import android.app.Service;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.util.Log; | package com.ubiqlog.sensors;
public class HardwareSensor_OLD extends Service implements SensorConnector, SensorEventListener {
private SensorManager sensorManager;
private Sensor sensorAccelerometer; | private DataAcquisitor dataAcq = new DataAcquisitor(); | 0 |
lukaspili/Volley-Ball | samples/src/main/java/com/siu/android/volleyball/samples/activity/CompleteRequestActivity.java | [
"public class BallResponse<T> {\n\n public static enum ResponseSource {\n LOCAL, CACHE, NETWORK\n }\n\n protected Response<T> mResponse;\n protected ResponseSource mResponseSource;\n protected boolean mIdentical = false;\n\n /**\n * Returns whether this response is considered successful.\n */\n public boolean isSuccess() {\n return mResponse.isSuccess();\n }\n\n public static <T> BallResponse<T> identical(ResponseSource responseSource) {\n return new BallResponse<T>(Response.<T>success(null, null), responseSource, true);\n }\n\n public static <T> BallResponse<T> success(T result) {\n return new BallResponse<T>(Response.success(result, null));\n }\n\n public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) {\n return new BallResponse<T>(Response.success(result, cacheEntry));\n }\n\n public static <T> BallResponse<T> error(VolleyError error) {\n return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network\n }\n\n protected BallResponse(Response<T> response) {\n this(response, null, false);\n }\n\n protected BallResponse(Response<T> response, ResponseSource responseSource) {\n this(response, responseSource, false);\n }\n\n public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) {\n mResponse = response;\n mResponseSource = responseSource;\n mIdentical = identical;\n }\n\n public ResponseSource getResponseSource() {\n return mResponseSource;\n }\n\n public void setResponseSource(ResponseSource responseSource) {\n this.mResponseSource = responseSource;\n }\n\n public boolean isIntermediate() {\n return mResponse.intermediate;\n }\n\n public void setIntermediate(boolean intermediate) {\n mResponse.intermediate = intermediate;\n }\n\n public T getResult() {\n return mResponse.result;\n }\n\n public Cache.Entry getCacheEntry() {\n return mResponse.cacheEntry;\n }\n\n public VolleyError getError() {\n return mResponse.error;\n }\n\n public boolean isIdentical() {\n return mIdentical;\n }\n\n public void setIdentical(boolean identical) {\n mIdentical = identical;\n }\n}",
"public interface ResponseListener<T> {\n\n public void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource);\n\n public void onFinalResponse(T response, BallResponse.ResponseSource responseSource);\n\n public void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource);\n}",
"public class Application extends android.app.Application {\n\n private static Context sContext;\n private static BallRequestQueue sRequestQueue;\n private static BallRequestQueue sScenarioRequestQueue;\n private static DatabaseHelper sDatabaseHelper;\n private static SQLiteDatabase sSQLiteDatabase;\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n sContext = getApplicationContext();\n\n if (Constants.DEBUG) {\n deleteDatabase(DatabaseHelper.NAME);\n }\n\n // init volley ball\n VolleyBallConfig.Builder configBuilder = new VolleyBallConfig.Builder(sContext);\n\n // mock\n if (Constants.MOCK_WEBSERVICE) {\n FileMockNetwork network = new FileMockNetwork(sContext, new FileMockNetwork.Config()\n .basePath(\"fakeapi\")\n .requestDuration(1)\n .realNetworkHttpStack(new OkHttpStack()));\n configBuilder.network(network);\n } else {\n configBuilder.httpStack(new OkHttpStack());\n }\n\n sRequestQueue = VolleyBall.newRequestQueue(configBuilder.build());\n\n sScenarioRequestQueue = VolleyBall.newRequestQueue(new VolleyBallConfig.Builder(sContext)\n .network(new FakeNetwork())\n .build());\n\n // init database helper\n sDatabaseHelper = new DatabaseHelper(sContext);\n sSQLiteDatabase = sDatabaseHelper.getWritableDatabase();\n }\n\n public static Context getContext() {\n return sContext;\n }\n\n public static BallRequestQueue getRequestQueue() {\n return sRequestQueue;\n }\n\n public static BallRequestQueue getScenarioRequestQueue() {\n return sScenarioRequestQueue;\n }\n\n public static DatabaseHelper getDatabaseHelper() {\n return sDatabaseHelper;\n }\n\n public static SQLiteDatabase getSQLiteDatabase() {\n return sSQLiteDatabase;\n }\n}",
"public class EntriesAdapter extends BindableAdapter<Entry> {\n\n private List<Entry> mEntries;\n\n public EntriesAdapter(Context context, List<Entry> entries) {\n super(context);\n mEntries = entries;\n }\n\n @Override\n public Entry getItem(int position) {\n return mEntries.get(position);\n }\n\n @Override\n public View newView(LayoutInflater inflater, int position, ViewGroup container) {\n return inflater.inflate(R.layout.row, null);\n }\n\n @Override\n public void bindView(Entry item, int position, View view) {\n TextView titleTextView = (TextView) view.findViewById(R.id.title);\n titleTextView.setText(item.getTitle());\n }\n\n @Override\n public int getCount() {\n return mEntries.size();\n }\n\n @Override\n public long getItemId(int i) {\n return i;\n }\n}",
"public class Entry implements EntryMapping {\n\n private long id;\n private String title;\n\n public Entry() {\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n}",
"public class SimpleLogger {\n\n // D\n public static void d(String string) {\n Log.d(SimpleLogger.class.getName(), string);\n }\n\n public static void d(String string, Throwable tr) {\n Log.d(SimpleLogger.class.getName(), string, tr);\n }\n\n public static void d(String string, Object... args) {\n d(String.format(string, args));\n }\n\n public static void d(String string, Throwable tr, Object... args) {\n d(String.format(string, args), tr);\n }\n\n\n // E\n public static void e(String string) {\n Log.e(SimpleLogger.class.getName(), string);\n }\n\n public static void e(String string, Throwable tr) {\n Log.e(SimpleLogger.class.getName(), string, tr);\n }\n\n public static void e(String string, Object... args) {\n e(String.format(string, args));\n }\n\n public static void e(String string, Throwable tr, Object... args) {\n e(String.format(string, args), tr);\n }\n}",
"public class CompleteEntryRequest extends CompleteRequest<List<Entry>> {\n\n private static final Gson sGson = new Gson();\n\n /**\n * In this sample we mock the request so we don't care about the url\n */\n private static final String URL = \"http://some.url.com/entries\";\n\n public CompleteEntryRequest(ResponseListener<List<Entry>> responseListener, Response.ErrorListener errorListener) {\n super(Method.GET, URL, responseListener, errorListener);\n }\n\n /*\n Network processing\n We override those methods related to the network processing of the request in the same way we would do with the Request class\n The only difference is the implementation of parseBallNetworkResponse rather than parseNetworkResponse because of some shitty constraints\n */\n\n @Override\n protected BallResponse<List<Entry>> parseBallNetworkResponse(NetworkResponse response) {\n try {\n String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));\n List<Entry> entries = sGson.fromJson(json, new TypeToken<List<Entry>>() {\n }.getType());\n return BallResponse.success(entries, HttpHeaderParser.parseCacheHeaders(response));\n } catch (Exception e) {\n return BallResponse.error(new ParseError(e));\n }\n }\n\n\n /*\n Local processing\n And now comes the new part, the local processing\n */\n\n @Override\n protected List<Entry> getLocalResponse() {\n List<Entry> entries = EntryDao.getEntries();\n return entries.isEmpty() ? null : entries; // we return null if entries list from database is empty to tell volleyball to ignore this\n // local response, we may have more chance with the local cache response.\n // this can happen if for example the database is deleted for some reason but disk cache is still there\n }\n\n @Override\n public void saveNetworkResponseToLocal(List<Entry> entries) {\n // replace the previous old content with the new one retrieved from the network\n EntryDao.replaceAll(entries);\n }\n}",
"public class SampleRequest extends CompleteRequest<Object> {\n\n public SampleRequest(int method, String url, ResponseListener<Object> responseListener, Response.ErrorListener errorListener) {\n super(method, url, responseListener, errorListener);\n }\n\n @Override\n protected Object getLocalResponse() {\n // query your local database for example\n // return the result or null if there is no result from database\n return new Object();\n }\n\n @Override\n public void saveNetworkResponseToLocal(Object response) {\n // save the network response to the local database\n // next time the request is performed the local response will return the result faster than the network request\n }\n\n @Override\n protected BallResponse<Object> parseBallNetworkResponse(NetworkResponse response) {\n // parse the result from the network request, in the same way than with volley\n return null;\n }\n}"
] | import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.ListView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.siu.android.volleyball.BallResponse;
import com.siu.android.volleyball.response.ResponseListener;
import com.siu.android.volleyball.samples.Application;
import com.siu.android.volleyball.samples.R;
import com.siu.android.volleyball.samples.adapter.EntriesAdapter;
import com.siu.android.volleyball.samples.model.Entry;
import com.siu.android.volleyball.samples.util.SimpleLogger;
import com.siu.android.volleyball.samples.volley.request.CompleteEntryRequest;
import com.siu.android.volleyball.samples.volley.request.SampleRequest;
import java.util.ArrayList;
import java.util.List; | package com.siu.android.volleyball.samples.activity;
public class CompleteRequestActivity extends Activity {
private ListView mListView; | private EntriesAdapter mEntriesAdapter; | 3 |
criticalmaps/criticalmaps-android | app/src/main/java/de/stephanlindauer/criticalmaps/handler/ShowGpxHandler.java | [
"public class App extends Application {\n\n private static AppComponent appComponent;\n\n public static AppComponent components() {\n return appComponent;\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n if (BuildConfig.DEBUG) {\n Timber.plant(new Timber.DebugTree());\n } else {\n Timber.plant(new NoOpTree());\n }\n\n appComponent = DaggerAppComponent.builder().app(this).build();\n }\n\n private static class NoOpTree extends Timber.Tree {\n @Override\n protected void log(int priority, String tag, @NotNull String message, Throwable t) {\n }\n }\n}",
"@Singleton\npublic class GpxModel {\n\n private String uri;\n private List<GpxTrack> tracks = new ArrayList<>();\n private List<GpxPoi> poiList = new ArrayList<>();\n\n @Inject\n public GpxModel() {\n }\n\n public String getUri() {\n return uri;\n }\n\n public void setUri(String uri) {\n this.uri = uri;\n }\n\n public List<GpxTrack> getTracks() {\n return tracks;\n }\n\n public void setTracks(List<GpxTrack> tracks) {\n this.tracks = tracks;\n }\n\n public List<GpxPoi> getPoiList() {\n return poiList;\n }\n\n public void setPoiList(List<GpxPoi> poiList) {\n this.poiList = poiList;\n }\n\n public void clear() {\n tracks.clear();\n poiList.clear();\n uri = null;\n }\n}",
"public class GpxTrack {\n\n private String name;\n private List<GeoPoint> waypoints;\n\n public GpxTrack(String name, List<GeoPoint> waypoints) {\n this.name = name;\n this.waypoints = waypoints;\n }\n\n public String getName() {\n return name;\n }\n\n public List<GeoPoint> getWaypoints() {\n return waypoints;\n }\n}",
"public interface SharedPrefsKeys {\n String PRIVACY_POLICY_ACCEPTED =\n BuildConfig.APPLICATION_ID + \".PRIVACY_POLICY_ACCEPTED\";\n String OSMDROID_BASE_PATH =\n BuildConfig.APPLICATION_ID + \".OSMDROID_BASE_PATH\";\n String OBSERVER_MODE_ACTIVE =\n BuildConfig.APPLICATION_ID + \".OBSERVER_MODE_ACTIVE\";\n String SHOW_ON_LOCKSCREEN =\n BuildConfig.APPLICATION_ID + \".SHOW_ON_LOCKSCREEN\";\n String KEEP_SCREEN_ON =\n BuildConfig.APPLICATION_ID + \".KEEP_SCREEN_ON\";\n String DISABLE_MAP_ROTATION =\n BuildConfig.APPLICATION_ID + \".DISABLE_MAP_ROTATION\";\n String USE_HIGH_RES_MAP_TILES =\n BuildConfig.APPLICATION_ID + \".USE_HIGH_RES_MAP_TILES\";\n String SHOW_GPX =\n BuildConfig.APPLICATION_ID + \".SHOW_GPX\";\n String GPX_FILE =\n BuildConfig.APPLICATION_ID + \".GPX_FILE\";\n}",
"public class GpxReader {\n\n private static final String ELEMENT_TRK = \"trk\";\n private static final String ELEMENT_NAME = \"name\";\n private static final String ELEMENT_TRKSEG = \"trkseg\";\n private static final String ELEMENT_TRKPT = \"trkpt\";\n private static final String ATTRIBUTE_LAT = \"lat\";\n private static final String ATTRIBUTE_LON = \"lon\";\n private static final String ELEMENT_ELE = \"ele\";\n private static final String ELEMENT_WPT = \"wpt\";\n\n private final GpxModel gpxModel;\n\n @Inject\n public GpxReader(GpxModel gpxModel) {\n this.gpxModel = gpxModel;\n }\n\n public void readDataFromStream(InputStream gpxInputStream, String uri) throws IOException, SAXException, ParserConfigurationException {\n gpxModel.clear();\n readGpxFile(gpxInputStream);\n gpxModel.setUri(uri);\n }\n\n private void readGpxFile(InputStream gpxInputStream) throws ParserConfigurationException, IOException, SAXException {\n DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();\n Document gpxDocument = documentBuilder.parse(gpxInputStream);\n Element gpxElement = gpxDocument.getDocumentElement();\n readTracks(gpxElement);\n readWaypoints(gpxElement);\n }\n\n private void readWaypoints(Element gpxElement) {\n NodeList wptList = gpxElement.getElementsByTagName(ELEMENT_WPT);\n for (int i = 0; i < wptList.getLength(); i++) {\n Element wpt = (Element) wptList.item(i);\n GeoPoint location = parsePoint(wpt);\n String pointName = parseName(wpt);\n gpxModel.getPoiList().add(new GpxPoi(pointName, location));\n }\n }\n\n private void readTracks(Element gpxElement) {\n NodeList trkList = gpxElement.getElementsByTagName(ELEMENT_TRK);\n for (int i = 0; i < trkList.getLength(); i++) {\n Element track = (Element) trkList.item(i);\n List<GeoPoint> trackPoints = getTrackPoints(track);\n String trackName = parseName(track);\n gpxModel.getTracks().add(new GpxTrack(trackName, trackPoints));\n }\n }\n\n @NotNull\n private List<GeoPoint> getTrackPoints(Element track) {\n List<GeoPoint> trackPoints = new ArrayList<>();\n NodeList trksegList = track.getElementsByTagName(ELEMENT_TRKSEG);\n for (int j = 0; j < trksegList.getLength(); j++) {\n Element trkseg = (Element) trksegList.item(j);\n NodeList trkptList = trkseg.getElementsByTagName(ELEMENT_TRKPT);\n for (int k = 0; k < trkptList.getLength(); k++) {\n Element trkpt = (Element) trkptList.item(k);\n trackPoints.add(parsePoint(trkpt));\n }\n }\n return trackPoints;\n }\n\n private String parseName(Element track) {\n NodeList nameList = track.getElementsByTagName(ELEMENT_NAME);\n if (nameList.getLength() > 0) {\n return nameList.item(0).getTextContent();\n }\n return null;\n }\n\n @NotNull\n private GeoPoint parsePoint(Element point) {\n GeoPoint newPoint;\n double lat = Double.parseDouble(point.getAttributes().getNamedItem(ATTRIBUTE_LAT).getNodeValue());\n double lon = Double.parseDouble(point.getAttributes().getNamedItem(ATTRIBUTE_LON).getNodeValue());\n\n NodeList eleList = point.getElementsByTagName(ELEMENT_ELE);\n if (eleList.getLength() > 0) {\n double ele = Double.parseDouble(eleList.item(0).getTextContent());\n newPoint = new GeoPoint(lat, lon, ele);\n } else {\n newPoint = new GeoPoint(lat, lon);\n }\n return newPoint;\n }\n\n}"
] | import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.widget.Toast;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.Marker;
import org.osmdroid.views.overlay.Polyline;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import javax.inject.Inject;
import javax.xml.parsers.ParserConfigurationException;
import de.stephanlindauer.criticalmaps.App;
import de.stephanlindauer.criticalmaps.R;
import de.stephanlindauer.criticalmaps.model.gpx.GpxModel;
import de.stephanlindauer.criticalmaps.model.gpx.GpxPoi;
import de.stephanlindauer.criticalmaps.model.gpx.GpxTrack;
import de.stephanlindauer.criticalmaps.prefs.SharedPrefsKeys;
import de.stephanlindauer.criticalmaps.utils.GpxReader;
import info.metadude.android.typedpreferences.BooleanPreference;
import info.metadude.android.typedpreferences.StringPreference; | package de.stephanlindauer.criticalmaps.handler;
public class ShowGpxHandler {
private final SharedPreferences sharedPreferences;
private final GpxModel gpxModel;
private final App app;
private final GpxReader gpxReader;
@Inject
public ShowGpxHandler(SharedPreferences sharedPreferences, GpxModel gpxModel, App app, GpxReader gpxReader) {
this.sharedPreferences = sharedPreferences;
this.gpxModel = gpxModel;
this.app = app;
this.gpxReader = gpxReader;
}
public void showGpx(MapView mapView) {
boolean showTrack = new BooleanPreference(sharedPreferences, SharedPrefsKeys.SHOW_GPX).get();
if (!showTrack) {
return;
}
String gpxUri = new StringPreference(sharedPreferences, SharedPrefsKeys.GPX_FILE).get();
if (gpxModel.getUri() == null || !gpxModel.getUri().equals(gpxUri)) {
readFile(gpxUri);
}
showModelOnMap(mapView);
}
private void readFile(String gpxUri) {
try {
InputStream gpxInputStream = app.getContentResolver().openInputStream(Uri.parse(gpxUri));
gpxReader.readDataFromStream(gpxInputStream, gpxUri);
} catch (SecurityException | IOException | SAXException | ParserConfigurationException e) {
Toast.makeText(app, R.string.gpx_reading_error, Toast.LENGTH_SHORT).show();
}
}
private void showModelOnMap(MapView mapView) { | for (GpxTrack track : gpxModel.getTracks()) { | 2 |
sarnowski/eve-api | cdi/src/main/java/org/onsteroids/eve/api/provider/eve/DefaultAllianceList.java | [
"public final class DateUtility {\n private static final Logger LOG = LoggerFactory.getLogger(DateUtility.class);\n\n // CCPs date scheme\n private static final DateFormat dateParser = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\n\n public static Date parse(String date) {\n\t try {\n\t\t return dateParser.parse(date);\n\t } catch (ParseException e) {\n\t\t throw new IllegalArgumentException(e);\n\t }\n }\n\n public static Date withTimeDifference(Date date, long timeDifference, TimeUnit timeDifferenceUnit) {\n return new Date(date.getTime() + timeDifferenceUnit.toMillis(timeDifference));\n }\n\n\tpublic static Date parse(String date, long timeDifference) {\n return withTimeDifference(parse(date), timeDifference, TimeUnit.MILLISECONDS);\n }\n\n\tpublic static Date parse(String date, long timeDifference, TimeUnit timeDifferenceUnit) {\n\t\treturn withTimeDifference(parse(date), timeDifference, timeDifferenceUnit);\n\t}\n\n}",
"public final class XmlUtility {\n\tprivate static final Logger LOG = LoggerFactory.getLogger(XmlUtility.class);\n\n\tprivate Node node;\n\n\tpublic XmlUtility(Node node) {\n\t\tthis.node = Preconditions.checkNotNull(node, \"Node\");\n\t}\n\n\n\tpublic Node getNodeByName(String name) {\n\t\treturn getNodeByName(name, node);\n\t}\n\n\tpublic static Node getNodeByName(String name, Node parent) {\n\t\tPreconditions.checkNotNull(name, \"Name\");\n\t\tPreconditions.checkNotNull(parent, \"Parent\");\n\t\tNodeList list = parent.getChildNodes();\n\t\tfor (int n = 0; n < list.getLength(); n++) {\n\t\t\tNode node = list.item(n);\n\t\t\tif (name.equals(node.getNodeName())) {\n\t\t\t\treturn node;\n\t\t\t}\n\t\t}\n\t\tthrow new IllegalArgumentException(\"Node \" + name + \" not found\");\n\t}\n\n\n\tpublic boolean hasNodeWithName(String name) {\n\t\treturn hasNodeWithName(name, node);\n\t}\n\n\tpublic static boolean hasNodeWithName(String name, Node parent) {\n\t\tPreconditions.checkNotNull(name, \"Name\");\n\t\tPreconditions.checkNotNull(parent, \"Parent\");\n\t\tNodeList list = parent.getChildNodes();\n\t\tfor (int n = 0; n < list.getLength(); n++) {\n\t\t\tNode node = list.item(n);\n\t\t\tif (name.equals(node.getNodeName())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\n\tpublic List<Node> getNodesByName(String name) {\n\t\treturn getNodesByName(name, node);\n\t}\n\n\tpublic static List<Node> getNodesByName(String name, Node parent) {\n\t\tPreconditions.checkNotNull(name, \"Name\");\n\t\tPreconditions.checkNotNull(parent, \"Parent\");\n\t\tList<Node> nodes = Lists.newArrayList();\n\t\tNodeList list = parent.getChildNodes();\n\t\tfor (int n = 0; n < list.getLength(); n++) {\n\t\t\tNode node = list.item(n);\n\t\t\tif (name.equals(node.getNodeName())) {\n\t\t\t\tnodes.add(node);\n\t\t\t}\n\t\t}\n\t\treturn nodes;\n\t}\n\n\n\tpublic String getContentOf(String nodeName) {\n\t\treturn getContentOf(nodeName, node);\n\t}\n\n\tpublic static String getContentOf(String nodeName, Node node) {\n\t\tPreconditions.checkNotNull(nodeName, \"nodeName\");\n\t\tPreconditions.checkNotNull(node, \"node\");\n\t\treturn getNodeByName(nodeName, node).getTextContent();\n\t}\n\n\n\tpublic String getAttribute(String name) {\n\t\treturn getAttribute(name, node);\n\t}\n\n\tpublic static String getAttribute(String name, Node node) {\n\t\tPreconditions.checkNotNull(name, \"Name\");\n\t\tPreconditions.checkNotNull(node, \"Node\");\n\t\tPreconditions.checkNotNull(node.getAttributes().getNamedItem(name), \"Attribute not found: \" + name);\n\t\treturn node.getAttributes().getNamedItem(name).getTextContent();\n\t}\n}",
"public interface XmlApiResult extends ApiResult {\n\n\t/**\n\t * @return returns the <result> node of the api response\n\t */\n\tNode getResult();\n \n /**\n * getTimeDifference = serverTime - localTime\n *\n * @return the time difference from server to local in milliseconds\n */\n long getTimeDifference();\n\n}",
"public abstract class SerializableApiListResult<S extends SerializableApiResult> extends SerializableApiResult implements ApiListResult<S> {\n\t// because java doesn't support multi inheritance we have to choose between SerializableApiResult and ForwardingList\n\t// from google collections. We want to be immutable and using all features of ApiResult which can change quite often\n\t// so we implement the forwarding, immutable list ourself.\n\n\tprivate static final Logger LOG = LoggerFactory.getLogger(SerializableApiListResult.class);\n\n\tprivate List<S> results;\n\n\n\tpublic SerializableApiListResult() {\n\t}\n\n\tpublic SerializableApiListResult(XmlApiResult xmlApiResult, Node xmlResult) throws ApiException {\n\t\tprocessCoreResult(xmlApiResult, xmlResult);\n\t}\n\n\t@Override\n\tpublic void processResult(XmlApiResult xmlApiResult, Node xmlResult) throws ApiException {\n\t\tList<S> results = Lists.newArrayList();\n\n\t\tClass<? extends S> definition = getRowDefinition();\n\n\t\tNode rowset = XmlUtility.getNodeByName(\"rowset\", xmlResult);\n\t\tList<Node> rows = XmlUtility.getNodesByName(\"row\", rowset);\n\t\tfor (Node row: rows) {\n\n\t\t\tS result;\n\t\t\ttry {\n\t\t\t\tresult = definition.newInstance();\n\t\t\t} catch (InstantiationException e) {\n\t\t\t\tthrow new InternalApiException(e);\n\t\t\t} catch (IllegalAccessException e) {\n\t\t\t\tthrow new InternalApiException(e);\n\t\t\t}\n\n\t\t\tresult.processCoreResult(xmlApiResult, row);\n\n\t\t\tresults.add(result);\n\t\t}\n\n\t\t// we cannot change the servers values, so we are immutable!\n\t\tthis.results = ImmutableList.copyOf(results);\n\t}\n\n\t/**\n\t * @return the class which defines the implementation\n\t */\n\tpublic abstract Class<? extends S> getRowDefinition();\n\n\n\t@Override\n\tpublic int size() {\n\t\treturn results.size();\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn results.isEmpty();\n\t}\n\n\t@Override\n\tpublic boolean contains(Object o) {\n\t\treturn results.contains(o);\n\t}\n\n\t@Override\n\tpublic Iterator<S> iterator() {\n\t\treturn results.iterator();\n\t}\n\n\t@Override\n\tpublic Object[] toArray() {\n\t\treturn results.toArray();\n\t}\n\n\t@Override\n\tpublic <T> T[] toArray(T[] a) {\n\t\treturn results.toArray(a);\n\t}\n\n\t@Override\n\tpublic boolean add(S t) {\n\t\treturn results.add(t);\n\t}\n\n\t@Override\n\tpublic boolean remove(Object o) {\n\t\treturn results.remove(o);\n\t}\n\n\t@Override\n\tpublic boolean containsAll(Collection<?> c) {\n\t\treturn results.containsAll(c);\n\t}\n\n\t@Override\n\tpublic boolean addAll(Collection<? extends S> c) {\n\t\treturn results.addAll(c);\n\t}\n\n\t@Override\n\tpublic boolean addAll(int index, Collection<? extends S> c) {\n\t\treturn results.addAll(index, c);\n\t}\n\n\t@Override\n\tpublic boolean removeAll(Collection<?> c) {\n\t\treturn results.removeAll(c);\n\t}\n\n\t@Override\n\tpublic boolean retainAll(Collection<?> c) {\n\t\treturn results.retainAll(c);\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\tresults.clear();\n\t}\n\n\t@Override\n\tpublic S get(int index) {\n\t\treturn results.get(index);\n\t}\n\n\t@Override\n\tpublic S set(int index, S element) {\n\t\treturn results.set(index, element);\n\t}\n\n\t@Override\n\tpublic void add(int index, S element) {\n\t\tresults.add(index, element);\n\t}\n\n\t@Override\n\tpublic S remove(int index) {\n\t\treturn results.remove(index);\n\t}\n\n\t@Override\n\tpublic int indexOf(Object o) {\n\t\treturn results.indexOf(o);\n\t}\n\n\t@Override\n\tpublic int lastIndexOf(Object o) {\n\t\treturn results.lastIndexOf(o);\n\t}\n\n\t@Override\n\tpublic ListIterator<S> listIterator() {\n\t\treturn results.listIterator();\n\t}\n\n\t@Override\n\tpublic ListIterator<S> listIterator(int index) {\n\t\treturn results.listIterator(index);\n\t}\n\n\t@Override\n\tpublic List<S> subList(int fromIndex, int toIndex) {\n\t\treturn results.subList(fromIndex, toIndex);\n\t}\n}",
"public abstract class SerializableApiResult implements ApiResult, Serializable {\n\n\tprivate Date created;\n\tprivate Date cachedUntil;\n private long timeDifference;\n\n\tprivate String requestedXmlPath;\n\tprivate ApiKey usedApiKey;\n\tprivate Map<String,String> usedParameters;\n\tprivate URI usedServerUri;\n\n\tpublic SerializableApiResult() {\n\t}\n\n\tpublic SerializableApiResult(XmlApiResult xmlApiResult, Node node) throws ApiException {\n\t\tprocessCoreResult(xmlApiResult, node);\n\t}\n\n\tvoid processCoreResult(XmlApiResult xmlApiResult, Node node) throws ApiException {\n\t\tPreconditions.checkNotNull(xmlApiResult, \"ApiResult\");\n\t\tPreconditions.checkNotNull(node, \"Node\");\n\n\t\tcreated = xmlApiResult.getDateCreated();\n\t\tcachedUntil = xmlApiResult.getCachedUntil();\n timeDifference = xmlApiResult.getTimeDifference();\n\t\trequestedXmlPath = xmlApiResult.getRequestedXmlPath();\n\t\tusedApiKey = xmlApiResult.getUsedApiKey();\n\t\tusedParameters = xmlApiResult.getUsedParameters();\n\t\tusedServerUri = xmlApiResult.getUsedServerUri();\n\n\t\tprocessResult(xmlApiResult, node);\n\t}\n\n\t/**\n\t * Processes the XML given by the api server.\n\t *\n\t * @param xmlResult the result node of an api response\n\t */\n\tpublic abstract void processResult(XmlApiResult xmlApiResult, Node xmlResult) throws ApiException;\n\n\t@Override\n\tpublic Date getDateCreated() {\n\t\treturn created;\n\t}\n\n\t@Override\n\tpublic Date getCachedUntil() {\n\t\treturn cachedUntil;\n\t}\n \n\tpublic long getTimeDifference() {\n\t\treturn timeDifference;\n\t}\n\n\t@Override\n\tpublic String getRequestedXmlPath() {\n\t\treturn requestedXmlPath;\n\t}\n\n\t@Override\n\tpublic ApiKey getUsedApiKey() {\n\t\treturn usedApiKey;\n\t}\n\n\t@Override\n\tpublic Map<String, String> getUsedParameters() {\n\t\treturn usedParameters;\n\t}\n\n\t@Override\n\tpublic URI getUsedServerUri() {\n\t\treturn usedServerUri;\n\t}\n}"
] | import com.eveonline.api.ApiListResult;
import com.eveonline.api.eve.AllianceList;
import com.eveonline.api.exceptions.ApiException;
import org.onsteroids.eve.api.DateUtility;
import org.onsteroids.eve.api.XmlUtility;
import org.onsteroids.eve.api.connector.XmlApiResult;
import org.onsteroids.eve.api.provider.SerializableApiListResult;
import org.onsteroids.eve.api.provider.SerializableApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import java.util.Date;
import java.util.concurrent.TimeUnit; | /**
* Copyright 2010 Tobias Sarnowski
*
* 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 org.onsteroids.eve.api.provider.eve;
/**
* @author Tobias Sarnowski
*/
public final class DefaultAllianceList extends SerializableApiListResult<DefaultAllianceList.DefaultAlliance> implements AllianceList<DefaultAllianceList.DefaultAlliance> {
private static final Logger LOG = LoggerFactory.getLogger(DefaultAllianceList.class);
@Override
public Class<? extends DefaultAlliance> getRowDefinition() {
return DefaultAlliance.class;
}
public static final class DefaultAlliance extends SerializableApiResult implements AllianceList.Alliance {
private long id;
private String name;
private String shortName;
private long executorCorporationId;
private int memberCount;
private Date startDate;
private SerializableApiListResult<DefaultAllianceList.CorporationImpl> corporations;
@Override | public void processResult(XmlApiResult xmlApiResult, Node xmlResult) throws ApiException { | 2 |
nullpointerexceptionapps/TeamCityDownloader | java/com/raidzero/teamcitydownloader/activities/settings/SettingsServerActivity.java | [
"public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks {\n\n private static final String tag = \"MainActivity\";\n\n public static AppHelper helper;\n\n private long lastBackPressTime = 0;\n\n private NavigationDrawerFragment mNavigationDrawerFragment;\n\n private AlarmManager alarmManager;\n private PendingIntent pendingIntent;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n ThemeUtility.setAppTheme(this);\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_main);\n\n int holoDialogTheme = ThemeUtility.getHoloDialogTheme(this);\n\n helper = ((AppHelper) getApplication());\n helper.setDialogTheme(holoDialogTheme);\n\n int versionCode = getVersionCode();\n helper.setCurrentVersionCode(versionCode);\n\n // first run?\n if (helper.isFirstRun()) {\n Debug.Log(tag, \"first run\");\n startActivity(new Intent(this, WelcomeActivity.class));\n }\n\n //Fragment managing the behaviors, interactions and presentation of the navigation drawer.\n mNavigationDrawerFragment = (NavigationDrawerFragment)\n getFragmentManager().findFragmentById(R.id.navigation_drawer);\n\n // Set up the drawer.\n mNavigationDrawerFragment.setUp(\n R.id.navigation_drawer,\n (DrawerLayout) findViewById(R.id.drawer_layout));\n\n alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);\n\n showHomeFragment();\n\n }\n\n @Override\n public void onResume() {\n ThemeUtility.setAppTheme(this);\n\n try {\n boolean isNonPlayAppAllowed = Settings.Secure.getInt(getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS) == 1;\n if (!isNonPlayAppAllowed) {\n Intent i = new Intent(this, UnknownSourcesActivity.class);\n startActivityForResult(i, Common.REQUEST_CODE_EXIT_APP);\n }\n } catch (Settings.SettingNotFoundException e) {\n // do nothing\n }\n\n // set up pending intent\n Intent notificationServiceIntent = new Intent(this, NotificationService.class);\n //startService(notificationServiceIntent);\n\n pendingIntent = PendingIntent.getService(this, 0, notificationServiceIntent, 0);\n alarmManager.cancel(pendingIntent);\n\n // set alarm for notifications if desired\n if (helper.getBoolPref(\"pref_enable_notifications\")) {\n // get interval\n long interval = helper.getCheckInterval();\n Debug.Log(tag, \"alarm interval: \" + interval);\n\n alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,\n SystemClock.elapsedRealtime() + interval, interval, pendingIntent);\n }\n\n super.onResume();\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n Debug.Log(tag, \"onActivityResult(\" + requestCode + \", \" + resultCode + \")\");\n\n if (requestCode == Common.REQUEST_CODE_EXIT_APP) {\n if (resultCode == RESULT_CANCELED) {\n finish();\n }\n }\n }\n\n @Override\n public void onNavigationDrawerItemSelected(NavigationMenuItem item) {\n if (item != null && item.getName() != null) {\n\n if (item.getName().equalsIgnoreCase(getString(R.string.your_projects))) {\n showHomeFragment();\n } else if (item.getName().equalsIgnoreCase(getString(R.string.settings_main_title))) {\n Intent settingsIntent = new Intent(this, SettingsMainActivity.class);\n startActivity(settingsIntent);\n } else if (item.getName().equalsIgnoreCase(getString(R.string.action_downloaded_files))) {\n Intent viewDownloadsIntent = new Intent(this, DownloadsListActivity.class);\n startActivity(viewDownloadsIntent);\n } else if (item.getName().equalsIgnoreCase(getString(R.string.title_about_server))) {\n Intent aboutServerIntent = new Intent(this, AboutServerActivity.class);\n startActivity(aboutServerIntent);\n } else if (item.getName().equalsIgnoreCase(getString(R.string.action_open_welcome))) {\n Intent welcomeIntent = new Intent(this, WelcomeActivity.class);\n welcomeIntent.putExtra(\"showQuickStart\", true);\n startActivity(welcomeIntent);\n } else {\n // favorite item\n TeamCityItem tcItem = (TeamCityItem) item.getObj();\n Intent i = new Intent(this, ControllerActivity.class);\n i.putExtra(\"gotoStarred\", true);\n i.putExtra(\"selectedBuildConfig\", tcItem);\n startActivity(i);\n }\n } else {\n Debug.Log(tag, \"Null item clicked\");\n }\n }\n\n @Override\n public void onBackPressed() {\n if (mNavigationDrawerFragment.isDrawerOpen()) {\n mNavigationDrawerFragment.hideDrawer();\n return;\n }\n\n if (isHomeFragment()) {\n // toast already home. one more press within 2 secs to exit\n if (lastBackPressTime < (System.currentTimeMillis() - 2000)) {\n lastBackPressTime = System.currentTimeMillis();\n DialogUtility.makeToast(this, getResources().getString(R.string.main_back_to_exit));\n } else {\n helper.clearResponseCache();\n finish();\n }\n } else {\n super.onBackPressed();\n }\n }\n\n private int getVersionCode() {\n int versionCode = 0;\n\n try {\n PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);\n versionCode = packageInfo.versionCode;\n } catch (Exception e) {\n Debug.Log(tag, \"Couldn't get package info\", e);\n }\n\n return versionCode;\n }\n\n public void showHomeFragment() {\n Fragment displayFragment = new ProjectsListFragment();\n\n FragmentManager fragmentManager = getFragmentManager();\n fragmentManager.beginTransaction()\n .replace(R.id.container, displayFragment, \"HOME_FRAGMENT\")\n .commit();\n\n setActionBarTitle(getResources().getString(R.string.title_main));\n }\n\n private boolean isHomeFragment() {\n Fragment f = getFragmentManager().findFragmentByTag(\"HOME_FRAGMENT\");\n return (f.isVisible());\n }\n\n // used by fragments to set navigation drawer selection highlight\n public void setNavItemSelection(int position) {\n if (mNavigationDrawerFragment != null) {\n mNavigationDrawerFragment.setSelectedItem(position);\n }\n }\n\n public void setActionBarTitle(String title) {\n getSupportActionBar().setTitle(title);\n }\n\n @Override\n public boolean onKeyDown(int keyCode, KeyEvent e) {\n if (keyCode == KeyEvent.KEYCODE_MENU) {\n\n mNavigationDrawerFragment.showDrawer();\n return true;\n }\n\n return super.onKeyDown(keyCode, e);\n }\n}",
"public class WebResponse {\n private String responseDocument;\n private StatusLine status;\n private String requestUrl;\n\n public WebResponse(StatusLine statusLine, String requestUrl, String response) {\n this.status = statusLine;\n this.requestUrl = requestUrl;\n this.responseDocument = response;\n }\n\n public int getStatusCode() {\n return this.status.getStatusCode();\n }\n\n public String getStatusReason(Context context) {\n // find the matching item in the web_response array\n String[] reasons = context.getResources().getStringArray(R.array.web_responses);\n\n for (String reason : reasons) {\n if (reason.startsWith(String.valueOf(status.getStatusCode()))) {\n return reason;\n }\n }\n\n return status.getReasonPhrase();\n }\n\n public void setReasonPhrase(final String reason) {\n final ProtocolVersion protoVersion = status.getProtocolVersion();\n final int statusCode = status.getStatusCode();\n\n status = new StatusLine() {\n @Override\n public ProtocolVersion getProtocolVersion() {\n return protoVersion;\n }\n\n @Override\n public int getStatusCode() {\n return statusCode;\n }\n\n @Override\n public String getReasonPhrase() {\n return reason;\n }\n };\n }\n\n public String getResponseDocument() {\n return this.responseDocument;\n }\n\n public String getRequestUrl() {\n return this.requestUrl;\n }\n}",
"public class SettingsFragmentServer extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {\n\n private static final String tag = \"SettingsFragmentServer\";\n\n PreferenceCategory credentials_category;\n EditTextPreference pref_serverAddress;\n CheckBoxPreference pref_use_guest;\n EditTextPreference pref_username;\n EditTextPreference pref_password;\n PreferenceScreen server_screen;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n // Load the preferences from an XML resource\n addPreferencesFromResource(R.xml.settings_server);\n\n credentials_category = (PreferenceCategory) findPreference(\"pref_key_credentials\");\n\n pref_serverAddress = (EditTextPreference) findPreference(\"pref_server_address\");\n pref_use_guest = (CheckBoxPreference) findPreference(\"pref_enable_guest\");\n pref_username = (EditTextPreference) findPreference(\"pref_server_username\");\n pref_password = (EditTextPreference) findPreference(\"pref_server_password\");\n\n server_screen = (PreferenceScreen) findPreference(\"pref_screen_server\");\n\n if (pref_use_guest.isChecked()) {\n server_screen.removePreference(credentials_category);\n }\n\n String serverAddress = pref_serverAddress.getText();\n String username = pref_username.getText();\n String password = pref_password.getText();\n\n if (serverAddress != null) {\n pref_serverAddress.setSummary(serverAddress);\n }\n\n if (username != null) {\n pref_username.setSummary(username);\n }\n\n if (password != null) {\n EditText edit = pref_password.getEditText();\n String maskedPassword = pref_password.getEditText().getTransformationMethod().getTransformation(password, edit).toString();\n pref_password.setSummary(maskedPassword);\n }\n }\n\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {\n\n // handle guest login option\n if (key.equals(\"pref_enable_guest\")) {\n server_screen = (PreferenceScreen) findPreference(\"pref_screen_server\");\n\n if (sharedPreferences.getBoolean(key, false)) {\n server_screen.removePreference(credentials_category);\n } else {\n server_screen.addPreference(credentials_category);\n }\n }\n\n // update summary of text preferences\n if (key.equals(\"pref_server_address\")) {\n String serverAddress = sharedPreferences.getString(\"pref_server_address\", \"\");\n\n // what if http prefix was left out?\n if (!serverAddress.isEmpty() && !serverAddress.startsWith(\"http\")) {\n serverAddress = \"http://\" + serverAddress;\n DialogUtility.makeToast(getActivity(), \"Notice: HTTP prefix automatically added\");\n }\n\n pref_serverAddress.setSummary(serverAddress);\n pref_serverAddress.setText(serverAddress);\n }\n\n if (key.equals(\"pref_server_username\")) {\n pref_username.setSummary(sharedPreferences.getString(\"pref_server_username\", \"\"));\n }\n\n if (key.equals(\"pref_server_password\")) {\n String newPassword = sharedPreferences.getString(\"pref_server_password\", \"\");\n\n EditText edit = pref_password.getEditText();\n String maskedPassword = pref_password.getEditText().getTransformationMethod().getTransformation(newPassword, edit).toString();\n pref_password.setSummary(maskedPassword);\n }\n\n // broadcast this event\n Debug.Log(tag, \"broadcasting intent to refresh server data\");\n Intent i = new Intent(Common.INTENT_SERVER_UPDATE);\n getActivity().sendBroadcast(i);\n }\n\n @Override\n public void onResume() {\n ThemeUtility.setAppTheme(getActivity());\n super.onResume();\n\n getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n public void onPause() {\n getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);\n super.onPause();\n }\n\n @Override\n public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {\n\n // test server\n if (preference.getKey().equals(\"pref_test_connection\")) {\n ((SettingsServerActivity) getActivity()).testConnection();\n }\n\n return super.onPreferenceTreeClick(preferenceScreen, preference);\n }\n}",
"public class DialogUtility {\n public static final String tag = \"DialogUtility\";\n\n public static void showAlert(Context context, String title, String message) {\n int dialogTheme = ThemeUtility.getHoloDialogTheme(context);\n\n AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(context, dialogTheme));\n\n builder.setTitle(title);\n builder.setMessage(message);\n\n AlertDialog dialog = builder.create();\n dialog.show();\n }\n\n public static void showAlertWithButton(Context context, String title, String message, DialogInterface.OnClickListener clickListener) {\n int dialogTheme = ThemeUtility.getHoloDialogTheme(context);\n\n AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(context, dialogTheme));\n\n builder.setTitle(title);\n builder.setMessage(message);\n builder.setPositiveButton(context.getResources().getString(android.R.string.ok), clickListener);\n\n AlertDialog dialog = builder.create();\n dialog.show();\n }\n\n public static void makeToast(Context context, String msg) {\n Toast toast;\n // use getApplicationContext so the toast is styled as default even when on the light theme\n toast = Toast.makeText(context.getApplicationContext(), msg, Toast.LENGTH_SHORT);\n toast.show();\n }\n}",
"public class QueryUtility implements TeamCityTask.OnWebRequestCompleteListener {\n private static final String tag = \"QueryUtility\";\n private Context context;\n private AppHelper helper;\n private String query;\n private TeamCityServer server;\n private QueryCallbacks callbacks;\n private boolean isQuerying;\n private boolean onSettingsScreen;\n\n // interface\n public interface QueryCallbacks {\n void onQueryComplete(WebResponse response);\n void startSpinning();\n void stopSpinning();\n void setActivityTitle(String title);\n }\n\n // constructor\n public QueryUtility(Context context, String query) {\n this.context = context;\n this.query = query;\n\n helper = (AppHelper) context.getApplicationContext();\n server = helper.getTcServer();\n\n callbacks = (QueryCallbacks) context;\n }\n\n public boolean isQuerying() {\n return isQuerying;\n }\n\n public void setQuery(String url) {\n this.query = url;\n }\n\n public void setOnSettingsScreen(boolean b) {\n onSettingsScreen = b;\n }\n\n public void queryServer(boolean forceRefresh) {\n Debug.Log(tag, \"queryServer(\" + query + \")...\");\n\n // refresh button\n if (forceRefresh) {\n Debug.Log(tag, \"forcing query for \" + query);\n // clear this cached request\n helper.removeReponseFromCache(query);\n\n runTask(query);\n return;\n }\n\n // see if we have cached this request\n WebResponse cachedResponse = helper.getResponseFromCache(query);\n\n if (cachedResponse != null) {\n if (cachedResponse.getResponseDocument() != null) {\n Debug.Log(tag, \"got cached response for queryUrl \" + query);\n\n // invoke listener with cached response\n onWebRequestComplete(cachedResponse);\n return;\n }\n }\n\n // if we got here there is no cached response\n runTask(query);\n }\n\n private void runTask(String queryUrl) {\n isQuerying = true;\n Debug.Log(tag, \"runTask on query \" + queryUrl);\n Debug.Log(tag, \"server is null? \" + (server == null));\n callbacks.startSpinning();\n callbacks.setActivityTitle(context.getString(R.string.querying));\n\n if (server != null) {\n // run task\n server.setContext(this);\n server.setOnSettingsScreen(onSettingsScreen);\n TeamCityTask task = server.getRequestTask(queryUrl);\n task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);\n } else {\n TeamCityServer.serverMisconfigured(context, onSettingsScreen);\n if (onSettingsScreen) {\n SettingsServerActivity.querying = false;\n }\n\n callbacks.stopSpinning();\n }\n }\n\n @Override\n public void onWebRequestComplete(WebResponse response) {\n Debug.Log(tag, \"onWebRequestComplete\");\n callbacks.stopSpinning();\n isQuerying = false;\n callbacks.onQueryComplete(response);\n }\n}",
"public class ThemeUtility {\n private static final String tag = \"ThemeUtility\";\n\n public static void setAppTheme(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String themeName = prefs.getString(\"theme\", \"\");\n\n // if it doesnt exist in prefs, create it, as dark\n if (prefs.getString(\"theme\", \"\").isEmpty()) {\n SharedPreferences.Editor editor = prefs.edit();\n editor.putString(\"theme\", \"dark\");\n editor.apply();\n themeName = \"dark\";\n }\n\n if (themeName.equalsIgnoreCase(\"light\")) {\n context.setTheme(R.style.Light);\n } else {\n context.setTheme(R.style.Dark);\n }\n }\n\n public static int getDialogActivityTheme(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n String themeName = prefs.getString(\"theme\", \"\");\n\n // if it doesnt exist in prefs, create it, as dark\n if (prefs.getString(\"theme\", \"\").isEmpty()) {\n SharedPreferences.Editor editor = prefs.edit();\n editor.putString(\"theme\", \"dark\");\n editor.apply();\n themeName = \"dark\";\n }\n\n if (themeName.equalsIgnoreCase(\"light\")) {\n return R.style.LightDialogActivity;\n } else {\n return R.style.DarkDialogActivity;\n }\n }\n public static int getThemeId(Context context) {\n TypedValue outValue = new TypedValue();\n context.getTheme().resolveAttribute(R.attr.themeName, outValue, true);\n if (\"Dark\".equals(outValue.string)) {\n return R.style.Dark;\n } else {\n return R.style.Light;\n }\n }\n\n public static int getHoloDialogTheme(Context context) {\n if (getThemeId(context) == R.style.Dark) {\n Debug.Log(tag, \"returning dark theme\");\n return AlertDialog.THEME_HOLO_DARK;\n } else {\n Debug.Log(tag, \"returning light theme\");\n return AlertDialog.THEME_HOLO_LIGHT;\n }\n }\n\n public static Drawable getThemedDrawable(Context context, int resId) {\n TypedArray a = context.getTheme().obtainStyledAttributes(getThemeId(context), new int[]{resId});\n\n if (a != null) {\n int attributeResourceId = a.getResourceId(0, 0);\n return context.getResources().getDrawable(attributeResourceId);\n }\n\n return null;\n }\n\n public static int getThemedColor(Context context, int resId) {\n TypedArray a = context.getTheme().obtainStyledAttributes(getThemeId(context), new int[]{resId});\n\n if (a != null) {\n int attributeResourceId = a.getResourceId(0, 0);\n return context.getResources().getColor(attributeResourceId);\n }\n\n return -1;\n }\n}"
] | import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import com.raidzero.teamcitydownloader.R;
import com.raidzero.teamcitydownloader.activities.MainActivity;
import com.raidzero.teamcitydownloader.data.WebResponse;
import com.raidzero.teamcitydownloader.fragments.settings.SettingsFragmentServer;
import com.raidzero.teamcitydownloader.global.DialogUtility;
import com.raidzero.teamcitydownloader.global.QueryUtility;
import com.raidzero.teamcitydownloader.global.ThemeUtility; | package com.raidzero.teamcitydownloader.activities.settings;
/**
* Created by raidzero on 1/11/15.
*/
public class SettingsServerActivity extends ActionBarActivity implements QueryUtility.QueryCallbacks {
private QueryUtility queryUtility;
private boolean cameFromError;
private ProgressDialog progDialog;
public static boolean querying = false;
@Override
public void onCreate(Bundle savedInstanceState) {
ThemeUtility.setAppTheme(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
cameFromError = getIntent().getBooleanExtra("cameFromError", false);
getFragmentManager().beginTransaction().replace(R.id.frameLayout_settings,
new SettingsFragmentServer()).commit();
progDialog = new ProgressDialog(this, ThemeUtility.getHoloDialogTheme(this));
progDialog.setIndeterminate(true);
progDialog.setMessage(getString(R.string.querying_please_wait));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (cameFromError) { | Intent i = new Intent(getApplicationContext(), MainActivity.class); | 0 |