answer stringlengths 17 10.2M |
|---|
package io.robusta.rra.controller;
import io.robusta.rra.representation.Representation;
import io.robusta.rra.representation.Rra;
import io.robusta.rra.security.implementation.CodecException;
import io.robusta.rra.security.implementation.CodecImpl;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
public class JaxRsController {
public static Representation defaultRepresentation = Rra.defaultRepresentation;
@Context
HttpHeaders httpHeader;
@Context
UriInfo uriInfo;
@Context
Response response;
@Context
Request request;
public HttpHeaders getHttpHeader() {
return httpHeader;
}
public UriInfo getUriInfo() {
return uriInfo;
}
public MultivaluedMap<String, String> getHeaders() {
return getHttpHeader().getRequestHeaders();
}
public boolean isJsonApplication() {
List<String> type = getHeaders().get( "content-type" );
return ( type.get( 0 ) != null && type.get( 0 ).equals( "application/json" ) );
}
public boolean isSecure( UriInfo uriInfo ) {
return uriInfo.getAbsolutePath().toString().contains( "https" );
}
public String[] getBasicAuthentification() {
String[] values = new String[2];
List<String> authorization = getHeaders().get( "authorization" );
if ( authorization.get( 0 ) != null && authorization.get( 0 ).startsWith( "Basic" ) ) {
String base64Credentials = authorization.get( 0 ).substring( "Basic".length() ).trim();
CodecImpl codecimpl = new CodecImpl();
try {
values[0] = codecimpl.getUsername( base64Credentials );
values[1] = codecimpl.getPassword( base64Credentials );
} catch ( CodecException e ) {
e.printStackTrace();
}
}
return values;
}
public Response getBasicAuthentificationResponse() {
if ( !isSecure( getUriInfo() ) ) {
return response
.status( 401 )
.entity(
"<a href='http://docs.oracle.com/javaee/5/tutorial/doc/bnbxw.html'>Establishing a Secure Connection Using SSL</a>" )
.build();
} else
return response.status( 200 ).entity( "The authentification is secure !" ).build();
}
protected void throwIfNull( Representation representation ) throws ControllerException {
if ( representation == null ) {
throw new ControllerException( "Representation is null" );
}
}
public Representation getRepresentation( String requestEntity ) {
return defaultRepresentation.createNewRepresentation( getRequestEntity( requestEntity ) );
}
public boolean validate( String requestEntity, String... keys ) {
Representation representation = getRepresentation( requestEntity );
throwIfNull( representation );
return representation.has( keys );
}
public Response validateResponse( String requestEntity, String... keys ) {
if ( !validate( requestEntity, keys ) ) {
return response.status( 406 ).entity( "Json representation is not valid !" ).build();
} else
return response.status( 200 ).entity( requestEntity ).build();
}
public String getRequestEntity( String requestEntity ) {
return requestEntity;
}
public List<String> getUserAgent() {
return getHeaders().get( "user-agent" );
}
public boolean isChrome() {
return getUserAgent().get( 0 ).toUpperCase().contains( "CHROME" );
}
public boolean isFirefox() {
return getUserAgent().get( 0 ).toUpperCase().contains( "FIREFOX" );
}
public boolean isTablet() {
return getUserAgent().get( 0 ).toUpperCase().contains( "TABLET" )
|| getUserAgent().get( 0 ).toUpperCase().contains( "IPAD" );
}
public boolean isMobile() {
return getUserAgent().get( 0 ).toUpperCase().contains( "MOBILE" );
}
} |
package io.swagger.api;
import io.swagger.model.ErrorBody;
import io.swagger.model.RegistryEntry;
import io.swagger.model.RegistryEntryList;
import io.swagger.annotations.*;
import org.apache.catalina.connector.Response;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.net.HttpHeaders;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-09-22T00:15:19.505Z")
@Controller
public class RegistryEntryApiController implements RegistryEntryApi {
//this static variable will be used in lieu of database solution.
private static final RegistryEntryList entries = new RegistryEntryList();
private static long id = 0;
public RegistryEntryApiController(){
int ttlcnt = 0;
for(long i=1;i<6;i++){
ttlcnt++;
id++;
RegistryEntry entry = new RegistryEntry();
entry.setId(id);
entry.setName("Test Name" + i);
entry.setValue("test value" + i);
entry.setScope("/Scope" + i);
entry.setConfidential(true);
entries.addListItem(entry);
for(int j = 1; j<5; j++){
for(int k = 1; k<14; k++){
ttlcnt++;
id++;
RegistryEntry entrysub = new RegistryEntry();
entrysub.setId(id);
entrysub.setName("Test Name" + k);
entrysub.setValue("test value" + j);
entrysub.setScope("/Scope" + i + "/Subscope" + j);
entrysub.setConfidential(false);
entries.addListItem(entrysub);
}
}
}
entries.setTotalCount(ttlcnt);
}
public ResponseEntity<RegistryEntry> addRegistryEntry(
@ApiParam(value = "" ) @RequestBody RegistryEntry body
) {
id++;
if(body.getName() == null || body.getName().isEmpty()) return new ResponseEntity<RegistryEntry>(HttpStatus.BAD_REQUEST);
if(entries.EntryExists(body.getScope(),body.getName()))return new ResponseEntity<RegistryEntry>(HttpStatus.CONFLICT);
RegistryEntry entry = new RegistryEntry();
entry.setId(id);
entry.setName(body.getName());
entry.setValue(body.getValue());
entry.setScope(body.getScope());
entry.setConfidential(body.getConfidential());
entries.addListItem(entry);
return new ResponseEntity<RegistryEntry>(entry,HttpStatus.OK);
}
public ResponseEntity<RegistryEntryList> addUpdateRegistryEntries(
@ApiParam(value = "" ) @RequestBody RegistryEntryList body
) {
for(RegistryEntry entry : body.getList()){
id++;
entry.setId(id);
entries.addListItem(entry);
}
return new ResponseEntity<RegistryEntryList>(body,HttpStatus.OK);
}
public ResponseEntity<Void> deleteRegistryEntries(
@ApiParam(value = "",required=true ) @PathVariable("id") String id
) {
String[] ids = id.split(",");
List<RegistryEntry> entrieslist = entries.getList();
for(int i = 0; i<ids.length;i++){
long deleteId = Long.parseLong(ids[i]);
for(RegistryEntry entry : entrieslist){
long entryid = entry.getId();
if(entryid == deleteId){
entrieslist.remove(entry);
break;
}
}
}
return new ResponseEntity<Void>(HttpStatus.OK);
}
public ResponseEntity<RegistryEntry> getRegistryEntry(
@ApiParam(value = "",required=true ) @PathVariable("id") String id
) {
// assigned to Yifei
RegistryEntry entry = new RegistryEntry();
entry.setConfidential(true);
entry.setId((long) 20);
entry.setName("gwy");
entry.setValue("test");
entry.setScope("test");
ResponseEntity<RegistryEntry> reEnt = new ResponseEntity<RegistryEntry>(entry,HttpStatus.OK);
return reEnt;
}
public ResponseEntity<RegistryEntryList> searchRegistryEntries(@ApiParam(value = "", defaultValue = "*") @RequestParam(value = "scope", required = false, defaultValue="*") String scope
,
@ApiParam(value = "", defaultValue = "*") @RequestParam(value = "name", required = false, defaultValue="*") String name
,
@ApiParam(value = "", defaultValue = "*") @RequestParam(value = "confidential", required = false, defaultValue="*") String confidential
,
@ApiParam(value = "", defaultValue = "*") @RequestParam(value = "value", required = false, defaultValue="*") String value
,
@ApiParam(value = "", defaultValue = "false") @RequestParam(value = "useInheritance", required = false, defaultValue="false") Boolean useInheritance
,
@ApiParam(value = "", defaultValue = "100") @RequestParam(value = "count", required = false, defaultValue="100") Integer count
,
@ApiParam(value = "", defaultValue = "0") @RequestParam(value = "offset", required = false, defaultValue="0") Integer offset
,
@ApiParam(value = "", defaultValue = "false") @RequestParam(value = "matchCase", required = false, defaultValue="false") Boolean matchCase
) {
//assigned to Richard
//this feature is broken so we probably won't use.
RegistryEntryList filteredList = new RegistryEntryList();
List<RegistryEntry> mainlist = entries.getList();
int ttlcount = 0;
for(RegistryEntry entry : mainlist){
int caseSensitivityFlags = matchCase==false?Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE:0;
Pattern nameRE;
nameRE = Pattern.compile("^" + name.replaceAll("[*]", ".*") + "$",caseSensitivityFlags);
Matcher namematcher = nameRE.matcher(entry.getName());
Pattern scopeRE = Pattern.compile("^" + scope.replaceAll("[*]", ".*") + "$",caseSensitivityFlags);
Matcher scopematcher = scopeRE.matcher(entry.getScope());
Pattern valueRE = Pattern.compile("^" + value.replaceAll("[*]", ".*") + "$",caseSensitivityFlags);
Matcher valuematcher = valueRE.matcher(entry.getValue());
if(namematcher.find() && valuematcher.find() && scopematcher.find()){
ttlcount++;
boolean onlyConfidential = confidential.equals("true");
boolean showEntry = (onlyConfidential && entry.getConfidential() == true);
showEntry = onlyConfidential != true?true:showEntry;
//Boolean ?true:entry.getConfidential();
if(showEntry == true){
filteredList.addListItem(entry);
}
}
/*
if((name.equals("*") || entry.getName().equals(name) ) &&
(scope.equals("*") || entry.getScope().equals(scope)) &&
(value.equals("*") || entry.getValue().equals(value) )
){
ttlcount++;
filteredList.addListItem(entry);
}
*/
}
List<RegistryEntry> offsetlist = filteredList.getList();
if(offset>0) offsetlist.subList(0, offset).clear();
int size = offsetlist.size();
if(count <= size)
offsetlist.subList(count, offsetlist.size()).clear();
filteredList.setList(offsetlist);
filteredList.setTotalCount(ttlcount);
return new ResponseEntity<RegistryEntryList>(filteredList, HttpStatus.OK);
}
public ResponseEntity<RegistryEntry> updateRegistryEntry(
@ApiParam(value = "",required=true ) @PathVariable("id") String id
,
@ApiParam(value = "" ) @RequestBody RegistryEntry body
) {
List<RegistryEntry> entrieslist = entries.getList();
for(RegistryEntry entry : entrieslist){
long entryid = entry.getId();
if(Long.parseLong(id) == entryid){
entry.setConfidential(body.getConfidential());
entry.setName(body.getName());
entry.setScope(body.getScope());
entry.setValue(body.getValue());
return new ResponseEntity<RegistryEntry>(entry,HttpStatus.OK);
}
}
//assigned to CK, Snefa
return new ResponseEntity<RegistryEntry>(HttpStatus.OK);
}
} |
package mcjty.rftools.blocks.builder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import mcjty.lib.varia.Logging;
import mcjty.rftools.GeneralConfiguration;
import mcjty.rftools.RFTools;
import mcjty.rftools.blocks.ModBlocks;
import mcjty.rftools.crafting.PreservingShapedRecipe;
import mcjty.rftools.items.ModItems;
import mcjty.rftools.items.builder.ShapeCardItem;
import mcjty.rftools.items.builder.SpaceChamberCardItem;
import mcjty.rftools.proxy.CommonProxy;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class BuilderSetup {
public static SpaceChamberBlock spaceChamberBlock;
public static SpaceChamberControllerBlock spaceChamberControllerBlock;
public static BuilderBlock builderBlock;
public static SupportBlock supportBlock;
public static SpaceChamberCardItem spaceChamberCardItem;
public static ShapeCardItem shapeCardItem;
private static Map<String,BlockInformation> blockInformationMap = new HashMap<String, BlockInformation>();
public static void init() {
spaceChamberBlock = new SpaceChamberBlock();
spaceChamberControllerBlock = new SpaceChamberControllerBlock();
builderBlock = new BuilderBlock();
supportBlock = new SupportBlock();
initItems();
readBuilderBlocksInternal();
readBuilderBlocksConfig();
}
@SideOnly(Side.CLIENT)
public static void initClient() {
spaceChamberBlock.initModel();
spaceChamberControllerBlock.initModel();
builderBlock.initModel();
supportBlock.initModel();
spaceChamberCardItem.initModel();
shapeCardItem.initModel();
}
private static void initItems() {
spaceChamberCardItem = new SpaceChamberCardItem();
shapeCardItem = new ShapeCardItem();
}
public static void initCrafting() {
Block redstoneTorch = Blocks.redstone_torch;
ItemStack lapisStack = new ItemStack(Items.dye, 1, 4);
ItemStack inkSac = new ItemStack(Items.dye, 1, 0);
GameRegistry.addRecipe(new ItemStack(spaceChamberBlock), "lgl", "gMg", "lgl", 'M', ModBlocks.machineFrame, 'g', Blocks.glass, 'l', lapisStack);
GameRegistry.addRecipe(new ItemStack(spaceChamberControllerBlock), " e ", "tMt", " e ", 'M', spaceChamberBlock, 't', redstoneTorch, 'e', Items.ender_pearl);
if (GeneralConfiguration.enableBuilderRecipe) {
GameRegistry.addRecipe(new ItemStack(builderBlock), "beb", "rMr", "brb", 'M', ModBlocks.machineFrame, 'e', Items.ender_pearl, 'r', Items.redstone, 'b', Blocks.brick_block);
}
GameRegistry.addRecipe(new ItemStack(spaceChamberCardItem), " b ", "rir", " b ", 'r', Items.redstone, 'i', Items.iron_ingot,
'b', Items.brick);
if (BuilderConfiguration.shapeCardAllowed) {
GameRegistry.addRecipe(new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_SHAPE), "pbp", "rir", "pbp", 'r', Items.redstone, 'i', Items.iron_ingot,
'b', Items.brick, 'p', Items.paper);
if (BuilderConfiguration.quarryAllowed) {
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[]{
inkSac, new ItemStack(Blocks.obsidian), inkSac,
new ItemStack(Blocks.obsidian), new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_SHAPE), new ItemStack(Blocks.obsidian),
inkSac, new ItemStack(Blocks.obsidian), inkSac
}, new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_VOID), 4));
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[]{
new ItemStack(Items.redstone), new ItemStack(Items.diamond_pickaxe), new ItemStack(Items.redstone),
new ItemStack(Items.iron_ingot), new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_SHAPE), new ItemStack(Items.iron_ingot),
new ItemStack(Items.redstone), new ItemStack(Items.diamond_shovel), new ItemStack(Items.redstone)
}, new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY), 4));
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[]{
new ItemStack(ModItems.dimensionalShardItem), new ItemStack(Items.nether_star), new ItemStack(ModItems.dimensionalShardItem),
new ItemStack(Items.diamond), new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY), new ItemStack(Items.diamond),
new ItemStack(ModItems.dimensionalShardItem), new ItemStack(Items.diamond), new ItemStack(ModItems.dimensionalShardItem)
}, new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY_SILK), 4));
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[]{
new ItemStack(ModItems.dimensionalShardItem), new ItemStack(Items.ghast_tear), new ItemStack(ModItems.dimensionalShardItem),
new ItemStack(Items.emerald), new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY), new ItemStack(Items.diamond),
new ItemStack(ModItems.dimensionalShardItem), new ItemStack(Items.redstone), new ItemStack(ModItems.dimensionalShardItem)
}, new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY_FORTUNE), 4));
if (BuilderConfiguration.clearingQuarryAllowed) {
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[]{
new ItemStack(Blocks.glass), new ItemStack(Blocks.glass), new ItemStack(Blocks.glass),
new ItemStack(Blocks.glass), new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY), new ItemStack(Blocks.glass),
new ItemStack(Blocks.glass), new ItemStack(Blocks.glass), new ItemStack(Blocks.glass)
}, new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY_CLEAR), 4));
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[]{
new ItemStack(Blocks.glass), new ItemStack(Blocks.glass), new ItemStack(Blocks.glass),
new ItemStack(Blocks.glass), new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY_SILK), new ItemStack(Blocks.glass),
new ItemStack(Blocks.glass), new ItemStack(Blocks.glass), new ItemStack(Blocks.glass)
}, new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY_CLEAR_SILK), 4));
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[]{
new ItemStack(Blocks.glass), new ItemStack(Blocks.glass), new ItemStack(Blocks.glass),
new ItemStack(Blocks.glass), new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY_FORTUNE), new ItemStack(Blocks.glass),
new ItemStack(Blocks.glass), new ItemStack(Blocks.glass), new ItemStack(Blocks.glass)
}, new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY_CLEAR_FORTUNE), 4));
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[]{
new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt),
new ItemStack(Blocks.dirt), new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY_CLEAR), new ItemStack(Blocks.dirt),
new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt)
}, new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY), 4));
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[]{
new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt),
new ItemStack(Blocks.dirt), new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY_CLEAR_SILK), new ItemStack(Blocks.dirt),
new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt)
}, new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY_SILK), 4));
GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[]{
new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt),
new ItemStack(Blocks.dirt), new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY_CLEAR_FORTUNE), new ItemStack(Blocks.dirt),
new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt), new ItemStack(Blocks.dirt)
}, new ItemStack(shapeCardItem, 1, ShapeCardItem.CARD_QUARRY_FORTUNE), 4));
}
}
}
}
private static void readBuilderBlocksInternal() {
try {
InputStream inputstream = RFTools.class.getResourceAsStream("/assets/rftools/text/builder.json");
parseBuilderJson(inputstream);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void readBuilderBlocksConfig() {
File modConfigDir = CommonProxy.modConfigDir;
try {
File file = new File(modConfigDir.getPath() + File.separator + "rftools", "userbuilder.json");
FileInputStream inputstream = new FileInputStream(file);
parseBuilderJson(inputstream);
} catch (IOException e) {
Logging.log("Could not read 'userbuilder.json', this is not an error!");
}
}
private static void parseBuilderJson(InputStream inputstream) throws UnsupportedEncodingException {
BufferedReader br = new BufferedReader(new InputStreamReader(inputstream, "UTF-8"));
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(br);
for (Map.Entry<String, JsonElement> entry : element.getAsJsonObject().entrySet()) {
if ("movables".equals(entry.getKey())) {
readMovablesFromJson(entry.getValue());
} else if ("rotatables".equals(entry.getKey())) {
readRotatablesFromJson(entry.getValue());
}
}
}
private static void readMovablesFromJson(JsonElement element) {
for (JsonElement entry : element.getAsJsonArray()) {
String blockName = entry.getAsJsonArray().get(0).getAsString();
String warningType = entry.getAsJsonArray().get(1).getAsString();
double costFactor = entry.getAsJsonArray().get(2).getAsDouble();
int status;
if ("-".equals(warningType)) {
status = SupportBlock.STATUS_ERROR;
} else if ("+".equals(warningType)) {
status = SupportBlock.STATUS_OK;
} else {
status = SupportBlock.STATUS_WARN;
}
BlockInformation old = blockInformationMap.get(blockName);
if (old == null) {
old = BlockInformation.OK;
}
blockInformationMap.put(blockName, new BlockInformation(old, blockName, status, costFactor));
}
}
private static void readRotatablesFromJson(JsonElement element) {
for (JsonElement entry : element.getAsJsonArray()) {
String blockName = entry.getAsJsonArray().get(0).getAsString();
String rotatable = entry.getAsJsonArray().get(1).getAsString();
BlockInformation old = blockInformationMap.get(blockName);
if (old == null) {
old = BlockInformation.OK;
}
blockInformationMap.put(blockName, new BlockInformation(old, rotatable));
}
}
public static BlockInformation getBlockInformation(Block block) {
return blockInformationMap.get(block.getRegistryName());
}
public static class BlockInformation {
private final String blockName;
private final int blockLevel; // One of SupportBlock.SUPPORT_ERROR/WARN
private final double costFactor;
private final int rotateInfo;
public static final int ROTATE_invalid = -1;
public static final int ROTATE_mmmm = 0;
public static final int ROTATE_mfff = 1;
public static final BlockInformation INVALID = new BlockInformation("", SupportBlock.STATUS_ERROR, 1.0);
public static final BlockInformation OK = new BlockInformation("", SupportBlock.STATUS_OK, 1.0, ROTATE_mmmm);
public static final BlockInformation FREE = new BlockInformation("", SupportBlock.STATUS_OK, 0.0, ROTATE_mmmm);
private static int rotateStringToId(String rotateString) {
if ("mmmm".equals(rotateString)) {
return ROTATE_mmmm;
} else if ("mfff".equals(rotateString)) {
return ROTATE_mfff;
} else {
return ROTATE_invalid;
}
}
public BlockInformation(String blockName, int blockLevel, double costFactor) {
this.blockName = blockName;
this.blockLevel = blockLevel;
this.costFactor = costFactor;
this.rotateInfo = ROTATE_mmmm;
}
public BlockInformation(String blockName, int blockLevel, double costFactor, int rotateInfo) {
this.blockName = blockName;
this.blockLevel = blockLevel;
this.costFactor = costFactor;
this.rotateInfo = rotateInfo;
}
public BlockInformation(BlockInformation other, String rotateInfo) {
this(other.blockName, other.blockLevel, other.costFactor, rotateStringToId(rotateInfo));
}
public BlockInformation(BlockInformation other, String blockName, int blockLevel, double costFactor) {
this(blockName, blockLevel, costFactor, other.rotateInfo);
}
public int getBlockLevel() {
return blockLevel;
}
public String getBlockName() {
return blockName;
}
public double getCostFactor() {
return costFactor;
}
public int getRotateInfo() {
return rotateInfo;
}
}
} |
package mesosphere.marathon.client;
import mesosphere.marathon.client.utils.ModelUtils;
import feign.Feign;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
public class MarathonClient {
static class MarathonHeadersInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
template.header("Accept", "application/json");
template.header("Content-Type", "application/json");
}
}
public static Marathon getInstance(String endpoint) {
GsonDecoder decoder = new GsonDecoder(ModelUtils.GSON);
GsonEncoder encoder = new GsonEncoder(ModelUtils.GSON);
return Feign.builder().encoder(encoder).decoder(decoder)
.requestInterceptor(new MarathonHeadersInterceptor())
.target(Marathon.class, endpoint);
}
} |
package net.finmath.marketdata.model.curves;
import java.io.Serializable;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Vector;
import net.finmath.interpolation.RationalFunctionInterpolation;
import net.finmath.marketdata.model.AnalyticModelInterface;
/**
* This class represents a curve build from a set of points in 2D.
* It provides different interpolation and extrapolation methods applied to a transformation of the input point,
* examples are
* <ul>
* <li>linear interpolation of the input points</li>
* <li>linear interpolation of the log of the input points</li>
* <li>linear interpolation of the log of the input points divided by their respective time</li>
* <li>cubic spline of the input points</li>
* <li>etc.</li>
* </ul>
* For the interpolation methods provided see {@link net.finmath.marketdata.model.curves.Curve.InterpolationMethod}.
* For the extrapolation methods provided see {@link net.finmath.marketdata.model.curves.Curve.ExtrapolationMethod}.
* For the possible interpolation entities see {@link net.finmath.marketdata.model.curves.Curve.InterpolationEntity}.
*
* @author Christian Fries
*/
public class Curve extends AbstractCurve implements Serializable {
/**
* Possible interpolation methods.
* @author Christian Fries
*/
public enum InterpolationMethod {
/** Linear interpolation. **/
LINEAR,
/** Cubic spline interpolation. **/
CUBIC_SPLINE
}
/**
* Possible extrapolation methods.
* @author Christian Fries
*/
public enum ExtrapolationMethod {
/** Constant extrapolation. **/
CONSTANT,
/** Linear extrapolation. **/
LINEAR
}
/**
* Possible interpolation entities.
* @author Christian Fries
*/
public enum InterpolationEntity {
/** Interpolation is performed on the native point values, i.e. value(t) **/
VALUE,
/** Interpolation is performed on the log of the point values, i.e. log(value(t)) **/
LOG_OF_VALUE,
/** Interpolation is performed on the log of the point values divided by their respective time, i.e. log(value(t))/t **/
LOG_OF_VALUE_PER_TIME
}
private static class Point implements Comparable<Point>, Serializable {
private static final long serialVersionUID = 8857387999991917430L;
public double time;
public double value;
/**
* @param time
* @param value
*/
public Point(double time, double value) {
super();
this.time = time;
this.value = value;
}
@Override
public int compareTo(Point point) {
if(this.time < point.time) return -1;
if(this.time > point.time) return +1;
return 0;
}
@Override
public Object clone() {
return new Point(time,value);
}
}
private Vector<Point> points = new Vector<Point>();
private InterpolationMethod interpolationMethod = InterpolationMethod.CUBIC_SPLINE;
private ExtrapolationMethod extrapolationMethod = ExtrapolationMethod.CONSTANT;
private InterpolationEntity interpolationEntity = InterpolationEntity.LOG_OF_VALUE;
private RationalFunctionInterpolation rationalFunctionInterpolation = null;
private static final long serialVersionUID = -4126228588123963885L;
static NumberFormat formatterReal = NumberFormat.getInstance(Locale.US);
/**
* Create a curve using
* @param name
* @param interpolationMethod
* @param extrapolationMethod
* @param interpolationEntity
*/
public Curve(String name, InterpolationMethod interpolationMethod, ExtrapolationMethod extrapolationMethod, InterpolationEntity interpolationEntity) {
super(name);
this.interpolationMethod = interpolationMethod;
this.extrapolationMethod = extrapolationMethod;
this.interpolationEntity = interpolationEntity;
}
/* (non-Javadoc)
* @see net.finmath.marketdata.model.curves.CurveInterface#getValue(double)
*/
@Override
public double getValue(double time)
{
return getValue(null, time);
}
/* (non-Javadoc)
* @see net.finmath.marketdata.model.curves.CurveInterface#getValue(double)
*/
@Override
public double getValue(AnalyticModelInterface model, double time)
{
return valueFromInterpolationEntity(getInterpolationEntityValue(time), time);
}
private double getInterpolationEntityValue(double time)
{
synchronized(this) {
if(rationalFunctionInterpolation == null) {
double[] pointsArray = new double[points.size()];
double[] valuesArray = new double[points.size()];
for(int i=0; i<points.size(); i++) {
pointsArray[i] = points.get(i).time;
valuesArray[i] = points.get(i).value;
}
rationalFunctionInterpolation = new RationalFunctionInterpolation(
pointsArray,
valuesArray,
RationalFunctionInterpolation.InterpolationMethod.valueOf(this.interpolationMethod.toString()),
RationalFunctionInterpolation.ExtrapolationMethod.valueOf(this.extrapolationMethod.toString())
);
}
}
return rationalFunctionInterpolation.getValue(time);
}
/**
* Add a point to this curve. The method will throw an exception if the point
* is already part of the curve.
*
* @param time The x<sub>i</sub> in <<sub>i</sub> = f(x<sub>i</sub>).
* @param value The y<sub>i</sub> in <<sub>i</sub> = f(x<sub>i</sub>).
*/
public void addPoint(double time, double value) {
double interpolationEntityValue = interpolationEntityFromValue(value, time);
int index = getTimeIndex(time);
if(index >= 0) {
if(points.get(index).value == interpolationEntityValue) return; // Already in list
else throw new RuntimeException("Trying to add a value for a time for which another value already exists.");
}
else {
// Insert the new point, retain ordering.
points.add(-index-1, new Point(time, interpolationEntityValue));
}
this.rationalFunctionInterpolation = null;
}
protected int getTimeIndex(double maturity) {
Point df = new Point(maturity, Double.NaN);
return java.util.Collections.binarySearch(points, df);
}
/* (non-Javadoc)
* @see net.finmath.marketdata.calibration.UnconstrainedParameterVectorInterface#getParameter()
*/
@Override
public double[] getParameter() {
double[] parameters = new double[points.size()];
for(int i=0; i<points.size(); i++) {
parameters[i] = valueFromInterpolationEntity(points.get(i).value, points.get(i).time);
}
return parameters;
}
/* (non-Javadoc)
* @see net.finmath.marketdata.calibration.UnconstrainedParameterVectorInterface#setParameter(double[])
*/
@Override
public void setParameter(double[] parameter) {
for(int i=0; i<points.size(); i++) {
points.get(i).value = interpolationEntityFromValue(parameter[i], points.get(i).time);
}
this.rationalFunctionInterpolation = null;
}
public String toString() {
String objectAsString = super.toString() + "\n";
for (Point point : points) {
objectAsString = objectAsString + point.time + "\t" + valueFromInterpolationEntity(point.value, point.time) + "\n";
}
return objectAsString;
}
private double interpolationEntityFromValue(double value, double time) {
switch(interpolationEntity) {
case VALUE:
default:
return value;
case LOG_OF_VALUE:
return Math.log(value);
case LOG_OF_VALUE_PER_TIME:
return Math.log(value) / time;
}
}
private double valueFromInterpolationEntity(double interpolationEntityValue, double time) {
switch(interpolationEntity) {
case VALUE:
default:
return interpolationEntityValue;
case LOG_OF_VALUE:
return Math.exp(interpolationEntityValue);
case LOG_OF_VALUE_PER_TIME:
return Math.exp(interpolationEntityValue * time);
}
}
@Override
public CurveInterface getCloneForParameter(double[] parameter) {
Curve newCurve = null;
try {
newCurve = (Curve) this.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
newCurve.points = new Vector<Point>();
for(Point point : points) newCurve.points.add((Point) point.clone());
newCurve.setParameter(parameter);
return newCurve;
}
} |
package net.glowstone.block.blocktype;
import net.glowstone.GlowChunk;
import net.glowstone.block.GlowBlock;
import net.glowstone.block.GlowBlockState;
import net.glowstone.block.entity.TEContainer;
import net.glowstone.block.entity.TEHopper;
import net.glowstone.block.entity.TileEntity;
import net.glowstone.entity.GlowPlayer;
import net.glowstone.entity.objects.GlowItem;
import net.glowstone.inventory.MaterialMatcher;
import net.glowstone.inventory.ToolType;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Hopper;
import org.bukkit.util.Vector;
import java.util.HashMap;
public class BlockHopper extends BlockContainer {
public void setFacingDirection(BlockState bs, BlockFace face) {
byte data;
switch (face) {
case DOWN:
data = 0;
break;
case UP:
data = 1;
break;
case NORTH:
data = 2;
break;
case SOUTH:
data = 3;
break;
case WEST:
data = 4;
break;
case EAST:
default:
data = 5;
break;
}
bs.setRawData(data);
}
@Override
public TileEntity createTileEntity(GlowChunk chunk, int cx, int cy, int cz) {
return new TEHopper(chunk.getBlock(cx, cy, cz));
}
@Override
public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face, ItemStack holding, Vector clickedLoc) {
super.placeBlock(player, state, face, holding, clickedLoc);
setFacingDirection(state, face.getOppositeFace());
requestPulse(state);
}
@Override
protected MaterialMatcher getNeededMiningTool(GlowBlock block) {
return ToolType.PICKAXE;
}
@Override
public void receivePulse(GlowBlock block) {
if (block.getTileEntity() == null) {
return;
}
TEHopper hopper = (TEHopper) block.getTileEntity();
pullItems(block, hopper);
if (!((Hopper) block.getState().getData()).isPowered()) {
pushItems(block, hopper);
}
}
@Override
public void onRedstoneUpdate(GlowBlock block) {
((Hopper) block.getState().getData()).setActive(!block.isBlockPowered());
}
private void pullItems(GlowBlock block, TEHopper hopper) {
GlowBlock source = block.getRelative(BlockFace.UP);
if (source.getType() == null || source.getType() == Material.AIR) {
GlowItem item = getFirstDroppedItem(source.getLocation());
if (item == null) {
return;
}
ItemStack stack = item.getItemStack();
HashMap<Integer, ItemStack> add = hopper.getInventory().addItem(stack);
if (add.size() > 0) {
item.setItemStack(add.get(0));
} else {
item.remove();
}
} else if (source.getTileEntity() != null && source.getTileEntity() instanceof TEContainer) {
TEContainer sourceContainer = (TEContainer) source.getTileEntity();
if (sourceContainer.getInventory() == null || sourceContainer.getInventory().getContents().length == 0) {
return;
}
ItemStack item = getFirstItem(sourceContainer);
if (item == null) {
return;
}
ItemStack clone = item.clone();
clone.setAmount(1);
if (hopper.getInventory().addItem(clone).size() > 0) {
return;
}
if (item.getAmount() - 1 == 0) {
sourceContainer.getInventory().remove(item);
} else {
item.setAmount(item.getAmount() - 1);
}
}
}
private void pushItems(GlowBlock block, TEHopper hopper) {
if (hopper.getInventory() == null || hopper.getInventory().getContents().length == 0) {
return;
}
GlowBlock target = block.getRelative(((Hopper) block.getState().getData()).getFacing());
if (target.getType() != null && target.getTileEntity() instanceof TEContainer) {
ItemStack item = getFirstItem(hopper);
if (item == null) {
return;
}
ItemStack clone = item.clone();
clone.setAmount(1);
if (((TEContainer) target.getTileEntity()).getInventory().addItem(clone).size() > 0) {
return;
}
if (item.getAmount() - 1 == 0) {
hopper.getInventory().remove(item);
} else {
item.setAmount(item.getAmount() - 1);
}
}
}
private GlowItem getFirstDroppedItem(Location location) {
for (Entity entity : location.getChunk().getEntities()) {
if (location.getBlockX() != entity.getLocation().getBlockX() || location.getBlockY() != entity.getLocation().getBlockY() || location.getBlockZ() != entity.getLocation().getBlockZ()) {
continue;
}
if (entity.getType() != EntityType.DROPPED_ITEM) {
continue;
}
return ((GlowItem) entity);
}
return null;
}
private ItemStack getFirstItem(TEContainer container) {
Inventory inventory = container.getInventory();
for (int i = 0; i < inventory.getSize(); i++) {
if (inventory.getItem(i) == null || inventory.getItem(i).getType() == null) {
continue;
}
return inventory.getItem(i);
}
return null;
}
@Override
public void requestPulse(GlowBlockState state) {
state.getBlock().getWorld().requestPulse(state.getBlock(), 8, false);
}
@Override
public boolean canTickRandomly() {
return true;
}
} |
package net.glowstone.entity.objects;
import com.flowpowered.network.Message;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import lombok.Getter;
import lombok.Setter;
import net.glowstone.entity.GlowEntity;
import net.glowstone.entity.GlowPlayer;
import net.glowstone.inventory.GlowInventory;
import net.glowstone.net.message.play.entity.SpawnObjectMessage;
import net.glowstone.net.message.play.player.InteractEntityMessage;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.minecart.CommandMinecart;
import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.entity.minecart.HopperMinecart;
import org.bukkit.entity.minecart.PoweredMinecart;
import org.bukkit.entity.minecart.RideableMinecart;
import org.bukkit.entity.minecart.SpawnerMinecart;
import org.bukkit.entity.minecart.StorageMinecart;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.util.Vector;
// TODO: Implement movement and collision detection.
public abstract class GlowMinecart extends GlowEntity implements Minecart {
@Getter
@Setter
private volatile double damage;
@Getter
@Setter
private volatile double maxSpeed;
@Getter
@Setter
private volatile boolean slowWhenEmpty;
@Getter
@Setter
private volatile Vector flyingVelocityMod;
@Getter
@Setter
private volatile Vector derailedVelocityMod;
@Getter
@Setter
private volatile MaterialData displayBlock;
@Getter
@Setter
private volatile int displayBlockOffset;
@Getter
private final MinecartType minecartType;
/**
* Creates a minecart.
*
* @param location the location
* @param minecartType the minecart type (i.e. the type of block carried, if any)
*/
public GlowMinecart(Location location, MinecartType minecartType) {
super(location);
setSize(0.98f, 0.7f);
this.minecartType = minecartType;
}
/**
* Factory method that creates a minecart.
*
* @param location the location
* @param minecartType the minecart type (i.e. the type of block carried, if any)
*/
public static GlowMinecart create(Location location, MinecartType minecartType) {
return minecartType.getCreator().apply(location);
}
@Override
public List<Message> createSpawnMessage() {
return Collections.singletonList(
new SpawnObjectMessage(id, getUniqueId(), 10, location, minecartType.ordinal()));
}
@Override
public boolean entityInteract(GlowPlayer player, InteractEntityMessage message) {
if (message.getAction() == InteractEntityMessage.Action.ATTACK.ordinal()) {
// todo: damage points
if (this instanceof InventoryHolder) {
InventoryHolder inv = (InventoryHolder) this;
if (inv.getInventory() != null) {
for (ItemStack drop : inv.getInventory().getContents()) {
if (drop == null || drop.getType() == Material.AIR
|| drop.getAmount() < 1) {
continue;
}
GlowItem item = world.dropItemNaturally(getLocation(), drop);
item.setPickupDelay(30);
item.setBias(player);
}
}
}
remove();
}
return true;
}
public enum MinecartType {
RIDEABLE(Rideable.class, EntityType.MINECART, RideableMinecart.class, Rideable::new),
CHEST(Storage.class, EntityType.MINECART_CHEST, StorageMinecart.class, Storage::new),
FURNACE(Powered.class, EntityType.MINECART_FURNACE, PoweredMinecart.class, Powered
::new),
TNT(Explosive.class, EntityType.MINECART_TNT, ExplosiveMinecart.class, Explosive::new),
SPAWNER(Spawner.class, EntityType.MINECART_MOB_SPAWNER, SpawnerMinecart.class, Spawner::new),
HOPPER(Hopper.class, EntityType.MINECART_HOPPER, HopperMinecart.class, Hopper::new),
COMMAND(Command.class, EntityType.MINECART_COMMAND, CommandMinecart.class, Command::new); // todo
@Getter
private final Class<? extends GlowMinecart> minecartClass;
@Getter
private final EntityType entityType;
@Getter
private final Class<? extends Minecart> entityClass;
@Getter
private final Function<? super Location, ? extends GlowMinecart> creator;
MinecartType(Class<? extends GlowMinecart> minecartClass, EntityType entityType,
Class<? extends Minecart> entityClass,
Function<Location, ? extends GlowMinecart> creator) {
this.minecartClass = minecartClass;
this.entityType = entityType;
this.entityClass = entityClass;
this.creator = creator;
}
}
public static class Rideable extends GlowMinecart implements RideableMinecart {
public Rideable(Location location) {
super(location, MinecartType.RIDEABLE);
}
@Override
public boolean entityInteract(GlowPlayer player, InteractEntityMessage message) {
super.entityInteract(player, message);
if (message.getAction() != InteractEntityMessage.Action.INTERACT.ordinal()) {
return false;
}
if (player.isSneaking()) {
return false;
}
if (isEmpty()) {
// todo: fix passengers
// setPassenger(player);
return true;
}
return false;
}
}
public static class Storage extends GlowMinecart implements StorageMinecart {
private final Inventory inventory;
public Storage(Location location) {
super(location, MinecartType.CHEST);
inventory = new GlowInventory(this, InventoryType.CHEST,
InventoryType.CHEST.getDefaultSize(), "Minecart with Chest");
}
@Override
public boolean entityInteract(GlowPlayer player, InteractEntityMessage message) {
super.entityInteract(player, message);
if (message.getAction() != InteractEntityMessage.Action.INTERACT.ordinal()) {
return false;
}
if (player.isSneaking()) {
return false;
}
player.openInventory(inventory);
return true;
}
@Override
public Inventory getInventory() {
return inventory;
}
}
public static class Powered extends GlowMinecart implements PoweredMinecart {
public Powered(Location location) {
super(location, MinecartType.FURNACE);
}
}
public static class Explosive extends GlowMinecart implements ExplosiveMinecart {
public Explosive(Location location) {
super(location, MinecartType.TNT);
}
}
public static class Hopper extends GlowMinecart implements HopperMinecart {
@Getter
private final Inventory inventory;
@Getter
@Setter
private boolean enabled = true;
public Hopper(Location location) {
super(location, MinecartType.HOPPER);
inventory = new GlowInventory(this, InventoryType.HOPPER,
InventoryType.HOPPER.getDefaultSize(), "Minecart with Hopper");
}
@Override
public boolean entityInteract(GlowPlayer player, InteractEntityMessage message) {
super.entityInteract(player, message);
if (message.getAction() != InteractEntityMessage.Action.INTERACT.ordinal()) {
return false;
}
if (player.isSneaking()) {
return false;
}
player.openInventory(inventory);
return true;
}
}
public static class Spawner extends GlowMinecart implements SpawnerMinecart {
public Spawner(Location location) {
super(location, MinecartType.SPAWNER);
}
}
public static class Command extends GlowMinecart implements CommandMinecart {
// TODO: Behavior not implemented
@Getter
@Setter
private String command;
@Getter
@Setter
private String name;
public Command(Location location) {
super(location, MinecartType.COMMAND);
}
}
} |
package net.imagej.ops.cached;
import java.util.Collection;
import net.imagej.ops.AbstractOp;
import net.imagej.ops.CustomOpEnvironment;
import net.imagej.ops.FunctionOp;
import net.imagej.ops.HybridOp;
import net.imagej.ops.Op;
import net.imagej.ops.OpEnvironment;
import org.scijava.Priority;
import org.scijava.cache.CacheService;
import org.scijava.command.CommandInfo;
import org.scijava.plugin.Parameter;
/**
* Creates {@link CachedFunctionOp}s which know how to cache their outputs.
*
* @author Christian Dietz, University of Konstanz
*/
public class CachedOpEnvironment extends CustomOpEnvironment {
@Parameter
private CacheService cs;
public CachedOpEnvironment(final OpEnvironment parent) {
this(parent, null);
}
public CachedOpEnvironment(final OpEnvironment parent,
final Collection<? extends CommandInfo> prioritizedInfos)
{
super(parent, prioritizedInfos);
for (final CommandInfo info : prioritizedInfos) {
info.setPriority(Priority.FIRST_PRIORITY);
}
}
@Override
public <I, O, OP extends Op> FunctionOp<I, O> function(final Class<OP> opType,
final Class<O> outType, final Class<I> inType, Object... otherArgs)
{
final CachedFunctionOp<I, O> cached = new CachedFunctionOp<I, O>(
super.function(opType, outType, inType, otherArgs), otherArgs);
getContext().inject(cached);
return cached;
}
@Override
public <I, O, OP extends Op> FunctionOp<I, O> function(final Class<OP> opType,
final Class<O> outType, I in, Object... otherArgs)
{
final CachedFunctionOp<I, O> cached = new CachedFunctionOp<I, O>(
super.function(opType, outType, in, otherArgs), otherArgs);
getContext().inject(cached);
return cached;
}
@Override
public <I, O, OP extends Op> HybridOp<I, O> hybrid(Class<OP> opType,
Class<O> outType, Class<I> inType, Object... otherArgs)
{
final CachedHybridOp<I, O> cached = new CachedHybridOp<I, O>(super.hybrid(
opType, outType, inType, otherArgs), otherArgs);
getContext().inject(cached);
return cached;
}
@Override
public <I, O, OP extends Op> HybridOp<I, O> hybrid(Class<OP> opType,
Class<O> outType, I in, Object... otherArgs)
{
final CachedHybridOp<I, O> cached = new CachedHybridOp<I, O>(super.hybrid(
opType, outType, in, otherArgs), otherArgs);
getContext().inject(cached);
return cached;
}
/**
* Wraps a {@link FunctionOp} and caches the results. New inputs will result
* in re-computation of the result.
*
* @author Christian Dietz, University of Konstanz
* @param <I>
* @param <O>
*/
class CachedFunctionOp<I, O> extends AbstractOp implements FunctionOp<I, O> {
@Parameter
private CacheService cache;
private final FunctionOp<I, O> delegate;
private final Object[] args;
public CachedFunctionOp(final FunctionOp<I, O> delegate,
final Object[] args)
{
this.delegate = delegate;
this.args = args;
}
@Override
public O compute(final I input) {
final Hash hash = new Hash(input, delegate, args);
@SuppressWarnings("unchecked")
O output = (O) cache.get(hash);
if (output == null) {
output = delegate.compute(input);
cache.put(hash, output);
}
return output;
}
@Override
public void run() {
delegate.run();
}
@Override
public I in() {
return delegate.in();
}
@Override
public void setInput(I input) {
delegate.setInput(input);
}
@Override
public O out() {
return delegate.out();
}
@Override
public void initialize() {
delegate.initialize();
}
@Override
public CachedFunctionOp<I, O> getIndependentInstance() {
return this;
}
}
/**
* Wraps a {@link HybridOp} and caches the results. New inputs will result in
* re-computation if {@link HybridOp} is used as {@link FunctionOp}.
*
* @author Christian Dietz, University of Konstanz
* @param <I>
* @param <O>
*/
class CachedHybridOp<I, O> extends CachedFunctionOp<I, O> implements
HybridOp<I, O>
{
@Parameter
private CacheService cache;
private final HybridOp<I, O> delegate;
private final Object[] args;
public CachedHybridOp(final HybridOp<I, O> delegate, final Object[] args) {
super(delegate, args);
this.delegate = delegate;
this.args = args;
}
@Override
public O compute(final I input) {
final Hash hash = new Hash(input, delegate, args);
@SuppressWarnings("unchecked")
O output = (O) cache.get(hash);
if (output == null) {
output = createOutput(input);
compute(input, output);
cache.put(hash, output);
}
return output;
}
@Override
public O createOutput(I input) {
return delegate.createOutput(input);
}
@Override
public void compute(final I input, final O output) {
delegate.compute(input, output);
}
@Override
public CachedHybridOp<I, O> getIndependentInstance() {
return this;
}
}
/**
* Simple utility class to wrap two objects and an array of objects in a
* single object which combines their hashes.
*/
private class Hash {
private final int hash;
public Hash(final Object o1, final Object o2, final Object[] args) {
long hash = o1.hashCode() ^ o2.getClass().getSimpleName().hashCode();
for (final Object o : args) {
hash ^= o.hashCode();
}
this.hash = (int) hash;
}
@Override
public int hashCode() {
return hash;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (obj instanceof Hash) return hash == ((Hash) obj).hash;
return false;
}
}
} |
package net.malisis.core.renderer;
import java.util.HashMap;
import java.util.Map;
import javax.vecmath.Matrix4f;
import net.malisis.core.block.IBoundingBox;
import net.malisis.core.block.MalisisBlock;
import net.malisis.core.renderer.element.Shape;
import net.malisis.core.renderer.element.face.SouthFace;
import net.malisis.core.renderer.element.shape.Cube;
import net.malisis.core.renderer.icon.MalisisIcon;
import net.malisis.core.renderer.model.MalisisModel;
import net.malisis.core.renderer.model.loader.TextureModelLoader;
import net.malisis.core.util.AABBUtils;
import net.malisis.core.util.TransformBuilder;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.AxisAlignedBB;
/**
* @author Ordinastie
*
*/
public class DefaultRenderer
{
public static MalisisRenderer<?> nullRender = new Null();
public static Block block = new Block();
public static Item item = new Item();
public static class Null extends MalisisRenderer<TileEntity>
{
@Override
public void render()
{}
}
public static class Block extends MalisisRenderer<TileEntity>
{
// "display": {
// "gui": {
// "rotation": [ 30, 225, 0 ],
// "translation": [ 0, 0, 0],
// "scale":[ 0.625, 0.625, 0.625 ]
// "ground": {
// "rotation": [ 0, 0, 0 ],
// "translation": [ 0, 3, 0],
// "scale":[ 0.25, 0.25, 0.25 ]
// "fixed": {
// "rotation": [ 0, 0, 0 ],
// "translation": [ 0, 0, 0],
// "scale":[ 0.5, 0.5, 0.5 ]
// "thirdperson_righthand": {
// "rotation": [ 75, 45, 0 ],
// "translation": [ 0, 2.5, 0],
// "scale": [ 0.375, 0.375, 0.375 ]
// "firstperson_righthand": {
// "rotation": [ 0, 45, 0 ],
// "translation": [ 0, 0, 0 ],
// "scale": [ 0.40, 0.40, 0.40 ]
// "firstperson_lefthand": {
// "rotation": [ 0, 225, 0 ],
// "translation": [ 0, 0, 0 ],
// "scale": [ 0.40, 0.40, 0.40 ]
private Matrix4f gui = new TransformBuilder().rotate(30, 225, 0).scale(0.625F).get();
private Matrix4f firstPersonLeftHand = new TransformBuilder().rotate(0, 225, 0).scale(0.4F).get();
private Matrix4f firstPersonRightHand = new TransformBuilder().rotate(0, 45, 0).scale(0.4F).get();
private Matrix4f thirdPerson = new TransformBuilder().translate(0, 0F, 0).rotateAfter(75, 45, 0).scale(0.375F).get();
private Matrix4f fixed = new TransformBuilder().scale(0.5F).get();
private Matrix4f ground = new TransformBuilder().translate(0, 0.3F, 0).scale(0.25F).get();
private Shape shape = new Cube();
private RenderParameters rp = new RenderParameters();
@Override
public boolean isGui3d()
{
return true;
}
@Override
public Matrix4f getTransform(ItemCameraTransforms.TransformType tranformType)
{
switch (tranformType)
{
case GUI:
return gui;
case FIRST_PERSON_LEFT_HAND:
return firstPersonLeftHand;
case FIRST_PERSON_RIGHT_HAND:
return firstPersonRightHand;
case THIRD_PERSON_LEFT_HAND:
case THIRD_PERSON_RIGHT_HAND:
return thirdPerson;
case GROUND:
return ground;
case FIXED:
return fixed;
default:
return null;
}
}
@Override
public void render()
{
AxisAlignedBB[] aabbs;
if (block instanceof IBoundingBox)
{
aabbs = ((MalisisBlock) block).getRenderBoundingBox(world, pos, blockState);
rp.useBlockBounds.set(false);
}
else
{
aabbs = AABBUtils.identities();
rp.useBlockBounds.set(true);
}
for (AxisAlignedBB aabb : aabbs)
{
if (aabb != null)
{
//shape = new Cube();
//shape = new Shape(new SouthFace());
shape.resetState().limit(aabb);
rp.renderBounds.set(aabb);
drawShape(shape, rp);
}
}
}
}
public static class Item extends MalisisRenderer<TileEntity>
{
// "display": {
// "thirdperson_righthand": {
// "rotation": [ 0, -90, 55 ],
// "translation": [ 0, 4.0, 0.5 ],
// "scale": [ 0.85, 0.85, 0.85 ]
// "thirdperson_lefthand": {
// "rotation": [ 0, 90, -55 ],
// "translation": [ 0, 4.0, 0.5 ],
// "scale": [ 0.85, 0.85, 0.85 ]
// "firstperson_righthand": {
// "rotation": [ 0, -90, 25 ],
// "translation": [ 1.13, 3.2, 1.13 ],
// "scale": [ 0.68, 0.68, 0.68 ]
// "firstperson_lefthand": {
// "rotation": [ 0, 90, -25 ],
// "translation": [ 1.13, 3.2, 1.13 ],
// "scale": [ 0.68, 0.68, 0.68 ]
// translations manually ajusted
private Matrix4f firstPersonRightHand = new TransformBuilder().translate(0, .2F, .13F).scale(0.68F).rotate(0, -90, 25).get();
private Matrix4f firstPersonLeftHand = new TransformBuilder().translate(0, .2F, .13F).scale(0.68F).rotate(0, 90, -25).get();
private Matrix4f thirdPersonRightHand = new TransformBuilder().translate(0, 0.3F, 0.02F).scale(0.85F).rotate(0, -90, 55).get();
private Matrix4f thirdPersonLeftHand = new TransformBuilder().translate(0, 0.3F, 0.02F).scale(0.85F).rotate(0, 90, -55).get();
private Shape gui;
private Map<MalisisIcon, MalisisModel> itemModels = new HashMap<>();
@Override
public void initialize()
{
gui = new Shape(new SouthFace());
}
@Override
public boolean isGui3d()
{
return false;
}
@Override
public Matrix4f getTransform(ItemCameraTransforms.TransformType tranformType)
{
switch (tranformType)
{
case FIRST_PERSON_LEFT_HAND:
return firstPersonLeftHand;
case FIRST_PERSON_RIGHT_HAND:
return firstPersonRightHand;
case THIRD_PERSON_LEFT_HAND:
return thirdPersonLeftHand;
case THIRD_PERSON_RIGHT_HAND:
return thirdPersonRightHand;
default:
return null;
}
// if (tranformType == TransformType.THIRD_PERSON_LEFT_HAND || tranformType == TransformType.THIRD_PERSON_RIGHT_HAND)
// return thirdPerson;
// else if (tranformType == TransformType.FIRST_PERSON_LEFT_HAND || tranformType == TransformType.FIRST_PERSON_RIGHT_HAND)
// return firstPerson;
}
@Override
public void render()
{
RenderParameters rp = new RenderParameters();
rp.applyTexture.set(false);
if (tranformType == TransformType.GUI)
drawShape(gui);
else
{
//drawShape(gui);
drawShape(getModelShape(), rp);
}
}
protected Shape getModelShape()
{
MalisisIcon icon = getIcon(null, new RenderParameters());
MalisisModel model = itemModels.get(icon);
if (model == null)
{
model = new MalisisModel(new TextureModelLoader(icon));
itemModels.put(icon, model);
}
return model.getShape("shape");
}
public void clearModels()
{
itemModels.clear();
}
};
} |
package net.sf.jabref.external;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.sf.jabref.*;
import net.sf.jabref.gui.*;
import net.sf.jabref.gui.maintable.MainTable;
import net.sf.jabref.gui.undo.NamedCompound;
import net.sf.jabref.gui.undo.UndoableFieldChange;
import net.sf.jabref.gui.undo.UndoableInsertEntry;
import net.sf.jabref.model.entry.IdGenerator;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.model.database.BibDatabase;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.logic.util.io.FileUtil;
import net.sf.jabref.util.Util;
import net.sf.jabref.logic.xmp.XMPUtil;
import com.jgoodies.forms.builder.FormBuilder;
import com.jgoodies.forms.layout.FormLayout;
/**
* This class holds the functionality of autolinking to a file that's dropped
* onto an entry.
* <p>
* Options for handling the files are:
* <p>
* 1) Link to the file in its current position (disabled if the file is remote)
* <p>
* 2) Copy the file to ??? directory, rename after bibtex key, and extension
* <p>
* 3) Move the file to ??? directory, rename after bibtex key, and extension
*/
public class DroppedFileHandler {
private static final Log LOGGER = LogFactory.getLog(DroppedFileHandler.class);
public static final String DFH_LEAVE = "DroppedFileHandler_LeaveFileInDir";
public static final String DFH_COPY = "DroppedFileHandler_CopyFile";
public static final String DFH_MOVE = "DroppedFileHandler_MoveFile";
public static final String DFH_RENAME = "DroppedFileHandler_RenameFile";
private final JabRefFrame frame;
private final BasePanel panel;
private final JRadioButton linkInPlace = new JRadioButton();
private final JRadioButton copyRadioButton = new JRadioButton();
private final JRadioButton moveRadioButton = new JRadioButton();
private final JLabel destDirLabel = new JLabel();
private final JCheckBox renameCheckBox = new JCheckBox();
private final JTextField renameToTextBox = new JTextField(50);
private final JPanel optionsPanel = new JPanel();
public DroppedFileHandler(JabRefFrame frame, BasePanel panel) {
this.frame = frame;
this.panel = panel;
ButtonGroup grp = new ButtonGroup();
grp.add(linkInPlace);
grp.add(copyRadioButton);
grp.add(moveRadioButton);
FormLayout layout = new FormLayout("left:15dlu,pref,pref,pref", "bottom:14pt,pref,pref,pref,pref");
layout.setRowGroups(new int[][]{{1, 2, 3, 4, 5}});
FormBuilder builder = FormBuilder.create().layout(layout);
builder.add(linkInPlace).xyw(1, 1, 4);
builder.add(destDirLabel).xyw(1, 2, 4);
builder.add(copyRadioButton).xyw(2, 3, 3);
builder.add(moveRadioButton).xyw(2, 4, 3);
builder.add(renameCheckBox).xyw(2, 5, 1);
builder.add(renameToTextBox).xyw(4, 5, 1);
optionsPanel.add(builder.getPanel());
}
/**
* Offer copy/move/linking options for a dragged external file. Perform the
* chosen operation, if any.
*
* @param fileName The name of the dragged file.
* @param fileType The FileType associated with the file.
* @param localFile Indicate whether this is a local file, or a remote file copied
* to a local temporary file.
* @param mainTable The MainTable the file was dragged to.
* @param dropRow The row where the file was dropped.
*/
public void handleDroppedfile(String fileName, ExternalFileType fileType, MainTable mainTable, int dropRow) {
BibEntry entry = mainTable.getEntryAt(dropRow);
handleDroppedfile(fileName, fileType, entry);
}
/**
* @param fileName The name of the dragged file.
* @param fileType The FileType associated with the file.
* @param localFile Indicate whether this is a local file, or a remote file copied
* to a local temporary file.
* @param entry The target entry for the drop.
*/
public void handleDroppedfile(String fileName, ExternalFileType fileType, BibEntry entry) {
NamedCompound edits = new NamedCompound(Localization.lang("Drop %0", fileType.getExtension()));
if (tryXmpImport(fileName, fileType, edits)) {
edits.end();
panel.undoManager.addEdit(edits);
return;
}
// Show dialog
if (!showLinkMoveCopyRenameDialog(fileName, fileType, entry, panel.database())) {
return;
}
/*
* Ok, we're ready to go. See first if we need to do a file copy before
* linking:
*/
boolean success = true;
String destFilename;
if (linkInPlace.isSelected()) {
destFilename = FileUtil.shortenFileName(new File(fileName), panel.getBibDatabaseContext().getMetaData().getFileDirectory(Globals.FILE_FIELD)).toString();
} else {
destFilename = renameCheckBox.isSelected() ? renameToTextBox.getText() : new File(fileName).getName();
if (copyRadioButton.isSelected()) {
success = doCopy(fileName, destFilename, edits);
} else if (moveRadioButton.isSelected()) {
success = doMove(fileName, destFilename, edits);
}
}
if (success) {
doLink(entry, fileType, destFilename, false, edits);
panel.markBaseChanged();
panel.updateEntryEditorIfShowing();
}
edits.end();
panel.undoManager.addEdit(edits);
}
// Done by MrDlib
public void linkPdfToEntry(String fileName, MainTable entryTable, int dropRow) {
BibEntry entry = entryTable.getEntryAt(dropRow);
linkPdfToEntry(fileName, entry);
}
public void linkPdfToEntry(String fileName, BibEntry entry) {
ExternalFileType fileType = ExternalFileTypes.getInstance().getExternalFileTypeByExt("pdf");
// Show dialog
if (!showLinkMoveCopyRenameDialog(fileName, fileType, entry, panel.database())) {
return;
}
/*
* Ok, we're ready to go. See first if we need to do a file copy before
* linking:
*/
boolean success = true;
String destFilename;
NamedCompound edits = new NamedCompound(Localization.lang("Drop %0", fileType.getExtension()));
if (linkInPlace.isSelected()) {
destFilename = FileUtil.shortenFileName(new File(fileName), panel.getBibDatabaseContext().getMetaData().getFileDirectory(Globals.FILE_FIELD)).toString();
} else {
destFilename = renameCheckBox.isSelected() ? renameToTextBox.getText() : new File(fileName).getName();
if (copyRadioButton.isSelected()) {
success = doCopy(fileName, destFilename, edits);
} else if (moveRadioButton.isSelected()) {
success = doMove(fileName, destFilename, edits);
}
}
if (success) {
doLink(entry, fileType, destFilename, false, edits);
panel.markBaseChanged();
}
edits.end();
panel.undoManager.addEdit(edits);
}
// Done by MrDlib
private boolean tryXmpImport(String fileName, ExternalFileType fileType, NamedCompound edits) {
if (!"pdf".equals(fileType.getExtension())) {
return false;
}
List<BibEntry> xmpEntriesInFile;
try {
xmpEntriesInFile = XMPUtil.readXMP(fileName);
} catch (IOException e) {
LOGGER.warn("Problem reading XMP", e);
return false;
}
if ((xmpEntriesInFile == null) || xmpEntriesInFile.isEmpty()) {
return false;
}
JLabel confirmationMessage = new JLabel(
Localization.lang("The PDF contains one or several bibtex-records.")
+ "\n"
+ Localization.lang("Do you want to import these as new entries into the current database?"));
int reply = JOptionPane.showConfirmDialog(frame, confirmationMessage,
Localization.lang("XMP metadata found in PDF: %0", fileName), JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (reply == JOptionPane.CANCEL_OPTION) {
return true; // The user canceled thus that we are done.
}
if (reply == JOptionPane.NO_OPTION) {
return false;
}
// reply == JOptionPane.YES_OPTION)
/*
* TODO Extract Import functionality from ImportMenuItem then we could
* do:
*
* ImportMenuItem importer = new ImportMenuItem(frame, (mainTable ==
* null), new PdfXmpImporter());
*
* importer.automatedImport(new String[] { fileName });
*/
boolean isSingle = xmpEntriesInFile.size() == 1;
BibEntry single = isSingle ? xmpEntriesInFile.get(0) : null;
boolean success = true;
String destFilename;
if (linkInPlace.isSelected()) {
destFilename = FileUtil.shortenFileName(new File(fileName), panel.getBibDatabaseContext().getMetaData().getFileDirectory(Globals.FILE_FIELD)).toString();
} else {
if (renameCheckBox.isSelected()) {
destFilename = fileName;
} else {
destFilename = single.getCiteKey() + "." + fileType.getExtension();
}
if (copyRadioButton.isSelected()) {
success = doCopy(fileName, destFilename, edits);
} else if (moveRadioButton.isSelected()) {
success = doMove(fileName, destFilename, edits);
}
}
if (success) {
for (BibEntry aXmpEntriesInFile : xmpEntriesInFile) {
aXmpEntriesInFile.setId(IdGenerator.next());
edits.addEdit(new UndoableInsertEntry(panel.getDatabase(), aXmpEntriesInFile, panel));
panel.getDatabase().insertEntry(aXmpEntriesInFile);
doLink(aXmpEntriesInFile, fileType, destFilename, true, edits);
}
panel.markBaseChanged();
panel.updateEntryEditorIfShowing();
}
return true;
}
// @return true if user pushed "OK", false otherwise
private boolean showLinkMoveCopyRenameDialog(String linkFileName, ExternalFileType fileType,
BibEntry entry,
BibDatabase database) {
String dialogTitle = Localization.lang("Link to file %0", linkFileName);
List<String> dirs = panel.getBibDatabaseContext().getMetaData().getFileDirectory(Globals.FILE_FIELD);
int found = -1;
for (int i = 0; i < dirs.size(); i++) {
if (new File(dirs.get(i)).exists()) {
found = i;
break;
}
}
if (found < 0) {
destDirLabel.setText(Localization.lang("File directory is not set or does not exist!"));
copyRadioButton.setEnabled(false);
moveRadioButton.setEnabled(false);
renameToTextBox.setEnabled(false);
renameCheckBox.setEnabled(false);
linkInPlace.setSelected(true);
} else {
destDirLabel.setText(Localization.lang("File directory is '%0':", dirs.get(found)));
copyRadioButton.setEnabled(true);
moveRadioButton.setEnabled(true);
renameToTextBox.setEnabled(true);
renameCheckBox.setEnabled(true);
}
ChangeListener cl = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
renameCheckBox.setEnabled(!linkInPlace.isSelected());
renameToTextBox.setEnabled(!linkInPlace.isSelected());
}
};
linkInPlace.setText(Localization.lang("Leave file in its current directory."));
copyRadioButton.setText(Localization.lang("Copy file to file directory."));
moveRadioButton.setText(Localization.lang("Move file to file directory."));
renameCheckBox.setText(Localization.lang("Rename file to").concat(": "));
// Determine which name to suggest:
String targetName = Util.getLinkedFileName(database, entry, Globals.journalAbbreviationLoader.getRepository());
renameToTextBox.setText(targetName.concat(".").concat(fileType.getExtension()));
linkInPlace.setSelected(frame.prefs().getBoolean(DroppedFileHandler.DFH_LEAVE));
copyRadioButton.setSelected(frame.prefs().getBoolean(DroppedFileHandler.DFH_COPY));
moveRadioButton.setSelected(frame.prefs().getBoolean(DroppedFileHandler.DFH_MOVE));
renameCheckBox.setSelected(frame.prefs().getBoolean(DroppedFileHandler.DFH_RENAME));
linkInPlace.addChangeListener(cl);
cl.stateChanged(new ChangeEvent(linkInPlace));
try {
Object[] messages = {Localization.lang("How would you like to link to '%0'?", linkFileName),
optionsPanel};
int reply = JOptionPane.showConfirmDialog(frame, messages, dialogTitle,
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (reply == JOptionPane.OK_OPTION) {
// store user's choice
frame.prefs().putBoolean(DroppedFileHandler.DFH_LEAVE, linkInPlace.isSelected());
frame.prefs().putBoolean(DroppedFileHandler.DFH_COPY, copyRadioButton.isSelected());
frame.prefs().putBoolean(DroppedFileHandler.DFH_MOVE, moveRadioButton.isSelected());
frame.prefs().putBoolean(DroppedFileHandler.DFH_RENAME, renameCheckBox.isSelected());
return true;
} else {
return false;
}
} finally {
linkInPlace.removeChangeListener(cl);
}
}
/**
* Make a extension to the file.
*
* @param entry The entry to extension from.
* @param fileType The FileType associated with the file.
* @param filename The path to the file.
* @param edits An NamedCompound action this action is to be added to. If none
* is given, the edit is added to the panel's undoManager.
*/
private void doLink(BibEntry entry, ExternalFileType fileType, String filename,
boolean avoidDuplicate, NamedCompound edits) {
Optional<String> oldValue = entry.getFieldOptional(Globals.FILE_FIELD);
FileListTableModel tm = new FileListTableModel();
oldValue.ifPresent(tm::setContent);
// If avoidDuplicate==true, we should check if this file is already linked:
if (avoidDuplicate) {
// For comparison, find the absolute filename:
List<String> dirs = panel.getBibDatabaseContext().getMetaData().getFileDirectory(Globals.FILE_FIELD);
String absFilename;
if (new File(filename).isAbsolute() || dirs.isEmpty()) {
absFilename = filename;
} else {
Optional<File> file = FileUtil.expandFilename(filename, dirs);
if (file.isPresent()) {
absFilename = file.get().getAbsolutePath();
} else {
absFilename = ""; // This shouldn't happen based on the old code, so maybe one should set it something else?
}
}
LOGGER.debug("absFilename: " + absFilename);
for (int i = 0; i < tm.getRowCount(); i++) {
FileListEntry flEntry = tm.getEntry(i);
// Find the absolute filename for this existing link:
String absName;
if (new File(flEntry.link).isAbsolute() || dirs.isEmpty()) {
absName = flEntry.link;
} else {
Optional<File> file = FileUtil.expandFilename(flEntry.link, dirs);
if (file.isPresent()) {
absName = file.get().getAbsolutePath();
} else {
absName = null;
}
}
LOGGER.debug("absName: " + absName);
// If the filenames are equal, we don't need to link, so we simply return:
if (absFilename.equals(absName)) {
return;
}
}
}
tm.addEntry(tm.getRowCount(), new FileListEntry("", filename, fileType));
String newValue = tm.getStringRepresentation();
UndoableFieldChange edit = new UndoableFieldChange(entry, Globals.FILE_FIELD, oldValue.orElse(null), newValue);
entry.setField(Globals.FILE_FIELD, newValue);
if (edits == null) {
panel.undoManager.addEdit(edit);
} else {
edits.addEdit(edit);
}
}
/**
* Move the given file to the base directory for its file type, and rename
* it to the given filename.
*
* @param fileName The name of the source file.
* @param destFilename The destination filename.
* @param edits TODO we should be able to undo this action
* @return true if the operation succeeded.
*/
private boolean doMove(String fileName, String destFilename,
NamedCompound edits) {
List<String> dirs = panel.getBibDatabaseContext().getMetaData().getFileDirectory(Globals.FILE_FIELD);
int found = -1;
for (int i = 0; i < dirs.size(); i++) {
if (new File(dirs.get(i)).exists()) {
found = i;
break;
}
}
if (found < 0) {
// OOps, we don't know which directory to put it in, or the given
// dir doesn't exist....
// This should not happen!!
LOGGER.warn("Cannot determine destination directory or destination directory does not exist");
return false;
}
File toFile = new File(dirs.get(found) + System.getProperty("file.separator") + destFilename);
if (toFile.exists()) {
int answer = JOptionPane.showConfirmDialog(frame,
Localization.lang("'%0' exists. Overwrite file?", toFile.getAbsolutePath()),
Localization.lang("Overwrite file?"),
JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.NO_OPTION) {
return false;
}
}
File fromFile = new File(fileName);
if (fromFile.renameTo(toFile)) {
return true;
} else {
JOptionPane.showMessageDialog(frame,
Localization.lang("Could not move file '%0'.", toFile.getAbsolutePath()) +
Localization.lang("Please move the file manually and link in place."),
Localization.lang("Move file failed"), JOptionPane.ERROR_MESSAGE);
return false;
}
}
/**
* Copy the given file to the base directory for its file type, and give it
* the given name.
*
* @param fileName The name of the source file.
* @param fileType The FileType associated with the file.
* @param toFile The destination filename. An existing path-component will be removed.
* @param edits TODO we should be able to undo this!
* @return
*/
private boolean doCopy(String fileName, String toFile, NamedCompound edits) {
List<String> dirs = panel.getBibDatabaseContext().getMetaData().getFileDirectory(Globals.FILE_FIELD);
int found = -1;
for (int i = 0; i < dirs.size(); i++) {
if (new File(dirs.get(i)).exists()) {
found = i;
break;
}
}
if (found < 0) {
// OOps, we don't know which directory to put it in, or the given
// dir doesn't exist....
// This should not happen!!
LOGGER.warn("Cannot determine destination directory or destination directory does not exist");
return false;
}
String destinationFileName = new File(toFile).getName();
File destFile = new File(dirs.get(found) + System.getProperty("file.separator") + destinationFileName);
if (destFile.equals(new File(fileName))) {
// File is already in the correct position. Don't override!
return true;
}
if (destFile.exists()) {
int answer = JOptionPane.showConfirmDialog(frame,
Localization.lang("'%0' exists. Overwrite file?", destFile.getPath()),
Localization.lang("File exists"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer == JOptionPane.NO_OPTION) {
return false;
}
}
try {
FileUtil.copyFile(new File(fileName), destFile, true);
} catch (IOException e) {
LOGGER.error("Problem copying file", e);
return false;
}
return true;
}
} |
package nom.bdezonia.zorbage.type.storage;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorage;
import nom.bdezonia.zorbage.type.storage.file.FileStorage;
/**
*
* @author Barry DeZonia
*
*/
public class Storage {
public static <U> IndexedDataSource<?, U> allocate(long numElements, U type) {
try {
return ArrayStorage.allocate(numElements, type);
} catch (OutOfMemoryError e) {
return FileStorage.allocate(numElements, type);
}
}
} |
package org.browsermob.proxy.bricks;
import com.google.common.collect.Multimap;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.google.sitebricks.At;
import com.google.sitebricks.client.transport.Json;
import com.google.sitebricks.headless.Reply;
import com.google.sitebricks.headless.Request;
import com.google.sitebricks.headless.Service;
import com.google.sitebricks.http.Delete;
import com.google.sitebricks.http.Get;
import com.google.sitebricks.http.Post;
import com.google.sitebricks.http.Put;
import org.browsermob.core.har.Har;
import org.browsermob.proxy.ProxyManager;
import org.browsermob.proxy.ProxyServer;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.protocol.HttpContext;
import org.apache.http.HttpRequest;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import java.util.List;
@At("/proxy")
@Service
public class ProxyResource {
private ProxyManager proxyManager;
@Inject
public ProxyResource(ProxyManager proxyManager) {
this.proxyManager = proxyManager;
}
@Post
public Reply<ProxyDescriptor> newProxy(Request request) throws Exception {
String httpProxy = request.param("httpProxy");
Hashtable<String, String> options = new Hashtable<String, String>();
if (httpProxy != null) {
options.put("httpProxy", httpProxy);
}
ProxyServer proxy = proxyManager.create(options);
int port = proxy.getPort();
return Reply.with(new ProxyDescriptor(port)).as(Json.class);
}
@Get
@At("/:port/har")
public Reply<Har> getHar(@Named("port") int port) {
ProxyServer proxy = proxyManager.get(port);
Har har = proxy.getHar();
return Reply.with(har).as(Json.class);
}
@Put
@At("/:port/har")
public Reply<?> newHar(@Named("port") int port, Request request) {
String initialPageRef = request.param("initialPageRef");
ProxyServer proxy = proxyManager.get(port);
Har oldHar = proxy.newHar(initialPageRef);
String captureHeaders = request.param("captureHeaders");
String captureContent = request.param("captureContent");
proxy.setCaptureHeaders(Boolean.parseBoolean(captureHeaders));
proxy.setCaptureContent(Boolean.parseBoolean(captureContent));
if (oldHar != null) {
return Reply.with(oldHar).as(Json.class);
} else {
return Reply.saying().noContent();
}
}
@Put
@At("/:port/har/pageRef")
public Reply<?> setPage(@Named("port") int port, Request request) {
String pageRef = request.param("pageRef");
ProxyServer proxy = proxyManager.get(port);
proxy.newPage(pageRef);
return Reply.saying().ok();
}
@Put
@At("/:port/blacklist")
public Reply<?> blacklist(@Named("port") int port, Request request) {
String blacklist = request.param("regex");
int responseCode = parseResponseCode(request.param("status"));
ProxyServer proxy = proxyManager.get(port);
proxy.blacklistRequests(blacklist, responseCode);
return Reply.saying().ok();
}
@Put
@At("/:port/whitelist")
public Reply<?> whitelist(@Named("port") int port, Request request) {
String regex = request.param("regex");
int responseCode = parseResponseCode(request.param("status"));
ProxyServer proxy = proxyManager.get(port);
proxy.whitelistRequests(regex.split(","), responseCode);
return Reply.saying().ok();
}
@Put
@At("/:port/headers")
public Reply<?> headers(@Named("port") int port, Request request) {
ProxyServer proxy = proxyManager.get(port);
final Multimap headers = request.params();
proxy.addRequestInterceptor(new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) {
Set keySet = headers.keySet();
Iterator keyIterator = keySet.iterator();
while (keyIterator.hasNext() ) {
String key = (String) keyIterator.next();
List values = (List) headers.get(key);
String value = (String) values.get(0);
request.removeHeaders(key);
request.addHeader(key, value);
}
}
});
return Reply.saying().ok();
}
@Put
@At("/:port/limit")
public Reply<?> limit(@Named("port") int port, Request request) {
ProxyServer proxy = proxyManager.get(port);
String upstreamKbps = request.param("upstreamKbps");
if (upstreamKbps != null) {
try {
proxy.setUpstreamKbps(Integer.parseInt(upstreamKbps));
} catch (NumberFormatException e) { }
}
String downstreamKbps = request.param("downstreamKbps");
if (downstreamKbps != null) {
try {
proxy.setDownstreamKbps(Integer.parseInt(downstreamKbps));
} catch (NumberFormatException e) { }
}
String latency = request.param("latency");
if (latency != null) {
try {
proxy.setLatency(Integer.parseInt(latency));
} catch (NumberFormatException e) { }
}
return Reply.saying().ok();
}
@Delete
@At("/:port")
public Reply<?> delete(@Named("port") int port) throws Exception {
proxyManager.delete(port);
return Reply.saying().ok();
}
private int parseResponseCode(String response)
{
int responseCode = 200;
if (response != null) {
try {
responseCode = Integer.parseInt(response);
} catch (NumberFormatException e) { }
}
return responseCode;
}
public static class ProxyDescriptor {
private int port;
public ProxyDescriptor() {
}
public ProxyDescriptor(int port) {
this.port = port;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
} |
package org.buddycloud.channelserver.channel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;
import org.buddycloud.channelserver.pubsub.affiliation.Affiliations;
import org.buddycloud.channelserver.pubsub.publishmodel.PublishModels;
import org.buddycloud.channelserver.pubsub.accessmodel.AccessModels;
import org.xmpp.packet.JID;
//TODO! Refactor this!
// Lot's of duplicate code plus other mayhem (like the SimpleDateFormat.
public class Conf {
public static final String TYPE = "pubsub#type";
public static final String TITLE = "pubsub#title";
public static final String DESCRIPTION = "pubsub#description";
public static final String PUBLISH_MODEL = "pubsub#publish_model";
public static final String ACCESS_MODEL = "pubsub#access_model";
public static final String CREATION_DATE = "pubsub#creation_date";
public static final String OWNER = "pubsub#owner";
public static final String DEFAULT_AFFILIATION = "buddycloud#default_affiliation";
public static final String NUM_SUBSCRIBERS = "pubsub#num_subscribers";
public static final String NOTIFY_CONFIG = "pubsub#notify_config";
public static final String CHANNEL_TYPE = "buddycloud#channel_type";
private static final String PUBLISHERS = "publishers";
// Most of these are copied from here
// https://github.com/buddycloud/buddycloud-server/blob/master/src/local/operations.coffee#L14
public static String getPostChannelNodename(JID channelJID) {
return "/user/" + channelJID.toBareJID() + "/posts";
}
public static HashMap<String, String> getDefaultPostChannelConf(JID channelJID) {
// TODO! Refactor this!
String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
HashMap<String, String> conf = new HashMap<String, String>();
conf.put(TYPE, "http:
conf.put(TITLE, channelJID.toBareJID() + "'s very own buddycloud channel!");
conf.put(DESCRIPTION, "This channel belongs to " + channelJID.toBareJID() + ". To nobody else!");
conf.put(PUBLISH_MODEL, PUBLISHERS);
conf.put(ACCESS_MODEL, AccessModels.open.toString());
conf.put(CREATION_DATE, sdf.format(new Date()));
conf.put(OWNER, channelJID.toBareJID());
conf.put(DEFAULT_AFFILIATION, Affiliations.member.toString());
conf.put(NUM_SUBSCRIBERS, "1");
conf.put(NOTIFY_CONFIG, "1");
conf.put(CHANNEL_TYPE, "personal");
return conf;
}
public static String getStatusChannelNodename(JID channelJID) {
return "/user/" + channelJID.toBareJID() + "/status";
}
public static HashMap<String, String> getDefaultStatusChannelConf(JID channelJID) {
// TODO! Refactor this!
String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
HashMap<String, String> conf = new HashMap<String, String>();
conf.put(TYPE, "http:
conf.put(TITLE, channelJID.toBareJID() + "'s very own buddycloud status!");
conf.put(DESCRIPTION, "This is " + channelJID.toBareJID() + "'s mood a.k.a status -channel. Depends how geek you are.");
conf.put(PUBLISH_MODEL, PUBLISHERS);
conf.put(ACCESS_MODEL, AccessModels.open.toString());
conf.put(CREATION_DATE, sdf.format(new Date()));
conf.put(OWNER, channelJID.toBareJID());
conf.put(DEFAULT_AFFILIATION, Affiliations.member.toString());
conf.put(NUM_SUBSCRIBERS, "1");
conf.put(NOTIFY_CONFIG, "1");
return conf;
}
public static String getGeoPreviousChannelNodename(JID channelJID) {
return "/user/" + channelJID.toBareJID() + "/geo/previous";
}
public static HashMap<String, String> getDefaultGeoPreviousChannelConf(JID channelJID) {
// TODO! Refactor this!
String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
HashMap<String, String> conf = new HashMap<String, String>();
conf.put(TYPE, "http:
conf.put(TITLE, channelJID.toBareJID() + "'s previous location.");
conf.put(DESCRIPTION, "Where " + channelJID.toBareJID() + " has been before.");
conf.put(PUBLISH_MODEL, PUBLISHERS);
conf.put(ACCESS_MODEL, AccessModels.open.toString());
conf.put(CREATION_DATE, sdf.format(new Date()));
conf.put(OWNER, channelJID.toBareJID());
conf.put(DEFAULT_AFFILIATION, Affiliations.member.toString());
conf.put(NUM_SUBSCRIBERS, "1");
conf.put(NOTIFY_CONFIG, "1");
return conf;
}
public static String getGeoCurrentChannelNodename(JID channelJID) {
return "/user/" + channelJID.toBareJID() + "/geo/current";
}
public static HashMap<String, String> getDefaultGeoCurrentChannelConf(JID channelJID) {
// TODO! Refactor this!
String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
HashMap<String, String> conf = new HashMap<String, String>();
conf.put(TYPE, "http:
conf.put(TITLE, channelJID.toBareJID() + "'s current location.");
conf.put(DESCRIPTION, "Where " + channelJID.toBareJID() + " is now.");
conf.put(PUBLISH_MODEL, PUBLISHERS);
conf.put(ACCESS_MODEL, AccessModels.open.toString());
conf.put(CREATION_DATE, sdf.format(new Date()));
conf.put(OWNER, channelJID.toBareJID());
conf.put(DEFAULT_AFFILIATION, Affiliations.member.toString());
conf.put(NUM_SUBSCRIBERS, "1");
conf.put(NOTIFY_CONFIG, "1");
return conf;
}
public static String getGeoNextChannelNodename(JID channelJID) {
return "/user/" + channelJID.toBareJID() + "/geo/next";
}
public static HashMap<String, String> getDefaultGeoNextChannelConf(JID channelJID) {
// TODO! Refactor this!
String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
HashMap<String, String> conf = new HashMap<String, String>();
conf.put(TYPE, "http:
conf.put(TITLE, channelJID.toBareJID() + "'s next location.");
conf.put(DESCRIPTION, "Where " + channelJID.toBareJID() + " is going to go.");
conf.put(PUBLISH_MODEL, PUBLISHERS);
conf.put(ACCESS_MODEL, AccessModels.open.toString());
conf.put(CREATION_DATE, sdf.format(new Date()));
conf.put(OWNER, channelJID.toBareJID());
conf.put(DEFAULT_AFFILIATION, Affiliations.member.toString());
conf.put(NUM_SUBSCRIBERS, "1");
conf.put(NOTIFY_CONFIG, "1");
return conf;
}
public static String getSubscriptionsChannelNodename(JID channelJID) {
return "/user/" + channelJID.toBareJID() + "/subscriptions";
}
public static HashMap<String, String> getDefaultSubscriptionsChannelConf(JID channelJID) {
// TODO! Refactor this!
String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
HashMap<String, String> conf = new HashMap<String, String>();
conf.put(TYPE, "http:
conf.put(TITLE, channelJID.toBareJID() + "'s susbcriptions.");
conf.put(DESCRIPTION, channelJID.toBareJID() + "'s subscriptions. ");
conf.put(PUBLISH_MODEL, PUBLISHERS);
conf.put(ACCESS_MODEL, AccessModels.open.toString());
conf.put(CREATION_DATE, sdf.format(new Date()));
conf.put(OWNER, channelJID.toBareJID());
conf.put(DEFAULT_AFFILIATION, Affiliations.member.toString());
conf.put(NUM_SUBSCRIBERS, "1");
conf.put(NOTIFY_CONFIG, "1");
return conf;
}
} |
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Graphe {
private int nbSommets;
private boolean arcs[][];
public Graphe() {
nbSommets = 0;
arcs = new boolean[nbSommets][nbSommets];
}
public Graphe(int nbSommets) {
this.nbSommets = nbSommets;
arcs = new boolean[nbSommets][nbSommets];
}
public Graphe(String filename) {
int nbSommets = 0;
try{
FileInputStream fis = new FileInputStream(filename);
InputStreamReader ipsr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(ipsr);
String ligne;
while ((ligne=br.readLine())!=null){
if(ligne.startsWith("p")) {
String[] split_line = ligne.split(" ");
nbSommets = Integer.parseInt(split_line[2]);
break;
}
}
this.nbSommets = nbSommets;
arcs = new boolean[nbSommets][nbSommets];
init();
while ((ligne=br.readLine())!=null){
if(ligne.startsWith("e")) {
String[] split_ligne = ligne.split(" ");
int from = Integer.parseInt(split_ligne[1]);
int to = Integer.parseInt(split_ligne[2]);
System.out.print("From " + from + " To " + to + "\n");
arcs[from-1][to-1] = true;
arcs[to-1][from-1] = true;
}
}
br.close();
ipsr.close();
fis.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
// GETTERS
public int getNbSommets() {
return nbSommets;
}
public boolean[][] getArcs() {
return arcs;
}
// SETTERS
public void setNbSommets(int nbSommets) {
this.nbSommets = nbSommets;
}
public void setArcs(boolean[][] arcs) {
this.arcs = arcs;
}
@Override
public String toString() {
super.toString();
String ch = "Sommets : " + nbSommets + "\n" +
"Arcs : \n";
for(int i=0 ; i<nbSommets ; i++) {
ch += "| ";
for(int j=0 ; j<nbSommets ; j++) {
ch += arcs[i][j] + " |";
}
ch += "\n";
}
return ch;
}
// METHODES
public void init() {
for(int i=0 ; i<nbSommets ; i++) {
for(int j=0 ; j<nbSommets ; j++) {
arcs[i][j] = false;
}
}
}
/**
* Teste si le @link Graphe est une clique
* @return <code>true</code> si le Graphe est une clique, <code>false</code> sinon
*/
public boolean isClique() {
for(int i=0 ; i<nbSommets ; i++) {
for(int j=0 ; j<nbSommets ; j++) {
if((i != j && arcs[i][j] == false))
return false;
}
}
return true;
}
public boolean isClique(ArrayList<Integer> sommets){
for(Integer s1 : sommets){
for(Integer s2 : sommets){
if((s1 != s2 && arcs[s1][s2] == false))
return false;
}
}
return true;
}
public boolean existingClique(int nbSom){
for(int i = 0 ; i < nbSom ; ++i){ //i est le sommet qu'on ne comptabilise pas pour le moment
ArrayList<Integer> sommets = new ArrayList<Integer>();
for(int j = 0; j < nbSom; ++j){ // tous les sommets sauf i
if(j != i) sommets.add(j);
}
if(isClique(sommets)) return true;
}
return false;
}
public int cliqueMax(){
if(isClique()) return nbSommets; // Pas besoin de tester toute la matrice si le graphe d'origine est une clique
for(int i = nbSommets ; i > 0 ; --i){
if(existingClique(i)) return i;
}
return 0;
}
} |
package org.deepsymmetry.beatlink.data;
import org.deepsymmetry.beatlink.CdjStatus;
import org.deepsymmetry.beatlink.dbserver.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Provides support for navigating the menu hierarchy offered by the dbserver on a player for a particular media slot.
* Note that for historical reasons, loading track metadata, playlists, and the full track list are performed by the
* {@link MetadataFinder}, even though those are technically menu operations.
*
* @since 0.4.0
*
* @author James Elliott
*/
public class MenuLoader {
private static final Logger logger = LoggerFactory.getLogger(MenuLoader.class);
public List<Message> requestRootMenuFrom(final SlotReference slotReference, final int sortOrder)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting root menu.");
Message response = client.menuRequest(Message.KnownType.ROOT_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,
new NumberField(sortOrder), new NumberField(0xffffff));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting root menu");
}
public List<Message> requestPlaylistMenuFrom(final SlotReference slotReference, final int sortOrder)
throws Exception {
return MetadataFinder.getInstance().requestPlaylistItemsFrom(slotReference.player, slotReference.slot, sortOrder,
0, true);
}
public List<Message> requestHistoryMenuFrom(final SlotReference slotReference, final int sortOrder)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting History menu.");
Message response = client.menuRequest(Message.KnownType.HISTORY_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,
new NumberField(sortOrder));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting history menu");
}
public List<Message> requestHistoryPlaylistFrom(final SlotReference slotReference, final int sortOrder, final int historyId)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting History playlist.");
Message response = client.menuRequest(Message.KnownType.TRACK_MENU_FOR_HISTORY_REQ, Message.MenuIdentifier.MAIN_MENU,
slotReference.slot, new NumberField(sortOrder), new NumberField(historyId));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting history playlist");
}
public List<Message> requestTrackMenuFrom(final SlotReference slotReference, final int sortOrder)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
return MetadataFinder.getInstance().getFullTrackList(slotReference.slot, client, sortOrder);
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting track menu");
}
public List<Message> requestArtistMenuFrom(final SlotReference slotReference, final int sortOrder)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting Artist menu.");
Message response = client.menuRequest(Message.KnownType.ARTIST_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,
new NumberField(sortOrder));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting artist menu");
}
public List<Message> requestArtistAlbumMenuFrom(final SlotReference slotReference, final int sortOrder, final int artistId)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting Artist Album menu.");
Message response = client.menuRequest(Message.KnownType.ALBUM_MENU_FOR_ARTIST_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,
new NumberField(sortOrder), new NumberField(artistId));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting artist album menu");
}
public List<Message> requestArtistAlbumTrackMenuFrom(final SlotReference slotReference, final int sortOrder, final int artistId, final int albumId)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting Artist Album Track menu.");
Message response = client.menuRequest(Message.KnownType.TRACK_MENU_FOR_ARTIST_AND_ALBUM, Message.MenuIdentifier.MAIN_MENU,
slotReference.slot, new NumberField(sortOrder), new NumberField(artistId), new NumberField(albumId));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting artist album tracks menu");
}
public List<Message> requestAlbumTrackMenuFrom(final SlotReference slotReference, final int sortOrder, final int albumId)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting Album Track menu.");
Message response = client.menuRequest(Message.KnownType.TRACK_MENU_FOR_ALBUM_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,
new NumberField(sortOrder), new NumberField(albumId));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting album tracks menu");
}
public List<Message> requestGenreMenuFrom(final SlotReference slotReference, final int sortOrder)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting Genre menu.");
Message response = client.menuRequest(Message.KnownType.GENRE_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,
new NumberField(sortOrder));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting genre menu");
}
public List<Message> requestGenreArtistMenuFrom(final SlotReference slotReference, final int sortOrder, final int genreId)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting Genre Artist menu.");
Message response = client.menuRequest(Message.KnownType.ARTIST_MENU_FOR_GENRE_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,
new NumberField(sortOrder), new NumberField(genreId));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting genre artists menu");
}
public List<Message> requestGenreArtistAlbumMenuFrom(final SlotReference slotReference, final int sortOrder, final int genreId, final int artistId)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting Genre Artist Album menu.");
Message response = client.menuRequest(Message.KnownType.ALBUM_MENU_FOR_GENRE_AND_ARTIST, Message.MenuIdentifier.MAIN_MENU,
slotReference.slot, new NumberField(sortOrder), new NumberField(genreId), new NumberField(artistId));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting genre artist albums menu");
}
public List<Message> requestGenreArtistAlbumTrackMenuFrom(final SlotReference slotReference, final int sortOrder, final int genreId,
final int artistId, final int albumId)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting Genre Artist Album Track menu.");
Message response = client.menuRequest(Message.KnownType.TRACK_MENU_FOR_GENRE_ARTIST_AND_ALBUM, Message.MenuIdentifier.MAIN_MENU,
slotReference.slot, new NumberField(sortOrder), new NumberField(genreId), new NumberField(artistId), new NumberField(albumId));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting genre artist album tracks menu");
}
public List<Message> requestAlbumMenuFrom(final SlotReference slotReference, final int sortOrder)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting Album menu.");
Message response = client.menuRequest(Message.KnownType.ALBUM_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,
new NumberField(sortOrder));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting album menu");
}
public List<Message> requestKeyMenuFrom(final SlotReference slotReference, final int sortOrder)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting Key menu.");
Message response = client.menuRequest(Message.KnownType.KEY_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,
new NumberField(sortOrder));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting key menu");
}
public List<Message> requestKeyNeighborMenuFrom(final SlotReference slotReference, final int sortOrder, final int keyId)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting key neighbor menu.");
Message response = client.menuRequest(Message.KnownType.NEIGHBOR_MENU_FOR_KEY, Message.MenuIdentifier.MAIN_MENU,
slotReference.slot, new NumberField(sortOrder), new NumberField(keyId));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting key neighbor menu");
}
public List<Message> requestTracksByKeyAndDistanceFrom(final SlotReference slotReference, final int sortOrder, final int keyId, final int distance)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting key neighbor menu.");
Message response = client.menuRequest(Message.KnownType.TRACK_MENU_FOR_KEY_AND_DISTANCE, Message.MenuIdentifier.MAIN_MENU,
slotReference.slot, new NumberField(sortOrder), new NumberField(keyId), new NumberField(distance));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting tracks by key and distance menu");
}
public List<Message> requestBpmMenuFrom(final SlotReference slotReference, final int sortOrder)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting BPM menu.");
Message response = client.menuRequest(Message.KnownType.BPM_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,
new NumberField(sortOrder));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting BPM menu");
}
public List<Message> requestRatingMenuFrom(final SlotReference slotReference, final int sortOrder)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting Rating menu.");
Message response = client.menuRequest(Message.KnownType.RATING_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,
new NumberField(sortOrder));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting rating menu");
}
public List<Message> requestTracksByRatingFrom(final SlotReference slotReference, final int sortOrder, final int rating)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting key neighbor menu.");
Message response = client.menuRequest(Message.KnownType.TRACK_MENU_FOR_RATING_REQ, Message.MenuIdentifier.MAIN_MENU,
slotReference.slot, new NumberField(sortOrder), new NumberField(rating));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting tracks by rating menu");
}
public List<Message> requestFolderMenuFrom(final SlotReference slotReference, final int sortOrder)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
logger.debug("Requesting Key menu.");
Message response = client.menuRequest(Message.KnownType.FOLDER_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,
new NumberField(sortOrder));
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.REKORDBOX, response);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
};
return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, "requesting folder menu");
}
private List<Message> getSearchItems(CdjStatus.TrackSourceSlot slot, int sortOrder, String text,
AtomicInteger count, Client client)
throws IOException, InterruptedException, TimeoutException {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
final StringField textField = new StringField(text);
Message response = client.menuRequest(Message.KnownType.SEARCH_MENU, Message.MenuIdentifier.MAIN_MENU, slot,
new NumberField(sortOrder), new NumberField(textField.getSize()), textField, NumberField.WORD_0);
final int actualCount = (int)response.getMenuResultsCount();
if (actualCount == Message.NO_MENU_RESULTS_AVAILABLE || actualCount == 0) {
if (count != null) {
count.set(0);
}
return Collections.emptyList();
}
// Gather the requested number of search menu items
if (count == null) {
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, CdjStatus.TrackType.REKORDBOX, response);
} else {
final int desiredCount = Math.min(count.get(), actualCount);
count.set(actualCount);
if (desiredCount < 1) {
return Collections.emptyList();
}
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, CdjStatus.TrackType.REKORDBOX,
0, desiredCount);
}
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
public List<Message> requestSearchResultsFrom(final int player, final CdjStatus.TrackSourceSlot slot,
final int sortOrder, final String text,
final AtomicInteger count)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
return getSearchItems(slot, sortOrder, text.toUpperCase(), count, client);
}
};
return ConnectionManager.getInstance().invokeWithClientSession(player, task, "performing search");
}
private List<Message> getMoreSearchItems(final CdjStatus.TrackSourceSlot slot, final int sortOrder, final String text,
final int offset, final int count, final Client client)
throws IOException, InterruptedException, TimeoutException {
if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {
try {
final StringField textField = new StringField(text);
Message response = client.menuRequest(Message.KnownType.SEARCH_MENU, Message.MenuIdentifier.MAIN_MENU, slot,
new NumberField(sortOrder), new NumberField(textField.getSize()), textField, NumberField.WORD_0);
final int actualCount = (int)response.getMenuResultsCount();
if (offset + count > actualCount) {
throw new IllegalArgumentException("Cannot request items past the end of the menu.");
}
// Gather the requested search menu items
return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot, CdjStatus.TrackType.REKORDBOX,
offset, count);
} finally {
client.unlockForMenuOperations();
}
} else {
throw new TimeoutException("Unable to lock player for menu operations.");
}
}
public List<Message> requestMoreSearchResultsFrom(final int player, final CdjStatus.TrackSourceSlot slot,
final int sortOrder, final String text,
final int offset, final int count)
throws Exception {
ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {
@Override
public List<Message> useClient(Client client) throws Exception {
return getMoreSearchItems(slot, sortOrder, text.toUpperCase(), offset, count, client);
}
};
return ConnectionManager.getInstance().invokeWithClientSession(player, task, "performing search");
}
/**
* Holds the singleton instance of this class.
*/
private static final MenuLoader ourInstance = new MenuLoader();
/**
* Get the singleton instance of this class.
*
* @return the only instance of this class which exists.
*/
public static MenuLoader getInstance() {
return ourInstance;
}
/**
* Prevent direct instantiation.
*/
private MenuLoader() {
// Nothing to do.
}
} |
package org.dita.dost.module;
import static org.dita.dost.reader.GenListModuleReader.*;
import static org.dita.dost.util.Constants.*;
import static org.dita.dost.util.FileUtils.getRelativeUnixPath;
import static org.dita.dost.util.FileUtils.resolve;
import static org.dita.dost.util.Job.*;
import static org.dita.dost.util.Configuration.*;
import static org.dita.dost.util.URLUtils.*;
import static org.dita.dost.util.FilterUtils.*;
import static org.dita.dost.util.XMLUtils.*;
import java.io.*;
import java.net.URI;
import java.util.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.apache.xerces.xni.grammars.XMLGrammarPool;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.exception.DITAOTXMLErrorHandler;
import org.dita.dost.pipeline.AbstractPipelineInput;
import org.dita.dost.pipeline.AbstractPipelineOutput;
import org.dita.dost.reader.DitaValReader;
import org.dita.dost.reader.GrammarPoolManager;
import org.dita.dost.reader.SubjectSchemeReader;
import org.dita.dost.util.*;
import org.dita.dost.writer.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.*;
import org.xml.sax.ext.LexicalHandler;
/**
* DebugAndFilterModule implement the second step in preprocess. It will insert debug
* information into every dita files and filter out the information that is not
* necessary.
*
* @author Zhang, Yuan Peng
*/
public final class DebugAndFilterModule extends AbstractPipelineModuleImpl {
private Mode processingMode;
/** Generate {@code xtrf} and {@code xtrc} attributes */
private boolean genDebugInfo;
/** Absolute input map path. */
private URI inputMap;
/** use grammar pool cache */
private boolean gramcache = true;
private boolean setSystemId;
/** Profiling is enabled. */
private boolean profilingEnabled;
private boolean validate;
private String transtype;
/** Absolute DITA-OT base path. */
private File ditaDir;
private File ditavalFile;
private FilterUtils filterUtils;
/** Absolute path to current destination file. */
private File outputFile;
private Map<String, Map<String, Set<String>>> validateMap;
private Map<String, Map<String, String>> defaultValueMap;
/** XMLReader instance for parsing dita file */
private XMLReader reader;
/** Absolute path to current source file. */
private URI currentFile;
private Map<URI, Set<URI>> dic;
private SubjectSchemeReader subjectSchemeReader;
private FilterUtils baseFilterUtils;
private DitaWriterFilter ditaWriterFilter;
private TopicFragmentFilter topicFragmentFilter;
@Override
public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException {
if (logger == null) {
throw new IllegalStateException("Logger not set");
}
try {
readArguments(input);
init();
for (final FileInfo f: job.getFileInfo()) {
if (isFormatDita(f.format) || ATTR_FORMAT_VALUE_DITAMAP.equals(f.format)) {
processFile(f);
}
}
job.write();
} catch (final Exception e) {
e.printStackTrace();
throw new DITAOTException("Exception doing debug and filter module processing: " + e.getMessage(), e);
}
return null;
}
private void processFile(final FileInfo f) {
currentFile = f.src;
if (!exists(f.src)) { //copytoMap.containsKey(f.file)
logger.debug("Ignoring a copy-to file " + f.src);
return;
}
outputFile = new File(job.tempDir, f.file.getPath());
final File outputDir = outputFile.getParentFile();
if (!outputDir.exists() && !outputDir.mkdirs()) {
logger.error("Failed to create output directory " + outputDir.getAbsolutePath());
return;
}
logger.info("Processing " + f.src);
final Set<URI> schemaSet = dic.get(f.uri);
if (schemaSet != null && !schemaSet.isEmpty()) {
logger.debug("Loading subject schemes");
subjectSchemeReader.reset();
for (final URI schema : schemaSet) {
subjectSchemeReader.loadSubjectScheme(new File(job.tempDir.toURI().resolve(schema.getPath() + SUBJECT_SCHEME_EXTENSION)));
}
validateMap = subjectSchemeReader.getValidValuesMap();
defaultValueMap = subjectSchemeReader.getDefaultValueMap();
} else {
validateMap = Collections.EMPTY_MAP;
defaultValueMap = Collections.EMPTY_MAP;
}
if (profilingEnabled) {
filterUtils = baseFilterUtils.refine(subjectSchemeReader.getSubjectSchemeMap());
}
InputSource in = null;
Result out = null;
try {
reader.setErrorHandler(new DITAOTXMLErrorHandler(currentFile.toString(), logger));
final TransformerFactory tf = TransformerFactory.newInstance();
final SAXTransformerFactory stf = (SAXTransformerFactory) tf;
final TransformerHandler serializer = stf.newTransformerHandler();
XMLReader parser = getXmlReader(f.format);
XMLReader xmlSource = parser;
for (final XMLFilter filter: getProcessingPipe(currentFile)) {
filter.setParent(xmlSource);
xmlSource = filter;
}
// ContentHandler must be reset so e.g. Saxon 9.1 will reassign ContentHandler
// when reusing filter with multiple Transformers.
xmlSource.setContentHandler(null);
try {
final LexicalHandler lexicalHandler = new DTDForwardHandler(xmlSource);
parser.setProperty("http://xml.org/sax/properties/lexical-handler", lexicalHandler);
parser.setFeature("http://xml.org/sax/features/lexical-handler", true);
} catch (final SAXNotRecognizedException e) {}
in = new InputSource(f.src.toString());
out = new StreamResult(new FileOutputStream(outputFile));
serializer.setResult(out);
xmlSource.setContentHandler(serializer);
xmlSource.parse(new InputSource(f.src.toString()));
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
} finally {
try {
close(out);
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
}
try {
close(in);
} catch (final IOException e) {
logger.error(e.getMessage(), e) ;
}
}
if (isFormatDita(f.format)) {
f.format = ATTR_FORMAT_VALUE_DITA;
}
}
private XMLReader getXmlReader(final String format) throws SAXException {
for (final Map.Entry<String, String> e: parserMap.entrySet()) {
if (format != null && format.equals(e.getKey())) {
try {
return (XMLReader) this.getClass().forName(e.getValue()).newInstance();
} catch (final InstantiationException | ClassNotFoundException | IllegalAccessException ex) {
throw new SAXException(ex);
}
}
}
return reader;
}
private void init() throws IOException, DITAOTException, SAXException {
// Output subject schemas
outputSubjectScheme();
subjectSchemeReader = new SubjectSchemeReader();
subjectSchemeReader.setLogger(logger);
dic = SubjectSchemeReader.readMapFromXML(new File(job.tempDir, FILE_NAME_SUBJECT_DICTIONARY));
if (profilingEnabled) {
final DitaValReader filterReader = new DitaValReader();
filterReader.setLogger(logger);
filterReader.initXMLReader(setSystemId);
Map<FilterKey, Action> filterMap;
if (ditavalFile != null) {
filterReader.read(ditavalFile.getAbsoluteFile());
filterMap = filterReader.getFilterMap();
} else {
filterMap = Collections.EMPTY_MAP;
}
baseFilterUtils = new FilterUtils(printTranstype.contains(transtype), filterMap);
baseFilterUtils.setLogger(logger);
}
initXmlReader();
initFilters();
}
/**
* Init xml reader used for pipeline parsing.
*/
private void initXmlReader() throws SAXException {
CatalogUtils.setDitaDir(ditaDir);
reader = XMLUtils.getXMLReader();
if (validate) {
reader.setFeature(FEATURE_VALIDATION, true);
try {
reader.setFeature(FEATURE_VALIDATION_SCHEMA, true);
} catch (final SAXNotRecognizedException e) {
// Not Xerces, ignore exception
}
}
reader.setFeature(FEATURE_NAMESPACE, true);
final CatalogResolver resolver = CatalogUtils.getCatalogResolver();
reader.setEntityResolver(resolver);
if (gramcache) {
final XMLGrammarPool grammarPool = GrammarPoolManager.getGrammarPool();
try {
reader.setProperty("http://apache.org/xml/properties/internal/grammar-pool", grammarPool);
logger.info("Using Xerces grammar pool for DTD and schema caching.");
} catch (final NoClassDefFoundError e) {
logger.debug("Xerces not available, not using grammar caching");
} catch (final SAXNotRecognizedException | SAXNotSupportedException e) {
logger.warn("Failed to set Xerces grammar pool for parser: " + e.getMessage());
}
}
}
/**
* Initialize reusable filters.
*/
private void initFilters() {
ditaWriterFilter = new DitaWriterFilter();
ditaWriterFilter.setLogger(logger);
ditaWriterFilter.setJob(job);
ditaWriterFilter.setEntityResolver(reader.getEntityResolver());
topicFragmentFilter = new TopicFragmentFilter(ATTRIBUTE_NAME_CONREF, ATTRIBUTE_NAME_CONREFEND);
}
/**
* Get pipe line filters
*
* @param fileToParse absolute URI to current file being processed
*/
private List<XMLFilter> getProcessingPipe(final URI fileToParse) {
final List<XMLFilter> pipe = new ArrayList<>();
if (genDebugInfo) {
final DebugFilter debugFilter = new DebugFilter();
debugFilter.setLogger(logger);
debugFilter.setCurrentFile(currentFile);
pipe.add(debugFilter);
}
if (filterUtils != null) {
final ProfilingFilter profilingFilter = new ProfilingFilter();
profilingFilter.setLogger(logger);
profilingFilter.setFilterUtils(filterUtils);
pipe.add(profilingFilter);
}
final ValidationFilter validationFilter = new ValidationFilter();
validationFilter.setLogger(logger);
validationFilter.setValidateMap(validateMap);
validationFilter.setCurrentFile(fileToParse);
validationFilter.setJob(job);
validationFilter.setProcessingMode(processingMode);
pipe.add(validationFilter);
final NormalizeFilter normalizeFilter = new NormalizeFilter();
normalizeFilter.setLogger(logger);
pipe.add(normalizeFilter);
pipe.add(topicFragmentFilter);
ditaWriterFilter.setDefaultValueMap(defaultValueMap);
ditaWriterFilter.setCurrentFile(currentFile);
ditaWriterFilter.setOutputFile(outputFile);
pipe.add(ditaWriterFilter);
return pipe;
}
private void readArguments(AbstractPipelineInput input) {
final File baseDir = toFile(input.getAttribute(ANT_INVOKER_PARAM_BASEDIR));
ditaDir = new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_DITADIR));
transtype = input.getAttribute(ANT_INVOKER_EXT_PARAM_TRANSTYPE);
profilingEnabled = true;
if (input.getAttribute(ANT_INVOKER_PARAM_PROFILING_ENABLED) != null) {
profilingEnabled = Boolean.parseBoolean(input.getAttribute(ANT_INVOKER_PARAM_PROFILING_ENABLED));
}
if (profilingEnabled) {
if (input.getAttribute(ANT_INVOKER_PARAM_DITAVAL) != null) {
ditavalFile = new File(input.getAttribute(ANT_INVOKER_PARAM_DITAVAL));
if (!ditavalFile.isAbsolute()) {
ditavalFile = new File(baseDir, ditavalFile.getPath()).getAbsoluteFile();
}
}
}
gramcache = "yes".equalsIgnoreCase(input.getAttribute(ANT_INVOKER_EXT_PARAM_GRAMCACHE));
validate = Boolean.valueOf(input.getAttribute(ANT_INVOKER_EXT_PARAM_VALIDATE));
setSystemId = "yes".equals(input.getAttribute(ANT_INVOKER_EXT_PARAN_SETSYSTEMID));
genDebugInfo = Boolean.valueOf(input.getAttribute(ANT_INVOKER_EXT_PARAM_GENERATE_DEBUG_ATTR));
final String mode = input.getAttribute(ANT_INVOKER_EXT_PARAM_PROCESSING_MODE);
processingMode = mode != null ? Mode.valueOf(mode.toUpperCase()) : Mode.LAX;
// Absolute input directory path
URI inputDir = job.getInputDir();
if (!inputDir.isAbsolute()) {
inputDir = baseDir.toURI().resolve(inputDir);
}
inputMap = inputDir.resolve(job.getInputMap());
}
/**
* Output subject schema file.
*
* @throws DITAOTException if generation files
*/
private void outputSubjectScheme() throws DITAOTException {
try {
final Map<URI, Set<URI>> graph = SubjectSchemeReader.readMapFromXML(new File(job.tempDir, FILE_NAME_SUBJECT_RELATION));
final Queue<URI> queue = new LinkedList<>(graph.keySet());
final Set<URI> visitedSet = new HashSet<>();
final DocumentBuilder builder = XMLUtils.getDocumentBuilder();
builder.setEntityResolver(CatalogUtils.getCatalogResolver());
while (!queue.isEmpty()) {
final URI parent = queue.poll();
final Set<URI> children = graph.get(parent);
if (children != null) {
queue.addAll(children);
}
if (ROOT_URI.equals(parent) || visitedSet.contains(parent)) {
continue;
}
visitedSet.add(parent);
final File tmprel = new File(FileUtils.resolve(job.tempDir, parent) + SUBJECT_SCHEME_EXTENSION);
final Document parentRoot;
if (!tmprel.exists()) {
final URI src = job.getInputDir().resolve(parent);
parentRoot = builder.parse(src.toString());
} else {
parentRoot = builder.parse(tmprel);
}
if (children != null) {
for (final URI childpath: children) {
final Document childRoot = builder.parse(inputMap.resolve(childpath.getPath()).toString());
mergeScheme(parentRoot, childRoot);
generateScheme(new File(job.tempDir, childpath.getPath() + SUBJECT_SCHEME_EXTENSION), childRoot);
}
}
//Output parent scheme
generateScheme(new File(job.tempDir.getAbsoluteFile(), parent.getPath() + SUBJECT_SCHEME_EXTENSION), parentRoot);
}
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
throw new DITAOTException(e);
}
}
private void mergeScheme(final Document parentRoot, final Document childRoot) {
final Queue<Element> pQueue = new LinkedList<>();
pQueue.offer(parentRoot.getDocumentElement());
while (!pQueue.isEmpty()) {
final Element pe = pQueue.poll();
NodeList pList = pe.getChildNodes();
for (int i = 0; i < pList.getLength(); i++) {
final Node node = pList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
pQueue.offer((Element)node);
}
}
String value = pe.getAttribute(ATTRIBUTE_NAME_CLASS);
if (StringUtils.isEmptyString(value)
|| !SUBJECTSCHEME_SUBJECTDEF.matches(value)) {
continue;
}
if (!StringUtils.isEmptyString(
value = pe.getAttribute(ATTRIBUTE_NAME_KEYREF))) {
// extend child scheme
final Element target = searchForKey(childRoot.getDocumentElement(), value);
if (target == null) {
/*
* TODO: we have a keyref here to extend into child scheme, but can't
* find any matching <subjectdef> in child scheme. Shall we throw out
* a warning?
*
* Not for now, just bypass it.
*/
continue;
}
// target found
pList = pe.getChildNodes();
for (int i = 0; i < pList.getLength(); i++) {
final Node tmpnode = childRoot.importNode(pList.item(i), false);
if (tmpnode.getNodeType() == Node.ELEMENT_NODE
&& searchForKey(target,
((Element)tmpnode).getAttribute(ATTRIBUTE_NAME_KEYS)) != null) {
continue;
}
target.appendChild(tmpnode);
}
} else if (!StringUtils.isEmptyString(
value = pe.getAttribute(ATTRIBUTE_NAME_KEYS))) {
// merge into parent scheme
final Element target = searchForKey(childRoot.getDocumentElement(), value);
if (target != null) {
pList = target.getChildNodes();
for (int i = 0; i < pList.getLength(); i++) {
final Node tmpnode = parentRoot.importNode(pList.item(i), false);
if (tmpnode.getNodeType() == Node.ELEMENT_NODE
&& searchForKey(pe,
((Element)tmpnode).getAttribute(ATTRIBUTE_NAME_KEYS)) != null) {
continue;
}
pe.appendChild(tmpnode);
}
}
}
}
}
private Element searchForKey(final Element root, final String key) {
if (root == null || StringUtils.isEmptyString(key)) {
return null;
}
final Queue<Element> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
final Element pe = queue.poll();
final NodeList pchildrenList = pe.getChildNodes();
for (int i = 0; i < pchildrenList.getLength(); i++) {
final Node node = pchildrenList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
queue.offer((Element)node);
}
}
String value = pe.getAttribute(ATTRIBUTE_NAME_CLASS);
if (StringUtils.isEmptyString(value)
|| !SUBJECTSCHEME_SUBJECTDEF.matches(value)) {
continue;
}
value = pe.getAttribute(ATTRIBUTE_NAME_KEYS);
if (StringUtils.isEmptyString(value)) {
continue;
}
if (value.equals(key)) {
return pe;
}
}
return null;
}
/**
* Serialize subject scheme file.
*
* @param filename output filepath
* @param root subject scheme document
*
* @throws DITAOTException if generation fails
*/
private void generateScheme(final File filename, final Document root) throws DITAOTException {
final File p = filename.getParentFile();
if (!p.exists() && !p.mkdirs()) {
throw new DITAOTException("Failed to make directory " + p.getAbsolutePath());
}
Result res = null;
try {
res = new StreamResult(new FileOutputStream(filename));
final DOMSource ds = new DOMSource(root);
final TransformerFactory tff = TransformerFactory.newInstance();
final Transformer tf = tff.newTransformer();
tf.transform(ds, res);
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
throw new DITAOTException(e);
} finally {
try {
close(res);
} catch (IOException e) {
throw new DITAOTException(e);
}
}
}
/**
* Get path to base directory
*
* @param filename relative input file path from base directory
* @param traceFilename absolute input file
* @param inputMap absolute path to start file
* @return path to base directory, {@code null} if not available
*/
public static File getPathtoProject(final File filename, final File traceFilename, final File inputMap, final Job job) {
if (job.getGeneratecopyouter() != Job.Generate.OLDSOLUTION) {
if (isOutFile(traceFilename, inputMap)) {
return toFile(getRelativePathFromOut(traceFilename.getAbsoluteFile(), job));
} else {
return new File(getRelativeUnixPath(traceFilename.getAbsolutePath(), inputMap.getAbsolutePath())).getParentFile();
}
} else {
return FileUtils.getRelativePath(filename);
}
}
/**
* Just for the overflowing files.
* @param overflowingFile overflowingFile
* @return relative system path to out which ends in {@link java.io.File#separator File.separator}
*/
private static String getRelativePathFromOut(final File overflowingFile, final Job job) {
final URI relativePath = getRelativePath(job.getInputFile(), overflowingFile.toURI());
final File outputDir = job.getOutputDir().getAbsoluteFile();
final File outputPathName = new File(outputDir, "index.html");
final File finalOutFilePathName = resolve(outputDir, relativePath.getPath());
final File finalRelativePathName = FileUtils.getRelativePath(finalOutFilePathName, outputPathName);
File parentDir = finalRelativePathName.getParentFile();
if (parentDir == null || parentDir.getPath().isEmpty()) {
parentDir = new File(".");
}
return parentDir.getPath() + File.separator;
}
/**
* Check if path falls outside start document directory
*
* @param filePathName absolute path to test
* @param inputMap absolute input map path
* @return {@code true} if outside start directory, otherwise {@code false}
*/
private static boolean isOutFile(final File filePathName, final File inputMap){
final File relativePath = FileUtils.getRelativePath(inputMap.getAbsoluteFile(), filePathName.getAbsoluteFile());
return !(relativePath.getPath().length() == 0 || !relativePath.getPath().startsWith(".."));
}
/**
* Lexical handler to forward DTD declaration into processing instructions.
*/
private final class DTDForwardHandler implements LexicalHandler {
private final XMLReader parser;
public DTDForwardHandler(XMLReader parser) {
this.parser = parser;
}
@Override
public void startDTD(final String name, final String publicId, final String systemId) throws SAXException {
if (publicId != null && !publicId.isEmpty()) {
parser.getContentHandler().processingInstruction("doctype-public", publicId);
}
if (systemId != null && !systemId.isEmpty()) {
parser.getContentHandler().processingInstruction("doctype-system", systemId);
}
}
@Override
public void endDTD() throws SAXException {}
@Override
public void startEntity(String name) throws SAXException {}
@Override
public void endEntity(String name) throws SAXException {}
@Override
public void startCDATA() throws SAXException {}
@Override
public void endCDATA() throws SAXException {}
@Override
public void comment(char[] ch, int start, int length) throws SAXException {}
}
} |
package org.everit.osgi.ecm.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The <code>Dectivate</code> annotation defines the method which is used to deactivate the component.
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Deactivate {
} |
package org.g_node.crawler.LKTLogbook;
import com.hp.hpl.jena.datatypes.RDFDatatype;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.DCTerms;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.g_node.srv.RDFService;
import org.g_node.srv.RDFUtils;
import org.g_node.srv.Utils;
/**
* Class converting parsed data to RDF.
*/
public class LKTLogToRDF {
/**
* Namespace used to identify RDF resources and properties specific for the current use case.
*/
private static final String RDF_NS_LKT = "https://orcid.org/0000-0003-4857-1083
/**
* Namespace prefix for all instances of the LKT use case.
*/
private static final String RDF_NS_LKT_ABR = "lkt";
/**
* Map containing all projects with their newly created UUIDs of the parsed ODS sheet.
*/
private Map<String, String> projectList;
/**
* Map containing all the subjectIDs with their newly created UUIDs of the parsed ODS sheet.
*/
private Map<String, String> subjectList;
/**
* Map containing all the experimenters with their newly created UUIDs contained in the parsed ODS sheet.
*/
private Map<String, String> experimenterList;
/**
* Main RDF model containing all the parsed information from the ODS sheet.
*/
private Model model;
/**
* Constructor.
*/
public LKTLogToRDF() {
this.projectList = new HashMap<>();
this.subjectList = new HashMap<>();
this.experimenterList = new HashMap<>();
this.model = ModelFactory.createDefaultModel();
this.model.setNsPrefix(RDFUtils.RDF_NS_RDF_ABR, RDFUtils.RDF_NS_RDF);
this.model.setNsPrefix(RDFUtils.RDF_NS_RDFS_ABR, RDFUtils.RDF_NS_RDFS);
this.model.setNsPrefix(RDFUtils.RDF_NS_XSD_ABR, RDFUtils.RDF_NS_XSD);
this.model.setNsPrefix(RDFUtils.RDF_NS_FOAF_ABR, RDFUtils.RDF_NS_FOAF);
this.model.setNsPrefix(RDFUtils.RDF_NS_DC_ABR, RDFUtils.RDF_NS_DC);
this.model.setNsPrefix(RDFUtils.RDF_NS_GN_ONT_ABR, RDFUtils.RDF_NS_GN_ONT);
this.model.setNsPrefix(LKTLogToRDF.RDF_NS_LKT_ABR, LKTLogToRDF.RDF_NS_LKT);
}
/**
* Adds all data from a parsed ODS sheet to an RDF model and writes the results to a designated output file.
* Data specific notes:
* This method creates an RDF Provenance class instance, using a hash ID as identifier. This hash ID is
* created using the filename of the input file and the current date (XSDDateTime format).
* The hash ID is created using the {@link Utils#getHashSHA} method.
* @param allSheets Data from the parsed ODS sheets.
* @param inputFile Name and path of the input file
* @param outputFile Name and path of the designated output file.
* @param outputFormat RDF output format.
*/
public final void createRDFModel(final ArrayList<LKTLogParserSheet> allSheets, final String inputFile,
final String outputFile, final String outputFormat) {
final String provDateTime = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
final String provID = Utils.getHashSHA(new ArrayList<>(Arrays.asList(inputFile, provDateTime)));
this.createInst(provID)
.addProperty(RDF.type, this.mainRes("Provenance"))
.addLiteral(DCTerms.source, inputFile)
.addLiteral(DCTerms.created,
this.mainTypedLiteral(provDateTime,
XSDDatatype.XSDdateTime)
)
.addLiteral(DCTerms.subject,
"This RDF file was created by parsing data from the file indicated in the source literal");
allSheets.stream().forEach(a -> this.addSubject(a, provID));
RDFService.writeModelToFile(outputFile, this.model, outputFormat);
}
/**
* The method adds data of a parsed ODS sheet to the main RDF model.
* Data specific notes:
* This method creates an RDF Subject class instance, using a hash ID as identifier. This hash ID is
* created using the current sheets values (in this order) of scientific name, subject ID,
* date of birth (XSDDate format).
* The method creates an RDF Permit class instance, using a hash ID as identifier. The hash ID is created
* using the permit number parsed from the current sheet.
* The hash IDs are created using the {@link Utils#getHashSHA} method.
* @param currSheet Data from the current sheet.
* @param provID ID of the current provenance resource.
*/
private void addSubject(final LKTLogParserSheet currSheet, final String provID) {
final String subjectID = currSheet.getSubjectID();
if (!this.subjectList.containsKey(subjectID)) {
// TODO A problem with this key could be different writing styles of the scientific name.
final ArrayList<String> subjListID = new ArrayList<>(
Arrays.asList(currSheet.getScientificName(),
currSheet.getSubjectID(),
currSheet.getDateOfBirth().toString()));
this.subjectList.put(subjectID, Utils.getHashSHA(subjListID));
}
final String permitHashID = Utils.getHashSHA(Collections.singletonList(currSheet.getPermitNumber()));
final Resource permit = this.createInst(permitHashID)
.addProperty(this.mainProp("hasProvenance"), this.fetchInstance(provID))
.addProperty(RDF.type, this.mainRes("Permit"))
.addLiteral(this.mainProp("hasNumber"), currSheet.getPermitNumber());
final Resource subject = this.createInst(this.subjectList.get(subjectID))
.addProperty(this.mainProp("hasProvenance"), this.fetchInstance(provID))
.addProperty(RDF.type, this.mainRes("Subject"))
.addLiteral(this.mainProp("hasSubjectID"), subjectID)
.addLiteral(this.mainProp("hasSex"), currSheet.getSubjectSex())
.addLiteral(
this.mainProp("hasBirthDate"),
this.mainTypedLiteral(currSheet.getDateOfBirth().toString(), XSDDatatype.XSDdate))
.addLiteral(
this.mainProp("hasWithdrawalDate"),
this.mainTypedLiteral(currSheet.getDateOfWithdrawal().toString(), XSDDatatype.XSDdate))
.addProperty(this.mainProp("hasPermit"), permit);
RDFUtils.addNonEmptyLiteral(subject, this.mainProp("hasSpeciesName"), currSheet.getSpecies());
RDFUtils.addNonEmptyLiteral(subject, this.mainProp("hasScientificName"), currSheet.getScientificName());
currSheet.getEntries().stream().forEach(
c -> this.addEntry(c, subject, provID, subjectID)
);
}
/**
* The method adds the data of a parsed ODS row to the main RDF model.
* Data specific notes:
* This method creates an RDF Project class instance, using a hash ID as identifier. This hash ID is
* created using the provided project name value of the current entry.
* The method creates an RDF Experimenter class instance, using a hash ID as identifier. The hash ID is created
* using the full name of a person parsed from the current entry.
* The hash IDs are created using the {@link Utils#getHashSHA} method.
* @param currEntry Data from the current ODS line entry.
* @param subject Resource from the main RDF model containing the information about
* the test subject this entry is associated with.
* @param provID ID of the current provenance resource.
* @param subjectID Plain ID of the current test subject the experiment is connected to. This ID is required
* to create the Hash IDs for Experiment and SubjectLogEntry instances.
*/
private void addEntry(final LKTLogParserEntry currEntry, final Resource subject,
final String provID, final String subjectID) {
final String project = currEntry.getProject();
// Add RDF Project instance only once to the RDF model.
if (!this.projectList.containsKey(project)) {
final String projectHashID = Utils.getHashSHA(Collections.singletonList(project));
this.projectList.put(project, projectHashID);
this.createInst(projectHashID)
.addProperty(this.mainProp("hasProvenance"), this.fetchInstance(provID))
.addProperty(RDF.type, this.mainRes("Project"))
.addLiteral(RDFS.label, project);
}
// Fetch RDF Project instance.
final Resource projectRes = this.fetchInstance(this.projectList.get(project));
// Add new RDF Experimenter instance only once to the RDF model.
final String experimenter = currEntry.getExperimenterName();
if (!this.experimenterList.containsKey(experimenter)) {
// TODO Problem: This will be the name as entered,
// TODO there is no control over the order of first and last name.
this.experimenterList.put(experimenter, Utils.getHashSHA(
Collections.singletonList(experimenter)));
final Property name = this.model.createProperty(String.join("", RDFUtils.RDF_NS_FOAF, "name"));
final Resource personRes = this.model.createResource(String.join("", RDFUtils.RDF_NS_FOAF, "Person"));
this.createInst(this.experimenterList.get(experimenter))
.addProperty(this.mainProp("hasProvenance"), this.fetchInstance(provID))
.addProperty(RDF.type, this.mainRes("Experimenter"))
.addLiteral(name, experimenter)
// TODO Check if this is actually correct or if the subclass
// TODO is supposed to be found only in the definition.
.addProperty(RDFS.subClassOf, personRes);
}
// Fetch RDF Experimenter instance.
final Resource experimenterRes = this.fetchInstance(this.experimenterList.get(experimenter));
// Create current RDF Experiment instance.
final Resource exp = this.addExperimentEntry(currEntry, subjectID);
// Link current RDF Experiment instance to RDF Experimenter instance and RDF SubjectLogEntry instance.
exp.addProperty(this.mainProp("hasProvenance"), this.fetchInstance(provID))
.addProperty(this.mainProp("hasExperimenter"), experimenterRes)
.addProperty(this.mainProp("hasSubject"), subject);
projectRes.addProperty(this.mainProp("hasExperiment"), exp);
// Create current RDF SubjectLogEntry instance.
final Resource subjectLogEntry = this.addSubjectLogEntry(currEntry, subjectID);
// Link RDF SubjectLogEntry instance to RDF Experimenter instance.
subjectLogEntry
.addProperty(this.mainProp("hasProvenance"), this.fetchInstance(provID))
.addProperty(this.mainProp("hasExperimenter"), experimenterRes);
// Add RDF SubjectLogEntry instance to the current RDF Subject instance.
subject.addProperty(this.mainProp("hasSubjectLogEntry"), subjectLogEntry);
}
/**
* Create RDF Experiment instance. A hash ID is created as identifier for this instance
* using the {@link Utils#getHashSHA} method.
* The Hash ID of an RDF Experiment instance uses primary key: SubjectID, Paradigm, Experiment,
* Experimenter, DateTime (XSDDateTime format)
* Rational: an experimenter could potentially run two different experiments at the same time with the same
* subject, but not within the same paradigm.
* @param currEntry Current entry line of the parsed ODS file.
* @param subjectID Plain ID of the current test subject the experiment is connected to.
* @return Created Experiment instance.
*/
private Resource addExperimentEntry(final LKTLogParserEntry currEntry, final String subjectID) {
final String expDate = currEntry.getExperimentDate().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
final ArrayList<String> experimentList = new ArrayList<>(Arrays.asList(
subjectID, currEntry.getParadigm(), currEntry.getExperiment(),
currEntry.getExperimenterName(), expDate));
final Resource experiment = this.createInst(Utils.getHashSHA(experimentList))
.addProperty(RDF.type, this.mainRes("Experiment"))
.addLiteral(
this.mainProp("startedAt"),
this.mainTypedLiteral(expDate, XSDDatatype.XSDdateTime)
)
.addLiteral(RDFS.label, currEntry.getExperiment());
RDFUtils.addNonEmptyLiteral(experiment, this.mainProp("hasParadigm"), currEntry.getParadigm());
RDFUtils.addNonEmptyLiteral(experiment, this.mainProp("hasParadigmSpecifics"),
currEntry.getParadigmSpecifics());
RDFUtils.addNonEmptyLiteral(experiment, RDFS.comment, currEntry.getCommentExperiment());
return experiment;
}
/**
* Create RDF SubjectLogEntry instance. A hash ID is created as identifier for this instance
* using the {@link Utils#getHashSHA} method.
* Hash ID of an RDF SubjectLogEntry instance uses primary key:
* SubjectID, Experimenter, DateTime (XSDDateTime format)
* Problem: same as with the Hash ID created for Experimenter, the name used here has to be in the
* proper order and of the same spelling to create the same Hash ID.
* Rational: there can only be one SubjectLogEntry at a particular point in time.
* @param currEntry Current entry line of the parsed ODS file.
* @param subjectID Plain ID of the current test subject the experiment is connected to.
* @return Created SubjectLogEntry instance.
*/
private Resource addSubjectLogEntry(final LKTLogParserEntry currEntry, final String subjectID) {
final String logDate = currEntry.getExperimentDate().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
final ArrayList<String> subjLogList =
new ArrayList<>(Arrays.asList(subjectID, currEntry.getExperimenterName(), logDate));
final Resource res = this.createInst(Utils.getHashSHA(subjLogList))
.addProperty(RDF.type, this.mainRes("SubjectLogEntry"))
.addLiteral(
this.mainProp("startedAt"),
this.mainTypedLiteral(logDate, XSDDatatype.XSDdateTime)
)
.addLiteral(
this.mainProp("hasDiet"),
this.mainTypedLiteral(currEntry.getIsOnDiet().toString(), XSDDatatype.XSDboolean))
.addLiteral(
this.mainProp("hasInitialWeightDate"),
this.mainTypedLiteral(currEntry.getIsInitialWeight().toString(), XSDDatatype.XSDboolean)
);
if (currEntry.getWeight() != null) {
final Resource weight = this.model.createResource()
.addLiteral(this.mainProp("hasValue"), currEntry.getWeight())
.addLiteral(this.mainProp("hasUnit"), "g");
res.addProperty(this.mainProp("hasWeight"), weight);
}
RDFUtils.addNonEmptyLiteral(res, RDFS.comment, currEntry.getCommentSubject());
RDFUtils.addNonEmptyLiteral(res, this.mainProp("hasFeed"), currEntry.getFeed());
return res;
}
/**
* Convenience method for fetching an RDF resource from
* an existing UUID.
* @param fetchID ID corresponding to the required Resource.
* @return Requested Resource.
*/
private Resource fetchInstance(final String fetchID) {
return this.model.getResource(
String.join("", LKTLogToRDF.RDF_NS_LKT, fetchID)
);
}
/**
* Convenience method for creating an RDF resource with the
* Namespace used for instances used by this crawler.
* @param resName Contains the name of the resource.
* @return The created RDF Resource.
*/
private Resource createInst(final String resName) {
return this.model.createResource(
String.join("", LKTLogToRDF.RDF_NS_LKT, resName)
);
}
/**
* Convenience method for creating an RDF resource with the
* Namespace of the G-Node ontology to define Classes and Properties.
* @param resName Contains the name of the resource.
* @return The created RDF Resource.
*/
private Resource mainRes(final String resName) {
return this.model.createResource(
String.join("", RDFUtils.RDF_NS_GN_ONT, resName)
);
}
/**
* Convenience method for creating an RDF property with the
* Namespace of the G-Node ontology.
* @param propName Contains the name of the property.
* @return The created RDF Property.
*/
private Property mainProp(final String propName) {
return this.model.createProperty(
String.join("", RDFUtils.RDF_NS_GN_ONT, propName)
);
}
/**
* Convenience method for creating a typed literal with the
* Namespace of the G-Node ontology.
* @param litVal Contains the value of the Literal.
* @param litType Contains the RDFDatatype of the returned Literal.
* @return The created typed Literal.
*/
private Literal mainTypedLiteral(final String litVal, final RDFDatatype litType) {
return this.model.createTypedLiteral(litVal, litType);
}
} |
package org.java_websocket.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.UnresolvedAddressException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.java_websocket.SocketChannelIOHelper;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketAdapter;
import org.java_websocket.WebSocketFactory;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.WrappedByteChannel;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_10;
import org.java_websocket.exceptions.InvalidHandshakeException;
import org.java_websocket.framing.CloseFrame;
import org.java_websocket.handshake.HandshakeImpl1Client;
import org.java_websocket.handshake.Handshakedata;
import org.java_websocket.handshake.ServerHandshake;
/**
* The <tt>WebSocketClient</tt> is an abstract class that expects a valid
* "ws://" URI to connect to. When connected, an instance recieves important
* events related to the life of the connection. A subclass must implement
* <var>onOpen</var>, <var>onClose</var>, and <var>onMessage</var> to be
* useful. An instance can send messages to it's connected server via the
* <var>send</var> method.
*
* @author Nathan Rajlich
*/
public abstract class WebSocketClient extends WebSocketAdapter implements Runnable {
/**
* The URI this channel is supposed to connect to.
*/
private URI uri = null;
/**
* The WebSocket instance this channel object wraps.
*/
private WebSocketImpl conn = null;
/**
* The SocketChannel instance this channel uses.
*/
private SocketChannel channel = null;
private ByteChannel wrappedchannel = null;
private SelectionKey key = null;
/**
* The 'Selector' used to get event keys from the underlying socket.
*/
private Selector selector = null;
private Thread thread;
private Draft draft;
private Map<String,String> headers;
WebSocketClientFactory wf = new WebSocketClientFactory() {
@Override
public WebSocket createWebSocket( WebSocketAdapter a, Draft d, Socket s ) {
return new WebSocketImpl( WebSocketClient.this, d, s );
}
@Override
public WebSocket createWebSocket( WebSocketAdapter a, List<Draft> d, Socket s ) {
return new WebSocketImpl( WebSocketClient.this, d, s );
}
@Override
public ByteChannel wrapChannel( SelectionKey c, String host, int port ) {
return (ByteChannel) c.channel();
}
};
public WebSocketClient( URI serverURI ) {
this( serverURI, new Draft_10() );
}
/**
* Constructs a WebSocketClient instance and sets it to the connect to the
* specified URI. The channel does not attampt to connect automatically. You
* must call <var>connect</var> first to initiate the socket connection.
*/
public WebSocketClient( URI serverUri , Draft draft ) {
this( serverUri, draft, null );
}
public WebSocketClient( URI serverUri , Draft draft , Map<String,String> headers ) {
if( serverUri == null ) {
throw new IllegalArgumentException();
}
if( draft == null ) {
throw new IllegalArgumentException( "null as draft is permitted for `WebSocketServer` only!" );
}
this.uri = serverUri;
this.draft = draft;
this.headers = headers;
}
/**
* Gets the URI that this WebSocketClient is connected to.
*
* @return The <tt>URI</tt> for this WebSocketClient.
*/
public URI getURI() {
return uri;
}
/** Returns the protocol version this channel uses. */
public Draft getDraft() {
return draft;
}
/**
* Starts a background thread that attempts and maintains a WebSocket
* connection to the URI specified in the constructor or via <var>setURI</var>.
* <var>setURI</var>.
*/
public void connect() {
if( thread != null )
throw new IllegalStateException( "already/still connected" );
thread = new Thread( this );
thread.start();
}
public void close() {
if( thread != null ) {
conn.close( CloseFrame.NORMAL );
/*closelock.lock();
try {
if( selector != null )
selector.wakeup();
} finally {
closelock.unlock();
}*/
}
}
/**
* Sends <var>text</var> to the connected WebSocket server.
*
* @param text
* The String to send to the WebSocket server.
*/
public void send( String text ) throws NotYetConnectedException {
if( conn != null ) {
conn.send( text );
}
}
/**
* Sends <var>data</var> to the connected WebSocket server.
*
* @param data
* The Byte-Array of data to send to the WebSocket server.
*/
public void send( byte[] data ) throws NotYetConnectedException {
if( conn != null ) {
conn.send( data );
}
}
private void tryToConnect( InetSocketAddress remote ) throws IOException {
channel = SocketChannel.open();
channel.configureBlocking( false );
channel.connect( remote );
selector = Selector.open();
key = channel.register( selector, SelectionKey.OP_CONNECT );
}
// Runnable IMPLEMENTATION /////////////////////////////////////////////////
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
}
private final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try{
while ( channel.isOpen() ) {
SelectionKey key = null;
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
conn.eot();
continue;
}
if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, wrappedchannel ) ) {
conn.decode( buff );
}
if( key.isConnectable() ) {
try {
finishConnect( key );
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
}
}
if( key.isWritable() ) {
if( SocketChannelIOHelper.batch( conn, wrappedchannel ) ) {
if( key.isValid() )
key.interestOps( SelectionKey.OP_READ );
} else {
key.interestOps( SelectionKey.OP_READ | SelectionKey.OP_WRITE );
}
}
}
if( wrappedchannel instanceof WrappedByteChannel ) {
WrappedByteChannel w = (WrappedByteChannel) wrappedchannel;
if( w.isNeedRead() ) {
while ( SocketChannelIOHelper.read( buff, conn, w ) ) {
conn.decode( buff );
}
}
}
}
} catch ( CancelledKeyException e ) {
conn.eot();
} catch ( IOException e ) {
// onError( e );
conn.eot();
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
}
}
private int getPort() {
int port = uri.getPort();
if( port == -1 ) {
String scheme = uri.getScheme();
if( scheme.equals( "wss" ) ) {
return WebSocket.DEFAULT_WSS_PORT;
} else if( scheme.equals( "ws" ) ) {
return WebSocket.DEFAULT_PORT;
} else {
throw new RuntimeException( "unkonow scheme" + scheme );
}
}
return port;
}
private void finishConnect( SelectionKey key ) throws IOException , InvalidHandshakeException {
if( channel.isConnectionPending() ) {
channel.finishConnect();
}
// Now that we're connected, re-register for only 'READ' keys.
conn.key = key.interestOps( SelectionKey.OP_READ | SelectionKey.OP_WRITE );
conn.channel = wrappedchannel = wf.wrapChannel( key, uri.getHost(), getPort() );
sendHandshake();
}
private void sendHandshake() throws InvalidHandshakeException {
String path;
String part1 = uri.getPath();
String part2 = uri.getQuery();
if( part1 == null || part1.length() == 0 )
path = "/";
else
path = part1;
if( part2 != null )
path += "?" + part2;
int port = getPort();
String host = uri.getHost() + ( port != WebSocket.DEFAULT_PORT ? ":" + port : "" );
HandshakeImpl1Client handshake = new HandshakeImpl1Client();
handshake.setResourceDescriptor( path );
handshake.put( "Host", host );
if( headers != null ) {
for( Map.Entry<String,String> kv : headers.entrySet() ) {
handshake.put( kv.getKey(), kv.getValue() );
}
}
conn.startHandshake( handshake );
}
/**
* Retrieve the WebSocket 'readyState'.
* This represents the state of the connection.
* It returns a numerical value, as per W3C WebSockets specs.
*
* @return Returns '0 = CONNECTING', '1 = OPEN', '2 = CLOSING' or '3 = CLOSED'
*/
public int getReadyState() {
if( conn == null ) {
return WebSocket.READY_STATE_CONNECTING;
}
return conn.getReadyState();
}
/**
* Calls subclass' implementation of <var>onMessage</var>.
*
* @param conn
* @param message
*/
@Override
public final void onWebsocketMessage( WebSocket conn, String message ) {
onMessage( message );
}
@Override
public final void onWebsocketMessage( WebSocket conn, ByteBuffer blob ) {
onMessage( blob );
}
/**
* Calls subclass' implementation of <var>onOpen</var>.
*
* @param conn
*/
@Override
public final void onWebsocketOpen( WebSocket conn, Handshakedata handshake ) {
onOpen( (ServerHandshake) handshake );
}
/**
* Calls subclass' implementation of <var>onClose</var>.
*
* @param conn
*/
@Override
public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) {
onClose( code, reason, remote );
}
/**
* Calls subclass' implementation of <var>onIOError</var>.
*
* @param conn
*/
@Override
public final void onWebsocketError( WebSocket conn, Exception ex ) {
onError( ex );
}
@Override
public final void onWriteDemand( WebSocket conn ) {
try {
key.interestOps( SelectionKey.OP_READ | SelectionKey.OP_WRITE );
selector.wakeup();
} catch ( CancelledKeyException e ) {
// since such an exception/event will also occur on the selector there is no need to do anything here
}
}
public WebSocket getConnection() {
return conn;
}
public final void setWebSocketFactory( WebSocketClientFactory wsf ) {
this.wf = wsf;
}
public final WebSocketFactory getWebSocketFactory() {
return wf;
}
// ABTRACT METHODS /////////////////////////////////////////////////////////
public abstract void onOpen( ServerHandshake handshakedata );
public abstract void onMessage( String message );
public abstract void onClose( int code, String reason, boolean remote );
public abstract void onError( Exception ex );
public void onMessage( ByteBuffer bytes ) {
};
public interface WebSocketClientFactory extends WebSocketFactory {
public ByteChannel wrapChannel( SelectionKey key, String host, int port ) throws IOException;
}
} |
package org.jenkinsci.plugins.badge;
import hudson.model.BallColor;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import static jenkins.model.Jenkins.getInstance;
import org.apache.commons.io.IOUtils;
import static org.apache.commons.io.IOUtils.toInputStream;
/**
* TO DO
* @author dkersch
*/
public class ImageResolver {
/**
* TO DO
*/
private final HashMap<String, StatusImage[]> styles;
/**
* TO DO
*/
private final StatusImage[] defaultStyle;
/**
* TO DO
*/
public static final String RED = "#cc0000";
/**
* TO DO
*/
public static final String YELLOW = "#b2b200";
/**
* TO DO
*/
public static final String GREEN = "#008000";
/**
* TO DO
*/
public static final String GREY = "#808080";
/**
* TO DO
*/
public static final String BLUE = "#007ec6";
/**
* TO DO
* @throws IOException
*/
public ImageResolver() throws IOException {
styles = new HashMap<String, StatusImage[]>();
// shields.io "flat" style (new default from Feb 1 2015)
StatusImage[] flatImages;
flatImages = new StatusImage[]{
new StatusImage("build-failing-red-flat.svg"),
new StatusImage("build-unstable-yellow-flat.svg"),
new StatusImage("build-passing-brightgreen-flat.svg"),
new StatusImage("build-running-blue-flat.svg"),
new StatusImage("build-aborted-lightgrey-flat.svg"),
new StatusImage("build-unknown-lightgrey-flat.svg")
};
defaultStyle = flatImages;
styles.put("default", defaultStyle);
}
/**
* TO DO
* @param codeCoverage
* @return
*/
public StatusImage getCoverageImage(Integer codeCoverage) {
// TODO don't read file everytime, store this as a static variable in
// TODO memory with the constructor
URL image = null;
try {
image = new URL(
getInstance().pluginManager.getPlugin("embeddable-badges").baseResourceURL,
"status/build-coverage-flat.svg");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuilder sb = null;
try {
sb = new StringBuilder(IOUtils.toString(image.openStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String replacedImage = replaceCodeCoverageSVG(sb.toString(), codeCoverage);
InputStream is = toInputStream(replacedImage);
String etag = "status/build-coverage-flat.svg" + codeCoverage;
try {
return new StatusImage(etag, is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* TO DO
* @param image
* @param codeCoverage
* @return
*/
private String replaceCodeCoverageSVG(String image, Integer codeCoverage) {
if (codeCoverage == null) {
String modifiedColor = image.replace("{hex-color-to-change}", GREY);
return modifiedColor.replace("{code-coverage-to-change}", "0");
} else if (codeCoverage < 20) {
String modifiedColor = image.replace("{hex-color-to-change}", RED);
return modifiedColor.replace("{code-coverage-to-change}", codeCoverage.toString());
} else if (codeCoverage < 80) {
String modifiedColor = image.replace("{hex-color-to-change}", YELLOW);
return modifiedColor.replace("{code-coverage-to-change}", codeCoverage.toString());
} else {
String modifiedColor = image.replace("{hex-color-to-change}", GREEN);
return modifiedColor.replace("{code-coverage-to-change}", codeCoverage.toString());
}
}
/**
* TO DO
* @param testPass
* @param testTotal
* @return
*/
public StatusImage getTestResultImage(Integer testPass, Integer testTotal) {
// TODO don't read file everytime
// TODO store this as a static variable in memory with the constructor
URL image = null;
try {
image = new URL(
getInstance().pluginManager.getPlugin("embeddable-badges").baseResourceURL,
"status/build-test-result-flat.svg");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuilder sb = null;
try {
sb = new StringBuilder(IOUtils.toString(image.openStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String replacedImage = replaceTestResultSVG(sb.toString(), testPass, testTotal);
InputStream is = toInputStream(replacedImage);
String etag = "status/build-test-result-flat.svg" + testPass + testTotal;
try {
return new StatusImage(etag, is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* TO DO
* @param image
* @param testPass
* @param testTotal
* @return
*/
private String replaceTestResultSVG(String image, Integer testPass, Integer testTotal) {
if (testTotal == null || testPass == null) {
String modifiedColor = image.replace("{hex-color-to-change}", GREY);
return modifiedColor.replace("{passed-tests}/{total-tests}", "n/a");
}
else {
double passTest = (double) (testPass);
double passTotal = (double) (testTotal);
double passPercent = (passTest / passTotal) * 100.0;
if (passPercent < 20) {
String modifiedColor = image.replace("{hex-color-to-change}", RED);
String modifiedPass = modifiedColor.replace("{passed-tests}", testPass.toString());
return modifiedPass.replace("{total-tests}", testTotal.toString());
} else if (passPercent < 80) {
String modifiedColor = image.replace("{hex-color-to-change}", YELLOW);
String modifiedPass = modifiedColor.replace("{passed-tests}", testPass.toString());
return modifiedPass.replace("{total-tests}", testTotal.toString());
} else {
String modifiedColor = image.replace("{hex-color-to-change}", GREEN);
String modifiedPass = modifiedColor.replace("{passed-tests}", testPass.toString());
return modifiedPass.replace("{total-tests}", testTotal.toString());
}
}
}
/**
* TO DO
* @param color
* @return
*/
public StatusImage getImage(BallColor color) {
StatusImage[] images = styles.get("default");
if (color.isAnimated()) {
return images[3];
}
switch (color) {
case RED:
return images[0];
case YELLOW:
return images[1];
case BLUE:
return images[2];
case ABORTED:
return images[4];
default:
return images[5];
}
}
/**
* TO DO
* @param image
* @param testPass
* @param testTotal
* @return
*/
private String replaceBuildDescriptionSVG(String image, String buildDescription) {
if (buildDescription == null) {
String modifiedColor = image.replace("{hex-color-to-change}", GREY);
return modifiedColor.replace("{description_text}", "n/a");
}
else {
String modifiedColor = image.replace("{hex-color-to-change}", BLUE);
String modifiedPass = modifiedColor.replace("{description_text}", buildDescription);
return modifiedPass;
}
}
public StatusImage getBuildDescriptionImage(String buildDescription) {
// TODO don't read file everytime
// TODO store this as a static variable in memory with the constructor
URL image = null;
try {
image = new URL(
getInstance().pluginManager.getPlugin("embeddable-badges").baseResourceURL,
"status/build-description-flat.svg");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuilder sb = null;
try {
sb = new StringBuilder(IOUtils.toString(image.openStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String replacedImage = replaceBuildDescriptionSVG(sb.toString(), buildDescription);
InputStream is = toInputStream(replacedImage);
String etag = "status/build-description-flat.svg" + buildDescription;
try {
return new StatusImage(etag, is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
} |
package org.lightmare.jpa.datasource;
/**
* Configuration of jdbc driver classes and database names
*
* @author levan
*
*/
public class DriverConfig {
// Driver class names
private static final String ORACLE_DRIVER = "oracle.jdbc.OracleDriver";
private static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
private static final String MSSQL_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String DB2_DRIVER = "com.ibm.db2.jcc.DB2Driver";
private static final String H2_DRIVER = "org.h2.Driver";
private static final String DERBY_DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
// Database names
private static final String ORACLE_NAME = "oracle";
private static final String MYSQL_NAME = "mysql";
private static final String DB2_NAME = "db2";
private static final String MSSQL_NAME = "mssql";
private static final String H2_NAME = "h2";
private static final String DERBY_NAME = "derby";
/**
* Caches database driver names and classes
*
* @author levan
*
*/
public static enum Drivers {
ORACLE("oracle", "oracle.jdbc.OracleDriver"), // Oracle
MYSQL("mysql", "com.mysql.jdbc.Driver"), // MYSQL
MSSQL("mssql", "com.microsoft.sqlserver.jdbc.SQLServerDriver"), // MSSQL
DB2("db2", "com.ibm.db2.jcc.DB2Driver"), // DB2
H2("h2", "org.h2.Driver"),
DERBY("derby", "org.apache.derby.jdbc.EmbeddedDriver"); // DERBY
// Database names
public String name;
// Driver class names
public String driver;
private Drivers(String name, String driver) {
this.name = name;
this.driver = driver;
}
}
/**
* Resolves appropriate jdbc driver class name by database name
*
* @param name
* @return {@link String}
*/
public static String getDriverName(String name) {
if (ORACLE_NAME.equals(name)) {
return ORACLE_DRIVER;
} else if (MYSQL_NAME.equals(name)) {
return MYSQL_DRIVER;
} else if (DB2_NAME.equals(name)) {
return DB2_DRIVER;
} else if (MSSQL_NAME.equals(name)) {
return MSSQL_DRIVER;
} else if (H2_NAME.equals(name)) {
return H2_DRIVER;
} else if (DERBY_NAME.equals(name)) {
return DERBY_DRIVER;
} else {
return null;
}
}
public static boolean isOracle(String name) {
return ORACLE_DRIVER.equals(name);
}
public static boolean isMySQL(String name) {
return MYSQL_DRIVER.equals(name);
}
public static boolean isDB2(String name) {
return DB2_DRIVER.equals(name);
}
public static boolean isMsSQL(String name) {
return MSSQL_DRIVER.equals(name);
}
public static boolean isH2(String name) {
return H2_DRIVER.equals(name);
}
public static boolean isDerby(String name) {
return DERBY_DRIVER.equals(name);
}
} |
package org.lightmare.jpa.jta;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.jpa.JpaManager;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
/**
* Implementation of {@link UserTransaction} interface for JNDI and EJB beans
*
* @author levan
*
*/
public class UserTransactionImpl implements UserTransaction {
// Caches EntityTransaction instances for immediate commit or join with
// other transactions
private Stack<EntityTransaction> transactions;
// Caches EntityManager instances for clear up
private Stack<EntityManager> ems;
// Caches EntityTransaction instances for immediate commit
private Stack<EntityTransaction> requareNews;
// Caches EntityManager instances for immediate clean up
private Stack<EntityManager> requareNewEms;
// Object which first called this (UserTransaction) instance
private Object caller;
// Denotes active transaction
private static int ACTIVE = 1;
// Denotes inactive transaction
private static int INACTIVE = 0;
private static final String TIMEOUT_NOT_SUPPORTED_ERROR = "Timeouts are not supported yet";
protected UserTransactionImpl(EntityTransaction... transactions) {
this.transactions = new Stack<EntityTransaction>();
if (CollectionUtils.valid(transactions)) {
addTransactions(transactions);
}
}
/**
* Adds {@link EntityTransaction} to transactions {@link List} for further
* processing
*
* @param transaction
*/
public void addTransaction(EntityTransaction transaction) {
transactions.add(transaction);
}
/**
* Adds {@link EntityTransaction}s to transactions {@link List} for further
* processing
*
* @param transactions
*/
public void addTransactions(EntityTransaction... transactions) {
Collections.addAll(this.transactions, transactions);
}
/**
* Adds {@link EntityManager} to collection to close after transactions
* processing
*
* @param em
*/
public void addEntityManager(EntityManager em) {
if (ObjectUtils.notNull(em)) {
if (ems == null) {
ems = new Stack<EntityManager>();
}
ems.push(em);
}
}
/**
* Adds {@link EntityManager}'s to collection to close after transactions
* processing
*
* @param em
*/
public void addEntityManagers(Collection<EntityManager> ems) {
if (CollectionUtils.valid(ems)) {
for (EntityManager em : ems) {
addEntityManager(em);
}
}
}
/**
* Adds new {@link EntityTransaction} for
* {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} annotated bean
* methods
*
* @param entityTransaction
*/
public void pushReqNew(EntityTransaction entityTransaction) {
getNews().push(entityTransaction);
}
/**
* Adds {@link EntityManager} to collection to close after
* {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} type transactions
* processing
*
* @param em
*/
public void pushReqNewEm(EntityManager em) {
getNewEms().push(em);
}
/**
* Closes each of passed {@link EntityManager}s {@link Stack}
*
* @param entityManagers
*/
private void close(Stack<EntityManager> entityManagers) {
if (CollectionUtils.valid(entityManagers)) {
EntityManager em;
while (CollectionUtils.notEmpty(entityManagers)) {
em = entityManagers.pop();
JpaManager.closeEntityManager(em);
}
}
}
private void setRollbackOnly(EntityTransaction transaction)
throws IllegalStateException, SystemException {
if (transaction.isActive()) {
transaction.setRollbackOnly();
}
}
private void setRollbackOnly(
Collection<EntityTransaction> entityTransactions)
throws IllegalStateException, SystemException {
if (CollectionUtils.valid(entityTransactions)) {
for (EntityTransaction entityTransaction : entityTransactions) {
setRollbackOnly(entityTransaction);
}
}
}
/**
* Begins each of passed {@link EntityTransaction}s {@link Collection}
*
* @param entityTransactions
* @throws NotSupportedException
* @throws SystemException
*/
private void begin(Collection<EntityTransaction> entityTransactions)
throws NotSupportedException, SystemException {
if (CollectionUtils.valid(entityTransactions))
for (EntityTransaction transaction : entityTransactions) {
transaction.begin();
}
}
private void commit(EntityTransaction transaction)
throws RollbackException, HeuristicMixedException,
HeuristicRollbackException, SecurityException,
IllegalStateException, SystemException {
if (transaction.isActive()) {
transaction.commit();
}
}
private void commit(Stack<EntityTransaction> entityTransactions)
throws SecurityException, IllegalStateException, RollbackException,
HeuristicMixedException, HeuristicRollbackException,
SystemException {
if (CollectionUtils.valid(entityTransactions)) {
EntityTransaction entityTransaction;
while (CollectionUtils.notEmpty(entityTransactions)) {
entityTransaction = entityTransactions.pop();
commit(entityTransaction);
}
}
}
/**
* Rollbacks passed {@link EntityTransaction} if it is active
*
* @param transaction
*/
private void rollback(EntityTransaction transaction) {
if (transaction.isActive()) {
transaction.rollback();
}
}
/**
* Rollbacks each of {@link EntityTransaction}s {@link Stack}
*
* @param entityTransactions
*/
private void rollback(Stack<EntityTransaction> entityTransactions) {
if (CollectionUtils.valid(entityTransactions)) {
EntityTransaction entityTransaction;
while (CollectionUtils.notEmpty(entityTransactions)) {
entityTransaction = entityTransactions.pop();
rollback(entityTransaction);
}
}
}
/**
* Closes all cached immediate {@link EntityManager} instances
*/
private void closeReqNew() {
close(requareNewEms);
}
/**
* Closes all contained {@link EntityManager}s
*/
public void closeEntityManagers() {
close(ems);
}
@Override
public void begin() throws NotSupportedException, SystemException {
if (CollectionUtils.valid(transactions)) {
begin(transactions);
}
}
@Override
public void commit() throws RollbackException, HeuristicMixedException,
HeuristicRollbackException, SecurityException,
IllegalStateException, SystemException {
try {
if (CollectionUtils.valid(transactions)) {
commit(transactions);
}
} finally {
closeEntityManagers();
}
}
@Override
public int getStatus() throws SystemException {
int active = INACTIVE;
if (CollectionUtils.valid(transactions)) {
for (EntityTransaction transaction : transactions) {
boolean isActive = transaction.isActive();
active += isActive ? ACTIVE : INACTIVE;
}
}
if (CollectionUtils.valid(requareNews)) {
for (EntityTransaction transaction : requareNews) {
boolean isActive = transaction.isActive();
active += isActive ? ACTIVE : INACTIVE;
}
}
return active;
}
/**
* Rollbacks new {@link EntityTransaction} at the end of
* {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} annotated bean
* methods
*/
public void rollbackReqNews() throws IllegalStateException,
SecurityException, SystemException {
try {
rollback(requareNews);
} finally {
closeReqNew();
}
}
@Override
public void rollback() throws IllegalStateException, SecurityException,
SystemException {
try {
rollback(transactions);
} finally {
closeEntityManagers();
}
}
@Override
public void setRollbackOnly() throws IllegalStateException, SystemException {
setRollbackOnly(transactions);
}
@Override
public void setTransactionTimeout(int time) throws SystemException {
throw new UnsupportedOperationException(TIMEOUT_NOT_SUPPORTED_ERROR);
}
private Stack<EntityTransaction> getNews() {
if (requareNews == null) {
requareNews = new Stack<EntityTransaction>();
}
return requareNews;
}
private Stack<EntityManager> getNewEms() {
if (requareNewEms == null) {
requareNewEms = new Stack<EntityManager>();
}
return requareNewEms;
}
public void commitReqNew() throws SecurityException, IllegalStateException,
RollbackException, HeuristicMixedException,
HeuristicRollbackException, SystemException {
try {
commit(requareNews);
} finally {
closeReqNew();
}
}
public boolean checkCaller(BeanHandler handler) {
boolean check = ObjectUtils.notNull(caller);
if (check) {
check = caller.equals(handler.getBean());
}
return check;
}
public void setCaller(BeanHandler handler) {
caller = handler.getBean();
}
public Object getCaller() {
return caller;
}
/**
* Closes all cached {@link EntityManager} isntances
*/
public void close() {
closeEntityManagers();
closeReqNew();
}
} |
package org.lightmare.jpa.jta;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.jpa.JpaManager;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
/**
* Implementation of {@link UserTransaction} interface for JNDI and EJB beans
*
* @author levan
*
*/
public class UserTransactionImpl implements UserTransaction {
// Caches EntityTransaction instances for immediate commit or join with
// other transactions
private Stack<EntityTransaction> transactions;
// Caches EntityManager instances for clear up
private Stack<EntityManager> ems;
// Caches EntityTransaction instances for immediate commit
private Stack<EntityTransaction> requareNews;
// Caches EntityManager instances for immediate clean up
private Stack<EntityManager> requareNewEms;
private Stack<EntityManager> notTransactionalEms;
// Object which first called this (UserTransaction) instance
private Object caller;
// Denotes active transaction
private static int ACTIVE = 1;
// Denotes inactive transaction
private static int INACTIVE = 0;
private static final String TIMEOUT_NOT_SUPPORTED_ERROR = "Timeouts are not supported yet";
protected UserTransactionImpl(EntityTransaction... transactions) {
this.transactions = new Stack<EntityTransaction>();
if (CollectionUtils.valid(transactions)) {
addTransactions(transactions);
}
}
/**
* Adds {@link EntityTransaction} to transactions {@link List} for further
* processing
*
* @param transaction
*/
public void addTransaction(EntityTransaction transaction) {
transactions.add(transaction);
}
/**
* Adds {@link EntityTransaction}s to transactions {@link List} for further
* processing
*
* @param transactions
*/
public void addTransactions(EntityTransaction... transactions) {
Collections.addAll(this.transactions, transactions);
}
/**
* Adds {@link EntityManager} to collection to close after transactions
* processing
*
* @param em
*/
public void addEntityManager(EntityManager em) {
if (ObjectUtils.notNull(em)) {
if (ems == null) {
ems = new Stack<EntityManager>();
}
ems.push(em);
}
}
/**
* Adds {@link EntityManager}'s to collection to close after transactions
* processing
*
* @param em
*/
public void addEntityManagers(Collection<EntityManager> ems) {
if (CollectionUtils.valid(ems)) {
for (EntityManager em : ems) {
addEntityManager(em);
}
}
}
private Stack<EntityTransaction> getNews() {
if (requareNews == null) {
requareNews = new Stack<EntityTransaction>();
}
return requareNews;
}
private Stack<EntityManager> getNewEms() {
if (requareNewEms == null) {
requareNewEms = new Stack<EntityManager>();
}
return requareNewEms;
}
private Stack<EntityManager> getNotTransactionalEms() {
if (notTransactionalEms == null) {
notTransactionalEms = new Stack<EntityManager>();
}
return notTransactionalEms;
}
/**
* Adds new {@link EntityTransaction} for
* {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} annotated bean
* methods
*
* @param entityTransaction
*/
public void pushReqNew(EntityTransaction entityTransaction) {
getNews().push(entityTransaction);
}
/**
* Adds {@link EntityManager} to collection to close after
* {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} type transactions
* processing
*
* @param em
*/
public void pushReqNewEm(EntityManager em) {
getNewEms().push(em);
}
/**
* Adds {@link EntityManager} to collection of not supported declarative
* transactions
*
* @param em
*/
public void pushNotSupportedEm(EntityManager em) {
getNotSupportedEms().push(em);
}
/**
* Closes each of passed {@link EntityManager}s {@link Stack}
*
* @param entityManagers
*/
private void close(Stack<EntityManager> entityManagers) {
if (CollectionUtils.valid(entityManagers)) {
EntityManager em;
while (CollectionUtils.notEmpty(entityManagers)) {
em = entityManagers.pop();
JpaManager.closeEntityManager(em);
}
}
}
private void setRollbackOnly(EntityTransaction transaction)
throws IllegalStateException, SystemException {
if (transaction.isActive()) {
transaction.setRollbackOnly();
}
}
private void setRollbackOnly(
Collection<EntityTransaction> entityTransactions)
throws IllegalStateException, SystemException {
if (CollectionUtils.valid(entityTransactions)) {
for (EntityTransaction entityTransaction : entityTransactions) {
setRollbackOnly(entityTransaction);
}
}
}
/**
* Begins each of passed {@link EntityTransaction}s {@link Collection}
*
* @param entityTransactions
* @throws NotSupportedException
* @throws SystemException
*/
private void begin(Collection<EntityTransaction> entityTransactions)
throws NotSupportedException, SystemException {
if (CollectionUtils.valid(entityTransactions))
for (EntityTransaction transaction : entityTransactions) {
transaction.begin();
}
}
private void commit(EntityTransaction transaction)
throws RollbackException, HeuristicMixedException,
HeuristicRollbackException, SecurityException,
IllegalStateException, SystemException {
if (transaction.isActive()) {
transaction.commit();
}
}
private void commit(Stack<EntityTransaction> entityTransactions)
throws SecurityException, IllegalStateException, RollbackException,
HeuristicMixedException, HeuristicRollbackException,
SystemException {
if (CollectionUtils.valid(entityTransactions)) {
EntityTransaction entityTransaction;
while (CollectionUtils.notEmpty(entityTransactions)) {
entityTransaction = entityTransactions.pop();
commit(entityTransaction);
}
}
}
/**
* Rollbacks passed {@link EntityTransaction} if it is active
*
* @param transaction
*/
private void rollback(EntityTransaction transaction) {
if (transaction.isActive()) {
transaction.rollback();
}
}
/**
* Rollbacks each of {@link EntityTransaction}s {@link Stack}
*
* @param entityTransactions
*/
private void rollback(Stack<EntityTransaction> entityTransactions) {
if (CollectionUtils.valid(entityTransactions)) {
EntityTransaction entityTransaction;
while (CollectionUtils.notEmpty(entityTransactions)) {
entityTransaction = entityTransactions.pop();
rollback(entityTransaction);
}
}
}
/**
* Closes all cached immediate {@link EntityManager} instances
*/
private void closeReqNew() {
close(requareNewEms);
}
/**
* Closes all contained {@link EntityManager}s
*/
public void closeEntityManagers() {
close(ems);
}
/**
* Begins all require new transactions
*
* @throws NotSupportedException
* @throws SystemException
*/
public void beginReqNews() throws NotSupportedException, SystemException {
if (CollectionUtils.valid(requareNews)) {
begin(requareNews);
}
}
@Override
public void begin() throws NotSupportedException, SystemException {
if (CollectionUtils.valid(transactions)) {
begin(transactions);
}
}
public void commitReqNew() throws SecurityException, IllegalStateException,
RollbackException, HeuristicMixedException,
HeuristicRollbackException, SystemException {
try {
commit(requareNews);
} finally {
closeReqNew();
}
}
@Override
public void commit() throws RollbackException, HeuristicMixedException,
HeuristicRollbackException, SecurityException,
IllegalStateException, SystemException {
try {
if (CollectionUtils.valid(transactions)) {
commit(transactions);
}
} finally {
closeEntityManagers();
}
}
/**
* Rollbacks new {@link EntityTransaction} at the end of
* {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} annotated bean
* methods
*/
public void rollbackReqNews() throws IllegalStateException,
SecurityException, SystemException {
try {
rollback(requareNews);
} finally {
closeReqNew();
}
}
@Override
public void rollback() throws IllegalStateException, SecurityException,
SystemException {
try {
rollback(transactions);
} finally {
closeEntityManagers();
}
}
@Override
public void setRollbackOnly() throws IllegalStateException, SystemException {
setRollbackOnly(transactions);
}
@Override
public int getStatus() throws SystemException {
int active = INACTIVE;
if (CollectionUtils.valid(transactions)) {
for (EntityTransaction transaction : transactions) {
boolean isActive = transaction.isActive();
active += isActive ? ACTIVE : INACTIVE;
}
}
if (CollectionUtils.valid(requareNews)) {
for (EntityTransaction transaction : requareNews) {
boolean isActive = transaction.isActive();
active += isActive ? ACTIVE : INACTIVE;
}
}
return active;
}
@Override
public void setTransactionTimeout(int time) throws SystemException {
throw new UnsupportedOperationException(TIMEOUT_NOT_SUPPORTED_ERROR);
}
public boolean checkCaller(BeanHandler handler) {
boolean check = ObjectUtils.notNull(caller);
if (check) {
check = caller.equals(handler.getBean());
}
return check;
}
public void setCaller(BeanHandler handler) {
caller = handler.getBean();
}
public Object getCaller() {
return caller;
}
/**
* Closes all cached {@link EntityManager} isntances
*/
public void close() {
closeEntityManagers();
closeReqNew();
}
} |
package org.lightmare.jpa.jta;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.jpa.JpaManager;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
/**
* {@link UserTransaction} implementation for JNDI and EJB beans
*
* @author levan
*
*/
public class UserTransactionImpl implements UserTransaction {
// Caches EntityTransaction instances for immediate commit or join with
// other transactions
private Stack<EntityTransaction> transactions;
// Caches EntityManager instances for clear up
private Stack<EntityManager> ems;
// Caches EntityTransaction instances for immediate commit
private Stack<EntityTransaction> requareNews;
// Caches EntityManager instances for immediate clean up
private Stack<EntityManager> requareNewEms;
private Object caller;
// Denotes active transaction
private static int ACTIVE = 1;
// Denotes inactive transaction
private static int INACTIVE = 0;
public UserTransactionImpl(EntityTransaction... transactions) {
this.transactions = new Stack<EntityTransaction>();
if (CollectionUtils.valid(transactions)) {
addTransactions(transactions);
}
}
private void beginAll() throws NotSupportedException, SystemException {
for (EntityTransaction transaction : transactions) {
transaction.begin();
}
}
@Override
public void begin() throws NotSupportedException, SystemException {
if (CollectionUtils.valid(transactions)) {
beginAll();
}
}
private void commit(EntityTransaction transaction)
throws RollbackException, HeuristicMixedException,
HeuristicRollbackException, SecurityException,
IllegalStateException, SystemException {
if (transaction.isActive()) {
transaction.commit();
}
}
private void commitAll() throws RollbackException, HeuristicMixedException,
HeuristicRollbackException, SecurityException,
IllegalStateException, SystemException {
EntityTransaction transaction;
while (CollectionUtils.notEmpty(transactions)) {
transaction = transactions.pop();
commit(transaction);
}
}
@Override
public void commit() throws RollbackException, HeuristicMixedException,
HeuristicRollbackException, SecurityException,
IllegalStateException, SystemException {
try {
if (CollectionUtils.valid(transactions)) {
commitAll();
}
} finally {
closeEntityManagers();
}
}
@Override
public int getStatus() throws SystemException {
int active = INACTIVE;
if (CollectionUtils.valid(transactions)) {
for (EntityTransaction transaction : transactions) {
boolean isActive = transaction.isActive();
active += isActive ? ACTIVE : INACTIVE;
}
}
if (CollectionUtils.valid(requareNews)) {
for (EntityTransaction transaction : requareNews) {
boolean isActive = transaction.isActive();
active += isActive ? ACTIVE : INACTIVE;
}
}
return active;
}
/**
* Rollbacks passed {@link EntityTransaction} if it is active
*
* @param transaction
*/
private void rollback(EntityTransaction transaction) {
if (transaction.isActive()) {
transaction.rollback();
}
}
private void rollbackAll() throws IllegalStateException, SecurityException,
SystemException {
EntityTransaction transaction;
while (CollectionUtils.notEmpty(transactions)) {
transaction = transactions.pop();
rollback(transaction);
}
}
@Override
public void rollback() throws IllegalStateException, SecurityException,
SystemException {
try {
if (CollectionUtils.valid(transactions)) {
rollbackAll();
}
} finally {
closeEntityManagers();
}
}
private void setRollbackOnly(EntityTransaction transaction)
throws IllegalStateException, SystemException {
if (transaction.isActive()) {
transaction.setRollbackOnly();
}
}
private void setRollbackOnlyAll() throws IllegalStateException,
SystemException {
for (EntityTransaction transaction : transactions) {
setRollbackOnly(transaction);
}
}
@Override
public void setRollbackOnly() throws IllegalStateException, SystemException {
if (CollectionUtils.valid(transactions)) {
setRollbackOnlyAll();
}
}
@Override
public void setTransactionTimeout(int time) throws SystemException {
throw new UnsupportedOperationException(
"Timeouts are not supported yet");
}
private Stack<EntityTransaction> getNews() {
if (requareNews == null) {
requareNews = new Stack<EntityTransaction>();
}
return requareNews;
}
private Stack<EntityManager> getNewEms() {
if (requareNewEms == null) {
requareNewEms = new Stack<EntityManager>();
}
return requareNewEms;
}
/**
* Check if {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} type
* transactions stack is empty
*
* @return <code>boolean</code>
*/
private boolean checkNews() {
boolean notEmpty = CollectionUtils.valid(requareNews);
return notEmpty;
}
/**
* Check if {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} type
* transactions referenced {@link EntityManager} stack is empty
*
* @return <code>boolean</code>
*/
private boolean checkNewEms() {
boolean notEmpty = CollectionUtils.valid(requareNewEms);
return notEmpty;
}
/**
* Adds new {@link EntityTransaction} for
* {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} annotated bean
* methods
*
* @param entityTransaction
*/
public void pushReqNew(EntityTransaction entityTransaction) {
getNews().push(entityTransaction);
}
/**
* Adds {@link EntityManager} to collection to close after
* {@link javax.ejb.TransactionAttributeType#REQUIRES_NEW} type transactions
* processing
*
* @param em
*/
public void pushReqNewEm(EntityManager em) {
getNewEms().push(em);
}
public void commitReqNew() throws SecurityException, IllegalStateException,
RollbackException, HeuristicMixedException,
HeuristicRollbackException, SystemException {
try {
if (checkNews()) {
EntityTransaction entityTransaction = getNews().pop();
commit(entityTransaction);
}
} finally {
closeReqNew();
}
}
/**
* Closes all cached immediate {@link EntityManager} instances
*/
private void closeReqNew() {
if (checkNewEms()) {
EntityManager em = getNewEms().pop();
JpaManager.closeEntityManager(em);
}
}
/**
* Adds {@link EntityTransaction} to transactions {@link List} for further
* processing
*
* @param transaction
*/
public void addTransaction(EntityTransaction transaction) {
transactions.add(transaction);
}
/**
* Adds {@link EntityTransaction}s to transactions {@link List} for further
* processing
*
* @param transactions
*/
public void addTransactions(EntityTransaction... transactions) {
Collections.addAll(this.transactions, transactions);
}
/**
* Adds {@link EntityManager} to collection to close after transactions
* processing
*
* @param em
*/
public void addEntityManager(EntityManager em) {
if (ObjectUtils.notNull(em)) {
if (ems == null) {
ems = new Stack<EntityManager>();
}
ems.push(em);
}
}
/**
* Adds {@link EntityManager}'s to collection to close after transactions
* processing
*
* @param em
*/
public void addEntityManagers(Collection<EntityManager> ems) {
if (CollectionUtils.valid(ems)) {
for (EntityManager em : ems) {
addEntityManager(em);
}
}
}
/**
* Closes passed {@link EntityManager} instance
*
* @param em
*/
private void closeEntityManager(EntityManager em) {
JpaManager.closeEntityManager(em);
}
/**
* Closes all cached {@link EntityManager} instances
*/
private void closeAllEntityManagers() {
EntityManager em;
while (CollectionUtils.notEmpty(ems)) {
em = ems.pop();
closeEntityManager(em);
}
}
/**
* Closes all contained {@link EntityManager}s
*/
public void closeEntityManagers() {
if (CollectionUtils.valid(ems)) {
closeAllEntityManagers();
}
}
public boolean checkCaller(BeanHandler handler) {
boolean check = ObjectUtils.notNull(caller);
if (check) {
check = caller.equals(handler.getBean());
}
return check;
}
public void setCaller(BeanHandler handler) {
caller = handler.getBean();
}
public Object getCaller() {
return caller;
}
} |
package org.lightmare.rest.providers;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.ws.rs.ext.Provider;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.spi.Container;
import org.glassfish.jersey.server.spi.ContainerLifecycleListener;
import org.lightmare.rest.RestConfig;
import org.lightmare.utils.ObjectUtils;
/**
* Reloads {@link RestConfig} (implementation of {@link ResourceConfig}) at
* runtime
*
* @author Levan Tsinadze
* @since 0.0.50-SNAPSHOT
* @see ResourceConfig
*/
@Provider
public class RestReloader implements ContainerLifecycleListener {
private static RestReloader reloader;
private static final Lock LOCK = new ReentrantLock();
public RestReloader() {
ObjectUtils.lock(LOCK);
try {
reloader = this;
} finally {
ObjectUtils.unlock(LOCK);
}
}
public static RestReloader get() {
RestReloader restReloader;
ObjectUtils.lock(LOCK);
try {
restReloader = reloader;
} finally {
ObjectUtils.unlock(LOCK);
}
return restReloader;
}
private Container container;
public void reload() {
container.reload();
}
public void reload(ResourceConfig config) {
container.reload(config);
}
@Override
public void onStartup(Container container) {
this.container = container;
}
@Override
public void onReload(Container container) {
}
@Override
public void onShutdown(Container container) {
}
} |
package org.owasp.esapi.reference;
import java.util.HashMap;
import org.apache.log4j.Level;
import javax.servlet.http.HttpSession;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.LogFactory;
import org.owasp.esapi.Logger;
import org.owasp.esapi.User;
public class Log4JLogFactory implements LogFactory {
private String applicationName;
@SuppressWarnings("unchecked")
private HashMap loggersMap = new HashMap();
/**
* Null argument constructor for this implementation of the LogFactory interface
* needed for dynamic configuration.
*/
public Log4JLogFactory() {}
/**
* Constructor for this implementation of the LogFactory interface.
*
* @param applicationName The name of this application this logger is being constructed for.
*/
public Log4JLogFactory(String applicationName) {
this.applicationName = applicationName;
}
/**
* {@inheritDoc}
*/
public void setApplicationName(String newApplicationName) {
applicationName = newApplicationName;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public Logger getLogger(Class clazz) {
// If a logger for this class already exists, we return the same one, otherwise we create a new one.
Logger classLogger = (Logger) loggersMap.get(clazz);
if (classLogger == null) {
classLogger = new Log4JLogger(applicationName, clazz.getName());
loggersMap.put(clazz, classLogger);
}
return classLogger;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public Logger getLogger(String moduleName) {
// If a logger for this module already exists, we return the same one, otherwise we create a new one.
Logger moduleLogger = (Logger) loggersMap.get(moduleName);
if (moduleLogger == null) {
moduleLogger = new Log4JLogger(applicationName, moduleName);
loggersMap.put(moduleName, moduleLogger);
}
return moduleLogger;
}
private static class Log4JLogger implements org.owasp.esapi.Logger {
/** The jlogger object used by this class to log everything. */
private org.apache.log4j.Logger jlogger = null;
/** The application name using this log. */
private String applicationName = null;
/** The module name using this log. */
private String moduleName = null;
/**
* Public constructor should only ever be called via the appropriate LogFactory
*
* @param applicationName the application name
* @param moduleName the module name
*/
private Log4JLogger(String applicationName, String moduleName) {
this.applicationName = applicationName;
this.moduleName = moduleName;
this.jlogger = org.apache.log4j.Logger.getLogger(applicationName + ":" + moduleName);
}
/**
* {@inheritDoc}
* Note: In this implementation, this change is not persistent,
* meaning that if the application is restarted, the log level will revert to the level defined in the
* ESAPI SecurityConfiguration properties file.
*/
public void setLevel(int level)
{
try {
jlogger.setLevel(convertESAPILeveltoLoggerLevel( level ));
}
catch (IllegalArgumentException e) {
this.error(Logger.SECURITY_FAILURE, "", e);
}
}
private static Level convertESAPILeveltoLoggerLevel(int level)
{
switch (level) {
case Logger.OFF: return Level.OFF;
case Logger.FATAL: return Level.FATAL;
case Logger.ERROR: return Level.ERROR;
case Logger.WARNING: return Level.WARN;
case Logger.INFO: return Level.INFO;
case Logger.DEBUG: return Level.DEBUG; //fine
case Logger.TRACE: return Level.TRACE; //finest
case Logger.ALL: return Level.ALL;
default: {
throw new IllegalArgumentException("Invalid logging level. Value was: " + level);
}
}
}
/**
* {@inheritDoc}
*/
public void trace(EventType type, String message, Throwable throwable) {
log(Level.TRACE, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void trace(EventType type, String message) {
log(Level.TRACE, type, message, null);
}
/**
* {@inheritDoc}
*/
public void debug(EventType type, String message, Throwable throwable) {
log(Level.DEBUG, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void debug(EventType type, String message) {
log(Level.DEBUG, type, message, null);
}
/**
* {@inheritDoc}
*/
public void info(EventType type, String message) {
log(Level.INFO, type, message, null);
}
/**
* {@inheritDoc}
*/
public void info(EventType type, String message, Throwable throwable) {
log(Level.INFO, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void warning(EventType type, String message, Throwable throwable) {
log(Level.WARN, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void warning(EventType type, String message) {
log(Level.WARN, type, message, null);
}
/**
* {@inheritDoc}
*/
public void error(EventType type, String message, Throwable throwable) {
log(Level.ERROR, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void error(EventType type, String message) {
log(Level.ERROR, type, message, null);
}
/**
* {@inheritDoc}
*/
public void fatal(EventType type, String message, Throwable throwable) {
log(Level.FATAL, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void fatal(EventType type, String message) {
log(Level.FATAL, type, message, null);
}
/**
* Log the message after optionally encoding any special characters that might be dangerous when viewed
* by an HTML based log viewer. Also encode any carriage returns and line feeds to prevent log
* injection attacks. This logs all the supplied parameters plus the user ID, user's source IP, a logging
* specific session ID, and the current date/time.
*
* It will only log the message if the current logging level is enabled, otherwise it will
* discard the message.
*
* @param level the severity level of the security event
* @param type the type of the event (SECURITY, FUNCTIONALITY, etc.)
* @param success whether this was a failed or successful event
* @param message the message
* @param throwable the throwable
*/
private void log(Level level, EventType type, String message, Throwable throwable) {
// Before we waste time preparing this event for the log, we check to see if it needs to be logged
if (!jlogger.isEnabledFor( level )) return;
User user = ESAPI.authenticator().getCurrentUser();
// create a random session number for the user to represent the user's 'session', if it doesn't exist already
String userSessionIDforLogging = "unknown";
try {
HttpSession session = ESAPI.httpUtilities().getCurrentRequest().getSession( false );
userSessionIDforLogging = (String)session.getAttribute("ESAPI_SESSION");
// if there is no session ID for the user yet, we create one and store it in the user's session
if ( userSessionIDforLogging == null ) {
userSessionIDforLogging = ""+ ESAPI.randomizer().getRandomInteger(0, 1000000);
session.setAttribute("ESAPI_SESSION", userSessionIDforLogging);
}
} catch( NullPointerException e ) {
// continue
}
// ensure there's something to log
if ( message == null ) {
message = "";
}
// ensure no CRLF injection into logs for forging records
String clean = message.replace( '\n', '_' ).replace( '\r', '_' );
if ( ((DefaultSecurityConfiguration)ESAPI.securityConfiguration()).getLogEncodingRequired() ) {
clean = ESAPI.encoder().encodeForHTML(message);
if (!message.equals(clean)) {
clean += " (Encoded)";
}
}
// create the message to log
String msg = "";
if ( user != null && type != null) {
msg = type + " " + user.getAccountName() + "@"+ user.getLastHostAddress() +":" + userSessionIDforLogging + " " + clean;
}
if(throwable == null) {
jlogger.log(level, applicationName + " " + moduleName + " " + msg);
} else {
jlogger.log(level, applicationName + " " + moduleName + " " + msg, throwable);
}
}
/**
* {@inheritDoc}
*/
public boolean isDebugEnabled() {
return jlogger.isEnabledFor(Level.DEBUG);
}
/**
* {@inheritDoc}
*/
public boolean isErrorEnabled() {
return jlogger.isEnabledFor(Level.ERROR);
}
/**
* {@inheritDoc}
*/
public boolean isFatalEnabled() {
return jlogger.isEnabledFor(Level.FATAL);
}
/**
* {@inheritDoc}
*/
public boolean isInfoEnabled() {
return jlogger.isEnabledFor(Level.INFO);
}
/**
* {@inheritDoc}
*/
public boolean isTraceEnabled() {
return jlogger.isEnabledFor(Level.TRACE);
}
/**
* {@inheritDoc}
*/
public boolean isWarningEnabled() {
return jlogger.isEnabledFor(Level.WARN);
}
}
} |
package org.testng.reporters;
import org.testng.IResultMap;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.annotations.Test;
import org.testng.collections.Lists;
import org.testng.collections.Maps;
import org.testng.collections.Sets;
import org.testng.internal.ConstructorOrMethod;
import org.testng.internal.Utils;
import org.testng.util.Strings;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* Utility writing an ISuiteResult to an XMLStringBuffer. Depending on the settings in the <code>config</code> property
* it might generate an additional XML file with the actual content and only reference the file with an <code>url</code>
* attribute in the passed XMLStringBuffer.
*
* @author Cosmin Marginean, Mar 16, 2007
*/
public class XMLSuiteResultWriter {
private XMLReporterConfig config;
public XMLSuiteResultWriter(XMLReporterConfig config) {
this.config = config;
}
/**
* Writes the specified ISuiteResult in the given XMLStringBuffer. Please consider that depending on the settings in
* the <code>config</code> property it might generate an additional XML file with the actual content and only
* reference the file with an <code>url</code> attribute in the passed XMLStringBuffer.
*
* @param xmlBuffer The XML buffer where to write or reference the suite result
* @param suiteResult The <code>ISuiteResult</code> to serialize
*/
public void writeSuiteResult(XMLStringBuffer xmlBuffer, ISuiteResult suiteResult) {
if (XMLReporterConfig.FF_LEVEL_SUITE_RESULT != config.getFileFragmentationLevel()) {
writeAllToBuffer(xmlBuffer, suiteResult);
} else {
String parentDir =
config.getOutputDirectory() + File.separatorChar + suiteResult.getTestContext().getSuite().getName();
File file = referenceSuiteResult(xmlBuffer, parentDir, suiteResult);
XMLStringBuffer suiteXmlBuffer = new XMLStringBuffer();
writeAllToBuffer(suiteXmlBuffer, suiteResult);
Utils.writeUtf8File(file.getAbsoluteFile().getParent(), file.getName(), suiteXmlBuffer.toXML());
}
}
private void writeAllToBuffer(XMLStringBuffer xmlBuffer, ISuiteResult suiteResult) {
xmlBuffer.push(XMLReporterConfig.TAG_TEST, getSuiteResultAttributes(suiteResult));
Set<ITestResult> testResults = Sets.newHashSet();
ITestContext testContext = suiteResult.getTestContext();
addAllTestResults(testResults, testContext.getPassedTests());
addAllTestResults(testResults, testContext.getFailedTests());
addAllTestResults(testResults, testContext.getSkippedTests());
addAllTestResults(testResults, testContext.getPassedConfigurations());
addAllTestResults(testResults, testContext.getSkippedConfigurations());
addAllTestResults(testResults, testContext.getFailedConfigurations());
addAllTestResults(testResults, testContext.getFailedButWithinSuccessPercentageTests());
addTestResults(xmlBuffer, testResults);
xmlBuffer.pop();
}
@SuppressWarnings("unchecked")
private void addAllTestResults(Set<ITestResult> testResults, IResultMap resultMap) {
if (resultMap != null) {
// Sort the results chronologically before adding them
List<ITestResult> allResults = new ArrayList<ITestResult>();
allResults.addAll(resultMap.getAllResults());
Collections.sort(new ArrayList(allResults), new Comparator<ITestResult>() {
@Override
public int compare(ITestResult o1, ITestResult o2) {
return (int) (o1.getStartMillis() - o2.getStartMillis());
}
});
testResults.addAll(allResults);
}
}
private File referenceSuiteResult(XMLStringBuffer xmlBuffer, String parentDir, ISuiteResult suiteResult) {
Properties attrs = new Properties();
String suiteResultName = suiteResult.getTestContext().getName() + ".xml";
attrs.setProperty(XMLReporterConfig.ATTR_URL, suiteResultName);
xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_TEST, attrs);
return new File(parentDir + File.separatorChar + suiteResultName);
}
private Properties getSuiteResultAttributes(ISuiteResult suiteResult) {
Properties attributes = new Properties();
ITestContext tc = suiteResult.getTestContext();
attributes.setProperty(XMLReporterConfig.ATTR_NAME, tc.getName());
XMLReporter.addDurationAttributes(config, attributes, tc.getStartDate(), tc.getEndDate());
return attributes;
}
private void addTestResults(XMLStringBuffer xmlBuffer, Set<ITestResult> testResults) {
Map<String, List<ITestResult>> testsGroupedByClass = buildTestClassGroups(testResults);
for (Map.Entry<String, List<ITestResult>> result : testsGroupedByClass.entrySet()) {
Properties attributes = new Properties();
String className = result.getKey();
if (config.isSplitClassAndPackageNames()) {
int dot = className.lastIndexOf('.');
attributes.setProperty(XMLReporterConfig.ATTR_NAME,
dot > -1 ? className.substring(dot + 1, className.length()) : className);
attributes.setProperty(XMLReporterConfig.ATTR_PACKAGE, dot > -1 ? className.substring(0, dot) : "[default]");
} else {
attributes.setProperty(XMLReporterConfig.ATTR_NAME, className);
}
xmlBuffer.push(XMLReporterConfig.TAG_CLASS, attributes);
List<ITestResult> sortedResults = result.getValue();
Collections.sort( sortedResults );
for (ITestResult testResult : sortedResults) {
addTestResult(xmlBuffer, testResult);
}
xmlBuffer.pop();
}
}
private Map<String, List<ITestResult>> buildTestClassGroups(Set<ITestResult> testResults) {
Map<String, List<ITestResult>> map = Maps.newHashMap();
for (ITestResult result : testResults) {
String className = result.getTestClass().getName();
List<ITestResult> list = map.get(className);
if (list == null) {
list = Lists.newArrayList();
map.put(className, list);
}
list.add(result);
}
return map;
}
private void addTestResult(XMLStringBuffer xmlBuffer, ITestResult testResult) {
Properties attribs = getTestResultAttributes(testResult);
attribs.setProperty(XMLReporterConfig.ATTR_STATUS, getStatusString(testResult.getStatus()));
xmlBuffer.push(XMLReporterConfig.TAG_TEST_METHOD, attribs);
addTestMethodParams(xmlBuffer, testResult);
addTestResultException(xmlBuffer, testResult);
if (config.isGenerateTestResultAttributes()) {
addTestResultAttributes(xmlBuffer, testResult);
}
xmlBuffer.pop();
}
private String getStatusString(int testResultStatus) {
switch (testResultStatus) {
case ITestResult.SUCCESS:
return "PASS";
case ITestResult.FAILURE:
return "FAIL";
case ITestResult.SKIP:
return "SKIP";
case ITestResult.SUCCESS_PERCENTAGE_FAILURE:
return "SUCCESS_PERCENTAGE_FAILURE";
}
return null;
}
private Properties getTestResultAttributes(ITestResult testResult) {
Properties attributes = new Properties();
if (!testResult.getMethod().isTest()) {
attributes.setProperty(XMLReporterConfig.ATTR_IS_CONFIG, "true");
}
attributes.setProperty(XMLReporterConfig.ATTR_NAME, testResult.getMethod().getMethodName());
String testInstanceName = testResult.getTestName();
if (null != testInstanceName) {
attributes.setProperty(XMLReporterConfig.ATTR_TEST_INSTANCE_NAME, testInstanceName);
}
String description = testResult.getMethod().getDescription();
if (!Utils.isStringEmpty(description)) {
attributes.setProperty(XMLReporterConfig.ATTR_DESC, description);
}
attributes.setProperty(XMLReporterConfig.ATTR_METHOD_SIG, removeClassName(testResult.getMethod().toString()));
SimpleDateFormat format = new SimpleDateFormat(config.getTimestampFormat());
String startTime = format.format(testResult.getStartMillis());
String endTime = format.format(testResult.getEndMillis());
attributes.setProperty(XMLReporterConfig.ATTR_STARTED_AT, startTime);
attributes.setProperty(XMLReporterConfig.ATTR_FINISHED_AT, endTime);
long duration = testResult.getEndMillis() - testResult.getStartMillis();
String strDuration = Long.toString(duration);
attributes.setProperty(XMLReporterConfig.ATTR_DURATION_MS, strDuration);
if (config.isGenerateGroupsAttribute()) {
String groupNamesStr = Utils.arrayToString(testResult.getMethod().getGroups());
if (!Utils.isStringEmpty(groupNamesStr)) {
attributes.setProperty(XMLReporterConfig.ATTR_GROUPS, groupNamesStr);
}
}
if (config.isGenerateDependsOnMethods()) {
String dependsOnStr = Utils.arrayToString(testResult.getMethod().getMethodsDependedUpon());
if (!Utils.isStringEmpty(dependsOnStr)) {
attributes.setProperty(XMLReporterConfig.ATTR_DEPENDS_ON_METHODS, dependsOnStr);
}
}
if (config.isGenerateDependsOnGroups()) {
String dependsOnStr = Utils.arrayToString(testResult.getMethod().getGroupsDependedUpon());
if (!Utils.isStringEmpty(dependsOnStr)) {
attributes.setProperty(XMLReporterConfig.ATTR_DEPENDS_ON_GROUPS, dependsOnStr);
}
}
ConstructorOrMethod cm = testResult.getMethod().getConstructorOrMethod();
Test testAnnotation;
if (cm.getMethod() != null) {
testAnnotation = cm.getMethod().getAnnotation(Test.class);
if (testAnnotation != null) {
String dataProvider = testAnnotation.dataProvider();
if (!Strings.isNullOrEmpty(dataProvider)) {
attributes.setProperty(XMLReporterConfig.ATTR_DATA_PROVIDER, dataProvider);
}
}
}
return attributes;
}
private String removeClassName(String methodSignature) {
int firstParanthesisPos = methodSignature.indexOf("(");
int dotAferClassPos = methodSignature.substring(0, firstParanthesisPos).lastIndexOf(".");
return methodSignature.substring(dotAferClassPos + 1, methodSignature.length());
}
public void addTestMethodParams(XMLStringBuffer xmlBuffer, ITestResult testResult) {
Object[] parameters = testResult.getParameters();
if ((parameters != null) && (parameters.length > 0)) {
xmlBuffer.push(XMLReporterConfig.TAG_PARAMS);
for (int i = 0; i < parameters.length; i++) {
addParameter(xmlBuffer, parameters[i], i);
}
xmlBuffer.pop();
}
}
private void addParameter(XMLStringBuffer xmlBuffer, Object parameter, int i) {
Properties attrs = new Properties();
attrs.setProperty(XMLReporterConfig.ATTR_INDEX, String.valueOf(i));
xmlBuffer.push(XMLReporterConfig.TAG_PARAM, attrs);
if (parameter == null) {
Properties valueAttrs = new Properties();
valueAttrs.setProperty(XMLReporterConfig.ATTR_IS_NULL, "true");
xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_PARAM_VALUE, valueAttrs);
} else {
xmlBuffer.push(XMLReporterConfig.TAG_PARAM_VALUE);
xmlBuffer.addCDATA(parameter.toString());
xmlBuffer.pop();
}
xmlBuffer.pop();
}
private void addTestResultException(XMLStringBuffer xmlBuffer, ITestResult testResult) {
Throwable exception = testResult.getThrowable();
if (exception != null) {
Properties exceptionAttrs = new Properties();
exceptionAttrs.setProperty(XMLReporterConfig.ATTR_CLASS, exception.getClass().getName());
xmlBuffer.push(XMLReporterConfig.TAG_EXCEPTION, exceptionAttrs);
if (!Utils.isStringEmpty(exception.getMessage())) {
xmlBuffer.push(XMLReporterConfig.TAG_MESSAGE);
xmlBuffer.addCDATA(exception.getMessage());
xmlBuffer.pop();
}
String[] stackTraces = Utils.stackTrace(exception, false);
if ((config.getStackTraceOutputMethod() & XMLReporterConfig.STACKTRACE_SHORT) == XMLReporterConfig
.STACKTRACE_SHORT) {
xmlBuffer.push(XMLReporterConfig.TAG_SHORT_STACKTRACE);
xmlBuffer.addCDATA(stackTraces[0]);
xmlBuffer.pop();
}
if ((config.getStackTraceOutputMethod() & XMLReporterConfig.STACKTRACE_FULL) == XMLReporterConfig
.STACKTRACE_FULL) {
xmlBuffer.push(XMLReporterConfig.TAG_FULL_STACKTRACE);
xmlBuffer.addCDATA(stackTraces[1]);
xmlBuffer.pop();
}
xmlBuffer.pop();
}
}
private void addTestResultAttributes(XMLStringBuffer xmlBuffer, ITestResult testResult) {
if (testResult.getAttributeNames() != null && testResult.getAttributeNames().size() > 0) {
xmlBuffer.push(XMLReporterConfig.TAG_ATTRIBUTES);
for (String attrName: testResult.getAttributeNames()) {
if (attrName == null) {
continue;
}
Object attrValue = testResult.getAttribute(attrName);
Properties attributeAttrs = new Properties();
attributeAttrs.setProperty(XMLReporterConfig.ATTR_NAME, attrName);
if (attrValue == null) {
attributeAttrs.setProperty(XMLReporterConfig.ATTR_IS_NULL, "true");
xmlBuffer.addEmptyElement(XMLReporterConfig.TAG_ATTRIBUTE, attributeAttrs);
} else {
xmlBuffer.push(XMLReporterConfig.TAG_ATTRIBUTE, attributeAttrs);
xmlBuffer.addCDATA(attrValue.toString());
xmlBuffer.pop();
}
}
xmlBuffer.pop();
}
}
} |
package org.xmlcml.cmine.args;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import nu.xom.Builder;
import nu.xom.Element;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.xmlcml.cmine.args.log.AbstractLogElement;
import org.xmlcml.cmine.args.log.CMineLog;
import org.xmlcml.cmine.files.CMDir;
import org.xmlcml.cmine.files.CMDirList;
import org.xmlcml.cmine.files.DefaultSearcher;
import org.xmlcml.html.HtmlElement;
import org.xmlcml.html.HtmlFactory;
import org.xmlcml.html.HtmlP;
import org.xmlcml.xml.XMLUtil;
/** base class for all arg processing. Also contains the workflow logic:
*
* the list of CMDirs is created in
*
* parseArgs(String[]) or
* parseArgs(String)
*
* calls
* protected void addArgumentOptionsAndRunParseMethods(ArgIterator argIterator, String arg) throws Exception {
* which iterates through the args, loking for init* and parse* methods
for (ArgumentOption option : argumentOptionList) {
if (option.matches(arg)) {
LOG.trace("OPTION>> "+option);
String initMethodName = option.getInitMethodName();
if (initMethodName != null) {
runInitMethod(option, initMethodName);
}
String parseMethodName = option.getParseMethodName();
if (parseMethodName != null) {
runParseMethod(argIterator, option, parseMethodName);
}
processed = true;
chosenArgumentOptionList.add(option);
break;
}
}
}
}
this will generate CMDirList
after that
*
*
* runAndOutput() iterates through each CMDir
*
for (int i = 0; i < cmDirList.size(); i++) {
currentCMDir = cmDirList.get(i);
// generateLogFile here
currentCMDir.getOrCreateLog();
// each CMDir has a ContentProcessor
currentCMDir.ensureContentProcessor(this);
// possible initFooOption
runInitMethodsOnChosenArgOptions();
// possible runFooOption
runRunMethodsOnChosenArgOptions();
// possible outputFooOptions
runOutputMethodsOnChosenArgOptions();
}
// a "reduce" or "gather" method to run overe many CMDirs (e.g summaries)
runFinalMethodsOnChosenArgOptions();
}
*
* @author pm286
*
*/
public class DefaultArgProcessor {
private static final Logger LOG = Logger.getLogger(DefaultArgProcessor.class);
static {
LOG.setLevel(Level.DEBUG);
}
private static final String ARGS2HTML_XSL = "/org/xmlcml/cmine/args/args2html.xsl";
private static final File MAIN_RESOURCES = new File("src/main/resources");
public static final String MINUS = "-";
public static final String[] DEFAULT_EXTENSIONS = {"html", "xml", "pdf"};
public final static String H = "-h";
public final static String HELP = "--help";
private static Pattern INTEGER_RANGE = Pattern.compile("(.*)\\{(\\d+),(\\d+)\\}(.*)");
private static String RESOURCE_NAME_TOP = "/org/xmlcml/cmine/args";
protected static final String ARGS_XML = "args.xml";
private static String ARGS_RESOURCE = RESOURCE_NAME_TOP+"/"+ARGS_XML;
private static final String NAME = "name";
private static final String VERSION = "version";
private static final Pattern INTEGER_RANGE_PATTERN = Pattern.compile("(\\d+):(\\d+)");
public static final String WHITESPACE = "\\s+";
public static Pattern GENERAL_PATTERN = Pattern.compile("\\{([^\\}]*)\\}");
public static final VersionManager DEFAULT_VERSION_MANAGER = new VersionManager();
public static final String LOGFILE = "target/log.xml";
/** creates a list of tokens that are found in an allowed list.
*
* @param allowed
* @param tokens
* @return list of allowed tokens
*/
protected static List<String> getChosenList(List<String> allowed, List<String> tokens) {
List<String> chosenTokens = new ArrayList<String>();
for (String method : tokens) {
if (allowed.contains(method)) {
chosenTokens.add(method);
} else {
LOG.error("Unknown token: "+method);
}
}
return chosenTokens;
}
// arg values
protected String output;
protected List<String> extensionList = null;
private boolean recursive = false;
protected List<String> inputList;
protected String logfileName;
public String update;
public List<ArgumentOption> argumentOptionList;
public List<ArgumentOption> chosenArgumentOptionList;
protected CMDirList cmDirList;
// change protection later
protected CMDir currentCMDir;
protected String summaryFileName;
// variable processing
protected Map<String, String> variableByNameMap;
private VariableProcessor variableProcessor;
// searching
protected List<DefaultSearcher> searcherList; // req
protected HashMap<String, DefaultSearcher> searcherByNameMap; // req
protected String project;
protected AbstractLogElement cTreeLog;
protected AbstractLogElement initLog;
protected List<ArgumentOption> getArgumentOptionList() {
return argumentOptionList;
}
public DefaultArgProcessor() {
ensureDefaultLogFiles();
readArgumentOptions(getArgsResource());
}
private void ensureDefaultLogFiles() {
createCTreeLog(new File("target/defaultCTreeLog.xml"));
createInitLog(new File("target/defaultInitLog.xml"));
}
public void createCTreeLog(File logFile) {
cTreeLog = new CMineLog(logFile);
}
public void createInitLog(File logFile) {
initLog = new CMineLog(logFile);
}
protected static VersionManager getVersionManager() {
// LOG.debug("VM Default "+DEFAULT_VERSION_MANAGER.hashCode()+" "+DEFAULT_VERSION_MANAGER.getName()+";"+DEFAULT_VERSION_MANAGER.getVersion());
return DEFAULT_VERSION_MANAGER;
}
private String getArgsResource() {
return ARGS_RESOURCE;
}
public void readArgumentOptions(String resourceName) {
ensureArgumentOptionList();
try {
InputStream is = this.getClass().getResourceAsStream(resourceName);
if (is == null) {
throw new RuntimeException("Cannot read/find input resource stream: "+resourceName);
}
Element argListElement = new Builder().build(is).getRootElement();
initLog = this.getOrCreateLog(logfileName);
getVersionManager().readNameVersion(argListElement);
createArgumentOptions(argListElement);
} catch (Exception e) {
throw new RuntimeException("Cannot read/process args file "+resourceName, e);
}
}
private void createArgumentOptions(Element argElement) {
List<Element> elementList = XMLUtil.getQueryElements(argElement, "/*/*[local-name()='arg']");
for (Element element : elementList) {
ArgumentOption argOption = ArgumentOption.createOption(this.getClass(), element);
LOG.trace("created ArgumentOption: "+argOption);
argumentOptionList.add(argOption);
}
}
private void ensureArgumentOptionList() {
if (this.argumentOptionList == null) {
this.argumentOptionList = new ArrayList<ArgumentOption>();
}
}
public void expandWildcardsExhaustively() {
while (expandWildcardsOnce());
}
public boolean expandWildcardsOnce() {
boolean change = false;
ensureInputList();
List<String> newInputList = new ArrayList<String>();
for (String input : inputList) {
List<String> expanded = expandWildcardsOnce(input);
newInputList.addAll(expanded);
change |= (expanded.size() > 1 || !expanded.get(0).equals(input));
}
inputList = newInputList;
return change;
}
/** expand expressions/wildcards in input.
*
* @param input
* @return
*/
private List<String> expandWildcardsOnce(String input) {
Matcher matcher = GENERAL_PATTERN.matcher(input);
List<String> inputs = new ArrayList<String>();
if (matcher.find()) {
String content = matcher.group(1);
String pre = input.substring(0, matcher.start());
String post = input.substring(matcher.end());
inputs = expandIntegerMatch(content, pre, post);
if (inputs.size() == 0) {
inputs = expandStrings(content, pre, post);
}
if (inputs.size() == 0) {
LOG.error("Cannot expand "+content);
}
} else {
inputs.add(input);
}
return inputs;
}
private List<String> expandIntegerMatch(String content, String pre, String post) {
List<String> stringList = new ArrayList<String>();
Matcher matcher = INTEGER_RANGE_PATTERN.matcher(content);
if (matcher.find()) {
int start = Integer.parseInt(matcher.group(1));
int end = Integer.parseInt(matcher.group(2));
for (int i = start; i <= end; i++) {
String s = pre + i + post;
stringList.add(s);
}
}
return stringList;
}
private List<String> expandStrings(String content, String pre, String post) {
List<String> newStringList = new ArrayList<String>();
List<String> vars = Arrays.asList(content.split("\\|"));
for (String var : vars) {
newStringList.add(pre + var + post);
}
return newStringList;
}
public AbstractLogElement getOrCreateLog(String logfileName) {
AbstractLogElement cMineLog = null;
if (logfileName == null) {
logfileName = DefaultArgProcessor.LOGFILE;
}
File file = new File(logfileName);
cMineLog = new CMineLog(file);
return cMineLog;
}
public void parseVersion(ArgumentOption option, ArgIterator argIterator) {
argIterator.createTokenListUpToNextNonDigitMinus(option);
printVersion();
}
public void parseExtensions(ArgumentOption option, ArgIterator argIterator) {
List<String> extensions = argIterator.createTokenListUpToNextNonDigitMinus(option);
setExtensions(extensions);
}
public void parseQSNorma(ArgumentOption option, ArgIterator argIterator) {
parseCMDir(option, argIterator);
}
public void parseCMDir(ArgumentOption option, ArgIterator argIterator) {
List<String> cmDirNames = argIterator.createTokenListUpToNextNonDigitMinus(option);
if (cmDirNames.size() == 0) {
if (inputList == null || inputList.size() == 0) {
LOG.error("Must give inputList before --cmdir");
} else if (output == null) {
LOG.error("Must give output before --cmdir");
} else {
finalizeInputList();
// generateFilenamesFromInputDirectory();
createCMDirListFromInput();
}
} else {
createCMDirList(cmDirNames);
}
}
public void parseInput(ArgumentOption option, ArgIterator argIterator) {
List<String> inputs = argIterator.createTokenListUpToNextNonDigitMinus(option);
inputList = expandAllWildcards(inputs);
}
public void parseLogfile(ArgumentOption option, ArgIterator argIterator) {
List<String> strings = argIterator.getStrings(option);
logfileName = (strings.size() == 0) ? CMDir.LOGFILE : strings.get(0);
}
public void parseOutput(ArgumentOption option, ArgIterator argIterator) {
output = argIterator.getString(option);
}
public void parseProject(ArgumentOption option, ArgIterator argIterator) {
project = argIterator.getString(option);
}
public void parseRecursive(ArgumentOption option, ArgIterator argIterator) {
recursive = argIterator.getBoolean(option);
}
public void parseSummaryFile(ArgumentOption option, ArgIterator argIterator) {
summaryFileName = argIterator.getString(option);
}
public void runMakeDocs(ArgumentOption option) {
transformArgs2html();
}
public void runTest(ArgumentOption option) {
String name = new Object(){}.getClass().getEnclosingMethod().getName();
cTreeLog.info("testing");
}
public void outputMethod(ArgumentOption option) {
LOG.error("outputMethod needs overwriting");
}
public void printHelp(ArgumentOption option, ArgIterator argIterator) {
printHelp();
}
private void createCMDirListFromInput() {
File outputDir = output == null ? null : new File(output);
for (String filename : inputList) {
File infile = new File(filename);
if (!infile.isDirectory()) {
File cmdirParent = output == null ? infile.getParentFile() : outputDir;
String cmName = filename.replaceAll("\\p{Punct}", "_")+"/";
File directory = new File(cmdirParent, cmName);
CMDir cmDir = new CMDir(directory, true);
String reservedFilename = CMDir.getCMDirReservedFilenameForExtension(filename);
try {
cmDir.writeReservedFile(infile, reservedFilename, true);
} catch (Exception e) {
throw new RuntimeException("Cannot create/write: "+filename, e);
}
}
}
}
protected void printVersion() {
DefaultArgProcessor.getVersionManager().printVersion();
}
private void createCMDirList(List<String> qDirectoryNames) {
FileFilter directoryFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
cmDirList = new CMDirList();
LOG.trace("creating CMDIRList from: "+qDirectoryNames);
for (String qDirectoryName : qDirectoryNames) {
File qDirectory = new File(qDirectoryName);
if (!qDirectory.exists()) {
LOG.error("File does not exist: "+qDirectory.getAbsolutePath());
continue;
}
if (!qDirectory.isDirectory()) {
LOG.error("Not a directory: "+qDirectory.getAbsolutePath());
continue;
}
CMDir cmDir = new CMDir(qDirectoryName);
LOG.trace("...creating CMDIR from: "+qDirectoryName);
if (cmDir.containsNoReservedFilenames() && cmDir.containsNoReservedDirectories()) {
LOG.debug("... No reserved files or directories: "+cmDir);
List<File> childFiles = new ArrayList<File>(Arrays.asList(qDirectory.listFiles(directoryFilter)));
List<String> childFilenames = new ArrayList<String>();
for (File childFile : childFiles) {
if (childFile.isDirectory()) {
childFilenames.add(childFile.toString());
}
}
LOG.trace(childFilenames);
// recurse (no mixed directory structures)
// FIXME
LOG.trace("Recursing CMDIRs is probably a BUG");
createCMDirList(childFilenames);
} else {
cmDirList.add(cmDir);
}
}
LOG.trace("CMDIRList: "+cmDirList.size());
for (CMDir cmdir : cmDirList) {
LOG.trace("CMDir: "+cmdir);
}
}
private List<String> expandAllWildcards(List<String> inputs) {
inputList = new ArrayList<String>();
for (String input : inputs) {
inputList.addAll(expandWildcards(input));
}
return inputList;
}
/** expand expressions/wildcards in input.
*
* @param input
* @return
*/
private List<String> expandWildcards(String input) {
Matcher matcher = INTEGER_RANGE.matcher(input);
List<String> inputs = new ArrayList<String>();
if (matcher.matches()) {
int start = Integer.parseInt(matcher.group(2));
int end = Integer.parseInt(matcher.group(3));
if (start <= end) {
for (int i = start; i <= end; i++) {
String input0 = matcher.group(1)+i+matcher.group(4);
inputs.add(input0);
}
}
} else {
inputs.add(input);
}
LOG.trace("inputs: "+inputs);
return inputs;
}
private void transformArgs2html() {
InputStream transformStream = getArgsXml2HtmlXsl();
if (transformStream == null) {
throw new RuntimeException("Cannot find argsXml2Html file");
}
List<File> argsList = getArgs2HtmlList();
for (File argsXmlFile : argsList) {
File argsHtmlFile = getHtmlFromXML(argsXmlFile);
try {
String xmlString = transformArgsXml2Html(new FileInputStream(argsXmlFile), transformStream);
FileUtils.writeStringToFile(argsHtmlFile, xmlString);
} catch (Exception e) {
throw new RuntimeException("Cannot transform "+argsXmlFile, e);
}
}
}
private String transformArgsXml2Html(InputStream argsXmlIs, InputStream argsXml2HtmlXslIs) throws Exception {
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer javaxTransformer = tfactory.newTransformer(new StreamSource(argsXml2HtmlXslIs));
OutputStream baos = new ByteArrayOutputStream();
javaxTransformer.transform(new StreamSource(argsXmlIs), new StreamResult(baos));
return baos.toString();
}
private InputStream getArgsXml2HtmlXsl() {
return this.getClass().getResourceAsStream(ARGS2HTML_XSL);
}
private File getHtmlFromXML(File argsXml) {
String xmlPath = argsXml.getPath();
String htmlPath = xmlPath.replaceAll("\\.xml", ".html");
return new File(htmlPath);
}
private List<File> getArgs2HtmlList() {
List<File> argsList = new ArrayList<File>(FileUtils.listFiles(MAIN_RESOURCES, new String[]{"xml"}, true));
for (int i = argsList.size() - 1; i >= 0; i
File file = argsList.get(i);
if (!(ARGS_XML.equals(file.getName()))) {
argsList.remove(i);
}
}
return argsList;
}
public void setExtensions(List<String> extensions) {
this.extensionList = extensions;
}
public List<String> getInputList() {
ensureInputList();
return inputList;
}
public String getString() {
ensureInputList();
return (inputList.size() != 1) ? null : inputList.get(0);
}
private void ensureInputList() {
if (inputList == null) {
inputList = new ArrayList<String>();
}
}
public String getOutput() {
return output;
}
public boolean isRecursive() {
return recursive;
}
public String getSummaryFileName() {
return summaryFileName;
}
public CMDirList getCMDirList() {
ensureCMDirList();
return cmDirList;
}
protected void ensureCMDirList() {
if (cmDirList == null) {
cmDirList = new CMDirList();
}
}
public void parseArgs(String[] commandLineArgs) {
if (commandLineArgs == null || commandLineArgs.length == 0) {
printHelp();
} else {
String[] totalArgs = addDefaultsAndParsedArgs(commandLineArgs);
ArgIterator argIterator = new ArgIterator(totalArgs);
LOG.trace("args with defaults is: "+new ArrayList<String>(Arrays.asList(totalArgs)));
while (argIterator.hasNext()) {
String arg = argIterator.next();
LOG.trace("arg> "+arg);
try {
addArgumentOptionsAndRunParseMethods(argIterator, arg);
} catch (Exception e) {
throw new RuntimeException("cannot process argument: "+arg+" ("+ExceptionUtils.getRootCauseMessage(e)+")", e);
}
}
finalizeArgs();
}
}
public void parseArgs(String args) {
parseArgs(args.trim().split("\\s+"));
}
private void finalizeArgs() {
processArgumentDependencies();
finalizeInputList();
}
private void processArgumentDependencies() {
for (ArgumentOption argumentOption : chosenArgumentOptionList) {
argumentOption.processDependencies(chosenArgumentOptionList);
}
}
private void finalizeInputList() {
List<String> inputList0 = new ArrayList<String>();
ensureInputList();
for (String input : inputList) {
File file = new File(input);
if (file.isDirectory()) {
LOG.trace("DIR: "+file.getAbsolutePath()+"; "+file.isDirectory());
addDirectoryFiles(inputList0, file);
} else {
inputList0.add(input);
}
}
inputList = inputList0;
}
private void addDirectoryFiles(List<String> inputList0, File file) {
String[] extensions = getExtensions().toArray(new String[0]);
List<File> files = new ArrayList<File>(
FileUtils.listFiles(file, extensions, recursive));
for (File file0 : files) {
inputList0.add(file0.toString());
}
}
private String[] addDefaultsAndParsedArgs(String[] commandLineArgs) {
String[] defaultArgs = createDefaultArgumentStrings();
List<String> totalArgList = new ArrayList<String>(Arrays.asList(createDefaultArgumentStrings()));
List<String> commandArgList = Arrays.asList(commandLineArgs);
totalArgList.addAll(commandArgList);
String[] totalArgs = totalArgList.toArray(new String[0]);
return totalArgs;
}
private String[] createDefaultArgumentStrings() {
StringBuilder sb = new StringBuilder();
for (ArgumentOption option : argumentOptionList) {
String defalt = String.valueOf(option.getDefault());
LOG.trace("default: "+defalt);
if (defalt != null && defalt.toString().trim().length() > 0) {
String command = getBriefOrVerboseCommand(option);
sb.append(command+" "+option.getDefault()+" ");
}
}
String s = sb.toString().trim();
return s.length() == 0 ? new String[0] : s.split("\\s+");
}
private String getBriefOrVerboseCommand(ArgumentOption option) {
String command = option.getBrief();
if (command == null || command.trim().length() == 0) {
command = option.getVerbose();
}
return command;
}
public List<String> getExtensions() {
ensureExtensionList();
return extensionList;
}
private void ensureExtensionList() {
if (extensionList == null) {
extensionList = new ArrayList<String>();
}
}
public void runInitMethodsOnChosenArgOptions() {
runMethodsOfType(ArgumentOption.INIT_METHOD);
}
public void runRunMethodsOnChosenArgOptions() {
runMethodsOfType(ArgumentOption.RUN_METHOD);
}
public void runOutputMethodsOnChosenArgOptions() {
runMethodsOfType(ArgumentOption.OUTPUT_METHOD);
}
public void runFinalMethodsOnChosenArgOptions() {
runMethodsOfType(ArgumentOption.FINAL_METHOD);
}
protected void runMethodsOfType(String methodNameType) {
List<ArgumentOption> optionList = getOptionsWithMethod(methodNameType);
for (ArgumentOption option : optionList) {
LOG.trace("option "+option+" "+this.getClass());
String methodName = null;
try {
methodName = option.getMethodName(methodNameType);
if (methodName != null) {
instantiateAndRunMethod(option, methodName);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("cannot run ["+methodName+"] in "+option.getVerbose()+
" ("+ExceptionUtils.getRootCauseMessage(e)+")");
}
}
}
private List<ArgumentOption> getOptionsWithMethod(String methodName) {
List<ArgumentOption> optionList0 = new ArrayList<ArgumentOption>();
for (ArgumentOption option : chosenArgumentOptionList) {
LOG.trace("run "+option.getRunMethodName());
if (option.getMethodName(methodName) != null) {
LOG.trace("added run "+option.getRunMethodName());
optionList0.add(option);
}
}
return optionList0;
}
protected void addArgumentOptionsAndRunParseMethods(ArgIterator argIterator, String arg) throws Exception {
ensureChosenArgumentList();
boolean processed = false;
if (!arg.startsWith(MINUS)) {
LOG.error("Parsing failed at: ("+arg+"), expected \"-\" trying to recover");
} else {
for (ArgumentOption option : argumentOptionList) {
if (option.matches(arg)) {
LOG.trace("OPTION>> "+option);
String initMethodName = option.getInitMethodName();
if (initMethodName != null) {
runInitMethod1(option, initMethodName);
}
String parseMethodName = option.getParseMethodName();
if (parseMethodName != null) {
runParseMethod1(argIterator, option, parseMethodName);
}
processed = true;
chosenArgumentOptionList.add(option);
break;
}
}
if (!processed) {
LOG.error("Unknown arg: ("+arg+"), trying to recover");
}
}
}
private void runInitMethod1(ArgumentOption option, String initMethodName) {
runMethod(null, option, initMethodName);
}
private void runParseMethod1(ArgIterator argIterator, ArgumentOption option, String parseMethodName) {
runMethod(argIterator, option, parseMethodName);
}
private void runMethod(ArgIterator argIterator, ArgumentOption option, String methodName) {
Method method;
try {
if (argIterator == null) {
method = this.getClass().getMethod(methodName, option.getClass());
} else {
method = this.getClass().getMethod(methodName, option.getClass(), argIterator.getClass());
}
} catch (NoSuchMethodException e) {
debugMethods();
throw new RuntimeException("Cannot find: "+methodName+" in "+this.getClass()+"; from argument "+option.getClass()+";", e);
}
method.setAccessible(true);
try {
if (argIterator == null) {
method.invoke(this, option);
} else {
method.invoke(this, option, argIterator);
}
} catch (Exception e) {
LOG.trace("failed to run "+methodName+" in "+this.getClass()+"; from argument "+option.getClass()+";"+e.getCause());
// e.printStackTrace();
throw new RuntimeException("Cannot run: "+methodName+" in "+this.getClass()+"; from argument "+option.getClass()+";", e);
}
}
private void debugMethods() {
LOG.debug("methods for "+this.getClass());
for (Method meth : this.getClass().getDeclaredMethods()) {
LOG.debug(meth);
}
}
// protected void runInitMethod(ArgumentOption option, String methodName) throws Exception {
// instantiateAndRunMethod(option, methodName);
// protected void runRunMethod(ArgumentOption option, String methodName) throws Exception {
// instantiateAndRunMethod(option, methodName);
// protected void runFinalMethod(ArgumentOption option, String methodName) throws Exception {
// instantiateAndRunMethod(option, methodName);
private void instantiateAndRunMethod(ArgumentOption option, String methodName)
throws IllegalAccessException, InvocationTargetException {
if (methodName != null) {
Method method = null;
try {
method = this.getClass().getMethod(methodName, option.getClass());
} catch (NoSuchMethodException nsme) {
throw new RuntimeException(methodName+"; "+this.getClass()+"; "+option.getClass()+"; \nContact Norma developers: ", nsme);
}
try {
method.setAccessible(true);
method.invoke(this, option);
} catch (Exception ee) {
throw new RuntimeException("invoke "+methodName+" fails", ee);
}
}
}
private void ensureChosenArgumentList() {
if (chosenArgumentOptionList == null) {
chosenArgumentOptionList = new ArrayList<ArgumentOption>();
}
}
protected void printHelp() {
for (ArgumentOption option : argumentOptionList) {
System.err.println(option.getHelp());
}
}
public List<ArgumentOption> getChosenArgumentList() {
ensureChosenArgumentList();
return chosenArgumentOptionList;
}
public String createDebugString() {
StringBuilder sb = new StringBuilder();
getChosenArgumentList();
for (ArgumentOption argumentOption : chosenArgumentOptionList) {
sb.append(argumentOption.toString()+"\n");
}
return sb.toString();
}
/** MAIN CONTROL LOOP
*
*/
public void runAndOutput() {
ensureCMDirList();
if (cmDirList.size() == 0) {
if (project != null) {
output = project;
} else if (output != null) {
LOG.warn("please replace --output with --project");
project = output;
} else {
LOG.error("Cannot create output: --project or --output must be given");
return;
}
LOG.debug("treating as CMDir creation under project "+project);
runRunMethodsOnChosenArgOptions();
} else {
for (int i = 0; i < cmDirList.size(); i++) {
currentCMDir = cmDirList.get(i);
LOG.trace("running dir: "+currentCMDir.getDirectory());
cTreeLog = currentCMDir.getOrCreateCTreeLog(this, logfileName);
currentCMDir.ensureContentProcessor(this);
runInitMethodsOnChosenArgOptions();
runRunMethodsOnChosenArgOptions();
runOutputMethodsOnChosenArgOptions();
if (cTreeLog != null) {
cTreeLog.writeLog();
}
}
}
runFinalMethodsOnChosenArgOptions();
writeLog();
}
private void writeLog() {
if (initLog != null) {
initLog.writeLog();
}
}
protected void addVariableAndExpandReferences(String name, String value) {
ensureVariableProcessor();
try {
variableProcessor.addVariableAndExpandReferences(name, value);
} catch (Exception e) {
LOG.error("add variable {"+name+", "+value+"} failed");
}
}
public VariableProcessor ensureVariableProcessor() {
if (variableProcessor == null) {
variableProcessor = new VariableProcessor();
}
return variableProcessor;
}
public String getUpdate() {
return update;
}
protected void ensureSearcherList() {
if (searcherList == null) {
searcherList = new ArrayList<DefaultSearcher>();
}
}
public List<DefaultSearcher> getSearcherList() {
return searcherList;
}
public List<? extends Element> extractPSectionElements(CMDir cmDir) {
List<? extends Element> elements = null;
if (cmDir != null) {
cmDir.ensureScholarlyHtmlElement();
elements = HtmlP.extractSelfAndDescendantIs(cmDir.htmlElement);
}
return elements;
}
/** gets the HtmlElement for ScholarlyHtml.
*
*
* @return
*/
public static HtmlElement getScholarlyHtmlElement(CMDir cmDir) {
HtmlElement htmlElement = null;
if (cmDir != null && cmDir.hasScholarlyHTML()) {
File scholarlyHtmlFile = cmDir.getExistingScholarlyHTML();
try {
Element xml = XMLUtil.parseQuietlyToDocument(scholarlyHtmlFile).getRootElement();
htmlElement = new HtmlFactory().parse(scholarlyHtmlFile);
} catch (Exception e) {
LOG.error("Cannot create scholarlyHtmlElement");
}
}
return htmlElement;
}
} |
package romelo333.notenoughwands.Items;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.common.util.ForgeDirection;
import romelo333.notenoughwands.Config;
import romelo333.notenoughwands.varia.Tools;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MovingWand extends GenericWand {
private float maxHardness = 50;
private int placeDistance = 4;
public Map<String,Double> blacklisted = new HashMap<String, Double>();
public MovingWand() {
setup("MovingWand", "movingWand").xpUsage(3).availability(AVAILABILITY_NORMAL).loot(5);
}
@Override
public void initConfig(Configuration cfg) {
super.initConfig(cfg);
maxHardness = (float) cfg.get(Config.CATEGORY_WANDS, getUnlocalizedName() + "_maxHardness", maxHardness, "Max hardness this block can move.)").getDouble();
placeDistance = cfg.get(Config.CATEGORY_WANDS, getUnlocalizedName() + "_placeDistance", placeDistance, "Distance at which to place blocks in 'in-air' mode").getInt();
ConfigCategory category = cfg.getCategory(Config.CATEGORY_MOVINGBLACKLIST);
if (category.isEmpty()) {
// Initialize with defaults
blacklist(cfg, "tile.shieldBlock");
blacklist(cfg, "tile.shieldBlock2");
blacklist(cfg, "tile.shieldBlock3");
blacklist(cfg, "tile.solidShieldBlock");
blacklist(cfg, "tile.invisibleShieldBlock");
setCost(cfg, "tile.mobSpawner", 5.0);
setCost(cfg, "tile.blockAiry", 20.0);
} else {
for (Map.Entry<String, Property> entry : category.entrySet()) {
blacklisted.put(entry.getKey(), entry.getValue().getDouble());
}
}
}
private void blacklist(Configuration cfg, String name) {
setCost(cfg, name, -1.0);
}
private void setCost(Configuration cfg, String name, double cost) {
cfg.get(Config.CATEGORY_MOVINGBLACKLIST, name, cost);
blacklisted.put(name, cost);
}
@Override
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean b) {
super.addInformation(stack, player, list, b);
NBTTagCompound compound = stack.getTagCompound();
if (!hasBlock(compound)) {
list.add(EnumChatFormatting.RED + "Wand is empty.");
} else {
int id = compound.getInteger("block");
Block block = (Block) Block.blockRegistry.getObjectById(id);
int meta = compound.getInteger("meta");
String name = Tools.getBlockName(block, meta);
list.add(EnumChatFormatting.GREEN + "Block: " + name);
}
list.add("Right click to take a block.");
list.add("Right click again on block to place it down.");
}
private boolean hasBlock(NBTTagCompound compound) {
return compound != null && compound.hasKey("block");
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
if (!world.isRemote) {
NBTTagCompound compound = stack.getTagCompound();
if (hasBlock(compound)) {
Vec3 lookVec = player.getLookVec();
Vec3 start = Vec3.createVectorHelper(player.posX, player.posY + player.getEyeHeight(), player.posZ);
int distance = this.placeDistance;
Vec3 end = start.addVector(lookVec.xCoord * distance, lookVec.yCoord * distance, lookVec.zCoord * distance);
MovingObjectPosition position = world.rayTraceBlocks(start, end);
if (position == null) {
place(stack, world, (int) end.xCoord, (int) end.yCoord, (int) end.zCoord, ForgeDirection.UNKNOWN.ordinal());
}
}
}
return stack;
}
@Override
public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
if (!world.isRemote) {
NBTTagCompound compound = stack.getTagCompound();
if (hasBlock(compound)) {
place(stack, world, x, y, z, side);
} else {
pickup(stack, player, world, x, y, z);
}
return true;
}
return false;
}
private void place(ItemStack stack, World world, int x, int y, int z, int side) {
int xx = x + ForgeDirection.getOrientation(side).offsetX;
int yy = y + ForgeDirection.getOrientation(side).offsetY;
int zz = z + ForgeDirection.getOrientation(side).offsetZ;
NBTTagCompound tagCompound = stack.getTagCompound();
int id = tagCompound.getInteger("block");
Block block = (Block) Block.blockRegistry.getObjectById(id);
int meta = tagCompound.getInteger("meta");
world.setBlock(xx, yy, zz, block, meta, 3);
world.setBlockMetadataWithNotify(xx, yy, zz, meta, 3);
if (tagCompound.hasKey("tedata")) {
NBTTagCompound tc = (NBTTagCompound) tagCompound.getTag("tedata");
TileEntity tileEntity = world.getTileEntity(xx, yy, zz);
if (tileEntity != null) {
tc.setInteger("x", xx);
tc.setInteger("y", yy);
tc.setInteger("z", zz);
tileEntity.readFromNBT(tc);
tileEntity.markDirty();
world.markBlockForUpdate(xx, yy, zz);
}
}
tagCompound.removeTag("block");
tagCompound.removeTag("tedata");
tagCompound.removeTag("meta");
stack.setTagCompound(tagCompound);
}
private void pickup(ItemStack stack, EntityPlayer player, World world, int x, int y, int z) {
Block block = world.getBlock(x, y, z);
int meta = world.getBlockMetadata(x, y, z);
double cost = checkPickup(player, world, x, y, z, block, maxHardness, blacklisted);
if (cost < 0.0) {
return;
}
if (!checkUsage(stack, player, (float) cost)) {
return;
}
NBTTagCompound tagCompound = Tools.getTagCompound(stack);
String name = Tools.getBlockName(block, meta);
if (name == null) {
Tools.error(player, "You cannot select this block!");
} else {
int id = Block.blockRegistry.getIDForObject(block);
tagCompound.setInteger("block", id);
tagCompound.setInteger("meta", meta);
TileEntity tileEntity = world.getTileEntity(x, y, z);
if (tileEntity != null) {
NBTTagCompound tc = new NBTTagCompound();
tileEntity.writeToNBT(tc);
world.removeTileEntity(x, y, z);
tc.removeTag("x");
tc.removeTag("y");
tc.removeTag("z");
tagCompound.setTag("tedata", tc);
}
world.setBlockToAir(x, y, z);
Tools.notify(player, "You took: " + name);
registerUsage(stack, player, (float) cost);
}
}
@Override
protected void setupCraftingInt(Item wandcore) {
GameRegistry.addRecipe(new ItemStack(this), "re ", "ew ", " w", 'r', Items.redstone, 'e', Items.ender_pearl, 'w', wandcore);
}
} |
package sdk.weixin.res.auth;
/**
* accessRefresh response
*
* @author ray
* @version %I%, %G%
* @see sdk.weixin.req.auth.AccessRefreshRequest
* @since 1.0
*/
public class AccessRefreshResponse {
private String authorizerAccessToken;
private String authorizerrefreshToken;
private Integer expiresIn;
public AccessRefreshResponse() {
}
public String getAuthorizerAccessToken() {
return authorizerAccessToken;
}
public void setAuthorizerAccessToken(String authorizerAccessToken) {
this.authorizerAccessToken = authorizerAccessToken;
}
public String getAuthorizerrefreshToken() {
return authorizerrefreshToken;
}
public void setAuthorizerrefreshToken(String authorizerrefreshToken) {
this.authorizerrefreshToken = authorizerrefreshToken;
}
public Integer getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(Integer expiresIn) {
this.expiresIn = expiresIn;
}
} |
package seedu.ezdo.logic.parser;
import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.ezdo.logic.parser.CliSyntax.KEYWORDS_ARGS_FORMAT;
import static seedu.ezdo.logic.parser.CliSyntax.PREFIX_DUEDATE;
import static seedu.ezdo.logic.parser.CliSyntax.PREFIX_PRIORITY;
import static seedu.ezdo.logic.parser.CliSyntax.PREFIX_STARTDATE;
import static seedu.ezdo.logic.parser.CliSyntax.PREFIX_TAG;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import seedu.ezdo.commons.exceptions.IllegalValueException;
import seedu.ezdo.commons.util.SearchParameters;
import seedu.ezdo.logic.commands.Command;
import seedu.ezdo.logic.commands.FindCommand;
import seedu.ezdo.logic.commands.IncorrectCommand;
import seedu.ezdo.logic.parser.ArgumentTokenizer.Prefix;
import seedu.ezdo.model.todo.Priority;
import seedu.ezdo.model.todo.Task;
import seedu.ezdo.model.todo.TaskDate;
//@@author A0141010L
/**
* Parses input arguments and creates a new FindCommand object
*/
public class FindCommandParser implements CommandParser {
/**
* Parses the given {@code String} of arguments in the context of the
* FindCommand and returns an FindCommand object for execution.
*/
@Override
public Command parse(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE));
}
assert args != null;
ArgumentTokenizer argsTokenizer = new ArgumentTokenizer(PREFIX_PRIORITY, PREFIX_STARTDATE, PREFIX_DUEDATE,
PREFIX_TAG);
argsTokenizer.tokenize(args);
String namesToMatch = argsTokenizer.getPreamble().orElse("");
String[] splitNames = namesToMatch.split("\\s+");
Optional<Priority> findPriority = null;
Optional<TaskDate> findStartDate = null;
Optional<TaskDate> findDueDate = null;
Set<String> findTags = null;
boolean searchBeforeStartDate = false;
boolean searchBeforeDueDate = false;
boolean searchAfterStartDate = false;
boolean searchAfterDueDate = false;
try {
boolean isFind = true;
Optional<String> optionalStartDate = getOptionalValue(argsTokenizer, PREFIX_STARTDATE);
Optional<String> optionalDueDate = getOptionalValue(argsTokenizer, PREFIX_DUEDATE);
if (isFindBefore(optionalStartDate)) {
optionalStartDate = parseFindBefore(optionalStartDate);
searchBeforeStartDate = true;
}
if (isFindBefore(optionalDueDate)) {
optionalDueDate = parseFindBefore(optionalDueDate);
searchBeforeDueDate = true;
}
if (isFindAfter(optionalStartDate)) {
optionalStartDate = parseFindAfter(optionalStartDate);
searchAfterStartDate = true;
}
if (isFindAfter(optionalDueDate)) {
optionalDueDate = parseFindAfter(optionalDueDate);
searchAfterDueDate = true;
}
findStartDate = ParserUtil.parseStartDate(optionalStartDate, isFind);
findDueDate = ParserUtil.parseDueDate(optionalDueDate, isFind);
findTags = ParserUtil.toSet(argsTokenizer.getAllValues(PREFIX_TAG));
findPriority = ParserUtil.parsePriority(getOptionalValue(argsTokenizer, PREFIX_PRIORITY));
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
Set<String> keywords = new HashSet<String>(Arrays.asList(splitNames));
SearchParameters searchParameters = new SearchParameters.Builder().name(keywords).priority(findPriority)
.startDate(findStartDate).dueDate(findDueDate).tags(findTags).startBefore(searchBeforeStartDate)
.dueBefore(searchBeforeDueDate).startAfter(searchAfterStartDate).dueAfter(searchAfterDueDate).build();
return new FindCommand(searchParameters);
}
private Optional<String> getOptionalValue(ArgumentTokenizer tokenizer, Prefix prefix) {
Optional<String> optionalString;
if (!tokenizer.getValue(prefix).isPresent()) {
optionalString = Optional.empty();
} else {
optionalString = Optional.of(tokenizer.getValue(prefix).get());
}
return optionalString;
}
/**
* Removes "before" prefix from the start of a given String
*/
private Optional<String> parseFindBefore(Optional<String> taskDate) {
Optional<String> optionalDate;
String taskDateString = taskDate.get();
String commandString = taskDateString.substring(6, taskDateString.length()).trim();
optionalDate = Optional.of(commandString);
return optionalDate;
}
/**
* Removes "after" prefix from the start of a given String
*/
private Optional<String> parseFindAfter(Optional<String> taskDate) {
Optional<String> optionalDate;
String taskDateString = taskDate.get();
String commandString = taskDateString.substring(5, taskDateString.length()).trim();
optionalDate = Optional.of(commandString);
return optionalDate;
}
private boolean isFindBefore(Optional<String> taskDate) {
if (!taskDate.isPresent()) {
return false;
}
String taskDateString = taskDate.get();
int prefixLength = 6;
if (taskDateString.length() <= prefixLength) {
return false;
}
String prefixToCompare1 = "before";
String prefixToCompare2 = "Before";
String byPrefix = taskDateString.substring(0, prefixLength);
return byPrefix.equals(prefixToCompare1) || byPrefix.equals(prefixToCompare2);
}
private boolean isFindAfter(Optional<String> taskDate) {
if (!taskDate.isPresent()) {
return false;
}
String taskDateString = taskDate.get();
int prefixLength = 5;
if (taskDateString.length() <= prefixLength) {
return false;
}
String prefixToCompare1 = "after";
String prefixToCompare2 = "After";
String byPrefix = taskDateString.substring(0, prefixLength);
return byPrefix.equals(prefixToCompare1) || byPrefix.equals(prefixToCompare2);
}
} |
package seedu.taskitty.logic.parser;
import seedu.taskitty.commons.exceptions.IllegalValueException;
import seedu.taskitty.commons.util.StringUtil;
import seedu.taskitty.commons.util.TaskUtil;
import seedu.taskitty.logic.commands.*;
import seedu.taskitty.model.tag.Tag;
import seedu.taskitty.model.task.Task;
import seedu.taskitty.model.task.TaskDate;
import seedu.taskitty.model.task.TaskTime;
import static seedu.taskitty.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.taskitty.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.joestelmach.natty.DateGroup;
import com.joestelmach.natty.Parser;
/**
* Parses user input.
*/
public class CommandParser {
public static final String COMMAND_QUOTE_SYMBOL = "\"";
public static final String EMPTY_STRING = "";
public static final int NOT_FOUND = -1;
public static final int STRING_START = 0;
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
//Used for checking for number date formats in arguments
private static final Pattern LOCAL_DATE_FORMAT = Pattern.compile(".* (?<arguments>\\d(\\d)?[/-]\\d(\\d)?).*");
private static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
private static final Pattern TASK_DATA_ARGS_FORMAT = //Tags must be at the end
Pattern.compile("(?<arguments>[\\p{Graph} ]+)"); // \p{Graph} is \p{Alnum} or \p{Punct}
public CommandParser() {}
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return prepareAdd(arguments);
case DeleteCommand.COMMAND_WORD:
return prepareDelete(arguments);
case EditCommand.COMMAND_WORD:
return prepareEdit(arguments);
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case FindCommand.COMMAND_WORD:
return prepareFind(arguments);
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
case UndoCommand.COMMAND_WORD:
return new UndoCommand();
case DoneCommand.COMMAND_WORD:
return prepareDone(arguments);
case ViewCommand.COMMAND_WORD:
if (userInput.equals("view")) {
return prepareView(null);
}
return prepareView(arguments);
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
/**
* Parses arguments in the context of the view command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareView(String arguments) {
if (arguments == null) {
return new ViewCommand(); // view events today, and all deadlines and todos
}
if (arguments.trim().equals("done")) {
return new ViewCommand("done"); // view done command
}
String[] details = extractTaskDetailsNatty(arguments);
if (details.length!= 3) { // no date was successfully extracted
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ViewCommand.MESSAGE_USAGE));
} else {
assert details[1] != null; // contains date
return new ViewCommand(details[1]);
}
}
//@@author A0139930B
/**
* Parses arguments in the context of the add task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareAdd(String args){
final Matcher matcher = TASK_DATA_ARGS_FORMAT.matcher(args.trim());
// Validate arg string format
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
try {
String arguments = matcher.group("arguments");
String taskDetailArguments = getTaskDetailArguments(arguments);
String tagArguments = getTagArguments(arguments);
return new AddCommand(
extractTaskDetailsNatty(taskDetailArguments),
getTagsFromArgs(tagArguments)
);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
/**
* Parses the argument to get a string of all the relevant details of the task
*
* @param arguments command args string without command word
*/
private String getTaskDetailArguments(String arguments) {
int detailLastIndex = arguments.indexOf(Tag.TAG_VALIDATION_REGEX_PREFIX);
if (detailLastIndex == NOT_FOUND) {
detailLastIndex = arguments.length();
}
return arguments.substring(STRING_START, detailLastIndex).trim();
}
/**
* Parses the argument to get a string of all tags, including the Tag prefix
*
* @param arguments command args string without command word
*/
private String getTagArguments(String arguments) {
//This line is exactly the same as the 1st line of getTaskDetailArguments.. how?
int tagStartIndex = arguments.indexOf(Tag.TAG_VALIDATION_REGEX_PREFIX);
if (tagStartIndex == NOT_FOUND) {
tagStartIndex = arguments.length();
}
return arguments.substring(tagStartIndex);
}
/**
* Extracts the task details into a String array representing the name, date, time.
* Details are arranged according to index shown in Task
*
* @param dataArguments command args string with only name, date, time arguments
*/
private String[] extractTaskDetailsNatty(String dataArguments) {
dataArguments = convertToNattyDateFormat(dataArguments);
int nameEndIndex = dataArguments.length();
ArrayList<String> details = new ArrayList<String>();
//Attempt to extract name out if it is surrounded by quotes
nameEndIndex = dataArguments.lastIndexOf(COMMAND_QUOTE_SYMBOL);
boolean isNameExtracted = false;
if (nameEndIndex != NOT_FOUND) {
int nameStartIndex = dataArguments.indexOf(COMMAND_QUOTE_SYMBOL);
if (nameStartIndex == NOT_FOUND) {
nameStartIndex = STRING_START;
}
//+1 because we want the quote included in the string
String nameDetail = dataArguments.substring(nameStartIndex, nameEndIndex + 1);
//remove name from dataArguments
dataArguments = dataArguments.replace(nameDetail, EMPTY_STRING);
//remove quotes from nameDetail
nameDetail = nameDetail.replaceAll(COMMAND_QUOTE_SYMBOL, EMPTY_STRING);
details.add(Task.TASK_COMPONENT_INDEX_NAME, nameDetail);
isNameExtracted = true;
}
Parser dateTimeParser = new Parser();
List<DateGroup> dateGroups = dateTimeParser.parse(dataArguments);
nameEndIndex = dataArguments.length();
for (DateGroup group : dateGroups) {
List<Date> dates = group.getDates();
//Natty's getPosition returns 1 based position
//-1 because we want the 0 based position
nameEndIndex = Math.min(nameEndIndex, group.getPosition() - 1);
for (Date date : dates) {
details.add(extractLocalDate(date));
details.add(extractLocalTime(date));
}
}
if (!isNameExtracted) {
details.add(Task.TASK_COMPONENT_INDEX_NAME,
dataArguments.substring(STRING_START, nameEndIndex).trim());
}
String[] returnDetails = new String[details.size()];
details.toArray(returnDetails);
return returnDetails;
}
//@@author A0139052L
/**
* Converts any number formats of date from the local format to one which can be parsed by natty
* @param arguments
* @return arguments with converted dates if any
*/
private String convertToNattyDateFormat(String arguments) {
Matcher matchDate = LOCAL_DATE_FORMAT.matcher(arguments);
if (matchDate.matches()) {
String localDateString = matchDate.group("arguments");
String dateSeparator = getDateSeparator(localDateString);
return convertToNattyFormat(arguments, localDateString, dateSeparator);
} else {
return arguments;
}
}
/**
* Get the separator between day month and year in a date
* @param localDateString the string representing the date
* @return the separator character used in localDateString
*/
private String getDateSeparator(String localDateString) {
// if 2nd char in string is an integer, then the 3rd char must be the separator
// else 2nd char is the separator
if (StringUtil.isInteger(localDateString.substring(1,2))) {
return localDateString.substring(2, 3);
} else {
return localDateString.substring(1, 2);
}
}
/**
* Convert the local date format inside arguments into a format
* which can be parsed by natty
* @param arguments the full argument string
* @param localDateString the localDate extracted out from arguments
* @param dateSeparator the separator for the date extracted out
* @return converted string where the date format has been converted from local to natty format
*/
private String convertToNattyFormat(String arguments, String localDateString, String dateSeparator) {
String[] dateComponents = localDateString.split(dateSeparator);
int indexOfDate = arguments.indexOf(localDateString);
String nattyDateString = swapDayAndMonth(dateComponents, dateSeparator);
arguments = arguments.replace(localDateString, nattyDateString);
String stringFromConvertedDate = arguments.substring(indexOfDate);
String stringUpToConvertedDate = arguments.substring(0, indexOfDate);
return convertToNattyDateFormat(stringUpToConvertedDate) + stringFromConvertedDate;
}
/**
* Swaps the day and month component of the date
* @param dateComponents the String array obtained after separting the date string
* @param dateSeparator the Separator used in the date string
* @return the date string with its day and month component swapped
*/
private String swapDayAndMonth(String[] dateComponents, String dateSeparator) {
StringBuilder nattyDateStringBuilder = new StringBuilder();
nattyDateStringBuilder.append(dateComponents[1]);
nattyDateStringBuilder.append(dateSeparator);
nattyDateStringBuilder.append(dateComponents[0]);
return nattyDateStringBuilder.toString();
}
//@@author A0139930B
/**
* Takes in a date from Natty and converts it into a string representing date
* Format of date returned is according to TaskDate
*
* @param date retrieved using Natty
*/
private String extractLocalDate(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat(TaskDate.DATE_FORMAT_STRING);
return dateFormat.format(date);
}
/**
* Takes in a date from Natty and converts it into a string representing time
* Format of time returned is according to TaskTime
*
* @param date retrieved using Natty
*/
private String extractLocalTime(Date date) {
SimpleDateFormat timeFormat = new SimpleDateFormat(TaskTime.TIME_FORMAT_STRING);
String currentTime = timeFormat.format(new Date());
String inputTime = timeFormat.format(date);
if (currentTime.equals(inputTime)) {
//Natty parses the current time if string does not include time.
//We want to ignore input when current time equal input time
return null;
}
return inputTime;
}
//@@author
/**
* Extracts the new person's tags from the add command's tag arguments string.
* Merges duplicate tag strings.
*/
private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException {
// no tags
if (tagArguments.isEmpty()) {
return Collections.emptySet();
}
// replace first delimiter prefix, then split
final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/"));
return new HashSet<>(tagStrings);
}
/**
* Parses arguments in the context of the delete person command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
args = args.trim();
if (args.length() != 1 && args.length() != 2) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
//takes the last argument given for parsing index
Optional<Integer> index = parseIndex(args.substring(args.length() - 1));
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
if (args.length() == 1) {
return new DeleteCommand(index.get());
} else {
return new DeleteCommand(index.get(), TaskUtil.getCategoryIndex(args.substring(0, 1)));
}
}
//@@author A0135793W
/**
* Parses arguments in the context of the mark as done command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDone(String args) {
args = args.trim();
if (args.length() != 1 && args.length() != 2) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DoneCommand.MESSAGE_USAGE));
}
//takes the last argument given for parsing index
Optional<Integer> index = parseIndex(args.substring(args.length() - 1));
if (!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DoneCommand.MESSAGE_USAGE));
}
if (args.length() == 1) {
return new DoneCommand(index.get());
} else {
return new DoneCommand(index.get(), TaskUtil.getCategoryIndex(args.substring(0, 1)));
}
}
/**
* Parses arguments in the context of the edit task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareEdit(String args) {
String[] splitArgs = args.trim().split(" ");
if (splitArgs.length < 2) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
String indexWithCategory = splitArgs[0];
Optional<Integer> index = parseIndex(indexWithCategory.substring(indexWithCategory.length() - 1));
if(!index.isPresent() || (indexWithCategory.length() != 1 && indexWithCategory.length() != 2)){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
try {
String arguments = "";
for (int i = 1; i<splitArgs.length; i++){
arguments = arguments + splitArgs[i] + " ";
}
arguments.substring(0, arguments.length() - 1);
String taskDetailArguments = getTaskDetailArguments(arguments);
String tagArguments = getTagArguments(arguments);
if (indexWithCategory.length() == 1) {
return new EditCommand(
extractTaskDetailsNatty(taskDetailArguments),
getTagsFromArgs(tagArguments),
index.get());
} else {
return new EditCommand(
extractTaskDetailsNatty(taskDetailArguments),
getTagsFromArgs(tagArguments),
index.get(),
TaskUtil.getCategoryIndex(indexWithCategory.substring(0, 1)));
}
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
//@@author
/**
* Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index.
* Returns an {@code Optional.empty()} otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if(!StringUtil.isUnsignedInteger(index)){
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses arguments in the context of the find person command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareFind(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
} |
package seedu.taskitty.logic.parser;
import seedu.taskitty.commons.exceptions.IllegalValueException;
import seedu.taskitty.commons.util.StringUtil;
import seedu.taskitty.commons.util.TaskUtil;
import seedu.taskitty.logic.commands.*;
import seedu.taskitty.model.tag.Tag;
import seedu.taskitty.model.task.Task;
import seedu.taskitty.model.task.TaskDate;
import seedu.taskitty.model.task.TaskTime;
import static seedu.taskitty.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.taskitty.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.joestelmach.natty.DateGroup;
import com.joestelmach.natty.Parser;
import javafx.util.Pair;
/**
* Parses user input.
*/
public class CommandParser {
public static final String COMMAND_QUOTE_SYMBOL = "\"";
public static final String EMPTY_STRING = "";
public static final int NOT_FOUND = -1;
public static final int STRING_START = 0;
public static final int FILE_EXTENSION_LENGTH = 4;
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
//Used for checking for number date formats in arguments
private static final Pattern LOCAL_DATE_FORMAT = Pattern.compile("\\d{1,2}[/-]\\d{1,2}[/-]?(\\d{2}|\\d{4})?");
private static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
private static final Pattern TASK_DATA_ARGS_FORMAT = //Tags must be at the end
Pattern.compile("(?<arguments>[\\p{Graph} ]+)"); // \p{Graph} is \p{Alnum} or \p{Punct}
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
HelpCommand.MESSAGE_ERROR));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return prepareAdd(arguments);
case DeleteCommand.COMMAND_WORD:
return prepareDelete(arguments);
case EditCommand.COMMAND_WORD:
return prepareEdit(arguments);
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case FindCommand.COMMAND_WORD:
return prepareFind(arguments);
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
case UndoCommand.COMMAND_WORD:
return new UndoCommand();
case RedoCommand.COMMAND_WORD:
return new RedoCommand();
case DoneCommand.COMMAND_WORD:
return prepareDone(arguments);
case ViewCommand.COMMAND_WORD:
return prepareView(arguments);
case PathCommand.COMMAND_WORD:
return preparePath(arguments);
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
//@@author A0135793W
/**
* Parses arguments in the context of path command
* @param argument full command args string
* @return the prepared command
*/
private Command preparePath(String argument) {
String args = argument.trim();
if (args.equals(EMPTY_STRING)) {
return new IncorrectCommand(String.format(PathCommand.MESSAGE_INVALID_MISSING_FILEPATH,
PathCommand.MESSAGE_VALID_FILEPATH_USAGE));
} else if (args.length() < FILE_EXTENSION_LENGTH) {
return new IncorrectCommand(String.format(PathCommand.MESSAGE_INVALID_FILEPATH,
PathCommand.MESSAGE_VALID_FILEPATH_USAGE));
} else if (!isValidFileXmlExtension(args)) {
return new IncorrectCommand(String.format(PathCommand.MESSAGE_INVALID_FILEPATH,
PathCommand.MESSAGE_VALID_FILEPATH_USAGE));
}
return new PathCommand(args);
}
/**
* Checks if input argument has a valid xml file extension
* @param argument full command args string
* @return true if argument ends with .xml and false otherwise
*/
private boolean isValidFileXmlExtension(String argument) {
//Checking if filename ends with .xml
Optional<String> fileExtension = getFileExtension(argument.trim());
if (!fileExtension.isPresent()) {
return false;
} else if (!fileExtension.get().equals(".xml")) {
return false;
}
return true;
}
private Optional<String> getFileExtension(String argument) {
int length = argument.length();
String extension = argument.substring(length-FILE_EXTENSION_LENGTH);
if (extension.charAt(STRING_START) != '.') {
return Optional.empty();
}
return Optional.of(extension);
}
//@@author
//@@author A0130853L
/**
* Parses arguments in the context of the view command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareView(String arguments) {
if (arguments.trim().isEmpty()) {
return new ViewCommand(); // view all upcoming uncompleted tasks, events and deadlines
}
if (arguments.trim().equals("done")) {
return new ViewCommand("done"); // view done command
}
if (arguments.trim().equals("all")) {
return new ViewCommand("all"); // view all command
}
String[] details = extractTaskDetailsNatty(arguments);
if (details.length!= 3) { // no date was successfully extracted
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
Command.MESSAGE_FORMAT + ViewCommand.MESSAGE_PARAMETER));
} else {
assert details[1] != null; // contains date
return new ViewCommand(details[1]);
}
}
//@@author A0139930B
/**
* Parses arguments in the context of the add task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareAdd(String args){
final Matcher matcher = TASK_DATA_ARGS_FORMAT.matcher(args.trim());
// Validate arg string format
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
Command.MESSAGE_FORMAT + AddCommand.MESSAGE_PARAMETER));
}
try {
String arguments = matcher.group("arguments");
String taskDetailArguments = getTaskDetailArguments(arguments);
String tagArguments = getTagArguments(arguments);
return new AddCommand(
extractTaskDetailsNatty(taskDetailArguments),
getTagsFromArgs(tagArguments),
args
);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
/**
* Parses the argument to get a string of all the relevant details of the task
*
* @param arguments command args string without command word
*/
private String getTaskDetailArguments(String arguments) {
int detailLastIndex = arguments.indexOf(Tag.TAG_PREFIX);
if (detailLastIndex == NOT_FOUND) {
detailLastIndex = arguments.length();
}
return arguments.substring(STRING_START, detailLastIndex).trim();
}
/**
* Parses the argument to get a string of all tags, including the Tag prefix
*
* @param arguments command args string without command word
*/
private String getTagArguments(String arguments) {
int tagStartIndex = arguments.indexOf(Tag.TAG_PREFIX);
if (tagStartIndex == NOT_FOUND) {
tagStartIndex = arguments.length();
}
return arguments.substring(tagStartIndex);
}
/**
* Extracts the task details into a String array representing the name, date, time.
* Details are arranged according to index shown in Task
*
* @param dataArguments command args string with only name, date, time arguments
*/
private String[] extractTaskDetailsNatty(String dataArguments) {
String dataArgumentsNattyFormat = convertToNattyDateFormat(dataArguments);
int nameEndIndex = dataArgumentsNattyFormat.length();
ArrayList<String> details = new ArrayList<String>();
//Attempt to extract name out if it is surrounded by quotes
nameEndIndex = dataArgumentsNattyFormat.lastIndexOf(COMMAND_QUOTE_SYMBOL);
boolean isNameExtracted = false;
if (nameEndIndex != NOT_FOUND) {
int nameStartIndex = dataArgumentsNattyFormat.indexOf(COMMAND_QUOTE_SYMBOL);
if (nameStartIndex == NOT_FOUND) {
nameStartIndex = STRING_START;
}
//+1 because we want the quote included in the string
String nameDetail = dataArgumentsNattyFormat.substring(nameStartIndex, nameEndIndex + 1);
//remove name from dataArguments
dataArgumentsNattyFormat = dataArgumentsNattyFormat.replace(nameDetail, EMPTY_STRING);
//remove quotes from nameDetail
nameDetail = nameDetail.replaceAll(COMMAND_QUOTE_SYMBOL, EMPTY_STRING);
details.add(Task.TASK_COMPONENT_INDEX_NAME, nameDetail);
isNameExtracted = true;
}
Parser dateTimeParser = new Parser();
List<DateGroup> dateGroups = dateTimeParser.parse(dataArgumentsNattyFormat);
nameEndIndex = dataArgumentsNattyFormat.length();
for (DateGroup group : dateGroups) {
List<Date> dates = group.getDates();
//Natty's getPosition returns 1 based position
//-1 because we want the 0 based position
nameEndIndex = Math.min(nameEndIndex, group.getPosition() - 1);
for (Date date : dates) {
details.add(extractLocalDate(date));
details.add(extractLocalTime(date));
}
}
if (!isNameExtracted) {
details.add(Task.TASK_COMPONENT_INDEX_NAME,
dataArgumentsNattyFormat.substring(STRING_START, nameEndIndex).trim());
}
String[] returnDetails = new String[details.size()];
details.toArray(returnDetails);
return returnDetails;
}
//@@author A0139052L
/**
* Converts any number formats of date from the local format to one which can be parsed by natty
* @param arguments
* @return arguments with converted dates if any
*/
private String convertToNattyDateFormat(String arguments) {
String convertedString = arguments;
String[] splitArgs = arguments.split(" ");
for (String arg: splitArgs) {
Matcher matchArg = LOCAL_DATE_FORMAT.matcher(arg);
if (matchArg.matches()) {
String dateSeparator = getDateSeparator(arg);
String convertedDate = swapDayAndMonth(arg.split(dateSeparator), dateSeparator);
convertedString = convertedString.replace(arg, convertedDate);
}
}
return convertedString;
// Matcher matchDate = LOCAL_DATE_FORMAT.matcher(arguments);
// if (matchDate.matches()) {
// String localDateString = matchDate.group("arguments");
// String dateSeparator = getDateSeparator(localDateString);
// return convertToNattyFormat(arguments, localDateString, dateSeparator);
// } else {
// return arguments;
}
/**
* Get the separator between day month and year in a date
* @param localDateString the string representing the date
* @return the separator character used in localDateString
*/
private String getDateSeparator(String localDateString) {
// if 2nd char in string is an integer, then the 3rd char must be the separator
// else 2nd char is the separator
if (StringUtil.isInteger(localDateString.substring(1,2))) {
return localDateString.substring(2, 3);
} else {
return localDateString.substring(1, 2);
}
}
/**
* Convert the local date format inside arguments into a format
* which can be parsed by natty
* @param arguments the full argument string
* @param localDateString the localDate extracted out from arguments
* @param dateSeparator the separator for the date extracted out
* @return converted string where the date format has been converted from local to natty format
*/
private String convertToNattyFormat(String arguments, String localDateString, String dateSeparator) {
String[] dateComponents = localDateString.split(dateSeparator);
int indexOfDate = arguments.indexOf(localDateString);
String nattyDateString = swapDayAndMonth(dateComponents, dateSeparator);
arguments = arguments.replace(localDateString, nattyDateString);
String stringFromConvertedDate = arguments.substring(indexOfDate);
String stringUpToConvertedDate = arguments.substring(0, indexOfDate);
return convertToNattyDateFormat(stringUpToConvertedDate) + stringFromConvertedDate;
}
/**
* Swaps the day and month component of the date
* @param dateComponents the String array obtained after separting the date string
* @param dateSeparator the Separator used in the date string
* @return the date string with its day and month component swapped
*/
private String swapDayAndMonth(String[] dateComponents, String dateSeparator) {
StringBuilder nattyDateStringBuilder = new StringBuilder();
nattyDateStringBuilder.append(dateComponents[1]);
nattyDateStringBuilder.append(dateSeparator);
nattyDateStringBuilder.append(dateComponents[0]);
return nattyDateStringBuilder.toString();
}
//@@author A0139930B
/**
* Takes in a date from Natty and converts it into a string representing date
* Format of date returned is according to TaskDate
*
* @param date retrieved using Natty
*/
private String extractLocalDate(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat(TaskDate.DATE_FORMAT_STRING);
return dateFormat.format(date);
}
/**
* Takes in a date from Natty and converts it into a string representing time
* Format of time returned is according to TaskTime
*
* @param date retrieved using Natty
*/
private String extractLocalTime(Date date) {
SimpleDateFormat timeFormat = new SimpleDateFormat(TaskTime.TIME_FORMAT_STRING);
String currentTime = timeFormat.format(new Date());
String inputTime = timeFormat.format(date);
if (currentTime.equals(inputTime)) {
//Natty parses the current time if string does not include time.
//We want to ignore input when current time equal input time
return null;
}
return inputTime;
}
//@@author A0139930B
/**
* Extracts the new task's tags from the add command's tag arguments string.
* Merges duplicate tag strings.
*/
private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException {
// no tags
if (tagArguments.isEmpty()) {
return Collections.emptySet();
}
// replace first delimiter prefix, then split
final Collection<String> tagStrings = Arrays.asList(tagArguments
.replaceFirst(Tag.TAG_PREFIX, EMPTY_STRING)
.split(Tag.TAG_PREFIX));
return new HashSet<>(tagStrings);
}
//@@author A0139052L
/**
* Parses arguments in the context of the delete person command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
String dataArgs = args.trim();
String[] indexes = dataArgs.split("\\s");
ArrayList<Pair<Integer, Integer>> listOfIndexes = getIndexes(indexes);
if (listOfIndexes == null) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT,
Command.MESSAGE_FORMAT + DeleteCommand.MESSAGE_PARAMETER));
}
return new DeleteCommand(listOfIndexes, args);
}
//@@author A0135793W
/**
* Parses arguments in the context of the mark as done command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDone(String args) {
String dataArgs = args.trim();
String[] indexes = dataArgs.split("\\s");
ArrayList<Pair<Integer, Integer>> listOfIndexes = getIndexes(indexes);
if (listOfIndexes == null) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT,
Command.MESSAGE_FORMAT + DoneCommand.MESSAGE_PARAMETER));
}
return new DoneCommand(listOfIndexes, args);
}
//@@author
//@@author A0139052L
/**
*
* Parses each index string in the array and adds them to a list if valid
* @param indexes the string array of indexes separated
* @return a list of all valid indexes parsed or null if an invalid index was given
*/
private ArrayList<Pair<Integer, Integer>> getIndexes(String[] indexes) {
Pair<Integer, Integer> categoryAndIndex;
ArrayList<Pair<Integer, Integer>> listOfIndexes = new ArrayList<Pair<Integer, Integer>>();
for (String index: indexes) {
if (index.contains("-")) {
String[] splitIndex = index.split("-");
categoryAndIndex = getCategoryAndIndex(splitIndex[0]);
Optional<Integer> secondIndex = parseIndex(splitIndex[1]);
if (!secondIndex.isPresent() || categoryAndIndex == null) {
return null;
}
int firstIndex = categoryAndIndex.getValue();
int categoryIndex = categoryAndIndex.getKey();
if (firstIndex >= secondIndex.get()) {
return null;
}
for (; firstIndex <= secondIndex.get(); firstIndex++) {
categoryAndIndex = new Pair<Integer, Integer>(categoryIndex, firstIndex);
listOfIndexes.add(categoryAndIndex);
}
} else {
categoryAndIndex = getCategoryAndIndex(index);
if (categoryAndIndex == null) {
return null;
}
listOfIndexes.add(categoryAndIndex);
}
}
return listOfIndexes;
}
//@@author A0135793W
/**
* Parses arguments in the context of the edit task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareEdit(String args) {
String[] splitArgs = args.trim().split(" ");
if (splitArgs.length < 2) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT,
Command.MESSAGE_FORMAT + EditCommand.MESSAGE_PARAMETER));
}
Pair<Integer, Integer> categoryAndIndexPair = getCategoryAndIndex(splitArgs[0]);
if (categoryAndIndexPair == null) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT,
Command.MESSAGE_FORMAT + EditCommand.MESSAGE_PARAMETER));
}
try {
String arguments = "";
for (int i = 1; i<splitArgs.length; i++){
arguments = arguments + splitArgs[i] + " ";
}
arguments.substring(0, arguments.length() - 1);
String taskDetailArguments = getTaskDetailArguments(arguments);
String tagArguments = getTagArguments(arguments);
return new EditCommand(
extractTaskDetailsNatty(taskDetailArguments),
getTagsFromArgs(tagArguments),
categoryAndIndexPair.getValue(),
categoryAndIndexPair.getKey(),
args);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
//@@author
//@@author A0139052L
/**
* Parses the string and returns the categoryIndex and the index if a valid one was given
* @param args
* @return an int array with categoryIndex and index in 0 and 1 index respectively
*/
private Pair<Integer, Integer> getCategoryAndIndex(String args) {
if (args.trim().equals(EMPTY_STRING)) {
return null;
}
// category index should be the first char in the string
Optional<Integer> checkForCategory = parseIndex(args.substring(0, 1));
Optional<Integer> index;
int categoryIndex;
if (checkForCategory.isPresent()){
index = parseIndex(args);
// give the default category index if none was provided
categoryIndex = TaskUtil.getDefaultCategoryIndex();
} else {
// index should be the rest of the string if category char is present
index = parseIndex(args.substring(1));
categoryIndex = TaskUtil.getCategoryIndex(args.charAt(0));
}
if (!index.isPresent()){
return null;
}
return new Pair<Integer, Integer>(categoryIndex, index.get());
}
//@@author
/**
* Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index.
* Returns an {@code Optional.empty()} otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if(!StringUtil.isUnsignedInteger(index)){
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses arguments in the context of the find person command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareFind(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
} |
package studentcapture.assignment;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.InputMismatchException;
import java.util.Map;
public class AssignmentModel {
private Integer assignmentID;
private int courseID;
private String title;
private String description;
private AssignmentVideoIntervall videoIntervall;
private AssignmentDateIntervalls assignmentIntervall;
private GradeScale scale;
private String recap;
private Timestamp published;
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
public AssignmentModel(int courseID,
String title,
String description,
AssignmentVideoIntervall videoIntervall,
AssignmentDateIntervalls assignmentIntervall,
String scale,
String recap) throws InputMismatchException {
this.courseID = courseID;
this.title = title;
this.description = description;
this.videoIntervall = videoIntervall;
this.assignmentIntervall = assignmentIntervall;
this.scale = GradeScale.valueOf(scale);
this.recap = recap;
}
public AssignmentModel() {
}
public AssignmentModel(Map<String, Object> map) {
assignmentID = (Integer) map.get("AssignmentId");
courseID = (int) map.get("CourseId");
title = (String) map.get("Title");
assignmentIntervall = new AssignmentDateIntervalls();
assignmentIntervall.setStartDate(FORMATTER.format((Timestamp) map.get("StartDate")));
assignmentIntervall.setEndDate(FORMATTER.format((Timestamp) map.get("EndDate")));
videoIntervall = new AssignmentVideoIntervall();
videoIntervall.setMinTimeSeconds((Integer) map.get("MinTime"));
videoIntervall.setMaxTimeSeconds((Integer) map.get("MaxTime"));
try {
published = (Timestamp) map.get("Published");
} catch (NullPointerException e) {
published = null;
}
description = (String) map.get("Description");
try {
scale = (GradeScale) map.get("Scale");
if(scale == null) {
throw new NullPointerException();
}
} catch (Exception e) {
scale = GradeScale.NUMBER_SCALE;
}
}
public Integer getAssignmentID() {
return assignmentID;
}
public void setAssignmentID(Integer assignmentID) {
this.assignmentID = assignmentID;
}
public int getCourseID() {
return courseID;
}
public void setCourseID(int courseID) {
this.courseID = courseID;
}
public void setVideoIntervall(AssignmentVideoIntervall videoIntervall) {
this.videoIntervall = videoIntervall;
}
public AssignmentVideoIntervall getVideoIntervall() {
return videoIntervall;
}
public void setAssignmentIntervall(AssignmentDateIntervalls assignmentIntervall) {
this.assignmentIntervall = assignmentIntervall;
}
public AssignmentDateIntervalls getAssignmentIntervall() {
return assignmentIntervall;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getScale() {
return scale.name();
}
public void setScale(String scale) {
this.scale = GradeScale.valueOf(scale);
}
public String getRecap() {
return recap;
}
public void setRecap(String recap) {
this.recap = recap;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AssignmentModel that = (AssignmentModel) o;
if (courseID != that.courseID) return false;
if (assignmentID != null ? !assignmentID.equals(that.assignmentID) : that.assignmentID != null)
return false;
if (title != null ? !title.equals(that.title) : that.title != null)
return false;
if (description != null ? !description.equals(that.description) : that.description != null)
return false;
if (videoIntervall != null ? !videoIntervall.equals(that.videoIntervall) : that.videoIntervall != null)
return false;
if (assignmentIntervall != null ? !assignmentIntervall.equals(that.assignmentIntervall) : that.assignmentIntervall != null)
return false;
if (scale != that.scale) return false;
if (recap != null ? !recap.equals(that.recap) : that.recap != null)
return false;
return published != null ? published.equals(that.published) : that.published == null;
}
@Override
public int hashCode() {
int result = assignmentID != null ? assignmentID.hashCode() : 0;
result = 31 * result + courseID;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
result = 31 * result + (videoIntervall != null ? videoIntervall.hashCode() : 0);
result = 31 * result + (assignmentIntervall != null ? assignmentIntervall.hashCode() : 0);
result = 31 * result + (scale != null ? scale.hashCode() : 0);
result = 31 * result + (recap != null ? recap.hashCode() : 0);
result = 31 * result + (published != null ? published.hashCode() : 0);
return result;
}
} |
package com.biz.fragment;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.VideoView;
import com.biz.CZSZApplication;
import com.biz.R;
import com.danikula.videocache.CacheListener;
import com.danikula.videocache.HttpProxyCacheServer;
import com.shsunframework.app.BaseFragment;
import java.io.File;
public class MyVideoFragment extends BaseFragment {
public static final String TAG = MyVideoFragment.class.getSimpleName();
private String mRemoteVideoURL;
private String mCachedVideoURL;
private ImageView mCacheStatusImageView;
private VideoView mVideoView;
private SeekBar mSeekBar;
private final VideoProgressUpdater mUpdater = new VideoProgressUpdater();
CacheListener mCacheListener = new CacheListener() {
@Override
public void onCacheAvailable(File file, String url, int percentsAvailable) {
mSeekBar.setSecondaryProgress(percentsAvailable);
setCachedState(percentsAvailable == 100);
Log.d(TAG, String.format("onCacheAvailable. percents: %d, file: %s, mRemoteVideoURL: %s", percentsAvailable, file, url));
}
};
@SuppressLint("WrongViewCast")
@Override
public View initView(Bundle bundle, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = LayoutInflater.from(this.getContext()).inflate(R.layout.my_fragment_video, null);
mCacheStatusImageView = (ImageView) view.findViewById(R.id.cacheStatusImageView);
mSeekBar = (SeekBar) view.findViewById(R.id.seekBar);
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekVideo();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
;
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
;
}
});
mVideoView = (VideoView) view.findViewById(R.id.videoView);
return view;
}
@Override
public void initData(Bundle bundle) {
mRemoteVideoURL = "http://219.238.4.104/video07/2013/12/17/779163-102-067-2207_5.mp4";
mCachedVideoURL = this.getContext().getExternalCacheDir().getAbsolutePath();
checkCachedState();
startVideo();
}
private void checkCachedState() {
HttpProxyCacheServer proxy = CZSZApplication.getInstance().getProxyCacheServer();
boolean fullyCached = proxy.isCached(mRemoteVideoURL);
setCachedState(fullyCached);
if (fullyCached) {
mSeekBar.setSecondaryProgress(100);
}
}
private void startVideo() {
HttpProxyCacheServer proxy = CZSZApplication.getInstance().getProxyCacheServer();
proxy.registerCacheListener(mCacheListener, mRemoteVideoURL);
String proxyUrl = proxy.getProxyUrl(mRemoteVideoURL);
Log.d(TAG, "Use proxy mRemoteVideoURL " + proxyUrl + " instead of original mRemoteVideoURL " + mRemoteVideoURL);
mVideoView.setVideoPath(proxyUrl);
mVideoView.start();
}
private void setCachedState(boolean cached) {
final int statusIconId = cached ? R.drawable.ic_cloud_done : R.drawable.ic_cloud_download;
mCacheStatusImageView.setImageResource(statusIconId);
}
private void seekVideo() {
int videoPosition = mVideoView.getDuration() * mSeekBar.getProgress() / 100;
mVideoView.seekTo(videoPosition);
}
protected void onVisible() {
super.onVisible();
}
protected void onInvisible() {
Log.d(TAG, "onInvisible");
if (mVideoView != null && mUpdater != null) {
mVideoView.pause();
mUpdater.stop();
}
}
@Override
public void onResume() {
super.onResume();
mUpdater.start();
}
@Override
public void onPause() {
super.onPause();
mVideoView.pause();
mUpdater.stop();
}
@Override
public void onStop() {
super.onStop();
mVideoView.pause();
mUpdater.stop();
}
@Override
public void onDetach() {
super.onDetach();
mVideoView.pause();
mUpdater.stop();
}
@Override
public void onDestroy() {
super.onDestroy();
mVideoView.stopPlayback();
CZSZApplication.getInstance().getProxyCacheServer().unregisterCacheListener(mCacheListener);
}
private void updateVideoProgress() {
int videoProgress = mVideoView.getCurrentPosition() * 100 / mVideoView.getDuration();
mSeekBar.setProgress(videoProgress);
}
private final class VideoProgressUpdater extends Handler {
public void start() {
sendEmptyMessage(0);
}
public void stop() {
removeMessages(0);
}
@Override
public void handleMessage(Message msg) {
updateVideoProgress();
sendEmptyMessageDelayed(0, 500);
}
}
} |
package com.example.idk.myuber;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
public class PostBike2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_postbike_two);
Intent intent = getIntent();
String description =intent.getStringExtra("1");
String uri = getIntent().getStringExtra("0");
ImageView imgview =(ImageView)findViewById(R.id.rent_bike_image);
Uri imgUri=Uri.parse(uri);
imgview.setImageURI(imgUri);
TextView txtview =(TextView)findViewById(R.id.post_description_string);
txtview.setText(description);
Button postBike = (Button)findViewById(R.id.post_bike_post_button);
postBike.setOnClickListener((View.OnClickListener) this);
}
protected void onDestroy(){
super.onDestroy();
}
public void onClick(View v){
switch (v.getId()) {
case R.id.post_bike_post_button:
Httpget post = new Httpget();
JSONObject postobj = new JSONObject();
AsyncTask<String, Void, Void> task = post.new newBike();
task.execute("1");
break;
}
}
} |
package com.icaynia.dmxario;
import android.content.Context;
import android.util.Log;
import android.widget.Button;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ScenePackage
{
private Context context;
private HashMap<String, String> config;
private Scene[] scene = new Scene[56];
private ObjectFileManager mObj;
// region Constructors
public ScenePackage(Context _context)
{
context = _context;
config = new HashMap<String, String>();
mObj = new ObjectFileManager(context);
}
// endregion
// region Accessors
public void loadPackage(String PackageName)
{
mObj = new ObjectFileManager(context);
config = mObj.load("Scene/"+PackageName+"/config.scn");
if (config == null)
{
Log.e("ScenePackage", "Package not found!");
((MainActivity)context).makeToast(PackageName + " : Package not found!");
}
else
{
Log.e("ScenePackage", "Load Successfully.");
}
}
public void printAll() {
Iterator iterator = config.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
Log.e("ScenePackage", "key : " + entry.getKey() + " value : "
+ entry.getValue());
}
}
public void savePackage()
{
this.put("testValue", "testVal123123");
mObj.newFolder("Scene/"+getPackageName());
mObj.save(config, "Scene/"+getPackageName()+"/config.scn");
}
public String getPackageName()
{
String packageName = this.get("PackageName");
return packageName;
}
public void setPackageName(String _packageName)
{
this.put("PackageName", _packageName);
}
public void putScene(Scene scn)
{
String scnName = scn.getSceneName();
mObj.save(scn.getHashMap(), "Scene/"+getPackageName()+"/"+scnName+".scn");
}
public void mkScene(int id)
{
this.scene[id] = new Scene(context);
}
public void playScene(int id)
{
this.stopScene(id);
this.scene[id].play();
}
public void stopScene(int id)
{
if (this.scene[id].isRunning())
{
this.scene[id].stop();
}
}
public void loadScene(String packageName, String fileName, int id)
{
this.scene[id].loadScene(packageName, fileName);
}
// endregion
// region private function
private String get(String key)
{
return config.get(key);
}
private void put(String key, String value)
{
config.put(key, value);
}
} |
package uk.org.sappho.configuration;
import java.util.List;
public interface Configuration {
public String getProperty(String name) throws ConfigurationException;
public String getProperty(String name, String defaultValue);
public List<String> getPropertyList(String name) throws ConfigurationException;
public List<String> getPropertyList(String name, List<String> defaultValue);
public <T> Class<T> getPlugin(String name, String defaultPackage) throws ConfigurationException;
public Object getGroovyScriptObject(String name) throws ConfigurationException;
public void setProperty(String name, String value);
public void load(String filename) throws ConfigurationException;
public void takeSnapshot();
public void saveChanged(String filenameKey) throws ConfigurationException;
} |
package urchin.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.AlternateTypeRule;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static springfox.documentation.schema.AlternateTypeRules.newRule;
@EnableSwagger2
@Configuration
public class SwaggerConfiguration {
private static final String SCAN_PACKAGE = "urchin.controller";
private final Logger log = LoggerFactory.getLogger(SwaggerConfiguration.class);
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex("(.*)\\/api\\/(.*)"))
.build()
.alternateTypeRules(getAlternateTypeRules());
}
private AlternateTypeRule[] getAlternateTypeRules() {
log.info("applying alternateTypeRules for swagger");
log.debug("discovering rest controllers in {} package", SCAN_PACKAGE);
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AnnotationTypeFilter(RestController.class));
List<String> classNames = provider.findCandidateComponents(SCAN_PACKAGE).stream()
.map(BeanDefinition::getBeanClassName)
.collect(Collectors.toList());
log.debug("discovering parameter classes used in rest controllers");
List<Class> classes = getClasses(classNames).stream()
.map(this::getParameterClasses)
.flatMap(List::stream)
.distinct()
.collect(Collectors.toList());
log.debug("discovering immutable classes for parameter classes");
List<Class> immutableClasses = getClasses(classes.stream()
.map(this::getImmutableClassName)
.collect(Collectors.toList()));
log.debug("creating alternateTypeRules from discovered parameter classes and corresponding immutable classes");
List<AlternateTypeRule> alternateTypeRules = new ArrayList<>();
classes.forEach(c -> immutableClasses.stream()
.filter(ic -> ic.getName().equals(getImmutableClassName(c)))
.findFirst()
.ifPresent(ic -> alternateTypeRules.add(newRule(c, ic)))
);
return alternateTypeRules.toArray(new AlternateTypeRule[0]);
}
private List<Class> getClasses(List<String> classNames) {
List<Class> classes = new ArrayList<>();
classNames.forEach(className -> {
try {
classes.add(Class.forName(className));
} catch (ClassNotFoundException ignore) {
}
});
return classes;
}
private List<Class> getParameterClasses(Class clazz) {
List<Class<?>> parameterTypes = Arrays.stream(clazz.getDeclaredMethods())
.map(Method::getParameterTypes)
.flatMap(Arrays::stream)
.collect(Collectors.toList());
return getClasses(parameterTypes.stream()
.map(Class::getName)
.collect(Collectors.toList()));
}
private String getImmutableClassName(Class c) {
String className = c.getName();
int i = className.lastIndexOf(".");
return className.substring(0, i) + ".Immutable" + className.substring(i + 1, className.length());
}
} |
package com.samourai.wallet;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.Toast;
//import android.util.Log;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.crypto.MnemonicException;
import com.dm.zbar.android.scanner.ZBarConstants;
import com.dm.zbar.android.scanner.ZBarScannerActivity;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.android.Contents;
import com.google.zxing.client.android.encode.QRCodeEncoder;
import com.samourai.wallet.JSONRPC.TrustedNodeUtil;
import com.samourai.wallet.access.AccessFactory;
import com.samourai.wallet.api.APIFactory;
import com.samourai.wallet.bip47.BIP47Activity;
import com.samourai.wallet.bip47.BIP47Meta;
import com.samourai.wallet.bip47.BIP47Util;
import com.samourai.wallet.bip47.rpc.PaymentAddress;
import com.samourai.wallet.bip47.rpc.PaymentCode;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.payload.PayloadUtil;
import com.samourai.wallet.ricochet.RicochetActivity;
import com.samourai.wallet.ricochet.RicochetMeta;
import com.samourai.wallet.segwit.BIP49Util;
import com.samourai.wallet.send.BlockedUTXO;
import com.samourai.wallet.send.FeeUtil;
import com.samourai.wallet.send.MyTransactionOutPoint;
import com.samourai.wallet.send.RBFSpend;
import com.samourai.wallet.send.SendFactory;
import com.samourai.wallet.send.SuggestedFee;
import com.samourai.wallet.send.UTXO;
import com.samourai.wallet.send.UTXOFactory;
import com.samourai.wallet.util.AddressFactory;
import com.samourai.wallet.util.AppUtil;
import com.samourai.wallet.util.CharSequenceX;
import com.samourai.wallet.util.ExchangeRateFactory;
import com.samourai.wallet.util.FormatsUtil;
import com.samourai.wallet.util.MonetaryUtil;
import com.samourai.wallet.util.PrefsUtil;
import com.samourai.wallet.send.PushTx;
import com.samourai.wallet.send.RBFUtil;
import com.samourai.wallet.util.SendAddressUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.text.DecimalFormatSymbols;
import java.util.Vector;
import com.yanzhenjie.zbar.Symbol;
import org.bitcoinj.core.Coin;
import org.bitcoinj.script.Script;
import org.json.JSONException;
import org.json.JSONObject;
import org.bouncycastle.util.encoders.DecoderException;
import org.bouncycastle.util.encoders.Hex;
import static java.lang.System.currentTimeMillis;
public class SendActivity extends Activity {
private final static int SCAN_QR = 2012;
private final static int RICOCHET = 2013;
private TextView tvMaxPrompt = null;
private TextView tvMax = null;
private long balance = 0L;
private EditText edAddress = null;
private String strDestinationBTCAddress = null;
private TextWatcher textWatcherAddress = null;
private EditText edAmountBTC = null;
private EditText edAmountFiat = null;
private TextWatcher textWatcherBTC = null;
private TextWatcher textWatcherFiat = null;
private String defaultSeparator = null;
private Button btLowFee = null;
private Button btAutoFee = null;
private Button btPriorityFee = null;
private Button btCustomFee = null;
private TextView tvFeePrompt = null;
private final static int FEE_LOW = 0;
private final static int FEE_NORMAL = 1;
private final static int FEE_PRIORITY = 2;
private final static int FEE_CUSTOM = 3;
private int FEE_TYPE = FEE_LOW;
public final static int SPEND_SIMPLE = 0;
public final static int SPEND_BIP126 = 1;
public final static int SPEND_RICOCHET = 2;
private int SPEND_TYPE = SPEND_BIP126;
// private CheckBox cbSpendType = null;
private Switch swRicochet = null;
private String strFiat = null;
private double btc_fx = 286.0;
private TextView tvFiatSymbol = null;
private Button btSend = null;
private int selectedAccount = 0;
private String strPCode = null;
private boolean bViaMenu = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
SendActivity.this.getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
if(SamouraiWallet.getInstance().getShowTotalBalance()) {
if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 2) {
selectedAccount = 1;
}
else {
selectedAccount = 0;
}
}
else {
selectedAccount = 0;
}
tvMaxPrompt = (TextView)findViewById(R.id.max_prompt);
tvMax = (TextView)findViewById(R.id.max);
try {
balance = APIFactory.getInstance(SendActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(selectedAccount).xpubstr());
}
catch(IOException ioe) {
balance = 0L;
}
catch(MnemonicException.MnemonicLengthException mle) {
balance = 0L;
}
catch(java.lang.NullPointerException npe) {
balance = 0L;
}
final String strAmount;
NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setMaximumFractionDigits(8);
nf.setMinimumFractionDigits(1);
nf.setMinimumIntegerDigits(1);
strAmount = nf.format(balance / 1e8);
tvMax.setText(strAmount + " " + getDisplayUnits());
tvMaxPrompt.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
edAmountBTC.setText(strAmount);
return false;
}
});
tvMax.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
edAmountBTC.setText(strAmount);
return false;
}
});
DecimalFormat format = (DecimalFormat)DecimalFormat.getInstance(Locale.US);
DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
defaultSeparator = Character.toString(symbols.getDecimalSeparator());
strFiat = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD");
btc_fx = ExchangeRateFactory.getInstance(SendActivity.this).getAvgPrice(strFiat);
tvFiatSymbol = (TextView)findViewById(R.id.fiatSymbol);
tvFiatSymbol.setText(getDisplayUnits() + "-" + strFiat);
edAddress = (EditText)findViewById(R.id.destination);
textWatcherAddress = new TextWatcher() {
public void afterTextChanged(Editable s) {
validateSpend();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
;
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
;
}
};
edAddress.addTextChangedListener(textWatcherAddress);
edAddress.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//final int DRAWABLE_LEFT = 0;
//final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
//final int DRAWABLE_BOTTOM = 3;
if(event.getAction() == MotionEvent.ACTION_UP && event.getRawX() >= (edAddress.getRight() - edAddress.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
final List<String> entries = new ArrayList<String>();
entries.addAll(BIP47Meta.getInstance().getSortedByLabels(false));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SendActivity.this, android.R.layout.select_dialog_singlechoice);
for(int i = 0; i < entries.size(); i++) {
arrayAdapter.add(BIP47Meta.getInstance().getDisplayLabel(entries.get(i)));
}
AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this);
dlg.setIcon(R.drawable.ic_launcher);
dlg.setTitle(R.string.app_name);
dlg.setAdapter(arrayAdapter,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Toast.makeText(SendActivity.this, BIP47Meta.getInstance().getDisplayLabel(entries.get(which)), Toast.LENGTH_SHORT).show();
// Toast.makeText(SendActivity.this, entries.get(which), Toast.LENGTH_SHORT).show();
processPCode(entries.get(which), null);
}
});
dlg.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dlg.show();
return true;
}
return false;
}
});
edAmountBTC = (EditText)findViewById(R.id.amountBTC);
edAmountFiat = (EditText)findViewById(R.id.amountFiat);
textWatcherBTC = new TextWatcher() {
public void afterTextChanged(Editable s) {
edAmountBTC.removeTextChangedListener(this);
edAmountFiat.removeTextChangedListener(textWatcherFiat);
int max_len = 8;
NumberFormat btcFormat = NumberFormat.getInstance(Locale.US);
btcFormat.setMaximumFractionDigits(max_len + 1);
btcFormat.setMinimumFractionDigits(0);
double d = 0.0;
try {
d = NumberFormat.getInstance(Locale.US).parse(s.toString()).doubleValue();
String s1 = btcFormat.format(d);
if (s1.indexOf(defaultSeparator) != -1) {
String dec = s1.substring(s1.indexOf(defaultSeparator));
if (dec.length() > 0) {
dec = dec.substring(1);
if (dec.length() > max_len) {
edAmountBTC.setText(s1.substring(0, s1.length() - 1));
edAmountBTC.setSelection(edAmountBTC.getText().length());
s = edAmountBTC.getEditableText();
}
}
}
} catch (NumberFormatException nfe) {
;
} catch (ParseException pe) {
;
}
if(d > 21000000.0) {
edAmountFiat.setText("0.00");
edAmountFiat.setSelection(edAmountFiat.getText().length());
edAmountBTC.setText("0");
edAmountBTC.setSelection(edAmountBTC.getText().length());
Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show();
}
else {
edAmountFiat.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(d * btc_fx));
edAmountFiat.setSelection(edAmountFiat.getText().length());
}
edAmountFiat.addTextChangedListener(textWatcherFiat);
edAmountBTC.addTextChangedListener(this);
validateSpend();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
;
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
;
}
};
edAmountBTC.addTextChangedListener(textWatcherBTC);
textWatcherFiat = new TextWatcher() {
public void afterTextChanged(Editable s) {
edAmountFiat.removeTextChangedListener(this);
edAmountBTC.removeTextChangedListener(textWatcherBTC);
int max_len = 2;
NumberFormat fiatFormat = NumberFormat.getInstance(Locale.US);
fiatFormat.setMaximumFractionDigits(max_len + 1);
fiatFormat.setMinimumFractionDigits(0);
double d = 0.0;
try {
d = NumberFormat.getInstance(Locale.US).parse(s.toString()).doubleValue();
String s1 = fiatFormat.format(d);
if(s1.indexOf(defaultSeparator) != -1) {
String dec = s1.substring(s1.indexOf(defaultSeparator));
if(dec.length() > 0) {
dec = dec.substring(1);
if(dec.length() > max_len) {
edAmountFiat.setText(s1.substring(0, s1.length() - 1));
edAmountFiat.setSelection(edAmountFiat.getText().length());
}
}
}
}
catch(NumberFormatException nfe) {
;
}
catch(ParseException pe) {
;
}
if((d / btc_fx) > 21000000.0) {
edAmountFiat.setText("0.00");
edAmountFiat.setSelection(edAmountFiat.getText().length());
edAmountBTC.setText("0");
edAmountBTC.setSelection(edAmountBTC.getText().length());
Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show();
}
else {
edAmountBTC.setText(MonetaryUtil.getInstance().getBTCFormat().format(d / btc_fx));
edAmountBTC.setSelection(edAmountBTC.getText().length());
}
edAmountBTC.addTextChangedListener(textWatcherBTC);
edAmountFiat.addTextChangedListener(this);
validateSpend();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
;
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
;
}
};
edAmountFiat.addTextChangedListener(textWatcherFiat);
SPEND_TYPE = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_BIP126, true) ? SPEND_BIP126 : SPEND_SIMPLE;
if(SPEND_TYPE > SPEND_BIP126) {
SPEND_TYPE = SPEND_BIP126;
PrefsUtil.getInstance(SendActivity.this).setValue(PrefsUtil.SPEND_TYPE, SPEND_BIP126);
}
swRicochet = (Switch)findViewById(R.id.ricochet);
swRicochet.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
SPEND_TYPE = SPEND_RICOCHET;
}
else {
SPEND_TYPE = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.SPEND_TYPE, SPEND_BIP126);
}
}
});
btLowFee = (Button)findViewById(R.id.low_fee);
btAutoFee = (Button)findViewById(R.id.auto_fee);
btPriorityFee = (Button)findViewById(R.id.priority_fee);
btCustomFee = (Button)findViewById(R.id.custom_fee);
tvFeePrompt = (TextView)findViewById(R.id.current_fee_prompt);
FEE_TYPE = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_NORMAL);
long lo = FeeUtil.getInstance().getLowFee().getDefaultPerKB().longValue() / 1000L;
long mi = FeeUtil.getInstance().getNormalFee().getDefaultPerKB().longValue() / 1000L;
long hi = FeeUtil.getInstance().getHighFee().getDefaultPerKB().longValue() / 1000L;
if(lo == mi && mi == hi) {
lo = (long) ((double) mi * 0.85);
hi = (long) ((double) mi * 1.15);
SuggestedFee lo_sf = new SuggestedFee();
lo_sf.setDefaultPerKB(BigInteger.valueOf(lo * 1000L));
FeeUtil.getInstance().setLowFee(lo_sf);
SuggestedFee hi_sf = new SuggestedFee();
hi_sf.setDefaultPerKB(BigInteger.valueOf(hi * 1000L));
FeeUtil.getInstance().setHighFee(hi_sf);
}
else if(lo == mi || mi == hi) {
mi = (lo + hi) / 2L;
SuggestedFee mi_sf = new SuggestedFee();
mi_sf.setDefaultPerKB(BigInteger.valueOf(mi * 1000L));
FeeUtil.getInstance().setNormalFee(mi_sf);
}
else {
;
}
switch(FEE_TYPE) {
case FEE_LOW:
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee());
sanitizeFee();
btLowFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.blue));
btAutoFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btPriorityFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btCustomFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btLowFee.setTypeface(null, Typeface.BOLD);
btAutoFee.setTypeface(null, Typeface.NORMAL);
btPriorityFee.setTypeface(null, Typeface.NORMAL);
btCustomFee.setTypeface(null, Typeface.NORMAL);
tvFeePrompt.setText(getText(R.string.fee_low_priority) + " " + getText(R.string.blocks_to_cf));
break;
case FEE_PRIORITY:
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee());
sanitizeFee();
btLowFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btAutoFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btPriorityFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.blue));
btCustomFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btLowFee.setTypeface(null, Typeface.NORMAL);
btAutoFee.setTypeface(null, Typeface.NORMAL);
btPriorityFee.setTypeface(null, Typeface.BOLD);
btCustomFee.setTypeface(null, Typeface.NORMAL);
tvFeePrompt.setText(getText(R.string.fee_high_priority) + " " + getText(R.string.blocks_to_cf));
break;
default:
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee());
sanitizeFee();
btLowFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btAutoFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.blue));
btPriorityFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btCustomFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btLowFee.setTypeface(null, Typeface.NORMAL);
btAutoFee.setTypeface(null, Typeface.BOLD);
btPriorityFee.setTypeface(null, Typeface.NORMAL);
btCustomFee.setTypeface(null, Typeface.NORMAL);
tvFeePrompt.setText(getText(R.string.fee_mid_priority) + " " + getText(R.string.blocks_to_cf));
break;
}
btLowFee.setText((FeeUtil.getInstance().getLowFee().getDefaultPerKB().longValue() / 1000L) + "\n" + getString(R.string.sat_b));
btPriorityFee.setText((FeeUtil.getInstance().getHighFee().getDefaultPerKB().longValue() / 1000L) + "\n" + getString(R.string.sat_b));
btAutoFee.setText((FeeUtil.getInstance().getNormalFee().getDefaultPerKB().longValue() / 1000L) + "\n" + getString(R.string.sat_b));
btLowFee.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee());
PrefsUtil.getInstance(SendActivity.this).setValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_LOW);
btLowFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.blue));
btAutoFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btPriorityFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btCustomFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btLowFee.setTypeface(null, Typeface.BOLD);
btAutoFee.setTypeface(null, Typeface.NORMAL);
btPriorityFee.setTypeface(null, Typeface.NORMAL);
btCustomFee.setTypeface(null, Typeface.NORMAL);
btCustomFee.setText(R.string.custom_fee);
tvFeePrompt.setText(getText(R.string.fee_low_priority) + " " + getText(R.string.blocks_to_cf));
}
});
btAutoFee.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee());
PrefsUtil.getInstance(SendActivity.this).setValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_NORMAL);
btLowFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btAutoFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.blue));
btPriorityFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btCustomFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btLowFee.setTypeface(null, Typeface.NORMAL);
btAutoFee.setTypeface(null, Typeface.BOLD);
btPriorityFee.setTypeface(null, Typeface.NORMAL);
btCustomFee.setTypeface(null, Typeface.NORMAL);
btCustomFee.setText(R.string.custom_fee);
tvFeePrompt.setText(getText(R.string.fee_mid_priority) + " " + getText(R.string.blocks_to_cf));
}
});
btPriorityFee.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee());
PrefsUtil.getInstance(SendActivity.this).setValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_PRIORITY);
btLowFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btAutoFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btPriorityFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.blue));
btCustomFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btLowFee.setTypeface(null, Typeface.NORMAL);
btAutoFee.setTypeface(null, Typeface.NORMAL);
btPriorityFee.setTypeface(null, Typeface.BOLD);
btCustomFee.setTypeface(null, Typeface.NORMAL);
btCustomFee.setText(R.string.custom_fee);
tvFeePrompt.setText(getText(R.string.fee_high_priority) + " " + getText(R.string.blocks_to_cf));
}
});
btCustomFee.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doCustomFee();
}
});
btSend = (Button)findViewById(R.id.send);
btSend.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btSend.setClickable(false);
btSend.setActivated(false);
double btc_amount = 0.0;
try {
btc_amount = NumberFormat.getInstance(Locale.US).parse(edAmountBTC.getText().toString().trim()).doubleValue();
// Log.i("SendFragment", "amount entered:" + btc_amount);
} catch (NumberFormatException nfe) {
btc_amount = 0.0;
} catch (ParseException pe) {
btc_amount = 0.0;
}
double dAmount = btc_amount;
long amount = (long)(Math.round(dAmount * 1e8));;
// Log.i("SendActivity", "amount:" + amount);
final String address = strDestinationBTCAddress == null ? edAddress.getText().toString() : strDestinationBTCAddress;
final int accountIdx = selectedAccount;
final boolean isSegwitChange = (FormatsUtil.getInstance().isValidBech32(address) || Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) || PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true) == false;
final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>();
receivers.put(address, BigInteger.valueOf(amount));
// store current change index to restore value in case of sending fail
int change_index = 0;
if(isSegwitChange) {
change_index = BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx();
}
else {
try {
change_index = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx();
// Log.d("SendActivity", "storing change index:" + change_index);
}
catch(IOException ioe) {
;
}
catch(MnemonicException.MnemonicLengthException mle) {
;
}
}
// get all UTXO
List<UTXO> utxos = null;
// if possible, get UTXO by input 'type': p2pkh, p2sh-p2wpkh or p2wpkh, else get all UTXO
long neededAmount = 0L;
if(FormatsUtil.getInstance().isValidBech32(address)) {
neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(0, 0, UTXOFactory.getInstance().getCountP2WPKH(), 4).longValue();
// Log.d("SendActivity", "segwit:" + neededAmount);
}
else if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) {
neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(0, UTXOFactory.getInstance().getCountP2SH_P2WPKH(), 0, 4).longValue();
// Log.d("SendActivity", "segwit:" + neededAmount);
}
else {
neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(UTXOFactory.getInstance().getCountP2PKH(), 0, 4).longValue();
// Log.d("SendActivity", "p2pkh:" + neededAmount);
}
neededAmount += amount;
neededAmount += SamouraiWallet.bDust.longValue();
if(FormatsUtil.getInstance().isValidBech32(address) && (UTXOFactory.getInstance().getP2WPKH().size() > 0 && UTXOFactory.getInstance().getTotalP2WPKH() > neededAmount)) {
utxos = new ArrayList<UTXO>(UTXOFactory.getInstance().getP2WPKH().values());
// Log.d("SendActivity", "segwit utxos:" + utxos.size());
}
else if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress() && (UTXOFactory.getInstance().getP2SH_P2WPKH().size() > 0 && UTXOFactory.getInstance().getTotalP2SH_P2WPKH() > neededAmount)) {
utxos = new ArrayList<UTXO>(UTXOFactory.getInstance().getP2SH_P2WPKH().values());
// Log.d("SendActivity", "segwit utxos:" + utxos.size());
}
else if((UTXOFactory.getInstance().getP2PKH().size() > 0) && (UTXOFactory.getInstance().getTotalP2PKH() > neededAmount)) {
utxos = new ArrayList<UTXO>(UTXOFactory.getInstance().getP2PKH().values());
// Log.d("SendActivity", "p2pkh utxos:" + utxos.size());
}
else {
utxos = APIFactory.getInstance(SendActivity.this).getUtxos(true);
// Log.d("SendActivity", "all filtered utxos:" + utxos.size());
}
final List<UTXO> selectedUTXO = new ArrayList<UTXO>();
long totalValueSelected = 0L;
long change = 0L;
BigInteger fee = null;
// Log.d("SendActivity", "amount:" + amount);
// Log.d("SendActivity", "balance:" + balance);
// insufficient funds
if(amount > balance) {
Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show();
}
// entire balance (can only be simple spend)
else if(amount == balance) {
// make sure we are using simple spend
SPEND_TYPE = SPEND_SIMPLE;
// Log.d("SendActivity", "amount == balance");
// take all utxos, deduct fee
selectedUTXO.addAll(utxos);
for(UTXO u : selectedUTXO) {
totalValueSelected += u.getValue();
}
// Log.d("SendActivity", "balance:" + balance);
// Log.d("SendActivity", "total value selected:" + totalValueSelected);
}
else {
;
}
org.apache.commons.lang3.tuple.Pair<ArrayList<MyTransactionOutPoint>, ArrayList<TransactionOutput>> pair = null;
if(SPEND_TYPE == SPEND_RICOCHET) {
boolean samouraiFeeViaBIP47 = false;
if(BIP47Meta.getInstance().getOutgoingStatus(BIP47Meta.strSamouraiDonationPCode) == BIP47Meta.STATUS_SENT_CFM) {
samouraiFeeViaBIP47 = true;
}
final JSONObject jObj = RicochetMeta.getInstance(SendActivity.this).script(amount, FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue(), address, 4, strPCode, samouraiFeeViaBIP47);
if(jObj != null) {
try {
long totalAmount = jObj.getLong("total_spend");
if(totalAmount > balance) {
Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show();
return;
}
String msg = getText(R.string.ricochet_spend1) + " " + address + " " + getText(R.string.ricochet_spend2) + " " + Coin.valueOf(totalAmount).toPlainString() + " " + getText(R.string.ricochet_spend3);
AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this)
.setTitle(R.string.app_name)
.setMessage(msg)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
RicochetMeta.getInstance(SendActivity.this).add(jObj);
dialog.dismiss();
Intent intent = new Intent(SendActivity.this, RicochetActivity.class);
startActivityForResult(intent, RICOCHET);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if(!isFinishing()) {
dlg.show();
}
return;
}
catch(JSONException je) {
return;
}
}
return;
}
// if BIP126 try both hetero/alt, if fails change type to SPEND_SIMPLE
else if(SPEND_TYPE == SPEND_BIP126) {
List<UTXO> _utxos = utxos;
//Collections.shuffle(_utxos);
// sort in descending order by value
Collections.sort(_utxos, new UTXO.UTXOComparator());
// hetero
pair = SendFactory.getInstance(SendActivity.this).heterogeneous(_utxos, BigInteger.valueOf(amount), address);
if(pair == null) {
//Collections.sort(_utxos, new UTXO.UTXOComparator());
// alt
pair = SendFactory.getInstance(SendActivity.this).altHeterogeneous(_utxos, BigInteger.valueOf(amount), address);
}
if(pair == null) {
// can't do BIP126, revert to SPEND_SIMPLE
SPEND_TYPE = SPEND_SIMPLE;
}
}
else {
;
}
// simple spend (less than balance)
if(SPEND_TYPE == SPEND_SIMPLE) {
List<UTXO> _utxos = utxos;
// sort in ascending order by value
Collections.sort(_utxos, new UTXO.UTXOComparator());
Collections.reverse(_utxos);
// get smallest 1 UTXO > than spend + fee + dust
for(UTXO u : _utxos) {
Pair<Integer,Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(u.getOutpoints());
if(u.getValue() >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getRight(), 2).longValue())) {
selectedUTXO.add(u);
totalValueSelected += u.getValue();
// Log.d("SendActivity", "spend type:" + SPEND_TYPE);
// Log.d("SendActivity", "single output");
// Log.d("SendActivity", "amount:" + amount);
// Log.d("SendActivity", "value selected:" + u.getValue());
// Log.d("SendActivity", "total value selected:" + totalValueSelected);
// Log.d("SendActivity", "nb inputs:" + u.getOutpoints().size());
break;
}
}
if(selectedUTXO.size() == 0) {
// sort in descending order by value
Collections.sort(_utxos, new UTXO.UTXOComparator());
int selected = 0;
int p2pkh = 0;
int p2sh_p2wpkh = 0;
int p2wpkh = 0;
// get largest UTXOs > than spend + fee + dust
for(UTXO u : _utxos) {
selectedUTXO.add(u);
totalValueSelected += u.getValue();
selected += u.getOutpoints().size();
// Log.d("SendActivity", "value selected:" + u.getValue());
// Log.d("SendActivity", "total value selected/threshold:" + totalValueSelected + "/" + (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(selected, 2).longValue()));
Triple<Integer,Integer,Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector<MyTransactionOutPoint>(u.getOutpoints()));
p2pkh += outpointTypes.getLeft();
p2sh_p2wpkh += outpointTypes.getMiddle();
p2wpkh += outpointTypes.getRight();
if(totalValueSelected >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2sh_p2wpkh, p2wpkh, 2).longValue())) {
// Log.d("SendActivity", "spend type:" + SPEND_TYPE);
// Log.d("SendActivity", "multiple outputs");
// Log.d("SendActivity", "amount:" + amount);
// Log.d("SendActivity", "total value selected:" + totalValueSelected);
// Log.d("SendActivity", "nb inputs:" + selected);
break;
}
}
}
}
else if(pair != null) {
selectedUTXO.clear();
receivers.clear();
long inputAmount = 0L;
long outputAmount = 0L;
for(MyTransactionOutPoint outpoint : pair.getLeft()) {
UTXO u = new UTXO();
List<MyTransactionOutPoint> outs = new ArrayList<MyTransactionOutPoint>();
outs.add(outpoint);
u.setOutpoints(outs);
totalValueSelected += u.getValue();
selectedUTXO.add(u);
inputAmount += u.getValue();
}
for(TransactionOutput output : pair.getRight()) {
try {
Script script = new Script(output.getScriptBytes());
receivers.put(script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), BigInteger.valueOf(output.getValue().longValue()));
outputAmount += output.getValue().longValue();
}
catch(Exception e) {
Toast.makeText(SendActivity.this, R.string.error_bip126_output, Toast.LENGTH_SHORT).show();
return;
}
}
change = outputAmount - amount;
fee = BigInteger.valueOf(inputAmount - outputAmount);
}
else {
Toast.makeText(SendActivity.this, R.string.cannot_select_utxo, Toast.LENGTH_SHORT).show();
return;
}
// do spend here
if(selectedUTXO.size() > 0) {
// estimate fee for simple spend, already done if BIP126
if(SPEND_TYPE == SPEND_SIMPLE) {
List<MyTransactionOutPoint> outpoints = new ArrayList<MyTransactionOutPoint>();
for(UTXO utxo : selectedUTXO) {
outpoints.addAll(utxo.getOutpoints());
}
Triple<Integer,Integer,Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(outpoints));
fee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 2);
}
// Log.d("SendActivity", "spend type:" + SPEND_TYPE);
// Log.d("SendActivity", "amount:" + amount);
// Log.d("SendActivity", "total value selected:" + totalValueSelected);
// Log.d("SendActivity", "fee:" + fee.longValue());
// Log.d("SendActivity", "nb inputs:" + selectedUTXO.size());
change = totalValueSelected - (amount + fee.longValue());
// Log.d("SendActivity", "change:" + change);
boolean changeIsDust = false;
if(change < SamouraiWallet.bDust.longValue() && SPEND_TYPE == SPEND_SIMPLE) {
change = 0L;
fee = fee.add(BigInteger.valueOf(change));
amount = totalValueSelected - fee.longValue();
// Log.d("SendActivity", "fee:" + fee.longValue());
// Log.d("SendActivity", "change:" + change);
// Log.d("SendActivity", "amount:" + amount);
receivers.put(address, BigInteger.valueOf(amount));
changeIsDust = true;
}
final long _change = change;
final BigInteger _fee = fee;
final int _change_index = change_index;
String dest = null;
if(strPCode != null && strPCode.length() > 0) {
dest = BIP47Meta.getInstance().getDisplayLabel(strPCode);
}
else {
dest = address;
}
final String strPrivacyWarning;
if(SendAddressUtil.getInstance().get(address) == 1) {
strPrivacyWarning = getString(R.string.send_privacy_warning) + "\n\n";
}
else {
strPrivacyWarning = "";
}
String strChangeIsDust = null;
if(changeIsDust) {
strChangeIsDust = getString(R.string.change_is_dust) + "\n\n";
}
else {
strChangeIsDust = "";
}
String message = strChangeIsDust + strPrivacyWarning + "Send " + Coin.valueOf(amount).toPlainString() + " to " + dest + " (fee:" + Coin.valueOf(_fee.longValue()).toPlainString() + ")?\n";
final long _amount = amount;
AlertDialog.Builder builder = new AlertDialog.Builder(SendActivity.this);
builder.setTitle(R.string.app_name);
builder.setMessage(message);
final CheckBox cbShowAgain;
if(strPrivacyWarning.length() > 0) {
cbShowAgain = new CheckBox(SendActivity.this);
cbShowAgain.setText(R.string.do_not_repeat_sent_to);
cbShowAgain.setChecked(false);
builder.setView(cbShowAgain);
}
else {
cbShowAgain = null;
}
builder.setCancelable(false);
builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
final ProgressDialog progress = new ProgressDialog(SendActivity.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getString(R.string.please_wait_sending));
progress.show();
final List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>();
for(UTXO u : selectedUTXO) {
outPoints.addAll(u.getOutpoints());
}
// add change
if(_change > 0L) {
if(SPEND_TYPE == SPEND_SIMPLE) {
if(isSegwitChange) {
String change_address = BIP49Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getAddressAsString();
receivers.put(change_address, BigInteger.valueOf(_change));
}
else {
try {
String change_address = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddressAt(HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx()).getAddressString();
receivers.put(change_address, BigInteger.valueOf(_change));
}
catch(IOException ioe) {
Toast.makeText(SendActivity.this, R.string.error_change_output, Toast.LENGTH_SHORT).show();
return;
}
catch(MnemonicException.MnemonicLengthException mle) {
Toast.makeText(SendActivity.this, R.string.error_change_output, Toast.LENGTH_SHORT).show();
return;
}
}
}
else if (SPEND_TYPE == SPEND_BIP126) {
// do nothing, change addresses included
}
else {
;
}
}
// make tx
Transaction tx = SendFactory.getInstance(SendActivity.this).makeTransaction(0, outPoints, receivers);
final RBFSpend rbf;
if(PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.RBF_OPT_IN, false) == true) {
rbf = new RBFSpend();
for(TransactionInput input : tx.getInputs()) {
boolean _isBIP49 = false;
String _addr = null;
Address _address = input.getConnectedOutput().getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams());
if(_address != null) {
_addr = _address.toString();
}
if(_addr == null) {
_addr = input.getConnectedOutput().getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
_isBIP49 = true;
}
String path = APIFactory.getInstance(SendActivity.this).getUnspentPaths().get(_addr);
if(path != null) {
if(_isBIP49) {
rbf.addKey(input.getOutpoint().toString(), path + "/49");
}
else {
rbf.addKey(input.getOutpoint().toString(), path);
}
}
else {
String pcode = BIP47Meta.getInstance().getPCode4Addr(_addr);
int idx = BIP47Meta.getInstance().getIdx4Addr(_addr);
rbf.addKey(input.getOutpoint().toString(), pcode + "/" + idx);
}
}
}
else {
rbf = null;
}
if(tx != null) {
tx = SendFactory.getInstance(SendActivity.this).signTransaction(tx);
final Transaction _tx = tx;
final String hexTx = new String(Hex.encode(tx.bitcoinSerialize()));
// Log.d("SendActivity", hexTx);
final String strTxHash = tx.getHashAsString();
if(PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BROADCAST_TX, true) == false) {
if(progress != null && progress.isShowing()) {
progress.dismiss();
}
doShowTx(hexTx, strTxHash);
return;
}
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
boolean isOK = false;
String response = null;
try {
if(PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true) {
if(TrustedNodeUtil.getInstance().isSet()) {
response = PushTx.getInstance(SendActivity.this).trustedNode(hexTx);
JSONObject jsonObject = new org.json.JSONObject(response);
if(jsonObject.has("result")) {
if(jsonObject.getString("result").matches("^[A-Za-z0-9]{64}$")) {
isOK = true;
}
else {
Toast.makeText(SendActivity.this, R.string.trusted_node_tx_error, Toast.LENGTH_SHORT).show();
}
}
}
else {
Toast.makeText(SendActivity.this, R.string.trusted_node_not_valid, Toast.LENGTH_SHORT).show();
}
}
else {
response = PushTx.getInstance(SendActivity.this).samourai(hexTx);
if(response != null) {
JSONObject jsonObject = new org.json.JSONObject(response);
if(jsonObject.has("status")) {
if(jsonObject.getString("status").equals("ok")) {
isOK = true;
}
}
}
else {
Toast.makeText(SendActivity.this, R.string.pushtx_returns_null, Toast.LENGTH_SHORT).show();
}
}
if(isOK) {
if(PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == false) {
Toast.makeText(SendActivity.this, R.string.tx_sent, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(SendActivity.this, R.string.trusted_node_tx_sent, Toast.LENGTH_SHORT).show();
}
if(_change > 0L && SPEND_TYPE == SPEND_SIMPLE) {
if(isSegwitChange) {
BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().incAddrIdx();
}
else {
try {
HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().incAddrIdx();
}
catch(IOException ioe) {
;
}
catch(MnemonicException.MnemonicLengthException mle) {
;
}
}
}
if(PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.RBF_OPT_IN, false) == true) {
for(TransactionOutput out : _tx.getOutputs()) {
try {
if(!isSegwitChange && !address.equals(out.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString())) {
rbf.addChangeAddr(out.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
}
else if(isSegwitChange && !address.equals(out.getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString())) {
rbf.addChangeAddr(out.getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
}
else {
;
}
}
catch(NullPointerException npe) {
; // test for bech32, skip for now as it's not a change address
}
}
rbf.setHash(strTxHash);
rbf.setSerializedTx(hexTx);
RBFUtil.getInstance().add(rbf);
}
// increment counter if BIP47 spend
if(strPCode != null && strPCode.length() > 0) {
BIP47Meta.getInstance().getPCode4AddrLookup().put(address, strPCode);
BIP47Meta.getInstance().inc(strPCode);
SimpleDateFormat sd = new SimpleDateFormat("dd MMM");
String strTS = sd.format(currentTimeMillis());
String event = strTS + " " + SendActivity.this.getString(R.string.sent) + " " + MonetaryUtil.getInstance().getBTCFormat().format((double) _amount / 1e8) + " BTC";
BIP47Meta.getInstance().setLatestEvent(strPCode, event);
strPCode = null;
}
if(strPrivacyWarning.length() > 0 && cbShowAgain != null) {
SendAddressUtil.getInstance().add(address, cbShowAgain.isChecked() ? false : true);
}
else if(SendAddressUtil.getInstance().get(address) == 0) {
SendAddressUtil.getInstance().add(address, false);
}
else {
SendAddressUtil.getInstance().add(address, true);
}
if(_change == 0L) {
Intent intent = new Intent("com.samourai.wallet.BalanceFragment.REFRESH");
intent.putExtra("notifTx", false);
intent.putExtra("fetch", true);
LocalBroadcastManager.getInstance(SendActivity.this).sendBroadcast(intent);
}
View view = SendActivity.this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)SendActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
if(bViaMenu) {
SendActivity.this.finish();
}
else {
Intent _intent = new Intent(SendActivity.this, BalanceActivity.class);
_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(_intent);
}
}
else {
Toast.makeText(SendActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show();
// reset change index upon tx fail
if(isSegwitChange) {
BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(_change_index);
}
else {
HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().setAddrIdx(_change_index);
}
}
}
catch(JSONException je) {
Toast.makeText(SendActivity.this, "pushTx:" + je.getMessage(), Toast.LENGTH_SHORT).show();
}
catch(MnemonicException.MnemonicLengthException mle) {
Toast.makeText(SendActivity.this, "pushTx:" + mle.getMessage(), Toast.LENGTH_SHORT).show();
}
catch(DecoderException de) {
Toast.makeText(SendActivity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show();
}
catch(IOException ioe) {
Toast.makeText(SendActivity.this, "pushTx:" + ioe.getMessage(), Toast.LENGTH_SHORT).show();
}
finally {
SendActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
btSend.setActivated(true);
btSend.setClickable(true);
progress.dismiss();
dialog.dismiss();
}
});
}
Looper.loop();
}
}).start();
}
else {
// Log.d("SendActivity", "tx error");
Toast.makeText(SendActivity.this, "tx error", Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
try {
// reset change index upon 'NO'
if(isSegwitChange) {
BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(_change_index);
}
else {
HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().setAddrIdx(_change_index);
}
}
catch(Exception e) {
// Log.d("SendActivity", e.getMessage());
Toast.makeText(SendActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
finally {
SendActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
btSend.setActivated(true);
btSend.setClickable(true);
dialog.dismiss();
}
});
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
});
Bundle extras = getIntent().getExtras();
if(extras != null) {
bViaMenu = extras.getBoolean("via_menu", false);
String strUri = extras.getString("uri");
strPCode = extras.getString("pcode");
if(strUri != null && strUri.length() > 0) {
processScan(strUri);
}
if(strPCode != null && strPCode.length() > 0) {
processPCode(strPCode, null);
}
}
validateSpend();
}
@Override
public void onResume() {
super.onResume();
AppUtil.getInstance(SendActivity.this).checkTimeOut();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onDestroy() {
SendActivity.this.getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
menu.findItem(R.id.action_settings).setVisible(false);
menu.findItem(R.id.action_sweep).setVisible(false);
menu.findItem(R.id.action_backup).setVisible(false);
menu.findItem(R.id.action_refresh).setVisible(false);
menu.findItem(R.id.action_share_receive).setVisible(false);
menu.findItem(R.id.action_tor).setVisible(false);
menu.findItem(R.id.action_sign).setVisible(false);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.action_scan_qr) {
doScan();
}
else if (id == R.id.action_ricochet) {
Intent intent = new Intent(SendActivity.this, RicochetActivity.class);
startActivity(intent);
}
else if (id == R.id.action_empty_ricochet) {
emptyRicochetQueue();
}
else if (id == R.id.action_utxo) {
doUTXO();
}
else if (id == R.id.action_fees) {
doFees();
}
else if (id == R.id.action_batch) {
doBatchSpend();
}
else if (id == R.id.action_support) {
doSupport();
}
else {
;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) {
if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
processScan(strResult);
}
}
else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) {
;
}
else if(resultCode == Activity.RESULT_OK && requestCode == RICOCHET) {
;
}
else if(resultCode == Activity.RESULT_CANCELED && requestCode == RICOCHET) {
;
}
else {
;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
if(bViaMenu) {
SendActivity.this.finish();
}
else {
Intent _intent = new Intent(SendActivity.this, BalanceActivity.class);
_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(_intent);
}
return true;
}
else {
;
}
return false;
}
private void doScan() {
Intent intent = new Intent(SendActivity.this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } );
startActivityForResult(intent, SCAN_QR);
}
private void doSupport() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://support.samourai.io/section/8-sending-bitcoin"));
startActivity(intent);
}
private void processScan(String data) {
if(data.contains("https://bitpay.com")) {
AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.no_bitpay)
.setCancelable(false)
.setPositiveButton(R.string.learn_more, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.samouraiwallet.com/post/169222582782/bitpay-qr-codes-are-no-longer-valid-important"));
startActivity(intent);
}
}).setNegativeButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if(!isFinishing()) {
dlg.show();
}
return;
}
if(FormatsUtil.getInstance().isValidPaymentCode(data)) {
processPCode(data, null);
return;
}
if(FormatsUtil.getInstance().isBitcoinUri(data)) {
String address = FormatsUtil.getInstance().getBitcoinAddress(data);
String amount = FormatsUtil.getInstance().getBitcoinAmount(data);
edAddress.setText(address);
if(amount != null) {
try {
NumberFormat btcFormat = NumberFormat.getInstance(Locale.US);
btcFormat.setMaximumFractionDigits(8);
btcFormat.setMinimumFractionDigits(1);
edAmountBTC.setText(btcFormat.format(Double.parseDouble(amount) / 1e8));
}
catch (NumberFormatException nfe) {
edAmountBTC.setText("0.0");
}
}
tvFiatSymbol.setText(getDisplayUnits() + "-" + strFiat);
final String strAmount;
NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setMinimumIntegerDigits(1);
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(8);
strAmount = nf.format(balance / 1e8);
tvMax.setText(strAmount + " " + getDisplayUnits());
try {
if(amount != null && Double.parseDouble(amount) != 0.0) {
edAddress.setEnabled(false);
edAmountBTC.setEnabled(false);
edAmountFiat.setEnabled(false);
// Toast.makeText(SendActivity.this, R.string.no_edit_BIP21_scan, Toast.LENGTH_SHORT).show();
}
}
catch (NumberFormatException nfe) {
edAmountBTC.setText("0.0");
}
}
else if(FormatsUtil.getInstance().isValidBitcoinAddress(data)) {
edAddress.setText(data);
}
else if(data.indexOf("?") != -1) {
String pcode = data.substring(0, data.indexOf("?"));
// not valid BIP21 but seen often enough
if(pcode.startsWith("bitcoin:
pcode = pcode.substring(10);
}
if(pcode.startsWith("bitcoin:")) {
pcode = pcode.substring(8);
}
if(FormatsUtil.getInstance().isValidPaymentCode(pcode)) {
processPCode(pcode, data.substring(data.indexOf("?")));
}
}
else {
Toast.makeText(SendActivity.this, R.string.scan_error, Toast.LENGTH_SHORT).show();
}
validateSpend();
}
private void processPCode(String pcode, String meta) {
if(FormatsUtil.getInstance().isValidPaymentCode(pcode)) {
if(BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_SENT_CFM) {
try {
PaymentCode _pcode = new PaymentCode(pcode);
PaymentAddress paymentAddress = BIP47Util.getInstance(SendActivity.this).getSendAddress(_pcode, BIP47Meta.getInstance().getOutgoingIdx(pcode));
strDestinationBTCAddress = paymentAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
strPCode = _pcode.toString();
edAddress.setText(BIP47Meta.getInstance().getDisplayLabel(strPCode));
edAddress.setEnabled(false);
}
catch(Exception e) {
Toast.makeText(SendActivity.this, R.string.error_payment_code, Toast.LENGTH_SHORT).show();
}
}
else {
// Toast.makeText(SendActivity.this, "Payment must be added and notification tx sent", Toast.LENGTH_SHORT).show();
if(meta != null && meta.startsWith("?") && meta.length() > 1) {
meta = meta.substring(1);
}
Intent intent = new Intent(SendActivity.this, BIP47Activity.class);
intent.putExtra("pcode", pcode);
if(meta != null && meta.length() > 0) {
intent.putExtra("meta", meta);
}
startActivity(intent);
}
}
else {
Toast.makeText(SendActivity.this, R.string.invalid_payment_code, Toast.LENGTH_SHORT).show();
}
}
private void validateSpend() {
boolean isValid = false;
boolean insufficientFunds = false;
double btc_amount = 0.0;
String strBTCAddress = edAddress.getText().toString().trim();
if(strBTCAddress.startsWith("bitcoin:")) {
edAddress.setText(strBTCAddress.substring(8));
}
try {
btc_amount = NumberFormat.getInstance(Locale.US).parse(edAmountBTC.getText().toString().trim()).doubleValue();
// Log.i("SendFragment", "amount entered:" + btc_amount);
}
catch (NumberFormatException nfe) {
btc_amount = 0.0;
}
catch (ParseException pe) {
btc_amount = 0.0;
}
final double dAmount = btc_amount;
// Log.i("SendFragment", "amount entered (converted):" + dAmount);
final long amount = (long)(Math.round(dAmount * 1e8));
// Log.i("SendFragment", "amount entered (converted to long):" + amount);
// Log.i("SendFragment", "balance:" + balance);
if(amount > balance) {
insufficientFunds = true;
}
// Log.i("SendFragment", "insufficient funds:" + insufficientFunds);
if(btc_amount > 0.00 && FormatsUtil.getInstance().isValidBitcoinAddress(edAddress.getText().toString())) {
isValid = true;
}
else if(btc_amount > 0.00 && strDestinationBTCAddress != null && FormatsUtil.getInstance().isValidBitcoinAddress(strDestinationBTCAddress)) {
isValid = true;
}
else {
isValid = false;
}
if(!isValid || insufficientFunds) {
btSend.setVisibility(View.INVISIBLE);
}
else {
btSend.setVisibility(View.VISIBLE);
}
}
public String getDisplayUnits() {
return MonetaryUtil.getInstance().getBTCUnits();
}
private boolean hasBIP47UTXO(List<MyTransactionOutPoint> outPoints) {
List<String> addrs = BIP47Meta.getInstance().getUnspentAddresses(SendActivity.this, BIP47Util.getInstance(SendActivity.this).getWallet().getAccount(0).getPaymentCode());
for(MyTransactionOutPoint o : outPoints) {
if(addrs.contains(o.getAddress())) {
return true;
}
}
return false;
}
private String getCurrentFeeSetting() {
return getText(R.string.current_fee_selection) + "\n" + (FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
}
private void doCustomFee() {
double sanitySat = FeeUtil.getInstance().getHighFee().getDefaultPerKB().doubleValue() / 1000.0;
final double sanityValue = sanitySat * 1.5;
final EditText etCustomFee = new EditText(SendActivity.this);
// String val = null;
double d = FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().doubleValue() / 1000.0;
NumberFormat decFormat = NumberFormat.getInstance(Locale.US);
decFormat.setMaximumFractionDigits(3);
decFormat.setMinimumFractionDigits(0);
/*
if((d - (int)d) != 0.0) {
val = Double.toString(d);
}
else {
val = Integer.toString((int)d);
}
*/
etCustomFee.setText(decFormat.format(d));
InputFilter filter = new InputFilter() {
String strCharset = "0123456789nollNOLL.";
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for(int i = start; i < end; i++) {
if(strCharset.indexOf(source.charAt(i)) == -1) {
return "";
}
}
return null;
}
};
etCustomFee.setFilters(new InputFilter[] { filter } );
AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.set_sat)
.setView(etCustomFee)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String strCustomFee = etCustomFee.getText().toString();
double customValue = 0.0;
if(strCustomFee.equalsIgnoreCase("noll") && PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true) {
customValue = 0.0;
}
else {
try {
customValue = Double.valueOf(strCustomFee);
} catch (Exception e) {
Toast.makeText(SendActivity.this, R.string.custom_fee_too_low, Toast.LENGTH_SHORT).show();
return;
}
}
if(customValue < 1.0 && !strCustomFee.equalsIgnoreCase("noll")) {
Toast.makeText(SendActivity.this, R.string.custom_fee_too_low, Toast.LENGTH_SHORT).show();
}
else if(customValue > sanityValue) {
Toast.makeText(SendActivity.this, R.string.custom_fee_too_high, Toast.LENGTH_SHORT).show();
}
else {
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFee.setDefaultPerKB(BigInteger.valueOf((long)(customValue * 1000.0)));
Log.d("SendActivity", "custom fee:" + BigInteger.valueOf((long)(customValue * 1000.0)));
FeeUtil.getInstance().setSuggestedFee(suggestedFee);
btLowFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btAutoFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btPriorityFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.darkgrey));
btCustomFee.setBackgroundColor(SendActivity.this.getResources().getColor(R.color.blue));
btCustomFee.setText((FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().doubleValue() / 1000.0) + "\n" + getString(R.string.sat_b));
btCustomFee.setTypeface(null, Typeface.BOLD);
btLowFee.setTypeface(null, Typeface.NORMAL);
btAutoFee.setTypeface(null, Typeface.NORMAL);
btPriorityFee.setTypeface(null, Typeface.NORMAL);
long lowFee = FeeUtil.getInstance().getLowFee().getDefaultPerKB().longValue() / 1000L;
long normalFee = FeeUtil.getInstance().getNormalFee().getDefaultPerKB().longValue() / 1000L;
long highFee = FeeUtil.getInstance().getHighFee().getDefaultPerKB().longValue() / 1000L;
double pct = 0.0;
int nbBlocks = 6;
if(customValue == 0.0) {
customValue = 1.0;
}
if(customValue <= (double)lowFee) {
pct = ((double)lowFee / customValue);
nbBlocks = ((Double)Math.ceil(pct * 24.0)).intValue();
}
else if(customValue >= (double)highFee) {
pct = ((double)highFee / customValue);
nbBlocks = ((Double)Math.ceil(pct * 2.0)).intValue();
if(nbBlocks < 1) {
nbBlocks = 1;
}
}
else {
pct = ((double)normalFee / customValue);
nbBlocks = ((Double)Math.ceil(pct * 6.0)).intValue();
}
tvFeePrompt.setText(getText(R.string.fee_custom_priority) + " " + nbBlocks + " " + getText(R.string.blocks_to_cf));
}
dialog.dismiss();
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if(!isFinishing()) {
dlg.show();
}
}
private void doUTXO() {
Intent intent = new Intent(SendActivity.this, UTXOActivity.class);
startActivity(intent);
}
private void doBatchSpend() {
Intent intent = new Intent(SendActivity.this, BatchSendActivity.class);
startActivity(intent);
}
private void doFees() {
SuggestedFee highFee = FeeUtil.getInstance().getHighFee();
SuggestedFee normalFee = FeeUtil.getInstance().getNormalFee();
SuggestedFee lowFee = FeeUtil.getInstance().getLowFee();
String message = getText(R.string.current_fee_selection) + " " + (FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
message += "\n";
message += getText(R.string.current_hi_fee_value) + " " + (highFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
message += "\n";
message += getText(R.string.current_mid_fee_value) + " " + (normalFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
message += "\n";
message += getText(R.string.current_lo_fee_value) + " " + (lowFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if(!isFinishing()) {
dlg.show();
}
}
private void emptyRicochetQueue() {
RicochetMeta.getInstance(SendActivity.this).setLastRicochet(null);
RicochetMeta.getInstance(SendActivity.this).empty();
new Thread(new Runnable() {
@Override
public void run() {
try {
PayloadUtil.getInstance(SendActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(SendActivity.this).getGUID() + AccessFactory.getInstance(SendActivity.this).getPIN()));
}
catch(Exception e) {
;
}
}
}).start();
}
private void doShowTx(final String hexTx, final String txHash) {
final int QR_ALPHANUM_CHAR_LIMIT = 4296; // tx max size in bytes == 2148
TextView showTx = new TextView(SendActivity.this);
showTx.setText(hexTx);
showTx.setTextIsSelectable(true);
showTx.setPadding(40, 10, 40, 10);
showTx.setTextSize(18.0f);
final CheckBox cbMarkInputsUnspent = new CheckBox(SendActivity.this);
cbMarkInputsUnspent.setText(R.string.mark_inputs_as_unspendable);
cbMarkInputsUnspent.setChecked(false);
LinearLayout hexLayout = new LinearLayout(SendActivity.this);
hexLayout.setOrientation(LinearLayout.VERTICAL);
hexLayout.addView(cbMarkInputsUnspent);
hexLayout.addView(showTx);
new AlertDialog.Builder(SendActivity.this)
.setTitle(txHash)
.setView(hexLayout)
.setCancelable(false)
.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if(cbMarkInputsUnspent.isChecked()) {
markUTXOAsUnspendable(hexTx);
Intent intent = new Intent("com.samourai.wallet.BalanceFragment.REFRESH");
intent.putExtra("notifTx", false);
intent.putExtra("fetch", true);
LocalBroadcastManager.getInstance(SendActivity.this).sendBroadcast(intent);
}
dialog.dismiss();
SendActivity.this.finish();
}
})
.setNegativeButton(R.string.show_qr, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if(cbMarkInputsUnspent.isChecked()) {
markUTXOAsUnspendable(hexTx);
Intent intent = new Intent("com.samourai.wallet.BalanceFragment.REFRESH");
intent.putExtra("notifTx", false);
intent.putExtra("fetch", true);
LocalBroadcastManager.getInstance(SendActivity.this).sendBroadcast(intent);
}
if(hexTx.length() <= QR_ALPHANUM_CHAR_LIMIT) {
final ImageView ivQR = new ImageView(SendActivity.this);
Display display = (SendActivity.this).getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int imgWidth = Math.max(size.x - 240, 150);
Bitmap bitmap = null;
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(hexTx, null, Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), imgWidth);
try {
bitmap = qrCodeEncoder.encodeAsBitmap();
} catch (WriterException e) {
e.printStackTrace();
}
ivQR.setImageBitmap(bitmap);
LinearLayout qrLayout = new LinearLayout(SendActivity.this);
qrLayout.setOrientation(LinearLayout.VERTICAL);
qrLayout.addView(ivQR);
new AlertDialog.Builder(SendActivity.this)
.setTitle(txHash)
.setView(qrLayout)
.setCancelable(false)
.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
SendActivity.this.finish();
}
})
.setNegativeButton(R.string.share_qr, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String strFileName = AppUtil.getInstance(SendActivity.this).getReceiveQRFilename();
File file = new File(strFileName);
if(!file.exists()) {
try {
file.createNewFile();
}
catch(Exception e) {
Toast.makeText(SendActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
file.setReadable(true, false);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
}
catch(FileNotFoundException fnfe) {
;
}
if(file != null && fos != null) {
Bitmap bitmap = ((BitmapDrawable)ivQR.getDrawable()).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos);
try {
fos.close();
}
catch(IOException ioe) {
;
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
startActivity(Intent.createChooser(intent, SendActivity.this.getText(R.string.send_tx)));
}
}
}).show();
}
else {
Toast.makeText(SendActivity.this, R.string.tx_too_large_qr, Toast.LENGTH_SHORT).show();
}
}
}).show();
}
private void markUTXOAsUnspendable(String hexTx) {
HashMap<String, Long> utxos = new HashMap<String,Long>();
for(UTXO utxo : APIFactory.getInstance(SendActivity.this).getUtxos(true)) {
for(MyTransactionOutPoint outpoint : utxo.getOutpoints()) {
utxos.put(outpoint.getTxHash().toString() + "-" + outpoint.getTxOutputN(), outpoint.getValue().longValue());
}
}
Transaction tx = new Transaction(SamouraiWallet.getInstance().getCurrentNetworkParams(), Hex.decode(hexTx));
for(TransactionInput input : tx.getInputs()) {
BlockedUTXO.getInstance().add(input.getOutpoint().getHash().toString(), (int)input.getOutpoint().getIndex(), utxos.get(input.getOutpoint().getHash().toString() + "-" + (int)input.getOutpoint().getIndex()));
}
}
private void sanitizeFee() {
if(FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue() / 1000L == 1L) {
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf((long)(1.15 * 1000.0)));
Log.d("SendActivity", "adjusted fee:" + suggestedFee.getDefaultPerKB().longValue());
FeeUtil.getInstance().setSuggestedFee(suggestedFee);
}
}
} |
package com.samourai.wallet.util;
import android.content.Context;
import android.util.Log;
//import android.util.Log;
import com.samourai.wallet.R;
import com.samourai.wallet.SettingsActivity2;
import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.client.methods.HttpGet;
import info.guardianproject.netcipher.client.StrongHttpsClient;
import info.guardianproject.netcipher.proxy.OrbotHelper;
public class WebUtil {
public static final String BLOCKCHAIN_DOMAIN = "https://blockchain.info/";
public static final String SAMOURAI_API = "https://api.samouraiwallet.com/";
public static final String SAMOURAI_API_CHECK = "https://api.samourai.io/v1/status";
public static final String LBC_EXCHANGE_URL = "https://localbitcoins.com/bitcoinaverage/ticker-all-currencies/";
public static final String BTCe_EXCHANGE_URL = "https://btc-e.com/api/3/ticker/";
public static final String BFX_EXCHANGE_URL = "https://api.bitfinex.com/v1/pubticker/btcusd";
public static final String AVG_EXCHANGE_URL = "https://api.bitcoinaverage.com/ticker/global/all";
public static final String VALIDATE_SSL_URL = SAMOURAI_API;
public static final String DYNAMIC_FEE_URL = "https://bitcoinfees.21.co/api/v1/fees/recommended";
public static final String BTCX_FEE_URL = "http://bitcoinexchangerate.org/fees";
public static final String CHAINSO_TX_PREV_OUT_URL = "https://chain.so/api/v2/tx/BTC/";
public static final String CHAINSO_PUSHTX_URL = "https://chain.so/api/v2/send_tx/BTC/";
public static final String RECOMMENDED_BIP47_URL = "http://samouraiwallet.com/api/v1/get-pcodes";
private static final int DefaultRequestRetry = 2;
private static final int DefaultRequestTimeout = 60000;
private static WebUtil instance = null;
private static Context context = null;
private WebUtil() {
;
}
public static WebUtil getInstance(Context ctx) {
context = ctx;
if(instance == null) {
instance = new WebUtil();
}
return instance;
}
public String postURL(String request, String urlParameters) throws Exception {
return postURL(null, request, urlParameters);
}
public String postURL(String contentType, String request, String urlParameters) throws Exception {
String error = null;
for (int ii = 0; ii < DefaultRequestRetry; ++ii) {
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", contentType == null ? "application/x-www-form-urlencoded" : contentType);
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
connection.setUseCaches (false);
connection.setConnectTimeout(DefaultRequestTimeout);
connection.setReadTimeout(DefaultRequestTimeout);
connection.connect();
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.setInstanceFollowRedirects(false);
if (connection.getResponseCode() == 200) {
// System.out.println("postURL:return code 200");
return IOUtils.toString(connection.getInputStream(), "UTF-8");
}
else {
error = IOUtils.toString(connection.getErrorStream(), "UTF-8");
// System.out.println("postURL:return code " + error);
}
Thread.sleep(5000);
} finally {
connection.disconnect();
}
}
throw new Exception("Invalid Response " + error);
}
public String getURL(String URL) throws Exception {
if(context == null) {
return _getURL(URL);
}
else {
//if(TorUtil.getInstance(context).orbotIsRunning()) {
Log.i("WebUtil", "Tor enabled status:" + TorUtil.getInstance(context).statusFromBroadcast());
if(TorUtil.getInstance(context).statusFromBroadcast()) {
return tor_getURL(URL);
}
else {
return _getURL(URL);
}
}
}
private String _getURL(String URL) throws Exception {
URL url = new URL(URL);
String error = null;
for (int ii = 0; ii < DefaultRequestRetry; ++ii) {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setRequestMethod("GET");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
connection.setConnectTimeout(DefaultRequestTimeout);
connection.setReadTimeout(DefaultRequestTimeout);
connection.setInstanceFollowRedirects(false);
connection.connect();
if (connection.getResponseCode() == 200)
return IOUtils.toString(connection.getInputStream(), "UTF-8");
else
error = IOUtils.toString(connection.getErrorStream(), "UTF-8");
Thread.sleep(5000);
} finally {
connection.disconnect();
}
}
return error;
}
private String tor_getURL(String URL) throws Exception {
StrongHttpsClient httpclient = new StrongHttpsClient(context, R.raw.debiancacerts);
httpclient.useProxy(true, StrongHttpsClient.TYPE_SOCKS, "127.0.0.1", 9050);
// httpclient.useProxy(true, StrongHttpsClient.TYPE_HTTP, "127.0.0.1", 8118);
HttpGet httpget = new HttpGet(URL);
HttpResponse response = httpclient.execute(httpget);
StringBuffer sb = new StringBuffer();
sb.append(response.getStatusLine()).append("\n\n");
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
httpclient.close();
String result = sb.toString();
// Log.d("WebUtil", "result via Tor:" + result);
int idx = result.indexOf("{");
if(idx != -1) {
return result.substring(idx);
}
else {
return null;
}
}
} |
package org.codehaus.groovy.classgen;
import groovy.lang.GroovyRuntimeException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.AnnotatedNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.CompileUnit;
import org.codehaus.groovy.ast.ConstructorNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.InnerClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.PropertyNode;
import org.codehaus.groovy.ast.VariableScope;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.ArrayExpression;
import org.codehaus.groovy.ast.expr.AttributeExpression;
import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.BitwiseNegExpression;
import org.codehaus.groovy.ast.expr.BooleanExpression;
import org.codehaus.groovy.ast.expr.CastExpression;
import org.codehaus.groovy.ast.expr.ClassExpression;
import org.codehaus.groovy.ast.expr.ClosureExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
import org.codehaus.groovy.ast.expr.DeclarationExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.ExpressionTransformer;
import org.codehaus.groovy.ast.expr.FieldExpression;
import org.codehaus.groovy.ast.expr.GStringExpression;
import org.codehaus.groovy.ast.expr.ListExpression;
import org.codehaus.groovy.ast.expr.MapEntryExpression;
import org.codehaus.groovy.ast.expr.MapExpression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.expr.MethodPointerExpression;
import org.codehaus.groovy.ast.expr.NegationExpression;
import org.codehaus.groovy.ast.expr.NotExpression;
import org.codehaus.groovy.ast.expr.PostfixExpression;
import org.codehaus.groovy.ast.expr.PrefixExpression;
import org.codehaus.groovy.ast.expr.PropertyExpression;
import org.codehaus.groovy.ast.expr.RangeExpression;
import org.codehaus.groovy.ast.expr.RegexExpression;
import org.codehaus.groovy.ast.expr.SpreadExpression;
import org.codehaus.groovy.ast.expr.SpreadMapExpression;
import org.codehaus.groovy.ast.expr.StaticMethodCallExpression;
import org.codehaus.groovy.ast.expr.TernaryExpression;
import org.codehaus.groovy.ast.expr.TupleExpression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.ast.stmt.AssertStatement;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.BreakStatement;
import org.codehaus.groovy.ast.stmt.CaseStatement;
import org.codehaus.groovy.ast.stmt.CatchStatement;
import org.codehaus.groovy.ast.stmt.ContinueStatement;
import org.codehaus.groovy.ast.stmt.DoWhileStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.ForStatement;
import org.codehaus.groovy.ast.stmt.IfStatement;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.ast.stmt.SwitchStatement;
import org.codehaus.groovy.ast.stmt.SynchronizedStatement;
import org.codehaus.groovy.ast.stmt.ThrowStatement;
import org.codehaus.groovy.ast.stmt.TryCatchStatement;
import org.codehaus.groovy.ast.stmt.WhileStatement;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.syntax.RuntimeParserException;
import org.codehaus.groovy.syntax.Token;
import org.codehaus.groovy.syntax.Types;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
/**
* Generates Java class versions of Groovy classes using ASM.
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @author <a href="mailto:b55r@sina.com">Bing Ran</a>
* @author Jochen Theodorou
*
* @version $Revision$
*/
public class AsmClassGenerator extends ClassGenerator {
private Logger log = Logger.getLogger(getClass().getName());
private ClassVisitor cw;
private MethodVisitor cv;
private GeneratorContext context;
private String sourceFile;
// current class details
private ClassNode classNode;
private ClassNode outermostClass;
private String internalClassName;
private String internalBaseClassName;
/** maps the variable names to the JVM indices */
private CompileStack compileStack;
/** have we output a return statement yet */
private boolean outputReturn;
/** are we on the left or right of an expression */
private boolean leftHandExpression;
// cached values
MethodCaller invokeMethodMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeMethod");
MethodCaller invokeMethodSafeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeMethodSafe");
MethodCaller invokeMethodSpreadSafeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeMethodSpreadSafe");
MethodCaller invokeStaticMethodMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeStaticMethod");
MethodCaller invokeConstructorMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeConstructor");
MethodCaller invokeConstructorOfMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeConstructorOf");
MethodCaller invokeNoArgumentsConstructorOf = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeNoArgumentsConstructorOf");
MethodCaller invokeConstructorAtMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeConstructorAt");
MethodCaller invokeNoArgumentsConstructorAt = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeNoArgumentsConstructorAt");
MethodCaller invokeClosureMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeClosure");
MethodCaller invokeSuperMethodMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeSuperMethod");
MethodCaller invokeNoArgumentsMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeNoArgumentsMethod");
MethodCaller invokeNoArgumentsSafeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeNoArgumentsSafeMethod");
MethodCaller invokeNoArgumentsSpreadSafeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeNoArgumentsSpreadSafeMethod");
MethodCaller invokeStaticNoArgumentsMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "invokeStaticNoArgumentsMethod");
MethodCaller asIntMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "asInt");
MethodCaller asTypeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "asType");
MethodCaller getAttributeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "getAttribute");
MethodCaller getAttributeSafeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "getAttributeSafe");
MethodCaller getAttributeSpreadSafeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "getAttributeSpreadSafe");
MethodCaller setAttributeMethod2 = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "setAttribute2");
MethodCaller setAttributeSafeMethod2 = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "setAttributeSafe2");
MethodCaller getPropertyMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "getProperty");
MethodCaller getPropertySafeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "getPropertySafe");
MethodCaller getPropertySpreadSafeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "getPropertySpreadSafe");
MethodCaller setPropertyMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "setProperty");
MethodCaller setPropertyMethod2 = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "setProperty2");
MethodCaller setPropertySafeMethod2 = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "setPropertySafe2");
MethodCaller getGroovyObjectPropertyMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "getGroovyObjectProperty");
MethodCaller setGroovyObjectPropertyMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "setGroovyObjectProperty");
MethodCaller asIteratorMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "asIterator");
MethodCaller asBool = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "asBool");
MethodCaller notBoolean = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "notBoolean");
MethodCaller notObject = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "notObject");
MethodCaller regexPattern = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "regexPattern");
MethodCaller spreadList = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "spreadList");
MethodCaller spreadMap = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "spreadMap");
MethodCaller getMethodPointer = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "getMethodPointer");
MethodCaller negation = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "negate");
MethodCaller bitNegation = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "bitNegate");
MethodCaller convertPrimitiveArray = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "convertPrimitiveArray");
MethodCaller convertToPrimitiveArray = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "convertToPrimitiveArray");
MethodCaller compareIdenticalMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareIdentical");
MethodCaller compareEqualMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareEqual");
MethodCaller compareNotEqualMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareNotEqual");
MethodCaller compareToMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareTo");
MethodCaller findRegexMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "findRegex");
MethodCaller matchRegexMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "matchRegex");
MethodCaller compareLessThanMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareLessThan");
MethodCaller compareLessThanEqualMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareLessThanEqual");
MethodCaller compareGreaterThanMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareGreaterThan");
MethodCaller compareGreaterThanEqualMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "compareGreaterThanEqual");
MethodCaller isCaseMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "isCase");
MethodCaller createListMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "createList");
MethodCaller createTupleMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "createTuple");
MethodCaller createMapMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "createMap");
MethodCaller createRangeMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "createRange");
MethodCaller assertFailedMethod = MethodCaller.newStatic(ScriptBytecodeAdapter.class, "assertFailed");
MethodCaller iteratorNextMethod = MethodCaller.newInterface(Iterator.class, "next");
MethodCaller iteratorHasNextMethod = MethodCaller.newInterface(Iterator.class, "hasNext");
// exception blocks list
private List exceptionBlocks = new ArrayList();
private Set syntheticStaticFields = new HashSet();
private boolean passingClosureParams;
private ConstructorNode constructorNode;
private MethodNode methodNode;
private BytecodeHelper helper = new BytecodeHelper(null);
public static final boolean CREATE_DEBUG_INFO = true;
public static final boolean CREATE_LINE_NUMBER_INFO = true;
private static final boolean MARK_START = true;
/*public static final String EB_SWITCH_NAME = "static.dispatching";
public boolean ENABLE_EARLY_BINDING;
{ //
String ebSwitch = (String) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return System.getProperty(EB_SWITCH_NAME, "false"); // set default to true if early binding is on by default.
}
});
//System.out.println("ebSwitch = " + ebSwitch);
if (ebSwitch.equals("true")) {
ENABLE_EARLY_BINDING = true;
}
else if (ebSwitch.equals("false")) {
ENABLE_EARLY_BINDING = false;
}
else {
ENABLE_EARLY_BINDING = false;
log.warning("The value of system property " + EB_SWITCH_NAME + " is not recognized. Late dispatching is assumed. ");
}
}*/
public static final boolean ASM_DEBUG = false; // add marker in the bytecode to show source-byecode relationship
private int lineNumber = -1;
private int columnNumber = -1;
private ASTNode currentASTNode = null;
private DummyClassGenerator dummyGen = null;
private ClassWriter dummyClassWriter = null;
public AsmClassGenerator(
GeneratorContext context, ClassVisitor classVisitor,
ClassLoader classLoader, String sourceFile
) {
super(classLoader);
this.context = context;
this.cw = classVisitor;
this.sourceFile = sourceFile;
this.dummyClassWriter = new ClassWriter(true);
dummyGen = new DummyClassGenerator(context, dummyClassWriter, classLoader, sourceFile);
compileStack = new CompileStack();
}
protected SourceUnit getSourceUnit() {
// TODO Auto-generated method stub
return null;
}
// GroovyClassVisitor interface
public void visitClass(ClassNode classNode) {
// todo to be tested
// createDummyClass(classNode);
try {
syntheticStaticFields.clear();
this.classNode = classNode;
this.outermostClass = null;
this.internalClassName = BytecodeHelper.getClassInternalName(classNode);
this.internalBaseClassName = BytecodeHelper.getClassInternalName(classNode.getSuperClass());
cw.visit(
asmJDKVersion,
classNode.getModifiers(),
internalClassName,
null,
internalBaseClassName,
BytecodeHelper.getClassInternalNames(classNode.getInterfaces())
);
cw.visitSource(sourceFile,null);
super.visitClass(classNode);
// set the optional enclosing method attribute of the current inner class
// br comment out once Groovy uses the latest CVS HEAD of ASM
// MethodNode enclosingMethod = classNode.getEnclosingMethod();
// String ownerName = BytecodeHelper.getClassInternalName(enclosingMethod.getDeclaringClass().getName());
// String descriptor = BytecodeHelper.getMethodDescriptor(enclosingMethod.getReturnType(), enclosingMethod.getParameters());
// EnclosingMethodAttribute attr = new EnclosingMethodAttribute(ownerName,enclosingMethod.getName(),descriptor);
// cw.visitAttribute(attr);
createSyntheticStaticFields();
for (Iterator iter = innerClasses.iterator(); iter.hasNext();) {
ClassNode innerClass = (ClassNode) iter.next();
String innerClassName = innerClass.getName();
String innerClassInternalName = BytecodeHelper.getClassInternalName(innerClassName);
{
int index = innerClassName.lastIndexOf('$');
if (index>=0) innerClassName = innerClassName.substring(index+1);
}
String outerClassName = internalClassName; // default for inner classes
MethodNode enclosingMethod = innerClass.getEnclosingMethod();
if (enclosingMethod != null) {
// local inner classes do not specify the outer class name
outerClassName = null;
innerClassName = null;
}
cw.visitInnerClass(
innerClassInternalName,
outerClassName,
innerClassName,
innerClass.getModifiers());
}
// br TODO an inner class should have an entry of itself
cw.visitEnd();
}
catch (GroovyRuntimeException e) {
e.setModule(classNode.getModule());
throw e;
}
}
private String[] buildExceptions(ClassNode[] exceptions) {
if (exceptions==null) return null;
String[] ret = new String[exceptions.length];
for (int i = 0; i < exceptions.length; i++) {
ret[i] = BytecodeHelper.getClassInternalName(exceptions[i]);
}
return ret;
}
protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor) {
String methodType = BytecodeHelper.getMethodDescriptor(node.getReturnType(), node.getParameters());
cv = cw.visitMethod(node.getModifiers(), node.getName(), methodType, null, buildExceptions(node.getExceptions()));
helper = new BytecodeHelper(cv);
if (!node.isAbstract()) {
Statement code = node.getCode();
if (isConstructor && (code == null || !firstStatementIsSuperInit(code))) {
// invokes the super class constructor
//cv.visitLabel(new Label());
cv.visitVarInsn(ALOAD, 0);
cv.visitMethodInsn(INVOKESPECIAL, internalBaseClassName, "<init>", "()V");
}
compileStack.init(node.getVariableScope(),node.getParameters(),cv, BytecodeHelper.getTypeDescription(classNode));
super.visitConstructorOrMethod(node, isConstructor);
if (!outputReturn || node.isVoidMethod()) {
cv.visitInsn(RETURN);
}
compileStack.clear();
// lets do all the exception blocks
for (Iterator iter = exceptionBlocks.iterator(); iter.hasNext();) {
Runnable runnable = (Runnable) iter.next();
runnable.run();
}
exceptionBlocks.clear();
cv.visitMaxs(0, 0);
}
}
public void visitConstructor(ConstructorNode node) {
this.constructorNode = node;
this.methodNode = null;
outputReturn = false;
super.visitConstructor(node);
}
public void visitMethod(MethodNode node) {
this.constructorNode = null;
this.methodNode = node;
outputReturn = false;
super.visitMethod(node);
}
public void visitField(FieldNode fieldNode) {
onLineNumber(fieldNode, "visitField: " + fieldNode.getName());
ClassNode t = fieldNode.getType();
cw.visitField(
fieldNode.getModifiers(),
fieldNode.getName(),
BytecodeHelper.getTypeDescription(t),
null, //fieldValue, //br all the sudden that one cannot init the field here. init is done in static initilizer and instace intializer.
null);
visitAnnotations(fieldNode);
}
public void visitProperty(PropertyNode statement) {
// the verifyer created the field and the setter/getter methods, so here is
// not really something to do
onLineNumber(statement, "visitProperty:" + statement.getField().getName());
this.methodNode = null;
}
// GroovyCodeVisitor interface
// Statements
protected void visitStatement(Statement statement) {
String name = statement.getStatementLabel();
if (name!=null) {
Label label = compileStack.createLocalLabel(name);
cv.visitLabel(label);
}
}
public void visitBlockStatement(BlockStatement block) {
onLineNumber(block, "visitBlockStatement");
visitStatement(block);
compileStack.pushVariableScope(block.getVariableScope());
super.visitBlockStatement(block);
compileStack.pop();
}
public void visitForLoop(ForStatement loop) {
onLineNumber(loop, "visitForLoop");
visitStatement(loop);
compileStack.pushLoop(loop.getVariableScope(),loop.getStatementLabel());
// Declare the loop counter.
Variable variable = compileStack.defineVariable(loop.getVariable(),false);
// Then initialize the iterator and generate the loop control
loop.getCollectionExpression().visit(this);
asIteratorMethod.call(cv);
final int iteratorIdx = compileStack.defineTemporaryVariable("iterator", ClassHelper.make(java.util.Iterator.class),true);
Label continueLabel = compileStack.getContinueLabel();
Label breakLabel = compileStack.getBreakLabel();
cv.visitLabel(continueLabel);
cv.visitVarInsn(ALOAD, iteratorIdx);
iteratorHasNextMethod.call(cv);
// note: ifeq tests for ==0, a boolean is 0 if it is false
cv.visitJumpInsn(IFEQ, breakLabel);
cv.visitVarInsn(ALOAD, iteratorIdx);
iteratorNextMethod.call(cv);
helper.storeVar(variable);
// Generate the loop body
loop.getLoopBlock().visit(this);
cv.visitJumpInsn(GOTO, continueLabel);
cv.visitLabel(breakLabel);
compileStack.pop();
}
public void visitWhileLoop(WhileStatement loop) {
onLineNumber(loop, "visitWhileLoop");
visitStatement(loop);
compileStack.pushLoop(loop.getStatementLabel());
Label continueLabel = compileStack.getContinueLabel();
Label breakLabel = compileStack.getBreakLabel();
cv.visitLabel(continueLabel);
loop.getBooleanExpression().visit(this);
cv.visitJumpInsn(IFEQ, breakLabel);
loop.getLoopBlock().visit(this);
cv.visitJumpInsn(GOTO, continueLabel);
cv.visitLabel(breakLabel);
}
public void visitDoWhileLoop(DoWhileStatement loop) {
onLineNumber(loop, "visitDoWhileLoop");
visitStatement(loop);
compileStack.pushLoop(loop.getStatementLabel());
Label breakLabel = compileStack.getBreakLabel();
Label continueLabel = compileStack.getContinueLabel();
cv.visitLabel(continueLabel);
loop.getLoopBlock().visit(this);
loop.getBooleanExpression().visit(this);
cv.visitJumpInsn(IFEQ, continueLabel);
cv.visitLabel(breakLabel);
compileStack.pop();
}
public void visitIfElse(IfStatement ifElse) {
onLineNumber(ifElse, "visitIfElse");
visitStatement(ifElse);
ifElse.getBooleanExpression().visit(this);
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
ifElse.getIfBlock().visit(this);
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
ifElse.getElseBlock().visit(this);
cv.visitLabel(l1);
}
public void visitTernaryExpression(TernaryExpression expression) {
onLineNumber(expression, "visitTernaryExpression");
expression.getBooleanExpression().visit(this);
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
expression.getTrueExpression().visit(this);
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
expression.getFalseExpression().visit(this);
cv.visitLabel(l1);
}
public void visitAssertStatement(AssertStatement statement) {
onLineNumber(statement, "visitAssertStatement");
visitStatement(statement);
BooleanExpression booleanExpression = statement.getBooleanExpression();
booleanExpression.visit(this);
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
// do nothing
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
// push expression string onto stack
String expressionText = booleanExpression.getText();
List list = new ArrayList();
addVariableNames(booleanExpression, list);
if (list.isEmpty()) {
cv.visitLdcInsn(expressionText);
}
else {
boolean first = true;
// lets create a new expression
cv.visitTypeInsn(NEW, "java/lang/StringBuffer");
cv.visitInsn(DUP);
cv.visitLdcInsn(expressionText + ". Values: ");
cv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuffer", "<init>", "(Ljava/lang/String;)V");
int tempIndex = compileStack.defineTemporaryVariable("assert",true);
for (Iterator iter = list.iterator(); iter.hasNext();) {
String name = (String) iter.next();
String text = name + " = ";
if (first) {
first = false;
}
else {
text = ", " + text;
}
cv.visitVarInsn(ALOAD, tempIndex);
cv.visitLdcInsn(text);
cv.visitMethodInsn(
INVOKEVIRTUAL,
"java/lang/StringBuffer",
"append",
"(Ljava/lang/Object;)Ljava/lang/StringBuffer;");
cv.visitInsn(POP);
cv.visitVarInsn(ALOAD, tempIndex);
new VariableExpression(name).visit(this);
cv.visitMethodInsn(
INVOKEVIRTUAL,
"java/lang/StringBuffer",
"append",
"(Ljava/lang/Object;)Ljava/lang/StringBuffer;");
cv.visitInsn(POP);
}
cv.visitVarInsn(ALOAD, tempIndex);
compileStack.removeVar(tempIndex);
}
// now the optional exception expression
statement.getMessageExpression().visit(this);
assertFailedMethod.call(cv);
cv.visitLabel(l1);
}
private void addVariableNames(Expression expression, List list) {
if (expression instanceof BooleanExpression) {
BooleanExpression boolExp = (BooleanExpression) expression;
addVariableNames(boolExp.getExpression(), list);
}
else if (expression instanceof BinaryExpression) {
BinaryExpression binExp = (BinaryExpression) expression;
addVariableNames(binExp.getLeftExpression(), list);
addVariableNames(binExp.getRightExpression(), list);
}
else if (expression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) expression;
list.add(varExp.getName());
}
}
public void visitTryCatchFinally(TryCatchStatement statement) {
onLineNumber(statement, "visitTryCatchFinally");
visitStatement(statement);
// todo need to add blockscope handling
CatchStatement catchStatement = statement.getCatchStatement(0);
Statement tryStatement = statement.getTryStatement();
if (tryStatement.isEmpty() || catchStatement == null) {
final Label l0 = new Label();
cv.visitLabel(l0);
tryStatement.visit(this);
int index1 = compileStack.defineTemporaryVariable("exception",false);
int index2 = compileStack.defineTemporaryVariable("exception",false);
final Label l1 = new Label();
cv.visitJumpInsn(JSR, l1);
final Label l2 = new Label();
cv.visitLabel(l2);
final Label l3 = new Label();
cv.visitJumpInsn(GOTO, l3);
final Label l4 = new Label();
cv.visitLabel(l4);
cv.visitVarInsn(ASTORE, index1);
cv.visitJumpInsn(JSR, l1);
final Label l5 = new Label();
cv.visitLabel(l5);
cv.visitVarInsn(ALOAD, index1);
cv.visitInsn(ATHROW);
cv.visitLabel(l1);
cv.visitVarInsn(ASTORE, index2);
statement.getFinallyStatement().visit(this);
cv.visitVarInsn(RET, index2);
cv.visitLabel(l3);
exceptionBlocks.add(new Runnable() {
public void run() {
cv.visitTryCatchBlock(l0, l2, l4, null);
cv.visitTryCatchBlock(l4, l5, l4, null);
}
});
}
else {
int finallySubAddress = compileStack.defineTemporaryVariable("exception",false);
int anyExceptionIndex = compileStack.defineTemporaryVariable("exception",false);
// start try block, label needed for exception table
final Label tryStart = new Label();
cv.visitLabel(tryStart);
tryStatement.visit(this);
// goto finally part
final Label finallyStart = new Label();
cv.visitJumpInsn(GOTO, finallyStart);
// marker needed for Exception table
final Label tryEnd = new Label();
cv.visitLabel(tryEnd);
for (Iterator it=statement.getCatchStatements().iterator(); it.hasNext();) {
catchStatement = (CatchStatement) it.next();
ClassNode exceptionType = catchStatement.getExceptionType();
// start catch block, label needed for exception table
final Label catchStart = new Label();
cv.visitLabel(catchStart);
// create exception variable and store the exception
compileStack.defineVariable(catchStatement.getVariable(),true);
// handle catch body
catchStatement.visit(this);
// goto finally start
cv.visitJumpInsn(GOTO, finallyStart);
// add exception to table
final String exceptionTypeInternalName = BytecodeHelper.getClassInternalName(exceptionType);
exceptionBlocks.add(new Runnable() {
public void run() {
cv.visitTryCatchBlock(tryStart, tryEnd, catchStart, exceptionTypeInternalName);
}
});
}
// marker needed for the exception table
final Label endOfAllCatches = new Label();
cv.visitLabel(endOfAllCatches);
// start finally
cv.visitLabel(finallyStart);
Label finallySub = new Label();
// run finally sub
cv.visitJumpInsn(JSR, finallySub);
// goto end of finally
Label afterFinally = new Label();
cv.visitJumpInsn(GOTO, afterFinally);
// start a block catching any Exception
final Label catchAny = new Label();
cv.visitLabel(catchAny);
//store exception
cv.visitVarInsn(ASTORE, anyExceptionIndex);
// run finally subroutine
cv.visitJumpInsn(JSR, finallySub);
// load the exception and rethrow it
cv.visitVarInsn(ALOAD, anyExceptionIndex);
cv.visitInsn(ATHROW);
// start the finally subroutine
cv.visitLabel(finallySub);
// store jump address
cv.visitVarInsn(ASTORE, finallySubAddress);
if (!statement.getFinallyStatement().isEmpty())
statement.getFinallyStatement().visit(this);
// return from subroutine
cv.visitVarInsn(RET, finallySubAddress);
// end of all catches and finally parts
cv.visitLabel(afterFinally);
// add catch any block to exception table
exceptionBlocks.add(new Runnable() {
public void run() {
cv.visitTryCatchBlock(tryStart, endOfAllCatches, catchAny, null);
}
});
}
}
public void visitSwitch(SwitchStatement statement) {
onLineNumber(statement, "visitSwitch");
visitStatement(statement);
statement.getExpression().visit(this);
// switch does not have a continue label. use its parent's for continue
Label breakLabel = compileStack.pushSwitch();
int switchVariableIndex = compileStack.defineTemporaryVariable("switch",true);
List caseStatements = statement.getCaseStatements();
int caseCount = caseStatements.size();
Label[] labels = new Label[caseCount + 1];
for (int i = 0; i < caseCount; i++) {
labels[i] = new Label();
}
int i = 0;
for (Iterator iter = caseStatements.iterator(); iter.hasNext(); i++) {
CaseStatement caseStatement = (CaseStatement) iter.next();
visitCaseStatement(caseStatement, switchVariableIndex, labels[i], labels[i + 1]);
}
statement.getDefaultStatement().visit(this);
cv.visitLabel(breakLabel);
compileStack.pop();
}
public void visitCaseStatement(CaseStatement statement) {
}
public void visitCaseStatement(
CaseStatement statement,
int switchVariableIndex,
Label thisLabel,
Label nextLabel) {
onLineNumber(statement, "visitCaseStatement");
cv.visitVarInsn(ALOAD, switchVariableIndex);
statement.getExpression().visit(this);
isCaseMethod.call(cv);
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
cv.visitLabel(thisLabel);
statement.getCode().visit(this);
// now if we don't finish with a break we need to jump past
// the next comparison
if (nextLabel != null) {
cv.visitJumpInsn(GOTO, nextLabel);
}
cv.visitLabel(l0);
}
public void visitBreakStatement(BreakStatement statement) {
onLineNumber(statement, "visitBreakStatement");
visitStatement(statement);
String name = statement.getLabel();
Label breakLabel;
if (name!=null) {
breakLabel = compileStack.getNamedBreakLabel(name);
} else {
breakLabel= compileStack.getBreakLabel();
}
cv.visitJumpInsn(GOTO, breakLabel);
}
public void visitContinueStatement(ContinueStatement statement) {
onLineNumber(statement, "visitContinueStatement");
visitStatement(statement);
String name = statement.getLabel();
Label continueLabel = compileStack.getContinueLabel();
if (name!=null) continueLabel = compileStack.getNamedContinueLabel(name);
cv.visitJumpInsn(GOTO, continueLabel);
}
public void visitSynchronizedStatement(SynchronizedStatement statement) {
onLineNumber(statement, "visitSynchronizedStatement");
visitStatement(statement);
statement.getExpression().visit(this);
int index = compileStack.defineTemporaryVariable("synchronized", ClassHelper.Integer_TYPE,true);
cv.visitVarInsn(ALOAD, index);
cv.visitInsn(MONITORENTER);
final Label l0 = new Label();
cv.visitLabel(l0);
statement.getCode().visit(this);
cv.visitVarInsn(ALOAD, index);
cv.visitInsn(MONITOREXIT);
final Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
final Label l2 = new Label();
cv.visitLabel(l2);
cv.visitVarInsn(ALOAD, index);
cv.visitInsn(MONITOREXIT);
cv.visitInsn(ATHROW);
cv.visitLabel(l1);
exceptionBlocks.add(new Runnable() {
public void run() {
cv.visitTryCatchBlock(l0, l2, l2, null);
}
});
}
public void visitThrowStatement(ThrowStatement statement) {
onLineNumber(statement, "visitThrowStatement");
visitStatement(statement);
statement.getExpression().visit(this);
// we should infer the type of the exception from the expression
cv.visitTypeInsn(CHECKCAST, "java/lang/Throwable");
cv.visitInsn(ATHROW);
}
public void visitReturnStatement(ReturnStatement statement) {
onLineNumber(statement, "visitReturnStatement");
visitStatement(statement);
ClassNode returnType = methodNode.getReturnType();
if (returnType==ClassHelper.VOID_TYPE) {
if (!(statement == ReturnStatement.RETURN_NULL_OR_VOID)) {
throwException("Cannot use return statement with an expression on a method that returns void");
}
cv.visitInsn(RETURN);
outputReturn = true;
return;
}
Expression expression = statement.getExpression();
evaluateExpression(expression);
if (returnType==ClassHelper.OBJECT_TYPE && expression.getType() != null && expression.getType()==ClassHelper.VOID_TYPE) {
cv.visitInsn(ACONST_NULL); // cheat the caller
cv.visitInsn(ARETURN);
} else {
// return is based on class type
// we may need to cast
helper.unbox(returnType);
if (returnType==ClassHelper.double_TYPE) {
cv.visitInsn(DRETURN);
}
else if (returnType==ClassHelper.float_TYPE) {
cv.visitInsn(FRETURN);
}
else if (returnType==ClassHelper.long_TYPE) {
cv.visitInsn(LRETURN);
}
else if (returnType==ClassHelper.boolean_TYPE) {
cv.visitInsn(IRETURN);
}
else if (
returnType==ClassHelper.char_TYPE
|| returnType==ClassHelper.byte_TYPE
|| returnType==ClassHelper.int_TYPE
|| returnType==ClassHelper.short_TYPE)
{
//byte,short,boolean,int are all IRETURN
cv.visitInsn(IRETURN);
}
else {
doConvertAndCast(returnType, expression, false, true);
cv.visitInsn(ARETURN);
}
}
outputReturn = true;
}
/**
* Casts to the given type unless it can be determined that the cast is unnecessary
*/
protected void doConvertAndCast(ClassNode type, Expression expression, boolean ignoreAutoboxing, boolean forceCast) {
ClassNode expType = getExpressionType(expression);
// temp resolution: convert all primitive casting to corresponsing Object type
if (!ignoreAutoboxing && ClassHelper.isPrimitiveType(type)) {
type = ClassHelper.getWrapper(type);
}
if (forceCast || (type!=null && !type.equals(expType))) {
doConvertAndCast(type);
}
}
/**
* @param expression
*/
protected void evaluateExpression(Expression expression) {
visitAndAutoboxBoolean(expression);
//expression.visit(this);
Expression assignExpr = createReturnLHSExpression(expression);
if (assignExpr != null) {
leftHandExpression = false;
assignExpr.visit(this);
}
}
public void visitExpressionStatement(ExpressionStatement statement) {
onLineNumber(statement, "visitExpressionStatement: " + statement.getExpression().getClass().getName());
visitStatement(statement);
Expression expression = statement.getExpression();
// disabled in favor of JIT resolving
// if (ENABLE_EARLY_BINDING)
// expression.resolve(this);
visitAndAutoboxBoolean(expression);
if (isPopRequired(expression)) {
cv.visitInsn(POP);
}
}
// Expressions
public void visitDeclarationExpression(DeclarationExpression expression) {
onLineNumber(expression, "visitDeclarationExpression: \""+expression.getVariableExpression().getName()+"\"");
Expression rightExpression = expression.getRightExpression();
// no need to visit left side, just get the variable name
VariableExpression vex = expression.getVariableExpression();
ClassNode type = vex.getType();
// lets not cast for primitive types as we handle these in field setting etc
if (ClassHelper.isPrimitiveType(type)) {
rightExpression.visit(this);
} else {
if (type!=ClassHelper.OBJECT_TYPE){
visitCastExpression(new CastExpression(type, rightExpression));
} else {
visitAndAutoboxBoolean(rightExpression);
}
}
compileStack.defineVariable(vex,true);
}
public void visitBinaryExpression(BinaryExpression expression) {
onLineNumber(expression, "visitBinaryExpression: \"" + expression.getOperation().getText() + "\" ");
switch (expression.getOperation().getType()) {
case Types.EQUAL : // = assignment
evaluateEqual(expression);
break;
case Types.COMPARE_IDENTICAL :
evaluateBinaryExpression(compareIdenticalMethod, expression);
break;
case Types.COMPARE_EQUAL :
evaluateBinaryExpression(compareEqualMethod, expression);
break;
case Types.COMPARE_NOT_EQUAL :
evaluateBinaryExpression(compareNotEqualMethod, expression);
break;
case Types.COMPARE_TO :
evaluateCompareTo(expression);
break;
case Types.COMPARE_GREATER_THAN :
evaluateBinaryExpression(compareGreaterThanMethod, expression);
break;
case Types.COMPARE_GREATER_THAN_EQUAL :
evaluateBinaryExpression(compareGreaterThanEqualMethod, expression);
break;
case Types.COMPARE_LESS_THAN :
evaluateBinaryExpression(compareLessThanMethod, expression);
break;
case Types.COMPARE_LESS_THAN_EQUAL :
evaluateBinaryExpression(compareLessThanEqualMethod, expression);
break;
case Types.LOGICAL_AND :
evaluateLogicalAndExpression(expression);
break;
case Types.LOGICAL_OR :
evaluateLogicalOrExpression(expression);
break;
case Types.BITWISE_AND :
evaluateBinaryExpression("and", expression);
break;
case Types.BITWISE_AND_EQUAL :
evaluateBinaryExpressionWithAsignment("and", expression);
break;
case Types.BITWISE_OR :
evaluateBinaryExpression("or", expression);
break;
case Types.BITWISE_OR_EQUAL :
evaluateBinaryExpressionWithAsignment("or", expression);
break;
case Types.BITWISE_XOR :
evaluateBinaryExpression("xor", expression);
break;
case Types.BITWISE_XOR_EQUAL :
evaluateBinaryExpressionWithAsignment("xor", expression);
break;
case Types.PLUS :
evaluateBinaryExpression("plus", expression);
break;
case Types.PLUS_EQUAL :
evaluateBinaryExpressionWithAsignment("plus", expression);
break;
case Types.MINUS :
evaluateBinaryExpression("minus", expression);
break;
case Types.MINUS_EQUAL :
evaluateBinaryExpressionWithAsignment("minus", expression);
break;
case Types.MULTIPLY :
evaluateBinaryExpression("multiply", expression);
break;
case Types.MULTIPLY_EQUAL :
evaluateBinaryExpressionWithAsignment("multiply", expression);
break;
case Types.DIVIDE :
evaluateBinaryExpression("div", expression);
break;
case Types.DIVIDE_EQUAL :
//SPG don't use divide since BigInteger implements directly
//and we want to dispatch through DefaultGroovyMethods to get a BigDecimal result
evaluateBinaryExpressionWithAsignment("div", expression);
break;
case Types.INTDIV :
evaluateBinaryExpression("intdiv", expression);
break;
case Types.INTDIV_EQUAL :
evaluateBinaryExpressionWithAsignment("intdiv", expression);
break;
case Types.MOD :
evaluateBinaryExpression("mod", expression);
break;
case Types.MOD_EQUAL :
evaluateBinaryExpressionWithAsignment("mod", expression);
break;
case Types.POWER :
evaluateBinaryExpression("power", expression);
break;
case Types.POWER_EQUAL :
evaluateBinaryExpressionWithAsignment("power", expression);
break;
case Types.LEFT_SHIFT :
evaluateBinaryExpression("leftShift", expression);
break;
case Types.LEFT_SHIFT_EQUAL :
evaluateBinaryExpressionWithAsignment("leftShift", expression);
break;
case Types.RIGHT_SHIFT :
evaluateBinaryExpression("rightShift", expression);
break;
case Types.RIGHT_SHIFT_EQUAL :
evaluateBinaryExpressionWithAsignment("rightShift", expression);
break;
case Types.RIGHT_SHIFT_UNSIGNED :
evaluateBinaryExpression("rightShiftUnsigned", expression);
break;
case Types.RIGHT_SHIFT_UNSIGNED_EQUAL :
evaluateBinaryExpressionWithAsignment("rightShiftUnsigned", expression);
break;
case Types.KEYWORD_INSTANCEOF :
evaluateInstanceof(expression);
break;
case Types.FIND_REGEX :
evaluateBinaryExpression(findRegexMethod, expression);
break;
case Types.MATCH_REGEX :
evaluateBinaryExpression(matchRegexMethod, expression);
break;
case Types.LEFT_SQUARE_BRACKET :
if (leftHandExpression) {
throwException("Should not be called here. Possible reason: postfix operation on array.");
// This is handled right now in the evaluateEqual()
// should support this here later
//evaluateBinaryExpression("putAt", expression);
} else {
evaluateBinaryExpression("getAt", expression);
}
break;
default :
throwException("Operation: " + expression.getOperation() + " not supported");
}
}
private void load(Expression exp) {
boolean wasLeft = leftHandExpression;
leftHandExpression = false;
// if (CREATE_DEBUG_INFO)
// helper.mark("-- loading expression: " + exp.getClass().getName() +
// " at [" + exp.getLineNumber() + ":" + exp.getColumnNumber() + "]");
//exp.visit(this);
visitAndAutoboxBoolean(exp);
// if (CREATE_DEBUG_INFO)
// helper.mark(" -- end of loading --");
leftHandExpression = wasLeft;
}
public void visitPostfixExpression(PostfixExpression expression) {
switch (expression.getOperation().getType()) {
case Types.PLUS_PLUS :
evaluatePostfixMethod("next", expression.getExpression());
break;
case Types.MINUS_MINUS :
evaluatePostfixMethod("previous", expression.getExpression());
break;
}
}
// store the data on the stack to the expression (variablem, property, field, etc.
private void store(Expression expression) {
if (expression instanceof BinaryExpression) {
throwException("BinaryExpression appeared on LHS. ");
}
if (ASM_DEBUG) {
if (expression instanceof VariableExpression) {
helper.mark(((VariableExpression)expression).getName());
}
}
boolean wasLeft = leftHandExpression;
leftHandExpression = true;
expression.visit(this);
//evaluateExpression(expression);
leftHandExpression = wasLeft;
return;
}
private void throwException(String s) {
throw new RuntimeParserException(s, currentASTNode);
}
public void visitPrefixExpression(PrefixExpression expression) {
switch (expression.getOperation().getType()) {
case Types.PLUS_PLUS :
evaluatePrefixMethod("next", expression.getExpression());
break;
case Types.MINUS_MINUS :
evaluatePrefixMethod("previous", expression.getExpression());
break;
}
}
public void visitClosureExpression(ClosureExpression expression) {
ClassNode innerClass = createClosureClass(expression);
addInnerClass(innerClass);
String innerClassinternalName = BytecodeHelper.getClassInternalName(innerClass);
ClassNode owner = innerClass.getOuterClass();
passingClosureParams = true;
List constructors = innerClass.getDeclaredConstructors();
ConstructorNode node = (ConstructorNode) constructors.get(0);
Parameter[] localVariableParams = node.getParameters();
cv.visitTypeInsn(NEW, innerClassinternalName);
cv.visitInsn(DUP);
if (isStaticMethod() || classNode.isStaticClass()) {
visitClassExpression(new ClassExpression(owner));
}
else {
loadThisOrOwner();
}
if (innerClass.getSuperClass()==ClassHelper.CLOSURE_TYPE) {
if (isStaticMethod()) {
/**
* todo could maybe stash this expression in a JVM variable
* from previous statement above
*/
visitClassExpression(new ClassExpression(owner));
}
else {
cv.visitVarInsn(ALOAD, 0);
}
}
// now lets load the various parameters we're passing
// we start at index 2 because the first 2 variables we pass
// are always the delegate and the outer instance and at this
// point they are already on the stack
for (int i = 2; i < localVariableParams.length; i++) {
Parameter param = localVariableParams[i];
String name = param.getName();
if (compileStack.getScope().isReferencedClassVariable(name)) {
visitFieldExpression(new FieldExpression(classNode.getField(name)));
} else {
Variable v = compileStack.getVariable(name,classNode.getSuperClass()!=ClassHelper.CLOSURE_TYPE);
if (v==null) {
// variable is not on stack because we are
// inside a nested Closure and this variable
// was not used before
// then load it from the Closure field
FieldNode field = classNode.getField(name);
cv.visitVarInsn(ALOAD, 0);
cv.visitFieldInsn(GETFIELD, internalClassName, name, BytecodeHelper.getTypeDescription(field.getType()));
// and define it
// Note:
// we can simply define it here and don't have to
// be afraid about name problems because a second
// variable with that name is not allowed inside the closure
param.setClosureSharedVariable(false);
v = compileStack.defineVariable(param,true);
param.setClosureSharedVariable(true);
v.setHolder(true);
}
cv.visitVarInsn(ALOAD, v.getIndex());
}
}
passingClosureParams = false;
// we may need to pass in some other constructors
//cv.visitMethodInsn(INVOKESPECIAL, innerClassinternalName, "<init>", prototype + ")V");
cv.visitMethodInsn(
INVOKESPECIAL,
innerClassinternalName,
"<init>",
BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, localVariableParams));
}
/**
* Loads either this object or if we're inside a closure then load the top level owner
*/
protected void loadThisOrOwner() {
if (isInnerClass()) {
visitFieldExpression(new FieldExpression(classNode.getField("owner")));
}
else {
cv.visitVarInsn(ALOAD, 0);
}
}
public void visitRegexExpression(RegexExpression expression) {
expression.getRegex().visit(this);
regexPattern.call(cv);
}
public void visitConstantExpression(ConstantExpression expression) {
Object value = expression.getValue();
helper.loadConstant(value);
}
public void visitSpreadExpression(SpreadExpression expression) {
Expression subExpression = expression.getExpression();
subExpression.visit(this);
spreadList.call(cv);
}
public void visitSpreadMapExpression(SpreadMapExpression expression) {
Expression subExpression = expression.getExpression();
subExpression.visit(this);
spreadMap.call(cv);
}
public void visitMethodPointerExpression(MethodPointerExpression expression) {
Expression subExpression = expression.getExpression();
subExpression.visit(this);
helper.loadConstant(expression.getMethodName());
getMethodPointer.call(cv);
}
public void visitNegationExpression(NegationExpression expression) {
Expression subExpression = expression.getExpression();
subExpression.visit(this);
negation.call(cv);
}
public void visitBitwiseNegExpression(BitwiseNegExpression expression) {
Expression subExpression = expression.getExpression();
subExpression.visit(this);
bitNegation.call(cv);
}
public void visitCastExpression(CastExpression expression) {
ClassNode type = expression.getType();
visitAndAutoboxBoolean(expression.getExpression());
doConvertAndCast(type, expression.getExpression(), expression.isIgnoringAutoboxing(),false);
}
public void visitNotExpression(NotExpression expression) {
Expression subExpression = expression.getExpression();
subExpression.visit(this);
// This is not the best way to do this. Javac does it by reversing the
// underlying expressions but that proved
// fairly complicated for not much gain. Instead we'll just use a
// utility function for now.
if (isComparisonExpression(expression.getExpression())) {
notBoolean.call(cv);
}
else {
notObject.call(cv);
}
}
/**
* return a primitive boolean value of the BooleanExpresion.
* @param expression
*/
public void visitBooleanExpression(BooleanExpression expression) {
compileStack.pushBooleanExpression();
expression.getExpression().visit(this);
if (!isComparisonExpression(expression.getExpression())) {
// comment out for optimization when boolean values are not autoboxed for eg. function calls.
// Class typeClass = expression.getExpression().getTypeClass();
// if (typeClass != null && typeClass != boolean.class) {
asBool.call(cv); // to return a primitive boolean
}
compileStack.pop();
}
private void prepareMethodcallObjectAndName(Expression objectExpression, boolean objectExpressionIsMethodName, String method) {
if (objectExpressionIsMethodName) {
VariableExpression.THIS_EXPRESSION.visit(this);
objectExpression.visit(this);
} else {
objectExpression.visit(this);
cv.visitLdcInsn(method);
}
}
public void visitMethodCallExpression(MethodCallExpression call) {
onLineNumber(call, "visitMethodCallExpression: \"" + call.getMethod() + "\":");
this.leftHandExpression = false;
Expression arguments = call.getArguments();
/*
* if (arguments instanceof TupleExpression) { TupleExpression
* tupleExpression = (TupleExpression) arguments; int size =
* tupleExpression.getExpressions().size(); if (size == 0) { arguments =
* ConstantExpression.EMPTY_ARRAY; } }
*/
boolean superMethodCall = MethodCallExpression.isSuperMethodCall(call);
String method = call.getMethod();
if (superMethodCall && method.equals("<init>")) {
/** todo handle method types! */
cv.visitVarInsn(ALOAD, 0);
if (isInClosureConstructor()) { // br use the second param to init the super class (Closure)
cv.visitVarInsn(ALOAD, 2);
cv.visitMethodInsn(INVOKESPECIAL, internalBaseClassName, "<init>", "(Ljava/lang/Object;)V");
}
else {
cv.visitVarInsn(ALOAD, 1);
cv.visitMethodInsn(INVOKESPECIAL, internalBaseClassName, "<init>", "(Ljava/lang/Object;)V");
}
}
else {
// are we a local variable
if (isThisExpression(call.getObjectExpression()) && isFieldOrVariable(method) && ! classNode.hasPossibleMethod(method, arguments)) {
/*
* if (arguments instanceof TupleExpression) { TupleExpression
* tupleExpression = (TupleExpression) arguments; int size =
* tupleExpression.getExpressions().size(); if (size == 1) {
* arguments = (Expression)
* tupleExpression.getExpressions().get(0); } }
*/
// lets invoke the closure method
visitVariableExpression(new VariableExpression(method));
arguments.visit(this);
invokeClosureMethod.call(cv);
} else {
if (superMethodCall) {
if (method.equals("super") || method.equals("<init>")) {
ConstructorNode superConstructorNode = findSuperConstructor(call);
cv.visitVarInsn(ALOAD, 0);
loadArguments(superConstructorNode.getParameters(), arguments);
String descriptor = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, superConstructorNode.getParameters());
cv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(classNode.getSuperClass()), "<init>", descriptor);
}
else {
MethodNode superMethodNode = findSuperMethod(call);
cv.visitVarInsn(ALOAD, 0);
loadArguments(superMethodNode.getParameters(), arguments);
String descriptor = BytecodeHelper.getMethodDescriptor(superMethodNode.getReturnType(), superMethodNode.getParameters());
cv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(superMethodNode.getDeclaringClass()), method, descriptor);
}
}
else {
Expression objectExpression = call.getObjectExpression();
boolean objectExpressionIsMethodName = false;
if (method.equals("call")) {
if (objectExpression instanceof GStringExpression) {
objectExpressionIsMethodName=true;
objectExpression = new CastExpression(ClassHelper.STRING_TYPE, objectExpression);
} else if (objectExpression instanceof ConstantExpression) {
Object value = ((ConstantExpression) objectExpression).getValue();
if ( value != null && value instanceof String) objectExpressionIsMethodName=true;
}
}
if (emptyArguments(arguments) && !call.isSafe() && !call.isSpreadSafe()) {
prepareMethodcallObjectAndName(objectExpression, objectExpressionIsMethodName,method);
invokeNoArgumentsMethod.call(cv);
} else {
if (argumentsUseStack(arguments)) {
arguments.visit(this);
int paramIdx = compileStack.defineTemporaryVariable(method + "_arg",true);
prepareMethodcallObjectAndName(objectExpression, objectExpressionIsMethodName,method);
cv.visitVarInsn(ALOAD, paramIdx);
compileStack.removeVar(paramIdx);
} else {
prepareMethodcallObjectAndName(objectExpression, objectExpressionIsMethodName,method);
arguments.visit(this);
}
if (call.isSpreadSafe()) {
invokeMethodSpreadSafeMethod.call(cv);
}
else if (call.isSafe()) {
invokeMethodSafeMethod.call(cv);
}
else {
invokeMethodMethod.call(cv);
}
}
}
}
}
}
/**
* Loads and coerces the argument values for the given method call
*/
protected void loadArguments(Parameter[] parameters, Expression expression) {
TupleExpression argListExp = (TupleExpression) expression;
List arguments = argListExp.getExpressions();
for (int i = 0, size = arguments.size(); i < size; i++) {
Expression argExp = argListExp.getExpression(i);
Parameter param = parameters[i];
visitAndAutoboxBoolean(argExp);
ClassNode type = param.getType();
ClassNode expType = getExpressionType(argExp);
if (!type.equals(expType)) {
doConvertAndCast(type);
}
}
}
/**
* Attempts to find the method of the given name in a super class
*/
protected MethodNode findSuperMethod(MethodCallExpression call) {
String methodName = call.getMethod();
TupleExpression argExpr = (TupleExpression) call.getArguments();
int argCount = argExpr.getExpressions().size();
ClassNode superClassNode = classNode.getSuperClass();
if (superClassNode != null) {
List methods = superClassNode.getMethods(methodName);
for (Iterator iter = methods.iterator(); iter.hasNext(); ) {
MethodNode method = (MethodNode) iter.next();
if (method.getParameters().length == argCount) {
return method;
}
}
}
throwException("No such method: " + methodName + " for class: " + classNode.getName());
return null; // should not come here
}
/**
* Attempts to find the constructor in a super class
*/
protected ConstructorNode findSuperConstructor(MethodCallExpression call) {
TupleExpression argExpr = (TupleExpression) call.getArguments();
int argCount = argExpr.getExpressions().size();
ClassNode superClassNode = classNode.getSuperClass();
if (superClassNode != null) {
List constructors = superClassNode.getDeclaredConstructors();
for (Iterator iter = constructors.iterator(); iter.hasNext(); ) {
ConstructorNode constructor = (ConstructorNode) iter.next();
if (constructor.getParameters().length == argCount) {
return constructor;
}
}
}
throwException("No such constructor for class: " + classNode.getName());
return null; // should not come here
}
protected boolean emptyArguments(Expression arguments) {
if (arguments instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) arguments;
int size = tupleExpression.getExpressions().size();
return size == 0;
}
return false;
}
public void visitStaticMethodCallExpression(StaticMethodCallExpression call) {
this.leftHandExpression = false;
Expression arguments = call.getArguments();
if (emptyArguments(arguments)) {
cv.visitLdcInsn(call.getOwnerType().getName());
cv.visitLdcInsn(call.getMethod());
invokeStaticNoArgumentsMethod.call(cv);
}
else {
if (arguments instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) arguments;
int size = tupleExpression.getExpressions().size();
if (size == 1) {
arguments = (Expression) tupleExpression.getExpressions().get(0);
}
}
cv.visitLdcInsn(call.getOwnerType().getName());
cv.visitLdcInsn(call.getMethod());
arguments.visit(this);
invokeStaticMethodMethod.call(cv);
}
}
public void visitConstructorCallExpression(ConstructorCallExpression call) {
onLineNumber(call, "visitConstructorCallExpression: \"" + call.getType().getName() + "\":");
this.leftHandExpression = false;
Expression arguments = call.getArguments();
if (arguments instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) arguments;
int size = tupleExpression.getExpressions().size();
if (size == 0) {
arguments = null;
}
}
// lets check that the type exists
ClassNode type = call.getType();
if (this.classNode != null) {
// TODO: GROOVY-435
pushClassTypeArgument(this.classNode, this.classNode);
pushClassTypeArgument(this.classNode, type);
if (arguments != null) {
arguments.visit(this);
invokeConstructorAtMethod.call(cv);
} else {
invokeNoArgumentsConstructorAt.call(cv);
}
}
else {
pushClassTypeArgument(this.classNode, type);
if (arguments !=null) {
arguments.visit(this);
invokeConstructorOfMethod.call(cv);
} else {
invokeNoArgumentsConstructorOf.call(cv);
}
}
}
private static String getStaticFieldName(ClassNode type) {
ClassNode componentType = type;
String prefix = "";
for (; componentType.isArray(); componentType=componentType.getComponentType()){
prefix+="$";
}
if (prefix.length()!=0) prefix = "array"+prefix;
String name = prefix+"class$" + BytecodeHelper.getClassInternalName(componentType).replace('/', '$').replace(';', ' ');
return name;
}
protected void pushClassTypeArgument(ClassNode ownerType, ClassNode type) {
String name = type.getName();
String staticFieldName = getStaticFieldName(type);
String ownerName = ownerType.getName().replace('.','/');
syntheticStaticFields.add(staticFieldName);
cv.visitFieldInsn(GETSTATIC, ownerName, staticFieldName, "Ljava/lang/Class;");
Label l0 = new Label();
cv.visitJumpInsn(IFNONNULL, l0);
cv.visitLdcInsn(name);
cv.visitMethodInsn(INVOKESTATIC, ownerName, "class$", "(Ljava/lang/String;)Ljava/lang/Class;");
cv.visitInsn(DUP);
cv.visitFieldInsn(PUTSTATIC, ownerName, staticFieldName, "Ljava/lang/Class;");
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
cv.visitFieldInsn(GETSTATIC, ownerName, staticFieldName, "Ljava/lang/Class;");
cv.visitLabel(l1);
}
public void visitPropertyExpression(PropertyExpression expression) {
Expression objectExpression = expression.getObjectExpression();
if (isThisExpression(objectExpression)) {
// lets use the field expression if its available
String name = expression.getProperty();
FieldNode field = classNode.getField(name);
if (field != null) {
visitFieldExpression(new FieldExpression(field));
return;
}
}
// we need to clear the LHS flag to avoid "this." evaluating as ASTORE
// rather than ALOAD
boolean left = leftHandExpression;
leftHandExpression = false;
objectExpression.visit(this);
leftHandExpression = left;
cv.visitLdcInsn(expression.getProperty());
if (isGroovyObject(objectExpression) && ! expression.isSafe()) {
if (left) {
setGroovyObjectPropertyMethod.call(cv);
}
else {
getGroovyObjectPropertyMethod.call(cv);
}
}
else {
if (expression.isSafe()) {
if (left) {
setPropertySafeMethod2.call(cv);
}
else {
if (expression.isSpreadSafe()) {
getPropertySpreadSafeMethod.call(cv);
}
else {
getPropertySafeMethod.call(cv);
}
}
}
else {
if (left) {
setPropertyMethod2.call(cv);
}
else {
getPropertyMethod.call(cv);
}
}
}
}
public void visitAttributeExpression(AttributeExpression expression) {
Expression objectExpression = expression.getObjectExpression();
if (isThisExpression(objectExpression)) {
// lets use the field expression if its available
String name = expression.getProperty();
FieldNode field = classNode.getField(name);
if (field != null) {
visitFieldExpression(new FieldExpression(field));
return;
}
}
// we need to clear the LHS flag to avoid "this." evaluating as ASTORE
// rather than ALOAD
boolean left = leftHandExpression;
leftHandExpression = false;
objectExpression.visit(this);
leftHandExpression = left;
cv.visitLdcInsn(expression.getProperty());
if (expression.isSafe()) {
if (left) {
setAttributeSafeMethod2.call(cv);
}
else {
if (expression.isSpreadSafe()) {
getAttributeSpreadSafeMethod.call(cv);
}
else {
getAttributeSafeMethod.call(cv);
}
}
}
else {
if (left) {
setAttributeMethod2.call(cv);
}
else {
getAttributeMethod.call(cv);
}
}
}
protected boolean isGroovyObject(Expression objectExpression) {
return isThisExpression(objectExpression);
}
public void visitFieldExpression(FieldExpression expression) {
FieldNode field = expression.getField();
if (field.isStatic()) {
if (leftHandExpression) {
storeStaticField(expression);
}
else {
loadStaticField(expression);
}
} else {
if (leftHandExpression) {
storeThisInstanceField(expression);
}
else {
loadInstanceField(expression);
}
}
}
/**
*
* @param fldExp
*/
public void loadStaticField(FieldExpression fldExp) {
FieldNode field = fldExp.getField();
boolean holder = field.isHolder() && !isInClosureConstructor();
ClassNode type = field.getType();
String ownerName = (field.getOwner().equals(classNode))
? internalClassName
: BytecodeHelper.getClassInternalName(field.getOwner());
if (holder) {
cv.visitFieldInsn(GETSTATIC, ownerName, fldExp.getFieldName(), BytecodeHelper.getTypeDescription(type));
cv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;");
}
else {
cv.visitFieldInsn(GETSTATIC, ownerName, fldExp.getFieldName(), BytecodeHelper.getTypeDescription(type));
if (ClassHelper.isPrimitiveType(type)) {
helper.box(type);
} else {
}
}
}
/**
* RHS instance field. should move most of the code in the BytecodeHelper
* @param fldExp
*/
public void loadInstanceField(FieldExpression fldExp) {
FieldNode field = fldExp.getField();
boolean holder = field.isHolder() && !isInClosureConstructor();
ClassNode type = field.getType();
String ownerName = (field.getOwner().equals(classNode))
? internalClassName
: helper.getClassInternalName(field.getOwner());
cv.visitVarInsn(ALOAD, 0);
cv.visitFieldInsn(GETFIELD, ownerName, fldExp.getFieldName(), BytecodeHelper.getTypeDescription(type));
if (holder) {
cv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;");
} else {
if (ClassHelper.isPrimitiveType(type)) {
helper.box(type);
} else {
}
}
}
public void storeThisInstanceField(FieldExpression expression) {
FieldNode field = expression.getField();
boolean holder = field.isHolder() && !isInClosureConstructor();
ClassNode type = field.getType();
String ownerName = (field.getOwner().equals(classNode)) ?
internalClassName : BytecodeHelper.getClassInternalName(field.getOwner());
if (holder) {
cv.visitVarInsn(ALOAD, 0);
cv.visitFieldInsn(GETFIELD, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(type));
cv.visitInsn(SWAP);
cv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "set", "(Ljava/lang/Object;)V");
}
else {
if (isInClosureConstructor()) {
helper.doCast(type);
}
else {
doConvertAndCast(type);
}
helper.loadThis();
helper.swapObjectWith(type);
helper.putField(field, ownerName);
}
}
public void storeStaticField(FieldExpression expression) {
FieldNode field = expression.getField();
boolean holder = field.isHolder() && !isInClosureConstructor();
ClassNode type = field.getType();
String ownerName = (field.getOwner().equals(classNode))
? internalClassName
: helper.getClassInternalName(field.getOwner());
if (holder) {
cv.visitFieldInsn(GETSTATIC, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(type));
cv.visitInsn(SWAP);
cv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "set", "(Ljava/lang/Object;)V");
}
else {
if (isInClosureConstructor()) {
helper.doCast(type);
}
else {
// this may be superfluous
//doConvertAndCast(type);
// use weaker cast
helper.doCast(type);
}
cv.visitFieldInsn(PUTSTATIC, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(type));
}
}
protected void visitOuterFieldExpression(FieldExpression expression, ClassNode outerClassNode, int steps, boolean first ) {
FieldNode field = expression.getField();
boolean isStatic = field.isStatic();
int tempIdx = compileStack.defineTemporaryVariable(field, leftHandExpression && first);
if (steps > 1 || !isStatic) {
cv.visitVarInsn(ALOAD, 0);
cv.visitFieldInsn(
GETFIELD,
internalClassName,
"owner",
BytecodeHelper.getTypeDescription(outerClassNode));
}
if( steps == 1 ) {
int opcode = (leftHandExpression) ? ((isStatic) ? PUTSTATIC : PUTFIELD) : ((isStatic) ? GETSTATIC : GETFIELD);
String ownerName = BytecodeHelper.getClassInternalName(outerClassNode);
if (leftHandExpression) {
cv.visitVarInsn(ALOAD, tempIdx);
boolean holder = field.isHolder() && !isInClosureConstructor();
if ( !holder) {
doConvertAndCast(field.getType());
}
}
cv.visitFieldInsn(opcode, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(field.getType()));
if (!leftHandExpression) {
if (ClassHelper.isPrimitiveType(field.getType())) {
helper.box(field.getType());
}
}
}
else {
visitOuterFieldExpression( expression, outerClassNode.getOuterClass(), steps - 1, false );
}
}
/**
* Visits a bare (unqualified) variable expression.
*/
public void visitVariableExpression(VariableExpression expression) {
String variableName = expression.getName();
// SPECIAL CASES
// "this" for static methods is the Class instance
if (isStaticMethod() && variableName.equals("this")) {
visitClassExpression(new ClassExpression(classNode));
return; // <<< FLOW CONTROL <<<<<<<<<
}
// "super" also requires special handling
if (variableName.equals("super")) {
visitClassExpression(new ClassExpression(classNode.getSuperClass()));
return; // <<< FLOW CONTROL <<<<<<<<<
}
Variable variable = compileStack.getVariable(variableName, false);
VariableScope scope = compileStack.getScope();
if (variable==null) {
processClassVariable(variableName);
} else {
processStackVariable(variable);
}
}
protected void processStackVariable(Variable variable) {
if( leftHandExpression ) {
helper.storeVar(variable);
} else {
helper.loadVar(variable);
}
if (ASM_DEBUG) {
helper.mark("var: " + variable.getName());
}
}
protected void processClassVariable(String name) {
if (passingClosureParams && isInScriptBody() ) {
// lets create a ScriptReference to pass into the closure
cv.visitTypeInsn(NEW, "org/codehaus/groovy/runtime/ScriptReference");
cv.visitInsn(DUP);
loadThisOrOwner();
cv.visitLdcInsn(name);
cv.visitMethodInsn(
INVOKESPECIAL,
"org/codehaus/groovy/runtime/ScriptReference",
"<init>",
"(Lgroovy/lang/Script;Ljava/lang/String;)V");
}
else {
visitPropertyExpression(new PropertyExpression(VariableExpression.THIS_EXPRESSION, name));
}
}
protected void processFieldAccess( String name, FieldNode field, int steps ) {
FieldExpression expression = new FieldExpression(field);
if( steps == 0 ) {
visitFieldExpression( expression );
}
else {
visitOuterFieldExpression( expression, classNode.getOuterClass(), steps, true );
}
}
/**
* @return true if we are in a script body, where all variables declared are no longer
* local variables but are properties
*/
protected boolean isInScriptBody() {
if (classNode.isScriptBody()) {
return true;
}
else {
return classNode.isScript() && methodNode != null && methodNode.getName().equals("run");
}
}
/**
* @return true if this expression will have left a value on the stack
* that must be popped
*/
protected boolean isPopRequired(Expression expression) {
if (expression instanceof MethodCallExpression) {
if (expression.getType()==ClassHelper.VOID_TYPE) { // nothing on the stack
return false;
} else {
return !MethodCallExpression.isSuperMethodCall((MethodCallExpression) expression);
}
}
if (expression instanceof DeclarationExpression) {
return false;
}
if (expression instanceof BinaryExpression) {
BinaryExpression binExp = (BinaryExpression) expression;
switch (binExp.getOperation().getType()) { // br todo should leave a copy of the value on the stack for all the assignemnt.
// case Types.EQUAL : // br a copy of the right value is left on the stack (see evaluateEqual()) so a pop is required for a standalone assignment
// case Types.PLUS_EQUAL : // this and the following are related to evaluateBinaryExpressionWithAsignment()
// case Types.MINUS_EQUAL :
// case Types.MULTIPLY_EQUAL :
// case Types.DIVIDE_EQUAL :
// case Types.INTDIV_EQUAL :
// case Types.MOD_EQUAL :
// return false;
}
}
return true;
}
protected boolean firstStatementIsSuperInit(Statement code) {
ExpressionStatement expStmt = null;
if (code instanceof ExpressionStatement) {
expStmt = (ExpressionStatement) code;
}
else if (code instanceof BlockStatement) {
BlockStatement block = (BlockStatement) code;
if (!block.getStatements().isEmpty()) {
Object expr = block.getStatements().get(0);
if (expr instanceof ExpressionStatement) {
expStmt = (ExpressionStatement) expr;
}
}
}
if (expStmt != null) {
Expression expr = expStmt.getExpression();
if (expr instanceof MethodCallExpression) {
MethodCallExpression call = (MethodCallExpression) expr;
if (MethodCallExpression.isSuperMethodCall(call)) {
// not sure which one is constantly used as the super class ctor call. To cover both for now
return call.getMethod().equals("<init>") || call.getMethod().equals("super");
}
}
}
return false;
}
protected void createSyntheticStaticFields() {
for (Iterator iter = syntheticStaticFields.iterator(); iter.hasNext();) {
String staticFieldName = (String) iter.next();
// generate a field node
cw.visitField(ACC_STATIC + ACC_SYNTHETIC, staticFieldName, "Ljava/lang/Class;", null, null);
}
if (!syntheticStaticFields.isEmpty()) {
cv =
cw.visitMethod(
ACC_STATIC + ACC_SYNTHETIC,
"class$",
"(Ljava/lang/String;)Ljava/lang/Class;",
null,
null);
helper = new BytecodeHelper(cv);
Label l0 = new Label();
cv.visitLabel(l0);
cv.visitVarInsn(ALOAD, 0);
cv.visitMethodInsn(INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;");
Label l1 = new Label();
cv.visitLabel(l1);
cv.visitInsn(ARETURN);
Label l2 = new Label();
cv.visitLabel(l2);
cv.visitVarInsn(ASTORE, 1);
cv.visitTypeInsn(NEW, "java/lang/NoClassDefFoundError");
cv.visitInsn(DUP);
cv.visitVarInsn(ALOAD, 1);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/ClassNotFoundException", "getMessage", "()Ljava/lang/String;");
cv.visitMethodInsn(INVOKESPECIAL, "java/lang/NoClassDefFoundError", "<init>", "(Ljava/lang/String;)V");
cv.visitInsn(ATHROW);
cv.visitTryCatchBlock(l0, l2, l2, "java/lang/ClassNotFoundException"); // br using l2 as the 2nd param seems create the right table entry
cv.visitMaxs(3, 2);
cw.visitEnd();
}
}
/** load class object on stack */
public void visitClassExpression(ClassExpression expression) {
ClassNode type = expression.getType();
//type = checkValidType(type, expression, "Must be a valid type name for a constructor call");
if (ClassHelper.isPrimitiveType(type)) {
ClassNode objectType = ClassHelper.getWrapper(type);
cv.visitFieldInsn(GETSTATIC, BytecodeHelper.getClassInternalName(objectType), "TYPE", "Ljava/lang/Class;");
}
else {
final String staticFieldName =
(type.equals(classNode)) ? "class$0" : getStaticFieldName(type);
syntheticStaticFields.add(staticFieldName);
cv.visitFieldInsn(GETSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;");
Label l0 = new Label();
cv.visitJumpInsn(IFNONNULL, l0);
cv.visitLdcInsn(type.getName());
cv.visitMethodInsn(INVOKESTATIC, internalClassName, "class$", "(Ljava/lang/String;)Ljava/lang/Class;");
cv.visitInsn(DUP);
cv.visitFieldInsn(PUTSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;");
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
cv.visitFieldInsn(GETSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;");
cv.visitLabel(l1);
}
}
public void visitRangeExpression(RangeExpression expression) {
leftHandExpression = false;
expression.getFrom().visit(this);
leftHandExpression = false;
expression.getTo().visit(this);
helper.pushConstant(expression.isInclusive());
createRangeMethod.call(cv);
}
public void visitMapEntryExpression(MapEntryExpression expression) {
}
public void visitMapExpression(MapExpression expression) {
List entries = expression.getMapEntryExpressions();
int size = entries.size();
helper.pushConstant(size * 2);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
int i = 0;
for (Iterator iter = entries.iterator(); iter.hasNext();) {
Object object = iter.next();
MapEntryExpression entry = (MapEntryExpression) object;
cv.visitInsn(DUP);
helper.pushConstant(i++);
visitAndAutoboxBoolean(entry.getKeyExpression());
cv.visitInsn(AASTORE);
cv.visitInsn(DUP);
helper.pushConstant(i++);
visitAndAutoboxBoolean(entry.getValueExpression());
cv.visitInsn(AASTORE);
}
createMapMethod.call(cv);
}
public void visitTupleExpression(TupleExpression expression) {
int size = expression.getExpressions().size();
helper.pushConstant(size);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
for (int i = 0; i < size; i++) {
cv.visitInsn(DUP);
helper.pushConstant(i);
visitAndAutoboxBoolean(expression.getExpression(i));
cv.visitInsn(AASTORE);
}
}
public void visitArrayExpression(ArrayExpression expression) {
ClassNode elementType = expression.getElementType();
String arrayTypeName = BytecodeHelper.getClassInternalName(elementType);
List sizeExpression = expression.getSizeExpression();
int size=0;
int dimensions=0;
if (sizeExpression!=null) {
for (Iterator iter = sizeExpression.iterator(); iter.hasNext();) {
Expression element = (Expression) iter.next();
if (element==ConstantExpression.EMTPY_EXPRESSION) break;
dimensions++;
// lets convert to an int
visitAndAutoboxBoolean(element);
asIntMethod.call(cv);
}
} else {
size = expression.getExpressions().size();
helper.pushConstant(size);
}
int storeIns=AASTORE;
if (sizeExpression!=null) {
arrayTypeName = BytecodeHelper.getTypeDescription(expression.getType());
cv.visitMultiANewArrayInsn(arrayTypeName, dimensions);
} else if (ClassHelper.isPrimitiveType(elementType)) {
int primType=0;
if (elementType==ClassHelper.boolean_TYPE) {
primType = T_BOOLEAN;
storeIns = BASTORE;
} else if (elementType==ClassHelper.char_TYPE) {
primType = T_CHAR;
storeIns = CASTORE;
} else if (elementType==ClassHelper.float_TYPE) {
primType = T_FLOAT;
storeIns = FASTORE;
} else if (elementType==ClassHelper.double_TYPE) {
primType = T_DOUBLE;
storeIns = DASTORE;
} else if (elementType==ClassHelper.byte_TYPE) {
primType = T_BYTE;
storeIns = BASTORE;
} else if (elementType==ClassHelper.short_TYPE) {
primType = T_SHORT;
storeIns = SASTORE;
} else if (elementType==ClassHelper.int_TYPE) {
primType = T_INT;
storeIns=IASTORE;
} else if (elementType==ClassHelper.long_TYPE) {
primType = T_LONG;
storeIns = LASTORE;
}
cv.visitIntInsn(NEWARRAY, primType);
} else {
cv.visitTypeInsn(ANEWARRAY, arrayTypeName);
}
for (int i = 0; i < size; i++) {
cv.visitInsn(DUP);
helper.pushConstant(i);
Expression elementExpression = expression.getExpression(i);
if (elementExpression == null) {
ConstantExpression.NULL.visit(this);
} else {
if (!elementType.equals(elementExpression.getType())) {
visitCastExpression(new CastExpression(elementType, elementExpression, true));
} else {
visitAndAutoboxBoolean(elementExpression);
}
}
cv.visitInsn(storeIns);
}
if (sizeExpression==null && ClassHelper.isPrimitiveType(elementType)) {
int par = compileStack.defineTemporaryVariable("par",true);
cv.visitVarInsn(ALOAD, par);
}
}
public void visitListExpression(ListExpression expression) {
int size = expression.getExpressions().size();
helper.pushConstant(size);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
for (int i = 0; i < size; i++) {
cv.visitInsn(DUP);
helper.pushConstant(i);
visitAndAutoboxBoolean(expression.getExpression(i));
cv.visitInsn(AASTORE);
}
createListMethod.call(cv);
}
public void visitGStringExpression(GStringExpression expression) {
int size = expression.getValues().size();
helper.pushConstant(size);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
for (int i = 0; i < size; i++) {
cv.visitInsn(DUP);
helper.pushConstant(i);
visitAndAutoboxBoolean(expression.getValue(i));
cv.visitInsn(AASTORE);
}
int paramIdx = compileStack.defineTemporaryVariable("iterator",true);
ClassNode innerClass = createGStringClass(expression);
addInnerClass(innerClass);
String innerClassinternalName = BytecodeHelper.getClassInternalName(innerClass);
cv.visitTypeInsn(NEW, innerClassinternalName);
cv.visitInsn(DUP);
cv.visitVarInsn(ALOAD, paramIdx);
cv.visitMethodInsn(INVOKESPECIAL, innerClassinternalName, "<init>", "([Ljava/lang/Object;)V");
compileStack.removeVar(paramIdx);
}
public void visitAnnotations(AnnotatedNode node) {
Map annotionMap = node.getAnnotations();
if (annotionMap.isEmpty()) return;
Iterator it = annotionMap.values().iterator();
while (it.hasNext()) {
AnnotationNode an = (AnnotationNode) it.next();
//skip builtin properties
if (an.isBuiltIn()) continue;
ClassNode type = an.getClassNode();
String clazz = type.getName();
AnnotationVisitor av = cw.visitAnnotation(BytecodeHelper.formatNameForClassLoading(clazz),false);
Iterator mIt = an.getMembers().keySet().iterator();
while (mIt.hasNext()) {
String name = (String) mIt.next();
ConstantExpression exp = (ConstantExpression) an.getMember(name);
av.visit(name,exp.getValue());
}
av.visitEnd();
}
}
// Implementation methods
protected boolean addInnerClass(ClassNode innerClass) {
innerClass.setModule(classNode.getModule());
return innerClasses.add(innerClass);
}
protected ClassNode createClosureClass(ClosureExpression expression) {
ClassNode owner = getOutermostClass();
ClassNode outerClass = owner;
String name = owner.getName() + "$"
+ context.getNextClosureInnerName(owner, classNode, methodNode); // br added a more infomative name
boolean staticMethodOrInStaticClass = isStaticMethod() || classNode.isStaticClass();
if (staticMethodOrInStaticClass) {
outerClass = ClassHelper.make(Class.class);
}
Parameter[] parameters = expression.getParameters();
if (parameters==null){
parameters = new Parameter[0];
} else if (parameters.length == 0) {
// lets create a default 'it' parameter
parameters = new Parameter[] { new Parameter(ClassHelper.OBJECT_TYPE, "it", ConstantExpression.NULL)};
}
Parameter[] localVariableParams = getClosureSharedVariables(expression);
InnerClassNode answer = new InnerClassNode(owner, name, 0, ClassHelper.CLOSURE_TYPE); // closures are local inners and not public
answer.setEnclosingMethod(this.methodNode);
answer.setSynthetic(true);
if (staticMethodOrInStaticClass) {
answer.setStaticClass(true);
}
if (isInScriptBody()) {
answer.setScriptBody(true);
}
MethodNode method =
answer.addMethod("doCall", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, parameters, ClassNode.EMPTY_ARRAY, expression.getCode());
method.setSourcePosition(expression);
VariableScope varScope = expression.getVariableScope();
if (varScope == null) {
throw new RuntimeException(
"Must have a VariableScope by now! for expression: " + expression + " class: " + name);
} else {
method.setVariableScope(varScope.copy());
}
if (parameters.length > 1
|| (parameters.length == 1
&& parameters[0].getType() != null
&& parameters[0].getType() != ClassHelper.OBJECT_TYPE)) {
// lets add a typesafe call method
MethodNode call = answer.addMethod(
"call",
ACC_PUBLIC,
ClassHelper.OBJECT_TYPE,
parameters,
ClassNode.EMPTY_ARRAY,
new ReturnStatement(
new MethodCallExpression(
VariableExpression.THIS_EXPRESSION,
"doCall",
new ArgumentListExpression(parameters))));
call.setSourcePosition(expression);
}
FieldNode ownerField = answer.addField("owner", ACC_PRIVATE, outerClass, null);
ownerField.setSourcePosition(expression);
// lets make the constructor
BlockStatement block = new BlockStatement();
block.setSourcePosition(expression);
VariableExpression outer = new VariableExpression("_outerInstance");
outer.setSourcePosition(expression);
block.getVariableScope().getReferencedLocalVariables().put("_outerInstance",outer);
block.addStatement(
new ExpressionStatement(
new MethodCallExpression(
new VariableExpression("super"),
"<init>",
outer)));
block.addStatement(
new ExpressionStatement(
new BinaryExpression(
new FieldExpression(ownerField),
Token.newSymbol(Types.EQUAL, -1, -1),
outer)));
// lets assign all the parameter fields from the outer context
for (int i = 0; i < localVariableParams.length; i++) {
Parameter param = localVariableParams[i];
String paramName = param.getName();
Expression initialValue = null;
ClassNode type = param.getType();
FieldNode paramField = null;
if (true) {
initialValue = new VariableExpression(paramName);
ClassNode realType = type;
type = ClassHelper.makeReference();
param.setType(type);
paramField = answer.addField(paramName, ACC_PRIVATE, type, initialValue);
paramField.setHolder(true);
String methodName = Verifier.capitalize(paramName);
// lets add a getter & setter
Expression fieldExp = new FieldExpression(paramField);
answer.addMethod(
"get" + methodName,
ACC_PUBLIC,
realType,
Parameter.EMPTY_ARRAY,
ClassNode.EMPTY_ARRAY,
new ReturnStatement(fieldExp));
/*
answer.addMethod(
"set" + methodName,
ACC_PUBLIC,
"void",
new Parameter[] { new Parameter(realType, "__value") },
new ExpressionStatement(
new BinaryExpression(expression, Token.newSymbol(Types.EQUAL, 0, 0), new VariableExpression("__value"))));
*/
}
}
Parameter[] params = new Parameter[2 + localVariableParams.length];
params[0] = new Parameter(outerClass, "_outerInstance");
params[1] = new Parameter(ClassHelper.OBJECT_TYPE, "_delegate");
System.arraycopy(localVariableParams, 0, params, 2, localVariableParams.length);
ASTNode sn = answer.addConstructor(ACC_PUBLIC, params, ClassNode.EMPTY_ARRAY, block);
sn.setSourcePosition(expression);
return answer;
}
protected Parameter[] getClosureSharedVariables(ClosureExpression ce){
VariableScope scope = ce.getVariableScope();
Map references = scope.getReferencedLocalVariables();
Parameter[] ret = new Parameter[references.size()];
int index = 0;
for (Iterator iter = references.values().iterator(); iter.hasNext();) {
org.codehaus.groovy.ast.Variable element = (org.codehaus.groovy.ast.Variable) iter.next();
if (element instanceof Parameter) {
ret[index] = (Parameter) element;
} else {
Parameter p = new Parameter(element.getType(),element.getName());
ret[index] = p;
}
index++;
}
return ret;
}
protected ClassNode getOutermostClass() {
if (outermostClass == null) {
outermostClass = classNode;
while (outermostClass instanceof InnerClassNode) {
outermostClass = outermostClass.getOuterClass();
}
}
return outermostClass;
}
protected ClassNode createGStringClass(GStringExpression expression) {
ClassNode owner = classNode;
if (owner instanceof InnerClassNode) {
owner = owner.getOuterClass();
}
String outerClassName = owner.getName();
String name = outerClassName + "$" + context.getNextInnerClassIdx();
InnerClassNode answer = new InnerClassNode(owner, name, 0, ClassHelper.GSTRING_TYPE);
answer.setEnclosingMethod(this.methodNode);
FieldNode stringsField =
answer.addField(
"strings",
ACC_PRIVATE /*| ACC_STATIC*/,
ClassHelper.STRING_TYPE.makeArray(),
new ArrayExpression(ClassHelper.STRING_TYPE, expression.getStrings()));
answer.addMethod(
"getStrings",
ACC_PUBLIC,
ClassHelper.STRING_TYPE.makeArray(),
Parameter.EMPTY_ARRAY,
ClassNode.EMPTY_ARRAY,
new ReturnStatement(new FieldExpression(stringsField)));
// lets make the constructor
BlockStatement block = new BlockStatement();
block.addStatement(
new ExpressionStatement(
new MethodCallExpression(new VariableExpression("super"), "<init>", new VariableExpression("values"))));
Parameter[] contructorParams = new Parameter[] { new Parameter(ClassHelper.OBJECT_TYPE.makeArray(), "values")};
answer.addConstructor(ACC_PUBLIC, contructorParams, ClassNode.EMPTY_ARRAY, block);
return answer;
}
protected void doConvertAndCast(ClassNode type) {
if (type==ClassHelper.OBJECT_TYPE) return;
if (isValidTypeForCast(type)) {
visitClassExpression(new ClassExpression(type));
asTypeMethod.call(cv);
}
helper.doCast(type);
}
protected void evaluateLogicalOrExpression(BinaryExpression expression) {
visitBooleanExpression(new BooleanExpression(expression.getLeftExpression()));
Label l0 = new Label();
Label l2 = new Label();
cv.visitJumpInsn(IFEQ, l0);
cv.visitLabel(l2);
visitConstantExpression(ConstantExpression.TRUE);
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
visitBooleanExpression(new BooleanExpression(expression.getRightExpression()));
cv.visitJumpInsn(IFNE, l2);
visitConstantExpression(ConstantExpression.FALSE);
cv.visitLabel(l1);
}
// todo: optimization: change to return primitive boolean. need to adjust the BinaryExpression and isComparisonExpression for
// consistancy.
protected void evaluateLogicalAndExpression(BinaryExpression expression) {
visitBooleanExpression(new BooleanExpression(expression.getLeftExpression()));
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
visitBooleanExpression(new BooleanExpression(expression.getRightExpression()));
cv.visitJumpInsn(IFEQ, l0);
visitConstantExpression(ConstantExpression.TRUE);
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
visitConstantExpression(ConstantExpression.FALSE);
cv.visitLabel(l1);
}
protected void evaluateBinaryExpression(String method, BinaryExpression expression) {
Expression leftExpression = expression.getLeftExpression();
leftHandExpression = false;
leftExpression.visit(this);
cv.visitLdcInsn(method);
leftHandExpression = false;
new ArgumentListExpression(new Expression[] { expression.getRightExpression()}).visit(this);
// expression.getRightExpression().visit(this);
invokeMethodMethod.call(cv);
}
protected void evaluateCompareTo(BinaryExpression expression) {
Expression leftExpression = expression.getLeftExpression();
leftHandExpression = false;
leftExpression.visit(this);
if (isComparisonExpression(leftExpression)) {
helper.boxBoolean();
}
// if the right hand side is a boolean expression, we need to autobox
Expression rightExpression = expression.getRightExpression();
rightExpression.visit(this);
if (isComparisonExpression(rightExpression)) {
helper.boxBoolean();
}
compareToMethod.call(cv);
}
protected void evaluateBinaryExpressionWithAsignment(String method, BinaryExpression expression) {
Expression leftExpression = expression.getLeftExpression();
if (leftExpression instanceof BinaryExpression) {
BinaryExpression leftBinExpr = (BinaryExpression) leftExpression;
if (leftBinExpr.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) {
// lets replace this assignment to a subscript operator with a
// method call
// e.g. x[5] += 10
// -> (x, [], 5), =, x[5] + 10
// -> methodCall(x, "putAt", [5, methodCall(x[5], "plus", 10)])
MethodCallExpression methodCall =
new MethodCallExpression(
expression.getLeftExpression(),
method,
new ArgumentListExpression(new Expression[] { expression.getRightExpression()}));
Expression safeIndexExpr = createReusableExpression(leftBinExpr.getRightExpression());
visitMethodCallExpression(
new MethodCallExpression(
leftBinExpr.getLeftExpression(),
"putAt",
new ArgumentListExpression(new Expression[] { safeIndexExpr, methodCall })));
//cv.visitInsn(POP);
return;
}
}
evaluateBinaryExpression(method, expression);
// br to leave a copy of rvalue on the stack. see also isPopRequired()
cv.visitInsn(DUP);
leftHandExpression = true;
evaluateExpression(leftExpression);
leftHandExpression = false;
}
private void evaluateBinaryExpression(MethodCaller compareMethod, BinaryExpression bin) {
evalBinaryExp_LateBinding(compareMethod, bin);
}
protected void evalBinaryExp_LateBinding(MethodCaller compareMethod, BinaryExpression expression) {
Expression leftExp = expression.getLeftExpression();
Expression rightExp = expression.getRightExpression();
load(leftExp);
load(rightExp);
compareMethod.call(cv);
}
protected void evaluateEqual(BinaryExpression expression) {
Expression leftExpression = expression.getLeftExpression();
if (leftExpression instanceof BinaryExpression) {
BinaryExpression leftBinExpr = (BinaryExpression) leftExpression;
if (leftBinExpr.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) {
// lets replace this assignment to a subscript operator with a
// method call
// e.g. x[5] = 10
// -> (x, [], 5), =, 10
// -> methodCall(x, "putAt", [5, 10])
visitMethodCallExpression(
new MethodCallExpression(
leftBinExpr.getLeftExpression(),
"putAt",
new ArgumentListExpression(
new Expression[] { leftBinExpr.getRightExpression(), expression.getRightExpression()})));
// cv.visitInsn(POP); //this is realted to isPopRequired()
return;
}
}
// lets evaluate the RHS then hopefully the LHS will be a field
leftHandExpression = false;
Expression rightExpression = expression.getRightExpression();
ClassNode type = getLHSType(leftExpression);
// lets not cast for primitive types as we handle these in field setting etc
if (ClassHelper.isPrimitiveType(type)) {
rightExpression.visit(this);
} else {
if (type!=ClassHelper.OBJECT_TYPE){
visitCastExpression(new CastExpression(type, rightExpression));
} else {
visitAndAutoboxBoolean(rightExpression);
}
}
cv.visitInsn(DUP); // to leave a copy of the rightexpression value on the stack after the assignment.
leftHandExpression = true;
leftExpression.visit(this);
leftHandExpression = false;
}
/**
* Deduces the type name required for some casting
*
* @return the type of the given (LHS) expression or null if it is java.lang.Object or it cannot be deduced
*/
protected ClassNode getLHSType(Expression leftExpression) {
if (leftExpression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) leftExpression;
ClassNode type = varExp.getType();
if (isValidTypeForCast(type)) {
return type;
}
String variableName = varExp.getName();
Variable variable = compileStack.getVariable(variableName,false);
if (variable != null) {
if (variable.isHolder()) {
return type;
}
if (variable.isProperty()) return variable.getType();
type = variable.getType();
if (isValidTypeForCast(type)) {
return type;
}
}
else {
FieldNode field = classNode.getField(variableName);
if (field == null) {
field = classNode.getOuterField(variableName);
}
if (field != null) {
type = field.getType();
if (!field.isHolder() && isValidTypeForCast(type)) {
return type;
}
}
}
}
else if (leftExpression instanceof FieldExpression) {
FieldExpression fieldExp = (FieldExpression) leftExpression;
ClassNode type = fieldExp.getType();
if (isValidTypeForCast(type)) {
return type;
}
}
return ClassHelper.DYNAMIC_TYPE;
}
protected boolean isValidTypeForCast(ClassNode type) {
return type!=ClassHelper.DYNAMIC_TYPE && !type.getName().equals("groovy.lang.Reference");
}
protected void visitAndAutoboxBoolean(Expression expression) {
expression.visit(this);
if (isComparisonExpression(expression)) {
helper.boxBoolean(); // convert boolean to Boolean
}
}
protected void evaluatePrefixMethod(String method, Expression expression) {
if (isNonStaticField(expression) && ! isHolderVariable(expression) && !isStaticMethod()) {
cv.visitVarInsn(ALOAD, 0);
}
expression.visit(this);
cv.visitLdcInsn(method);
invokeNoArgumentsMethod.call(cv);
leftHandExpression = true;
expression.visit(this);
leftHandExpression = false;
expression.visit(this);
}
protected void evaluatePostfixMethod(String method, Expression expression) {
leftHandExpression = false;
expression.visit(this);
int tempIdx = compileStack.defineTemporaryVariable("postfix_" + method, true);
cv.visitVarInsn(ALOAD, tempIdx);
cv.visitLdcInsn(method);
invokeNoArgumentsMethod.call(cv);
store(expression);
cv.visitVarInsn(ALOAD, tempIdx);
compileStack.removeVar(tempIdx);
}
protected void evaluateInstanceof(BinaryExpression expression) {
expression.getLeftExpression().visit(this);
Expression rightExp = expression.getRightExpression();
ClassNode classType = ClassHelper.DYNAMIC_TYPE;
if (rightExp instanceof ClassExpression) {
ClassExpression classExp = (ClassExpression) rightExp;
classType = classExp.getType();
}
else {
throw new RuntimeException(
"Right hand side of the instanceof keyworld must be a class name, not: " + rightExp);
}
String classInternalName = BytecodeHelper.getClassInternalName(classType);
cv.visitTypeInsn(INSTANCEOF, classInternalName);
}
/**
* @return true if the given argument expression requires the stack, in
* which case the arguments are evaluated first, stored in the
* variable stack and then reloaded to make a method call
*/
protected boolean argumentsUseStack(Expression arguments) {
return arguments instanceof TupleExpression || arguments instanceof ClosureExpression;
}
/**
* @return true if the given expression represents a non-static field
*/
protected boolean isNonStaticField(Expression expression) {
FieldNode field = null;
if (expression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) expression;
field = classNode.getField(varExp.getName());
}
else if (expression instanceof FieldExpression) {
FieldExpression fieldExp = (FieldExpression) expression;
field = classNode.getField(fieldExp.getFieldName());
}
else if (expression instanceof PropertyExpression) {
PropertyExpression fieldExp = (PropertyExpression) expression;
field = classNode.getField(fieldExp.getProperty());
}
if (field != null) {
return !field.isStatic();
}
return false;
}
protected boolean isThisExpression(Expression expression) {
if (expression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) expression;
return varExp.getName().equals("this");
}
return false;
}
/**
* For assignment expressions, return a safe expression for the LHS we can use
* to return the value
*/
protected Expression createReturnLHSExpression(Expression expression) {
if (expression instanceof BinaryExpression) {
BinaryExpression binExpr = (BinaryExpression) expression;
if (binExpr.getOperation().isA(Types.ASSIGNMENT_OPERATOR)) {
return createReusableExpression(binExpr.getLeftExpression());
}
}
return null;
}
protected Expression createReusableExpression(Expression expression) {
ExpressionTransformer transformer = new ExpressionTransformer() {
public Expression transform(Expression expression) {
if (expression instanceof PostfixExpression) {
PostfixExpression postfixExp = (PostfixExpression) expression;
return postfixExp.getExpression();
}
else if (expression instanceof PrefixExpression) {
PrefixExpression prefixExp = (PrefixExpression) expression;
return prefixExp.getExpression();
}
return expression;
}
};
// could just be a postfix / prefix expression or nested inside some other expression
return transformer.transform(expression.transformExpression(transformer));
}
protected boolean isComparisonExpression(Expression expression) {
if (expression instanceof BinaryExpression) {
BinaryExpression binExpr = (BinaryExpression) expression;
switch (binExpr.getOperation().getType()) {
case Types.COMPARE_EQUAL :
case Types.MATCH_REGEX :
case Types.COMPARE_GREATER_THAN :
case Types.COMPARE_GREATER_THAN_EQUAL :
case Types.COMPARE_LESS_THAN :
case Types.COMPARE_LESS_THAN_EQUAL :
case Types.COMPARE_IDENTICAL :
case Types.COMPARE_NOT_EQUAL :
case Types.KEYWORD_INSTANCEOF :
return true;
}
}
else if (expression instanceof BooleanExpression) {
return true;
}
return false;
}
protected void onLineNumber(ASTNode statement, String message) {
int line = statement.getLineNumber();
int col = statement.getColumnNumber();
this.currentASTNode = statement;
if (line >=0) {
lineNumber = line;
columnNumber = col;
}
if (CREATE_LINE_NUMBER_INFO && line >= 0 && cv != null) {
Label l = new Label();
cv.visitLabel(l);
cv.visitLineNumber(line, l);
if (ASM_DEBUG) {
helper.mark(message + "[" + statement.getLineNumber() + ":" + statement.getColumnNumber() + "]");
}
}
}
protected boolean isNotFieldOfOutermostClass(String var) {
return getOutermostClass().getField(var) == null;
}
private boolean isInnerClass() {
return classNode instanceof InnerClassNode;
}
/** @return true if the given name is a local variable or a field */
protected boolean isFieldOrVariable(String name) {
return compileStack.containsVariable(name) || classNode.getField(name) != null;
}
/**
* @return if the type of the expression can be determined at compile time
* then this method returns the type - otherwise null
*/
protected ClassNode getExpressionType(Expression expression) {
if (isComparisonExpression(expression)) {
return ClassHelper.boolean_TYPE;
}
if (expression instanceof VariableExpression) {
VariableExpression varExpr = (VariableExpression) expression;
Variable variable = compileStack.getVariable(varExpr.getName(),false);
if (variable != null && !variable.isHolder()) {
ClassNode type = variable.getType();
if (! variable.isDynamicTyped()) return type;
}
if (variable == null) {
org.codehaus.groovy.ast.Variable var = (org.codehaus.groovy.ast.Variable) compileStack.getScope().getReferencedClassVariables().get(varExpr.getName());
if (var!=null && !var.isDynamicTyped()) return var.getType();
}
}
return expression.getType();
}
protected boolean isInClosureConstructor() {
return constructorNode != null
&& classNode.getOuterClass() != null
&& classNode.getSuperClass()==ClassHelper.CLOSURE_TYPE;
}
protected boolean isStaticMethod() {
if (methodNode == null) { // we're in a constructor
return false;
}
return methodNode.isStatic();
}
protected CompileUnit getCompileUnit() {
CompileUnit answer = classNode.getCompileUnit();
if (answer == null) {
answer = context.getCompileUnit();
}
return answer;
}
protected boolean isHolderVariable(Expression expression) {
if (expression instanceof FieldExpression) {
FieldExpression fieldExp = (FieldExpression) expression;
return fieldExp.getField().isHolder();
}
if (expression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) expression;
Variable variable = compileStack.getVariable(varExp.getName(),false);
if (variable != null) {
return variable.isHolder();
}
FieldNode field = classNode.getField(varExp.getName());
if (field != null) {
return field.isHolder();
}
}
return false;
}
} |
package cz.lamorak.wordgame;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import com.jakewharton.rxbinding2.view.RxView;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import cz.lamorak.wordgame.model.Word;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
public class GameActivity extends AppCompatActivity {
private static final int WORD_LIMIT = 3; // seconds
private CompositeDisposable disposables;
private Disposable wordTimerDisposable;
private PublishSubject<Boolean> guessSubject;
private AtomicBoolean gameStarted;
private List<Word> words;
private TextView countdown;
private TextView wordOriginal;
private TextView wordGuess;
private Button wrongButton;
private Button correctButton;
public static void call(final Context context) {
final Intent intent = new Intent(context, GameActivity.class);
context.startActivity(intent);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
disposables = new CompositeDisposable();
guessSubject = PublishSubject.create();
gameStarted = new AtomicBoolean(false);
countdown = (TextView) findViewById(R.id.countdown);
wordOriginal = (TextView) findViewById(R.id.word_original);
wordGuess = (TextView) findViewById(R.id.word_guess);
correctButton = (Button) findViewById(R.id.button_correct);
wrongButton = (Button) findViewById(R.id.button_wrong);
disposables.add(
WordGameApp.getServiceProvider()
.getWordService()
.loadWords()
.doOnNext(Collections::shuffle)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::startGame)
);
}
@Override
protected void onResume() {
super.onResume();
disposables.add(
RxView.clicks(wrongButton)
.map(o -> false)
.subscribe(guessSubject::onNext)
);
disposables.add(
RxView.clicks(correctButton)
.map(o -> true)
.subscribe(guessSubject::onNext)
);
disposables.add(
guessSubject.subscribe(aBoolean -> displayWord())
);
if (gameStarted.get()) {
displayWord();
}
}
@Override
protected void onPause() {
super.onPause();
disposables.clear();
}
private void startGame(final List<Word> words) {
this.words = words;
gameStarted.set(true);
displayWord();
}
private void displayWord() {
if (words.size() < 2) {
finishGame();
}
final Word word = words.remove(0);
wordOriginal.setText(word.getEngllishWord());
wordGuess.setText(word.getSpanishWord());
wordGuess.setTranslationY(0);
wordGuess.animate()
.translationY(1000)
.setDuration(3000L)
.start();
if (wordTimerDisposable != null && !wordTimerDisposable.isDisposed()) {
wordTimerDisposable.dispose();
}
wordTimerDisposable = Observable.timer(WORD_LIMIT, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(l -> guessSubject.onNext(false));
disposables.add(wordTimerDisposable);
}
} |
package org.json;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* A JSONArray is an ordered sequence of values. Its external text form is a
* string wrapped in square brackets with commas separating the values. The
* internal form is an object having <code>get</code> and <code>opt</code>
* methods for accessing the values by index, and <code>put</code> methods for
* adding or replacing values. The values can be any of these types:
* <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
* <code>Number</code>, <code>String</code>, or the
* <code>JSONObject.NULL object</code>.
* <p>
* The constructor can convert a JSON text into a Java object. The
* <code>toString</code> method converts to JSON text.
* <p>
* A <code>get</code> method returns a value if one can be found, and throws an
* exception if one cannot be found. An <code>opt</code> method returns a
* default value instead of throwing an exception, and so is useful for
* obtaining optional values.
* <p>
* The generic <code>get()</code> and <code>opt()</code> methods return an
* object which you can cast or query for type. There are also typed
* <code>get</code> and <code>opt</code> methods that do type checking and type
* coercion for you.
* <p>
* The texts produced by the <code>toString</code> methods strictly conform to
* JSON syntax rules. The constructors are more forgiving in the texts they will
* accept:
* <ul>
* <li>An extra <code>,</code> <small>(comma)</small> may appear just
* before the closing bracket.</li>
* <li>The <code>null</code> value will be inserted when there
* is <code>,</code> <small>(comma)</small> elision.</li>
* <li>Strings may be quoted with <code>'</code> <small>(single
* quote)</small>.</li>
* <li>Strings do not need to be quoted at all if they do not begin with a quote
* or single quote, and if they do not contain leading or trailing spaces,
* and if they do not contain any of these characters:
* <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
* and if they are not the reserved words <code>true</code>,
* <code>false</code>, or <code>null</code>.</li>
* <li>Values can be separated by <code>;</code> <small>(semicolon)</small> as
* well as by <code>,</code> <small>(comma)</small>.</li>
* <li>Numbers may have the
* <code>0x-</code> <small>(hex)</small> prefix.</li>
* </ul>
* @author JSON.org
* @version 2011-08-25
*/
public class JSONArray {
/**
* The arrayList where the JSONArray's properties are kept.
*/
private ArrayList myArrayList;
/**
* Construct an empty JSONArray.
*/
public JSONArray() {
this.myArrayList = new ArrayList();
}
/**
* Construct a JSONArray from a JSONTokener.
* @param x A JSONTokener
* @throws JSONException If there is a syntax error.
*/
public JSONArray(JSONTokener x) throws JSONException {
this();
if (x.nextClean() != '[') {
throw x.syntaxError("A JSONArray text must start with '['");
}
if (x.nextClean() != ']') {
x.back();
for (;;) {
if (x.nextClean() == ',') {
x.back();
this.myArrayList.add(JSONObject.NULL);
} else {
x.back();
this.myArrayList.add(x.nextValue());
}
switch (x.nextClean()) {
case ';':
case ',':
if (x.nextClean() == ']') {
return;
}
x.back();
break;
case ']':
return;
default:
throw x.syntaxError("Expected a ',' or ']'");
}
}
}
}
/**
* Construct a JSONArray from a source JSON text.
* @param source A string that begins with
* <code>[</code> <small>(left bracket)</small>
* and ends with <code>]</code> <small>(right bracket)</small>.
* @throws JSONException If there is a syntax error.
*/
public JSONArray(String source) throws JSONException {
this(new JSONTokener(source));
}
/**
* Construct a JSONArray from a Collection.
* @param collection A Collection.
*/
public JSONArray(Collection collection) {
this.myArrayList = new ArrayList();
if (collection != null) {
Iterator iter = collection.iterator();
while (iter.hasNext()) {
this.myArrayList.add(JSONObject.wrap(iter.next()));
}
}
}
/**
* Construct a JSONArray from an array
* @throws JSONException If not an array.
*/
public JSONArray(Object array) throws JSONException {
this();
if (array.getClass().isArray()) {
int length = Array.getLength(array);
for (int i = 0; i < length; i += 1) {
this.put(JSONObject.wrap(Array.get(array, i)));
}
} else {
throw new JSONException(
"JSONArray initial value should be a string or collection or array.");
}
}
/**
* Get the object value associated with an index.
* @param index
* The index must be between 0 and length() - 1.
* @return An object value.
* @throws JSONException If there is no value for the index.
*/
public Object get(int index) throws JSONException {
Object object = opt(index);
if (object == null) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
return object;
}
/**
* Get the boolean value associated with an index.
* The string values "true" and "false" are converted to boolean.
*
* @param index The index must be between 0 and length() - 1.
* @return The truth.
* @throws JSONException If there is no value for the index or if the
* value is not convertible to boolean.
*/
public boolean getBoolean(int index) throws JSONException {
Object object = get(index);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
}
/**
* Get the double value associated with an index.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException If the key is not found or if the value cannot
* be converted to a number.
*/
public double getDouble(int index) throws JSONException {
Object object = get(index);
try {
return object instanceof Number ?
((Number)object).doubleValue() :
Double.parseDouble((String)object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
}
}
/**
* Get the int value associated with an index.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException If the key is not found or if the value is not a number.
*/
public int getInt(int index) throws JSONException {
Object object = get(index);
try {
return object instanceof Number ?
((Number)object).intValue() :
Integer.parseInt((String)object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
}
}
/**
* Get the JSONArray associated with an index.
* @param index The index must be between 0 and length() - 1.
* @return A JSONArray value.
* @throws JSONException If there is no value for the index. or if the
* value is not a JSONArray
*/
public JSONArray getJSONArray(int index) throws JSONException {
Object object = get(index);
if (object instanceof JSONArray) {
return (JSONArray)object;
}
throw new JSONException("JSONArray[" + index +
"] is not a JSONArray.");
}
/**
* Get the JSONObject associated with an index.
* @param index subscript
* @return A JSONObject value.
* @throws JSONException If there is no value for the index or if the
* value is not a JSONObject
*/
public JSONObject getJSONObject(int index) throws JSONException {
Object object = get(index);
if (object instanceof JSONObject) {
return (JSONObject)object;
}
throw new JSONException("JSONArray[" + index +
"] is not a JSONObject.");
}
/**
* Get the long value associated with an index.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException If the key is not found or if the value cannot
* be converted to a number.
*/
public long getLong(int index) throws JSONException {
Object object = get(index);
try {
return object instanceof Number ?
((Number)object).longValue() :
Long.parseLong((String)object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
}
}
/**
* Get the string associated with an index.
* @param index The index must be between 0 and length() - 1.
* @return A string value.
* @throws JSONException If there is no string value for the index.
*/
public String getString(int index) throws JSONException {
Object object = get(index);
if (object instanceof String) {
return (String)object;
}
throw new JSONException("JSONArray[" + index + "] not a string.");
}
/**
* Determine if the value is null.
* @param index The index must be between 0 and length() - 1.
* @return true if the value at the index is null, or if there is no value.
*/
public boolean isNull(int index) {
return JSONObject.NULL.equals(opt(index));
}
/**
* Make a string from the contents of this JSONArray. The
* <code>separator</code> string is inserted between each element.
* Warning: This method assumes that the data structure is acyclical.
* @param separator A string that will be inserted between the elements.
* @return a string.
* @throws JSONException If the array contains an invalid number.
*/
public String join(String separator) throws JSONException {
int len = length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < len; i += 1) {
if (i > 0) {
sb.append(separator);
}
sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
}
return sb.toString();
}
/**
* Get the number of elements in the JSONArray, included nulls.
*
* @return The length (or size).
*/
public int length() {
return this.myArrayList.size();
}
/**
* Get the optional object value associated with an index.
* @param index The index must be between 0 and length() - 1.
* @return An object value, or null if there is no
* object at that index.
*/
public Object opt(int index) {
return (index < 0 || index >= length()) ?
null : this.myArrayList.get(index);
}
/**
* Get the optional boolean value associated with an index.
* It returns false if there is no value at that index,
* or if the value is not Boolean.TRUE or the String "true".
*
* @param index The index must be between 0 and length() - 1.
* @return The truth.
*/
public boolean optBoolean(int index) {
return optBoolean(index, false);
}
/**
* Get the optional boolean value associated with an index.
* It returns the defaultValue if there is no value at that index or if
* it is not a Boolean or the String "true" or "false" (case insensitive).
*
* @param index The index must be between 0 and length() - 1.
* @param defaultValue A boolean default.
* @return The truth.
*/
public boolean optBoolean(int index, boolean defaultValue) {
try {
return getBoolean(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional double value associated with an index.
* NaN is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
*/
public double optDouble(int index) {
return optDouble(index, Double.NaN);
}
/**
* Get the optional double value associated with an index.
* The defaultValue is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
*
* @param index subscript
* @param defaultValue The default value.
* @return The value.
*/
public double optDouble(int index, double defaultValue) {
try {
return getDouble(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional int value associated with an index.
* Zero is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
*/
public int optInt(int index) {
return optInt(index, 0);
}
/**
* Get the optional int value associated with an index.
* The defaultValue is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
* @param index The index must be between 0 and length() - 1.
* @param defaultValue The default value.
* @return The value.
*/
public int optInt(int index, int defaultValue) {
try {
return getInt(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional JSONArray associated with an index.
* @param index subscript
* @return A JSONArray value, or null if the index has no value,
* or if the value is not a JSONArray.
*/
public JSONArray optJSONArray(int index) {
Object o = opt(index);
return o instanceof JSONArray ? (JSONArray)o : null;
}
/**
* Get the optional JSONObject associated with an index.
* Null is returned if the key is not found, or null if the index has
* no value, or if the value is not a JSONObject.
*
* @param index The index must be between 0 and length() - 1.
* @return A JSONObject value.
*/
public JSONObject optJSONObject(int index) {
Object o = opt(index);
return o instanceof JSONObject ? (JSONObject)o : null;
}
/**
* Get the optional long value associated with an index.
* Zero is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
*/
public long optLong(int index) {
return optLong(index, 0);
}
/**
* Get the optional long value associated with an index.
* The defaultValue is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
* @param index The index must be between 0 and length() - 1.
* @param defaultValue The default value.
* @return The value.
*/
public long optLong(int index, long defaultValue) {
try {
return getLong(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional string value associated with an index. It returns an
* empty string if there is no value at that index. If the value
* is not a string and is not null, then it is coverted to a string.
*
* @param index The index must be between 0 and length() - 1.
* @return A String value.
*/
public String optString(int index) {
return optString(index, "");
}
/**
* Get the optional string associated with an index.
* The defaultValue is returned if the key is not found.
*
* @param index The index must be between 0 and length() - 1.
* @param defaultValue The default value.
* @return A String value.
*/
public String optString(int index, String defaultValue) {
Object object = opt(index);
return JSONObject.NULL.equals(object) ? object.toString() : defaultValue;
}
/**
* Append a boolean value. This increases the array's length by one.
*
* @param value A boolean value.
* @return this.
*/
public JSONArray put(boolean value) {
put(value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
/**
* Put a value in the JSONArray, where the value will be a
* JSONArray which is produced from a Collection.
* @param value A Collection value.
* @return this.
*/
public JSONArray put(Collection value) {
put(new JSONArray(value));
return this;
}
/**
* Append a double value. This increases the array's length by one.
*
* @param value A double value.
* @throws JSONException if the value is not finite.
* @return this.
*/
public JSONArray put(double value) throws JSONException {
Double d = new Double(value);
JSONObject.testValidity(d);
put(d);
return this;
}
/**
* Append an int value. This increases the array's length by one.
*
* @param value An int value.
* @return this.
*/
public JSONArray put(int value) {
put(new Integer(value));
return this;
}
/**
* Append an long value. This increases the array's length by one.
*
* @param value A long value.
* @return this.
*/
public JSONArray put(long value) {
put(new Long(value));
return this;
}
/**
* Put a value in the JSONArray, where the value will be a
* JSONObject which is produced from a Map.
* @param value A Map value.
* @return this.
*/
public JSONArray put(Map value) {
put(new JSONObject(value));
return this;
}
/**
* Append an object value. This increases the array's length by one.
* @param value An object value. The value should be a
* Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
* JSONObject.NULL object.
* @return this.
*/
public JSONArray put(Object value) {
this.myArrayList.add(value);
return this;
}
/**
* Put or replace a boolean value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
* @param index The subscript.
* @param value A boolean value.
* @return this.
* @throws JSONException If the index is negative.
*/
public JSONArray put(int index, boolean value) throws JSONException {
put(index, value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
/**
* Put a value in the JSONArray, where the value will be a
* JSONArray which is produced from a Collection.
* @param index The subscript.
* @param value A Collection value.
* @return this.
* @throws JSONException If the index is negative or if the value is
* not finite.
*/
public JSONArray put(int index, Collection value) throws JSONException {
put(index, new JSONArray(value));
return this;
}
/**
* Put or replace a double value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad
* it out.
* @param index The subscript.
* @param value A double value.
* @return this.
* @throws JSONException If the index is negative or if the value is
* not finite.
*/
public JSONArray put(int index, double value) throws JSONException {
put(index, new Double(value));
return this;
}
/**
* Put or replace an int value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad
* it out.
* @param index The subscript.
* @param value An int value.
* @return this.
* @throws JSONException If the index is negative.
*/
public JSONArray put(int index, int value) throws JSONException {
put(index, new Integer(value));
return this;
}
/**
* Put or replace a long value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad
* it out.
* @param index The subscript.
* @param value A long value.
* @return this.
* @throws JSONException If the index is negative.
*/
public JSONArray put(int index, long value) throws JSONException {
put(index, new Long(value));
return this;
}
/**
* Put a value in the JSONArray, where the value will be a
* JSONObject that is produced from a Map.
* @param index The subscript.
* @param value The Map value.
* @return this.
* @throws JSONException If the index is negative or if the the value is
* an invalid number.
*/
public JSONArray put(int index, Map value) throws JSONException {
put(index, new JSONObject(value));
return this;
}
/**
* Put or replace an object value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
* @param index The subscript.
* @param value The value to put into the array. The value should be a
* Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
* JSONObject.NULL object.
* @return this.
* @throws JSONException If the index is negative or if the the value is
* an invalid number.
*/
public JSONArray put(int index, Object value) throws JSONException {
JSONObject.testValidity(value);
if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
if (index < length()) {
this.myArrayList.set(index, value);
} else {
while (index != length()) {
put(JSONObject.NULL);
}
put(value);
}
return this;
}
/**
* Remove an index and close the hole.
* @param index The index of the element to be removed.
* @return The value that was associated with the index,
* or null if there was no value.
*/
public Object remove(int index) {
Object o = opt(index);
this.myArrayList.remove(index);
return o;
}
/**
* Produce a JSONObject by combining a JSONArray of names with the values
* of this JSONArray.
* @param names A JSONArray containing a list of key strings. These will be
* paired with the values.
* @return A JSONObject, or null if there are no names or if this JSONArray
* has no values.
* @throws JSONException If any of the names are null.
*/
public JSONObject toJSONObject(JSONArray names) throws JSONException {
if (names == null || names.length() == 0 || length() == 0) {
return null;
}
JSONObject jo = new JSONObject();
for (int i = 0; i < names.length(); i += 1) {
jo.put(names.getString(i), this.opt(i));
}
return jo;
}
/**
* Make a JSON text of this JSONArray. For compactness, no
* unnecessary whitespace is added. If it is not possible to produce a
* syntactically correct JSON text then null will be returned instead. This
* could occur if the array contains an invalid number.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return a printable, displayable, transmittable
* representation of the array.
*/
public String toString() {
try {
return '[' + join(",") + ']';
} catch (Exception e) {
return null;
}
}
/**
* Make a prettyprinted JSON text of this JSONArray.
* Warning: This method assumes that the data structure is acyclical.
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @return a printable, displayable, transmittable
* representation of the object, beginning
* with <code>[</code> <small>(left bracket)</small> and ending
* with <code>]</code> <small>(right bracket)</small>.
* @throws JSONException
*/
public String toString(int indentFactor) throws JSONException {
return toString(indentFactor, 0);
}
/**
* Make a prettyprinted JSON text of this JSONArray.
* Warning: This method assumes that the data structure is acyclical.
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @param indent The indention of the top level.
* @return a printable, displayable, transmittable
* representation of the array.
* @throws JSONException
*/
String toString(int indentFactor, int indent) throws JSONException {
int len = length();
if (len == 0) {
return "[]";
}
int i;
StringBuffer sb = new StringBuffer("[");
if (len == 1) {
sb.append(JSONObject.valueToString(this.myArrayList.get(0),
indentFactor, indent));
} else {
int newindent = indent + indentFactor;
sb.append('\n');
for (i = 0; i < len; i += 1) {
if (i > 0) {
sb.append(",\n");
}
for (int j = 0; j < newindent; j += 1) {
sb.append(' ');
}
sb.append(JSONObject.valueToString(this.myArrayList.get(i),
indentFactor, newindent));
}
sb.append('\n');
for (i = 0; i < indent; i += 1) {
sb.append(' ');
}
}
sb.append(']');
return sb.toString();
}
/**
* Write the contents of the JSONArray as JSON text to a writer.
* For compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return The writer.
* @throws JSONException
*/
public Writer write(Writer writer) throws JSONException {
try {
boolean b = false;
int len = length();
writer.write('[');
for (int i = 0; i < len; i += 1) {
if (b) {
writer.write(',');
}
Object v = this.myArrayList.get(i);
if (v instanceof JSONObject) {
((JSONObject)v).write(writer);
} else if (v instanceof JSONArray) {
((JSONArray)v).write(writer);
} else {
writer.write(JSONObject.valueToString(v));
}
b = true;
}
writer.write(']');
return writer;
} catch (IOException e) {
throw new JSONException(e);
}
}
} |
package mindpop.learnpop;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
public class ResourceAdapter extends RecyclerView.Adapter<ResourceAdapter.ResourceViewHolder> {
List<Resource> resources;
private FragmentActivity _activity;
ResourceAdapter(FragmentActivity ac, List<Resource> list){
this._activity= ac;
this.resources = list;
}
public int getItemCount() {
return resources.size();
}
@Override
public ResourceViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_strategy, viewGroup, false);
ResourceViewHolder pvh = new ResourceViewHolder(v);
return pvh;
}
@Override
public void onBindViewHolder(ResourceViewHolder aViewHolder, int i) {
aViewHolder.setClickListener(new ResourceViewHolder.ClickListener(){
@Override
public void onClick(View v, int pos, boolean isLongClick){
Resource item = resources.get(pos);
/*WebViewFragment webFrag = new WebViewFragment();
webFrag.init(item.getUrl());*/
WebItem webItem = new WebItem();
webItem.init(item);
_activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
_activity.getSupportFragmentManager().beginTransaction().replace(R.id.container, webItem).addToBackStack(null).commit();
}
});
aViewHolder.title.setText(resources.get(i).getTitle());
String sub = resources.get(i).getSubject();
aViewHolder.subject.setText(sub);
int resID = 0;
switch(sub){
case "Bilingual": resID = R.drawable.bilingual; break;
case "Digital Media": resID = R.drawable.media; break;
case "Drama": resID = R.drawable.drama; break;
case "ELA": resID = R.drawable.ela; break;
case "History": resID = R.drawable.history; break;
case "Math": resID = R.drawable.math; break;
case "Movement": resID = R.drawable.move; break;
case "Music": resID = R.drawable.music; break;
case "Science": resID = R.drawable.science; break;
case "SEL": resID = R.drawable.sel; break;
case "Visual Art": resID = R.drawable.art; break;
}
aViewHolder.icon.setImageResource(resID);
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class ResourceViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{
CardView res;
TextView title;
TextView subject;
ImageView icon;
private ClickListener clickListener;
public interface ClickListener{
public void onClick(View v, int position, boolean isLongClick);
}
ResourceViewHolder(View itemView){
super(itemView);
res = (CardView)itemView.findViewById(R.id.card_resource);
title = (TextView)itemView.findViewById(R.id.res_title);
subject = (TextView)itemView.findViewById(R.id.res_sub);
icon = (ImageView)itemView.findViewById(R.id.icon_res);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
public void setClickListener(ClickListener clickListener) {
this.clickListener = clickListener;
}
@Override
public void onClick(View v) {
// If not long clicked, pass last variable as false.
clickListener.onClick(v, getPosition(), false);
}
@Override
public boolean onLongClick(View v) {
// If long clicked, passed last variable as true.
clickListener.onClick(v, getPosition(), true);
return true;
}
}
} |
package org.y20k.transistor;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.os.EnvironmentCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Toast;
import org.y20k.transistor.core.Collection;
import java.io.File;
/**
* MainActivity class
*/
public final class MainActivity extends AppCompatActivity {
/* Define log tag */
private static final String LOG_TAG = MainActivity.class.getSimpleName();
/* Keys */
private static final String ACTION_SHOW_PLAYER = "org.y20k.transistor.action.SHOW_PLAYER";
private static final String EXTRA_STATION_ID = "EXTRA_STATION_ID";
private static final String EXTRA_PLAYBACK_STATE = "EXTRA_PLAYBACK_STATE";
private static final String ARG_STATION_ID = "ArgStationID";
private static final String ARG_TWO_PANE = "ArgTwoPane";
private static final String ARG_PLAYBACK = "ArgPlayback";
private static final String PREF_TWO_PANE = "prefTwoPane";
private static final String PLAYERFRAGMENT_TAG = "PFTAG";
/* Main class variables */
private boolean mTwoPane;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout
setContentView(R.layout.activity_main);
// if player_container is present two-pane layout has been loaded
if (findViewById(R.id.player_container) != null) {
mTwoPane = true;
} else {
mTwoPane = false;
}
// load collection
Collection collection = new Collection(getCollectionDirectory("Collection"));
// get intent
Intent intent = getIntent();
// prepare bundle
Bundle playerArgs = new Bundle();
int stationID;
boolean startPlayback;
// special case: player activity should be launched
if (intent != null && ACTION_SHOW_PLAYER.equals(intent.getAction())) {
Log.v(LOG_TAG, "!!! Special case.");
// get id of station from intent
if (intent.hasExtra(EXTRA_STATION_ID)) {
stationID = intent.getIntExtra(EXTRA_STATION_ID, 0);
} else {
stationID = 0;
}
// get playback action from intent
if (intent.hasExtra(EXTRA_PLAYBACK_STATE)) {
startPlayback = intent.getBooleanExtra(EXTRA_PLAYBACK_STATE, false);
} else {
startPlayback = false;
}
if (mTwoPane) {
playerArgs.putInt(ARG_STATION_ID, stationID);
playerArgs.putBoolean(ARG_PLAYBACK, startPlayback);
} else {
// start player activity - on phone
Intent playerIntent = new Intent(this, PlayerActivity.class);
playerIntent.setAction(ACTION_SHOW_PLAYER);
playerIntent.putExtra(EXTRA_STATION_ID, stationID);
playerIntent.putExtra(EXTRA_PLAYBACK_STATE, startPlayback);
startActivity(playerIntent);
}
}
// tablet mode: show player fragment in player container
if (mTwoPane && savedInstanceState == null && !collection.getStations().isEmpty()) {
playerArgs.putBoolean(ARG_TWO_PANE, mTwoPane);
PlayerActivityFragment playerActivityFragment = new PlayerActivityFragment();
playerActivityFragment.setArguments(playerArgs);
getFragmentManager().beginTransaction()
.replace(R.id.player_container, playerActivityFragment, PLAYERFRAGMENT_TAG)
.commit();
} else if (mTwoPane) {
// make room for action call
findViewById(R.id.player_container).setVisibility(View.GONE);
}
saveAppState(this);
}
@Override
protected void onResume() {
super.onResume();
// TODO Replace with collection changed listener?
Collection collection = new Collection(getCollectionDirectory("Collection"));
View container = findViewById(R.id.player_container);
if (collection.getStations().isEmpty() && container != null) {
// make room for action call
container.setVisibility(View.GONE);
} else if (container != null) {
container.setVisibility(View.VISIBLE);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// activity opened for second time set intent to new intent
setIntent(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main_actionbar, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment_main);
// hand results over to fragment main
fragment.onActivityResult(requestCode, resultCode, data);
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment_main);
// hand results over to fragment main
fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
/* Saves app state to SharedPreferences */
private void saveAppState(Context context) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(PREF_TWO_PANE, mTwoPane);
editor.apply();
Log.v(LOG_TAG, "Saving state.");
}
/* Return a writeable sub-directory from external storage */
private File getCollectionDirectory(String subDirectory) {
File[] storage = this.getExternalFilesDirs(subDirectory);
for (File file : storage) {
String state = EnvironmentCompat.getStorageState(file);
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.i(LOG_TAG, "External storage: " + file.toString());
return file;
}
}
Toast.makeText(this, this.getString(R.string.toastalert_no_external_storage), Toast.LENGTH_LONG).show();
Log.e(LOG_TAG, "Unable to access external storage.");
// finish activity
this.finish();
return null;
}
} |
package sophena.rcp.editors.costs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.editor.FormPage;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import sophena.model.Boiler;
import sophena.model.Consumer;
import sophena.model.FlueGasCleaningEntry;
import sophena.model.HeatNet;
import sophena.model.HeatNetPipe;
import sophena.model.Producer;
import sophena.model.ProductType;
import sophena.model.Project;
import sophena.model.descriptors.ProducerDescriptor;
import sophena.model.descriptors.ProjectDescriptor;
import sophena.rcp.editors.consumers.ConsumerEditor;
import sophena.rcp.editors.heatnets.HeatNetEditor;
import sophena.rcp.editors.producers.ProducerEditor;
import sophena.rcp.utils.UI;
import sophena.utils.Strings;
class OverviewPage extends FormPage {
private CostEditor editor;
public OverviewPage(CostEditor editor) {
super(editor, "sophena.CostOverviewPage", "Investitionen");
this.editor = editor;
Collections.sort(project().productEntries, (e1, e2) -> {
if (e1.product == null || e2.product == null)
return 0;
else
return Strings.compare(e1.product.name, e2.product.name);
});
}
private Project project() {
return editor.getProject();
}
@Override
protected void createFormContent(IManagedForm mform) {
ScrolledForm form = UI.formHeader(mform, "Investitionen");
FormToolkit tk = mform.getToolkit();
Composite body = UI.formBody(form, tk);
for (ProductType type : ProductType.values()) {
switch (type) {
case BIOMASS_BOILER:
case FOSSIL_FUEL_BOILER:
case HEAT_PUMP:
case COGENERATION_PLANT:
boilers(type, body, tk);
break;
case HEAT_RECOVERY:
heatRecoveries(body, tk);
break;
case FLUE_GAS_CLEANING:
flueGasCleanings(body, tk);
break;
case BUFFER_TANK:
buffers(body, tk);
break;
case PIPE:
pipes(body, tk);
break;
case TRANSFER_STATION:
transferStations(body, tk);
break;
default:
new EntrySection(editor, type).create(body, tk);
}
}
form.reflow(true);
}
private void buffers(Composite body, FormToolkit tk) {
DisplaySection<HeatNet> s = new DisplaySection<>(
ProductType.BUFFER_TANK);
HeatNet net = editor.getProject().heatNet;
s.content = () -> {
if (net == null || net.bufferTank == null)
return Collections.emptyList();
else
return Collections.singletonList(net);
};
s.costs = n -> n.bufferTankCosts;
s.label = n -> n.bufferTank.name;
s.onOpen = n -> HeatNetEditor.open(project().toDescriptor());
s.create(body, tk);
}
private void pipes(Composite body, FormToolkit tk) {
DisplaySection<HeatNetPipe> s = new DisplaySection<>(
ProductType.PIPE);
HeatNet net = project().heatNet;
s.content = () -> {
if (net == null)
return Collections.emptyList();
else
return net.pipes;
};
s.costs = p -> p.costs;
s.label = p -> p.pipe != null ? p.pipe.name : null;
s.onOpen = p -> HeatNetEditor.open(project().toDescriptor());
s.create(body, tk);
}
private void transferStations(Composite body, FormToolkit tk) {
DisplaySection<Consumer> s = new DisplaySection<>(
ProductType.TRANSFER_STATION);
s.content = () -> {
List<Consumer> list = new ArrayList<>();
for (Consumer c : project().consumers) {
if (!c.disabled && c.transferStation != null) {
list.add(c);
}
}
Collections.sort(list, (c1, c2) -> Strings.compare(
c1.transferStation.name, c2.transferStation.name));
return list;
};
s.costs = c -> c.transferStationCosts;
s.label = c -> c.transferStation.name;
s.onOpen = c -> ConsumerEditor.open(project().toDescriptor(),
c.toDescriptor());
s.create(body, tk);
}
private void heatRecoveries(Composite body, FormToolkit tk) {
DisplaySection<Producer> s = new DisplaySection<>(
ProductType.HEAT_RECOVERY);
s.content = () -> {
List<Producer> list = new ArrayList<>();
for (Producer p : project().producers) {
if (p.heatRecovery != null) {
list.add(p);
}
}
Collections.sort(list, (p1, p2) -> Strings.compare(
p1.heatRecovery.name, p2.heatRecovery.name));
return list;
};
s.costs = p -> p.heatRecoveryCosts;
s.label = p -> p.heatRecovery.name;
s.onOpen = p -> ProducerEditor.open(project().toDescriptor(),
p.toDescriptor());
s.create(body, tk);
}
public void flueGasCleanings(Composite body, FormToolkit tk) {
DisplaySection<FlueGasCleaningEntry> s = new DisplaySection<>(
ProductType.FLUE_GAS_CLEANING);
s.content = () -> {
List<FlueGasCleaningEntry> list = new ArrayList<>();
for (FlueGasCleaningEntry e : project().flueGasCleaningEntries) {
if (e.product != null) {
list.add(e);
}
}
Collections.sort(list, (e1, e2) -> Strings.compare(
e1.product.name, e2.product.name));
return list;
};
s.costs = e -> e.costs;
s.label = e -> e.product.name;
s.create(body, tk);
}
private void boilers(ProductType type, Composite body, FormToolkit tk) {
DisplaySection<Producer> s = new DisplaySection<>(type);
s.content = () -> getProducers(type);
s.costs = p -> p.costs;
s.label = p -> p.boiler == null ? null : p.boiler.name;
s.onOpen = p -> {
ProjectDescriptor project = project().toDescriptor();
ProducerDescriptor producer = p.toDescriptor();
ProducerEditor.open(project, producer);
};
s.create(body, tk);
}
private List<Producer> getProducers(ProductType type) {
List<Producer> list = new ArrayList<>();
for (Producer p : project().producers) {
if (p.disabled)
continue;
Boiler b = p.boiler;
if (b != null && b.type == type)
list.add(p);
}
Collections.sort(list,
(p1, p2) -> Strings.compare(p1.boiler.name, p2.boiler.name));
return list;
}
} |
package com.artemis;
import java.util.BitSet;
import com.artemis.utils.Bag;
/**
* Handles the association between entities and their components.
* <p>
* Usually only one component manager will exists per {@link World} instance,
* managed by the world. Entites that add or remove components to them selves
* will call {@link #addComponent(Entity, ComponentType, Component)} or
* {@link #removeComponent(Entity, ComponentType)} respectively of the
* component manager of their world.
* </p>
*
* @author Arni Arent
*/
public class ComponentManager extends Manager {
/** Holds all components grouped by type. */
private final Bag<Bag<Component>> componentsByType;
/** Holds all packed components sorted by type index. */
private final Bag<PackedComponent> packedComponents;
private final Bag<Bag<Entity>> packedComponentOwners;
/** Collects all Entites marked for deletion from this ComponentManager. */
private final WildBag<Entity> deleted;
private final ComponentPool pooledComponents;
/**
* Creates a new instance of {@link ComponentManager}.
*/
public ComponentManager() {
componentsByType = new Bag<Bag<Component>>();
packedComponents = new Bag<PackedComponent>();
packedComponentOwners = new Bag<Bag<Entity>>();
pooledComponents = new ComponentPool();
deleted = new WildBag<Entity>();
}
@SuppressWarnings("unchecked")
protected <T extends Component> T create(Entity owner, Class<T> componentClass) {
ComponentType type = ComponentType.getTypeFor(componentClass);
switch (type.getTaxonomy())
{
case BASIC:
return newInstance(componentClass);
case PACKED:
PackedComponent packedComponent = packedComponents.get(type.getIndex());
if (packedComponent == null) {
packedComponent = (PackedComponent)newInstance(componentClass);
packedComponents.set(type.getIndex(), packedComponent);
}
getPackedComponentOwners(type).set(owner.getId(), owner);
packedComponent.setEntityId(owner.getId());
return (T)packedComponent;
case POOLED:
try {
return (T)pooledComponents.obtain((Class<PooledComponent>)componentClass);
} catch (InstantiationException e) {
throw new InvalidComponentException(componentClass, "Unable to instantiate component.", e);
} catch (IllegalAccessException e) {
throw new InvalidComponentException(componentClass, "Missing public constructor.", e);
}
default:
throw new InvalidComponentException(componentClass, " unknown component type: " + type.getTaxonomy());
}
}
protected Bag<Entity> getPackedComponentOwners(ComponentType type)
{
Bag<Entity> owners = packedComponentOwners.get(type.getIndex());
if (owners == null) {
owners = new Bag<Entity>(64);
packedComponentOwners.set(type.getIndex(), owners);
}
return owners;
}
private static <T extends Component> T newInstance(Class<T> componentClass) {
try {
return componentClass.newInstance();
} catch (InstantiationException e) {
throw new InvalidComponentException(componentClass, "Unable to instantiate component.", e);
} catch (IllegalAccessException e) {
throw new InvalidComponentException(componentClass, "Missing public constructor.", e);
}
}
@Override
protected void initialize() {}
/**
* Removes all components from the entity associated in this manager.
*
* @param e
* the entity to remove components from
*/
private void removeComponentsOfEntity(Entity e) {
BitSet componentBits = e.getComponentBits();
for (int i = componentBits.nextSetBit(0); i >= 0; i = componentBits.nextSetBit(i+1)) {
switch (ComponentType.getTaxonomy(i)) {
case BASIC:
componentsByType.get(i).set(e.getId(), null);
break;
case POOLED:
Component pooled = componentsByType.get(i).get(e.getId());
pooledComponents.free((PooledComponent)pooled);
componentsByType.get(i).set(e.getId(), null);
break;
case PACKED:
packedComponents.get(i).setEntityId(e.getId()).reset();
break;
default:
throw new InvalidComponentException(Component.class, " unknown component type: " + ComponentType.getTaxonomy(i));
}
}
componentBits.clear();
}
/**
* Adds the component of the given type to the entity.
* <p>
* Only one component of given type can be associated with a entity at the
* same time.
* </p>
*
* @param e
* the entity to add to
* @param type
* the type of component being added
* @param component
* the component to add
*/
protected void addComponent(Entity e, ComponentType type, Component component) {
if (type.isPackedComponent())
addPackedComponent(type, (PackedComponent)component);
else
addBasicComponent(e, type, component); // pooled components are handled the same
e.getComponentBits().set(type.getIndex());
}
private void addPackedComponent(ComponentType type, PackedComponent component) {
PackedComponent packed = packedComponents.get(type.getIndex());
if (packed == null) {
packedComponents.set(type.getIndex(), component);
}
}
private void addBasicComponent(Entity e, ComponentType type, Component component)
{
Bag<Component> components = componentsByType.get(type.getIndex());
if(components == null) {
components = new Bag<Component>();
componentsByType.set(type.getIndex(), components);
}
components.set(e.getId(), component);
}
/**
* Removes the component of given type from the entity.
*
* @param e
* the entity to remove from
* @param type
* the type of component being removed
*/
protected void removeComponent(Entity e, ComponentType type) {
int index = type.getIndex();
if(e.getComponentBits().get(index)) {
switch (type.getTaxonomy()) {
case BASIC:
componentsByType.get(index).set(e.getId(), null);
break;
case POOLED:
Component pooled = componentsByType.get(index).get(e.getId());
pooledComponents.free((PooledComponent)pooled);
componentsByType.get(index).set(e.getId(), null);
break;
case PACKED:
packedComponents.get(index).setEntityId(e.getId()).reset();
getPackedComponentOwners(type).set(e.getId(), null);
break;
default:
throw new InvalidComponentException(type.getType(), " unknown component type: " + type.getTaxonomy());
}
e.getComponentBits().clear(index);
}
}
/**
* Get all components from all entities for a given type.
*
* @param type
* the type of components to get
* @return a bag containing all components of the given type
*/
protected Bag<Component> getComponentsByType(ComponentType type) {
if (type.isPackedComponent())
throw new InvalidComponentException(type.getType(), "PackedComponent types aren't supported.");
Bag<Component> components = componentsByType.get(type.getIndex());
if(components == null) {
components = new Bag<Component>();
componentsByType.set(type.getIndex(), components);
}
return components;
}
/**
* Get a component of a entity.
*
* @param e
* the entity associated with the component
* @param type
* the type of component to get
* @return the component of given type
*/
protected Component getComponent(Entity e, ComponentType type) {
if (type.isPackedComponent()) {
PackedComponent component = packedComponents.get(type.getIndex());
if (component != null) component.setEntityId(e.getId());
return component;
} else {
Bag<Component> components = componentsByType.get(type.getIndex());
if(components != null) {
return components.get(e.getId());
}
}
return null;
}
/**
* Get all component associated with an entity.
*
* @param e
* the entity to get components from
* @param fillBag
* a bag to be filled with components
* @return the {@code fillBag}, filled with the entities components
*/
public Bag<Component> getComponentsFor(Entity e, Bag<Component> fillBag) {
BitSet componentBits = e.getComponentBits();
for (int i = componentBits.nextSetBit(0); i >= 0; i = componentBits.nextSetBit(i+1)) {
if (ComponentType.isPackedComponent(i)) {
fillBag.add(packedComponents.get(i));
} else {
fillBag.add(componentsByType.get(i).get(e.getId()));
}
}
return fillBag;
}
@Override
public void deleted(Entity e) {
deleted.add(e);
}
/**
* Removes all components from entities marked for deletion.
*/
protected void clean() {
int s = deleted.size();
if(s > 0) {
Object[] data = deleted.getData();
for(int i = 0; s > i; i++) {
removeComponentsOfEntity((Entity)data[i]);
data[i] = null;
}
deleted.setSize(0);
}
}
} |
package com.intellij.ide.todo.nodes;
import com.intellij.ide.projectView.impl.nodes.PackageElement;
import com.intellij.ide.projectView.impl.nodes.PackageUtil;
import com.intellij.ide.todo.TodoTreeBuilder;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiPackage;
import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class TodoPackageUtil {
public static boolean isPackageEmpty(PackageElement packageElement, TodoTreeBuilder builder, Project project) {
if (packageElement == null) return true;
final PsiPackage psiPackage = packageElement.getPackage();
final Module module = packageElement.getModule();
GlobalSearchScope scope = module != null ? GlobalSearchScope.moduleScope(module) : GlobalSearchScope.projectScope(project);
final PsiDirectory[] directories = psiPackage.getDirectories(scope);
boolean isEmpty = true;
for (PsiDirectory psiDirectory : directories) {
isEmpty &= builder.isDirectoryEmpty(psiDirectory);
}
return isEmpty;
}
public static void addPackagesToChildren(ArrayList<AbstractTreeNode> children,
Module module,
TodoTreeBuilder builder,
Project project) {
final PsiManager psiManager = PsiManager.getInstance(project);
final List<VirtualFile> roots = new ArrayList<VirtualFile>();
final List<VirtualFile> sourceRoots = new ArrayList<VirtualFile>();
if (module == null){
final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(project);
roots.addAll(Arrays.asList(projectRootManager.getContentRoots()));
sourceRoots.addAll(Arrays.asList(projectRootManager.getContentSourceRoots()));
} else {
ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
roots.addAll(Arrays.asList(moduleRootManager.getContentRoots()));
sourceRoots.addAll(Arrays.asList(moduleRootManager.getSourceRoots()));
}
final Set<PsiPackage> topLevelPackages = new HashSet<PsiPackage>();
for (final VirtualFile root : sourceRoots) {
final PsiDirectory directory = psiManager.findDirectory(root);
if (directory == null) {
continue;
}
final PsiPackage directoryPackage = directory.getPackage();
if (directoryPackage == null || PackageUtil.isPackageDefault(directoryPackage)) {
// add subpackages
final PsiDirectory[] subdirectories = directory.getSubdirectories();
for (PsiDirectory subdirectory : subdirectories) {
final PsiPackage aPackage = subdirectory.getPackage();
if (aPackage != null && !PackageUtil.isPackageDefault(aPackage)) {
topLevelPackages.add(aPackage);
} else {
final Iterator<PsiFile> files = builder.getFiles(subdirectory);
if (!files.hasNext()) continue;
TodoDirNode dirNode = new TodoDirNode(project, subdirectory, builder);
if (!children.contains(dirNode)){
children.add(dirNode);
}
}
}
// add non-dir items
final Iterator<PsiFile> filesUnderDirectory = builder.getFilesUnderDirectory(directory);
for (;filesUnderDirectory.hasNext();) {
final PsiFile file = filesUnderDirectory.next();
TodoFileNode todoFileNode = new TodoFileNode(project, file, builder, false);
if (!children.contains(todoFileNode)){
children.add(todoFileNode);
}
}
}
else {
// this is the case when a source root has pakage prefix assigned
PackageElement element = new PackageElement(module, directoryPackage, false);
TodoPackageNode packageNode = new TodoPackageNode(project, element, builder, directoryPackage.getQualifiedName());
if (!children.contains(packageNode)) {
children.add(packageNode);
}
}
}
GlobalSearchScope scope = module != null ? GlobalSearchScope.moduleScope(module) : GlobalSearchScope.projectScope(project);
ArrayList<PsiPackage> packages = new ArrayList<PsiPackage>();
for (PsiPackage psiPackage : topLevelPackages) {
final PsiPackage aPackage = findNonEmptyPackage(psiPackage, module, project, builder, scope);
if (aPackage != null){
packages.add(aPackage);
}
}
for (PsiPackage psiPackage : packages) {
PackageElement element = new PackageElement(module, psiPackage, false);
TodoPackageNode packageNode = new TodoPackageNode(project, element, builder, psiPackage.getQualifiedName());
if (!children.contains(packageNode)) {
children.add(packageNode);
}
}
roots.removeAll(sourceRoots);
for (VirtualFile dir : roots) {
final PsiDirectory directory = psiManager.findDirectory(dir);
if (directory == null) {
continue;
}
final Iterator<PsiFile> files = builder.getFiles(directory);
if (!files.hasNext()) continue;
TodoDirNode dirNode = new TodoDirNode(project, directory, builder);
if (!children.contains(dirNode)){
children.add(dirNode);
}
}
}
@Nullable
private static PsiPackage findNonEmptyPackage(PsiPackage rootPackage, Module module, Project project, TodoTreeBuilder builder, GlobalSearchScope scope){
if (!isPackageEmpty(new PackageElement(module, rootPackage, false), builder, project)){
return rootPackage;
}
final PsiPackage[] subPackages = rootPackage.getSubPackages(scope);
PsiPackage suggestedNonEmptyPackage = null;
int count = 0;
for (PsiPackage aPackage : subPackages) {
if (!isPackageEmpty(new PackageElement(module, aPackage, false), builder, project)){
if (++ count > 1) return rootPackage;
suggestedNonEmptyPackage = aPackage;
}
}
for (PsiPackage aPackage : subPackages) {
if (aPackage != suggestedNonEmptyPackage) {
PsiPackage subPackage = findNonEmptyPackage(aPackage, module, project, builder, scope);
if (subPackage != null){
if (count > 0){
return rootPackage;
} else {
count ++;
suggestedNonEmptyPackage = subPackage;
}
}
}
}
return suggestedNonEmptyPackage;
}
} |
package net.acomputerdog.core.storage;
import net.acomputerdog.core.identity.Identifiable;
import java.util.*;
/**
* A registry that stores Identifiables
*
* @param <T> The type of object to store
*/
public class Registry<T extends Identifiable> {
/**
* Map of definitions to identifiables
*/
private final Map<String, T> defMap;
/**
* Map of ids to identifiables
*/
private final Map<String, T> idMap;
/**
* Creates a new Identifiable
*/
public Registry() {
defMap = new LinkedHashMap<String, T>();
idMap = new LinkedHashMap<String, T>();
}
/**
* Registers an Identifiable
* @param item The identifiable to add
* @param <T2> The type of the Identifable
* @return Return the item
*/
public <T2 extends T> T2 register(T2 item) {
defMap.put(item.getDefinition(), item);
idMap.put(item.getId(), item);
return item;
}
/**
* Check if the definition maps to a known identifiable
* @param def The definition
* @return Return true if the definition is defined
*/
public boolean isDefined(String def) {
return defMap.containsKey(def);
}
/**
* Check if an item is defined in this registry
* @param item the item
* @return Return true if the item is defined
*/
public boolean isDefined(T item) {
return defMap.containsValue(item);
}
/**
* gets an item from its definition
* @param def The definition
* @return Return the item
*/
public T getFromDef(String def) {
return defMap.get(def);
}
/**
* Gets an item from its id
* @param id The ID
* @return Return the item
*/
public T getFromId(String id) {
return idMap.get(id);
}
/**
* Get a collection of all items in this registry
* @return Return a collection of all items in this registry
*/
public Collection<T> getItems() {
return defMap.values();
}
/**
* Get a set of all definitions in this registry
* @return Return a set of all definitions in this Registry
*/
public Set<String> getDefinitions() {
return Collections.unmodifiableSet(defMap.keySet());
}
/**
* Get a set of all ids in this registry
* @return Return a set of all ids in this Registry
*/
public Set<String> getIds() {
return Collections.unmodifiableSet(idMap.keySet());
}
} |
package controllers;
import java.util.ArrayList;
import java.util.List;
import models.Cg;
import models.Course;
import models.Degree;
import models.Requirement;
import models.Sr;
import org.json.JSONArray;
import org.json.JSONObject;
import play.mvc.Controller;
import controllers.algorithm.pre_and_core.CrossLinkedList;
import controllers.algorithm.req_and_course.ComplexReq;
import controllers.algorithm.req_and_course.CourseNode;
import controllers.algorithm.req_and_course.Course_LinkList;
import controllers.algorithm.req_and_course.Linklist;
import controllers.algorithm.req_and_course.Node;
import controllers.algorithm.req_and_course.TestLinkList;
public class StudyPlanController extends Controller {
public static CrossLinkedList allCross_relation = new CrossLinkedList();
public static int redNode = 0;
public static void CreateDegreeProgram(Integer id){
//boolean chooeseSuccess =false;//
Degree degree = Degree.findById(id);
TestLinkList degreeProgram = new TestLinkList(degree.getTitle()); //add new degree
List<String> complexIds = degree.getReq_ids(); //get Requirement ids
for(String complexId : complexIds)
{
try{
Requirement req = Requirement.findById(Integer.valueOf(complexId)); //get Requirement
JSONArray srReqs = new JSONArray(req.getSr_ids());
ComplexReq complexReq = null;
if(srReqs.length() < 2)
complexReq = new ComplexReq(Integer.valueOf(req.getId()), req.getTitle(), "or");
else
complexReq = new ComplexReq(Integer.valueOf(req.getId()), req.getTitle(), (String)((JSONObject)srReqs.get(1)).get("relation"));
JSONObject srReqObject = null;
for (int i = 0; i < srReqs.length(); i++) {
srReqObject = (JSONObject) srReqs.get(i);
int srId = srReqObject.getInt("id"); //get Simple Requirment
Sr sr = Sr.findById(new Integer(srId));
int cgId = Integer.valueOf(sr.getCg_id());
int reqNum = Integer.valueOf(sr.getRequired_num());
Linklist simpleReq = find_or_create_simpleReq(degreeProgram,srId, sr.getTitle(), reqNum); //initiate simple requirement
Cg cg = Cg.findById(new Integer(cgId));
List<String> courseIds = cg.getCourse_ids();
for(String courseId : courseIds)
{
addCourse(degreeProgram, simpleReq, Integer.valueOf(courseId)); //add course
add2Course_List2(degreeProgram, simpleReq, Integer.valueOf(courseId));
}
complexReq.insertSimple(simpleReq);
degreeProgram.course_list.add(simpleReq);
}
degreeProgram.addComplexReq(complexReq);
}catch(Exception e)
{
e.printStackTrace();
}
}
// allCross_relation.Display_All_Headnode();
// allCross_relation.displayCrossLinkedList();
// degreeProgram.displayallComplexReq();
// degreeProgram.displayCourseList();
// degreeProgram.displayAllCourse();
// TestLinkList degreeProgram =new TestLinkList("degreeName1"); //need degreeName input
// ComplexReq complexReq1 = new ComplexReq(1,"complexReq1","or");
// Linklist simpleReq1 = new Linklist(1,"simpleReq1",15);
// //req1 -> course1->course2
// addCourse(degreeProgram, simpleReq1, 100);
// //req1 -> course1->course2
// addCourse(degreeProgram, simpleReq1, 200);
// addCourse(degreeProgram, simpleReq1, 300);
// addCourse(degreeProgram, simpleReq1, 400);
// addCourse(degreeProgram, simpleReq1, 500);
// addCourse(degreeProgram, simpleReq1, 600);
// complexReq1.insertSimple(simpleReq1);
// degreeProgram.addComplexReq(complexReq1);
// degreeProgram.course_list.add(simpleReq1);
// degreeProgram.displayallComplexReq();
// //course1 -> req1 ->re2
// add2Course_List2(degreeProgram, simpleReq1,100);
// add2Course_List2(degreeProgram, simpleReq1,200);
// add2Course_List2(degreeProgram, simpleReq1,300);
// add2Course_List2(degreeProgram, simpleReq1,400);
// add2Course_List2(degreeProgram, simpleReq1,500);
// add2Course_List2(degreeProgram, simpleReq1,600);
// degreeProgram.displayCourseList();
//mark student's chosen course
// boolean chooeseSuccess = degreeProgram.checkCourseIn_ReqList(10,108);
// if(chooeseSuccess){
// degreeProgram.displayallComplexReq();
// degreeProgram.displayCourseList();
// degreeProgram.displayallComplexReq();
// degreeProgram.displayCourseList();
}
public static void addCourse(TestLinkList degreeProgram,Linklist simpleReq1, int courseID){
//System.out.println(ifCourseExist);
//System.out.println("OK");
Node newNode = new Node(courseID);
if (degreeProgram.course.containsKey(courseID)) {
degreeProgram.course.get(courseID).add(newNode);
} else {
ArrayList<Node> clist = new ArrayList<Node>();
clist.add(newNode);
degreeProgram.course.put(courseID, clist);
}
simpleReq1.insertNode(newNode);
/**
* @author tongrui
* function: construct the crosslist
*/
allCross_relation.addCourse(Integer.valueOf(courseID));
Course course = Course.findById(courseID);
String prereq = course.getPrereq(2);
String coreq = course.getCoreq(2);
if (!prereq.trim().equals("-")) {
String[] prelist = prereq.split(" ");
if (prelist.length - 2 == 1) {
allCross_relation.setArcBox(Integer.valueOf(prelist[2]), courseID, 1);
} else if (prelist.length - 2 == 3) {
if (prelist[3].equals(",")) {
allCross_relation.setArcBox(Integer.valueOf(prelist[2]), courseID, 1);
allCross_relation.setArcBox(Integer.valueOf(prelist[4]), courseID, 1);
} else if (prelist[3].equals("or")) {
allCross_relation.addCourse(--redNode);
allCross_relation.setArcBox(Integer.valueOf(prelist[2]), redNode, 3);
allCross_relation.setArcBox(Integer.valueOf(prelist[4]), redNode, 3);
allCross_relation.setArcBox(redNode, courseID, 3);
}
} else if (prelist.length - 2 == 5) {
if (prelist[3].equals(",")) {
allCross_relation.setArcBox(Integer.valueOf(prelist[2]), courseID, 1);
allCross_relation.setArcBox(Integer.valueOf(prelist[4]), courseID, 1);
if (prelist[5].equals("or")) {
// issue
} else if (prelist[5].equals(",")) {
allCross_relation.setArcBox(Integer.valueOf(prelist[6]), courseID, 1);
}
} else if (prelist[3].equals("or")) {
allCross_relation.addCourse(--redNode);
allCross_relation.setArcBox(Integer.valueOf(prelist[2]), redNode, 3);
allCross_relation.setArcBox(Integer.valueOf(prelist[4]), redNode, 3);
allCross_relation.setArcBox(redNode, courseID, 3);
if (prelist[5].equals("or")) {
allCross_relation.setArcBox(Integer.valueOf(prelist[6]), redNode, 3);
} else if (prelist[5].equals(",")) {
allCross_relation.setArcBox(redNode, courseID, 3);
allCross_relation.setArcBox(Integer.valueOf(prelist[6]), courseID, 1);
}
}
}
}
if (!coreq.trim().equals("-")) {
String[] colist = coreq.split(" ");
if (colist.length - 2 == 1) {
allCross_relation.setArcBox(Integer.valueOf(colist[2]), courseID, 2);
} else if (colist.length - 2 == 3) {
if (colist[3].equals(",")) {
allCross_relation.setArcBox(Integer.valueOf(colist[2]), courseID, 2);
allCross_relation.setArcBox(Integer.valueOf(colist[4]), courseID, 2);
} else if (colist[3].equals("or")) {
allCross_relation.addCourse(--redNode);
allCross_relation.setArcBox(Integer.valueOf(colist[2]), redNode, 3);
allCross_relation.setArcBox(Integer.valueOf(colist[4]), redNode, 3);
allCross_relation.setArcBox(redNode, courseID, 3);
}
} else if (colist.length - 2 == 5) {
if (colist[3].equals(",")) {
allCross_relation.setArcBox(Integer.valueOf(colist[2]), courseID, 2);
allCross_relation.setArcBox(Integer.valueOf(colist[4]), courseID, 2);
if (colist[5].equals("or")) {
// issue
} else if (colist[5].equals(",")) {
allCross_relation.setArcBox(Integer.valueOf(colist[6]), courseID, 2);
}
} else if (colist[3].equals("or")) {
allCross_relation.addCourse(--redNode);
allCross_relation.setArcBox(Integer.valueOf(colist[2]), redNode, 3);
allCross_relation.setArcBox(Integer.valueOf(colist[4]), redNode, 3);
allCross_relation.setArcBox(redNode, courseID, 3);
if (colist[5].equals("or")) {
allCross_relation.setArcBox(Integer.valueOf(colist[6]), redNode, 3);
} else if (colist[5].equals(",")) {
allCross_relation.setArcBox(redNode, courseID, 3);
allCross_relation.setArcBox(Integer.valueOf(colist[6]), courseID, 2);
}
}
}
}
return;
}
public static void add2Course_List2(TestLinkList degreeProgram, Linklist simpleReq1, int courseID){
boolean ifCourseExist = degreeProgram.prepareInsertCourseLinkList(courseID);
if(ifCourseExist){
int simpleReqName = simpleReq1.first.cName;
CourseNode simpleReq = new CourseNode(simpleReqName);
for(int i =0; i<degreeProgram.course_list2.size();i++){
if(courseID == degreeProgram.course_list2.get(i).first.rName){
degreeProgram.course_list2.get(i).insertNode(simpleReq);
}
}
}else{
Course_LinkList courseNode = new Course_LinkList(courseID);
int simpleReqName = simpleReq1.first.cName;
CourseNode simpleReq = new CourseNode(simpleReqName);
courseNode.insertNode(simpleReq);
degreeProgram.addReq2List(courseNode);
}
}
public static Linklist find_or_create_simpleReq(TestLinkList degreeProgram, int srId, String srTitle, int reqNum){
boolean simpleReqExist = degreeProgram.prepareInsertSimple(srId);
if(simpleReqExist){
int i=0;
for(; i<degreeProgram.course_list.size();i++){
if(srId == degreeProgram.course_list.get(i).first.cName)
break;
}
return degreeProgram.course_list.get(i);
}else{
Linklist simpleReq = new Linklist(srId, srTitle, reqNum);
return simpleReq;
}
}
} |
package org.encog.neural.networks.structure;
import org.encog.engine.EngineMachineLearning;
import org.encog.engine.network.flat.ActivationFunctions;
import org.encog.engine.validate.BasicMachineLearningValidate;
import org.encog.neural.NeuralNetworkError;
import org.encog.neural.activation.ActivationLinear;
import org.encog.neural.activation.ActivationSigmoid;
import org.encog.neural.activation.ActivationTANH;
import org.encog.neural.networks.BasicNetwork;
import org.encog.neural.networks.layers.BasicLayer;
import org.encog.neural.networks.layers.ContextLayer;
import org.encog.neural.networks.layers.Layer;
import org.encog.neural.networks.layers.RadialBasisFunctionLayer;
import org.encog.neural.networks.logic.FeedforwardLogic;
/**
* Only certain types of networks can be converted to a flat network. This class
* validates this.
*/
public class ValidateForFlat extends BasicMachineLearningValidate {
/**
* Determine if the specified neural network can be flat. If it can a null
* is returned, otherwise, an error is returned to show why the network
* cannot be flattened.
*
* @param network
* The network to check.
* @return Null, if the net can not be flattened, an error message
* otherwise.
*/
public String isValid(final EngineMachineLearning eml) {
if( !(eml instanceof BasicNetwork) )
return "Only a BasicNetwork can be converted to a flat network.";
BasicNetwork network = (BasicNetwork)eml;
final Layer inputLayer = network.getLayer(BasicNetwork.TAG_INPUT);
final Layer outputLayer = network.getLayer(BasicNetwork.TAG_OUTPUT);
if (inputLayer == null) {
return "To convert to a flat network, there must be an input layer.";
}
if (outputLayer == null) {
return "To convert to a flat network, there must be an output layer.";
}
if( !(network.getLogic() instanceof FeedforwardLogic) ) {
return "To convert to flat, must be using FeedforwardLogic or SimpleRecurrentLogic.";
}
for (final Layer layer : network.getStructure().getLayers()) {
if (layer.getNext().size() > 2) {
return "To convert to flat a network must have at most two outbound synapses.";
}
if (layer.getClass()!=ContextLayer.class && layer.getClass()!=BasicLayer.class && layer.getClass()!=RadialBasisFunctionLayer.class ) {
return "To convert to flat a network must have only BasicLayer and ContextLayer layers.";
}
}
return null;
}
} |
package org.objectweb.proactive.core.body;
import org.objectweb.proactive.core.body.future.Future;
import org.objectweb.proactive.core.body.future.FuturePool;
import org.objectweb.proactive.core.body.request.BlockingRequestQueue;
import org.objectweb.proactive.core.body.request.Request;
import org.objectweb.proactive.core.mop.MethodCall;
import org.objectweb.proactive.ext.security.exceptions.RenegotiateSessionException;
/**
* An object implementing this interface is an implementation of one part
* of the local view of the body of an active object. This interface define
* only one part of the local view and is used to be able to change easily the
* strategy of a body. Typically, after a body migrates, it is necessary to change
* the its local implementation.
* @author ProActive Team
* @version 1.0, 2001/10/23
* @since ProActive 0.9
*/
public interface LocalBodyStrategy {
/**
* Returns the future pool of this body
* @return the future pool of this body
*/
public FuturePool getFuturePool();
/**
* Returns the request queue associated to this body
* @return the request queue associated to this body
*/
public BlockingRequestQueue getRequestQueue();
/**
* Returns the reified object that body is for
* The reified object is the object that has been turned active.
* @return the reified object that body is for
*/
public Object getReifiedObject();
/**
* Returns the name of this body that can be used for displaying information
* @return the name of this body
*/
public String getName();
/**
* Sends the request <code>request</code> with the future <code>future</code> to the local body
* <code>body</code>.
* @param methodCall the methodCall to send
* @param future the future associated to the request
* @param destinationBody the body the request is sent to
* @exception java.io.IOException if the request cannot be sent to the destination body
*/
public void sendRequest(MethodCall methodCall, Future future,
UniversalBody destinationBody)
throws java.io.IOException, RenegotiateSessionException;
;
/**
* Serves the request <code>request</code> by the invoking the targeted method on the
* reified object. Some specific type of request may involve special processing that
* does not trigger a method on the reified object.
* @param request the request to serve
*/
public void serve(Request request);
} |
package org.opencms.xml.content;
import org.opencms.ade.containerpage.shared.CmsFormatterConfig;
import org.opencms.db.CmsUserSettings;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.types.CmsResourceTypeXmlContent;
import org.opencms.i18n.CmsMessages;
import org.opencms.i18n.CmsMultiMessages;
import org.opencms.json.JSONException;
import org.opencms.json.JSONObject;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.relations.CmsLink;
import org.opencms.relations.CmsRelationType;
import org.opencms.util.CmsMacroResolver;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.xml.CmsXmlContentDefinition;
import org.opencms.xml.CmsXmlGenericWrapper;
import org.opencms.xml.CmsXmlUtils;
import org.opencms.xml.containerpage.I_CmsFormatterBean;
import org.opencms.xml.content.CmsXmlContentProperty.PropType;
import org.opencms.xml.page.CmsXmlPage;
import org.opencms.xml.types.CmsXmlNestedContentDefinition;
import org.opencms.xml.types.CmsXmlVfsFileValue;
import org.opencms.xml.types.I_CmsXmlContentValue;
import org.opencms.xml.types.I_CmsXmlSchemaType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.dom4j.Element;
/**
* Provides common methods on XML property configuration.<p>
*
* @since 8.0.0
*/
public final class CmsXmlContentPropertyHelper implements Cloneable {
/** Element Property json property constants. */
public enum JsonProperty {
/** Property's default value. */
defaultValue,
/** Property's description. */
description,
/** Property's error message. */
error,
/** Property's nice name. */
niceName,
/** Property's validation regular expression. */
ruleRegex,
/** Property's validation rule type. */
ruleType,
/** Property's type. */
type,
/** Property's value. */
value,
/** Property's widget. */
widget,
/** Property's widget configuration. */
widgetConf;
}
/** Widget configuration key-value separator constant. */
private static final String CONF_KEYVALUE_SEPARATOR = ":";
/** Widget configuration parameter separator constant. */
private static final String CONF_PARAM_SEPARATOR = "\\|";
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsXmlContentPropertyHelper.class);
/**
* Hidden constructor.<p>
*/
private CmsXmlContentPropertyHelper() {
// prevent instantiation
}
/**
* Converts a map of properties from server format to client format.<p>
*
* @param cms the CmsObject to use for VFS operations
* @param props the map of properties
* @param propConfig the property configuration
*
* @return the converted property map
*/
public static Map<String, String> convertPropertiesToClientFormat(
CmsObject cms,
Map<String, String> props,
Map<String, CmsXmlContentProperty> propConfig) {
return convertProperties(cms, props, propConfig, true);
}
/**
* Converts a map of properties from client format to server format.<p>
*
* @param cms the CmsObject to use for VFS operations
* @param props the map of properties
* @param propConfig the property configuration
*
* @return the converted property map
*/
public static Map<String, String> convertPropertiesToServerFormat(
CmsObject cms,
Map<String, String> props,
Map<String, CmsXmlContentProperty> propConfig) {
return convertProperties(cms, props, propConfig, false);
}
/**
* Creates a deep copy of a property configuration map.<p>
*
* @param propConfig the property configuration which should be copied
*
* @return a copy of the property configuration
*/
public static Map<String, CmsXmlContentProperty> copyPropertyConfiguration(
Map<String, CmsXmlContentProperty> propConfig) {
Map<String, CmsXmlContentProperty> result = new LinkedHashMap<String, CmsXmlContentProperty>();
for (Map.Entry<String, CmsXmlContentProperty> entry : propConfig.entrySet()) {
String key = entry.getKey();
CmsXmlContentProperty propDef = entry.getValue();
result.put(key, propDef.copy());
}
return result;
}
/**
* Looks up an URI in the sitemap and returns either a sitemap entry id (if the URI is a sitemap URI)
* or the structure id of a resource (if the URI is a VFS path).<p>
*
* @param cms the current CMS context
* @param uri the URI to look up
* @return a sitemap entry id or a structure id
*
* @throws CmsException if something goes wrong
*/
public static CmsUUID getIdForUri(CmsObject cms, String uri) throws CmsException {
return cms.readResource(uri).getStructureId();
}
/**
* Creates and configures a new macro resolver for resolving macros which occur in property definitions.<p>
*
* @param cms the CMS context
* @param contentHandler the content handler which contains the message bundle that should be available in the macro resolver
*
* @return a new macro resolver
*/
public static CmsMacroResolver getMacroResolverForProperties(CmsObject cms, I_CmsXmlContentHandler contentHandler) {
CmsMacroResolver resolver = new CmsMacroResolver();
resolver.setCmsObject(cms);
CmsUserSettings settings = new CmsUserSettings(cms.getRequestContext().getCurrentUser());
CmsMultiMessages multimessages = new CmsMultiMessages(settings.getLocale());
CmsMessages messages = contentHandler.getMessages(settings.getLocale());
multimessages.addMessages(messages);
multimessages.addMessages(OpenCms.getWorkplaceManager().getMessages(settings.getLocale()));
resolver.setMessages(multimessages);
resolver.setKeepEmptyMacros(true);
return resolver;
}
/**
* Returns the property information for the given resource (type) AND the current user.<p>
*
* @param cms the current CMS context
* @param resource the resource
*
* @return the property information
*
* @throws CmsException if something goes wrong
*/
public static Map<String, CmsXmlContentProperty> getPropertyInfo(CmsObject cms, CmsResource resource)
throws CmsException {
if (CmsResourceTypeXmlContent.isXmlContent(resource)) {
I_CmsXmlContentHandler contentHandler = CmsXmlContentDefinition.getContentHandlerForResource(cms, resource);
Map<String, CmsXmlContentProperty> propertiesConf = contentHandler.getSettings(cms, resource);
CmsMacroResolver resolver = getMacroResolverForProperties(cms, contentHandler);
return resolveMacrosInProperties(propertiesConf, resolver);
}
return Collections.<String, CmsXmlContentProperty> emptyMap();
}
/**
* Returns a converted property value depending on the given type.<p>
*
* If the type is {@link CmsXmlContentProperty.PropType#vfslist}, the value is parsed as a
* list of paths and converted to a list of IDs.<p>
*
* @param cms the current CMS context
* @param type the property type
* @param value the raw property value
*
* @return a converted property value depending on the given type
*/
public static String getPropValueIds(CmsObject cms, String type, String value) {
if (PropType.isVfsList(type)) {
return convertPathsToIds(cms, value);
}
return value;
}
/**
* Returns a converted property value depending on the given type.<p>
*
* If the type is {@link CmsXmlContentProperty.PropType#vfslist}, the value is parsed as a
* list of IDs and converted to a list of paths.<p>
*
* @param cms the current CMS context
* @param type the property type
* @param value the raw property value
*
* @return a converted property value depending on the given type
*/
public static String getPropValuePaths(CmsObject cms, String type, String value) {
if (PropType.isVfsList(type)) {
return convertIdsToPaths(cms, value);
}
return value;
}
/**
* Returns a sitemap or VFS path given a sitemap entry id or structure id.<p>
*
* This method first tries to read a sitemap entry with the given id. If this succeeds,
* the sitemap entry's sitemap path will be returned. If it fails, the method interprets
* the id as a structure id and tries to read the corresponding resource, and then returns
* its VFS path.<p>
*
* @param cms the CMS context
* @param id a sitemap entry id or structure id
*
* @return a sitemap or VFS uri
*
* @throws CmsException if something goes wrong
*/
public static String getUriForId(CmsObject cms, CmsUUID id) throws CmsException {
CmsResource res = cms.readResource(id);
return cms.getSitePath(res);
}
/**
* Returns the widget configuration string parsed into a JSONObject.<p>
*
* The configuration string should be a map of key value pairs separated by ':' and '|': KEY_1:VALUE_1|KEY_2:VALUE_2 ...
*
* @param widgetConfiguration the configuration to parse
*
* @return the configuration JSON
*/
public static JSONObject getWidgetConfigurationAsJSON(String widgetConfiguration) {
JSONObject result = new JSONObject();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(widgetConfiguration)) {
return result;
}
Map<String, String> confEntries = CmsStringUtil.splitAsMap(
widgetConfiguration,
CONF_PARAM_SEPARATOR,
CONF_KEYVALUE_SEPARATOR);
for (Map.Entry<String, String> entry : confEntries.entrySet()) {
try {
result.put(entry.getKey(), entry.getValue());
} catch (JSONException e) {
// should never happen
LOG.error(
Messages.get().container(Messages.ERR_XMLCONTENT_UNKNOWN_ELEM_PATH_SCHEMA_1, widgetConfiguration),
e);
}
}
return result;
}
/**
* Extends the given properties with the default values
* from the resource's property configuration.<p>
*
* @param cms the current CMS context
* @param resource the resource to get the property configuration from
* @param properties the properties to extend
*
* @return a merged map of properties
*/
public static Map<String, String> mergeDefaults(CmsObject cms, CmsResource resource, Map<String, String> properties) {
Map<String, String> result = new HashMap<String, String>();
if (CmsResourceTypeXmlContent.isXmlContent(resource)) {
I_CmsFormatterBean formatter = null;
// check formatter configuration setting
for (Entry<String, String> property : properties.entrySet()) {
if (property.getKey().startsWith(CmsFormatterConfig.FORMATTER_SETTINGS_KEY)
&& CmsUUID.isValidUUID(property.getValue())) {
formatter = OpenCms.getADEManager().getCachedFormatters(
cms.getRequestContext().getCurrentProject().isOnlineProject()).getFormatters().get(
new CmsUUID(property.getValue()));
break;
}
}
try {
Map<String, CmsXmlContentProperty> propertyConfig;
if (formatter != null) {
propertyConfig = formatter.getSettings();
} else {
// fall back to schema configuration
propertyConfig = CmsXmlContentDefinition.getContentHandlerForResource(cms, resource).getSettings(
cms,
resource);
}
for (Map.Entry<String, CmsXmlContentProperty> entry : propertyConfig.entrySet()) {
CmsXmlContentProperty prop = entry.getValue();
result.put(entry.getKey(), getPropValueIds(cms, prop.getType(), prop.getDefault()));
}
} catch (CmsException e) {
// should never happen
LOG.error(e.getLocalizedMessage(), e);
}
}
result.putAll(properties);
return result;
}
/**
* Reads property nodes from the given location.<p>
*
* @param cms the current cms context
* @param baseLocation the base location
*
* @return the properties
*/
public static Map<String, String> readProperties(CmsObject cms, I_CmsXmlContentLocation baseLocation) {
Map<String, String> result = new HashMap<String, String>();
String elementName = CmsXmlContentProperty.XmlNode.Properties.name();
String nameElementName = CmsXmlContentProperty.XmlNode.Name.name();
List<I_CmsXmlContentValueLocation> propertyLocations = baseLocation.getSubValues(elementName);
for (I_CmsXmlContentValueLocation propertyLocation : propertyLocations) {
I_CmsXmlContentValueLocation nameLocation = propertyLocation.getSubValue(nameElementName);
String name = nameLocation.asString(cms).trim();
String value = null;
I_CmsXmlContentValueLocation valueLocation = propertyLocation.getSubValue(CmsXmlContentProperty.XmlNode.Value.name());
I_CmsXmlContentValueLocation stringLocation = valueLocation.getSubValue(CmsXmlContentProperty.XmlNode.String.name());
I_CmsXmlContentValueLocation fileListLocation = valueLocation.getSubValue(CmsXmlContentProperty.XmlNode.FileList.name());
if (stringLocation != null) {
value = stringLocation.asString(cms).trim();
} else if (fileListLocation != null) {
List<CmsUUID> idList = new ArrayList<CmsUUID>();
List<I_CmsXmlContentValueLocation> fileLocations = fileListLocation.getSubValues(CmsXmlContentProperty.XmlNode.Uri.name());
for (I_CmsXmlContentValueLocation fileLocation : fileLocations) {
CmsUUID structureId = fileLocation.asId(cms);
idList.add(structureId);
}
value = CmsStringUtil.listAsString(idList, CmsXmlContentProperty.PROP_SEPARATOR);
}
if (value != null) {
result.put(name, value);
}
}
return result;
}
/**
* Reads the properties from property-enabled xml content values.<p>
*
* @param xmlContent the xml content
* @param locale the current locale
* @param element the xml element
* @param elemPath the xpath
* @param elemDef the element definition
*
* @return the read property map
*
* @see org.opencms.xml.containerpage.CmsXmlContainerPage.XmlNode#Elements
*/
public static Map<String, String> readProperties(
CmsXmlContent xmlContent,
Locale locale,
Element element,
String elemPath,
CmsXmlContentDefinition elemDef) {
Map<String, String> propertiesMap = new HashMap<String, String>();
// Properties
for (Iterator<Element> itProps = CmsXmlGenericWrapper.elementIterator(
element,
CmsXmlContentProperty.XmlNode.Properties.name()); itProps.hasNext();) {
Element property = itProps.next();
// property itself
int propIndex = CmsXmlUtils.getXpathIndexInt(property.getUniquePath(element));
String propPath = CmsXmlUtils.concatXpath(
elemPath,
CmsXmlUtils.createXpathElement(property.getName(), propIndex));
I_CmsXmlSchemaType propSchemaType = elemDef.getSchemaType(property.getName());
I_CmsXmlContentValue propValue = propSchemaType.createValue(xmlContent, property, locale);
xmlContent.addBookmarkForValue(propValue, propPath, locale, true);
CmsXmlContentDefinition propDef = ((CmsXmlNestedContentDefinition)propSchemaType).getNestedContentDefinition();
// name
Element propName = property.element(CmsXmlContentProperty.XmlNode.Name.name());
xmlContent.addBookmarkForElement(propName, locale, property, propPath, propDef);
// choice value
Element value = property.element(CmsXmlContentProperty.XmlNode.Value.name());
if (value == null) {
// this can happen when adding the elements node to the xml content
continue;
}
int valueIndex = CmsXmlUtils.getXpathIndexInt(value.getUniquePath(property));
String valuePath = CmsXmlUtils.concatXpath(
propPath,
CmsXmlUtils.createXpathElement(value.getName(), valueIndex));
I_CmsXmlSchemaType valueSchemaType = propDef.getSchemaType(value.getName());
I_CmsXmlContentValue valueValue = valueSchemaType.createValue(xmlContent, value, locale);
xmlContent.addBookmarkForValue(valueValue, valuePath, locale, true);
CmsXmlContentDefinition valueDef = ((CmsXmlNestedContentDefinition)valueSchemaType).getNestedContentDefinition();
String val = null;
Element string = value.element(CmsXmlContentProperty.XmlNode.String.name());
if (string != null) {
// string value
xmlContent.addBookmarkForElement(string, locale, value, valuePath, valueDef);
val = string.getTextTrim();
} else {
// file list value
Element valueFileList = value.element(CmsXmlContentProperty.XmlNode.FileList.name());
if (valueFileList == null) {
// this can happen when adding the elements node to the xml content
continue;
}
int valueFileListIndex = CmsXmlUtils.getXpathIndexInt(valueFileList.getUniquePath(value));
String valueFileListPath = CmsXmlUtils.concatXpath(
valuePath,
CmsXmlUtils.createXpathElement(valueFileList.getName(), valueFileListIndex));
I_CmsXmlSchemaType valueFileListSchemaType = valueDef.getSchemaType(valueFileList.getName());
I_CmsXmlContentValue valueFileListValue = valueFileListSchemaType.createValue(
xmlContent,
valueFileList,
locale);
xmlContent.addBookmarkForValue(valueFileListValue, valueFileListPath, locale, true);
CmsXmlContentDefinition valueFileListDef = ((CmsXmlNestedContentDefinition)valueFileListSchemaType).getNestedContentDefinition();
List<CmsUUID> idList = new ArrayList<CmsUUID>();
// files
for (Iterator<Element> itFiles = CmsXmlGenericWrapper.elementIterator(
valueFileList,
CmsXmlContentProperty.XmlNode.Uri.name()); itFiles.hasNext();) {
Element valueUri = itFiles.next();
xmlContent.addBookmarkForElement(
valueUri,
locale,
valueFileList,
valueFileListPath,
valueFileListDef);
Element valueUriLink = valueUri.element(CmsXmlPage.NODE_LINK);
CmsUUID fileId = null;
if (valueUriLink == null) {
// this can happen when adding the elements node to the xml content
// it is not dangerous since the link has to be set before saving
} else {
fileId = new CmsLink(valueUriLink).getStructureId();
idList.add(fileId);
}
}
// comma separated list of UUIDs
val = CmsStringUtil.listAsString(idList, CmsXmlContentProperty.PROP_SEPARATOR);
}
propertiesMap.put(propName.getTextTrim(), val);
}
return propertiesMap;
}
/**
* Resolves macros in the given property information for the given resource (type) AND the current user.<p>
*
* @param cms the current CMS context
* @param resource the resource
* @param propertiesConf the property information
*
* @return the property information
*
* @throws CmsException if something goes wrong
*/
public static Map<String, CmsXmlContentProperty> resolveMacrosForPropertyInfo(
CmsObject cms,
CmsResource resource,
Map<String, CmsXmlContentProperty> propertiesConf) throws CmsException {
if (CmsResourceTypeXmlContent.isXmlContent(resource)) {
I_CmsXmlContentHandler contentHandler = CmsXmlContentDefinition.getContentHandlerForResource(cms, resource);
CmsMacroResolver resolver = getMacroResolverForProperties(cms, contentHandler);
return resolveMacrosInProperties(propertiesConf, resolver);
}
return propertiesConf;
}
/**
* Resolves macros in all properties in a map.<p>
*
* @param properties the map of properties in which macros should be resolved
* @param resolver the macro resolver to use
*
* @return a new map of properties with resolved macros
*/
public static Map<String, CmsXmlContentProperty> resolveMacrosInProperties(
Map<String, CmsXmlContentProperty> properties,
CmsMacroResolver resolver) {
Map<String, CmsXmlContentProperty> result = new LinkedHashMap<String, CmsXmlContentProperty>();
for (Map.Entry<String, CmsXmlContentProperty> entry : properties.entrySet()) {
String key = entry.getKey();
CmsXmlContentProperty prop = entry.getValue();
result.put(key, resolveMacrosInProperty(prop, resolver));
}
return result;
}
/**
* Resolves the macros in a single property.<p>
*
* @param property the property in which macros should be resolved
* @param resolver the macro resolver to use
*
* @return a new property with resolved macros
*/
public static CmsXmlContentProperty resolveMacrosInProperty(
CmsXmlContentProperty property,
CmsMacroResolver resolver) {
String propName = property.getName();
CmsXmlContentProperty result = new CmsXmlContentProperty(
propName,
property.getType(),
property.getWidget(),
resolver.resolveMacros(property.getWidgetConfiguration()),
property.getRuleRegex(),
property.getRuleType(),
property.getDefault(),
resolver.resolveMacros(property.getNiceName()),
resolver.resolveMacros(property.getDescription()),
resolver.resolveMacros(property.getError()),
property.isPreferFolder() ? "true" : "false");
return result;
}
/**
* Saves the given properties to the given xml element.<p>
*
* @param cms the current CMS context
* @param parentElement the parent xml element
* @param properties the properties to save, if there is a list of resources, every entry can be a site path or a UUID
* @param propertiesConf the configuration of the properties
*/
public static void saveProperties(
CmsObject cms,
Element parentElement,
Map<String, String> properties,
Map<String, CmsXmlContentProperty> propertiesConf) {
// remove old entries
for (Object propElement : parentElement.elements(CmsXmlContentProperty.XmlNode.Properties.name())) {
parentElement.remove((Element)propElement);
}
// create new entries
for (Map.Entry<String, String> property : properties.entrySet()) {
String propName = property.getKey();
String propValue = property.getValue();
if ((propValue == null) || (propValue.length() == 0)) {
continue;
}
// only if the property is configured in the schema we will save it
Element propElement = parentElement.addElement(CmsXmlContentProperty.XmlNode.Properties.name());
// the property name
propElement.addElement(CmsXmlContentProperty.XmlNode.Name.name()).addCDATA(propName);
Element valueElement = propElement.addElement(CmsXmlContentProperty.XmlNode.Value.name());
boolean isVfs = false;
CmsXmlContentProperty propDef = propertiesConf.get(propName);
if (propDef != null) {
isVfs = CmsXmlContentProperty.PropType.isVfsList(propDef.getType());
}
if (!isVfs) {
// string value
valueElement.addElement(CmsXmlContentProperty.XmlNode.String.name()).addCDATA(propValue);
} else {
addFileListPropertyValue(cms, valueElement, propValue);
}
}
}
/**
* Adds the XML for a property value of a property of type 'vfslist' to the DOM.<p>
*
* @param cms the current CMS context
* @param valueElement the element to which the vfslist property value should be added
* @param propValue the property value which should be saved
*/
protected static void addFileListPropertyValue(CmsObject cms, Element valueElement, String propValue) {
// resource list value
Element filelistElem = valueElement.addElement(CmsXmlContentProperty.XmlNode.FileList.name());
for (String strId : CmsStringUtil.splitAsList(propValue, CmsXmlContentProperty.PROP_SEPARATOR)) {
try {
Element fileValueElem = filelistElem.addElement(CmsXmlContentProperty.XmlNode.Uri.name());
CmsVfsFileValueBean fileValue = getFileValueForIdOrUri(cms, strId);
// HACK: here we assume weak relations, but it would be more robust to check it, with smth like:
// type = xmlContent.getContentDefinition().getContentHandler().getRelationType(fileValueElem.getPath());
CmsRelationType type = CmsRelationType.XML_WEAK;
CmsXmlVfsFileValue.fillEntry(fileValueElem, fileValue.getId(), fileValue.getPath(), type);
} catch (CmsException e) {
// should never happen
LOG.error(e.getLocalizedMessage(), e);
}
}
}
/**
* Converts a string containing zero or more structure ids into a string containing the corresponding VFS paths.<p>
*
* @param cms the CmsObject to use for the VFS operations
* @param value a string representation of a list of ids
*
* @return a string representation of a list of paths
*/
protected static String convertIdsToPaths(CmsObject cms, String value) {
if (value == null) {
return null;
}
// represent vfslists as lists of path in JSON
List<String> ids = CmsStringUtil.splitAsList(value, CmsXmlContentProperty.PROP_SEPARATOR);
List<String> paths = new ArrayList<String>();
for (String id : ids) {
try {
String path = getUriForId(cms, new CmsUUID(id));
paths.add(path);
} catch (Exception e) {
// should never happen
LOG.error(e.getLocalizedMessage(), e);
continue;
}
}
return CmsStringUtil.listAsString(paths, CmsXmlContentProperty.PROP_SEPARATOR);
}
/**
* Converts a string containing zero or more VFS paths into a string containing the corresponding structure ids.<p>
*
* @param cms the CmsObject to use for the VFS operations
* @param value a string representation of a list of paths
*
* @return a string representation of a list of ids
*/
protected static String convertPathsToIds(CmsObject cms, String value) {
if (value == null) {
return null;
}
// represent vfslists as lists of path in JSON
List<String> paths = CmsStringUtil.splitAsList(value, CmsXmlContentProperty.PROP_SEPARATOR);
List<String> ids = new ArrayList<String>();
for (String path : paths) {
try {
CmsUUID id = getIdForUri(cms, path);
ids.add(id.toString());
} catch (CmsException e) {
// should never happen
LOG.error(e.getLocalizedMessage(), e);
continue;
}
}
return CmsStringUtil.listAsString(ids, CmsXmlContentProperty.PROP_SEPARATOR);
}
/**
* Helper method for converting a map of properties from client format to server format or vice versa.<p>
*
* @param cms the CmsObject to use for VFS operations
* @param props the map of properties
* @param propConfig the property configuration
* @param toClient if true, convert from server to client, else from client to server
*
* @return the converted property map
*/
protected static Map<String, String> convertProperties(
CmsObject cms,
Map<String, String> props,
Map<String, CmsXmlContentProperty> propConfig,
boolean toClient) {
Map<String, String> result = new HashMap<String, String>();
for (Map.Entry<String, String> entry : props.entrySet()) {
String propName = entry.getKey();
String propValue = entry.getValue();
String type = "string";
CmsXmlContentProperty configEntry = getPropertyConfig(propConfig, propName);
if (configEntry != null) {
type = configEntry.getType();
}
String newValue = convertStringPropertyValue(cms, propValue, type, toClient);
result.put(propName, newValue);
}
return result;
}
/**
* Converts a property value given as a string between server format and client format.<p>
*
* @param cms the current CMS context
* @param propValue the property value to convert
* @param type the type of the property
* @param toClient if true, convert to client format, else convert to server format
*
* @return the converted property value
*/
protected static String convertStringPropertyValue(CmsObject cms, String propValue, String type, boolean toClient) {
if (propValue == null) {
return null;
}
if (toClient) {
return CmsXmlContentPropertyHelper.getPropValuePaths(cms, type, propValue);
} else {
return CmsXmlContentPropertyHelper.getPropValueIds(cms, type, propValue);
}
}
/**
* Given a string which might be a id or a (sitemap or VFS) URI, this method will return
* a bean containing the right (sitemap or vfs) root path and (sitemap entry or structure) id.<p>
*
* @param cms the current CMS context
* @param idOrUri a string containing an id or an URI
*
* @return a bean containing a root path and an id
*
* @throws CmsException if something goes wrong
*/
protected static CmsVfsFileValueBean getFileValueForIdOrUri(CmsObject cms, String idOrUri) throws CmsException {
CmsVfsFileValueBean result;
if (CmsUUID.isValidUUID(idOrUri)) {
CmsUUID id = new CmsUUID(idOrUri);
String uri = getUriForId(cms, id);
result = new CmsVfsFileValueBean(cms.getRequestContext().addSiteRoot(uri), id);
} else {
String uri = idOrUri;
CmsUUID id = getIdForUri(cms, idOrUri);
result = new CmsVfsFileValueBean(cms.getRequestContext().addSiteRoot(uri), id);
}
return result;
}
/**
* Helper method for accessing the property configuration for a single property.<p>
*
* This method uses the base name of the property to access the property configuration,
* i.e. if propName starts with a '#', the part after the '#' will be used as the key for
* the property configuration.<p>
*
* @param propertyConfig the property configuration map
* @param propName the name of a property
* @return the property configuration for the given property name
*/
protected static CmsXmlContentProperty getPropertyConfig(
Map<String, CmsXmlContentProperty> propertyConfig,
String propName) {
return propertyConfig.get(propName);
}
} |
package org.pentaho.di.trans.steps.filesfromresult;
import org.pentaho.di.i18n.BaseMessages;
public class Messages
{
public static final String packageName = Messages.class.getPackage().getName();
public static String getString(String key)
{
return BaseMessages.getString(packageName, key);
}
public static String getString(String key, String param1)
{
return BaseMessages.getString(packageName, key, param1);
}
public static String getString(String key, String param1, String param2)
{
return BaseMessages.getString(packageName, key, param1, param2);
}
public static String getString(String key, String param1, String param2, String param3)
{
return BaseMessages.getString(packageName, key, param1, param2, param3);
}
public static String getString(String key, String param1, String param2, String param3, String param4)
{
return BaseMessages.getString(packageName, key, param1, param2, param3, param4);
}
public static String getString(String key, String param1, String param2, String param3, String param4, String param5)
{
return BaseMessages.getString(packageName, key, param1, param2, param3, param4, param5);
}
public static String getString(String key, String param1, String param2, String param3, String param4, String param5, String param6)
{
return BaseMessages.getString(packageName, key, param1, param2, param3, param4, param5, param6);
}
} |
package org.seqcode.projects.sequnwinder.utils;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.UnaryOperator;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.seqcode.data.motifdb.WeightMatrix;
import org.seqcode.data.motifdb.WeightMatrixPainter;
import org.seqcode.gseutils.ArgParser;
import org.seqcode.gseutils.Args;
import org.seqcode.motifs.FreqMatrixImport;
import org.seqcode.viz.paintable.AbstractPaintable;
import org.seqcode.viz.paintable.PaintableFrame;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
public class HeatMapMaker extends AbstractPaintable {
protected Map<String,ArrayList<Double>> matrix = new HashMap<String,ArrayList<Double>>(); // matrix to draw a heat-map
protected List<String> colnames = new ArrayList<String>(); // col-names; labels or sub-groups
protected List<String> rownames = new ArrayList<String>(); // row-names; motif names
protected List<WeightMatrix> motifs = new ArrayList<WeightMatrix>(); // motifs; should be in the same order as rownames
private int ScreenSizeX=1000;
private int ScreenSizeY=1000;
private final int topBorder=50, bottomBorder=150;
private final int leftBorder=25, rightBorder=25,colLabSize=25;
private int topBound, bottomBound, leftBound, rightBound, baseLine, midLine;
private static int numVals =4;
private int BoxHeight=40, BoxWidth=40, colorbarWidth = 120, colorbarHeight=15;
private double maxExp=0.4, midExp=0, minExp=-0.4;
private Color expMaxColor = Color.yellow;
private Color expMidColor = Color.black;
private Color expMinColor = Color.blue;
private boolean singleColScheme = false;
private boolean drawMotiflabs = true;
public Image getImage(int w, int h){
Image im = createImage(w,h);
return im;
}
public int getImageWidth(){return ScreenSizeX;}
public int getImageHeight(){return ScreenSizeY;}
public void setMinExp(double m){minExp = m;}
public void setMaxExp(double m){maxExp = m;}
public void adjMidVal(){midExp = minExp+(maxExp - minExp)/2; }
public HeatMapMaker(Map<String,ArrayList<Double>> m, List<String> cn, List<String> rn, boolean colScheme) {
matrix.putAll(m);
colnames.addAll(cn);
rownames.addAll(rn);
numVals = colnames.size();
ScreenSizeY = rownames.size()*BoxHeight + 250;
ScreenSizeX = colnames.size()*BoxWidth + 300;
topBound = topBorder+50;
bottomBound = ScreenSizeY-bottomBorder;
leftBound = leftBorder;
rightBound = ScreenSizeX - rightBorder-200;
singleColScheme = colScheme;
if(singleColScheme){
expMaxColor = Color.yellow;
expMinColor = Color.black;
int red = (int)(expMaxColor.getRed() * 0.5 + expMinColor.getRed() * 0.5);
int green = (int)(expMaxColor.getGreen() * 0.5 + expMinColor.getGreen() * 0.5);
int blue = (int)(expMaxColor.getBlue() *0.5 + expMinColor.getBlue() *0.5);
expMidColor = new Color(red,green,blue);
}
}
public void setDrawMotiflabs(boolean b){drawMotiflabs = b;}
public void setColorScheme(boolean b){singleColScheme = b;}
// Load freq matrices
public void loadMotifsFromFile(String filename) throws NumberFormatException, IOException {
FreqMatrixImport motifImport = new FreqMatrixImport();
List<WeightMatrix> tmp = new ArrayList<WeightMatrix>();
tmp.addAll(motifImport.readTransfacMatricesAsFreqMatrices(filename));
for(String motname : rownames){
for(WeightMatrix wm : tmp){
if(wm.getName().equals(motname)){
motifs.add(wm);
break;
}
}
}
}
private void drawExpColorBar(Graphics2D g2d, int x, int y){
//Draw colors
GradientPaint colorbar = new GradientPaint(x, y, expMinColor, x+colorbarWidth/2, y, expMidColor, false);
g2d.setPaint(colorbar);
g2d.fillRect(x, y, colorbarWidth/2, colorbarHeight);
colorbar = new GradientPaint(x+colorbarWidth/2, y, expMidColor, x+colorbarWidth, y, expMaxColor, false);
g2d.setPaint(colorbar);
g2d.fillRect(x+(colorbarWidth/2), y, colorbarWidth/2, colorbarHeight);
//Draw border
g2d.setPaint(Color.black);
g2d.setColor(Color.black);
g2d.setStroke(new BasicStroke(1.0f));
g2d.drawRect(x, y, colorbarWidth, colorbarHeight);
//Legend
g2d.setFont(new Font("Ariel", Font.PLAIN, 25));
FontMetrics metrics = g2d.getFontMetrics();
int textY = y+colorbarHeight+ (metrics.getHeight());
g2d.drawString("0", x+(colorbarWidth/2)-(metrics.stringWidth("0")/2), textY);
g2d.drawString(String.format("%.1f",minExp), x-(metrics.stringWidth(String.format(".1f",minExp))/2), textY);
g2d.drawString(String.format("%.1f",maxExp), x+colorbarWidth-(metrics.stringWidth(String.format(".1f",maxExp))/2), textY);
//Title
g2d.setFont(new Font("Ariel", Font.PLAIN, 25));
metrics = g2d.getFontMetrics();
//g2d.drawString("Model specific discriminative score", x+(colorbarWidth/2)-(metrics.stringWidth("Model specific discriminative score")/2), y- (metrics.getHeight())/2);
g2d.drawString("Model specific", x+(colorbarWidth/2)-(metrics.stringWidth("Model specific")/2), y- (metrics.getHeight()));
g2d.drawString("discriminative score", x+(colorbarWidth/2)-(metrics.stringWidth("discriminative score")/2), y- (metrics.getHeight())/3);
}
@Override
public void paintItem(Graphics g, int x1, int y1, int x2, int y2) {
Graphics2D g2d = (Graphics2D)g;
// get the screen sizes
int screenSizeX = x2-x1;
int screenSizeY = y2-y1;
// make the background
g2d.setColor(Color.white);
g2d.fillRect(0, 0, screenSizeX, screenSizeY);
baseLine = (topBound+bottomBound)/2;
midLine = (leftBound+rightBound)/2;
int xPos = (leftBound+rightBound)/2;
// paint the column names
//AffineTransform old = g2d.getTransform();
//g2d.rotate(-Math.toRadians(90));
//Font collabelFont = new Font("Arial",Font.PLAIN,colLabSize);
//g2d.setFont(collabelFont);
//g2d.setColor(Color.BLACK);
//for(int c=0; c<colnames.size(); c++){
//g2d.setTransform(old);
//Background rounded boxes
//int j=0;
for(int r=0; r<rownames.size(); r++){
String motifName = rownames.get(r);
boolean found =false;
int boxX = xPos-BoxWidth*numVals/2;
int boxY = topBound+BoxHeight*r;
g2d.setColor(Color.gray);
g2d.setStroke(new BasicStroke(1.0f));
g2d.fillRect(boxX, boxY, BoxWidth*numVals,BoxHeight);
g2d.setColor(Color.darkGray);
g2d.fillRect(boxX, boxY, BoxWidth*numVals, BoxHeight);
//Default expression boxes
int eY = boxY;
for(int c=0; c<numVals; c++){
int eX = xPos - BoxWidth*numVals/2 +(c*BoxWidth);
g2d.setColor(Color.lightGray);
g2d.fillRect(eX, eY,BoxWidth, BoxHeight);
g2d.setColor(Color.white);
g2d.setStroke(new BasicStroke(1.0f));
g2d.drawRect(eX, eY,BoxWidth, BoxHeight);
}
//Find appropriate expression values
for(int c=0; c<numVals; c++){
Double v = matrix.get(motifName).get(c);
Color currCol = expColor(v);
int eX = xPos - BoxWidth*numVals/2 +(c*BoxWidth);
g2d.setColor(currCol);
g2d.fillRect(eX, eY,BoxWidth, BoxHeight);
g2d.setColor(Color.white);
g2d.setStroke(new BasicStroke(1.0f));
g2d.drawRect(eX, eY,BoxWidth, BoxHeight);
}
// now paint the motif
WeightMatrixPainter wmp = new WeightMatrixPainter();
if(drawMotiflabs){
wmp.paint(motifs.get(r),g2d,boxX+BoxWidth*numVals+30,boxY+2,boxX+BoxWidth*numVals+30+120,boxY+2+BoxHeight-4, rownames.get(r), false);
}else{
wmp.paint(motifs.get(r),g2d,boxX+BoxWidth*numVals+30,boxY+2,boxX+BoxWidth*numVals+30+120,boxY+2+BoxHeight-4, " ", false);
}
}
// draw the legend
drawExpColorBar(g2d,xPos-60,topBound+BoxHeight*(2+matrix.keySet().size()));
}
private Color expColor(double v){
Color c;
if(v>midExp){
Color maxColor = expMaxColor;
Color minColor = expMidColor;
double sVal = v>maxExp ? 1 : (v-midExp)/(maxExp-midExp);
int red = (int)(maxColor.getRed() * sVal + minColor.getRed() * (1 - sVal));
int green = (int)(maxColor.getGreen() * sVal + minColor.getGreen() * (1 - sVal));
int blue = (int)(maxColor.getBlue() *sVal + minColor.getBlue() * (1 - sVal));
c = new Color(red, green, blue);
}else{
Color maxColor = expMidColor;
Color minColor = expMinColor;
double sVal = v<minExp ? 0 : ((midExp-minExp)-(midExp-v))/(midExp-minExp);
int red = (int)(maxColor.getRed() * sVal + minColor.getRed() * (1 - sVal));
int green = (int)(maxColor.getGreen() * sVal + minColor.getGreen() * (1 - sVal));
int blue = (int)(maxColor.getBlue() *sVal + minColor.getBlue() * (1 - sVal));
c = new Color(red, green, blue);
}
return(c);
}
/**
* Main method only for testing
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException{
ArgParser ap = new ArgParser(args);
String valsFname = ap.getKeyValue("vals");
ArrayList<String> rnames = new ArrayList<String>();
ArrayList<String> cnames = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(valsFname));
Map<String, ArrayList<Double>> vals = new HashMap<String,ArrayList<Double>>();
String line=null;
while((line=br.readLine()) != null){
String[] pieces = line.split("\t");
if(line.contains("MotifName")){
for(int p=1; p<pieces.length; p++){
cnames.add(pieces[p]);
}
continue;
}else{
rnames.add(pieces[0]);
vals.put(pieces[0], new ArrayList<Double>());
for(int p=1; p<pieces.length; p++){
vals.get(pieces[0]).add(Double.parseDouble(pieces[p]));
}
}
}
br.close();
HeatMapMaker runner = new HeatMapMaker(vals,cnames,rnames,ap.hasKey("singleColScheme"));
if(ap.hasKey("minVal"))
runner.setMinExp(Args.parseDouble(args, "minVal", -1));
if(ap.hasKey("maxVal"))
runner.setMaxExp(Args.parseDouble(args, "maxVal", 1));
runner.adjMidVal();
runner.loadMotifsFromFile(ap.getKeyValue("motifs"));
runner.setDrawMotiflabs(!ap.hasKey("nolabs"));
if(ap.hasKey("raster")){
runner.saveImage(new File("tmpHeatmap.png"), runner.getImageWidth(), runner.getImageHeight(), true);
}else{
runner.saveImage(new File("tmpHeatmap.svg"), runner.getImageWidth(), runner.getImageHeight(), false);
}
}
} |
package org.teachingkidsprogramming.section02methods;
import org.teachingextensions.logo.Tortoise;
import org.teachingextensions.logo.utils.ColorUtils.PenColors;
public class Houses
{
public static void main(String[] args)
{
Tortoise.show();
Tortoise.setSpeed(10);
Tortoise.setX(200);
int height = 40;
drawHouse(height);
drawHouse(120);
drawHouse(90);
drawHouse(20);
drawHouse(100);
drawHouse(80);
drawHouse(40);
drawHouse(150);
}
private static void drawHouse(int height)
{
Tortoise.setPenColor(PenColors.Grays.LightGray);
Tortoise.move(height);
Tortoise.turn(90);
Tortoise.move(30);
Tortoise.turn(90);
Tortoise.move(height);
Tortoise.turn(-90);
Tortoise.move(20);
Tortoise.turn(-90);
}
} |
package org.usfirst.frc.team1306.robot.commands;
import org.usfirst.frc.team1306.robot.OI;
import org.usfirst.frc.team1306.robot.subsystems.Drivetrain;
import org.usfirst.frc.team1306.robot.subsystems.Intake;
import org.usfirst.frc.team1306.robot.subsystems.Shooter;
import org.usfirst.frc.team1306.robot.subsystems.Turret;
import org.usfirst.frc.team1306.robot.vision.Vision;
import edu.wpi.first.wpilibj.command.Command;
/**
* This class is the abstract for all other commands. This static class contains
* instances of all the subsystems and the oi class so that each command that
* extends this class can have access to the subsystems.
*
* @author James Tautges
*/
public abstract class CommandBase extends Command {
protected static OI oi;
protected static Drivetrain drivetrain;
protected static Shooter shooter;
protected static Turret turret;
protected static Intake intake;
protected static Vision vision;
public static void init() {
drivetrain = new Drivetrain();
shooter = new Shooter();
turret = new Turret();
intake = new Intake();
vision = new Vision();
oi = new OI();
}
} |
package org.vitrivr.cineast.core.db.adampro;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.vitrivr.adampro.grpc.AdamGrpc;
import org.vitrivr.adampro.grpc.AdamGrpc.AckMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.AckMessage.Code;
import org.vitrivr.adampro.grpc.AdamGrpc.BatchedQueryMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.BatchedQueryResultsMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.BooleanQueryMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.BooleanQueryMessage.WhereMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.DataMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.DenseVectorMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.EntityPropertiesMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.ExistsMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.ExternalHandlerQueryMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.FromMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.NearestNeighbourQueryMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.PreviewMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.PropertiesMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.QueryMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.QueryResultInfoMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.QueryResultTupleMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.QueryResultsMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.SubExpressionQueryMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.VectorMessage;
import org.vitrivr.cineast.core.config.ReadableQueryConfig;
import org.vitrivr.cineast.core.data.DefaultValueHashMap;
import org.vitrivr.cineast.core.data.distance.DistanceElement;
import org.vitrivr.cineast.core.data.providers.primitive.NothingProvider;
import org.vitrivr.cineast.core.data.providers.primitive.PrimitiveTypeProvider;
import org.vitrivr.cineast.core.db.DBSelector;
import org.vitrivr.cineast.core.db.DataMessageConverter;
import org.vitrivr.cineast.core.db.MergeOperation;
import org.vitrivr.cineast.core.util.LogHelper;
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.ListenableFuture;
public class ADAMproSelector implements DBSelector {
/**
* flag to choose if every selector should have its own connection to ADAMpro or if they should
* share one.
*/
private static boolean useGlobalWrapper = true;
private static final Logger LOGGER = LogManager.getLogger();
private static final ADAMproWrapper GLOBAL_ADAMPRO_WRAPPER = useGlobalWrapper ? new ADAMproWrapper() : null;
private ADAMproWrapper adampro = useGlobalWrapper ? GLOBAL_ADAMPRO_WRAPPER : new ADAMproWrapper();
/** MessageBuilder instance used to create the query messages. */
private final ADAMproMessageBuilder mb = new ADAMproMessageBuilder();
/** Name of the entity the current instance of ADAMproSelector uses. */
private String entityName;
/** FromMessaged used by the instance of ADAMproSelector. */
private FromMessage fromMessage;
@Override
public boolean open(String name) {
this.entityName = name;
this.fromMessage = this.mb.buildFromMessage(name);
return true;
}
@Override
public boolean close() {
if (useGlobalWrapper) {
return false;
}
this.adampro.close();
return true;
}
@Override
public List<float[]> getFeatureVectors(String fieldName, String value, String vectorName) {
QueryMessage qbqm = this.mb.buildQueryMessage(ADAMproMessageBuilder.DEFAULT_HINT, this.fromMessage, this.mb.buildBooleanQueryMessage(this.mb.buildWhereMessage(fieldName, value)), null, null);
ListenableFuture<QueryResultsMessage> f = this.adampro.booleanQuery(qbqm);
ArrayList<float[]> _return = new ArrayList<>();
QueryResultsMessage r;
try {
r = f.get();
} catch (InterruptedException | ExecutionException e) {
LOGGER.error(LogHelper.getStackTrace(e));
return new ArrayList<>(0);
}
if (r.getResponsesCount() == 0) {
return new ArrayList<>(0);
}
QueryResultInfoMessage response = r.getResponses(0); // only head (end-result) is important
AckMessage ack = response.getAck();
if (ack.getCode() != Code.OK) {
LOGGER.error("error in getFeatureVectors on entity {}, ({}) : {}", entityName, ack.getCode(), ack.getMessage());
return _return;
}
for (QueryResultTupleMessage result : response.getResultsList()) {
Map<String, DataMessage> data = result.getDataMap();
if (!data.containsKey(vectorName)) {
continue;
}
DataMessage dm = data.get(vectorName);
if (dm.getDatatypeCase() != DataMessage.DatatypeCase.VECTORDATA) {
continue;
}
VectorMessage featureData = dm.getVectorData();
if (featureData.getVectorCase() != VectorMessage.VectorCase.DENSEVECTOR) {
continue; // TODO add correct handling for sparse and int vectors
}
DenseVectorMessage dense = featureData.getDenseVector();
List<Float> list = dense.getVectorList();
if (list.isEmpty()) {
continue;
}
float[] vector = new float[list.size()];
int i = 0;
for (float x : list) {
vector[i++] = x;
}
_return.add(vector);
}
return _return;
}
/**
* Performs a batched kNN-search with multiple vectors. That is, ADAM pro is tasked to perform the kNN search for each vector in the
* provided list and return results of each query.
*
* @param k The number k vectors to return per query.
* @param vectors The list of vectors to use.
* @param column The column to perform the kNN search on.
* @param distanceElementClass The class to use to create the resulting DistanceElements
* @param configs The query configurations, which may contain distance definitions or query-hints. Every feature should have its own QueryConfig object.
* @param <T> The type T of the resulting DistanceElements.
* @return List of results.
*/
@Override
public <T extends DistanceElement> List<T> getBatchedNearestNeighbours(int k, List<float[]> vectors, String column, Class<T> distanceElementClass, List<ReadableQueryConfig> configs) {
/* Check if sizes of configs and vectors array correspond. */
if (vectors.size() > configs.size()) {
throw new IllegalArgumentException("You must provide a separate QueryConfig entry for each vector - even if it is the same instance of the QueryConfig.");
}
/* Prepare list of QueryMessages. */
List<QueryMessage> queryMessages = new ArrayList<>(vectors.size());
for (int i = 0; i<vectors.size(); i++) {
float[] vector = vectors.get(i);
ReadableQueryConfig config = configs.get(i);
/* Extract hints from QueryConfig. If they're not set, then replace by DEFAULT_HINT. */
Collection<ReadableQueryConfig.Hints> hints;
if (!config.getHints().isEmpty()) {
hints = config.getHints();
} else {
hints = ADAMproMessageBuilder.DEFAULT_HINT;
}
NearestNeighbourQueryMessage nnqMessage = this.mb.buildNearestNeighbourQueryMessage(column, DataMessageConverter.convertVectorMessage(vector), k, config);
queryMessages.add(this.mb.buildQueryMessage(hints, this.fromMessage, null, ADAMproMessageBuilder.DEFAULT_PROJECTION_MESSAGE, nnqMessage));
}
/* Prepare a BatchedQueryMessage. */
BatchedQueryMessage batchedQueryMessage = this.mb.buildBatchedQueryMessage(queryMessages);
ListenableFuture<BatchedQueryResultsMessage> future = this.adampro.batchedQuery(batchedQueryMessage);
BatchedQueryResultsMessage result;
try {
result = future.get();
} catch (InterruptedException | ExecutionException e) {
LOGGER.error(LogHelper.getStackTrace(e));
return new ArrayList<>(0);
}
/* Prepare empty list of results. */
List<T> results = new ArrayList<>(result.getResultsCount());
/*
* Merge results of the partial queries.
*/
for (int i = 0; i<result.getResultsCount(); i++) {
QueryResultsMessage partial = result.getResults(i);
AckMessage ack = partial.getAck();
if (ack.getCode() != AckMessage.Code.OK) {
LOGGER.error("error in getNearestNeighbours on entity {}, ({}) : {}", entityName, ack.getCode(), ack.getMessage());
continue;
}
if (partial.getResponsesCount() == 0) {
continue;
}
QueryResultInfoMessage response = partial.getResponses(0); // only head (end-result) is important
results.addAll(handleNearestNeighbourResponse(response, k, distanceElementClass));
}
return results;
}
/**
* Performs a combined kNN-search with multiple query vectors. That is, the storage engine is tasked to perform the kNN search for each vector and then
* merge the partial result sets pairwise using the desired MergeOperation.
*
* @param k The number k vectors to return per query.
* @param vectors The list of vectors to use.
* @param column The column to perform the kNN search on.
* @param distanceElementClass class of the {@link DistanceElement} type
* @param configs The query configuration, which may contain distance definitions or query-hints.
* @param <T>
* @return
*/
@Override
public <T extends DistanceElement> List<T> getCombinedNearestNeighbours(int k, List<float[]> vectors, String column, Class<T> distanceElementClass, List<ReadableQueryConfig> configs, MergeOperation mergeOperation, Map<String,String> options) {
/* Check if sizes of configs and vectors array correspond. */
if (vectors.size() > configs.size()) {
throw new IllegalArgumentException("You must provide a separate QueryConfig entry for each vector - even if it is the same instance of the QueryConfig.");
}
/* Prepare list of QueryMessages. */
List<SubExpressionQueryMessage> queryMessages = new ArrayList<>(vectors.size());
for (int i = 0; i<vectors.size(); i++) {
float[] vector = vectors.get(i);
ReadableQueryConfig config = configs.get(i);
/* Extract hints from QueryConfig. If they're not set, then replace by DEFAULT_HINT. */
Collection<ReadableQueryConfig.Hints> hints;
if (!config.getHints().isEmpty()) {
hints = config.getHints();
} else {
hints = ADAMproMessageBuilder.DEFAULT_HINT;
}
NearestNeighbourQueryMessage nnqMessage = this.mb.buildNearestNeighbourQueryMessage(column, DataMessageConverter.convertVectorMessage(vector), k, config);
QueryMessage qMessage = this.mb.buildQueryMessage(hints, this.fromMessage, null, ADAMproMessageBuilder.DEFAULT_PROJECTION_MESSAGE, nnqMessage);
queryMessages.add(this.mb.buildSubExpressionQueryMessage(qMessage));
}
/* Constructs the correct SubExpressionQueryMessage bassed on the mergeOperation. */
SubExpressionQueryMessage seqm;
switch (mergeOperation) {
case UNION:
seqm = this.mb.mergeSubexpressions(queryMessages, AdamGrpc.ExpressionQueryMessage.Operation.FUZZYUNION, options);
break;
case INTERSECT:
seqm = this.mb.mergeSubexpressions(queryMessages, AdamGrpc.ExpressionQueryMessage.Operation.FUZZYINTERSECT, options);
break;
case EXCEPT:
seqm = this.mb.mergeSubexpressions(queryMessages, AdamGrpc.ExpressionQueryMessage.Operation.EXCEPT, options);
break;
default:
seqm = this.mb.mergeSubexpressions(queryMessages, AdamGrpc.ExpressionQueryMessage.Operation.FUZZYUNION, options);
break;
}
FromMessage fromMessage = this.mb.buildFromSubExpressionMessage(seqm);
QueryMessage sqMessage = this.mb.buildQueryMessage(null, fromMessage, null, ADAMproMessageBuilder.DEFAULT_PROJECTION_MESSAGE, null);
ListenableFuture<QueryResultsMessage> future = this.adampro.standardQuery(sqMessage);
QueryResultsMessage result;
try {
result = future.get();
} catch (InterruptedException | ExecutionException e) {
LOGGER.error(LogHelper.getStackTrace(e));
return new ArrayList<>(0);
}
AckMessage ack = result.getAck();
if (ack.getCode() != AckMessage.Code.OK) {
LOGGER.error("error in getNearestNeighbours on entity {}, ({}) : {}", entityName, ack.getCode(), ack.getMessage());
return new ArrayList<>(0);
}
if (result.getResponsesCount() == 0) {
return new ArrayList<>(0);
}
QueryResultInfoMessage response = result.getResponses(0); // only head (end-result) is important
return handleNearestNeighbourResponse(response, k, distanceElementClass);
}
@Override
public <T extends DistanceElement> List<T> getNearestNeighbours(int k, float[] vector, String column,
Class<T> distanceElementClass, ReadableQueryConfig config) {
NearestNeighbourQueryMessage nnqMessage = mb.buildNearestNeighbourQueryMessage(column,
DataMessageConverter.convertVectorMessage(vector), k, config);
QueryMessage sqMessage = this.mb.buildQueryMessage(ADAMproMessageBuilder.DEFAULT_HINT, fromMessage, null, ADAMproMessageBuilder.DEFAULT_PROJECTION_MESSAGE, nnqMessage);
ListenableFuture<QueryResultsMessage> future = this.adampro.standardQuery(sqMessage);
QueryResultsMessage result;
try {
result = future.get();
} catch (InterruptedException | ExecutionException e) {
LOGGER.error(LogHelper.getStackTrace(e));
return new ArrayList<>(0);
}
AckMessage ack = result.getAck();
if (ack.getCode() != AckMessage.Code.OK) {
LOGGER.error("error in getNearestNeighbours on entity {}, ({}) : {}", entityName, ack.getCode(), ack.getMessage());
return new ArrayList<>(0);
}
if (result.getResponsesCount() == 0) {
return new ArrayList<>(0);
}
QueryResultInfoMessage response = result.getResponses(0); // only head (end-result) is important
return handleNearestNeighbourResponse(response, k, distanceElementClass);
}
private <T extends DistanceElement> List<T> handleNearestNeighbourResponse(QueryResultInfoMessage response, int k, Class<? extends T> distanceElementClass) {
List<T> result = new ArrayList<>(k);
for (QueryResultTupleMessage msg : response.getResultsList()) {
String id = msg.getDataMap().get("id").getStringData();
if (id == null) {
continue;
}
double distance = msg.getDataMap().get("ap_distance").getDoubleData();
T e = DistanceElement.create(distanceElementClass, id, distance);
result.add(e);
}
return result;
}
@Override
public List<Map<String, PrimitiveTypeProvider>> getRows(String fieldName, String value) {
return getRows(fieldName, Collections.singleton(value));
}
@Override
public List<Map<String, PrimitiveTypeProvider>> getRows(String fieldName, String... values) {
return getRows(fieldName, Arrays.asList(values));
}
@Override
public List<Map<String, PrimitiveTypeProvider>> getRows(String fieldName,
Iterable<String> values) {
if (values == null || Iterables.isEmpty(values)) {
return new ArrayList<>(0);
}
WhereMessage where = this.mb.buildWhereMessage(fieldName, values);
BooleanQueryMessage bqMessage = this.mb.buildBooleanQueryMessage(where);
return executeBooleanQuery(bqMessage);
}
/**
* SELECT label FROM ... Be careful with the size of the resulting List :)
*/
@Override
public List<PrimitiveTypeProvider> getAll(String label) {
List<Map<String, PrimitiveTypeProvider>> resultList = getAll();
return resultList.stream().map(row -> row.get(label)).collect(Collectors.toList());
}
@Override
public List<Map<String, PrimitiveTypeProvider>> getAll() {
return preview(Integer.MAX_VALUE);
}
@Override
public boolean existsEntity(String eName) {
ListenableFuture<ExistsMessage> future = this.adampro.existsEntity(eName);
try {
return future.get().getExists();
} catch (InterruptedException | ExecutionException e) {
LOGGER.error("error in existsEntity, entitiy {}: {}", this.entityName, LogHelper.getStackTrace(e));
return false;
}
}
@Override
public List<Map<String, PrimitiveTypeProvider>> preview(int k) {
PreviewMessage msg = PreviewMessage.newBuilder().setEntity(this.entityName).setN(k)
.build();
ListenableFuture<QueryResultsMessage> f = this.adampro.previewEntity(msg);
QueryResultsMessage result;
try {
result = f.get();
} catch (InterruptedException | ExecutionException e) {
LOGGER.error(LogHelper.getStackTrace(e));
return new ArrayList<>(0);
}
if (result.getResponsesCount() == 0) {
return new ArrayList<>(0);
}
QueryResultInfoMessage response = result.getResponses(0); // only head (end-result) is important
List<QueryResultTupleMessage> resultList = response.getResultsList();
return resultsToMap(resultList);
}
/**
* @param resultList can be empty
* @return an ArrayList of length one if the resultList is empty, else the transformed QueryResultTupleMessage
*/
private List<Map<String, PrimitiveTypeProvider>> resultsToMap(
List<QueryResultTupleMessage> resultList) {
if (resultList.isEmpty()) {
return new ArrayList<>(0);
}
ArrayList<Map<String, PrimitiveTypeProvider>> _return = new ArrayList<>(resultList.size());
for (QueryResultTupleMessage resultMessage : resultList) {
Map<String, DataMessage> data = resultMessage.getDataMap();
Set<String> keys = data.keySet();
DefaultValueHashMap<String, PrimitiveTypeProvider> map = new DefaultValueHashMap<>(NothingProvider.INSTANCE);
for (String key : keys) {
map.put(key, DataMessageConverter.convert(data.get(key)));
}
_return.add(map);
}
return _return;
}
/**
* Executes a QueryMessage and returns the resulting tuples
*
* @return an empty ArrayList if an error happens. Else just the list of rows
*/
private List<Map<String, PrimitiveTypeProvider>> executeQuery(QueryMessage qm) {
ListenableFuture<QueryResultsMessage> f = this.adampro.standardQuery(qm);
QueryResultsMessage result;
try {
result = f.get();
} catch (InterruptedException | ExecutionException e) {
LOGGER.error(LogHelper.getStackTrace(e));
return new ArrayList<>(0);
}
if (result.getAck().getCode() != AckMessage.Code.OK) {
LOGGER.error("Query returned non-OK result code {} with message: {}",
result.getAck().getCode(),
result.getAck().getMessage());
}
if (result.getResponsesCount() == 0) {
return new ArrayList<>(0);
}
QueryResultInfoMessage response = result.getResponses(0); // only head (end-result) is important
List<QueryResultTupleMessage> resultList = response.getResultsList();
return resultsToMap(resultList);
}
private List<Map<String, PrimitiveTypeProvider>> executeBooleanQuery(BooleanQueryMessage bqm) {
QueryMessage qbqm = this.mb.buildQueryMessage(ADAMproMessageBuilder.DEFAULT_HINT, this.fromMessage, bqm, null, null);
return executeQuery(qbqm);
}
@Override
protected void finalize() throws Throwable {
this.close();
super.finalize();
}
@Override
public List<Map<String, PrimitiveTypeProvider>> getNearestNeighbourRows(int k, float[] vector, String column, ReadableQueryConfig config) {
NearestNeighbourQueryMessage nnqMessage = this.mb.buildNearestNeighbourQueryMessage(column,
DataMessageConverter.convertVectorMessage(vector), k, config);
/* Extract hints from QueryConfig. If they're not set, then replace by DEFAULT_HINT. */
Collection<ReadableQueryConfig.Hints> hints;
if (!config.getHints().isEmpty()) {
hints = config.getHints();
} else {
hints = ADAMproMessageBuilder.DEFAULT_HINT;
}
QueryMessage sqMessage = this.mb.buildQueryMessage(hints, this.fromMessage, null, null, nnqMessage);
ListenableFuture<QueryResultsMessage> future = this.adampro.standardQuery(sqMessage);
QueryResultsMessage result;
try {
result = future.get();
} catch (InterruptedException | ExecutionException e) {
LOGGER.error(LogHelper.getStackTrace(e));
return new ArrayList<>(0);
}
if (result.getResponsesCount() == 0) {
return new ArrayList<>(0);
}
QueryResultInfoMessage response = result.getResponses(0); // only head (end-result) is important
ArrayList<Map<String, PrimitiveTypeProvider>> _return = new ArrayList<>(k);
AckMessage ack = response.getAck();
if (ack.getCode() != Code.OK) {
LOGGER.error("error in getNearestNeighbourRows, entitiy {} ({}) : {}", entityName, ack.getCode(), ack.getMessage());
return _return;
}
return resultsToMap(response.getResultsList());
}
public List<Map<String, PrimitiveTypeProvider>> getFromExternal(String externalHandlerName, Map<String, String> parameters) {
ExternalHandlerQueryMessage.Builder ehqmBuilder = ExternalHandlerQueryMessage.newBuilder();
ehqmBuilder.setEntity(this.entityName);
ehqmBuilder.setHandler(externalHandlerName);
ehqmBuilder.putAllParams(parameters);
SubExpressionQueryMessage.Builder seqmBuilder = SubExpressionQueryMessage.newBuilder();
seqmBuilder.setEhqm(ehqmBuilder);
FromMessage.Builder fmBuilder = FromMessage.newBuilder();
fmBuilder.setExpression(seqmBuilder);
QueryMessage qm = this.mb.buildQueryMessage(ADAMproMessageBuilder.DEFAULT_HINT, fmBuilder, null, null, null);
return executeQuery(qm);
}
} |
package org.wms.controller.orderedit;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import org.wms.model.order.Order;
import org.wms.model.order.OrderRow;
public class MaterialListTableModel extends AbstractTableModel {
private Order order;
private String[] headers = {"Code", "Quantity"};
public MaterialListTableModel(Order order) {
super();
this.order = order;
}
@Override
public int getRowCount() {
//TODO rimuovere try catch
try {
return order.getMaterials().size();
} catch (Exception e) {
return 0;
}
}
@Override
public int getColumnCount() {
return headers.length;
}
@Override
public String getColumnName(int column) {
return headers[column];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
OrderRow row = (OrderRow) order.getMaterials().toArray()[columnIndex];
switch (columnIndex) {
case 0:
return row.getMaterial();
case 1:
return row.getQuantity();
default:
break;
}
return "Unknow column: " + columnIndex;
}
} |
package org.opencms.gwt.client.util;
import org.opencms.gwt.client.ui.css.I_CmsLayoutBundle;
import org.opencms.gwt.client.util.impl.DOMImpl;
import org.opencms.gwt.client.util.impl.DocumentStyleImpl;
import org.opencms.util.CmsStringUtil;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.animation.client.Animation;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
/**
* Utility class to access the HTML DOM.<p>
*
* @author Tobias Herrmann
*
* @version $Revision: 1.32 $
*
* @since 8.0.0
*/
public final class CmsDomUtil {
/**
* HTML tag attributes.<p>
*/
public static enum Attribute {
/** class. */
clazz {
/**
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return "class";
}
},
/** title. */
title;
}
/**
* Helper class to encapsulate an attribute/value pair.<p>
*/
public static class AttributeValue {
/** The attribute. */
private Attribute m_attr;
/** The attribute value. */
private String m_value;
/**
* Constructor.<p>
*
* @param attr the attribute
*/
public AttributeValue(Attribute attr) {
this(attr, null);
}
/**
* Constructor.<p>
*
* @param attr the attribute
* @param value the value
*/
public AttributeValue(Attribute attr, String value) {
m_attr = attr;
m_value = value;
}
/**
* Returns the attribute.<p>
*
* @return the attribute
*/
public Attribute getAttr() {
return m_attr;
}
/**
* Returns the value.<p>
*
* @return the value
*/
public String getValue() {
return m_value;
}
/**
* Sets the value.<p>
*
* @param value the value to set
*/
public void setValue(String value) {
m_value = value;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(m_attr.toString());
if (m_value != null) {
sb.append("=\"").append(m_value).append("\"");
}
return sb.toString();
}
}
/**
* CSS Colors.<p>
*/
public static enum Color {
/** CSS Color. */
red;
}
/**
* HTML entities.<p>
*/
public static enum Entity {
/** non-breaking space. */
hellip,
/** non-breaking space. */
nbsp;
/**
* Returns the HTML code for this entity.<p>
*
* @return the HTML code for this entity
*/
public String html() {
return "&" + super.name() + ";";
}
}
/**
* CSS Properties.<p>
*/
public static enum Style {
/** CSS Property. */
backgroundColor,
/** CSS Property. */
backgroundImage,
/** CSS property. */
borderLeftWidth,
/** CSS property. */
borderRightWidth,
/** CSS Property. */
borderStyle,
/** CSS Property. */
display,
/** CSS Property. */
floatCss {
/**
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return "float";
}
},
/** CSS Property. */
fontFamily,
/** CSS Property. */
fontSize,
/** CSS Property. */
fontSizeAdjust,
/** CSS Property. */
fontStretch,
/** CSS Property. */
fontStyle,
/** CSS Property. */
fontVariant,
/** CSS Property. */
fontWeight,
/** CSS Property. */
height,
/** CSS Property. */
left,
/** CSS Property. */
letterSpacing,
/** CSS Property. */
lineHeight,
/** CSS Property. */
marginBottom,
/** CSS Property. */
marginTop,
/** CSS Property. */
opacity,
/** CSS Property. */
padding,
/** CSS Property. */
position,
/** CSS Property. */
textAlign,
/** CSS Property. */
textDecoration,
/** CSS Property. */
textIndent,
/** CSS Property. */
textShadow,
/** CSS Property. */
textTransform,
/** CSS Property. */
top,
/** CSS Property. */
visibility,
/** CSS Property. */
whiteSpace,
/** CSS Property. */
width,
/** CSS Property. */
wordSpacing,
/** CSS Property. */
wordWrap;
}
/**
* CSS Property values.<p>
*/
public static enum StyleValue {
/** CSS Property value. */
absolute,
/** CSS Property value. */
auto,
/** CSS Property value. */
hidden,
/** CSS Property value. */
none,
/** CSS Property value. */
normal,
/** CSS Property value. */
nowrap,
/** CSS Property value. */
transparent;
}
/**
* HTML Tags.<p>
*/
public static enum Tag {
/** HTML Tag. */
a,
/** HTML Tag. */
ALL {
/**
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return "*";
}
},
/** HTML Tag. */
b,
/** HTML Tag. */
body,
/** HTML Tag. */
div,
/** HTML Tag. */
h1,
/** HTML Tag. */
h2,
/** HTML Tag. */
h3,
/** HTML Tag. */
h4,
/** HTML Tag. */
li,
/** HTML Tag. */
p,
/** HTML Tag. */
script,
/** HTML Tag. */
span,
/** HTML Tag. */
ul;
}
/** Browser dependent DOM implementation. */
private static DOMImpl domImpl;
/** Browser dependent style implementation. */
private static DocumentStyleImpl styleImpl;
/**
* Hidden constructor.<p>
*/
private CmsDomUtil() {
// doing nothing
}
/**
* Adds an overlay div to the element.<p>
*
* @param element the element
*/
public static void addDisablingOverlay(Element element) {
Element overlay = DOM.createDiv();
overlay.addClassName(I_CmsLayoutBundle.INSTANCE.generalCss().disablingOverlay());
element.getStyle().setPosition(Position.RELATIVE);
element.appendChild(overlay);
}
/**
* Returns if the given client position is over the given element.<p>
* Use <code>-1</code> for x or y to ignore one ordering orientation.<p>
*
* @param element the element
* @param x the client x position, use <code>-1</code> to ignore x position
* @param y the client y position, use <code>-1</code> to ignore y position
*
* @return <code>true</code> if the given position is over the given element
*/
public static boolean checkPositionInside(Element element, int x, int y) {
// ignore x / left-right values for x == -1
if (x != -1) {
// check if the mouse pointer is within the width of the target
int left = CmsDomUtil.getRelativeX(x, element);
int offsetWidth = element.getOffsetWidth();
if ((left <= 0) || (left >= offsetWidth)) {
return false;
}
}
// ignore y / top-bottom values for y == -1
if (y != -1) {
// check if the mouse pointer is within the height of the target
int top = CmsDomUtil.getRelativeY(y, element);
int offsetHeight = element.getOffsetHeight();
if ((top <= 0) || (top >= offsetHeight)) {
return false;
}
}
return true;
}
/**
* Clones the given element.<p>
*
* It creates a new element with the same tag, and sets the class attribute,
* and sets the innerHTML.<p>
*
* @param element the element to clone
*
* @return the cloned element
*/
public static com.google.gwt.user.client.Element clone(Element element) {
com.google.gwt.user.client.Element elementClone = DOM.createElement(element.getTagName());
elementClone.setClassName(element.getClassName());
elementClone.setInnerHTML(element.getInnerHTML());
return elementClone;
}
/**
* Generates a closing tag.<p>
*
* @param tag the tag to use
*
* @return HTML code
*/
public static String close(Tag tag) {
return "</" + tag.name() + ">";
}
/**
* This method will create an {@link com.google.gwt.user.client.Element} for the given HTML.
* The HTML should have a single root tag, if not, the first tag will be used and all others discarded.
* Script-tags will be ignored.
*
* @param html the HTML to use for the element
*
* @return the created element
*
* @throws Exception if something goes wrong
*/
public static com.google.gwt.user.client.Element createElement(String html) throws Exception {
com.google.gwt.user.client.Element wrapperDiv = DOM.createDiv();
wrapperDiv.setInnerHTML(html);
com.google.gwt.user.client.Element elementRoot = (com.google.gwt.user.client.Element)wrapperDiv.getFirstChildElement();
DOM.removeChild(wrapperDiv, elementRoot);
// just in case we have a script tag outside the root HTML-tag
while ((elementRoot != null) && (elementRoot.getTagName().toLowerCase().equals(Tag.script.name()))) {
elementRoot = (com.google.gwt.user.client.Element)wrapperDiv.getFirstChildElement();
DOM.removeChild(wrapperDiv, elementRoot);
}
if (elementRoot == null) {
CmsDebugLog.getInstance().printLine(
"Could not create element as the given HTML has no appropriate root element");
throw new UnsupportedOperationException(
"Could not create element as the given HTML has no appropriate root element");
}
return elementRoot;
}
/**
* Convenience method to assemble the HTML to use for a button face.<p>
*
* @param text text the up face text to set, set to <code>null</code> to not show any
* @param imageClass the up face image class to use, set to <code>null</code> to not show any
* @param align the alignment of the text in reference to the image
*
* @return the HTML
*/
public static String createFaceHtml(String text, String imageClass, HorizontalAlignmentConstant align) {
StringBuffer sb = new StringBuffer();
if (align == HasHorizontalAlignment.ALIGN_LEFT) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(text)) {
sb.append(text.trim());
}
}
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(imageClass)) {
String clazz = imageClass;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(text)) {
if (align == HasHorizontalAlignment.ALIGN_LEFT) {
clazz += " " + I_CmsLayoutBundle.INSTANCE.buttonCss().spacerLeft();
} else {
clazz += " " + I_CmsLayoutBundle.INSTANCE.buttonCss().spacerRight();
}
}
AttributeValue attr = new AttributeValue(Attribute.clazz, clazz);
sb.append(enclose(Tag.span, "", attr));
}
if (align == HasHorizontalAlignment.ALIGN_RIGHT) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(text)) {
sb.append(text.trim());
}
}
return sb.toString();
}
/**
* Creates an iFrame element with the given name attribute.<p>
*
* @param name the name attribute value
*
* @return the iFrame element
*/
public static com.google.gwt.dom.client.Element createIFrameElement(String name) {
return getDOMImpl().createIFrameElement(Document.get(), name);
}
/**
* Encloses the given text with the given tag.<p>
*
* @param tag the tag to use
* @param text the text to enclose
* @param attrs the optional tag attributes
*
* @return HTML code
*/
public static String enclose(Tag tag, String text, AttributeValue... attrs) {
return open(tag, attrs) + text + close(tag);
}
/**
* Triggers a mouse-out event for the given element.<p>
*
* Useful in case something is capturing all events.<p>
*
* @param element the element to use
*/
public static void ensureMouseOut(Element element) {
NativeEvent nativeEvent = Document.get().createMouseOutEvent(0, 0, 0, 0, 0, false, false, false, false, 0, null);
element.dispatchEvent(nativeEvent);
}
/**
* Ensures that the given element is visible.<p>
*
* Assuming the scrollbars are on the container element, and that the element is a child of the container element.<p>
*
* @param containerElement the container element, has to be parent of the element
* @param element the element to be seen
* @param animationTime the animation time for scrolling, use zero for no animation
*/
public static void ensureVisible(final Element containerElement, Element element, int animationTime) {
Element item = element;
int realOffset = 0;
while ((item != null) && (item != containerElement)) {
realOffset += element.getOffsetTop();
item = item.getOffsetParent();
}
final int endScrollTop = realOffset - containerElement.getOffsetHeight() / 2;
if (animationTime <= 0) {
// no animation
containerElement.setScrollTop(endScrollTop);
return;
}
final int startScrollTop = containerElement.getScrollTop();
(new Animation() {
/**
* @see com.google.gwt.animation.client.Animation#onUpdate(double)
*/
@Override
protected void onUpdate(double progress) {
containerElement.setScrollTop(startScrollTop + (int)((endScrollTop - startScrollTop) * progress));
}
}).run(animationTime);
}
/**
* Returns the given element or it's closest ancestor with the given class.<p>
*
* Returns <code>null</code> if no appropriate element was found.<p>
*
* @param element the element
* @param className the class name
*
* @return the matching element
*/
public static Element getAncestor(Element element, String className) {
if (hasClass(className, element)) {
return element;
}
if (element.getTagName().equalsIgnoreCase(Tag.body.name())) {
return null;
}
return getAncestor(element.getParentElement(), className);
}
/**
* Returns the given element or it's closest ancestor with the given tag name.<p>
*
* Returns <code>null</code> if no appropriate element was found.<p>
*
* @param element the element
* @param tag the tag name
*
* @return the matching element
*/
public static Element getAncestor(Element element, Tag tag) {
if (element.getTagName().equalsIgnoreCase(tag.name())) {
return element;
}
if (element.getTagName().equalsIgnoreCase(Tag.body.name())) {
return null;
}
return getAncestor(element.getParentElement(), tag);
}
/**
* Returns the given element or it's closest ancestor with the given tag and class.<p>
*
* Returns <code>null</code> if no appropriate element was found.<p>
*
* @param element the element
* @param tag the tag name
* @param className the class name
*
* @return the matching element
*/
public static Element getAncestor(Element element, Tag tag, String className) {
if (element.getTagName().equalsIgnoreCase(tag.name()) && hasClass(className, element)) {
return element;
}
if (element.getTagName().equalsIgnoreCase(Tag.body.name())) {
return null;
}
return getAncestor(element.getParentElement(), tag, className);
}
/**
* Returns the computed style of the given element.<p>
*
* @param element the element
* @param style the CSS property
*
* @return the currently computed style
*/
public static String getCurrentStyle(Element element, Style style) {
if (styleImpl == null) {
styleImpl = GWT.create(DocumentStyleImpl.class);
}
return styleImpl.getCurrentStyle(element, style.toString());
}
/**
* Returns the computed style of the given element as floating point number.<p>
*
* @param element the element
* @param style the CSS property
*
* @return the currently computed style
*/
public static double getCurrentStyleFloat(Element element, Style style) {
String currentStyle = getCurrentStyle(element, style);
return CmsClientStringUtil.parseFloat(currentStyle);
}
/**
* Returns the computed style of the given element as number.<p>
*
* @param element the element
* @param style the CSS property
*
* @return the currently computed style
*/
public static int getCurrentStyleInt(Element element, Style style) {
String currentStyle = getCurrentStyle(element, style);
return CmsClientStringUtil.parseInt(currentStyle);
}
/**
* Returns all elements from the DOM with the given CSS class.<p>
*
* @param className the class name to look for
*
* @return the matching elements
*/
public static List<Element> getElementsByClass(String className) {
return getElementsByClass(className, Tag.ALL, Document.get().getBody());
}
/**
* Returns all elements with the given CSS class including the root element.<p>
*
* @param className the class name to look for
* @param rootElement the root element of the search
*
* @return the matching elements
*/
public static List<Element> getElementsByClass(String className, Element rootElement) {
return getElementsByClass(className, Tag.ALL, rootElement);
}
/**
* Returns all elements from the DOM with the given CSS class and tag name.<p>
*
* @param className the class name to look for
* @param tag the tag
*
* @return the matching elements
*/
public static List<Element> getElementsByClass(String className, Tag tag) {
return getElementsByClass(className, tag, Document.get().getBody());
}
/**
* Returns all elements with the given CSS class and tag name including the root element.<p>
*
* @param className the class name to look for
* @param tag the tag
* @param rootElement the root element of the search
*
* @return the matching elements
*/
public static List<Element> getElementsByClass(String className, Tag tag, Element rootElement) {
if ((rootElement == null) || (className == null) || (className.trim().length() == 0) || (tag == null)) {
return null;
}
className = className.trim();
List<Element> result = new ArrayList<Element>();
if (internalHasClass(className, rootElement)) {
result.add(rootElement);
}
NodeList<Element> elements = rootElement.getElementsByTagName(tag.toString());
for (int i = 0; i < elements.getLength(); i++) {
if (internalHasClass(className, elements.getItem(i))) {
result.add(elements.getItem(i));
}
}
return result;
}
/**
* Returns the element position relative to its siblings.<p>
*
* @param e the element to get the position for
*
* @return the position, or <code>-1</code> if not found
*/
public static int getPosition(Element e) {
NodeList<Node> childNodes = e.getParentElement().getChildNodes();
for (int i = childNodes.getLength(); i >= 0; i
if (childNodes.getItem(i) == e) {
return i;
}
}
return -1;
}
/**
* Returns the next ancestor to the element with an absolute, fixed or relative position.<p>
*
* @param child the element
*
* @return the positioning parent element (may be <code>null</code>)
*/
public static Element getPositioningParent(Element child) {
Element parent = child.getParentElement();
while (parent != null) {
String parentPositioning = CmsDomUtil.getCurrentStyle(parent, Style.position);
if (Position.RELATIVE.getCssName().equals(parentPositioning)
|| Position.ABSOLUTE.getCssName().equals(parentPositioning)
|| Position.FIXED.getCssName().equals(parentPositioning)) {
return parent;
}
parent = parent.getParentElement();
}
return null;
}
/**
* Gets the horizontal position of the given x-coordinate relative to a given element.<p>
*
* @param x the coordinate to use
* @param target the element whose coordinate system is to be used
*
* @return the relative horizontal position
*
* @see com.google.gwt.event.dom.client.MouseEvent#getRelativeX(com.google.gwt.dom.client.Element)
*/
public static int getRelativeX(int x, Element target) {
return x - target.getAbsoluteLeft() + target.getScrollLeft() + target.getOwnerDocument().getScrollLeft();
}
/**
* Gets the vertical position of the given y-coordinate relative to a given element.<p>
*
* @param y the coordinate to use
* @param target the element whose coordinate system is to be used
*
* @return the relative vertical position
*
* @see com.google.gwt.event.dom.client.MouseEvent#getRelativeY(com.google.gwt.dom.client.Element)
*/
public static int getRelativeY(int y, Element target) {
return y - target.getAbsoluteTop() + target.getScrollTop() + target.getOwnerDocument().getScrollTop();
}
/**
* Utility method to determine if the given element has a set background.<p>
*
* @param element the element
*
* @return <code>true</code> if the element has a background set
*/
public static boolean hasBackground(Element element) {
String backgroundColor = CmsDomUtil.getCurrentStyle(element, Style.backgroundColor);
String backgroundImage = CmsDomUtil.getCurrentStyle(element, Style.backgroundImage);
if ((backgroundColor.equals(StyleValue.transparent.toString()))
&& ((backgroundImage == null) || (backgroundImage.trim().length() == 0) || backgroundImage.equals(StyleValue.none.toString()))) {
return false;
}
return true;
}
/**
* Utility method to determine if the given element has a set border.<p>
*
* @param element the element
*
* @return <code>true</code> if the element has a border
*/
public static boolean hasBorder(Element element) {
String borderStyle = CmsDomUtil.getCurrentStyle(element, Style.borderStyle);
if ((borderStyle == null) || borderStyle.equals(StyleValue.none.toString()) || (borderStyle.length() == 0)) {
return false;
}
return true;
}
/**
* Indicates if the given element has a CSS class.<p>
*
* @param className the class name to look for
* @param element the element
*
* @return <code>true</code> if the element has the given CSS class
*/
public static boolean hasClass(String className, Element element) {
return internalHasClass(className.trim(), element);
}
/**
* Generates an opening tag.<p>
*
* @param tag the tag to use
* @param attrs the optional tag attributes
*
* @return HTML code
*/
public static String open(Tag tag, AttributeValue... attrs) {
StringBuffer sb = new StringBuffer();
sb.append("<").append(tag.name());
for (AttributeValue attr : attrs) {
sb.append(" ").append(attr.toString());
}
sb.append(">");
return sb.toString();
}
/**
* Positions an element in the DOM relative to another element.<p>
*
* @param elem the element to position
* @param referenceElement the element relative to which the first element should be positioned
* @param dx the x offset relative to the reference element
* @param dy the y offset relative to the reference element
*/
public static void positionElement(Element elem, Element referenceElement, int dx, int dy) {
com.google.gwt.dom.client.Style style = elem.getStyle();
style.setLeft(0, Unit.PX);
style.setTop(0, Unit.PX);
int myX = elem.getAbsoluteLeft();
int myY = elem.getAbsoluteTop();
int refX = referenceElement.getAbsoluteLeft();
int refY = referenceElement.getAbsoluteTop();
int newX = refX - myX + dx;
int newY = refY - myY + dy;
style.setLeft(newX, Unit.PX);
style.setTop(newY, Unit.PX);
}
/**
* Positions an element inside the given parent, reordering the content of the parent and returns the new position index.<p>
* This is none absolute positioning. Use for drag and drop reordering of drop targets.<p>
* Use <code>-1</code> for x or y to ignore one ordering orientation.<p>
*
* @param element the child element
* @param parent the parent element
* @param currentIndex the current index position of the element, use -1 if element is not attached to the parent yet
* @param x the client x position, use <code>-1</code> to ignore x position
* @param y the client y position, use <code>-1</code> to ignore y position
*
* @return the new index position
*/
public static int positionElementInside(Element element, Element parent, int currentIndex, int x, int y) {
if ((x == -1) && (y == -1)) {
// this is wrong usage, do nothing
CmsDebugLog.getInstance().printLine("this is wrong usage, doing nothing");
return currentIndex;
}
for (int index = 0; index < parent.getChildCount(); index++) {
Node node = parent.getChild(index);
if (!(node instanceof Element)) {
continue;
}
Element child = (Element)node;
String positioning = child.getStyle().getPosition();
if (positioning.equals(Position.ABSOLUTE.getCssName()) || positioning.equals(Position.FIXED.getCssName())) {
// only not 'position:absolute' elements into account,
// not visible children will be excluded in the next condition
continue;
}
int left = 0;
int width = 0;
int top = 0;
int height = 0;
if (x != -1) {
// check if the mouse pointer is within the width of the element
left = CmsDomUtil.getRelativeX(x, child);
width = child.getOffsetWidth();
if ((left <= 0) || (left >= width)) {
continue;
}
}
if (y != -1) {
// check if the mouse pointer is within the height of the element
top = CmsDomUtil.getRelativeY(y, child);
height = child.getOffsetHeight();
if ((top <= 0) || (top >= height)) {
continue;
}
} else {
if (child == element) {
return currentIndex;
}
if (left < width / 2) {
parent.insertBefore(element, child);
currentIndex = index;
return currentIndex;
} else {
parent.insertAfter(element, child);
currentIndex = index + 1;
return currentIndex;
}
}
if (child == element) {
return currentIndex;
}
if (top < height / 2) {
parent.insertBefore(element, child);
currentIndex = index;
return currentIndex;
} else {
parent.insertAfter(element, child);
currentIndex = index + 1;
return currentIndex;
}
}
// not over any child position
if ((currentIndex >= 0) && (element.getParentElement() == parent)) {
// element is already attached to this parent and no new position available
// don't do anything
return currentIndex;
}
int top = CmsDomUtil.getRelativeY(y, parent);
int offsetHeight = parent.getOffsetHeight();
if ((top >= offsetHeight / 2)) {
// over top half, insert as first child
parent.insertFirst(element);
currentIndex = 0;
return currentIndex;
}
// over bottom half, insert as last child
parent.appendChild(element);
currentIndex = parent.getChildCount() - 1;
return currentIndex;
}
/**
* Removes any present overlay from the element and it's children.<p>
*
* @param element the element
*/
public static void removeDisablingOverlay(Element element) {
List<Element> overlays = CmsDomUtil.getElementsByClass(
I_CmsLayoutBundle.INSTANCE.generalCss().disablingOverlay(),
Tag.div,
element);
if (overlays == null) {
return;
}
for (Element overlay : overlays) {
overlay.getParentElement().getStyle().clearPosition();
overlay.removeFromParent();
}
element.removeClassName(I_CmsLayoutBundle.INSTANCE.generalCss().hideOverlay());
}
/**
* Sets a CSS class to show or hide a given overlay. Will not add an overlay to the element.<p>
*
* @param element the parent element of the overlay
* @param show <code>true</code> to show the overlay
*/
public static void showOverlay(Element element, boolean show) {
if (show) {
element.removeClassName(I_CmsLayoutBundle.INSTANCE.generalCss().hideOverlay());
} else {
element.addClassName(I_CmsLayoutBundle.INSTANCE.generalCss().hideOverlay());
}
}
/**
* Returns the DOM implementation.<p>
*
* @return the DOM implementation
*/
private static DOMImpl getDOMImpl() {
if (domImpl == null) {
domImpl = GWT.create(DOMImpl.class);
}
return domImpl;
}
/**
* Internal method to indicate if the given element has a CSS class.<p>
*
* @param className the class name to look for
* @param element the element
*
* @return <code>true</code> if the element has the given CSS class
*/
private static boolean internalHasClass(String className, Element element) {
String elementClass = element.getClassName().trim();
boolean hasClass = elementClass.equals(className);
hasClass |= elementClass.contains(" " + className + " ");
hasClass |= elementClass.startsWith(className + " ");
hasClass |= elementClass.endsWith(" " + className);
return hasClass;
}
} |
package protocolsupport.protocol.typeremapper.id;
import protocolsupport.utils.ProtocolVersionsHelper;
public class IdRemapper {
public static final RemappingReigstry BLOCK = new RemappingReigstry() {
{
// slime -> emerald block
registerRemapEntry(165, 133, ProtocolVersionsHelper.BEFORE_1_8);
// barrier -> glass
registerRemapEntry(166, 20, ProtocolVersionsHelper.BEFORE_1_8);
// iron trapdoor -> trapdoor
registerRemapEntry(167, 96, ProtocolVersionsHelper.BEFORE_1_8);
// prismarine -> mossy cobblestone
registerRemapEntry(168, 48, ProtocolVersionsHelper.BEFORE_1_8);
// sea lantern -> glowstone
registerRemapEntry(169, 89, ProtocolVersionsHelper.BEFORE_1_8);
// standing banner -> standing sign
registerRemapEntry(176, 63, ProtocolVersionsHelper.BEFORE_1_8);
// wall banner -> wall sign
registerRemapEntry(177, 68, ProtocolVersionsHelper.BEFORE_1_8);
// red sandstone -> sandstone
registerRemapEntry(179, 24, ProtocolVersionsHelper.BEFORE_1_8);
// red sandstone stairs -> sandstone stairs
registerRemapEntry(180, 128, ProtocolVersionsHelper.BEFORE_1_8);
// red sandstone doubleslab -> double step
registerRemapEntry(181, 43, ProtocolVersionsHelper.BEFORE_1_8);
// red sandstone slab -> step
registerRemapEntry(182, 44, ProtocolVersionsHelper.BEFORE_1_8);
// all fence gates -> fence gate
registerRemapEntry(183, 107, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(184, 107, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(185, 107, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(186, 107, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(187, 107, ProtocolVersionsHelper.BEFORE_1_8);
// all fences -> fence
registerRemapEntry(188, 85, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(189, 85, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(190, 85, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(191, 85, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(192, 85, ProtocolVersionsHelper.BEFORE_1_8);
// all doors -> door
registerRemapEntry(193, 64, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(194, 64, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(195, 64, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(196, 64, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(197, 64, ProtocolVersionsHelper.BEFORE_1_8);
// inverted daylight detector -> daylight detector
registerRemapEntry(178, 151, ProtocolVersionsHelper.BEFORE_1_8);
// stained glass -> glass
registerRemapEntry(95, 20, ProtocolVersionsHelper.BEFORE_1_7);
// stained glass pane -> glass pane
registerRemapEntry(160, 102, ProtocolVersionsHelper.BEFORE_1_7);
// leaves2 -> leaves
registerRemapEntry(161, 18, ProtocolVersionsHelper.BEFORE_1_7);
// log2 -> log
registerRemapEntry(162, 17, ProtocolVersionsHelper.BEFORE_1_7);
// acacia stairs -> oak stairs
registerRemapEntry(163, 53, ProtocolVersionsHelper.BEFORE_1_7);
// dark oak stairs -> oak stairs
registerRemapEntry(164, 53, ProtocolVersionsHelper.BEFORE_1_7);
// tall plant -> yellow flower
registerRemapEntry(175, 38, ProtocolVersionsHelper.BEFORE_1_7);
// stained clay -> clay
registerRemapEntry(159, 82, ProtocolVersionsHelper.BEFORE_1_6);
// hay bale -> stone
registerRemapEntry(170, 1, ProtocolVersionsHelper.BEFORE_1_6);
// carpet -> stone pressure plate
registerRemapEntry(171, 70, ProtocolVersionsHelper.BEFORE_1_6);
// hardened clay -> clay
registerRemapEntry(172, 82, ProtocolVersionsHelper.BEFORE_1_6);
// coal block -> stone
registerRemapEntry(173, 1, ProtocolVersionsHelper.BEFORE_1_6);
// packed ice -> snow
registerRemapEntry(174, 80, ProtocolVersionsHelper.BEFORE_1_6);
}
@Override
protected RemappingTable createTable() {
return new RemappingTable(4096);
}
};
public static final RemappingReigstry ITEM = new RemappingReigstry() {
{
copy(BLOCK);
// all doors -> door
registerRemapEntry(427, 324, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(428, 324, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(429, 324, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(430, 324, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(431, 324, ProtocolVersionsHelper.BEFORE_1_8);
// rabbit raw meat -> chicken raw meat
registerRemapEntry(411, 365, ProtocolVersionsHelper.BEFORE_1_8);
// rabbit cooked meat -> chicken cooked meat
registerRemapEntry(412, 366, ProtocolVersionsHelper.BEFORE_1_8);
// rabbit stew -> mushroom stew
registerRemapEntry(413, 282, ProtocolVersionsHelper.BEFORE_1_8);
// raw mutton -> chicken raw meat
registerRemapEntry(423, 365, ProtocolVersionsHelper.BEFORE_1_8);
// cooked mutton -> chicken cooked meat
registerRemapEntry(424, 366, ProtocolVersionsHelper.BEFORE_1_8);
// banner -> sign
registerRemapEntry(425, 323, ProtocolVersionsHelper.BEFORE_1_8);
// everything else -> stone
registerRemapEntry(409, 1, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(410, 1, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(414, 1, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(415, 1, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(416, 1, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(417, 1, ProtocolVersionsHelper.BEFORE_1_6);
registerRemapEntry(418, 1, ProtocolVersionsHelper.BEFORE_1_6);
registerRemapEntry(419, 1, ProtocolVersionsHelper.BEFORE_1_6);
registerRemapEntry(420, 1, ProtocolVersionsHelper.BEFORE_1_6);
registerRemapEntry(421, 1, ProtocolVersionsHelper.BEFORE_1_6);
}
@Override
protected RemappingTable createTable() {
return new RemappingTable(4096);
}
};
public static final RemappingReigstry ENTITY = new RemappingReigstry() {
{
// endermite -> silverfish
registerRemapEntry(67, 60, ProtocolVersionsHelper.BEFORE_1_8);
// guardian -> sqiud
registerRemapEntry(68, 94, ProtocolVersionsHelper.BEFORE_1_8);
// rabbit -> chicken
registerRemapEntry(101, 93, ProtocolVersionsHelper.BEFORE_1_8);
// horse -> cow
registerRemapEntry(100, 92, ProtocolVersionsHelper.BEFORE_1_6);
}
@Override
protected RemappingTable createTable() {
return new RemappingTable(256);
}
};
public static final RemappingReigstry MAPCOLOR = new RemappingReigstry() {
{
registerRemapEntry(14, 8, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(15, 10, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(16, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(17, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(18, 2, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(19, 1, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(20, 4, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(21, 11, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(22, 11, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(23, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(24, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(25, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(26, 10, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(27, 7, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(28, 4, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(29, 11, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(30, 2, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(31, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(32, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(33, 7, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(34, 10, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(35, 4, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(36, 10, ProtocolVersionsHelper.BEFORE_1_7);
}
@Override
protected RemappingTable createTable() {
return new RemappingTable(64) {
@Override
public int getRemap(int id) {
int realColor = (id & 0xFF) >> 2;
return ((table[realColor] << 2) + (id & 0b11));
}
};
}
};
} |
package protocolsupport.protocol.typeremapper.id;
import protocolsupport.utils.ProtocolVersionsHelper;
public class IdRemapper {
public static final RemappingRegistry BLOCK = new RemappingRegistry() {
{
// slime -> emerald block
registerRemapEntry(165, 133, ProtocolVersionsHelper.BEFORE_1_8);
// barrier -> glass
registerRemapEntry(166, 20, ProtocolVersionsHelper.BEFORE_1_8);
// iron trapdoor -> trapdoor
registerRemapEntry(167, 96, ProtocolVersionsHelper.BEFORE_1_8);
// prismarine -> mossy cobblestone
registerRemapEntry(168, 48, ProtocolVersionsHelper.BEFORE_1_8);
// sea lantern -> glowstone
registerRemapEntry(169, 89, ProtocolVersionsHelper.BEFORE_1_8);
// standing banner -> standing sign
registerRemapEntry(176, 63, ProtocolVersionsHelper.BEFORE_1_8);
// wall banner -> wall sign
registerRemapEntry(177, 68, ProtocolVersionsHelper.BEFORE_1_8);
// red sandstone -> sandstone
registerRemapEntry(179, 24, ProtocolVersionsHelper.BEFORE_1_8);
// red sandstone stairs -> sandstone stairs
registerRemapEntry(180, 128, ProtocolVersionsHelper.BEFORE_1_8);
// red sandstone doubleslab -> double step
registerRemapEntry(181, 43, ProtocolVersionsHelper.BEFORE_1_8);
// red sandstone slab -> step
registerRemapEntry(182, 44, ProtocolVersionsHelper.BEFORE_1_8);
// all fence gates -> fence gate
registerRemapEntry(183, 107, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(184, 107, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(185, 107, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(186, 107, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(187, 107, ProtocolVersionsHelper.BEFORE_1_8);
// all fences -> fence
registerRemapEntry(188, 85, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(189, 85, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(190, 85, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(191, 85, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(192, 85, ProtocolVersionsHelper.BEFORE_1_8);
// all doors -> door
registerRemapEntry(193, 64, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(194, 64, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(195, 64, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(196, 64, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(197, 64, ProtocolVersionsHelper.BEFORE_1_8);
// inverted daylight detector -> daylight detector
registerRemapEntry(178, 151, ProtocolVersionsHelper.BEFORE_1_8);
// stained glass -> glass
registerRemapEntry(95, 20, ProtocolVersionsHelper.BEFORE_1_7);
// stained glass pane -> glass pane
registerRemapEntry(160, 102, ProtocolVersionsHelper.BEFORE_1_7);
// leaves2 -> leaves
registerRemapEntry(161, 18, ProtocolVersionsHelper.BEFORE_1_7);
// log2 -> log
registerRemapEntry(162, 17, ProtocolVersionsHelper.BEFORE_1_7);
// acacia stairs -> oak stairs
registerRemapEntry(163, 53, ProtocolVersionsHelper.BEFORE_1_7);
// dark oak stairs -> oak stairs
registerRemapEntry(164, 53, ProtocolVersionsHelper.BEFORE_1_7);
// tall plant -> yellow flower
registerRemapEntry(175, 38, ProtocolVersionsHelper.BEFORE_1_7);
// packed ice -> snow
registerRemapEntry(174, 80, ProtocolVersionsHelper.BEFORE_1_7);
// stained clay -> clay
registerRemapEntry(159, 82, ProtocolVersionsHelper.BEFORE_1_6);
// hay bale -> stone
registerRemapEntry(170, 1, ProtocolVersionsHelper.BEFORE_1_6);
// carpet -> stone pressure plate
registerRemapEntry(171, 70, ProtocolVersionsHelper.BEFORE_1_6);
// hardened clay -> clay
registerRemapEntry(172, 82, ProtocolVersionsHelper.BEFORE_1_6);
// coal block -> stone
registerRemapEntry(173, 1, ProtocolVersionsHelper.BEFORE_1_6);
// dropper -> stone
registerRemapEntry(178, 1, ProtocolVersionsHelper.BEFORE_1_5);
// hopper -> stone
registerRemapEntry(154, 1, ProtocolVersionsHelper.BEFORE_1_5);
// quartz -> snow
registerRemapEntry(155, 80, ProtocolVersionsHelper.BEFORE_1_5);
// quartz stairs -> stairs
registerRemapEntry(156, 109, ProtocolVersionsHelper.BEFORE_1_5);
// quartz slab -> slab
registerRemapEntry(156, 44, ProtocolVersionsHelper.BEFORE_1_5);
// inverted daylight detector -> stone
registerRemapEntry(178, 1, ProtocolVersionsHelper.BEFORE_1_5);
// daylight detector -> slab
registerRemapEntry(151, 44, ProtocolVersionsHelper.BEFORE_1_5);
// trapped chest -> chest
registerRemapEntry(146, 54, ProtocolVersionsHelper.BEFORE_1_5);
// redstone block -> glowing redstone ore
registerRemapEntry(146, 73, ProtocolVersionsHelper.BEFORE_1_5);
// activator rail -> some other rail
registerRemapEntry(157, 28, ProtocolVersionsHelper.BEFORE_1_5);
// nether quartz ore -> nettherrack
registerRemapEntry(153, 87, ProtocolVersionsHelper.BEFORE_1_5);
// wpressure plate light -> wood pressure plate
registerRemapEntry(147, 72, ProtocolVersionsHelper.BEFORE_1_5);
// wpressure plate heavy -> stone pressure plate
registerRemapEntry(148, 70, ProtocolVersionsHelper.BEFORE_1_5);
// redstone comparator -> repeater
registerRemapEntry(149, 93, ProtocolVersionsHelper.BEFORE_1_5);
}
@Override
protected RemappingTable createTable() {
return new RemappingTable(4096);
}
};
public static final RemappingRegistry ITEM = new RemappingRegistry() {
{
copy(BLOCK);
// all doors -> door
registerRemapEntry(427, 324, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(428, 324, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(429, 324, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(430, 324, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(431, 324, ProtocolVersionsHelper.BEFORE_1_8);
// rabbit raw meat -> chicken raw meat
registerRemapEntry(411, 365, ProtocolVersionsHelper.BEFORE_1_8);
// rabbit cooked meat -> chicken cooked meat
registerRemapEntry(412, 366, ProtocolVersionsHelper.BEFORE_1_8);
// rabbit stew -> mushroom stew
registerRemapEntry(413, 282, ProtocolVersionsHelper.BEFORE_1_8);
// raw mutton -> chicken raw meat
registerRemapEntry(423, 365, ProtocolVersionsHelper.BEFORE_1_8);
// cooked mutton -> chicken cooked meat
registerRemapEntry(424, 366, ProtocolVersionsHelper.BEFORE_1_8);
// banner -> sign
registerRemapEntry(425, 323, ProtocolVersionsHelper.BEFORE_1_8);
// everything else -> stone
registerRemapEntry(409, 1, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(410, 1, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(414, 1, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(415, 1, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(416, 1, ProtocolVersionsHelper.BEFORE_1_8);
registerRemapEntry(417, 1, ProtocolVersionsHelper.BEFORE_1_6);
registerRemapEntry(418, 1, ProtocolVersionsHelper.BEFORE_1_6);
registerRemapEntry(419, 1, ProtocolVersionsHelper.BEFORE_1_6);
registerRemapEntry(420, 1, ProtocolVersionsHelper.BEFORE_1_6);
registerRemapEntry(421, 1, ProtocolVersionsHelper.BEFORE_1_6);
// minecarts -> default minecart
registerRemapEntry(407, 328, ProtocolVersionsHelper.BEFORE_1_5);
registerRemapEntry(408, 328, ProtocolVersionsHelper.BEFORE_1_5);
// comparator -> repeater
registerRemapEntry(404, 356, ProtocolVersionsHelper.BEFORE_1_5);
// nether brick -> brick
registerRemapEntry(405, 336, ProtocolVersionsHelper.BEFORE_1_5);
// quartz -> feather
registerRemapEntry(406, 288, ProtocolVersionsHelper.BEFORE_1_5);
}
@Override
protected RemappingTable createTable() {
return new RemappingTable(4096);
}
};
public static final RemappingRegistry ENTITY = new RemappingRegistry() {
{
// endermite -> silverfish
registerRemapEntry(67, 60, ProtocolVersionsHelper.BEFORE_1_8);
// guardian -> sqiud
registerRemapEntry(68, 94, ProtocolVersionsHelper.BEFORE_1_8);
// rabbit -> chicken
registerRemapEntry(101, 93, ProtocolVersionsHelper.BEFORE_1_8);
// horse -> cow
registerRemapEntry(100, 92, ProtocolVersionsHelper.BEFORE_1_6);
}
@Override
protected RemappingTable createTable() {
return new RemappingTable(256);
}
};
public static final RemappingRegistry MAPCOLOR = new RemappingRegistry() {
{
registerRemapEntry(14, 8, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(15, 10, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(16, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(17, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(18, 2, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(19, 1, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(20, 4, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(21, 11, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(22, 11, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(23, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(24, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(25, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(26, 10, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(27, 7, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(28, 4, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(29, 11, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(30, 2, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(31, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(32, 5, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(33, 7, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(34, 10, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(35, 4, ProtocolVersionsHelper.BEFORE_1_7);
registerRemapEntry(36, 10, ProtocolVersionsHelper.BEFORE_1_7);
}
@Override
protected RemappingTable createTable() {
return new RemappingTable(64) {
@Override
public int getRemap(int id) {
int realColor = (id & 0xFF) >> 2;
return ((table[realColor] << 2) + (id & 0b11));
}
};
}
};
} |
package android.nimpres.client.dps;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.nimpres.client.presentation.Presentation;
import android.nimpres.client.presentation.Slide;
import android.nimpres.client.settings.NimpresSettings;
import android.util.Log;
/*This class offers methods to read a DSP file once it has been extracted*/
public class DPSReader {
public static Presentation makePresentation(String dpsPath){
Presentation presCreated = null;
File metaFile = new File(dpsPath +File.separator+NimpresSettings.METAFILE_NAME);
if(metaFile.exists()){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
Log.d("DPSReader","parsing metafile");
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(metaFile);
doc.getDocumentElement().normalize();
Node presRootNode = doc.getElementsByTagName("presentation").item(0);
Element presElement = (Element) presRootNode;
int numberSlides = Integer.parseInt(presElement.getElementsByTagName("number_slides").item(0).getTextContent());
Log.d("DPSReader","found number_slides:"+numberSlides);
String title = presElement.getElementsByTagName("presentation_title").item(0).getTextContent();
Log.d("DPSReader","found presentation_title:"+title);
String owner = presElement.getElementsByTagName("presentation_owner").item(0).getTextContent();
Log.d("DPSReader","found presentation_owner:"+owner);
int timestamp = Integer.parseInt(presElement.getElementsByTagName("presentation_timestamp").item(0).getTextContent());
Log.d("DPSReader","found presentation_timestamp:"+timestamp);
presCreated = new Presentation();
presCreated.setCurrentSlide(0);
presCreated.setNumSlides(numberSlides);
presCreated.setPresentationName(title);
presCreated.setTimestamp(timestamp);
presCreated.setOwner(owner);
Slide[] slides = new Slide[numberSlides];
NodeList slideElements = presElement.getElementsByTagName("slide");
for(int i=0;i<slideElements.getLength();i++){
Element thisSlide = (Element) slideElements.item(i);
int thisSlideNumber = Integer.parseInt(thisSlide.getAttribute("number"));
Log.d("DPSReader","found slide #:"+thisSlideNumber);
String thisSlideTitle = thisSlide.getElementsByTagName("title").item(0).getTextContent();
Log.d("DPSReader","found slide title:"+thisSlideTitle);
String thisSlideFileComments = thisSlide.getElementsByTagName("file").item(0).getTextContent();
Log.d("DPSReader","found slide file:"+thisSlideFileComments);
String thisSlideNotes = thisSlide.getElementsByTagName("notes").item(0).getTextContent();
Log.d("DPSReader","found slide notes:"+thisSlideNotes);
slides[thisSlideNumber-1] = new Slide(thisSlideFile,thisSlideNumber,thisSlideFileComments,thisSlideTitle);
}
presCreated.setSlideFiles(slides);
}catch(Exception e){
Log.d("DPSReader","Exception:"+e);
}
return presCreated;
}else{
//File did not exist
Log.d("DPSReader","file not found:"+metaFile.getPath());
return null;
}
}
} |
package org.zeromq.czmq;
public class Zconfig implements AutoCloseable{
static {
try {
System.loadLibrary ("czmqjni");
}
catch (Exception e) {
System.exit (-1);
}
}
public long self;
/*
Create new config item
*/
native static long __new (String name, long parent);
public Zconfig (String name, Zconfig parent) {
/* TODO: if __new fails, self is null... */
self = __new (name, parent.self);
}
public Zconfig (long pointer) {
self = pointer;
}
/*
Load a config tree from a specified ZPL text file; returns a zconfig_t
reference for the root, if the file exists and is readable. Returns NULL
if the file does not exist.
*/
native static long __load (String filename);
public static Zconfig load (String filename) {
return new Zconfig (__load (filename));
}
/*
Equivalent to zconfig_load, taking a format string instead of a fixed
filename.
*/
native static long __loadf (String format);
public static Zconfig loadf (String format) {
return new Zconfig (__loadf (format));
}
/*
Destroy a config item and all its children
*/
native static void __destroy (long self);
@Override
public void close () {
__destroy (self);
self = 0;
}
/*
Create copy of zconfig, caller MUST free the value
Create copy of config, as new zconfig object. Returns a fresh zconfig_t
object. If config is null, or memory was exhausted, returns null.
*/
native static long __dup (long self);
public Zconfig dup () {
return new Zconfig (__dup (self));
}
/*
Return name of config item
*/
native static String __name (long self);
public String name () {
return __name (self);
}
/*
Return value of config item
*/
native static String __value (long self);
public String value () {
return __value (self);
}
/*
Insert or update configuration key with value
*/
native static void __put (long self, String path, String value);
public void put (String path, String value) {
__put (self, path, value);
}
/*
Equivalent to zconfig_put, accepting a format specifier and variable
argument list, instead of a single string value.
*/
native static void __putf (long self, String path, String format);
public void putf (String path, String format) {
__putf (self, path, format);
}
/*
Get value for config item into a string value; leading slash is optional
and ignored.
*/
native static String __get (long self, String path, String defaultValue);
public String get (String path, String defaultValue) {
return __get (self, path, defaultValue);
}
/*
Set config item name, name may be NULL
*/
native static void __setName (long self, String name);
public void setName (String name) {
__setName (self, name);
}
/*
Set new value for config item. The new value may be a string, a printf
format, or NULL. Note that if string may possibly contain '%', or if it
comes from an insecure source, you must use '%s' as the format, followed
by the string.
*/
native static void __setValue (long self, String format);
public void setValue (String format) {
__setValue (self, format);
}
/*
Find our first child, if any
*/
native static long __child (long self);
public Zconfig child () {
return new Zconfig (__child (self));
}
/*
Find our first sibling, if any
*/
native static long __next (long self);
public Zconfig next () {
return new Zconfig (__next (self));
}
/*
Find a config item along a path; leading slash is optional and ignored.
*/
native static long __locate (long self, String path);
public Zconfig locate (String path) {
return new Zconfig (__locate (self, path));
}
/*
Locate the last config item at a specified depth
*/
native static long __atDepth (long self, int level);
public Zconfig atDepth (int level) {
return new Zconfig (__atDepth (self, level));
}
/*
Add comment to config item before saving to disk. You can add as many
comment lines as you like. If you use a null format, all comments are
deleted.
*/
native static void __setComment (long self, String format);
public void setComment (String format) {
__setComment (self, format);
}
/*
Return comments of config item, as zlist.
*/
native static long __comments (long self);
public Zlist comments () {
return new Zlist (__comments (self));
}
/*
Save a config tree to a specified ZPL text file, where a filename
"-" means dump to standard output.
*/
native static int __save (long self, String filename);
public int save (String filename) {
return __save (self, filename);
}
/*
Equivalent to zconfig_save, taking a format string instead of a fixed
filename.
*/
native static int __savef (long self, String format);
public int savef (String format) {
return __savef (self, format);
}
/*
Report filename used during zconfig_load, or NULL if none
*/
native static String __filename (long self);
public String filename () {
return __filename (self);
}
/*
Reload config tree from same file that it was previously loaded from.
Returns 0 if OK, -1 if there was an error (and then does not change
existing data).
*/
native static long __reload (long self);
public int reload () {
self = __reload (self);
return 0;
}
/*
Load a config tree from a memory chunk
*/
native static long __chunkLoad (long chunk);
public Zconfig chunkLoad (Zchunk chunk) {
return new Zconfig (__chunkLoad (chunk.self));
}
/*
Save a config tree to a new memory chunk
*/
native static long __chunkSave (long self);
public Zchunk chunkSave () {
return new Zchunk (__chunkSave (self));
}
/*
Load a config tree from a null-terminated string
*/
native static long __strLoad (String string);
public Zconfig strLoad (String string) {
return new Zconfig (__strLoad (string));
}
/*
Save a config tree to a new null terminated string
*/
native static String __strSave (long self);
public String strSave () {
return __strSave (self);
}
/*
Return true if a configuration tree was loaded from a file and that
file has changed in since the tree was loaded.
*/
native static boolean __hasChanged (long self);
public boolean hasChanged () {
return __hasChanged (self);
}
/*
Destroy subtree (all children)
*/
native static void __removeSubtree (long self);
public void removeSubtree () {
__removeSubtree (self);
}
/*
Destroy node and subtree (all children)
WARNING: manually fixed void -> long
*/
native static long __remove (long self);
public long remove () {
self = __remove (self);
return 0;
}
/*
Print properties of object
*/
native static void __print (long self);
public void print () {
__print (self);
}
/*
Self test of this class
*/
native static void __test (boolean verbose);
public static void test (boolean verbose) {
__test (verbose);
}
} |
/**
* @author Johnny Kumpf
*/
package authoringEnvironment;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import util.misc.SetHandler;
import javafx.collections.ObservableList;
public class InstanceManager {
// public static final ResourceBundle paramLists =
// ResourceBundle.getBundle("resources/part_parameters");
private static final String defaultSaveLocation = System.getProperty(
"user.dir").concat("/src/myTowerGames");
private static final String gameRootDirectory = System.getProperty(
"user.dir").concat("/src/exampleUserData");
public static final String partTypeKey = "PartType";
public static final String nameKey = "Name";
private static final String missingNameKey = "Map passed must contain a \"Name\" key. Key is case sensitive.";
private static final String listSizesDiffer = "Lists passed must contain same number of elements.";
private static final String partFileName = "GameParts.xml";
private static final String IMFileName = "GameManager.xml";
public static final String partsFileDir = "/AllPartData";
private static final String partKeyKey = "PartKey";
// a map of all the parts the user has created
// each part is represented by a map mapping the part's parameters to their
// data
// the fields look like: Map<partName, Map<parameterName, parameterData>>
// private Map<String, Map<String, Object>> userParts;
private Map<String, Map<String, Object>> userParts;
private String gameName;
private String rootDirectory;
/**
* Generates an instance manager for a game. An InstanceManager has a name
* (the game name), data, which is part data stored as a List of maps, and a
* root directory, in which all the parts are saved in various folders.
*
* @param name
* The name of the game for which this InstanceManager manages
* part data.
* @param partData
* The data maps corresponding to all the parts in this game
* @param rootDir
* The root directory in which all these parts and all other game
* information is stored.
*/
public InstanceManager(String name, Map<String, Map<String, Object>> partData,
String rootDir) {
gameName = name;
userParts = partData;
rootDirectory = rootDir;
}
public InstanceManager() {
this("Unnamed_Game", new HashMap<String, Map<String, Object>>(),
defaultSaveLocation + "/Unnamed_Game");
}
public InstanceManager(String name) {
this(name, new HashMap<String, Map<String, Object>>(), defaultSaveLocation
+ "/" + name);
}
public InstanceManager(String name, String rootDir) {
this(name, new HashMap<String, Map<String, Object>>(), rootDir);
}
public InstanceManager(String name, Map<String, Map<String, Object>> partData) {
this(name, partData, defaultSaveLocation + "/" + name);
}
/**
* This is one way parts will be added from the Editor windows like
* TowerEditor If convenient, any editor can pass the addPart method two
* lists, one of parameter names and the other of data (with corresponding
* indeces). A name and partType parameter will be added to the Map before
* it's added to the list of parts.
*
* @param partType
* The type of part, i.e. "Tower"
* @param partName
* The name of the part, i.e. "IceShooterTower"
* @param params
* List of the parameters that this part needs, i.e. "HP",
* "Range", "Projectile"
* @param data
* List of corresponding data values for those params, i.e. 1,
* 1.0, "Projectile1.xml"
* @return The part that was created and added top user's parts
*/
public Map<String, Object> addPart(String partType, String partName,
List<String> params, List<Object> data) {
Map<String, Object> toAdd = new HashMap<String, Object>();
try {
toAdd = generatePartMap(params, data);
toAdd.put(nameKey, partName);
addPart(partType, toAdd);
} catch (DataFormatException e) {
System.err
.println("Part could not be generated and was not added.");
}
return toAdd;
}
private Map<String, Object> generatePartMap(List<String> params,
List<Object> data) throws DataFormatException {
if (params.size() != data.size())
throw new DataFormatException(listSizesDiffer);
Map<String, Object> part = new HashMap<String, Object>();
for (int i = 0; i < params.size(); i++)
part.put(params.get(i), data.get(i));
return part;
}
/**
* Takes the partType and a map of parameters to data and uses that data to
* add the appropriate part to the list of parts. The map must already
* contain the key "Name" with the corresponding String data, or else name
* will be missing from the final part added.
*
* @param partType
* The type of part to be added, e.g. "Tower"
* @param part
* The map representing the parts parameters and data. Must
* include "Name" key.
* @return
*/
public Map<String, Object> addPart(String partType, Map<String, Object> part) {
part.put(partTypeKey, partType);
String partKey = gameName + "_" + (String) part.get(nameKey) + "." + partType;
part.put(partKeyKey, partKey);
try {
writePartToXML(addPartToUserParts(part, partKey));
} catch (DataFormatException e) {
System.err.println("Part was not added.");
}
return part;
}
private Map<String, Object> addPartToUserParts(
Map<String, Object> partToCheck, String partKey) throws DataFormatException {
if (partToCheck.containsKey("Name")) {
userParts.put(partKey, partToCheck);
return partToCheck;
} else
throw new DataFormatException(missingNameKey);
}
/**
* Writes the part, passed as a Map, into an XML file in:
* rootDirectory/partType/partName.xml, for example:
* ...myTowerGames/Tower/IceShootingTower.xml
*
* @param part
* The part to write to XML
*/
private void writePartToXML(Map<String, Object> part) {
String partType = (String) part.get(partTypeKey);
String partFileName = (String) part.get(nameKey) + ".xml";
String directory = rootDirectory + "/" + partType;
XMLWriter.toXML(part, partFileName, directory);
}
/**
* Writes all parts of the current game into their respective files
*/
public void writeAllPartsToXML() {
for (String key : userParts.keySet())
writePartToXML(userParts.get(key));
}
/**
* Saves everything about the current state of the user's game into an xml
* file. This method writes all the parts to individual files, and then
* writes the InstanceManager to a separate file for retrieval in the
* authoring environement later.
*
* @return the directory where the InstanceManager object was saved
*/
public String saveGame() {
writeAllPartsToXML();
// XMLWriter.toXML(userParts, partFileName, rootDirectory +
// partsFileDir);
System.out.println("writing to xml manager");
XMLWriter.toXML(this, IMFileName, rootDirectory + partsFileDir);
return rootDirectory + partsFileDir;
}
/**
* Loads the InstanceManager object that's stored in a data file. The path
* to this data file is found in the file that the String argument leads to.
* This path will lead to a .game file. This method can only be called by
* the authoring environment.
*
* @param pathToRootDirFile
* The location of the file that holds the path to the root
* directory of the game being loaded.
* @return the InstanceManager of the game specified by the path in the file
* specified by the argument
*/
protected static InstanceManager loadGameManager(String pathToRootDirFile) {
String[] nameAndDirectory = (String[]) XMLWriter
.fromXML(pathToRootDirFile);
String rootDirectory = nameAndDirectory[1];
return (InstanceManager) XMLWriter
.fromXML(rootDirectory + partsFileDir + "/" + IMFileName);
}
/**
* Gets a copy of the List of part data stored in the game specified by the
* argument.
*
* @param pathToRootDirFile
* The location of the file that holds the path to the root
* directory of the game whose data is being loaded.
* @return The list reperesnting the data of all the parts in this game
*/
public static Map<String, Map<String, Object>> loadGameData(
String pathToRootDirFile) {
return loadGameManager(pathToRootDirFile).getAllPartData();
}
/**
* Gets a copy of the data representing all the parts of this game. Altering
* this list will not alter the actual game data in any way.
* @return
*
* @return A copy of all the part data in this game, stored as a list of
* maps.
*/
public Map<String, Map<String, Object>> getAllPartData() {
return new HashMap<String, Map<String, Object>>(userParts);
}
/**
* Gets the part type by looking at what comes before the first "_" in the
* name
*
* @param partName
* The name of the part
* @return The type of part, i.e. "Tower", "Projectile", "Unit", etc.
*/
/*
* private static String partTypeFromName(String partName) { return
* partName.substring(0, partName.indexOf("_")); }
*/
/*
* //if you're using a class like TowerEditor, get the word "Tower" from it
* //not sure if this method's useful yet, or in its best form public static
* String getPartType(Object o){ String className = o.getClass().toString();
* return className.substring(0, className.indexOf("Editor")); }
*/
* /**
*
* @param partName The name of the part you want to update
*
* @param param Which parameter of that part you want to update
*
* @param newData The new value of that parameter's data, as a String
*/
/**
*
* @param gameName
* The name of the game from which you want to load a part
* @param partName
* The name of the part from that game you want to load
* @return The part in Map<String, Object> form
* @throws IOException
*/
public Map<String, Object> getPartFromXML(String fileLocation)
throws IOException {
return (Map<String, Object>) XMLWriter.fromXML(fileLocation);
}
@Override
public String toString() {
StringBuilder toPrint = new StringBuilder();
for (String key : userParts.keySet())
toPrint.append("Key: " + key)
.append(" = \n")
.append(" " + userParts.get(key).toString() + "\n");
return toPrint.toString();
}
public String getName() {
return gameName;
}
/**
* At the moment, this adds a default part, but this probably won't end up
* being used
*
* @param partType
* the kind of part to be added
* @return the part that was added
*/
/*
* public Map<String, Object> addPart(String partType){ Map<String, Object>
* newPart = GameManager.createDefaultPart(partType); String partName =
* partType + "_" + "Part_" + new Integer(partsCreated++).toString();
* userParts.put(partName, newPart); return newPart; }
*/
public static void main(String[] args) {
// gameRootDirectory will be chosen by the user, but here we're just
// putting an an example
InstanceManager example = GameCreator.createNewGame("TestingManagerGame", gameRootDirectory);
// hardcode in an example part to show how it works
List<String> params = new ArrayList<String>();
params.add("HP");
params.add("Range");
List<Object> data = new ArrayList<Object>();
data.add(new Integer(500));
data.add(new Double(1.5));
example.addPart("Tower", "MyFirstTower", params, data);
List<String> params2 = new ArrayList<String>();
params2.add("HP");
params2.add("Speed");
params2.add("Damage");
List<Object> data2 = new ArrayList<Object>();
data2.add(new Integer(100));
data2.add(new Double(1.5));
data2.add(new Double(10));
example.addPart("Enemy", "MyFirstEnemy", params2, data2);
example.saveGame();
//this method is called with the path to the .game file, which will be received from the user
Map<String, Map<String, Object>> gamedata =
InstanceManager.loadGameData(gameRootDirectory + "/TestingManagerGame/TestingManagerGame.game");
InstanceManager loadedIn = InstanceManager
.loadGameManager(gameRootDirectory + "/TestingManagerGame/TestingManagerGame.game");
System.out.println("GAME DATA AS MAP: \n" + gamedata.toString());
System.out.println("GAME AS MANAGER: \n" + loadedIn.toString());
/*
* InstanceManager gameManager = new InstanceManager("TestGame");
* GameManager.createGameFolders(gameManager.getName());
* gameManager.addPart(TOWER); gameManager.addPart(UNIT);
* gameManager.addPart(PROJECTILE); gameManager.addPart(PROJECTILE);
* gameManager.addPart(UNIT); gameManager.addPart(UNIT);
* gameManager.addPart(TOWER); System.out.println(gameManager);
*
* // TODO: Remove hardcoded "magic values" // Or if this is a test,
* then ignore this. gameManager.updatePart("Tower_Part_0", "HP",
* "5000"); gameManager.updatePart("Tower_Part_0", "FireRate", "8");
* gameManager.updatePart("Unit_Part_4", "Speed", "3");
* System.out.println(gameManager);
*
* gameManager.writeAllPartsToXML(); // example of overwriting a file //
* XMLWriter.toXML(new String("testing"), "Projectile_Part_2", //
* userDataPackage + "\\TestGame\\Projectile"); String stringyDir =
* XMLWriter.toXML(new String("String theory"), "stringy");
* XMLWriter.toXML(new String("hascode class test")); String
* stringyLoaded = (String) XMLWriter.fromXML(stringyDir);
* System.out.println("Stringy test: " + stringyLoaded); try {
* System.out.println("from xml: " +
* gameManager.getPartFromXML("Tower_Part_0")); } catch (IOException e)
* { // TODO Auto-generated catch block e.printStackTrace();
*
* }
*/
}
} |
package baseCode.math;
import cern.colt.list.DoubleArrayList;
import cern.jet.stat.Descriptive;
public class DescriptiveWithMissing extends cern.jet.stat.Descriptive {
private DescriptiveWithMissing() {
}
/**
* <b>Not supported. </b>
*
* @param data DoubleArrayList
* @param lag int
* @param mean double
* @param variance double
* @return double
*/
public static double autoCorrelation( DoubleArrayList data, int lag,
double mean, double variance ) {
throw new UnsupportedOperationException(
"autoCorrelation not supported with missing values" );
}
/**
* Returns the correlation of two data sequences. That is
* <tt>covariance(data1,data2)/(standardDev1*standardDev2)</tt>. Missing
* values are ignored.
*
* This method is overridden to stop users from using the method in the
* superclass when missing values are present. The problem is that the
* standard deviation cannot be computed without knowning which values are
* not missing in both vectors to be compared. Thus the standardDev
* parameters are thrown away by this method.
*
* @param data1 DoubleArrayList
* @param standardDev1 double - not used
* @param data2 DoubleArrayList
* @param standardDev2 double - not used
* @return double
*/
public static double correlation( DoubleArrayList data1,
double standardDev1, DoubleArrayList data2, double standardDev2 ) {
return correlation( data1, data2 );
}
/**
* Calculate the pearson correlation of two arrays. Missing values (NaNs) are
* ignored.
*
* @param x DoubleArrayList
* @param y DoubleArrayList
* @return double
*/
public static double correlation( DoubleArrayList x, DoubleArrayList y ) {
int j;
double syy, sxy, sxx, sx, sy, xj, yj, ay, ax;
int numused;
syy = 0.0;
sxy = 0.0;
sxx = 0.0;
sx = 0.0;
sy = 0.0;
numused = 0;
if ( x.size() != y.size() ) {
throw new ArithmeticException();
}
int length = x.size();
for ( j = 0; j < length; j++ ) {
xj = x.elements()[j];
yj = y.elements()[j];
if ( !Double.isNaN( xj ) && !Double.isNaN( yj ) ) {
sx += xj;
sy += yj;
sxy += xj * yj;
sxx += xj * xj;
syy += yj * yj;
numused++;
}
}
if ( numused > 0 ) {
ay = sy / numused;
ax = sx / numused;
return ( sxy - sx * ay )
/ Math.sqrt( ( sxx - sx * ax ) * ( syy - sy * ay ) );
} else {
return -2.0; // signifies that it could not be calculated.
}
}
/**
* Returns the covariance of two data sequences. Pairs of values are only
* considered if both are not NaN. If there are no non-missing pairs, the
* covariance is zero.
*
* @param data1 the first vector
* @param data2 the second vector
* @return double
*/
public static double covariance( DoubleArrayList data1, DoubleArrayList data2 ) {
int size = data1.size();
if ( size != data2.size() || size == 0 ) {
throw new IllegalArgumentException();
}
double[] elements1 = data1.elements();
double[] elements2 = data2.elements();
/* initialize sumx and sumy to the first non-NaN pair of values */
int i = 0;
double sumx = 0.0, sumy = 0.0, Sxy = 0.0;
while ( i < size ) {
sumx = elements1[i];
sumy = elements2[i];
if ( !Double.isNaN( elements1[i] ) && !Double.isNaN( elements2[i] ) ) {
break;
}
i++;
}
i++;
int usedPairs = 1;
for ( ; i < size; ++i ) {
double x = elements1[i];
double y = elements2[i];
if ( Double.isNaN( x ) || Double.isNaN( y ) ) {
continue;
}
sumx += x;
Sxy += ( x - sumx / ( usedPairs + 1 ) ) * ( y - sumy / usedPairs );
sumy += y;
usedPairs++;
}
return Sxy / usedPairs;
}
/**
* Durbin-Watson computation. This measures the serial correlation in a data
* series.
*
* @param data DoubleArrayList
* @return double
* @todo this will still break in some situations where there are missing
* values
*/
public static double durbinWatson( DoubleArrayList data ) {
int size = data.size();
if ( size < 2 ) {
throw new IllegalArgumentException(
"data sequence must contain at least two values." );
}
double[] elements = data.elements();
double run = 0;
double run_sq = 0;
int firstNotNaN = 0;
while ( firstNotNaN < size ) {
run_sq = elements[firstNotNaN] * elements[firstNotNaN];
if ( !Double.isNaN( elements[firstNotNaN] ) ) {
break;
}
firstNotNaN++;
}
if ( firstNotNaN > 0 && size - firstNotNaN < 2 ) {
throw new IllegalArgumentException(
"data sequence must contain at least two non-missing values." );
}
for ( int i = firstNotNaN + 1; i < size; i++ ) {
int gap = 1;
while ( Double.isNaN( elements[i] ) ) {
gap++;
i++;
continue;
}
double x = elements[i] - elements[i - gap];
run += x * x;
run_sq += elements[i] * elements[i];
}
return run / run_sq;
}
/**
* Returns the geometric mean of a data sequence. Missing values are ignored.
* Note that for a geometric mean to be meaningful, the minimum of the data
* sequence must not be less or equal to zero. <br>
* The geometric mean is given by <tt>pow( Product( data[i] ),
* 1/data.size())</tt>.
* This method tries to avoid overflows at the expense of an equivalent but
* somewhat slow definition: <tt>geo = Math.exp( Sum(
* Log(data[i]) ) / data.size())</tt>.
*
* @param data DoubleArrayList
* @return double
*/
public static double geometricMean( DoubleArrayList data ) {
return geometricMean( sizeWithoutMissingValues( data ), sumOfLogarithms(
data, 0, data.size() - 1 ) );
}
/**
* <b>Not supported. </b>
*
* @param data DoubleArrayList
* @param from int
* @param to int
* @param inOut double[]
*/
public static void incrementalUpdate( DoubleArrayList data, int from,
int to, double[] inOut ) {
throw new UnsupportedOperationException(
"incrementalUpdate not supported with missing values" );
}
/**
* <b>Not supported. </b>
*
* @param data DoubleArrayList
* @param from int
* @param to int
* @param fromSumIndex int
* @param toSumIndex int
* @param sumOfPowers double[]
*/
public static void incrementalUpdateSumsOfPowers( DoubleArrayList data,
int from, int to, int fromSumIndex, int toSumIndex,
double[] sumOfPowers ) {
throw new UnsupportedOperationException(
"incrementalUpdateSumsOfPowers not supported with missing values" );
}
/**
* <b>Not supported. </b>
*
* @param data DoubleArrayList
* @param weights DoubleArrayList
* @param from int
* @param to int
* @param inOut double[]
*/
public static void incrementalWeightedUpdate( DoubleArrayList data,
DoubleArrayList weights, int from, int to, double[] inOut ) {
throw new UnsupportedOperationException(
"incrementalWeightedUpdate not supported with missing values" );
}
/**
* Returns the kurtosis (aka excess) of a data sequence.
*
* @param moment4 the fourth central moment, which is
* <tt>moment(data,4,mean)</tt>.
* @param standardDeviation the standardDeviation.
* @return double
*/
public static double kurtosis( double moment4, double standardDeviation ) {
return -3
+ moment4
/ ( standardDeviation * standardDeviation * standardDeviation * standardDeviation );
}
/**
* Returns the kurtosis (aka excess) of a data sequence, which is <tt>-3 +
* moment(data,4,mean) / standardDeviation<sup>4</sup></tt>.
*
* @param data DoubleArrayList
* @param mean double
* @param standardDeviation double
* @return double
*/
public static double kurtosis( DoubleArrayList data, double mean,
double standardDeviation ) {
return kurtosis( moment( data, 4, mean ), standardDeviation );
}
/**
* <b>Not supported. </b>
*
* @param data DoubleArrayList
* @param mean double
* @return double
*/
public static double lag1( DoubleArrayList data, double mean ) {
throw new UnsupportedOperationException(
"lag1 not supported with missing values" );
}
/**
* @param data Values to be analyzed.
* @return Mean of the values in x. Missing values are ignored in the
* analysis.
*/
public static double mean( DoubleArrayList data ) {
return sum( data ) / sizeWithoutMissingValues( data );
}
/**
* Special mean calculation where we use the effective size as an input.
*
* @param x The data
* @param effectiveSize The effective size used for the mean calculation.
* @return double
*/
public static double mean( DoubleArrayList x, int effectiveSize ) {
int length = x.size();
if ( 0 == effectiveSize ) {
return Double.NaN;
}
double sum = 0.0;
int i, count;
count = 0;
double value;
double[] elements = x.elements();
for ( i = 0; i < length; i++ ) {
value = elements[i];
if ( Double.isNaN( value ) ) {
continue;
}
sum += value;
count++;
}
if ( 0.0 == count ) {
return Double.NaN;
} else {
return sum / effectiveSize;
}
}
/**
* Special mean calculation where we use the effective size as an input.
*
* @param elements The data double array.
* @param effectiveSize The effective size used for the mean calculation.
* @return double
*/
public static double mean( double[] elements, int effectiveSize ) {
int length = elements.length;
if ( 0 == effectiveSize ) {
return Double.NaN;
}
double sum = 0.0;
int i, count;
count = 0;
double value;
for ( i = 0; i < length; i++ ) {
value = elements[i];
if ( Double.isNaN( value ) ) {
continue;
}
sum += value;
count++;
}
if ( 0.0 == count ) {
return Double.NaN;
} else {
return sum / effectiveSize;
}
}
/**
* Calculate the mean of the values above a particular quantile of an array.
*
* @param quantile A value from 0 to 100
* @param array Array for which we want to get the quantile.
* @return double
*/
public static double meanAboveQuantile( int quantile, DoubleArrayList array ) {
if ( quantile < 0 || quantile > 100 ) {
throw new IllegalArgumentException(
"Quantile must be between 0 and 100" );
}
double returnvalue = 0.0;
int k = 0;
double median = Descriptive.quantile( array, ( double ) quantile );
for ( int i = 0; i < array.size(); i++ ) {
if ( array.get( i ) >= median ) {
returnvalue += array.get( i );
k++;
}
}
if ( k == 0 ) {
throw new ArithmeticException( "No values found above quantile" );
}
return ( returnvalue / k );
}
/**
* Returns the median of a sorted data sequence. Missing values are not
* considered.
*
* @param sortedData the data sequence; <b>must be sorted ascending </b>.
* @return double
*/
public static double median( DoubleArrayList sortedData ) {
return quantile( sortedData, 0.5 );
}
/**
* Returns the moment of <tt>k</tt> -th order with constant <tt>c</tt> of
* a data sequence, which is <tt>Sum( (data[i]-c)<sup>k</sup> ) /
* data.size()</tt>.
*
* @param data DoubleArrayList
* @param k int
* @param c double
* @return double
*/
public static double moment( DoubleArrayList data, int k, double c ) {
return sumOfPowerDeviations( data, k, c )
/ sizeWithoutMissingValues( data );
}
/**
* Returns the product of a data sequence, which is <tt>Prod( data[i] )</tt>.
* Missing values are ignored. In other words:
* <tt>data[0]*data[1]*...*data[data.size()-1]</tt>. Note that you may
* easily get numeric overflows.
*
* @param data DoubleArrayList
* @return double
*/
public static double product( DoubleArrayList data ) {
int size = data.size();
double[] elements = data.elements();
double product = 1;
for ( int i = size; --i >= 0; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
product *= elements[i];
}
return product;
}
/**
* Returns the <tt>phi-</tt> quantile; that is, an element <tt>elem</tt>
* for which holds that <tt>phi</tt> percent of data elements are less than
* <tt>elem</tt>. Missing values are ignored. The quantile need not
* necessarily be contained in the data sequence, it can be a linear
* interpolation.
*
* @param sortedData the data sequence; <b>must be sorted ascending </b>.
* @param phi the percentage; must satisfy <tt>0 <= phi <= 1</tt>.
* @todo possibly implement so a copy is not made.
* @return double
*/
public static double quantile( DoubleArrayList sortedData, double phi ) {
return Descriptive.quantile( removeMissing( sortedData ), phi );
}
/**
* Returns how many percent of the elements contained in the receiver are
* <tt><= element</tt>. Does linear interpolation if the element is not
* contained but lies in between two contained elements. Missing values are
* ignored.
*
* @param sortedList the list to be searched (must be sorted ascending).
* @param element the element to search for.
* @return the percentage <tt>phi</tt> of elements <tt><= element</tt>(
* <tt>0.0 <= phi <= 1.0)</tt>.
*/
public static double quantileInverse( DoubleArrayList sortedList,
double element ) {
return rankInterpolated( sortedList, element ) / sortedList.size();
}
/**
* Returns the quantiles of the specified percentages. The quantiles need not
* necessarily be contained in the data sequence, it can be a linear
* interpolation.
*
* @param sortedData the data sequence; <b>must be sorted ascending </b>.
* @param percentages the percentages for which quantiles are to be computed.
* Each percentage must be in the interval <tt>[0.0,1.0]</tt>.
* @return the quantiles.
*/
public static DoubleArrayList quantiles( DoubleArrayList sortedData,
DoubleArrayList percentages ) {
int s = percentages.size();
DoubleArrayList quantiles = new DoubleArrayList( s );
for ( int i = 0; i < s; i++ ) {
quantiles.add( quantile( sortedData, percentages.get( i ) ) );
}
return quantiles;
}
/**
* Returns the linearly interpolated number of elements in a list less or
* equal to a given element. Missing values are ignored. The rank is the
* number of elements <= element. Ranks are of the form
* <tt>{0, 1, 2,..., sortedList.size()}</tt>. If no element is <= element,
* then the rank is zero. If the element lies in between two contained
* elements, then linear interpolation is used and a non integer value is
* returned.
*
* @param sortedList the list to be searched (must be sorted ascending).
* @param element the element to search for.
* @return the rank of the element.
* @todo possibly implement so a copy is not made.
*/
public static double rankInterpolated( DoubleArrayList sortedList,
double element ) {
return Descriptive
.rankInterpolated( removeMissing( sortedList ), element );
}
/**
* Returns the sample kurtosis (aka excess) of a data sequence.
*
* @param data DoubleArrayList
* @param mean double
* @param sampleVariance double
* @return double
*/
public static double sampleKurtosis( DoubleArrayList data, double mean,
double sampleVariance ) {
return sampleKurtosis( sizeWithoutMissingValues( data ), moment( data, 4,
mean ), sampleVariance );
}
/**
* Returns the sample skew of a data sequence.
*
* @param data DoubleArrayList
* @param mean double
* @param sampleVariance double
* @return double
*/
public static double sampleSkew( DoubleArrayList data, double mean,
double sampleVariance ) {
return sampleSkew( sizeWithoutMissingValues( data ), moment( data, 3,
mean ), sampleVariance );
}
/**
* Returns the skew of a data sequence, which is <tt>moment(data,3,mean) /
* standardDeviation<sup>3</sup></tt>.
*
* @param data DoubleArrayList
* @param mean double
* @param standardDeviation double
* @return double
*/
public static double skew( DoubleArrayList data, double mean,
double standardDeviation ) {
return skew( moment( data, 3, mean ), standardDeviation );
}
/**
* Returns the sample variance of a data sequence. That is <tt>Sum (
* (data[i]-mean)^2 ) / (data.size()-1)</tt>.
*
* @param data DoubleArrayList
* @param mean double
* @return double
*/
public static double sampleVariance( DoubleArrayList data, double mean ) {
double[] elements = data.elements();
int effsize = sizeWithoutMissingValues( data );
int size = data.size();
double sum = 0;
// find the sum of the squares
for ( int i = size; --i >= 0; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
double delta = elements[i] - mean;
sum += delta * delta;
}
return sum / ( effsize - 1 );
}
/**
* Modifies a data sequence to be standardized. Mising values are ignored.
* Changes each element <tt>data[i]</tt> as follows:
* <tt>data[i] = (data[i]-mean)/standardDeviation</tt>.
*
* @param data DoubleArrayList
* @param mean mean of data
* @param standardDeviation stdev of data
*/
public static void standardize( DoubleArrayList data, double mean,
double standardDeviation ) {
double[] elements = data.elements();
for ( int i = data.size(); --i >= 0; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
elements[i] = ( elements[i] - mean ) / standardDeviation;
}
}
/**
* Standardize
*
* @param data DoubleArrayList
*/
public static void standardize( DoubleArrayList data ) {
double mean = DescriptiveWithMissing.mean( data );
double stdev = Math.sqrt( DescriptiveWithMissing.sampleVariance( data,
mean ) );
DescriptiveWithMissing.standardize( data, mean, stdev );
}
/**
* Returns the sum of a data sequence. That is <tt>Sum( data[i] )</tt>.
*
* @param data DoubleArrayList
* @return double
*/
public static double sum( DoubleArrayList data ) {
return sumOfPowerDeviations( data, 1, 0.0 );
}
/**
* Returns the sum of inversions of a data sequence, which is <tt>Sum( 1.0 /
* data[i])</tt>.
*
* @param data the data sequence.
* @param from the index of the first data element (inclusive).
* @param to the index of the last data element (inclusive).
* @return double
*/
public static double sumOfInversions( DoubleArrayList data, int from, int to ) {
return sumOfPowerDeviations( data, -1, 0.0, from, to );
}
/**
* Returns the sum of logarithms of a data sequence, which is <tt>Sum(
* Log(data[i])</tt>.
* Missing values are ignored.
*
* @param data the data sequence.
* @param from the index of the first data element (inclusive).
* @param to the index of the last data element (inclusive).
* @return double
*/
public static double sumOfLogarithms( DoubleArrayList data, int from, int to ) {
double[] elements = data.elements();
double logsum = 0;
for ( int i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
logsum += Math.log( elements[i] );
}
return logsum;
}
/**
* Returns the sum of powers of a data sequence, which is <tt>Sum (
* data[i]<sup>k</sup> )</tt>.
*
* @param data DoubleArrayList
* @param k int
* @return double
*/
public static double sumOfPowers( DoubleArrayList data, int k ) {
return sumOfPowerDeviations( data, k, 0 );
}
/**
* Returns the sum of squares of a data sequence. Skips missing values.
*
* @param data DoubleArrayList
* @return double
*/
public static double sumOfSquares( DoubleArrayList data ) {
return sumOfPowerDeviations( data, 2, 0.0 );
}
/**
* Compute the sum of the squared deviations from the mean of a data
* sequence. Missing values are ignored.
*
* @param data DoubleArrayList
* @return double
*/
public static double sumOfSquaredDeviations( DoubleArrayList data ) {
return sumOfSquaredDeviations( sizeWithoutMissingValues( data ),
variance( sizeWithoutMissingValues( data ), sum( data ),
sumOfSquares( data ) ) );
}
/**
* Returns <tt>Sum( (data[i]-c)<sup>k</sup> )</tt>; optimized for common
* parameters like <tt>c == 0.0</tt> and/or <tt>k == -2 .. 4</tt>.
*
* @param data DoubleArrayList
* @param k int
* @param c double
* @return double
*/
public static double sumOfPowerDeviations( DoubleArrayList data, int k,
double c ) {
return sumOfPowerDeviations( data, k, c, 0, data.size() - 1 );
}
/**
* Returns <tt>Sum( (data[i]-c)<sup>k</sup> )</tt> for all
* <tt>i = from ..
* to</tt>; optimized for common parameters like
* <tt>c == 0.0</tt> and/or <tt>k == -2 .. 5</tt>. Missing values are
* ignored.
*
* @param data DoubleArrayList
* @param k int
* @param c double
* @param from int
* @param to int
* @return double
*/
public static double sumOfPowerDeviations( final DoubleArrayList data,
final int k, final double c, final int from, final int to ) {
final double[] elements = data.elements();
double sum = 0;
double v;
int i;
switch ( k ) { // optimized for speed
case -2:
if ( c == 0.0 ) {
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
v = elements[i];
sum += 1 / ( v * v );
}
} else {
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
v = elements[i] - c;
sum += 1 / ( v * v );
}
}
break;
case -1:
if ( c == 0.0 ) {
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
sum += 1 / ( elements[i] );
}
} else {
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
sum += 1 / ( elements[i] - c );
}
}
break;
case 0:
sum += to - from + 1;
break;
case 1:
if ( c == 0.0 ) {
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
sum += elements[i];
}
} else {
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
sum += elements[i] - c;
}
}
break;
case 2:
if ( c == 0.0 ) {
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
v = elements[i];
sum += v * v;
}
} else {
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
v = elements[i] - c;
sum += v * v;
}
}
break;
case 3:
if ( c == 0.0 ) {
for ( i = from - 1; ++i <= to; ) {
v = elements[i];
sum += v * v * v;
}
} else {
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
v = elements[i] - c;
sum += v * v * v;
}
}
break;
case 4:
if ( c == 0.0 ) {
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
v = elements[i];
sum += v * v * v * v;
}
} else {
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
v = elements[i] - c;
sum += v * v * v * v;
}
}
break;
case 5:
if ( c == 0.0 ) {
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
v = elements[i];
sum += v * v * v * v * v;
}
} else {
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
v = elements[i] - c;
sum += v * v * v * v * v;
}
}
break;
default:
for ( i = from - 1; ++i <= to; ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
sum += Math.pow( elements[i] - c, k );
}
break;
}
return sum;
}
/**
* Return the size of the list, ignoring missing values.
*
* @param list DoubleArrayList
* @return int
*/
public static int sizeWithoutMissingValues( DoubleArrayList list ) {
int size = 0;
for ( int i = 0; i < list.size(); i++ ) {
if ( !Double.isNaN( list.get( i ) ) ) {
size++;
}
}
return size;
}
/**
* Returns the trimmed mean of a sorted data sequence. Missing values are
* completely ignored.
*
* @param sortedData the data sequence; <b>must be sorted ascending </b>.
* @param mean the mean of the (full) sorted data sequence.
* @param left int the number of leading elements to trim.
* @param right int number of trailing elements to trim.
* @return double
*/
public static double trimmedMean( DoubleArrayList sortedData, double mean,
int left, int right ) {
return Descriptive.trimmedMean( removeMissing( sortedData ), mean, left,
right );
}
/**
* Provided for convenience!
*
* @param data DoubleArrayList
* @return double
*/
public static double variance( DoubleArrayList data ) {
return variance( sizeWithoutMissingValues( data ), sum( data ),
sumOfSquares( data ) );
}
/**
* Returns the weighted mean of a data sequence. That is <tt> Sum (data[i] *
* weights[i]) / Sum ( weights[i] )</tt>.
*
* @param data DoubleArrayList
* @param weights DoubleArrayList
* @return double
*/
public static double weightedMean( DoubleArrayList data,
DoubleArrayList weights ) {
int size = data.size();
if ( size != weights.size() || size == 0 ) {
throw new IllegalArgumentException();
}
double[] elements = data.elements();
double[] theWeights = weights.elements();
double sum = 0.0;
double weightsSum = 0.0;
for ( int i = size; --i >= 0; ) {
double w = theWeights[i];
if ( Double.isNaN( elements[i] ) ) {
continue;
}
sum += elements[i] * w;
weightsSum += w;
}
return sum / weightsSum;
}
/**
* <b>Not supported. </b>
*
* @param sortedData DoubleArrayList
* @param mean double
* @param left int
* @param right int
* @return double
*/
public static double winsorizedMean( DoubleArrayList sortedData,
double mean, int left, int right ) {
throw new UnsupportedOperationException(
"winsorizedMean not supported with missing values" );
}
/* private methods */
/**
* Convenience function for internal use. Makes a copy of the list that
* doesn't have the missing values.
*
* @param data DoubleArrayList
* @return DoubleArrayList
*/
private static DoubleArrayList removeMissing( DoubleArrayList data ) {
DoubleArrayList r = new DoubleArrayList( sizeWithoutMissingValues( data ) );
double[] elements = data.elements();
int size = data.size();
for ( int i = 0; i < size; i++ ) {
if ( Double.isNaN( elements[i] ) ) {
continue;
}
r.add( elements[i] );
}
return r;
}
} // end of class |
package beast.app.beauti;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import beast.app.draw.InputEditor;
import beast.core.Input;
import beast.core.BEASTObject;
import beast.evolution.alignment.Alignment;
import beast.evolution.alignment.Sequence;
import beast.evolution.alignment.Taxon;
import beast.evolution.alignment.TaxonSet;
public class TaxonSetInputEditor extends InputEditor.Base {
private static final long serialVersionUID = 1L;
List<Taxon> m_taxonset;
List<Taxon> m_lineageset;
Map<String, String> m_taxonMap;
JTable m_table;
DefaultTableModel m_model = new DefaultTableModel();
JTextField filterEntry;
String m_sFilter = ".*";
int m_sortByColumn = 0;
boolean m_bIsAscending = true;
public TaxonSetInputEditor(BeautiDoc doc) {
super(doc);
}
@Override
public Class<?> type() {
return TaxonSet.class;
}
@Override
public void init(Input<?> input, BEASTObject plugin, int itemNr, ExpandOption bExpandOption, boolean bAddButtons) {
m_input = input;
m_plugin = plugin;
this.itemNr = itemNr;
TaxonSet taxonset = (TaxonSet) m_input.get();
if (taxonset == null) {
return;
}
List<Taxon> taxonsets = new ArrayList<Taxon>();
List<Taxon> taxa = taxonset.taxonsetInput.get();
for (Taxon taxon : taxa) {
taxonsets.add((TaxonSet) taxon);
}
add(getContent(taxonsets));
if (taxa.size() == 1 && taxa.get(0).getID().equals("Beauti2DummyTaxonSet") || taxa.size() == 0) {
taxa.clear();
try {
// species is first character of taxon
guessTaxonSets("(.).*", 0);
for (Taxon taxonset2 : m_taxonset) {
for (Taxon taxon : ((TaxonSet) taxonset2).taxonsetInput.get()) {
m_lineageset.add(taxon);
m_taxonMap.put(taxon.getID(), taxonset2.getID());
}
}
} catch (Exception e) {
e.printStackTrace();
}
taxonSetToModel();
modelToTaxonset();
}
}
private Component getContent(List<Taxon> taxonset) {
m_taxonset = taxonset;
m_taxonMap = new HashMap<String, String>();
m_lineageset = new ArrayList<Taxon>();
for (Taxon taxonset2 : m_taxonset) {
for (Taxon taxon : ((TaxonSet) taxonset2).taxonsetInput.get()) {
m_lineageset.add(taxon);
m_taxonMap.put(taxon.getID(), taxonset2.getID());
}
}
// set up table.
// special features: background shading of rows
// custom editor allowing only Date column to be edited.
m_model = new DefaultTableModel();
m_model.addColumn("Taxon");
m_model.addColumn("Species/Population");
taxonSetToModel();
m_table = new JTable(m_model) {
private static final long serialVersionUID = 1L;
// method that induces table row shading
@Override
public Component prepareRenderer(TableCellRenderer renderer, int Index_row, int Index_col) {
Component comp = super.prepareRenderer(renderer, Index_row, Index_col);
// even index, selected or not selected
if (isCellSelected(Index_row, Index_col)) {
comp.setBackground(Color.gray);
} else if (Index_row % 2 == 0) {
comp.setBackground(new Color(237, 243, 255));
} else {
comp.setBackground(Color.white);
}
return comp;
}
};
// set up editor that makes sure only doubles are accepted as entry
// and only the Date column is editable.
m_table.setDefaultEditor(Object.class, new TableCellEditor() {
JTextField m_textField = new JTextField();
int m_iRow
,
m_iCol;
@Override
public boolean stopCellEditing() {
m_table.removeEditor();
String sText = m_textField.getText();
System.err.println(sText);
m_model.setValueAt(sText, m_iRow, m_iCol);
// try {
// Double.parseDouble(sText);
// } catch (Exception e) {
// return false;
modelToTaxonset();
return true;
}
@Override
public boolean isCellEditable(EventObject anEvent) {
return m_table.getSelectedColumn() == 1;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int iRow,
int iCol) {
if (!isSelected) {
return null;
}
m_iRow = iRow;
m_iCol = iCol;
m_textField.setText((String) value);
return m_textField;
}
@Override
public boolean shouldSelectCell(EventObject anEvent) {
return false;
}
@Override
public void removeCellEditorListener(CellEditorListener l) {
}
@Override
public Object getCellEditorValue() {
return null;
}
@Override
public void cancelCellEditing() {
}
@Override
public void addCellEditorListener(CellEditorListener l) {
}
});
m_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
m_table.getColumnModel().getColumn(0).setPreferredWidth(250);
m_table.getColumnModel().getColumn(1).setPreferredWidth(250);
JTableHeader header = m_table.getTableHeader();
header.addMouseListener(new ColumnHeaderListener());
JScrollPane pane = new JScrollPane(m_table);
Box tableBox = Box.createHorizontalBox();
tableBox.add(Box.createHorizontalGlue());
tableBox.add(pane);
tableBox.add(Box.createHorizontalGlue());
Box box = Box.createVerticalBox();
box.add(createFilterBox());
box.add(tableBox);
box.add(createButtonBox());
return box;
}
private Component createButtonBox() {
Box buttonBox = Box.createHorizontalBox();
JButton fillDownButton = new JButton("Fill down");
fillDownButton.setName("Fill down");
fillDownButton.setToolTipText("replaces all taxons in selection with the one that is selected at the top");
fillDownButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int[] rows = m_table.getSelectedRows();
if (rows.length < 2) {
return;
}
String sTaxon = (String) ((Vector<?>) m_model.getDataVector().elementAt(rows[0])).elementAt(1);
for (int i = 1; i < rows.length; i++) {
m_model.setValueAt(sTaxon, rows[i], 1);
}
modelToTaxonset();
}
});
JButton guessButton = new JButton("Guess");
guessButton.setName("Guess");
guessButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
guess();
}
});
buttonBox.add(Box.createHorizontalGlue());
buttonBox.add(fillDownButton);
buttonBox.add(Box.createHorizontalGlue());
buttonBox.add(guessButton);
buttonBox.add(Box.createHorizontalGlue());
return buttonBox;
}
public class ColumnHeaderListener extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
// The index of the column whose header was clicked
int vColIndex = m_table.getColumnModel().getColumnIndexAtX(evt.getX());
if (vColIndex == -1) {
return;
}
if (vColIndex != m_sortByColumn) {
m_sortByColumn = vColIndex;
m_bIsAscending = true;
} else {
m_bIsAscending = !m_bIsAscending;
}
taxonSetToModel();
}
}
private void guess() {
GuessPatternDialog dlg = new GuessPatternDialog(this, m_sPattern);
switch(dlg.showDialog("Guess taxon sets")) {
case canceled: return;
case pattern:
String sPattern = dlg.getPattern();
try {
guessTaxonSets(sPattern, 0);
m_sPattern = sPattern;
break;
} catch (Exception e) {
e.printStackTrace();
}
case trait:
String trait = dlg.getTrait();
parseTrait(trait);
break;
}
m_lineageset.clear();
for (Taxon taxonset2 : m_taxonset) {
for (Taxon taxon : ((TaxonSet) taxonset2).taxonsetInput.get()) {
m_lineageset.add(taxon);
m_taxonMap.put(taxon.getID(), taxonset2.getID());
}
}
taxonSetToModel();
modelToTaxonset();
}
/**
* guesses taxon sets based on pattern in sRegExp based on the taxa in
* m_rawData
*/
public int guessTaxonSets(String sRegexp, int nMinSize) throws Exception {
m_taxonset.clear();
HashMap<String, TaxonSet> map = new HashMap<String, TaxonSet>();
Pattern m_pattern = Pattern.compile(sRegexp);
Set<Taxon> taxa = new HashSet<Taxon>();
Set<String> taxonIDs = new HashSet<String>();
for (Alignment alignment : getDoc().alignments) {
for (String sID : alignment.getTaxaNames()) {
if (!taxonIDs.contains(sID)) {
Taxon taxon = new Taxon();
taxon.setID(sID);
taxa.add(taxon);
taxonIDs.add(sID);
}
}
for (Sequence sequence : alignment.sequenceInput.get()) {
String sID = sequence.taxonInput.get();
if (!taxonIDs.contains(sID)) {
Taxon taxon = new Taxon();
// ensure sequence and taxon do not get same ID
if (sequence.getID().equals(sequence.taxonInput.get())) {
sequence.setID("_" + sequence.getID());
}
taxon.setID(sequence.taxonInput.get());
taxa.add(taxon);
taxonIDs.add(sID);
}
}
}
for (Taxon taxon : taxa) {
if (!(taxon instanceof TaxonSet)) {
Matcher matcher = m_pattern.matcher(taxon.getID());
if (matcher.find()) {
String sMatch = matcher.group(1);
try {
if (map.containsKey(sMatch)) {
TaxonSet set = map.get(sMatch);
set.taxonsetInput.setValue(taxon, set);
} else {
TaxonSet set = new TaxonSet();
set.setID(sMatch);
set.taxonsetInput.setValue(taxon, set);
map.put(sMatch, set);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
// add taxon sets
int nIgnored = 0;
for (TaxonSet set : map.values()) {
if (set.taxonsetInput.get().size() > nMinSize) {
m_taxonset.add(set);
} else {
nIgnored += set.taxonsetInput.get().size();
}
}
return nIgnored;
}
void parseTrait(String trait) {
Map<String,String> traitmap = new HashMap<String, String>();
for (String line : trait.split(",")) {
String [] strs = line.split("=");
if (strs.length == 2) {
traitmap.put(strs[0].trim(), strs[1].trim());
}
}
m_taxonset.clear();
Set<Taxon> taxa = new HashSet<Taxon>();
Set<String> taxonIDs = new HashSet<String>();
for (Alignment alignment : getDoc().alignments) {
for (Sequence sequence : alignment.sequenceInput.get()) {
String sID = sequence.taxonInput.get();
if (!taxonIDs.contains(sID)) {
Taxon taxon = new Taxon();
// ensure sequence and taxon do not get same ID
if (sequence.getID().equals(sequence.taxonInput.get())) {
sequence.setID("_" + sequence.getID());
}
taxon.setID(sequence.taxonInput.get());
taxa.add(taxon);
taxonIDs.add(sID);
}
}
}
HashMap<String, TaxonSet> map = new HashMap<String, TaxonSet>();
for (Taxon taxon : taxa) {
if (!(taxon instanceof TaxonSet)) {
String sMatch = traitmap.get(taxon.getID());
if (sMatch != null) {
try {
if (map.containsKey(sMatch)) {
TaxonSet set = map.get(sMatch);
set.taxonsetInput.setValue(taxon, set);
} else {
TaxonSet set = new TaxonSet();
set.setID(sMatch);
set.taxonsetInput.setValue(taxon, set);
map.put(sMatch, set);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
// add taxon sets
int nIgnored = 0;
for (TaxonSet set : map.values()) {
m_taxonset.add(set);
}
}
String m_sPattern = "^(.+)[-_\\. ](.*)$";
private Component createFilterBox() {
Box filterBox = Box.createHorizontalBox();
filterBox.add(new JLabel("filter: "));
// Dimension size = new Dimension(100,20);
filterEntry = new JTextField();
filterEntry.setColumns(20);
// filterEntry.setMinimumSize(size);
// filterEntry.setPreferredSize(size);
// filterEntry.setSize(size);
filterEntry.setToolTipText("Enter regular expression to match taxa");
filterEntry.setMaximumSize(new Dimension(1024, 20));
filterBox.add(filterEntry);
filterBox.add(Box.createHorizontalGlue());
filterEntry.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
processFilter();
}
@Override
public void insertUpdate(DocumentEvent e) {
processFilter();
}
@Override
public void changedUpdate(DocumentEvent e) {
processFilter();
}
private void processFilter() {
String sFilter = ".*" + filterEntry.getText() + ".*";
try {
// sanity check: make sure the filter is legit
sFilter.matches(sFilter);
m_sFilter = sFilter;
taxonSetToModel();
m_table.repaint();
} catch (PatternSyntaxException e) {
// ignore
}
}
});
return filterBox;
}
/**
* for convert taxon sets to table model *
*/
@SuppressWarnings("unchecked")
private void taxonSetToModel() {
// count number of lineages that match the filter
int i = 0;
for (String sLineageID : m_taxonMap.keySet()) {
if (sLineageID.matches(m_sFilter)) {
i++;
}
}
// clear table model
while (m_model.getRowCount() > 0) {
m_model.removeRow(0);
}
// fill table model with lineages matching the filter
for (String sLineageID : m_taxonMap.keySet()) {
if (sLineageID.matches(m_sFilter)) {
Object[] rowData = new Object[2];
rowData[0] = sLineageID;
rowData[1] = m_taxonMap.get(sLineageID);
m_model.addRow(rowData);
}
}
@SuppressWarnings("rawtypes")
Vector data = m_model.getDataVector();
Collections.sort(data, new Comparator<Vector<?>>() {
@Override
public int compare(Vector<?> v1, Vector<?> v2) {
String o1 = (String) v1.get(m_sortByColumn);
String o2 = (String) v2.get(m_sortByColumn);
if (o1.equals(o2)) {
o1 = (String) v1.get(1 - m_sortByColumn);
o2 = (String) v2.get(1 - m_sortByColumn);
}
if (m_bIsAscending) {
return o1.compareTo(o2);
} else {
return o2.compareTo(o1);
}
}
});
m_model.fireTableRowsInserted(0, m_model.getRowCount());
}
/**
* for convert table model to taxon sets *
*/
private void modelToTaxonset() {
// update map
for (int i = 0; i < m_model.getRowCount(); i++) {
String sLineageID = (String) ((Vector<?>) m_model.getDataVector().elementAt(i)).elementAt(0);
String sTaxonSetID = (String) ((Vector<?>) m_model.getDataVector().elementAt(i)).elementAt(1);
// new taxon set?
if (!m_taxonMap.containsValue(sTaxonSetID)) {
// create new taxon set
TaxonSet taxonset = new TaxonSet();
taxonset.setID(sTaxonSetID);
m_taxonset.add(taxonset);
}
m_taxonMap.put(sLineageID, sTaxonSetID);
}
// clear old taxon sets
for (Taxon taxon : m_taxonset) {
TaxonSet set = (TaxonSet) taxon;
set.taxonsetInput.get().clear();
doc.registerPlugin(set);
}
// group lineages with their taxon sets
for (String sLineageID : m_taxonMap.keySet()) {
for (Taxon taxon : m_lineageset) {
if (taxon.getID().equals(sLineageID)) {
String sTaxonSet = m_taxonMap.get(sLineageID);
for (Taxon taxon2 : m_taxonset) {
TaxonSet set = (TaxonSet) taxon2;
if (set.getID().equals(sTaxonSet)) {
try {
set.taxonsetInput.setValue(taxon, set);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
// remove unused taxon sets
for (int i = m_taxonset.size() - 1; i >= 0; i
if (((TaxonSet) m_taxonset.get(i)).taxonsetInput.get().size() == 0) {
doc.unregisterPlugin(m_taxonset.get(i));
m_taxonset.remove(i);
}
}
TaxonSet taxonset = (TaxonSet) m_input.get();
taxonset.taxonsetInput.get().clear();
for (Taxon taxon : m_taxonset) {
try {
taxonset.taxonsetInput.setValue(taxon, taxonset);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} |
package io.vertx.codegen.testmodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import io.vertx.codegen.annotations.Nullable;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
public class NullableTCKImpl implements NullableTCK {
@Override
public boolean methodWithNonNullableByteParam(Byte param) {
return param == null;
}
@Override
public void methodWithNullableByteParam(boolean expectNull, Byte param) {
assertEquals(methodWithNullableByteReturn(!expectNull), param);
}
@Override
public void methodWithNullableByteHandler(boolean notNull, Handler<@Nullable Byte> handler) {
handler.handle(methodWithNullableByteReturn(notNull));
}
@Override
public void methodWithNullableByteHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Byte>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableByteReturn(notNull)));
}
@Override
public @Nullable Byte methodWithNullableByteReturn(boolean notNull) {
return notNull ? (byte)67 : null;
}
@Override
public boolean methodWithNonNullableShortParam(Short param) {
return param == null;
}
@Override
public void methodWithNullableShortParam(boolean expectNull, Short param) {
assertEquals(methodWithNullableShortReturn(!expectNull), param);
}
@Override
public void methodWithNullableShortHandler(boolean notNull, Handler<@Nullable Short> handler) {
handler.handle(methodWithNullableShortReturn(notNull));
}
@Override
public void methodWithNullableShortHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Short>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableShortReturn(notNull)));
}
@Override
public @Nullable Short methodWithNullableShortReturn(boolean notNull) {
return notNull ? (short)1024 : null;
}
@Override
public boolean methodWithNonNullableIntegerParam(Integer param) {
return param == null;
}
@Override
public void methodWithNullableIntegerParam(boolean expectNull, Integer param) {
assertEquals(methodWithNullableIntegerReturn(!expectNull), param);
}
@Override
public void methodWithNullableIntegerHandler(boolean notNull, Handler<@Nullable Integer> handler) {
handler.handle(methodWithNullableIntegerReturn(notNull));
}
@Override
public void methodWithNullableIntegerHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Integer>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableIntegerReturn(notNull)));
}
@Override
public @Nullable Integer methodWithNullableIntegerReturn(boolean notNull) {
return notNull ? 1234567 : null;
}
@Override
public boolean methodWithNonNullableLongParam(Long param) {
return param == null;
}
@Override
public void methodWithNullableLongParam(boolean expectNull, Long param) {
assertEquals(methodWithNullableLongReturn(!expectNull), param);
}
@Override
public void methodWithNullableLongHandler(boolean notNull, Handler<@Nullable Long> handler) {
handler.handle(methodWithNullableLongReturn(notNull));
}
@Override
public void methodWithNullableLongHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Long>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableLongReturn(notNull)));
}
@Override
public @Nullable Long methodWithNullableLongReturn(boolean notNull) {
return notNull ? 9876543210L : null;
}
@Override
public boolean methodWithNonNullableFloatParam(Float param) {
return param == null;
}
@Override
public void methodWithNullableFloatParam(boolean expectNull, Float param) {
assertEquals(methodWithNullableFloatReturn(!expectNull), param);
}
@Override
public void methodWithNullableFloatHandler(boolean notNull, Handler<@Nullable Float> handler) {
handler.handle(methodWithNullableFloatReturn(notNull));
}
@Override
public void methodWithNullableFloatHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Float>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableFloatReturn(notNull)));
}
@Override
public @Nullable Float methodWithNullableFloatReturn(boolean notNull) {
return notNull ? 3.14f : null;
}
@Override
public boolean methodWithNonNullableDoubleParam(Double param) {
return param == null;
}
@Override
public void methodWithNullableDoubleParam(boolean expectNull, Double param) {
assertEquals(methodWithNullableDoubleReturn(!expectNull), param);
}
@Override
public void methodWithNullableDoubleHandler(boolean notNull, Handler<@Nullable Double> handler) {
handler.handle(methodWithNullableDoubleReturn(notNull));
}
@Override
public void methodWithNullableDoubleHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Double>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableDoubleReturn(notNull)));
}
@Override
public @Nullable Double methodWithNullableDoubleReturn(boolean notNull) {
return notNull ? 3.1415926D : null;
}
@Override
public boolean methodWithNonNullableBooleanParam(Boolean param) {
return param == null;
}
@Override
public void methodWithNullableBooleanParam(boolean expectNull, Boolean param) {
assertEquals(methodWithNullableBooleanReturn(!expectNull), param);
}
@Override
public void methodWithNullableBooleanHandler(boolean notNull, Handler<@Nullable Boolean> handler) {
handler.handle(methodWithNullableBooleanReturn(notNull));
}
@Override
public void methodWithNullableBooleanHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Boolean>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableBooleanReturn(notNull)));
}
@Override
public @Nullable Boolean methodWithNullableBooleanReturn(boolean notNull) {
return notNull ? true : null;
}
@Override
public boolean methodWithNonNullableStringParam(String param) {
return param == null;
}
@Override
public void methodWithNullableStringParam(boolean expectNull, @Nullable String param) {
assertEquals(methodWithNullableStringReturn(!expectNull), param);
}
@Override
public void methodWithNullableStringHandler(boolean notNull, Handler<@Nullable String> handler) {
handler.handle(methodWithNullableStringReturn(notNull));
}
@Override
public void methodWithNullableStringHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable String>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableStringReturn(notNull)));
}
@Override
public @Nullable String methodWithNullableStringReturn(boolean notNull) {
return notNull ? "the_string_value" : null;
}
@Override
public boolean methodWithNonNullableCharParam(Character param) {
return param == null;
}
@Override
public void methodWithNullableCharParam(boolean expectNull, Character param) {
assertEquals(methodWithNullableCharReturn(!expectNull), param);
}
@Override
public void methodWithNullableCharHandler(boolean notNull, Handler<@Nullable Character> handler) {
handler.handle(methodWithNullableCharReturn(notNull));
}
@Override
public void methodWithNullableCharHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Character>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableCharReturn(notNull)));
}
@Override
public @Nullable Character methodWithNullableCharReturn(boolean notNull) {
return notNull ? 'f' : null;
}
@Override
public boolean methodWithNonNullableJsonObjectParam(JsonObject param) {
return param == null;
}
@Override
public void methodWithNullableJsonObjectParam(boolean expectNull, JsonObject param) {
assertEquals(methodWithNullableJsonObjectReturn(!expectNull), param);
}
@Override
public void methodWithNullableJsonObjectHandler(boolean notNull, Handler<@Nullable JsonObject> handler) {
handler.handle(methodWithNullableJsonObjectReturn(notNull));
}
@Override
public void methodWithNullableJsonObjectHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable JsonObject>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableJsonObjectReturn(notNull)));
}
@Override
public @Nullable JsonObject methodWithNullableJsonObjectReturn(boolean notNull) {
if (notNull) {
return new JsonObject().put("foo", "wibble").put("bar", 3);
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableJsonArrayParam(JsonArray param) {
return param == null;
}
@Override
public void methodWithNullableJsonArrayParam(boolean expectNull, JsonArray param) {
assertEquals(methodWithNullableJsonArrayReturn(!expectNull), param);
}
@Override
public void methodWithNullableJsonArrayHandler(boolean notNull, Handler<@Nullable JsonArray> handler) {
handler.handle(methodWithNullableJsonArrayReturn(notNull));
}
@Override
public void methodWithNullableJsonArrayHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable JsonArray>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableJsonArrayReturn(notNull)));
}
@Override
public @Nullable JsonArray methodWithNullableJsonArrayReturn(boolean notNull) {
return notNull ? new JsonArray().add("one").add("two").add("three") : null;
}
@Override
public boolean methodWithNonNullableApiParam(RefedInterface1 param) {
return param == null;
}
@Override
public void methodWithNullableApiParam(boolean expectNull, RefedInterface1 param) {
assertEquals(methodWithNullableApiReturn(!expectNull), param);
}
@Override
public void methodWithNullableApiHandler(boolean notNull, Handler<RefedInterface1> handler) {
handler.handle(methodWithNullableApiReturn(notNull));
}
@Override
public void methodWithNullableApiHandlerAsyncResult(boolean notNull, Handler<AsyncResult<RefedInterface1>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableApiReturn(notNull)));
}
@Override
public @Nullable RefedInterface1 methodWithNullableApiReturn(boolean notNull) {
return notNull ? new RefedInterface1Impl().setString("lovely_dae") : null;
}
@Override
public boolean methodWithNonNullableDataObjectParam(TestDataObject param) {
return param == null;
}
@Override
public void methodWithNullableDataObjectParam(boolean expectNull, TestDataObject param) {
if (expectNull) {
assertNull(param);
} else {
assertEquals(methodWithNullableDataObjectReturn(true).toJson(), param.toJson());
}
}
@Override
public void methodWithNullableDataObjectHandler(boolean notNull, Handler<TestDataObject> handler) {
handler.handle(methodWithNullableDataObjectReturn(notNull));
}
@Override
public void methodWithNullableDataObjectHandlerAsyncResult(boolean notNull, Handler<AsyncResult<TestDataObject>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableDataObjectReturn(notNull)));
}
@Override
public @Nullable TestDataObject methodWithNullableDataObjectReturn(boolean notNull) {
return notNull ? new TestDataObject().setFoo("foo_value").setBar(12345).setWibble(3.5) : null;
}
@Override
public boolean methodWithNonNullableEnumParam(TestEnum param) {
return param == null;
}
@Override
public void methodWithNullableEnumParam(boolean expectNull, TestEnum param) {
assertEquals(methodWithNullableEnumReturn(!expectNull), param);
}
@Override
public void methodWithNullableEnumHandler(boolean notNull, Handler<TestEnum> handler) {
handler.handle(methodWithNullableEnumReturn(notNull));
}
@Override
public void methodWithNullableEnumHandlerAsyncResult(boolean notNull, Handler<AsyncResult<TestEnum>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableEnumReturn(notNull)));
}
@Override
public @Nullable TestEnum methodWithNullableEnumReturn(boolean notNull) {
return notNull ? TestEnum.TIM : null;
}
@Override
public <T> void methodWithNullableTypeVariableParam(boolean expectNull, T param) {
if (expectNull) {
assertNull(param);
} else {
assertNotNull(param);
}
}
@Override
public <T> void methodWithNullableTypeVariableHandler(boolean notNull, T value, Handler<T> handler) {
if (notNull) {
handler.handle(value);
} else {
handler.handle(null);
}
}
@Override
public <T> void methodWithNullableTypeVariableHandlerAsyncResult(boolean notNull, T value, Handler<AsyncResult<T>> handler) {
if (notNull) {
handler.handle(Future.succeededFuture(value));
} else {
handler.handle(Future.succeededFuture(null));
}
}
@Override
public <T> T methodWithNullableTypeVariableReturn(boolean notNull, T value) {
return notNull ? value : null;
}
@Override
public boolean methodWithNonNullableListByteParam(List<Byte> param) {
return param == null;
}
@Override
public void methodWithNullableListByteParam(boolean expectNull, List<Byte> param) {
assertEquals(methodWithNullableListByteReturn(!expectNull), param);
}
@Override
public void methodWithNullableListByteHandler(boolean notNull, Handler<@Nullable List<Byte>> handler) {
handler.handle(methodWithNullableListByteReturn(notNull));
}
@Override
public void methodWithNullableListByteHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<Byte>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListByteReturn(notNull)));
}
@Override
public @Nullable List<Byte> methodWithNullableListByteReturn(boolean notNull) {
if (notNull) {
return Arrays.asList((byte)1, (byte)2, (byte)3);
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableListShortParam(List<Short> param) {
return param == null;
}
@Override
public void methodWithNullableListShortParam(boolean expectNull, List<Short> param) {
assertEquals(methodWithNullableListShortReturn(!expectNull), param);
}
@Override
public void methodWithNullableListShortHandler(boolean notNull, Handler<@Nullable List<Short>> handler) {
handler.handle(methodWithNullableListShortReturn(notNull));
}
@Override
public void methodWithNullableListShortHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<Short>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListShortReturn(notNull)));
}
@Override
public @Nullable List<Short> methodWithNullableListShortReturn(boolean notNull) {
if (notNull) {
return Arrays.asList((short)1, (short)2, (short)3);
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableListIntegerParam(List<Integer> param) {
return param == null;
}
@Override
public void methodWithNullableListIntegerParam(boolean expectNull, List<Integer> param) {
assertEquals(methodWithNullableListIntegerReturn(!expectNull), param);
}
@Override
public void methodWithNullableListIntegerHandler(boolean notNull, Handler<@Nullable List<Integer>> handler) {
handler.handle(methodWithNullableListIntegerReturn(notNull));
}
@Override
public void methodWithNullableListIntegerHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<Integer>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListIntegerReturn(notNull)));
}
@Override
public @Nullable List<Integer> methodWithNullableListIntegerReturn(boolean notNull) {
if (notNull) {
return Arrays.asList(1, 2, 3);
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableListLongParam(List<Long> param) {
return param == null;
}
@Override
public void methodWithNullableListLongParam(boolean expectNull, List<Long> param) {
assertEquals(methodWithNullableListLongReturn(!expectNull), param);
}
@Override
public void methodWithNullableListLongHandler(boolean notNull, Handler<@Nullable List<Long>> handler) {
handler.handle(methodWithNullableListLongReturn(notNull));
}
@Override
public void methodWithNullableListLongHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<Long>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListLongReturn(notNull)));
}
@Override
public @Nullable List<Long> methodWithNullableListLongReturn(boolean notNull) {
if (notNull) {
return Arrays.asList(1L, 2L, 3L);
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableListFloatParam(List<Float> param) {
return param == null;
}
@Override
public void methodWithNullableListFloatParam(boolean expectNull, List<Float> param) {
assertEquals(methodWithNullableListFloatReturn(!expectNull), param);
}
@Override
public void methodWithNullableListFloatHandler(boolean notNull, Handler<@Nullable List<Float>> handler) {
handler.handle(methodWithNullableListFloatReturn(notNull));
}
@Override
public void methodWithNullableListFloatHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<Float>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListFloatReturn(notNull)));
}
@Override
public @Nullable List<Float> methodWithNullableListFloatReturn(boolean notNull) {
if (notNull) {
return Arrays.asList(1.1f, 2.2f, 3.3f);
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableListDoubleParam(List<Double> param) {
return param == null;
}
@Override
public void methodWithNullableListDoubleParam(boolean expectNull, List<Double> param) {
assertEquals(methodWithNullableListDoubleReturn(!expectNull), param);
}
@Override
public void methodWithNullableListDoubleHandler(boolean notNull, Handler<@Nullable List<Double>> handler) {
handler.handle(methodWithNullableListDoubleReturn(notNull));
}
@Override
public void methodWithNullableListDoubleHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<Double>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListDoubleReturn(notNull)));
}
@Override
public @Nullable List<Double> methodWithNullableListDoubleReturn(boolean notNull) {
if (notNull) {
return Arrays.asList(1.11d, 2.22d, 3.33d);
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableListBooleanParam(List<Boolean> param) {
return param == null;
}
@Override
public void methodWithNullableListBooleanParam(boolean expectNull, List<Boolean> param) {
assertEquals(methodWithNullableListBooleanReturn(!expectNull), param);
}
@Override
public void methodWithNullableListBooleanHandler(boolean notNull, Handler<@Nullable List<Boolean>> handler) {
handler.handle(methodWithNullableListBooleanReturn(notNull));
}
@Override
public void methodWithNullableListBooleanHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<Boolean>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListBooleanReturn(notNull)));
}
@Override
public @Nullable List<Boolean> methodWithNullableListBooleanReturn(boolean notNull) {
if (notNull) {
return Arrays.asList(true, false, true);
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableListStringParam(List<String> param) {
return param == null;
}
@Override
public void methodWithNullableListStringParam(boolean expectNull, List<String> param) {
assertEquals(methodWithNullableListStringReturn(!expectNull), param);
}
@Override
public void methodWithNullableListStringHandler(boolean notNull, Handler<@Nullable List<String>> handler) {
handler.handle(methodWithNullableListStringReturn(notNull));
}
@Override
public void methodWithNullableListStringHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<String>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListStringReturn(notNull)));
}
@Override
public @Nullable List<String> methodWithNullableListStringReturn(boolean notNull) {
if (notNull) {
return Arrays.asList("first", "second", "third");
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableListCharParam(List<Character> param) {
return param == null;
}
@Override
public void methodWithNullableListCharParam(boolean expectNull, List<Character> param) {
assertEquals(methodWithNullableListCharReturn(!expectNull), param);
}
@Override
public void methodWithNullableListCharHandler(boolean notNull, Handler<@Nullable List<Character>> handler) {
handler.handle(methodWithNullableListCharReturn(notNull));
}
@Override
public void methodWithNullableListCharHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<Character>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListCharReturn(notNull)));
}
@Override
public @Nullable List<Character> methodWithNullableListCharReturn(boolean notNull) {
if (notNull) {
return Arrays.asList('x', 'y', 'z');
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableListJsonObjectParam(List<JsonObject> param) {
return param == null;
}
@Override
public void methodWithNullableListJsonObjectParam(boolean expectNull, List<JsonObject> param) {
assertEquals(methodWithNullableListJsonObjectReturn(!expectNull), param);
}
@Override
public void methodWithNullableListJsonObjectHandler(boolean notNull, Handler<@Nullable List<JsonObject>> handler) {
handler.handle(methodWithNullableListJsonObjectReturn(notNull));
}
@Override
public void methodWithNullableListJsonObjectHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<JsonObject>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListJsonObjectReturn(notNull)));
}
@Override
public @Nullable List<JsonObject> methodWithNullableListJsonObjectReturn(boolean notNull) {
if (notNull) {
return Arrays.asList(new JsonObject().put("foo", "bar"), new JsonObject().put("juu", 3));
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableListJsonArrayParam(List<JsonArray> param) {
return param == null;
}
@Override
public void methodWithNullableListJsonArrayParam(boolean expectNull, List<JsonArray> param) {
assertEquals(methodWithNullableListJsonArrayReturn(!expectNull), param);
}
@Override
public void methodWithNullableListJsonArrayHandler(boolean notNull, Handler<@Nullable List<JsonArray>> handler) {
handler.handle(methodWithNullableListJsonArrayReturn(notNull));
}
@Override
public void methodWithNullableListJsonArrayHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<JsonArray>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListJsonArrayReturn(notNull)));
}
@Override
public @Nullable List<JsonArray> methodWithNullableListJsonArrayReturn(boolean notNull) {
if (notNull) {
return Arrays.asList(new JsonArray().add("foo").add("bar"), new JsonArray().add("juu"));
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableListApiParam(List<RefedInterface1> param) {
return param == null;
}
@Override
public void methodWithNullableListApiParam(boolean expectNull, List<RefedInterface1> param) {
assertEquals(methodWithNullableListApiReturn(!expectNull), param);
}
@Override
public void methodWithNullableListApiHandler(boolean notNull, Handler<@Nullable List<RefedInterface1>> handler) {
handler.handle(methodWithNullableListApiReturn(notNull));
}
@Override
public void methodWithNullableListApiHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<RefedInterface1>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListApiReturn(notNull)));
}
@Override
public @Nullable List<RefedInterface1> methodWithNullableListApiReturn(boolean notNull) {
return notNull ? Arrays.asList(new RefedInterface1Impl().setString("refed_is_here")) : null;
}
@Override
public boolean methodWithNonNullableListDataObjectParam(List<TestDataObject> param) {
return param == null;
}
@Override
public void methodWithNullableListDataObjectParam(boolean expectNull, List<TestDataObject> param) {
if (expectNull) {
assertEquals(null, param);
} else {
assertEquals(methodWithNullableListDataObjectReturn(true).stream().map(TestDataObject::toJson).collect(Collectors.toList()), param.stream().map(TestDataObject::toJson).collect(Collectors.toList()));
}
}
@Override
public void methodWithNullableListDataObjectHandler(boolean notNull, Handler<@Nullable List<TestDataObject>> handler) {
handler.handle(methodWithNullableListDataObjectReturn(notNull));
}
@Override
public void methodWithNullableListDataObjectHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<TestDataObject>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListDataObjectReturn(notNull)));
}
@Override
public @Nullable List<TestDataObject> methodWithNullableListDataObjectReturn(boolean notNull) {
return notNull ? Arrays.asList(new TestDataObject().setFoo("foo_value").setBar(12345).setWibble(5.6)) : null;
}
@Override
public boolean methodWithNonNullableListEnumParam(List<TestEnum> param) {
return param == null;
}
@Override
public void methodWithNullableListEnumParam(boolean expectNull, List<TestEnum> param) {
assertEquals(methodWithNullableListEnumReturn(!expectNull), param);
}
@Override
public void methodWithNullableListEnumHandler(boolean notNull, Handler<@Nullable List<TestEnum>> handler) {
handler.handle(methodWithNullableListEnumReturn(notNull));
}
@Override
public void methodWithNullableListEnumHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable List<TestEnum>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableListEnumReturn(notNull)));
}
@Override
public @Nullable List<TestEnum> methodWithNullableListEnumReturn(boolean notNull) {
return notNull ? Arrays.asList(TestEnum.TIM,TestEnum.JULIEN) : null;
}
@Override
public boolean methodWithNonNullableSetByteParam(Set<Byte> param) {
return param == null;
}
@Override
public void methodWithNullableSetByteParam(boolean expectNull, Set<Byte> param) {
assertEquals(methodWithNullableSetByteReturn(!expectNull), param);
}
@Override
public void methodWithNullableSetByteHandler(boolean notNull, Handler<@Nullable Set<Byte>> handler) {
handler.handle(methodWithNullableSetByteReturn(notNull));
}
@Override
public void methodWithNullableSetByteHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<Byte>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetByteReturn(notNull)));
}
@Override
public @Nullable Set<Byte> methodWithNullableSetByteReturn(boolean notNull) {
if (notNull) {
return new LinkedHashSet<>(Arrays.asList((byte)1, (byte)2, (byte)3));
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableSetShortParam(Set<Short> param) {
return param == null;
}
@Override
public void methodWithNullableSetShortParam(boolean expectNull, Set<Short> param) {
assertEquals(methodWithNullableSetShortReturn(!expectNull), param);
}
@Override
public void methodWithNullableSetShortHandler(boolean notNull, Handler<@Nullable Set<Short>> handler) {
handler.handle(methodWithNullableSetShortReturn(notNull));
}
@Override
public void methodWithNullableSetShortHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<Short>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetShortReturn(notNull)));
}
@Override
public @Nullable Set<Short> methodWithNullableSetShortReturn(boolean notNull) {
if (notNull) {
return new LinkedHashSet<>(Arrays.asList((short)1, (short)2, (short)3));
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableSetIntegerParam(Set<Integer> param) {
return param == null;
}
@Override
public void methodWithNullableSetIntegerParam(boolean expectNull, Set<Integer> param) {
assertEquals(methodWithNullableSetIntegerReturn(!expectNull), param);
}
@Override
public void methodWithNullableSetIntegerHandler(boolean notNull, Handler<@Nullable Set<Integer>> handler) {
handler.handle(methodWithNullableSetIntegerReturn(notNull));
}
@Override
public void methodWithNullableSetIntegerHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<Integer>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetIntegerReturn(notNull)));
}
@Override
public @Nullable Set<Integer> methodWithNullableSetIntegerReturn(boolean notNull) {
if (notNull) {
return new LinkedHashSet<>(Arrays.asList(1, 2, 3));
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableSetLongParam(Set<Long> param) {
return param == null;
}
@Override
public void methodWithNullableSetLongParam(boolean expectNull, Set<Long> param) {
assertEquals(methodWithNullableSetLongReturn(!expectNull), param);
}
@Override
public void methodWithNullableSetLongHandler(boolean notNull, Handler<@Nullable Set<Long>> handler) {
handler.handle(methodWithNullableSetLongReturn(notNull));
}
@Override
public void methodWithNullableSetLongHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<Long>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetLongReturn(notNull)));
}
@Override
public @Nullable Set<Long> methodWithNullableSetLongReturn(boolean notNull) {
if (notNull) {
return new LinkedHashSet<>(Arrays.asList(1L, 2L, 3L));
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableSetFloatParam(Set<Float> param) {
return param == null;
}
@Override
public void methodWithNullableSetFloatParam(boolean expectNull, Set<Float> param) {
assertEquals(methodWithNullableSetFloatReturn(!expectNull), param);
}
@Override
public void methodWithNullableSetFloatHandler(boolean notNull, Handler<@Nullable Set<Float>> handler) {
handler.handle(methodWithNullableSetFloatReturn(notNull));
}
@Override
public void methodWithNullableSetFloatHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<Float>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetFloatReturn(notNull)));
}
@Override
public @Nullable Set<Float> methodWithNullableSetFloatReturn(boolean notNull) {
if (notNull) {
return new LinkedHashSet<>(Arrays.asList(1.1f, 2.2f, 3.3f));
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableSetDoubleParam(Set<Double> param) {
return param == null;
}
@Override
public void methodWithNullableSetDoubleParam(boolean expectNull, Set<Double> param) {
assertEquals(methodWithNullableSetDoubleReturn(!expectNull), param);
}
@Override
public void methodWithNullableSetDoubleHandler(boolean notNull, Handler<@Nullable Set<Double>> handler) {
handler.handle(methodWithNullableSetDoubleReturn(notNull));
}
@Override
public void methodWithNullableSetDoubleHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<Double>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetDoubleReturn(notNull)));
}
@Override
public @Nullable Set<Double> methodWithNullableSetDoubleReturn(boolean notNull) {
if (notNull) {
return new LinkedHashSet<>(Arrays.asList(1.11d, 2.22d, 3.33d));
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableSetBooleanParam(Set<Boolean> param) {
return param == null;
}
@Override
public void methodWithNullableSetBooleanParam(boolean expectNull, Set<Boolean> param) {
assertEquals(methodWithNullableSetBooleanReturn(!expectNull), param);
}
@Override
public void methodWithNullableSetBooleanHandler(boolean notNull, Handler<@Nullable Set<Boolean>> handler) {
handler.handle(methodWithNullableSetBooleanReturn(notNull));
}
@Override
public void methodWithNullableSetBooleanHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<Boolean>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetBooleanReturn(notNull)));
}
@Override
public @Nullable Set<Boolean> methodWithNullableSetBooleanReturn(boolean notNull) {
if (notNull) {
return new LinkedHashSet<>(Arrays.asList(true, false));
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableSetStringParam(Set<String> param) {
return param == null;
}
@Override
public void methodWithNullableSetStringParam(boolean expectNull, Set<String> param) {
assertEquals(methodWithNullableSetStringReturn(!expectNull), param);
}
@Override
public void methodWithNullableSetStringHandler(boolean notNull, Handler<@Nullable Set<String>> handler) {
handler.handle(methodWithNullableSetStringReturn(notNull));
}
@Override
public void methodWithNullableSetStringHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<String>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetStringReturn(notNull)));
}
@Override
public @Nullable Set<String> methodWithNullableSetStringReturn(boolean notNull) {
if (notNull) {
return new LinkedHashSet<>(Arrays.asList("first", "second", "third"));
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableSetCharParam(Set<Character> param) {
return param == null;
}
@Override
public void methodWithNullableSetCharParam(boolean expectNull, Set<Character> param) {
assertEquals(methodWithNullableSetCharReturn(!expectNull), param);
}
@Override
public void methodWithNullableSetCharHandler(boolean notNull, Handler<@Nullable Set<Character>> handler) {
handler.handle(methodWithNullableSetCharReturn(notNull));
}
@Override
public void methodWithNullableSetCharHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<Character>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetCharReturn(notNull)));
}
@Override
public @Nullable Set<Character> methodWithNullableSetCharReturn(boolean notNull) {
if (notNull) {
return new LinkedHashSet<>(Arrays.asList('x', 'y', 'z'));
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableSetJsonObjectParam(Set<JsonObject> param) {
return param == null;
}
@Override
public void methodWithNullableSetJsonObjectParam(boolean expectNull, Set<JsonObject> param) {
assertEquals(methodWithNullableSetJsonObjectReturn(!expectNull), param);
}
@Override
public void methodWithNullableSetJsonObjectHandler(boolean notNull, Handler<@Nullable Set<JsonObject>> handler) {
handler.handle(methodWithNullableSetJsonObjectReturn(notNull));
}
@Override
public void methodWithNullableSetJsonObjectHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<JsonObject>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetJsonObjectReturn(notNull)));
}
@Override
public @Nullable Set<JsonObject> methodWithNullableSetJsonObjectReturn(boolean notNull) {
if (notNull) {
return new LinkedHashSet<>(Arrays.asList(new JsonObject().put("foo", "bar"), new JsonObject().put("juu", 3)));
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableSetJsonArrayParam(Set<JsonArray> param) {
return param == null;
}
@Override
public void methodWithNullableSetJsonArrayParam(boolean expectNull, Set<JsonArray> param) {
assertEquals(methodWithNullableSetJsonArrayReturn(!expectNull), param);
}
@Override
public void methodWithNullableSetJsonArrayHandler(boolean notNull, Handler<@Nullable Set<JsonArray>> handler) {
handler.handle(methodWithNullableSetJsonArrayReturn(notNull));
}
@Override
public void methodWithNullableSetJsonArrayHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<JsonArray>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetJsonArrayReturn(notNull)));
}
@Override
public @Nullable Set<JsonArray> methodWithNullableSetJsonArrayReturn(boolean notNull) {
if (notNull) {
return new LinkedHashSet<>(Arrays.asList(new JsonArray().add("foo").add("bar"), new JsonArray().add("juu")));
} else {
return null;
}
}
@Override
public boolean methodWithNonNullableSetApiParam(Set<RefedInterface1> param) {
return param == null;
}
@Override
public void methodWithNullableSetApiParam(boolean expectNull, Set<RefedInterface1> param) {
assertEquals(methodWithNullableSetApiReturn(!expectNull), param);
}
@Override
public void methodWithNullableSetApiHandler(boolean notNull, Handler<@Nullable Set<RefedInterface1>> handler) {
handler.handle(methodWithNullableSetApiReturn(notNull));
}
@Override
public void methodWithNullableSetApiHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<RefedInterface1>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetApiReturn(notNull)));
}
@Override
public @Nullable Set<RefedInterface1> methodWithNullableSetApiReturn(boolean notNull) {
return notNull ? new LinkedHashSet<>(Arrays.asList(new RefedInterface1Impl().setString("refed_is_here"))) : null;
}
@Override
public boolean methodWithNonNullableSetDataObjectParam(Set<TestDataObject> param) {
return param == null;
}
@Override
public void methodWithNullableSetDataObjectParam(boolean expectNull, Set<TestDataObject> param) {
if (expectNull) {
assertEquals(null, param);
} else {
assertEquals(methodWithNullableSetDataObjectReturn(true).stream().map(TestDataObject::toJson).collect(Collectors.toSet()), param.stream().map(TestDataObject::toJson).collect(Collectors.toSet()));
}
}
@Override
public void methodWithNullableSetDataObjectHandler(boolean notNull, Handler<@Nullable Set<TestDataObject>> handler) {
handler.handle(methodWithNullableSetDataObjectReturn(notNull));
}
@Override
public void methodWithNullableSetDataObjectHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<TestDataObject>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetDataObjectReturn(notNull)));
}
@Override
public @Nullable Set<TestDataObject> methodWithNullableSetDataObjectReturn(boolean notNull) {
return notNull ? new LinkedHashSet<>(Arrays.asList(new TestDataObject().setFoo("foo_value").setBar(12345).setWibble(5.6))) : null;
}
@Override
public boolean methodWithNonNullableSetEnumParam(Set<TestEnum> param) {
return param == null;
}
@Override
public void methodWithNullableSetEnumParam(boolean expectNull, Set<TestEnum> param) {
assertEquals(methodWithNullableSetEnumReturn(!expectNull), param);
}
@Override
public void methodWithNullableSetEnumHandler(boolean notNull, Handler<@Nullable Set<TestEnum>> handler) {
handler.handle(methodWithNullableSetEnumReturn(notNull));
}
@Override
public void methodWithNullableSetEnumHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Set<TestEnum>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableSetEnumReturn(notNull)));
}
@Override
public @Nullable Set<TestEnum> methodWithNullableSetEnumReturn(boolean notNull) {
return notNull ? new LinkedHashSet<>(Arrays.asList(TestEnum.TIM,TestEnum.JULIEN)) : null;
}
@Override
public boolean methodWithNonNullableMapStringParam(Map<String, String> param) {
return param == null;
}
@Override
public void methodWithNullableMapStringParam(boolean expectNull, Map<String, String> param) {
assertEquals(methodWithNullableMapStringReturn(!expectNull), param);
}
@Override
public void methodWithNullableMapStringHandler(boolean notNull, Handler<@Nullable Map<String, String>> handler) {
handler.handle(methodWithNullableMapStringReturn(notNull));
}
@Override
public void methodWithNullableMapStringHandlerAsyncResult(boolean notNull, Handler<AsyncResult<@Nullable Map<String, String>>> handler) {
handler.handle(Future.succeededFuture(methodWithNullableMapStringReturn(notNull)));
}
@Override
public @Nullable Map<String, String> methodWithNullableMapStringReturn(boolean notNull) {
if (notNull) {
Map<String, String> map = new LinkedHashMap<>();
map.put("1", "first");
map.put("2", "second");
map.put("3", "third");
return map;
} else {
return null;
}
}
@Override
public void methodWithListNullableByteParam(List<@Nullable Byte> param) {
assertEquals(param, methodWithListNullableByteReturn());
}
@Override
public void methodWithListNullableByteHandler(Handler<List<@Nullable Byte>> handler) {
handler.handle(methodWithListNullableByteReturn());
}
@Override
public void methodWithListNullableByteHandlerAsyncResult(Handler<AsyncResult<List<@Nullable Byte>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableByteReturn()));
}
@Override
public List<@Nullable Byte> methodWithListNullableByteReturn() {
ArrayList<Byte> ret = new ArrayList<>();
ret.add((byte)12);
ret.add(null);
ret.add((byte)24);
return ret;
}
@Override
public void methodWithListNullableShortParam(List<@Nullable Short> param) {
assertEquals(param, methodWithListNullableShortReturn());
}
@Override
public void methodWithListNullableShortHandler(Handler<List<@Nullable Short>> handler) {
handler.handle(methodWithListNullableShortReturn());
}
@Override
public void methodWithListNullableShortHandlerAsyncResult(Handler<AsyncResult<List<@Nullable Short>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableShortReturn()));
}
@Override
public List<@Nullable Short> methodWithListNullableShortReturn() {
ArrayList<Short> ret = new ArrayList<>();
ret.add((short)520);
ret.add(null);
ret.add((short)1040);
return ret;
}
@Override
public void methodWithListNullableIntegerParam(List<@Nullable Integer> param) {
assertEquals(param, methodWithListNullableIntegerReturn());
}
@Override
public void methodWithListNullableIntegerHandler(Handler<List<@Nullable Integer>> handler) {
handler.handle(methodWithListNullableIntegerReturn());
}
@Override
public void methodWithListNullableIntegerHandlerAsyncResult(Handler<AsyncResult<List<@Nullable Integer>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableIntegerReturn()));
}
@Override
public List<@Nullable Integer> methodWithListNullableIntegerReturn() {
ArrayList<Integer> ret = new ArrayList<>();
ret.add(12345);
ret.add(null);
ret.add(54321);
return ret;
}
@Override
public void methodWithListNullableLongParam(List<@Nullable Long> param) {
assertEquals(param, methodWithListNullableLongReturn());
}
@Override
public void methodWithListNullableLongHandler(Handler<List<@Nullable Long>> handler) {
handler.handle(methodWithListNullableLongReturn());
}
@Override
public void methodWithListNullableLongHandlerAsyncResult(Handler<AsyncResult<List<@Nullable Long>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableLongReturn()));
}
@Override
public List<@Nullable Long> methodWithListNullableLongReturn() {
ArrayList<Long> ret = new ArrayList<>();
ret.add(123456789L);
ret.add(null);
ret.add(987654321L);
return ret;
}
@Override
public void methodWithListNullableFloatParam(List<@Nullable Float> param) {
assertEquals(param, methodWithListNullableFloatReturn());
}
@Override
public void methodWithListNullableFloatHandler(Handler<List<@Nullable Float>> handler) {
handler.handle(methodWithListNullableFloatReturn());
}
@Override
public void methodWithListNullableFloatHandlerAsyncResult(Handler<AsyncResult<List<@Nullable Float>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableFloatReturn()));
}
@Override
public List<@Nullable Float> methodWithListNullableFloatReturn() {
ArrayList<Float> ret = new ArrayList<>();
ret.add(1.1f);
ret.add(null);
ret.add(3.3f);
return ret;
}
@Override
public void methodWithListNullableDoubleParam(List<@Nullable Double> param) {
assertEquals(param, methodWithListNullableDoubleReturn());
}
@Override
public void methodWithListNullableDoubleHandler(Handler<List<@Nullable Double>> handler) {
handler.handle(methodWithListNullableDoubleReturn());
}
@Override
public void methodWithListNullableDoubleHandlerAsyncResult(Handler<AsyncResult<List<@Nullable Double>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableDoubleReturn()));
}
@Override
public List<@Nullable Double> methodWithListNullableDoubleReturn() {
ArrayList<Double> ret = new ArrayList<>();
ret.add(1.11);
ret.add(null);
ret.add(3.33);
return ret;
}
@Override
public void methodWithListNullableBooleanParam(List<@Nullable Boolean> param) {
assertEquals(param, methodWithListNullableBooleanReturn());
}
@Override
public void methodWithListNullableBooleanHandler(Handler<List<@Nullable Boolean>> handler) {
handler.handle(methodWithListNullableBooleanReturn());
}
@Override
public void methodWithListNullableBooleanHandlerAsyncResult(Handler<AsyncResult<List<@Nullable Boolean>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableBooleanReturn()));
}
@Override
public List<@Nullable Boolean> methodWithListNullableBooleanReturn() {
ArrayList<Boolean> ret = new ArrayList<>();
ret.add(true);
ret.add(null);
ret.add(false);
return ret;
}
@Override
public void methodWithListNullableCharParam(List<@Nullable Character> param) {
assertEquals(param, methodWithListNullableCharReturn());
}
@Override
public void methodWithListNullableCharHandler(Handler<List<@Nullable Character>> handler) {
handler.handle(methodWithListNullableCharReturn());
}
@Override
public void methodWithListNullableCharHandlerAsyncResult(Handler<AsyncResult<List<@Nullable Character>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableCharReturn()));
}
@Override
public List<@Nullable Character> methodWithListNullableCharReturn() {
ArrayList<Character> ret = new ArrayList<>();
ret.add('F');
ret.add(null);
ret.add('R');
return ret;
}
@Override
public void methodWithListNullableStringParam(List<@Nullable String> param) {
assertEquals(param, methodWithListNullableStringReturn());
}
@Override
public void methodWithListNullableStringHandler(Handler<List<@Nullable String>> handler) {
handler.handle(methodWithListNullableStringReturn());
}
@Override
public void methodWithListNullableStringHandlerAsyncResult(Handler<AsyncResult<List<@Nullable String>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableStringReturn()));
}
@Override
public List<@Nullable String> methodWithListNullableStringReturn() {
ArrayList<String> ret = new ArrayList<>();
ret.add("first");
ret.add(null);
ret.add("third");
return ret;
}
@Override
public void methodWithListNullableJsonObjectParam(List<@Nullable JsonObject> param) {
assertEquals(param, methodWithListNullableJsonObjectReturn());
}
@Override
public void methodWithListNullableJsonObjectHandler(Handler<List<@Nullable JsonObject>> handler) {
handler.handle(methodWithListNullableJsonObjectReturn());
}
@Override
public void methodWithListNullableJsonObjectHandlerAsyncResult(Handler<AsyncResult<List<@Nullable JsonObject>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableJsonObjectReturn()));
}
@Override
public List<@Nullable JsonObject> methodWithListNullableJsonObjectReturn() {
ArrayList<JsonObject> ret = new ArrayList<>();
ret.add(new JsonObject().put("foo", "bar"));
ret.add(null);
ret.add(new JsonObject().put("juu", 3));
return ret;
}
@Override
public void methodWithListNullableJsonArrayParam(List<@Nullable JsonArray> param) {
assertEquals(param, methodWithListNullableJsonArrayReturn());
}
@Override
public void methodWithListNullableJsonArrayHandler(Handler<List<@Nullable JsonArray>> handler) {
handler.handle(methodWithListNullableJsonArrayReturn());
}
@Override
public void methodWithListNullableJsonArrayHandlerAsyncResult(Handler<AsyncResult<List<@Nullable JsonArray>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableJsonArrayReturn()));
}
@Override
public List<@Nullable JsonArray> methodWithListNullableJsonArrayReturn() {
ArrayList<JsonArray> ret = new ArrayList<>();
ret.add(new JsonArray().add("foo").add("bar"));
ret.add(null);
ret.add(new JsonArray().add("juu"));
return ret;
}
@Override
public void methodWithListNullableApiParam(List<@Nullable RefedInterface1> param) {
assertEquals(param, methodWithListNullableApiReturn());
}
@Override
public void methodWithListNullableApiHandler(Handler<List<@Nullable RefedInterface1>> handler) {
handler.handle(methodWithListNullableApiReturn());
}
@Override
public void methodWithListNullableApiHandlerAsyncResult(Handler<AsyncResult<List<@Nullable RefedInterface1>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableApiReturn()));
}
@Override
public List<@Nullable RefedInterface1> methodWithListNullableApiReturn() {
ArrayList<RefedInterface1> ret = new ArrayList<>();
ret.add(new RefedInterface1Impl().setString("first"));
ret.add(null);
ret.add(new RefedInterface1Impl().setString("third"));
return ret;
}
@Override
public void methodWithListNullableDataObjectParam(List<@Nullable TestDataObject> param) {
Function<@Nullable TestDataObject, JsonObject> conv = obj -> (obj != null) ? obj.toJson() : null;
assertEquals(param.stream().map(conv).collect(Collectors.toList()), methodWithListNullableDataObjectReturn().stream().map(conv).collect(Collectors.toList()));
}
@Override
public void methodWithListNullableDataObjectHandler(Handler<List<@Nullable TestDataObject>> handler) {
handler.handle(methodWithListNullableDataObjectReturn());
}
@Override
public void methodWithListNullableDataObjectHandlerAsyncResult(Handler<AsyncResult<List<@Nullable TestDataObject>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableDataObjectReturn()));
}
@Override
public List<@Nullable TestDataObject> methodWithListNullableDataObjectReturn() {
ArrayList<TestDataObject> ret = new ArrayList<>();
ret.add(new TestDataObject().setFoo("first").setBar(1).setWibble(1.1));
ret.add(null);
ret.add(new TestDataObject().setFoo("third").setBar(3).setWibble(3.3));
return ret;
}
@Override
public void methodWithListNullableEnumParam(List<@Nullable TestEnum> param) {
assertEquals(param, methodWithListNullableEnumReturn());
}
@Override
public void methodWithListNullableEnumHandler(Handler<List<@Nullable TestEnum>> handler) {
handler.handle(methodWithListNullableEnumReturn());
}
@Override
public void methodWithListNullableEnumHandlerAsyncResult(Handler<AsyncResult<List<@Nullable TestEnum>>> handler) {
handler.handle(Future.succeededFuture(methodWithListNullableEnumReturn()));
}
@Override
public List<@Nullable TestEnum> methodWithListNullableEnumReturn() {
ArrayList<TestEnum> ret = new ArrayList<>();
ret.add(TestEnum.TIM);
ret.add(null);
ret.add(TestEnum.JULIEN);
return ret;
}
@Override
public void methodWithNullableHandler(boolean expectNull, Handler<String> handler) {
if (expectNull) {
assertNull(handler);
} else {
handler.handle(methodWithNullableStringReturn(true));
}
}
@Override
public void methodWithNullableHandlerAsyncResult(boolean expectNull, Handler<AsyncResult<String>> handler) {
if (expectNull) {
assertNull(handler);
} else {
handler.handle(Future.succeededFuture(methodWithNullableStringReturn(true)));
}
}
} |
package ca.eandb.util.progress;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.tree.TreePath;
import org.jdesktop.swingx.JXTreeTable;
import org.jdesktop.swingx.treetable.AbstractTreeTableModel;
import ca.eandb.util.ui.TreeUtil;
import ca.eandb.util.ui.renderer.ProgressBarRenderer;
/**
* Displays a hierarchy of <code>ProgressMonitor</code>s in a tree table.
* @author brad
*/
public final class ProgressPanel extends JPanel implements ProgressMonitor {
/** Serialization version ID. */
private static final long serialVersionUID = 1L;
/** The <code>ProgressModel</code> describing the structure of the tree. */
private final ProgressModel model; // @jve:decl-index=0:
/** The top level <code>ProgressMonitor</code>. */
private ProgressMonitor monitor = null;
/**
* The <code>JXTreeTable</code> in which to display the progress monitors.
*/
private JXTreeTable progressTree = null;
/**
* This is the default constructor
*/
public ProgressPanel() {
super();
this.model = new ProgressModel();
initialize();
}
/**
* Creates a new <code>ProgressPanel</code>.
* @param title The title to apply to the root node.
*/
public ProgressPanel(String title) {
super();
this.model = new ProgressModel(title);
initialize();
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
gridBagConstraints1.fill = GridBagConstraints.BOTH;
gridBagConstraints1.gridy = 1;
gridBagConstraints1.weightx = 1.0;
gridBagConstraints1.weighty = 1.0;
gridBagConstraints1.gridx = 0;
this.setSize(300, 200);
this.setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
gridBagConstraints2.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints2.gridx = 0;
gridBagConstraints2.gridy = 0;
gridBagConstraints2.weightx = 1.0;
gridBagConstraints2.weighty = 0.0;
this.add(getProgressTree().getTableHeader(), gridBagConstraints2);
this.add(new JScrollPane(getProgressTree()), gridBagConstraints1);
}
/**
* Sets a value indicating whether the root progress node is visible.
* @param visible true to make the root node visible, false otherwise.
*/
public void setRootVisible(final boolean visible) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
getProgressTree().setRootVisible(visible);
}
});
}
/**
* Gets the top level <code>ProgressMonitor</code>.
* @return The top level <code>ProgressMonitor</code>.
*/
private ProgressMonitor getProgressMonitor() {
if (monitor == null) {
monitor = new SynchronizedProgressMonitor(model.getRootNode());
}
return monitor;
}
/**
* Provides a model for displaying the progress tree.
* @author brad
*/
private static final class ProgressModel extends AbstractTreeTableModel {
/** The names of the columns in the table. */
private final String[] columnNames = { "Title", "Progress", "Status" };
/** The types of the columns in the table. */
private final Class<?>[] columnTypes = { String.class, JProgressBar.class, String.class };
/**
* Creates a new <code>ProgressModel</code>.
*/
private ProgressModel() {
super(new Node());
getRootNode().setModel(this);
}
/**
* Creates a new <code>ProgressModel</code>.
* @param title The title to apply to the root node.
*/
private ProgressModel(String title) {
super(new Node(title));
getRootNode().setModel(this);
}
/**
* Gets root <code>Node</code> of the tree.
* @return The root <code>Node</code>.
*/
public Node getRootNode() {
return ((Node) super.root);
}
/* (non-Javadoc)
* @see org.jdesktop.swingx.treetable.TreeTableModel#getColumnCount()
*/
public int getColumnCount() {
return columnNames.length;
}
/* (non-Javadoc)
* @see org.jdesktop.swingx.treetable.AbstractTreeTableModel#getColumnName(int)
*/
public String getColumnName(int column) {
return columnNames[column];
}
/* (non-Javadoc)
* @see org.jdesktop.swingx.treetable.AbstractTreeTableModel#getHierarchicalColumn()
*/
@Override
public int getHierarchicalColumn() {
return 0;
}
/* (non-Javadoc)
* @see ca.eandb.util.ui.treetable.AbstractTreeTableModel#getColumnClass(int)
*/
@Override
public Class<?> getColumnClass(int column) {
return columnTypes[column];
}
/* (non-Javadoc)
* @see org.jdesktop.swingx.treetable.TreeTableModel#getValueAt(java.lang.Object, int)
*/
public Object getValueAt(Object node, int column) {
switch (column) {
case 0: // title
return ((Node) node).getTitle();
case 1: // progress
return ((Node) node).progressBar;
case 2: // status
return ((Node) node).getStatus();
}
return null;
}
/* (non-Javadoc)
* @see javax.swing.tree.TreeModel#getChild(java.lang.Object, int)
*/
public Object getChild(Object parent, int index) {
return ((Node) parent).children.get(index);
}
/* (non-Javadoc)
* @see javax.swing.tree.TreeModel#getChildCount(java.lang.Object)
*/
public int getChildCount(Object parent) {
return ((Node) parent).children.size();
}
/* (non-Javadoc)
* @see javax.swing.tree.TreeModel#getIndexOfChild(java.lang.Object, java.lang.Object)
*/
public int getIndexOfChild(Object parent, Object child) {
return ((Node) parent).children.indexOf(child);
}
/**
* Represents a single node in a progress tree.
* @author brad
*/
private static final class Node extends AbstractProgressMonitor {
/** The <code>JProgressBar</code> for this node. */
private final JProgressBar progressBar = new JProgressBar();
/** The <code>List</code> of this node's children. */
private final List<Node> children = new ArrayList<Node>();
/**
* The <code>ProgressModel</code> for which this node is a member.
*/
private ProgressModel model;
/**
* The parent <code>Node</code>.
*/
private Node parent;
/**
* Creates a new root <code>Node</code>.
*/
public Node() {
super();
model = null;
parent = null;
}
/**
* Creates a new root <code>Node</code>.
* @param title The title to use to label the node.
*/
public Node(String title) {
super(title);
model = null;
parent = null;
}
/**
* Creates a new <code>Node</code>.
* @param title The title to use to label the node.
* @param parent The parent node.
*/
private Node(String title, Node parent) {
super(title);
assert(model != null);
this.model = parent.model;
this.parent = parent;
}
/**
* Sets the <code>ProgressModel</code> for which this node is a
* member.
* @param model The <code>ProgressModel</code>.
*/
private void setModel(ProgressModel model) {
this.model = model;
}
/**
* Populates the provided list with the ancestors of this node
* (including this node), starting at the root.
* @param path The <code>List</code> to populate.
*/
private void accumulatePath(List<Object> path) {
if (parent != null) {
parent.accumulatePath(path);
}
path.add(this);
}
/**
* Gets the <code>TreePath</code> to this node.
* @return The <code>TreePath</code> to this node.
*/
private TreePath getPath() {
return getPath(this);
}
/**
* Gets the <code>TreePath</code> to the specified node.
* @param node The <code>Node</code> for which to obtain the
* <code>TreePath</code>.
* @return The <code>TreePath</code> to <code>node</code>.
*/
private static TreePath getPath(Node node) {
List<Object> path = new ArrayList<Object>();
if (node != null) {
node.accumulatePath(path);
}
return new TreePath(path.toArray());
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.AbstractProgressMonitor#createChildProgressMonitor(java.lang.String)
*/
public ProgressMonitor createChildProgressMonitor(String title) {
final int index = children.size();
final Node child = new Node(title, this);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
children.add(child);
model.modelSupport.fireChildAdded(getPath(), index, child);
}
});
return child;
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.AbstractProgressMonitor#notifyCancelled()
*/
@Override
public void notifyCancelled() {
super.notifyCancelled();
detach();
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.AbstractProgressMonitor#notifyComplete()
*/
@Override
public void notifyComplete() {
super.notifyComplete();
detach();
}
/**
* Removes this node from its parent.
*/
private void detach() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (parent != null) {
int index = parent.children.indexOf(this);
parent.children.remove(index);
model.modelSupport.fireChildRemoved(parent.getPath(), index, this);
parent = null;
}
}
});
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.AbstractProgressMonitor#notifyIndeterminantProgress()
*/
@Override
public boolean notifyIndeterminantProgress() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setIndeterminate(true);
model.modelSupport.firePathChanged(getPath());
}
});
return super.notifyIndeterminantProgress();
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.AbstractProgressMonitor#notifyProgress(double)
*/
@Override
public boolean notifyProgress(final double progress) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setIndeterminate(false);
progressBar.setMaximum(100);
progressBar.setValue((int) (100.0 * progress));
model.modelSupport.firePathChanged(getPath());
}
});
return super.notifyProgress(progress);
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.AbstractProgressMonitor#notifyProgress(int, int)
*/
@Override
public boolean notifyProgress(final int value, final int maximum) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressBar.setIndeterminate(false);
progressBar.setMaximum(maximum);
progressBar.setValue(value);
model.modelSupport.firePathChanged(getPath());
}
});
return super.notifyProgress(value, maximum);
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.AbstractProgressMonitor#notifyStatusChanged(java.lang.String)
*/
@Override
public void notifyStatusChanged(String status) {
super.notifyStatusChanged(status);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
model.modelSupport.firePathChanged(getPath());
}
});
}
} // class Node
} // class ProgressModel
/* (non-Javadoc)
* @see ca.eandb.util.progress.ProgressMonitor#createChildProgressMonitor(java.lang.String)
*/
public ProgressMonitor createChildProgressMonitor(String title) {
return getProgressMonitor().createChildProgressMonitor(title);
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.ProgressMonitor#isCancelPending()
*/
public boolean isCancelPending() {
return getProgressMonitor().isCancelPending();
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.ProgressMonitor#notifyCancelled()
*/
public void notifyCancelled() {
getProgressMonitor().notifyCancelled();
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.ProgressMonitor#notifyComplete()
*/
public void notifyComplete() {
getProgressMonitor().notifyComplete();
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.ProgressMonitor#notifyIndeterminantProgress()
*/
public boolean notifyIndeterminantProgress() {
return getProgressMonitor().notifyIndeterminantProgress();
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.ProgressMonitor#notifyProgress(int, int)
*/
public boolean notifyProgress(int value, int maximum) {
return getProgressMonitor().notifyProgress(value, maximum);
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.ProgressMonitor#notifyProgress(double)
*/
public boolean notifyProgress(double progress) {
return getProgressMonitor().notifyProgress(progress);
}
/* (non-Javadoc)
* @see ca.eandb.util.progress.ProgressMonitor#notifyStatusChanged(java.lang.String)
*/
public void notifyStatusChanged(String status) {
getProgressMonitor().notifyStatusChanged(status);
}
/**
* This method initializes progressTree
* @param title
*
* @return org.jdesktop.swingx.JXTreeTable
*/
private JXTreeTable getProgressTree() {
if (progressTree == null) {
progressTree = new JXTreeTable(model);
progressTree.setRootVisible(true);
TreeUtil.enableAutoExpansion(progressTree);
ProgressBarRenderer.applyTo(progressTree);
}
return progressTree;
}
} |
package test.dr.inference.distribution;
import dr.inference.distribution.DirichletProcessLikelihood;
import dr.inference.model.*;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* A test suit for the Dirichlet Process likelihood.
*
* @author Andrew Rambaut
* @author Trevor Bedford
* @version $Id: BinomialLikelihood.java,v 1.5 2005/05/24 20:25:59 rambaut Exp $
*/
public class DirichletProcessTest extends TestCase {
public DirichletProcessTest(String name) {
super(name);
}
public void setUp() throws Exception {
super.setUp();
}
public void testDirichletProcess() {
// these are expected results calculated manually...
testDirichletProcess(new double[] {1, 1, 1}, 1.0, -Math.log(6.0)); // log 1/6
testDirichletProcess(new double[] {2, 1}, 1.0, -Math.log(6.0)); // log 1/6
testDirichletProcess(new double[] {3}, 1.0, -Math.log(3.0)); // log 1/3
// check the unoccupied groups are not counted
testDirichletProcess(new double[] {2, 1, 0}, 1.0, -Math.log(6.0)); // log 1/6
testDirichletProcess(new double[] {3, 0, 0}, 1.0, -Math.log(3.0)); // log 1/3
// these are results calculated by the method but confirmed against an independent implementation...
testDirichletProcess(new double[] {1, 1, 1, 1, 1}, 0.5, -6.851184927493743);
testDirichletProcess(new double[] {2, 1, 1, 1, 0}, 0.5, -6.158037746933798);
testDirichletProcess(new double[] {3, 1, 1, 0, 0}, 0.5, -4.771743385813907);
testDirichletProcess(new double[] {4, 1, 0, 0, 0}, 0.5, -2.9799839165858524);
testDirichletProcess(new double[] {5, 0, 0, 0, 0}, 0.5, -0.9005423749060166);
testDirichletProcess(new double[] {1, 1, 1, 1, 1}, 1.0, -4.787491742782046);
testDirichletProcess(new double[] {2, 1, 1, 1, 0}, 1.0, -4.787491742782046);
testDirichletProcess(new double[] {3, 1, 1, 0, 0}, 1.0, -4.0943445622221);
testDirichletProcess(new double[] {4, 1, 0, 0, 0}, 1.0, -2.995732273553991);
testDirichletProcess(new double[] {5, 0, 0, 0, 0}, 1.0, -1.6094379124341005);
testDirichletProcess(new double[] {1, 1, 1, 1, 1}, 2.0, -3.1135153092103747);
testDirichletProcess(new double[] {2, 1, 1, 1, 0}, 2.0, -3.80666248977032);
testDirichletProcess(new double[] {3, 1, 1, 0, 0}, 2.0, -3.80666248977032);
testDirichletProcess(new double[] {4, 1, 0, 0, 0}, 2.0, -3.401197381662156);
testDirichletProcess(new double[] {5, 0, 0, 0, 0}, 2.0, -2.7080502011022105);
testDirichletProcess(new double[] {1, 1, 1, 1, 1}, 5.0, -1.5765840875630222);
testDirichletProcess(new double[] {2, 1, 1, 1, 0}, 5.0, -3.1860219999971227);
testDirichletProcess(new double[] {3, 1, 1, 0, 0}, 5.0, -4.102312731871278);
testDirichletProcess(new double[] {4, 1, 0, 0, 0}, 5.0, -4.613138355637268);
testDirichletProcess(new double[] {5, 0, 0, 0, 0}, 5.0, -4.836281906951478);
}
private void testDirichletProcess(double[] eta, double chi, double expectedLogL) {
Parameter etaParameter = new Parameter.Default("eta", eta);
Parameter chiParameter = new Parameter.Default("chi", chi, 0.0, Double.MAX_VALUE);
DirichletProcessLikelihood dirichlet = new DirichletProcessLikelihood(etaParameter, chiParameter);
assertEquals(expectedLogL, dirichlet.getLogLikelihood(), 1E-10);
}
public static Test suite() {
return new TestSuite(DirichletProcessTest.class);
}
} |
package br.uff.ic.graphmatching;
import br.uff.ic.utility.AttributeErrorMargin;
import br.uff.ic.utility.GraphAttribute;
import br.uff.ic.utility.Vocabulary;
import br.uff.ic.utility.graph.ActivityVertex;
import br.uff.ic.utility.graph.Edge;
import br.uff.ic.utility.graph.EntityVertex;
import br.uff.ic.utility.graph.Vertex;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Kohwalter
*/
public class GraphMatchingTest {
public GraphMatchingTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
/**
* Test of isSimilar method, of class GraphMatching.
*/
@Test
public void testIsSimilar() {
// System.out.println("isSimilar");
equals(1.00f, true);
almostEquals(0.75f, true);
halfEquals(0.5f, true);
quarterEquals(0.25f, true);
notEquals(0.00f, true);
equals(0.75f, true);
almostEquals(0.85f, false);
halfEquals(0.75f, false);
quarterEquals(0.5f, false);
notEquals(0.10f, false);
differentTypes(1.00f, false);
differentAttributes(0.5f, true);
differentAttributes(0.51f, false);
}
public void Comparing(float threshold, boolean expResult,
String a11, String a12,
String a21, String a22,
String e1, String e2, String e3, String e4) {
Vertex v1 = new ActivityVertex("v1", "test", "0");
Vertex v2 = new ActivityVertex("v2", "test", "0");
Map<String, AttributeErrorMargin> restrictionList = new HashMap<String, AttributeErrorMargin>();
Vocabulary vocabulary = new Vocabulary("asd, bvF");
vocabulary.addVocabulary("qwe, rty, asd");
GraphAttribute av1 = new GraphAttribute("a1", a11);
GraphAttribute av2 = new GraphAttribute("a1", a12);
AttributeErrorMargin epsilon = new AttributeErrorMargin("a1", e1);
restrictionList.put("a1", epsilon);
v1.addAttribute(av1);
v2.addAttribute(av2);
av1 = new GraphAttribute("a2", a21);
av2 = new GraphAttribute("a2", a22);
epsilon = new AttributeErrorMargin("a2", e2);
restrictionList.put("a2", epsilon);
v1.addAttribute(av1);
v2.addAttribute(av2);
av1 = new GraphAttribute("a3", "3");
av2 = new GraphAttribute("a3", "1.5");
epsilon = new AttributeErrorMargin("a3", e3);
restrictionList.put("a3", epsilon);
v1.addAttribute(av1);
v2.addAttribute(av2);
av1 = new GraphAttribute("a4", "1");
av2 = new GraphAttribute("a4", "-2");
epsilon = new AttributeErrorMargin("a4", e4);
restrictionList.put("a4", epsilon);
v1.addAttribute(av1);
v2.addAttribute(av2);
epsilon = new AttributeErrorMargin("Timestamp", "0", 0);
restrictionList.put("Timestamp", epsilon);
GraphMatching instance = new GraphMatching(restrictionList, vocabulary.getVocabulary(), threshold);
boolean result = instance.isSimilar(v1, v2);
assertEquals(expResult, result);
}
public void ComparingDefault(float threshold, boolean expResult,
String a11, String a12,
String a21, String a22,
String e3, String e4) {
Vertex v1 = new ActivityVertex("v1", "test", "0");
Vertex v2 = new ActivityVertex("v2", "test", "0");
Map<String, AttributeErrorMargin> restrictionList = new HashMap<String, AttributeErrorMargin>();
GraphAttribute av1 = new GraphAttribute("a1", a11);
GraphAttribute av2 = new GraphAttribute("a1", a12);
v1.addAttribute(av1);
v2.addAttribute(av2);
av1 = new GraphAttribute("a2", a21);
av2 = new GraphAttribute("a2", a22);
v1.addAttribute(av1);
v2.addAttribute(av2);
av1 = new GraphAttribute("a3", "3");
av2 = new GraphAttribute("a3", "1.5");
AttributeErrorMargin epsilon = new AttributeErrorMargin("a3", e3);
restrictionList.put("a3", epsilon);
v1.addAttribute(av1);
v2.addAttribute(av2);
av1 = new GraphAttribute("a4", "1");
av2 = new GraphAttribute("a4", "-2");
epsilon = new AttributeErrorMargin("a4", e4);
restrictionList.put("a4", epsilon);
v1.addAttribute(av1);
v2.addAttribute(av2);
GraphMatching instance = new GraphMatching(restrictionList, threshold, "25%");
boolean result = instance.isSimilar(v1, v2);
assertEquals(expResult, result);
}
public void equals(float threshold, boolean expResult) {
// System.out.println("Equal");
Comparing(threshold, expResult, "asd", "bvF", "2012-05-24T10:00:02", "2012-05-24T10:00:01", "asd, bvf", "2000", "50%", "300%");
Comparing(threshold, expResult, "8", "10", "2012-05-24T10:00:02", "2012-05-24T10:00:01", "2", "2000", "50%", "300%");
Comparing(threshold, expResult, "10", "8", "10", "7", "20%", "30%", "50%", "300%");
ComparingDefault(threshold, expResult, "8", "10", "-10", "-10", "50%", "300%");
}
public void almostEquals(float threshold, boolean expResult) {
// System.out.println("AlmostEqual");
Comparing(threshold, expResult, "asd", "AsD", "2012-05-24T10:00:01", "2012-05-24T10:00:02", "0", "2000", "50%", "0%");
ComparingDefault(threshold, expResult, "8", "10", "7", "10", "50%", "300%");
}
public void halfEquals(float threshold, boolean expResult) {
// System.out.println("HalfEqual");
Comparing(threshold, expResult, "asd", "AsD", "2012-05-24T10:00:01", "2012-05-24T10:00:02", "0", "2000", "0%", "0%");
ComparingDefault(threshold, expResult, "8", "10", "7", "10", "50%", "0");
}
public void quarterEquals(float threshold, boolean expResult) {
// System.out.println("notEqual");
Comparing(threshold, expResult, "asd", "AsD", "2012-05-24T10:00:01", "2012-05-24T10:00:02", "0", "0", "0%", "0%");
}
public void notEquals(float threshold, boolean expResult) {
// System.out.println("notEqual");
Comparing(threshold, expResult, "asd", "AsDD", "2012-05-24T10:00:01", "2012-05-24T10:00:02", "0", "0", "0%", "0%");
}
public void differentTypes(float threshold, boolean expResult) {
// System.out.println("Different Types");
Vertex v1 = new ActivityVertex("v1", "test", "0");
Vertex v2 = new EntityVertex("v2", "test", "0");
Map<String, AttributeErrorMargin> restrictionList = new HashMap<String, AttributeErrorMargin>();
GraphAttribute av1 = new GraphAttribute("a1", "0");
GraphAttribute av2 = new GraphAttribute("a1", "0");
AttributeErrorMargin epsilon = new AttributeErrorMargin("a1", "0");
restrictionList.put("a1", epsilon);
v1.addAttribute(av1);
v2.addAttribute(av2);
GraphMatching instance = new GraphMatching(restrictionList, threshold);
boolean result = instance.isSimilar(v1, v2);
assertEquals(expResult, result);
}
public void differentAttributes(float threshold, boolean expResult) {
// System.out.println("Different Types");
Vertex v1 = new ActivityVertex("v1", "test", "0");
Vertex v2 = new ActivityVertex("v2", "test", "0");
Map<String, AttributeErrorMargin> restrictionList = new HashMap<String, AttributeErrorMargin>();
GraphAttribute av1 = new GraphAttribute("a1", "0");
GraphAttribute av2 = new GraphAttribute("a1", "0");
AttributeErrorMargin epsilon = new AttributeErrorMargin("a1", "0");
restrictionList.put("a1", epsilon);
v1.addAttribute(av1);
v2.addAttribute(av2);
av1 = new GraphAttribute("a2", "1.5");
v1.addAttribute(av1);
av2 = new GraphAttribute("a3", "1.5");
v2.addAttribute(av2);
av1 = new GraphAttribute("a4", "1");
av2 = new GraphAttribute("a4", "1");
v1.addAttribute(av1);
v2.addAttribute(av2);
epsilon = new AttributeErrorMargin("Timestamp", "0", 0);
restrictionList.put("Timestamp", epsilon);
GraphMatching instance = new GraphMatching(restrictionList, threshold);
boolean result = instance.isSimilar(v1, v2);
assertEquals(expResult, result);
}
/**
* Test of combineVertices method, of class GraphMatching.
*/
@Test
public void testCombineVertices() {
// System.out.println("combineVertices");
Vertex v1 = new ActivityVertex("v1", "test01", "0");
Vertex v2 = new ActivityVertex("v2", "test02", "0");
GraphAttribute av1;
GraphAttribute av2;
av1 = new GraphAttribute("a1", "Asd");
av2 = new GraphAttribute("a1", "edf");
v1.addAttribute(av1);
v2.addAttribute(av2);
av1 = new GraphAttribute("a2", "4");
av2 = new GraphAttribute("a2", "2");
v1.addAttribute(av1);
v2.addAttribute(av2);
av1 = new GraphAttribute("a3", "3");
av2 = new GraphAttribute("a3", "1");
v1.addAttribute(av1);
v2.addAttribute(av2);
av1 = new GraphAttribute("a4", "2");
av2 = new GraphAttribute("a4", "-2");
v1.addAttribute(av1);
v2.addAttribute(av2);
av1 = new GraphAttribute("a5", "5");
v1.addAttribute(av1);
av2 = new GraphAttribute("a6", "6");
v2.addAttribute(av2);
GraphMatching instance = new GraphMatching(null, 0.0f);
Vertex expResult = new ActivityVertex(v1.getID() + ", " + v2.getID(), v1.getLabel() + "_" + v2.getLabel(), v1.getTimeString());
GraphAttribute aResult;
aResult = new GraphAttribute("a1", "Asd, edf");
aResult.incrementQuantity();
expResult.addAttribute(aResult);
aResult = new GraphAttribute("a2", "6");
aResult.incrementQuantity();
aResult.setMin(2);
aResult.setMax(4);
expResult.addAttribute(aResult);
aResult = new GraphAttribute("a3", "4");
aResult.incrementQuantity();
aResult.setMin(1);
aResult.setMax(3);
expResult.addAttribute(aResult);
aResult = new GraphAttribute("a4", "0");
aResult.incrementQuantity();
aResult.setMin(-2);
aResult.setMax(2);
expResult.addAttribute(aResult);
aResult = new GraphAttribute("a5", "5");
expResult.addAttribute(aResult);
aResult = new GraphAttribute("a6", "6");
expResult.addAttribute(aResult);
expResult.attributes.get("Timestamp").updateAttribute("0");
Vertex result = instance.combineVertices(v1, v2);
assertEquals(expResult.toString(), result.toString());
}
// /**
// * Test of addVertex method, of class GraphMatching.
// */
// @Test
// public void testAddVertex() {
// System.out.println("addVertex");
// Vertex vertex = null;
// GraphMatching instance = new GraphMatching();
// instance.addVertex(vertex);
// // TODO review the generated test code and remove the default call to fail.
// fail("The test case is a prototype.");
// /**
// * Test of addVertices method, of class GraphMatching.
// */
// @Test
// public void testAddVertices() {
// System.out.println("addVertices");
// Collection<Object> vertices = null;
// GraphMatching instance = new GraphMatching();
// instance.addVertices(vertices);
// // TODO review the generated test code and remove the default call to fail.
// fail("The test case is a prototype.");
/**
* Test of updateEdges method, of class GraphMatching.
*/
@Test
public void testUpdateEdges() {
// System.out.println("updateEdges");
Collection<Edge> edges = new ArrayList<Edge>();
GraphMatching instance = new GraphMatching(null, 0.0f);
Vertex v1 = new ActivityVertex("v1", "test01", "0");
Vertex v2 = new ActivityVertex("v2", "test02", "0");
Vertex source = new ActivityVertex("v3", "test03", "0");
Vertex target = new ActivityVertex("v4", "test04", "0");
Edge edge = new Edge("edge01", "Test", "Testing", "0", v1, source);
edges.add(edge);
edge = new Edge("edge02", "Test", "Testing", "0", target, v2);
edges.add(edge);
GraphAttribute av1;
GraphAttribute av2;
av1 = new GraphAttribute("a1", "0");
av2 = new GraphAttribute("a1", "0");
v1.addAttribute(av1);
v2.addAttribute(av2);
Vertex updatedVertex = instance.combineVertices(v1, v2);
Map<String, Edge> expResult = new HashMap<String, Edge>();
Edge updatedEdge = new Edge("edge01", "Test", "Testing", "0", updatedVertex, source);
expResult.put(updatedEdge.getID(), updatedEdge);
updatedEdge = new Edge("edge02", "Test", "Testing", "0", target, updatedVertex);
expResult.put(updatedEdge.getID(), updatedEdge);
Collection<Edge> result = instance.updateEdges(edges);
Edge result01 = ((Edge) result.toArray()[0]);
Edge expResult01 = ((Edge) expResult.values().toArray()[1]);
Edge result02 = ((Edge) result.toArray()[1]);
Edge expResult02 = ((Edge) expResult.values().toArray()[0]);
String result01Target = ((Vertex)result01.getTarget()).getID();
String expResult01Target = ((Vertex)expResult01.getTarget()).getID();
String result01Source = ((Vertex)result01.getSource()).getID();
String expResult01Source = ((Vertex)expResult01.getSource()).getID();
String result02Target = ((Vertex)result02.getTarget()).getID();
String expResult02Target = ((Vertex)expResult02.getTarget()).getID();
String result02Source = ((Vertex)result02.getSource()).getID();
String expResult02Source = ((Vertex)expResult02.getSource()).getID();
// System.out.println("Target: " + result01Target);
// System.out.println("Exp Target: " + expResult01Target);
// System.out.println("Source: " + result01Source);
// System.out.println("Exp Source: " + expResult01Source);
// System.out.println("Target: " + result02Target);
// System.out.println("Exp Target: " + expResult02Target);
// System.out.println("Source: " + result02Source);
// System.out.println("Exp Source: " + expResult02Source);
assertEquals(result01Target, expResult01Target);
assertEquals(result01Source, expResult01Source);
assertEquals(result02Target, expResult02Target);
assertEquals(result02Source, expResult02Source);
}
// /**
// * Test of addEdges method, of class GraphMatching.
// */
// @Test
// public void testAddEdges() {
// System.out.println("addEdges");
// Collection<Edge> edges = null;
// GraphMatching instance = new GraphMatching();
// instance.addEdges(edges);
// // TODO review the generated test code and remove the default call to fail.
// fail("The test case is a prototype.");
// /**
// * Test of combineEdges method, of class GraphMatching.
// */
// @Test
// public void testCombineEdges() {
// System.out.println("combineEdges");
// GraphMatching instance = new GraphMatching();
// instance.combineEdges();
// // TODO review the generated test code and remove the default call to fail.
// fail("The test case is a prototype.");
} |
package client.shareserver;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Creates a stream from a file that only contains the first n and last n bytes of a file.
* If the length of the file is less than 2n then this behaves as a normal fileinputstream.
*
* It depends on being able to skip a fileinputstream reliably!
*
* @author gary
*/
public class FileCropperStream extends FileInputStream {
long cropAt; //the start of the section to be discarded.
long cropLength; //the length of the discarded section.
long cropPosition = 0; //The real position in the file.
/**
* Create a new cropped file stream.
* @param inFile the file object.
* @param cropSize the size of the header and the footer to crop out.
* @throws FileNotFoundException
*/
public FileCropperStream(File inFile, long cropSize) throws FileNotFoundException{
super(inFile);
if (inFile.length() < cropSize*2) {
cropAt = Long.MAX_VALUE;
cropLength = 0;
} else {
cropAt = cropSize;
cropLength = inFile.length()-cropSize*2;
}
}
@Override
public long skip(long n) throws IOException {
long rb = byteRequest(n);
long skipped;
if (rb==n) {
skipped = super.skip(n);
cropPosition+=skipped;
} else {
//The crop is approaching, so do a skip-by parts:
skipped = super.skip(rb);
cropPosition+=skipped;
if (skipped==rb) {
//successfull first skip:
doCrop(); //Move past the cropped section
rb = n-rb; //Still have stuff remaining to skip
long skipped2 = super.skip(rb);
skipped+=skipped2;
cropPosition+=skipped2;
}
}
return skipped;
}
@Override
public int read() throws IOException {
//If we cant read a byte now then we need to do the crop:
long rb = byteRequest(1);
if (rb==0) {
doCrop();
}
cropPosition++;
return super.read();
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
// Follows the same idiom as skip:
public int read(byte[] b, int off, int len) throws IOException {
int rb = (int) byteRequest(len);
int bytesRead;
if (rb == len) {
bytesRead = super.read(b, off, len);
cropPosition += bytesRead;
} else {
// The crop is approaching, so do a read-by parts:
bytesRead = super.read(b, off, rb);
cropPosition += bytesRead;
if (bytesRead == rb) {
// Successful first read:
doCrop(); // Move past the cropped section
// Still have stuff remaining to read
int bytesRead2 = super.read(b, off + rb, len - rb);
bytesRead += bytesRead2;
cropPosition += bytesRead2;
}
}
return bytesRead;
}
// On skipping/reading this calculates how much may be done safely.
// (after the crop has been done this is just the requested amount)
private long byteRequest(long request) {
if (cropPosition+request > cropAt && cropLength > 0) {
return cropAt-cropPosition;
} else {
return request;
}
}
private void doCrop() throws IOException {
while (cropLength > 0) cropLength-=super.skip(cropLength);
cropPosition+=cropLength;
}
} |
package com.github.eventsource.client;
import java.net.URI;
import java.util.concurrent.CountDownLatch;
public class DebugClient {
public static void main(String[] args) throws InterruptedException {
EventSource es = new EventSource(URI.create("http://localhost:8090/es"), new EventSourceHandler() {
@Override
public void onConnect() {
System.out.println("CONNECTED");
}
@Override
public void onMessage(String event, MessageEvent message) {
System.out.println("event = " + event + ", message = " + message);
}
@Override
public void onError(Throwable t) {
System.err.println("ERROR");
t.printStackTrace();
}
@Override
public void onClosed(boolean willReconnect) {
System.err.println("CLOSED");
}
});
es.connect();
new CountDownLatch(1).await();
}
} |
package com.seleniumtests.tests;
import com.seleniumtests.controller.ContextManager;
import com.seleniumtests.controller.EasyFilter;
import com.seleniumtests.controller.TestPlan;
import com.seleniumtests.dataobject.User;
import com.seleniumtests.util.SpreadSheetUtil;
import com.seleniumtests.util.internal.entity.TestObject;
import com.seleniumtests.webpage.TestLinkLoginPage;
import org.testng.ITestContext;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.LinkedHashMap;
public class TestLinkLoginTest extends TestPlan {
@DataProvider(name = "loginData", parallel = true)
public static Iterator<Object[]> getUserInfo(Method m,
ITestContext testContext) throws Exception {
EasyFilter filter = EasyFilter.equalsIgnoreCase(TestObject.TEST_METHOD,
m.getName());
filter = EasyFilter.and(filter, EasyFilter.equalsIgnoreCase(
TestObject.TEST_SITE,
ContextManager.getTestLevelContext(testContext).getSite()));
LinkedHashMap<String, Class<?>> classMap = new LinkedHashMap<String, Class<?>>();
classMap.put("TestObject", TestObject.class);
classMap.put("User", User.class);
return SpreadSheetUtil.getEntitiesFromSpreadsheet(
TestLinkLoginTest.class, classMap, "loginuser.csv", 0,
null, filter);
}
/**
* Logs in to TestLink as valid user
*
* @param testObject
* @param user
* @throws Exception
*/
@Test(groups = {"loginTestSuccess"}, dataProvider = "loginData",
description = "Logs in to TestLink as admin")
public void loginTestSuccess(TestObject testObject, final User user)
throws Exception {
new TestLinkLoginPage(true)
.loginAsValidUser(user)
.verifyDocumentationDropDown();
}
/**
* Logs in to TestLink as invalid user
*
* @param testObject
* @param user
* @throws Exception
*/
@Test(groups = {"loginTestFailure"}, dataProvider = "loginData",
description = "Logs in to TestLink as invalid user")
public void loginTestFailure(TestObject testObject, final User user)
throws Exception {
new TestLinkLoginPage(true)
.loginAsInvalidUser(user)
.verifyLoginBoxPresence();
}
} |
package com.slicingdice.jslicer;
import com.slicingdice.jslicer.core.Requester;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Objects;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.json.JSONArray;
import org.json.JSONObject;
public class SlicingDiceTester {
// The SlicingDice client
private final SlicingDice client;
private boolean verbose = false;
// Translation table for columns with timestamp
private JSONObject columnTranslation;
// Sleep time in seconds
private long sleepTime;
// Directory containing examples to test
private String path;
// Examples file format
private String fileExtension;
public int numberOfSuccesses;
public int numberOfFails;
public ArrayList<Object> failedTests;
private boolean perTestInsertion;
private boolean insertSqlData;
public SlicingDiceTester(final String apiKey) {
this.client = new SlicingDice(apiKey);
this.loadConfigTest();
}
public SlicingDiceTester(final String apiKey, final boolean verbose) {
this.client = new SlicingDice(apiKey);
this.verbose = verbose;
this.loadConfigTest();
}
private void loadConfigTest() {
this.sleepTime = 10;
this.path = "src/test/java/com/slicingdice/jslicer/examples/";
this.fileExtension = ".json";
this.numberOfSuccesses = 0;
this.numberOfFails = 0;
this.failedTests = new ArrayList<>();
}
/**
* Run tests
*
* @param queryType the query type
*/
public void runTests(final String queryType) throws ExecutionException, InterruptedException {
final JSONArray testData = this.loadTestData(queryType);
final int numberOfTests = testData.length();
this.perTestInsertion = testData.getJSONObject(0).has("insert");
if (!this.perTestInsertion && this.insertSqlData) {
final JSONArray insertionData = this.loadInsertionData(queryType);
for (final Object insertCommand : insertionData) {
this.client.insert((JSONObject) insertCommand).get();
}
Thread.sleep(this.sleepTime);
}
for (int i = 0; i < numberOfTests; i++) {
final JSONObject testObject = (JSONObject) testData.get(i);
this.emptyColumnTranslation();
System.out.println(String.format("(%1$d/%2$d) Executing test \"%3$s\"", i + 1,
numberOfTests, testObject.getString("name")));
if (testObject.has("description")) {
System.out.println(String.format("\tDescription: %s",
testObject.get("description")));
}
System.out.println(String.format("\tQuery type: %s", queryType));
JSONObject result = null;
try {
if (this.perTestInsertion) {
this.createColumns(testObject);
this.insertData(testObject);
}
result = this.executeQuery(queryType, testObject);
} catch (final Exception e) {
result = new JSONObject()
.put("result", new JSONObject()
.put("error", e.toString()));
}
try {
this.compareResult(testObject, queryType, result);
} catch (final IOException e) {
e.printStackTrace();
}
}
}
private void emptyColumnTranslation() {
this.columnTranslation = new JSONObject();
}
/**
* Load test data from examples files
*
* @param queryType the query type
* @return JSONArray with test data
*/
private JSONArray loadTestData(final String queryType) {
return loadData(queryType, "");
}
/**
* Load insertion data from examples files
*
* @param queryType the query type
* @return JSONArray with insertion data
*/
private JSONArray loadInsertionData(final String queryType) {
return loadData(queryType, "_insert");
}
private JSONArray loadData(final String queryType, final String file_suffix) {
final String file = new File(this.path + queryType + file_suffix
+ this.fileExtension).getAbsolutePath();
String content = null;
try {
content = new Scanner(new File(file)).useDelimiter("\\Z").next();
return new JSONArray(content);
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* Create columns on SlicingDice API
*
* @param columnObject the column object to create
*/
private void createColumns(final JSONObject columnObject) {
final JSONArray columns = columnObject.getJSONArray("columns");
final boolean isSingular = columns.length() == 1;
String columnOrColumns = null;
if (isSingular) {
columnOrColumns = "column";
} else {
columnOrColumns = "columns";
}
System.out.println(String.format("\tCreating %1$d %2$s", columns.length(), columnOrColumns));
for (final Object column : columns) {
final JSONObject columnDict = (JSONObject) column;
this.addTimestampToColumnName(columnDict);
// call client command to create columns
try {
this.client.createColumn(columnDict).get();
} catch (final InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (this.verbose) {
System.out.println(String.format("\t\t- %s", columnDict.getString("api-name")));
}
}
}
/**
* Add timestamp to column name
*
* @param column the column to put timestamp
*/
private void addTimestampToColumnName(final JSONObject column) {
final String oldName = "\"" + column.getString("api-name") + "\"";
final String timestamp = this.getTimestamp();
column.put("name", column.get("name") + timestamp);
column.put("api-name", column.get("api-name") + timestamp);
final String newName = "\"" + column.getString("api-name") + "\"";
this.columnTranslation.put(oldName, newName);
}
/**
* Get actual timestamp
*
* @return timestamp converted to string
*/
private String getTimestamp() {
final Long currentTime = System.currentTimeMillis() * 10;
return currentTime.toString();
}
/**
* Insert data to SlicingDice API
*
* @param insertionObject the data to insert on SlicingDice
*/
private void insertData(final JSONObject insertionObject) {
final JSONObject insert = insertionObject.getJSONObject("insert");
final boolean isSingular = insert.length() == 1;
final String entityOrEntities;
if (isSingular) {
entityOrEntities = "entity";
} else {
entityOrEntities = "entities";
}
System.out.println(String.format("\tInserting %1$d %2$s", insert.length(), entityOrEntities));
final JSONObject insertData = this.translateColumnNames(insert);
// call client command to insert data
try {
this.client.insert(insertData).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
try {
// Wait a few seconds so the data can be inserted by SlicingDice
TimeUnit.SECONDS.sleep(this.sleepTime);
} catch (final InterruptedException e) {
e.printStackTrace();
System.out.println("An error occurred while processing your query on SlicingDice");
}
}
/**
* Translate column name to use timestamp
*
* @param column the column to translate
* @return the new column translated
*/
private JSONObject translateColumnNames(final JSONObject column) {
String dataString = column.toString();
for (final Object oldName : this.columnTranslation.keySet()) {
final String oldNameStr = (String) oldName;
final String newName = this.columnTranslation.getString(oldNameStr);
dataString = dataString.replaceAll(oldNameStr, newName);
}
return new JSONObject(dataString);
}
/**
* Execute query
*
* @param queryType the type of the query
* @param query the query to send to SlicingDice API
* @return the result of the query
*/
private JSONObject executeQuery(final String queryType, final JSONObject query)
throws ExecutionException, InterruptedException {
final JSONObject queryData;
if (this.perTestInsertion) {
queryData = this.translateColumnNames(query.getJSONObject("query"));
} else {
queryData = query;
}
System.out.println("\tQuerying");
if (this.verbose) {
System.out.println(String.format("\t\t- %s", queryData));
}
JSONObject result = null;
// call client command to make a query
switch (queryType) {
case "count_entity":
result = Requester.responseToJson(this.client.countEntity(queryData).get());
break;
case "count_event":
result = Requester.responseToJson(this.client.countEvent(queryData).get());
break;
case "top_values":
result = Requester.responseToJson(this.client.topValues(queryData).get());
break;
case "aggregation":
result = Requester.responseToJson(this.client.aggregation(queryData).get());
break;
case "result":
result = Requester.responseToJson(this.client.result(queryData).get());
break;
case "score":
result = Requester.responseToJson(this.client.score(queryData).get());
break;
case "sql":
result = Requester.responseToJson(this.client.sql(queryData.getString("query")).get());
break;
}
return result;
}
/**
* Compare result received from SlicingDice API
*
* @param expectedObject the object with expected result
* @param queryType - the type of the query
* @param result the result received from SlicingDice API
*/
private void compareResult(final JSONObject expectedObject, final String queryType,
final JSONObject result) throws IOException {
final JSONObject testExpected = expectedObject.getJSONObject("expected");
final JSONObject expected;
if (this.perTestInsertion) {
expected = this.translateColumnNames(expectedObject.getJSONObject("expected"));
} else {
expected = expectedObject.getJSONObject("expected");
}
for (final Object key : testExpected.keySet()) {
final String keyStr = (String) key;
final Object value = testExpected.get(keyStr);
if (value.toString().equals("ignore")) {
continue;
}
boolean testFailed = false;
if (!result.has(keyStr)) {
// try second time
if (testSecondTime(expectedObject, queryType, expected, keyStr)) {
continue;
}
testFailed = true;
} else {
if (!this.compareJsonValue(expected.get(keyStr),
result.get(keyStr))) {
// try second time
if (testSecondTime(expectedObject, queryType, expected, keyStr)) {
continue;
}
testFailed = true;
}
}
if (testFailed) {
this.numberOfFails += 1;
this.failedTests.add(expectedObject.getString("name"));
try {
System.out.println(String.format("\tExpected: \"%1$s\": %2$s", keyStr,
expected.getJSONObject(keyStr).toString()));
} catch (final Exception e) {
System.out.println(String.format("\tExpected: \"%1$s\": %2$s", keyStr,
e.getMessage()));
}
try {
System.out.println(String.format("\tResult: \"%1$s\": %2$s", keyStr,
result.getJSONObject(keyStr).toString()));
} catch (final Exception e) {
System.out.println(String.format("\tResult: \"%1$s\": %2$s", keyStr,
e.getMessage()));
}
System.out.println("\tStatus: Failed\n");
return;
} else {
this.numberOfSuccesses += 1;
System.out.println("\tStatus: Passed\n");
}
}
}
/**
* If first query doesn't return as expected we will try another time
*
* @param expectedObject -
* @param queryType - type of the query to send to SlicingDice
* @param expected = the expected json
* @param key - the json key to test
* @return true if second test succeed and false otherwise
* @throws IOException
*/
private boolean testSecondTime(final JSONObject expectedObject, final String queryType,
final JSONObject expected, final String key) {
try {
TimeUnit.SECONDS.sleep(this.sleepTime * 3);
} catch (final InterruptedException e) {
e.printStackTrace();
}
final JSONObject secondResult;
try {
secondResult = this.executeQuery(queryType, expectedObject);
if (this.compareJsonValue(expected.get(key), secondResult.get(key))) {
System.out.println("\tPassed at second try!");
this.numberOfSuccesses += 1;
System.out.println("\tStatus: Passed\n");
return true;
}
} catch (final Exception e) {
e.printStackTrace();
}
return false;
}
/**
* Compare two JSONObjects
*
* @param expected - The json with the expected result
* @param got = The json returned by the SlicingDice API
* @return - true if the two json's are equal and false otherwise
*/
private boolean compareJson(final JSONObject expected, final JSONObject got) {
if (expected.length() != got.length()) {
return false;
}
final Set keySet = expected.keySet();
final Iterator iterator = keySet.iterator();
while (iterator.hasNext()) {
final String name = (String) iterator.next();
final Object valueExpected = expected.get(name);
final Object valueGot = got.get(name);
if (!this.compareJsonValue(valueExpected, valueGot)) {
return false;
}
}
return true;
}
/**
* Compare two JSONArrays
*
* @param expected - The json with the expected result
* @param got = The json returned by the SlicingDice API
* @return - true if the two json's are equal and false otherwise
*/
private boolean compareJsonArray(final JSONArray expected, final JSONArray got) {
if (expected.length() != got.length()) {
return false;
}
for (int i = 0; i < expected.length(); ++i) {
final Object valueExpected = expected.get(i);
boolean hasTrue = false;
for (int j = 0; j < got.length(); j++) {
final Object valueGot = got.get(j);
if (this.compareJsonValue(valueExpected, valueGot)) {
hasTrue = true;
}
}
if (!hasTrue) {
return false;
}
}
return true;
}
/**
* Compare two json values
*
* @param valueExpected - the expected value
* @param valueGot - the received value
* @return true if the two values are equal and false otherwise
*/
private boolean compareJsonValue(final Object valueExpected, final Object valueGot) {
try {
if (valueExpected instanceof JSONObject) {
if (!this.compareJson((JSONObject) valueExpected, (JSONObject) valueGot)) {
return false;
}
} else if (valueExpected instanceof JSONArray) {
if (!this.compareJsonArray((JSONArray) valueExpected, (JSONArray) valueGot)) {
return false;
}
} else if (!valueExpected.equals(valueGot)) {
if (valueExpected instanceof Integer && valueGot instanceof Double ||
valueExpected instanceof Double && valueGot instanceof Integer) {
final Number expectedInteger = (Number) valueExpected;
final Number gotInteger = (Number) valueGot;
return expectedInteger.intValue() == gotInteger.intValue();
} else if (valueExpected instanceof Double || valueExpected instanceof Float) {
return this.compareNumbersClose((Number) valueExpected, (Number) valueGot);
} else {
return Objects.equals(valueExpected, valueGot);
}
}
} catch (final Exception e) {
return false;
}
return true;
}
private boolean compareNumbersClose(final Number expected, final Number result) {
final double expectedDouble = expected.doubleValue();
final double resultDouble = result.doubleValue();
return Math.abs(expectedDouble - resultDouble) <= Math.max(
(1e-09) * Math.max(Math.abs(expectedDouble), Math.abs(resultDouble)), 0.0);
}
} |
package eme.generator;
import static org.junit.Assert.assertEquals;
import org.eclipse.emf.ecore.EPackage;
import org.junit.Before;
import org.junit.Test;
import eme.generator.saving.CustomPathSavingStrategy;
import eme.model.ExtractedPackage;
import eme.model.IntermediateModel;
import eme.properties.ExtractionProperties;
import eme.properties.TestProperties;
public class EcoreMetamodelGeneratorTest {
ExtractionProperties properties;
EcoreMetamodelGenerator generator;
IntermediateModel model;
@Before
public void setUp() throws Exception {
properties = new TestProperties(); // don't use real properties
generator = new EcoreMetamodelGenerator(properties);
model = new IntermediateModel("UnitTestProject");
}
@Test
public void testPackageStructure() {
buildMVCPackages();
EPackage metamodel = generator.generateMetamodelFrom(model);
assertEquals(properties.getDefaultPackageName(), metamodel.getName());
assertEquals(properties.getDefaultPackageName(), metamodel.getNsPrefix());
assertEquals(model.getProjectName() + "/", metamodel.getNsURI());
assertEquals(1, metamodel.getESubpackages().size());
EPackage main = metamodel.getESubpackages().get(0);
assertEquals(3, main.getESubpackages().size());
}
@Test(expected = IllegalStateException.class)
public void testNullSaving() {
generator.saveMetamodel(); // no metamodel
}
@Test(expected = IllegalArgumentException.class)
public void testNullStrategy() {
generator.changeSavingStrategy(new CustomPathSavingStrategy()); // has to pass
generator.changeSavingStrategy(null); // throws exception
}
@Test(expected = IllegalArgumentException.class)
public void testIllegalModel() {
generator.generateMetamodelFrom(model); // empty model
}
private void buildMVCPackages() {
ExtractedPackage extractedPackage = new ExtractedPackage("");
extractedPackage.setAsRoot();
model.add(extractedPackage);
model.add(new ExtractedPackage("main"));
model.add(new ExtractedPackage("main.model"));
model.add(new ExtractedPackage("main.view"));
model.add(new ExtractedPackage("main.controller"));
}
} |
package net.openhft.chronicle.bytes;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.Random;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import static net.openhft.chronicle.bytes.StopCharTesters.CONTROL_STOP;
import static net.openhft.chronicle.bytes.StopCharTesters.SPACE_STOP;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/**
* User: peter.lawrey
*/
public class ByteStoreTest {
public static final int SIZE = 128;
private Bytes bytes;
private ByteBuffer byteBuffer;
private BytesStore bytesStore;
@Before
public void beforeTest() {
byteBuffer = ByteBuffer.allocate(SIZE).order(ByteOrder.nativeOrder());
bytesStore = BytesStore.wrap(byteBuffer);
bytes = bytesStore.bytesForWrite();
bytes.clear();
}
@Test
public void testReadIncompleteLong() {
bytes.writeLong(0x0102030405060708L);
assertEquals(0x0102030405060708L, bytes.readIncompleteLong(0));
bytes.clear();
long l = 0;
for (int i = 1; i <= 8; i++) {
bytes.writeUnsignedByte(i);
l |= (long) i << (i * 8 - 8);
assertEquals(l, bytes.readIncompleteLong(0));
}
}
@Test
public void testCAS() {
BytesStore bytes = BytesStore.wrap(ByteBuffer.allocate(100));
bytes.compareAndSwapLong(0, 0L, 1L);
assertEquals(1L, bytes.readLong(0));
}
@Test
public void testRead() {
for (int i = 0; i < bytes.capacity(); i++)
bytes.writeByte(i, i);
bytes.writePosition(bytes.capacity());
for (int i = 0; i < bytes.capacity(); i++)
assertEquals((byte) i, bytes.readByte());
for (int i = (int) (bytes.capacity() - 1); i >= 0; i
assertEquals((byte) i, bytes.readByte(i));
}
}
@Test
public void testReadFully() {
for (int i = 0; i < bytes.capacity(); i++)
bytes.writeByte((byte) i);
byte[] bytes = new byte[(int) this.bytes.capacity()];
this.bytes.read(bytes);
for (int i = 0; i < this.bytes.capacity(); i++)
Assert.assertEquals((byte) i, bytes[i]);
}
@Test
public void testCompareAndSetInt() {
Assert.assertTrue(bytes.compareAndSwapInt(0, 0, 1));
Assert.assertFalse(bytes.compareAndSwapInt(0, 0, 1));
Assert.assertTrue(bytes.compareAndSwapInt(8, 0, 1));
Assert.assertTrue(bytes.compareAndSwapInt(0, 1, 2));
}
@Test
public void testCompareAndSetLong() {
Assert.assertTrue(bytes.compareAndSwapLong(0L, 0L, 1L));
Assert.assertFalse(bytes.compareAndSwapLong(0L, 0L, 1L));
Assert.assertTrue(bytes.compareAndSwapLong(8L, 0L, 1L));
Assert.assertTrue(bytes.compareAndSwapLong(0L, 1L, 2L));
}
@Test
public void testPosition() {
for (int i = 0; i < bytes.capacity(); i++)
bytes.writeByte((byte) i);
for (int i = (int) (bytes.capacity() - 1); i >= 0; i
bytes.readPosition(i);
assertEquals((byte) i, bytes.readByte());
}
}
@Test
public void testCapacity() {
assertEquals(SIZE, bytes.capacity());
assertEquals(10, Bytes.allocateDirect(10).capacity());
}
@Test
public void testRemaining() {
assertEquals(0, bytes.readRemaining());
assertEquals(SIZE, bytes.writeRemaining());
bytes.writePosition(10);
assertEquals(10, bytes.readRemaining());
assertEquals(SIZE - 10, bytes.writeRemaining());
}
@Test
public void testByteOrder() {
assertEquals(ByteOrder.nativeOrder(), bytes.byteOrder());
}
@Test
public void testAppendDouble() throws IOException {
testAppendDouble0(-6.895305375646115E24);
Random random = new Random(1);
for (int i = 0; i < 100000; i++) {
double d = Math.pow(1e32, random.nextDouble()) / 1e6;
if (i % 3 == 0) d = -d;
testAppendDouble0(d);
}
}
private void testAppendDouble0(double d) throws IOException {
bytes.clear();
bytes.append(d).append(' ');
double d2 = bytes.parseDouble();
Assert.assertEquals(d, d2, 0);
/* assumes self terminating.
bytes.clear();
bytes.append(d);
bytes.flip();
double d3 = bytes.parseDouble();
Assert.assertEquals(d, d3, 0);
*/
}
/* @Test
public void testWriteReadBytes() {
byte[] bytes = "Hello World!".getBytes();
this.bytes.write(bytes);
byte[] bytes2 = new byte[bytes.length];
this.bytes.position(0);
this.bytes.read(bytes2);
assertTrue(Arrays.equals(bytes, bytes2));
this.bytes.write(22, bytes);
byte[] bytes3 = new byte[bytes.length];
this.bytes.skipBytes((int) (22 - this.bytes.position()));
assertEquals(bytes3.length, this.bytes.read(bytes3));
assertTrue(Arrays.equals(bytes, bytes3));
this.bytes.position(this.bytes.capacity());
assertEquals(-1, this.bytes.read(bytes3));
}*/
@Test
public void testWriteReadUtf8() {
bytes.writeUtf8(null);
String[] words = "Hello,World!,Bye£€!".split(",");
for (String word : words) {
bytes.writeUtf8(word);
}
assertEquals(null, bytes.readUtf8());
for (String word : words) {
assertEquals(word, bytes.readUtf8());
}
assertEquals(null, bytes.readUtf8());
assertEquals(25, bytes.readPosition()); // check the size
bytes.readPosition(0);
StringBuilder sb = new StringBuilder();
Assert.assertFalse(bytes.readUtf8(sb));
for (String word : words) {
Assert.assertTrue(bytes.readUtf8(sb));
Assert.assertEquals(word, sb.toString());
}
assertFalse(bytes.readUtf8(sb));
Assert.assertEquals("", sb.toString());
}
@Test
public void testWriteReadUTF() {
String[] words = "Hello,World!,Bye£€!".split(",");
for (String word : words) {
bytes.writeUtf8(word);
}
bytes.writeUtf8("");
bytes.writeUtf8(null);
assertEquals(26, bytes.writePosition()); // check the size, more bytes for less strings than writeUtf8
for (String word : words) {
assertEquals(word, bytes.readUtf8());
}
assertEquals("", bytes.readUtf8());
assertEquals(null, bytes.readUtf8());
}
@Test
public void testAppendParseUTF() throws IOException {
String[] words = "Hello,World!,Bye£€!".split(",");
for (String word : words) {
bytes.append(word).append('\t');
}
bytes.append('\t');
for (String word : words) {
assertEquals(word, bytes.parseUTF(CONTROL_STOP));
}
assertEquals("", bytes.parseUTF(CONTROL_STOP));
bytes.readPosition(0);
StringBuilder sb = new StringBuilder();
for (String word : words) {
bytes.parseUTF(sb, CONTROL_STOP);
Assert.assertEquals(word, sb.toString());
}
bytes.parseUTF(sb, CONTROL_STOP);
Assert.assertEquals("", sb.toString());
bytes.readPosition(0);
bytes.skipTo(CONTROL_STOP);
assertEquals(6, bytes.readPosition());
bytes.skipTo(CONTROL_STOP);
assertEquals(13, bytes.readPosition());
Assert.assertTrue(bytes.skipTo(CONTROL_STOP));
assertEquals(23, bytes.readPosition());
Assert.assertTrue(bytes.skipTo(CONTROL_STOP));
assertEquals(24, bytes.readPosition());
Assert.assertFalse(bytes.skipTo(CONTROL_STOP));
}
@Test
public void testWriteReadByteBuffer() {
byte[] bytes = "Hello\nWorld!\r\nBye".getBytes();
this.bytes.write(ByteBuffer.wrap(bytes));
byte[] bytes2 = new byte[bytes.length + 1];
ByteBuffer bb2 = ByteBuffer.wrap(bytes2);
this.bytes.read(bb2);
Assert.assertEquals(bytes.length, bb2.position());
byte[] bytes2b = Arrays.copyOf(bytes2, bytes.length);
Assert.assertTrue(Arrays.equals(bytes, bytes2b));
}
@Test
public void testReadWriteBoolean() {
for (int i = 0; i < 32; i++)
bytes.writeBoolean(i, (i & 3) == 0);
bytes.writePosition(32);
for (int i = 32; i < 64; i++)
bytes.writeBoolean((i & 5) == 0);
for (int i = 0; i < 32; i++)
assertEquals((i & 3) == 0, bytes.readBoolean());
for (int i = 32; i < 64; i++)
assertEquals((i & 5) == 0, bytes.readBoolean(i));
}
@Test
public void testReadWriteShort() {
for (int i = 0; i < 32; i += 2)
bytes.writeShort(i, (short) i);
bytes.writePosition(32);
for (int i = 32; i < 64; i += 2)
bytes.writeShort((short) i);
for (int i = 0; i < 32; i += 2)
assertEquals(i, bytes.readShort());
for (int i = 32; i < 64; i += 2)
assertEquals(i, bytes.readShort(i));
}
@Test
public void testReadWriteStop() {
long[] longs = {Long.MIN_VALUE, Long.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE};
for (long i : longs) {
bytes.writeStopBit(i);
// LOG.info(i + " " + bytes.position());
}
assertEquals(9 + 10, +5 + 6, bytes.writePosition());
for (long i : longs)
assertEquals(i, bytes.readStopBit());
}
@Test
public void testReadWriteUnsignedShort() {
for (int i = 0; i < 32; i += 2)
bytes.writeUnsignedShort(i, (~i) & 0xFFFF);
bytes.writePosition(32);
for (int i = 32; i < 64; i += 2)
bytes.writeUnsignedShort(~i & 0xFFFF);
for (int i = 0; i < 32; i += 2)
assertEquals(~i & 0xFFFF, bytes.readUnsignedShort());
for (int i = 32; i < 64; i += 2)
assertEquals(~i & 0xFFFF, bytes.readUnsignedShort(i));
}
@Test
public void testReadWriteInt() {
for (int i = 0; i < 32; i += 4)
bytes.writeInt(i, i);
bytes.writePosition(32);
for (int i = 32; i < 64; i += 4)
bytes.writeInt(i);
for (int i = 0; i < 32; i += 4)
assertEquals(i, bytes.readInt());
for (int i = 32; i < 64; i += 4)
assertEquals(i, bytes.readInt(i));
}
@Test
public void testReadWriteThreadeSafeInt() {
for (int i = 0; i < 32; i += 4)
bytes.writeOrderedInt(i, i);
bytes.writePosition(32);
for (int i = 32; i < 64; i += 4)
bytes.writeOrderedInt(i);
for (int i = 0; i < 32; i += 4)
assertEquals(i, bytes.readVolatileInt());
for (int i = 32; i < 64; i += 4)
assertEquals(i, bytes.readVolatileInt(i));
}
@Test
public void testReadWriteFloat() {
for (int i = 0; i < 32; i += 4)
bytes.writeFloat(i, i);
bytes.writePosition(32);
for (int i = 32; i < 64; i += 4)
bytes.writeFloat(i);
for (int i = 0; i < 32; i += 4)
assertEquals(i, bytes.readFloat(), 0);
for (int i = 32; i < 64; i += 4)
assertEquals(i, bytes.readFloat(i), 0);
}
@Test
public void testReadWriteUnsignedInt() {
for (int i = 0; i < 32; i += 4)
bytes.writeUnsignedInt(i, ~i & 0xFFFF);
bytes.writePosition(32);
for (int i = 32; i < 64; i += 4)
bytes.writeUnsignedInt(~i & 0xFFFF);
for (int i = 0; i < 32; i += 4)
assertEquals(~i & 0xFFFFL, bytes.readUnsignedInt());
for (int i = 32; i < 64; i += 4)
assertEquals(~i & 0xFFFFL, bytes.readUnsignedInt(i));
}
@Test
public void testReadWriteLong() {
for (long i = 0; i < 32; i += 8)
bytes.writeLong(i, i);
bytes.writePosition(32);
for (long i = 32; i < 64; i += 8)
bytes.writeLong(i);
for (long i = 0; i < 32; i += 8)
assertEquals(i, bytes.readLong());
for (long i = 32; i < 64; i += 8)
assertEquals(i, bytes.readLong(i));
}
@Test
public void testReadWriteThreadSafeLong() {
for (long i = 0; i < 32; i += 8)
bytes.writeOrderedLong(i, i);
bytes.writePosition(32);
for (long i = 32; i < 64; i += 8)
bytes.writeOrderedLong(i);
// LOG.info(bytes.bytes().toDebugString());
for (long i = 0; i < 32; i += 8)
assertEquals(i, bytes.readVolatileLong());
for (long i = 32; i < 64; i += 8)
assertEquals(i, bytes.readVolatileLong(i));
}
@Test
public void testReadWriteDouble() {
for (long i = 0; i < 32; i += 8)
bytes.writeDouble(i, i);
bytes.writePosition(32);
for (long i = 32; i < 64; i += 8)
bytes.writeDouble(i);
for (long i = 0; i < 32; i += 8)
assertEquals(i, bytes.readDouble(), 0);
for (long i = 32; i < 64; i += 8)
assertEquals(i, bytes.readDouble(i), 0);
}
@Test
public void testReadWriteStopBitDouble() {
double[] doubles = {
-Double.MAX_VALUE, Double.NEGATIVE_INFINITY,
Byte.MIN_VALUE, Byte.MAX_VALUE,
Short.MIN_VALUE, Short.MAX_VALUE,
Long.MIN_VALUE, Long.MAX_VALUE,
Integer.MIN_VALUE, Integer.MAX_VALUE};
for (double i : doubles) {
bytes.writeStopBit(i);
System.out.println(i + " " + bytes.writePosition());
}
for (double i : doubles)
assertEquals(i, bytes.readStopBitDouble(), 0.0);
}
@Test
public void testAppendSubstring() throws IOException {
bytes.append("Hello World", 2, 7).append("\n");
assertEquals("Hello World".substring(2, 7), bytes.parseUTF(CONTROL_STOP));
}
@Test
public void testAppendParse() throws IOException {
bytes.append("word£€)").append(' ');
bytes.append(1234).append(' ');
bytes.append(123456L).append(' ');
bytes.append(1.2345).append(' ');
assertEquals("word£€)", bytes.parseUTF(SPACE_STOP));
assertEquals(1234, bytes.parseLong());
assertEquals(123456L, bytes.parseLong());
assertEquals(1.2345, bytes.parseDouble(), 0);
}
@Test
public void testWriteBytes() {
bytes.write("Hello World\n".getBytes(), 0, 10);
bytes.write("good bye\n".getBytes(), 4, 4);
bytes.write(4, "0 w".getBytes());
assertEquals("Hell0 worl bye", bytes.parseUTF(CONTROL_STOP));
}
@Test
@Ignore
public void testStream() throws IOException {
bytes = BytesStore.wrap(ByteBuffer.allocate(1000)).bytesForWrite();
GZIPOutputStream out = new GZIPOutputStream(bytes.outputStream());
out.write("Hello world\n".getBytes());
out.close();
GZIPInputStream in = new GZIPInputStream(bytes.inputStream());
byte[] bytes = new byte[12];
for (int i = 0; i < 12; i++)
bytes[i] = (byte) in.read();
Assert.assertEquals(-1, in.read());
Assert.assertEquals("Hello world\n", new String(bytes));
in.close();
}
@Test
@Ignore
public void testStream2() throws IOException {
OutputStream out = bytes.outputStream();
out.write(11);
out.write(22);
out.write(33);
out.write(44);
out.write(55);
InputStream in = bytes.inputStream();
Assert.assertTrue(in.markSupported());
Assert.assertEquals(11, in.read());
in.mark(1);
assertEquals(1, bytes.readPosition());
Assert.assertEquals(22, in.read());
assertEquals(2, bytes.readPosition());
Assert.assertEquals(33, in.read());
in.reset();
assertEquals(1, bytes.readPosition());
Assert.assertEquals(22, in.read());
Assert.assertEquals(2, in.skip(2));
assertEquals(4, bytes.readPosition());
assertEquals(SIZE - 4, bytes.readRemaining());
Assert.assertEquals(55, in.read());
in.close();
}
@Test
public void testAddAndGet() {
bytesStore = NativeBytesStore.nativeStore(128);
for (int i = 0; i < 10; i++)
bytesStore.addAndGetInt(0L, 10);
assertEquals(100, bytesStore.readInt(0L));
assertEquals(0, bytesStore.readInt(4L));
for (int i = 0; i < 11; i++)
bytesStore.addAndGetInt(4L, 11);
assertEquals(100, bytesStore.readInt(0L));
assertEquals(11 * 11, bytesStore.readInt(4L));
}
@Test
public void testAddAndGetLong() {
bytesStore = NativeBytesStore.nativeStore(128);
for (int i = 0; i < 10; i++)
bytesStore.addAndGetLong(0L, 10);
assertEquals(100, bytesStore.readLong(0L));
assertEquals(0, bytesStore.readLong(8L));
for (int i = 0; i < 11; i++)
bytesStore.addAndGetLong(8L, 11);
assertEquals(100, bytesStore.readLong(0L));
assertEquals(11 * 11, bytesStore.readLong(8L));
}
@Test
public void testAddAndGetFloat() {
bytesStore = NativeBytesStore.nativeStore(128);
for (int i = 0; i < 10; i++)
bytesStore.addAndGetFloat(0L, 10);
assertEquals(100, bytesStore.readFloat(0L), 0f);
assertEquals(0, bytesStore.readVolatileFloat(4L), 0f);
for (int i = 0; i < 11; i++)
bytesStore.addAndGetFloat(4L, 11);
assertEquals(100, bytesStore.readVolatileFloat(0L), 0f);
assertEquals(11 * 11, bytesStore.readFloat(4L), 0f);
}
@Test
public void testAddAndGetDouble() {
bytesStore = NativeBytesStore.nativeStore(128);
for (int i = 0; i < 10; i++)
bytesStore.addAndGetDouble(0L, 10);
assertEquals(100, bytesStore.readDouble(0L), 0.0);
assertEquals(0, bytesStore.readVolatileDouble(8L), 0.0);
for (int i = 0; i < 11; i++)
bytesStore.addAndGetDouble(8L, 11);
assertEquals(100, bytesStore.readVolatileDouble(0L), 0.0);
assertEquals(11 * 11, bytesStore.readDouble(8L), 0.0);
}
@Test
public void testToString() {
Bytes bytes = NativeBytesStore.nativeStore(32).bytesForWrite();
assertEquals("[pos: 0, rlim: 0, wlim: 8EiB, cap: 8EiB ] ", bytes.toDebugString());
bytes.writeUnsignedByte(1);
assertEquals("[pos: 0, rlim: 1, wlim: 8EiB, cap: 8EiB ] ⒈", bytes.toDebugString());
bytes.writeUnsignedByte(2);
bytes.readByte();
assertEquals("[pos: 1, rlim: 2, wlim: 8EiB, cap: 8EiB ] ⒈‖⒉", bytes.toDebugString());
bytes.writeUnsignedByte(3);
assertEquals("[pos: 1, rlim: 3, wlim: 8EiB, cap: 8EiB ] ⒈‖⒉⒊", bytes.toDebugString());
bytes.writeUnsignedByte(4);
bytes.readByte();
assertEquals("[pos: 2, rlim: 4, wlim: 8EiB, cap: 8EiB ] ⒈⒉‖⒊⒋", bytes.toDebugString());
bytes.writeUnsignedByte(5);
assertEquals("[pos: 2, rlim: 5, wlim: 8EiB, cap: 8EiB ] ⒈⒉‖⒊⒋⒌", bytes.toDebugString());
bytes.writeUnsignedByte(6);
bytes.readByte();
assertEquals("[pos: 3, rlim: 6, wlim: 8EiB, cap: 8EiB ] ⒈⒉⒊‖⒋⒌⒍", bytes.toDebugString());
bytes.writeUnsignedByte(7);
assertEquals("[pos: 3, rlim: 7, wlim: 8EiB, cap: 8EiB ] ⒈⒉⒊‖⒋⒌⒍⒎", bytes.toDebugString());
bytes.writeUnsignedByte(8);
assertEquals("[pos: 3, rlim: 8, wlim: 8EiB, cap: 8EiB ] ⒈⒉⒊‖⒋⒌⒍⒎⒏", bytes.toDebugString());
}
} |
package net.sf.jabref.logic.l10n;
import java.util.Locale;
import net.sf.jabref.preferences.JabRefPreferences;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LocalizationTest {
private Locale locale;
@Before
public void storeDefaultLocale() {
locale = Locale.getDefault();
}
@After
public void restoreDefaultLocale() {
Locale.setDefault(locale);
javax.swing.JComponent.setDefaultLocale(locale);
Localization.setLanguage(JabRefPreferences.getInstance().get(JabRefPreferences.LANGUAGE));
}
@Test
public void testSetKnownLanguage() {
Locale.setDefault(Locale.CHINA);
Localization.setLanguage("en");
assertEquals("en", Locale.getDefault().toString());
}
@Test
public void testSetUnknownLanguage() {
Locale.setDefault(Locale.CHINA);
Localization.setLanguage("WHATEVER");
assertEquals("en", Locale.getDefault().toString());
}
@Test
public void testKnownTranslation() {
Localization.setLanguage("en");
String knownKey = "Groups";
assertEquals(knownKey, Localization.lang(knownKey));
String knownValueWithMnemonics = "&Groups";
assertEquals(knownValueWithMnemonics, Localization.menuTitle(knownKey));
}
@Test
public void testKnownTranslationWithCountryModifier() {
Localization.setLanguage("en_US");
String knownKey = "Groups";
assertEquals(knownKey, Localization.lang(knownKey));
String knownValueWithMnemonics = "&Groups";
assertEquals(knownValueWithMnemonics, Localization.menuTitle(knownKey));
}
@Test
public void testUnknownTranslation() {
Localization.setLanguage("en");
String knownKey = "WHATEVER";
assertEquals(knownKey, Localization.lang(knownKey));
assertEquals(knownKey, Localization.menuTitle(knownKey));
}
@Test
public void testUnsetLanguageTranslation() {
String knownKey = "Groups";
assertEquals(knownKey, Localization.lang(knownKey));
String knownValueWithMnemonics = "&Groups";
assertEquals(knownValueWithMnemonics, Localization.menuTitle(knownKey));
}
} |
package org.cryptomator.cryptofs.fh;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.Stream;
import static org.cryptomator.cryptofs.matchers.ByteBufferMatcher.contains;
import static org.cryptomator.cryptofs.util.ByteBuffers.repeat;
import static org.hamcrest.Matchers.is;
public class ChunkDataTest {
private static final int SIZE = 200;
public static Stream<WayToCreateEmptyChunkData> waysToCreateEmptyChunkData() {
return Stream.of(
new CreateEmptyChunkData(),
new WrapEmptyBuffer()
);
}
public static Stream<WayToCreateChunkDataWithContent> waysToCreateChunkDataWithContent() {
return Stream.of(
new WrapBuffer(),
new CreateEmptyChunkDataAndCopyFromBuffer(),
new WrapEmptyBufferAndCopyFromBuffer(),
new WrapPartOfBufferAndCopyRemainingFromBuffer()
);
}
@Test
public void testChunkDataWrappingBufferIsNotDirty() {
ByteBuffer buffer = repeat(3).times(200).asByteBuffer();
ChunkData inTest = ChunkData.wrap(buffer);
Assertions.assertFalse(inTest.isDirty());
}
@Test
public void testEmptyChunkDataIsNotDirty() {
ChunkData inTest = ChunkData.emptyWithSize(200);
Assertions.assertFalse(inTest.isDirty());
}
@Test
public void testWrittenChunkDataIsDirty() {
ChunkData inTest = ChunkData.emptyWithSize(200);
inTest.copyData().from(repeat(3).times(200).asByteBuffer());
Assertions.assertTrue(inTest.isDirty());
}
@Test
public void testToString() {
ChunkData inTest = ChunkData.emptyWithSize(150);
inTest.copyDataStartingAt(50).from(repeat(3).times(50).asByteBuffer());
MatcherAssert.assertThat(inTest.toString(), is("ChunkData(dirty: true, length: 100, capacity: 150)"));
}
@ParameterizedTest
@MethodSource("waysToCreateEmptyChunkData")
public void testAsReadOnlyBufferReturnsEmptyBufferIfEmpty(WayToCreateEmptyChunkData wayToCreateEmptyChunkData) {
ChunkData inTest = wayToCreateEmptyChunkData.create();
MatcherAssert.assertThat(inTest.asReadOnlyBuffer(), contains(new byte[0]));
}
@ParameterizedTest
@MethodSource("waysToCreateChunkDataWithContent")
public void testAsReadOnlyBufferReturnsContent(WayToCreateChunkDataWithContent wayToCreateChunkDataWithContent) {
ChunkData inTest = wayToCreateChunkDataWithContent.create(repeat(3).times(SIZE).asByteBuffer());
MatcherAssert.assertThat(inTest.asReadOnlyBuffer(), contains(repeat(3).times(SIZE).asByteBuffer()));
}
@ParameterizedTest
@MethodSource("waysToCreateChunkDataWithContent")
public void testCopyToCopiesContent(WayToCreateChunkDataWithContent wayToCreateChunkDataWithContent) {
ChunkData inTest = wayToCreateChunkDataWithContent.create(repeat(3).times(SIZE).asByteBuffer());
ByteBuffer target = ByteBuffer.allocate(200);
inTest.copyData().to(target);
target.flip();
MatcherAssert.assertThat(target, contains(repeat(3).times(SIZE).asByteBuffer()));
}
@ParameterizedTest
@MethodSource("waysToCreateEmptyChunkData")
public void testCopyToCopiesNothingIfEmpty(WayToCreateEmptyChunkData wayToCreateEmptyChunkData) {
ChunkData inTest = wayToCreateEmptyChunkData.create();
ByteBuffer target = ByteBuffer.allocate(SIZE);
inTest.copyData().to(target);
MatcherAssert.assertThat(target, contains(repeat(0).times(SIZE).asByteBuffer()));
}
@ParameterizedTest
@MethodSource("waysToCreateChunkDataWithContent")
public void testCopyToWithOffsetCopiesContentFromOffset(WayToCreateChunkDataWithContent wayToCreateChunkDataWithContent) {
int offset = 70;
ChunkData inTest = wayToCreateChunkDataWithContent.create(repeat(3).times(SIZE).asByteBuffer());
ByteBuffer target = ByteBuffer.allocate(SIZE);
inTest.copyDataStartingAt(offset).to(target);
target.limit(SIZE - offset);
target.position(0);
MatcherAssert.assertThat(target, contains(repeat(3).times(SIZE - offset).asByteBuffer()));
target.limit(SIZE);
target.position(SIZE - offset);
MatcherAssert.assertThat(target, contains(repeat(0).times(offset).asByteBuffer()));
}
@Test
public void testRaceConditionsDuringRead() throws InterruptedException {
ByteBuffer src = StandardCharsets.US_ASCII.encode("abcdefg");
ChunkData inTest = ChunkData.wrap(src);
int attempts = 4000;
int threads = 6;
CountDownLatch cdl = new CountDownLatch(attempts);
ExecutorService executor = Executors.newFixedThreadPool(threads);
LongAdder successfulTests = new LongAdder();
for (int i = 0; i < attempts; i++) {
int offset = i % 7;
char expected = "abcdefg".charAt(offset);
executor.execute(() -> {
try {
ByteBuffer dst = ByteBuffer.allocate(1);
inTest.copyDataStartingAt(offset).to(dst);
dst.flip();
char actual = StandardCharsets.US_ASCII.decode(dst).charAt(0);
if (expected == actual) {
successfulTests.increment();
}
} finally {
cdl.countDown();
}
});
}
Assertions.assertTimeoutPreemptively(Duration.ofSeconds(5), () -> cdl.await());
Assertions.assertEquals(attempts, successfulTests.sum());
}
interface WayToCreateEmptyChunkData {
ChunkData create();
}
interface WayToCreateChunkDataWithContent {
ChunkData create(ByteBuffer content);
}
private static class CreateEmptyChunkData implements WayToCreateEmptyChunkData {
@Override
public ChunkData create() {
return ChunkData.emptyWithSize(SIZE);
}
@Override
public String toString() {
return "CreateEmptyChunkData";
}
}
private static class WrapEmptyBuffer implements WayToCreateEmptyChunkData {
@Override
public ChunkData create() {
ByteBuffer buffer = ByteBuffer.allocate(SIZE);
buffer.limit(0);
return ChunkData.wrap(buffer);
}
@Override
public String toString() {
return "WrapEmptyBuffer";
}
}
private static class WrapBuffer implements WayToCreateChunkDataWithContent {
@Override
public ChunkData create(ByteBuffer content) {
return ChunkData.wrap(content);
}
@Override
public String toString() {
return "WrapBuffer";
}
}
private static class CreateEmptyChunkDataAndCopyFromBuffer implements WayToCreateChunkDataWithContent {
@Override
public ChunkData create(ByteBuffer content) {
ChunkData result = ChunkData.emptyWithSize(content.remaining());
result.copyData().from(content);
return result;
}
@Override
public String toString() {
return "CreateEmptyChunkDataAndCopyFromBuffer";
}
}
private static class WrapEmptyBufferAndCopyFromBuffer implements WayToCreateChunkDataWithContent {
@Override
public ChunkData create(ByteBuffer content) {
ByteBuffer buffer = ByteBuffer.allocate(content.remaining());
buffer.limit(0);
ChunkData result = ChunkData.wrap(buffer);
result.copyData().from(content.asReadOnlyBuffer());
return result;
}
@Override
public String toString() {
return "WrapEmptyBufferAndCopyFromBuffer";
}
}
private static class WrapPartOfBufferAndCopyRemainingFromBuffer implements WayToCreateChunkDataWithContent {
@Override
public ChunkData create(ByteBuffer content) {
int position = content.position();
int remaining = content.remaining();
int halfRemaining = remaining / 2;
ByteBuffer readOnlyContent = content.asReadOnlyBuffer();
readOnlyContent.limit(position + halfRemaining);
ByteBuffer wrappedContent = ByteBuffer.allocate(remaining);
wrappedContent.put(readOnlyContent);
wrappedContent.limit(halfRemaining);
ChunkData result = ChunkData.wrap(wrappedContent);
readOnlyContent.limit(position + remaining);
result.copyDataStartingAt(halfRemaining).from(readOnlyContent);
return result;
}
@Override
public String toString() {
return "WrapPartOfBufferAndCopyRemainingFromBuffer";
}
}
} |
package org.jboss.msc.service;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.junit.After;
import org.junit.Before;
/**
* Test base used for service test cases.
*
* @author John E. Bailey
* @author <a href="mailto:flavia.rainone@jboss.com">Flavia Rainone</a>
*/
public class AbstractServiceTest {
protected volatile ServiceContainer serviceContainer;
private boolean shutdownOnTearDown;
@Before
public void setUp() throws Exception {
serviceContainer = ServiceContainer.Factory.create();
shutdownOnTearDown = true;
}
@After
public void tearDown() throws Exception {
if (shutdownOnTearDown) {
serviceContainer.shutdown();
}
serviceContainer = null;
}
/**
* Shutdowns the container.
*/
public void shutdownContainer() {
serviceContainer.shutdown();
shutdownOnTearDown = false;
}
/**
* Asserts that {@code futureController.get()} returns the controller identified by {@code serviceName}, installed in
* {@link serviceContainer}.
*
* @param serviceName the name of the service
* @param futureController future that should compute the ServiceController identified by {@code serviceName},
* installed into {@code serviceContainer}
* @return the {@code ServiceController} returned by {@code futureController}
* @throws InterruptedException exception that may be thrown by {@code futureController.get()} method
* @throws ExecutionException exception that may be thrown by {@code futureController.get()} method
* @throws StartException if {@code ServiceController} contains a StartException, the exception is thrown,
* thus making it easier to identify unexpected failures in the test. For asserting
* expected StartExceptions, see {@link #assertFailure(ServiceName, Future)} and
* {@link #assertFailure(ServiceController, Future)}
*/
protected final ServiceController<?> assertController(ServiceName serviceName, Future<ServiceController<?>> futureController) throws InterruptedException, ExecutionException, StartException {
ServiceController<?> serviceController = futureController.get();
// retrieve the service controller only after future returns
ServiceController<?> expectedServiceController = serviceContainer.getService(serviceName);
assertController(expectedServiceController, serviceController);
return serviceController;
}
/**
* Asserts that {@code futureController.get()} returns the {@code serviceController}, a controller that should have
* been obtained by a previous call to {@link #assertController(ServiceName, Future)}, or by a previous service
* lookup in a {@link ServiceRegistry} instance.
*
* @param serviceController the expected result of {@code futureController.get()}
* @param futureController future that should compute a ServiceController
* @throws InterruptedException exception that may be thrown by {@code futureController.get()} method
* @throws ExecutionException exception that may be thrown by {@code futureController.get()} method
* @throws RuntimeException if {@code futureController} returns {@code null}, a check for whether
* {@code ServiceController} contains a StartException is made. If found, the
* exception is thrown wrapped in a RuntimeException, thus making it easier to
* identify unexpected failures in the test. For asserting expected StartExceptions,
* see {@link #assertFailure(ServiceName, Future)} and
* {@link #assertFailure(ServiceController, Future)}
*/
protected final void assertController(ServiceController<?> serviceController, Future<ServiceController<?>> futureController) throws InterruptedException, ExecutionException{
ServiceController<?> newServiceController = futureController.get();
assertController(serviceController, newServiceController);
}
private final void assertController(ServiceController<?> expectedServiceController, ServiceController<?> serviceController) {
if (serviceController == null) {
if (expectedServiceController.getStartException() != null) {
throw new RuntimeException("Container obtained from futureController is null. ", expectedServiceController.getStartException());
}
fail("Controller obtained from futureController is null. State of expectedServiceController is " + expectedServiceController);
}
assertSame(expectedServiceController, serviceController);
}
/**
* Asserts that {@code serviceFailure.get()} returns a {@code StartException} occurred at the start attempt
* performed by a service named {@code serviceName} installed at {@link serviceContainer}.
*
* @param serviceName the name of the service that is expected to have failed to start
* @param serviceFailure should compute the {@code StartException} thrown by the service
* @return the controller of the service
* @throws InterruptedException exception that may be thrown by {@code futureController.get()} method
* @throws ExecutionException exception that may be thrown by {@code futureController.get()} method
*/
protected final ServiceController<?> assertFailure(ServiceName serviceName, Future<StartException> serviceFailure) throws InterruptedException, ExecutionException {
ServiceController<?> serviceController = serviceContainer.getService(serviceName);
assertNotNull(serviceController);
assertFailure(serviceController, serviceFailure);
return serviceController;
}
/**
* Asserts that {@code serviceFailure.get()} returns a {@code StartException} occurred at the start attempt
* performed by a {@code serviceController}.
*
* @param serviceController controller of the service expected to have failed
* @param serviceFailure should compute the {@code StartException} thrown by the service
* @throws InterruptedException exception that may be thrown by {@code futureController.get()} method
* @throws ExecutionException exception that may be thrown by {@code futureController.get()} method
*/
protected final void assertFailure(ServiceController<?> serviceController, Future<StartException> serviceFailure) throws InterruptedException, ExecutionException {
StartException exception = serviceFailure.get();
assertNotNull("Exception is null, current service state is " + serviceController.getState(), exception);
assertSame(serviceController.getStartException(), exception);
}
/**
* Two opposite notifications are expected from {@code serviceController}. Depending on the order that
* asynchronous tasks are performed, the triggering events of such notifications may occur in an order opposite
* from expected. In this case, no notification occurs, as the events nullify each other.
*
* This method asserts that either both notifications were sent, or that none of them were sent.
*
* @param serviceController the controller of the service
* @param notification1 one of the dependency notifications
* @param notification2 one of the dependency notifications
*/
protected final void assertOppositeNotifications(ServiceController<?> serviceController,
Future<ServiceController<?>> notification1, Future<ServiceController<?>> notification2) throws Exception {
ServiceController<?> serviceController1 = notification1.get();
ServiceController<?> serviceController2 = notification2.get();
assertTrue((serviceController == serviceController1 && serviceController == serviceController2) ||
(serviceController1 == null && serviceController2 == null));
}
} |
package uk.org.taverna.databundle;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.DirectoryStream;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.purl.wf4ever.robundle.Bundle;
public class TestDataBundles {
protected void checkSignature(Path zip) throws IOException {
String MEDIATYPE = "application/vnd.wf4ever.robundle+zip";
// Check position 30++ according to RO Bundle specification
// http://purl.org/wf4ever/ro-bundle#ucf
byte[] expected = ("mimetype" + MEDIATYPE + "PK").getBytes("ASCII");
try (InputStream in = Files.newInputStream(zip)) {
byte[] signature = new byte[expected.length];
int MIME_OFFSET = 30;
assertEquals(MIME_OFFSET, in.skip(MIME_OFFSET));
assertEquals(expected.length, in.read(signature));
assertArrayEquals(expected, signature);
}
}
@Test
public void createList() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path list = DataBundles.getPort(inputs, "in1");
DataBundles.createList(list);
assertTrue(Files.isDirectory(list));
}
@Test
public void getError() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path portIn1 = DataBundles.getPort(inputs, "in1");
DataBundles.setError(portIn1, "Something did not work", "A very\n long\n error\n trace");
ErrorDocument error = DataBundles.getError(portIn1);
assertTrue(error.getCausedBy().isEmpty());
assertEquals("Something did not work", error.getMessage());
// Notice that the lack of trailing \n is preserved
assertEquals("A very\n long\n error\n trace", error.getTrace());
assertEquals(null, DataBundles.getError(null));
}
@Test
public void getErrorCause() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path portIn1 = DataBundles.getPort(inputs, "in1");
Path cause1 = DataBundles.setError(portIn1, "Something did not work", "A very\n long\n error\n trace");
Path portIn2 = DataBundles.getPort(inputs, "in2");
Path cause2 = DataBundles.setError(portIn2, "Something else did not work", "Shorter trace");
Path outputs = DataBundles.getOutputs(dataBundle);
Path portOut1 = DataBundles.getPort(outputs, "out1");
DataBundles.setError(portOut1, "Errors in input", "", cause1, cause2);
ErrorDocument error = DataBundles.getError(portOut1);
assertEquals("Errors in input", error.getMessage());
assertEquals("", error.getTrace());
assertEquals(2, error.getCausedBy().size());
assertTrue(Files.isSameFile(cause1, error.getCausedBy().get(0)));
assertTrue(Files.isSameFile(cause2, error.getCausedBy().get(1)));
}
@Test
public void getInputs() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
assertTrue(Files.isDirectory(inputs));
// Second time should not fail because it already exists
inputs = DataBundles.getInputs(dataBundle);
assertTrue(Files.isDirectory(inputs));
assertEquals(dataBundle.getRoot(), inputs.getParent());
}
@Test
public void getList() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path list = DataBundles.getPort(inputs, "in1");
DataBundles.createList(list);
for (int i = 0; i < 5; i++) {
Path item = DataBundles.newListItem(list);
DataBundles.setStringValue(item, "test" + i);
}
List<Path> paths = DataBundles.getList(list);
assertEquals(5, paths.size());
assertEquals("test0", DataBundles.getStringValue(paths.get(0)));
assertEquals("test4", DataBundles.getStringValue(paths.get(4)));
assertEquals(null, DataBundles.getList(null));
}
@Test
public void getListItem() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path list = DataBundles.getPort(inputs, "in1");
DataBundles.createList(list);
for (int i = 0; i < 5; i++) {
Path item = DataBundles.newListItem(list);
DataBundles.setStringValue(item, "item " + i);
}
// set at next available position
Path item5 = DataBundles.getListItem(list, 5);
assertTrue(item5.getFileName().toString().contains("5"));
DataBundles.setStringValue(item5, "item 5");
// set somewhere later
Path item8 = DataBundles.getListItem(list, 8);
assertTrue(item8.getFileName().toString().contains("8"));
DataBundles.setStringValue(item8, "item 8");
Path item7 = DataBundles.getListItem(list, 7);
assertFalse(Files.exists(item7));
assertFalse(DataBundles.isList(item7));
assertFalse(DataBundles.isError(item7));
assertFalse(DataBundles.isValue(item7));
// TODO: Is it really missing? item1337 is also missing..
assertTrue(DataBundles.isMissing(item7));
// overwrite
Path item2 = DataBundles.getListItem(list, 2);
DataBundles.setStringValue(item2, "replaced");
List<Path> listItems = DataBundles.getList(list);
assertEquals(9, listItems.size());
assertEquals("item 0", DataBundles.getStringValue(listItems.get(0)));
assertEquals("item 1", DataBundles.getStringValue(listItems.get(1)));
assertEquals("replaced", DataBundles.getStringValue(listItems.get(2)));
assertEquals("item 3", DataBundles.getStringValue(listItems.get(3)));
assertEquals("item 4", DataBundles.getStringValue(listItems.get(4)));
assertEquals("item 5", DataBundles.getStringValue(listItems.get(5)));
assertNull(listItems.get(6));
assertNull(listItems.get(7));
assertEquals("item 8", DataBundles.getStringValue(listItems.get(8)));
}
@Test
public void getOutputs() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path outputs = DataBundles.getOutputs(dataBundle);
assertTrue(Files.isDirectory(outputs));
// Second time should not fail because it already exists
outputs = DataBundles.getOutputs(dataBundle);
assertTrue(Files.isDirectory(outputs));
assertEquals(dataBundle.getRoot(), outputs.getParent());
}
@Test
public void getPort() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path portIn1 = DataBundles.getPort(inputs, "in1");
assertFalse(Files.exists(portIn1));
assertEquals(inputs, portIn1.getParent());
}
@Test
public void getPortChecksExtension() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path portIn1 = DataBundles.getPort(inputs, "in1");
assertFalse(Files.exists(portIn1));
Path ref = DataBundles.setReference(portIn1, URI.create("http://example.com/"));
Path portIn1Again = DataBundles.getPort(inputs, "in1");
assertEquals(ref, portIn1Again);
assertFalse(portIn1Again.equals(portIn1));
assertTrue(Files.exists(portIn1Again));
}
@Test
public void getListItemChecksExtension() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path portIn1 = DataBundles.getPort(inputs, "in1");
Path list = DataBundles.newListItem(portIn1);
Path item = DataBundles.newListItem(list);
Path ref = DataBundles.setReference(item, URI.create("http://example.com/"));
Path itemAgain = DataBundles.getListItem(list, 0);
assertEquals(ref, itemAgain);
assertFalse(itemAgain.equals(portIn1));
assertTrue(Files.exists(itemAgain));
}
@Test
public void getPorts() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
DataBundles.createList(DataBundles.getPort(inputs, "in1"));
DataBundles.createList(DataBundles.getPort(inputs, "in2"));
DataBundles.setStringValue(DataBundles.getPort(inputs, "value"),
"A value");
Map<String, Path> ports = DataBundles.getPorts(DataBundles
.getInputs(dataBundle));
assertEquals(3, ports.size());
// System.out.println(ports);
assertTrue(ports.containsKey("in1"));
assertTrue(ports.containsKey("in2"));
assertTrue(ports.containsKey("value"));
assertEquals("A value", DataBundles.getStringValue(ports.get("value")));
}
@Test
public void hasInputs() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
assertFalse(DataBundles.hasInputs(dataBundle));
DataBundles.getInputs(dataBundle); // create on demand
assertTrue(DataBundles.hasInputs(dataBundle));
}
@Test
public void hasOutputs() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
assertFalse(DataBundles.hasOutputs(dataBundle));
DataBundles.getInputs(dataBundle); // independent
assertFalse(DataBundles.hasOutputs(dataBundle));
DataBundles.getOutputs(dataBundle); // create on demand
assertTrue(DataBundles.hasOutputs(dataBundle));
}
@Test
public void isError() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path portIn1 = DataBundles.getPort(inputs, "in1");
DataBundles.setError(portIn1, "Something did not work", "A very\n long\n error\n trace");
assertFalse(DataBundles.isList(portIn1));
assertFalse(DataBundles.isValue(portIn1));
assertFalse(DataBundles.isMissing(portIn1));
assertFalse(DataBundles.isReference(portIn1));
assertTrue(DataBundles.isError(portIn1));
}
@Test
public void isList() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path list = DataBundles.getPort(inputs, "in1");
DataBundles.createList(list);
assertTrue(DataBundles.isList(list));
assertFalse(DataBundles.isValue(list));
assertFalse(DataBundles.isError(list));
assertFalse(DataBundles.isReference(list));
assertFalse(DataBundles.isMissing(list));
}
@Test
public void isMissing() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path portIn1 = DataBundles.getPort(inputs, "in1");
assertFalse(DataBundles.isList(portIn1));
assertFalse(DataBundles.isValue(portIn1));
assertFalse(DataBundles.isError(portIn1));
assertTrue(DataBundles.isMissing(portIn1));
assertFalse(DataBundles.isReference(portIn1));
}
@Test
public void isValueOnError() throws Exception {
Bundle bundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(bundle);
DataBundles.setError(DataBundles.getPort(inputs, "test"),
"error", "");
assertFalse(DataBundles.isValue(DataBundles.getPorts(inputs).get("test")));
}
@Test
public void isValueOnReference() throws Exception {
Bundle bundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(bundle);
DataBundles.setReference(DataBundles.getPort(inputs, "test"), URI.create("http:
assertFalse(DataBundles.isValue(DataBundles.getPorts(inputs).get("test")));
}
@Test
public void listOfLists() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path list = DataBundles.getPort(inputs, "in1");
DataBundles.createList(list);
Path sublist0 = DataBundles.newListItem(list);
DataBundles.createList(sublist0);
Path sublist1 = DataBundles.newListItem(list);
DataBundles.createList(sublist1);
assertEquals(Arrays.asList("0/", "1/"), ls(list));
DataBundles.setStringValue(DataBundles.newListItem(sublist1),
"Hello");
assertEquals(Arrays.asList("0"), ls(sublist1));
assertEquals("Hello",DataBundles.getStringValue(
DataBundles.getListItem(DataBundles.getListItem(list, 1), 0)));
}
protected List<String> ls(Path path) throws IOException {
List<String> paths = new ArrayList<>();
try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
for (Path p : ds) {
paths.add(p.getFileName() + "");
}
}
Collections.sort(paths);
return paths;
}
@Test
public void newListItem() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path list = DataBundles.getPort(inputs, "in1");
DataBundles.createList(list);
Path item0 = DataBundles.newListItem(list);
assertEquals(list, item0.getParent());
assertTrue(item0.getFileName().toString().contains("0"));
assertFalse(Files.exists(item0));
DataBundles.setStringValue(item0, "test");
Path item1 = DataBundles.newListItem(list);
assertTrue(item1.getFileName().toString().contains("1"));
// Because we've not actually created item1 yet
assertEquals(item1, DataBundles.newListItem(list));
DataBundles.setStringValue(item1, "test");
// Check that DataBundles.newListItem can deal with gaps
Files.delete(item0);
Path item2 = DataBundles.newListItem(list);
assertTrue(item2.getFileName().toString().contains("2"));
// Check that non-numbers don't interfere
Path nonumber = list.resolve("nonumber");
Files.createFile(nonumber);
item2 = DataBundles.newListItem(list);
assertTrue(item2.getFileName().toString().contains("2"));
// Check that extension is stripped
Path five = list.resolve("5.txt");
Files.createFile(five);
Path item6 = DataBundles.newListItem(list);
assertTrue(item6.getFileName().toString().contains("6"));
}
@Test(expected=FileAlreadyExistsException.class)
public void newListAlreadyExistsAsFile() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path list = DataBundles.getPort(inputs, "in1");
Files.createFile(list);
assertTrue(Files.isRegularFile(list));
DataBundles.setStringValue(list, "A string");
assertTrue(Files.isRegularFile(list));
assertFalse(Files.isDirectory(list));
DataBundles.createList(list);
}
@Test
public void setErrorArgs() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path portIn1 = DataBundles.getPort(inputs, "in1");
Path errorPath = DataBundles.setError(portIn1, "Something did not work", "A very\n long\n error\n trace");
assertEquals("in1.err", errorPath.getFileName().toString());
List<String> errLines = Files.readAllLines(errorPath, Charset.forName("UTF-8"));
assertEquals(6, errLines.size());
assertEquals("", errLines.get(0));
assertEquals("Something did not work", errLines.get(1));
assertEquals("A very", errLines.get(2));
assertEquals(" long", errLines.get(3));
assertEquals(" error", errLines.get(4));
assertEquals(" trace", errLines.get(5));
}
@Test
public void setErrorCause() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path portIn1 = DataBundles.getPort(inputs, "in1");
Path cause1 = DataBundles.setError(portIn1, "Something did not work", "A very\n long\n error\n trace");
Path portIn2 = DataBundles.getPort(inputs, "in2");
Path cause2 = DataBundles.setError(portIn2, "Something else did not work", "Shorter trace");
Path outputs = DataBundles.getOutputs(dataBundle);
Path portOut1 = DataBundles.getPort(outputs, "out1");
Path errorPath = DataBundles.setError(portOut1, "Errors in input", "", cause1, cause2);
List<String> errLines = Files.readAllLines(errorPath, Charset.forName("UTF-8"));
assertEquals("../inputs/in1.err", errLines.get(0));
assertEquals("../inputs/in2.err", errLines.get(1));
assertEquals("", errLines.get(2));
}
@Test
public void setErrorObj() throws Exception {
Bundle dataBundle = DataBundles.createBundle();
Path inputs = DataBundles.getInputs(dataBundle);
Path portIn1 = DataBundles.getPort(inputs, "in1");
Path cause1 = DataBundles.setError(portIn1, "a", "b");
Path portIn2 = DataBundles.getPort(inputs, "in2");
Path cause2 = DataBundles.setError(portIn2, "c", "d");
Path outputs = DataBundles.getOutputs(dataBundle);
Path portOut1 = DataBundles.getPort(outputs, "out1");
ErrorDocument error = new ErrorDocument();
error.getCausedBy().add(cause1);
error.getCausedBy().add(cause2);
error.setMessage("Something did not work");
error.setTrace("Here\nis\nwhy\n");
Path errorPath = DataBundles.setError(portOut1, error);
assertEquals("out1.err", errorPath.getFileName().toString());
List<String> errLines = Files.readAllLines(errorPath, Charset.forName("UTF-8"));
assertEquals(8, errLines.size());
assertEquals("../inputs/in1.err", errLines.get(0));
assertEquals("../inputs/in2.err", errLines.get(1));
assertEquals("", errLines.get(2));
assertEquals("Something did not work", errLines.get(3));
assertEquals("Here", errLines.get(4));
assertEquals("is", errLines.get(5));
assertEquals("why", errLines.get(6));
assertEquals("", errLines.get(7));
}
} |
package org.tensorics.core.lang;
import static org.junit.Assert.*;
import static org.tensorics.core.fields.doubles.Structures.doubles;
import static org.tensorics.core.tensor.lang.TensorStructurals.from;
import static org.tensorics.core.util.SystemState.currentTimeAfterGc;
import static org.tensorics.core.util.SystemState.currentTimeBeforeGc;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.measure.unit.SI;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.tensorics.core.fields.doubles.Structures;
import org.tensorics.core.quantity.ImmutableQuantifiedValue;
import org.tensorics.core.quantity.QuantifiedValue;
import org.tensorics.core.tensor.ImmutableTensor;
import org.tensorics.core.tensor.ImmutableTensor.Builder;
import org.tensorics.core.tensor.Position;
import org.tensorics.core.tensor.Tensor;
import org.tensorics.core.tensor.Tensor.Entry;
import org.tensorics.core.tensor.lang.TensorStructurals;
import org.tensorics.core.units.JScienceUnit;
import org.tensorics.core.units.Unit;
import org.tensorics.core.util.SystemState;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
/**
* @author agorzaws
*/
public class TensorCalculationsTest {
private static final int Z_COOR_NUMBER = 1;
private static final int Y_COOR_NUMBER = 2;
private static final int X_COOR_NUMBER = 512;
private Tensor<Double> tensor1;
private Tensor<Boolean> tensor1Flags;
private Tensor<Double> tensor2;
private Tensor<Double> tensor3Big;
private TensoricSupport<Double> tensoricFieldUsage;
@Before
public void setUp() throws Exception {
tensoricFieldUsage = Tensorics.using(Structures.doubles());
tensor1 = prepareValues(1.0);
tensor1Flags = prepareOnlyEvenValuesTrueFlag();
tensor2 = prepareValues(2.5);
System.out.println("============== <<<<<<<<<< NEXT TEST >>>>>>>>>> =============");
}
@Test
public void averageOverOneDimensionOnValue1() {
YCoordinate y = YCoordinate.of(1);
Tensor<Double> averagedOverX = TensorStructurals.from(tensor1).reduce(XCoordinate.class)
.byAveragingIn(doubles());
assertEquals(4.5, averagedOverX.get(Position.of(y)), 0.0);
}
@Test
public void averageOverOneDimensionKeepingOther() {
Tensor<Double> averageOverYCoordinte = TensorStructurals.from(tensor1).reduce(XCoordinate.class)
.byAveragingIn(doubles());
assertEquals(tensor1.shape().dimensionSet().size() - 1, averageOverYCoordinte.shape().dimensionSet().size());
Set<YCoordinate> coordinateValues = TensorStructurals.from(averageOverYCoordinte).extractCoordinatesOfType(
YCoordinate.class);
assertEquals(10, coordinateValues.size());
}
@Test
public void testMultiplyByNumber() {
YCoordinate y = YCoordinate.of(1);
XCoordinate x = XCoordinate.of(3);
Tensor<Double> tensor = tensoricFieldUsage.calculate(tensor1).elementTimesV(-1.0);
assertEquals(-3, tensor.get(x, y).doubleValue(), 0.0);
}
@Test
public void testDivideByNumber() {
YCoordinate y = YCoordinate.of(1);
XCoordinate x = XCoordinate.of(3);
Tensor<Double> tensor = tensoricFieldUsage.calculate(tensor1).elementDividedByV(2.0);
assertEquals(1.5, tensor.get(x, y).doubleValue(), 0.0);
}
@Test
public void testRMSCalculation() {
YCoordinate y = YCoordinate.of(1);
double rms = TensorStructurals.from(tensor1).reduce(XCoordinate.class).byRmsIn(doubles()).get(y);
assertEquals(5.33, rms, 0.01);
double rms2 = TensorStructurals.from(tensor1).reduce(XCoordinate.class).byRmsIn(doubles()).get(Position.of(y));
assertEquals(5.33, rms2, 0.01);
}
@Test(expected = NoSuchElementException.class)
public void testRMSCalculationTooManyCoordiantes() {
YCoordinate y = YCoordinate.of(1);
XCoordinate x = XCoordinate.of(2);
double rms = TensorStructurals.from(tensor1).reduce(XCoordinate.class).byRmsIn(doubles()).get(x, y);
assertEquals(5.33, rms, 0.01);
}
@Test
public void testMeanCalculation() {
YCoordinate y = YCoordinate.of(1);
double mean2 = TensorStructurals.from(TensorStructurals.from(tensor1).extractSliceAt(y))
.reduce(XCoordinate.class).byAveragingIn(doubles()).get(Position.empty());
assertEquals(4.5, mean2, 0.0);
}
@Test
public void testAddition() {
YCoordinate y = YCoordinate.of(2);
XCoordinate x = XCoordinate.of(6);
Tensor<Double> tensor = tensoricFieldUsage.calculate(tensor1).plus(tensor1);
assertEquals(24.0, tensor.get(x, y).doubleValue(), 0.0);
}
@Test
public void testSubtraction() {
YCoordinate y = YCoordinate.of(2);
XCoordinate x = XCoordinate.of(6);
Tensor<Double> tensor = tensoricFieldUsage.calculate(tensor1).minus(tensor1);
assertEquals(0.0, tensor.get(x, y).doubleValue(), 0.0);
}
@Test
public void testFluentAddition() {
YCoordinate y = YCoordinate.of(2);
XCoordinate x = XCoordinate.of(6);
Tensor<Double> tensor = tensoricFieldUsage.calculate(tensor1).plus(tensor1);
assertEquals(24.0, tensor.get(x, y).doubleValue(), 0.0);
}
@Test
public void testAdditionOf2elementsTo100WithResult2() {
YCoordinate y = YCoordinate.of(2);
XCoordinate x = XCoordinate.of(6);
XCoordinate x2 = XCoordinate.of(3);
Builder<Double> builder = ImmutableTensor.builder(ImmutableSet.of(y.getClass(), x.getClass()));
builder.at(Position.of(ImmutableSet.of(x, y))).put(13.2);
builder.at(Position.of(ImmutableSet.of(x2, y))).put(-1.2);
Tensor<Double> testTensor = builder.build();
Tensor<Double> tensor = tensoricFieldUsage.calculate(tensor1).plus(testTensor);
assertEquals(25.2, tensor.get(x, y).doubleValue(), 0.0);
}
@Test
public void testAdditionOf2elementsTo2() {
YCoordinate y = YCoordinate.of(2);
XCoordinate x = XCoordinate.of(6);
XCoordinate x2 = XCoordinate.of(3);
Builder<Double> builder = ImmutableTensor.builder(ImmutableSet.of(y.getClass(), x.getClass()));
builder.at(Position.of(ImmutableSet.of(x, y))).put(13.2);
builder.at(Position.of(ImmutableSet.of(x2, y))).put(-1.2);
Tensor<Double> testTensor = builder.build();
Builder<Double> builder2 = ImmutableTensor.builder(ImmutableSet.of(y.getClass(), x.getClass()));
builder2.at(Position.of(ImmutableSet.of(x, y))).put(1.2);
builder2.at(Position.of(ImmutableSet.of(x2, y))).put(1.2);
Tensor<Double> testTensor2 = builder2.build();
Tensor<Double> tensor = tensoricFieldUsage.calculate(testTensor).plus(testTensor2);
assertEquals(14.4, tensor.get(x, y).doubleValue(), 0.001);
}
@Test
public void testFlagApplience() {
Tensor<Double> tensor = from(tensor1).extractWhereTrue(tensor1Flags);
YCoordinate y = YCoordinate.of(2);
XCoordinate x = XCoordinate.of(6);
assertEquals(12.0, tensor.get(Position.of(ImmutableSet.of(x, y))).doubleValue(), 0.0);
assertEquals(5, TensorStructurals.from(tensor).extractCoordinatesOfType(x.getClass()).size());
}
@Test(expected = NoSuchElementException.class)
public void testFlagApplienceFailure() {
Tensor<Double> tensor = from(tensor1).extractWhereTrue(tensor1Flags);
YCoordinate y = YCoordinate.of(2);
XCoordinate x = XCoordinate.of(7);
assertEquals(14.0, tensor.get(x, y).doubleValue(), 0.0);
}
@Test
public void testAdditionFrom2elementsTo100WithWrongShapes() {
XCoordinate x = XCoordinate.of(6);
XCoordinate x2 = XCoordinate.of(3);
Builder<Double> builder = ImmutableTensor.builder(ImmutableSet.<Class<? extends TestCoordinate>> of(x
.getClass()));
double x1Add = 13.2;
double x2Add = -1.2;
builder.at(Position.of(x)).put(x1Add);
builder.at(Position.of(x2)).put(x2Add);
Tensor<Double> testTensor = builder.build();
Tensor<Double> result = tensoricFieldUsage.calculate(tensor1).plus(testTensor);
/*
* from broadcasting the y dimension of the test tensor to the values of tensor1 (10 values) together with the
* two x-coordinates, we expect a tensor of sixe 20.
*/
assertEquals(20, result.shape().size());
checkCorrectlyAdded(x, x1Add, result);
checkCorrectlyAdded(x2, x2Add, result);
}
private void checkCorrectlyAdded(XCoordinate x, double x1Add, Tensor<Double> result) {
for (Entry<Double> entry : result.entrySet()) {
Position position = entry.getPosition();
if (x.equals(position.coordinateFor(XCoordinate.class))) {
assertEquals(tensor1.get(position) + x1Add, entry.getValue(), 0.0000001);
}
}
}
@Test(expected = IllegalStateException.class)
public void testReductionOnNonExistingCoordinate() {
TensorStructurals.from(tensor1).extractSliceAt(ZCoordinate.of(1));
}
@Test
public void testOperationsOnBig512x2x1Tensor() {
long totalDiff = calculateOnTensor(X_COOR_NUMBER, Y_COOR_NUMBER, Z_COOR_NUMBER, true);
assertTrue(totalDiff < 700);
}
@Test
@Ignore
public void profileTensorPreparation() {
int maxY = 1000;
int step = 100;
int nX = 100;
int nZ = 1;
populateCaches(maxY);
populatePositionCache(nX, maxY, nZ);
List<ProfileResult> results = new ArrayList<>();
for (int nY = step; nY <= maxY; nY += step) {
results.add(profileTensorPreparation(nX, nY, nZ));
}
printProfileResult(results);
}
private void printProfileResult(List<ProfileResult> results) {
System.out.println("Step \tSize \ttime [ms] \tmem [byte]");
int step = 0;
for (ProfileResult result : results) {
SystemState stateDiff = result.systemStateDiff;
System.out.println(step++ + "\t" + result.tensorSize + "\t" + stateDiff.getTimeInMillis() + "\t"
+ stateDiff.getMemoryUsageInB());
}
}
@Ignore
@Test
public void profilePositionMapPreparation() {
int maxY = 1000;
int step = 100;
int nX = 100;
int nZ = 1;
populateCaches(maxY);
populatePositionCache(nX, maxY, nZ);
List<ProfileResult> results = new ArrayList<>();
for (int nY = step; nY <= maxY; nY += step) {
results.add(profileMapPreparation(nX, nY, nZ));
}
printProfileResult(results);
}
@Test
@Ignore
public void profileSimpleMapPopulation() {
int maxValue = 100000;
int step = 10000;
populateCaches(maxValue);
List<ProfileResult> results = new ArrayList<>();
for (int i = step; i <= maxValue; i += step) {
results.add(profileXCoordinateMap(i));
}
printProfileResult(results);
}
private ProfileResult profileXCoordinateMap(int size) {
System.out.println("Map preparation preparation of size=" + size + ":");
SystemState initialState = currentTimeAfterGc();
Map<XCoordinate, Double> map = createImmutableMapOfSize(size);
SystemState stateDiff = currentTimeAfterGc().minus(initialState);
stateDiff.printToStdOut();
return new ProfileResult(map.size(), stateDiff);
}
private Map<XCoordinate, Double> createHashMapOfSize(int size) {
Map<XCoordinate, Double> map = new HashMap<>();
for (int i = 0; i < size; i++) {
map.put(XCoordinate.of(i), valueForBig(i, i, i, 2.0));
}
return map;
}
private Map<XCoordinate, Double> createImmutableMapOfSize(int size) {
ImmutableMap.Builder<XCoordinate, Double> builder = ImmutableMap.builder();
for (int i = 0; i < size; i++) {
builder.put(XCoordinate.of(i), valueForBig(i, i, i, 2.0));
}
return builder.build();
}
private void populateCaches(int maxValue) {
for (int i = 0; i <= maxValue; i++) {
XCoordinate.of(i);
YCoordinate.of(i);
ZCoordinate.of(i);
}
}
private void populatePositionCache(int nX, int nY, int nZ) {
for (int i = 0; i <= nX; i++) {
for (int j = 0; j <= nY; j++) {
for (int k = 0; k <= nZ; k++) {
Position.of(coordinatesFor(i, j, k));
}
}
}
}
private ProfileResult profileTensorPreparation(int nX, int nY, int nZ) {
System.out.println("Tensor preparation for " + nX + "x" + nY + "x" + nZ + ":");
SystemState initialState = currentTimeAfterGc();
Tensor<Double> tensor = prepareValuesForBig(nX, nY, nZ, 2.0);
SystemState stateDiff = currentTimeBeforeGc().minus(initialState);
stateDiff.printToStdOut();
System.out.println("Tensor size:" + tensor.shape().size());
return new ProfileResult(tensor.shape().size(), stateDiff);
}
private ProfileResult profileMapPreparation(int nX, int nY, int nZ) {
System.out.println("Map preparation for " + nX + "x" + nY + "x" + nZ + ":");
SystemState initialState = currentTimeAfterGc();
Map<Position, Double> map = prepareMap(nX, nY, nZ);
SystemState stateDiff = currentTimeAfterGc().minus(initialState);
stateDiff.printToStdOut();
System.out.println("Map size:" + map.size());
return new ProfileResult(map.size(), stateDiff);
}
@Ignore
@Test
public void profileRepetitiveMap() {
List<ProfileResult> results = profileMapNTimes(10);
printProfileResult(results);
}
@Ignore
@Test
public void profileSimpleRepetitiveTensor() {
CoordinateRange range = CoordinateRange.fromSize(TensorSize.ofXYZ(400, 500, 1));
System.out.println("Created range");
List<ProfileResult> results = profileTensorCreationNTimes(5, range, new ValueFactory<Double>() {
@Override
public Double create(int x, int y, int z) {
return valueForBig(x, y, z, 2.0);
}
});
printProfileResult(results);
}
@Ignore
@Test
public void profileQuantifiedRepetitiveTensor() {
final Unit unit = JScienceUnit.of(SI.METER);
CoordinateRange range = CoordinateRange.fromSize(TensorSize.ofXYZ(100, 1000, 1));
List<ProfileResult> results = profileTensorCreationNTimes(10, range,
new ValueFactory<QuantifiedValue<Double>>() {
@Override
public QuantifiedValue<Double> create(int x, int y, int z) {
return ImmutableQuantifiedValue.of(valueForBig(x, y, z, 2.0), unit).withError(0.0);
}
});
printProfileResult(results);
}
public List<ProfileResult> profileMapNTimes(int nTimes) {
List<Map<Position, Double>> maps = new ArrayList<>();
List<ProfileResult> results = new ArrayList<>();
for (int i = 0; i < nTimes; i++) {
SystemState initialState = currentTimeAfterGc();
Map<Position, Double> map = prepareMap(100, 1000, 1);
SystemState stateDiff = currentTimeAfterGc().minus(initialState);
stateDiff.printToStdOut();
System.out.println("Map size:" + map.size());
results.add(new ProfileResult(map.size(), stateDiff));
maps.add(map);
}
return results;
}
public <V> List<ProfileResult> profileTensorCreationNTimes(int nTimes, CoordinateRange range,
ValueFactory<V> factory) {
List<Tensor<V>> tensors = new ArrayList<>();
List<ProfileResult> results = new ArrayList<>();
for (int i = 0; i < nTimes; i++) {
SystemState initialState = currentTimeAfterGc();
Tensor<V> tensor = createTensor(range, factory);
SystemState stateDiff = currentTimeBeforeGc().minus(initialState);
stateDiff.printToStdOut();
int size = tensor.shape().size();
System.out.println("Tensor size:" + size);
results.add(new ProfileResult(size, stateDiff));
tensors.add(tensor);
}
return results;
}
private interface TensorFactory<V> {
Tensor<V> create();
}
private Map<Position, Double> prepareMap(int nX, int nY, int nZ) {
Map<Position, Double> map = new HashMap<>();
for (int i = 0; i < nX; i++) {
for (int j = 0; j < nY; j++) {
for (int k = 0; k < nZ; k++) {
map.put(Position.of(coordinatesFor(i, j, k)), valueForBig(i, j, k, 2.0));
}
}
}
return map;
}
private static class ProfileResult {
private final SystemState systemStateDiff;
private final int tensorSize;
public ProfileResult(int tensorSize, SystemState systemStateDiff) {
super();
this.tensorSize = tensorSize;
this.systemStateDiff = systemStateDiff;
}
}
@Test
public void testOperationsOnBig1024x2x2Tensor() {
long totalDiff = calculateOnTensor(X_COOR_NUMBER * 2, Y_COOR_NUMBER, Z_COOR_NUMBER * 2, true);
assertTrue(totalDiff < 4000);
}
@Test
public void testSimpleTensoricsTask() {
Tensor<Double> result = new TensoricTask<Double, Tensor<Double>>(EnvironmentImpl.of(doubles(),
ManipulationOptions.defaultOptions(doubles()))) {
@Override
public Tensor<Double> run() {
return calculate(tensor1).plus(tensor2);
}
}.run();
assertEquals(100, result.shape().size());
}
private long calculateOnTensor(int xCoorNumber, int yCoorNumber, int zCoorNumber, boolean printLog) {
long memoryBefore = getMemoryUsage();
SimpleDateFormat sdf = new SimpleDateFormat("hh:MM:ss.SSS");
Date date = new Date();
int nbOfElements = xCoorNumber * yCoorNumber * zCoorNumber;
if (printLog) {
System.out.println(" Creation of [" + xCoorNumber + "," + yCoorNumber + "," + zCoorNumber
+ "] (total nb of elements: " + nbOfElements + ")\t" + sdf.format(date));
}
tensor3Big = prepareValuesForBig(xCoorNumber, yCoorNumber, zCoorNumber, 1.0);
System.out.println("used memory :" + (getMemoryUsage() - memoryBefore));
YCoordinate y = YCoordinate.of(0);
XCoordinate x = XCoordinate.of(0);
ZCoordinate z = ZCoordinate.of(0);
Date date2 = new Date();
if (printLog) {
System.out.println("done after (" + (date2.getTime() - date.getTime())
+ "ms); \n Multiplying (base*(-1))\t" + sdf.format(date2));
}
Tensor<Double> inversedTensor = tensoricFieldUsage.negativeOf(tensor3Big);
Date date3 = new Date();
if (printLog) {
System.out.println("done after (" + (date3.getTime() - date2.getTime())
+ "ms); \n Adding (base*(-1) to base)\t" + sdf.format(date3));
}
Tensor<Double> tensorOut = tensoricFieldUsage.calculate(tensor3Big).plus(inversedTensor);
Date date4 = new Date();
if (printLog) {
System.out.println("Done \t" + sdf.format(date4) + " (" + (date4.getTime() - date3.getTime()) + "ms)");
}
assertEquals(0.0, tensorOut.get(x, y, z).doubleValue(), 0.0);
Date date5 = new Date();
if (printLog) {
System.out.println("get value at [0,0,0] \t" + sdf.format(date5) + " done after ("
+ (date5.getTime() - date4.getTime()) + "ms)");
}
TensorStructurals.from(TensorStructurals.from(tensorOut).extractSliceAt(z, y)).reduce(XCoordinate.class)
.byAveragingIn(doubles());
Date date6 = new Date();
if (printLog) {
System.out.println("get mean on [x,0,0] \t" + sdf.format(date6) + " done after ("
+ (date6.getTime() - date5.getTime()) + "ms)");
}
// Tensors.getRmsOf(tensorOut).slicingAt(ImmutableSet.of(y, z));
TensorStructurals.from(tensorOut).reduce(XCoordinate.class).byRmsIn(doubles()).get(y, z);
Date date7 = new Date();
if (printLog) {
System.out.println("get rms on [x,0,0] \t" + sdf.format(date7) + " done after ("
+ (date7.getTime() - date6.getTime()) + "ms)");
}
long totalDiff = date7.getTime() - date2.getTime();
if (printLog) {
System.out.println("Total (since first calc) done after (" + totalDiff + "ms)");
System.out.println("used memory :" + (getMemoryUsage() - memoryBefore));
System.out.println("=====================================");
}
return totalDiff;
}
public long getMemoryUsage() {
for (int i = 0; i < 10; i++) {
System.gc(); // NOSONAR benchmarking code
}
int kb = 1024;
Runtime runtime = Runtime.getRuntime();
// Print used memory
long usedMemoryinKb = (runtime.totalMemory() - runtime.freeMemory()) / kb;
return usedMemoryinKb;
}
@SuppressWarnings("boxing")
private Tensor<Double> prepareValues(double factor) {
ImmutableSet<Class<? extends TestCoordinate>> dimensions = ImmutableSet
.of(XCoordinate.class, YCoordinate.class);
Builder<Double> builder = ImmutableTensor.builder(dimensions);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
builder.at(Position.of(coordinatesFor(i, j))).put(valueFor(i, j, factor));
}
}
return builder.build();
}
private Tensor<Boolean> prepareOnlyEvenValuesTrueFlag() {
ImmutableSet<Class<? extends TestCoordinate>> dimensions = ImmutableSet
.of(XCoordinate.class, YCoordinate.class);
Builder<Boolean> builder = ImmutableTensor.builder(dimensions);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
builder.at(Position.of(coordinatesFor(i, j))).put(flagFor(i, j));
}
}
return builder.build();
}
private Boolean flagFor(int i, int j) {
if (i % 2 == 0 && j % 2 == 0) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
private double valueFor(int i, int j, double factor) {
return j * i * factor;
}
private Set<TestCoordinate> coordinatesFor(int i, int j) {
Set<TestCoordinate> coordinates = new HashSet<>();
coordinates.add(XCoordinate.of(i));
coordinates.add(YCoordinate.of(j));
return coordinates;
}
private Set<TestCoordinate> coordinatesFor(int i, int j, int k) {
Set<TestCoordinate> coordinates = coordinatesFor(i, j);
coordinates.add(ZCoordinate.of(k));
return coordinates;
}
@SuppressWarnings("boxing")
private Tensor<Double> prepareValuesForBig(int Nx, int Ny, int Nz, final double factor) {
final CoordinateRange range = CoordinateRange.fromSize(TensorSize.ofXYZ(Nx, Ny, Nz));
return createTensor(range, new ValueFactory<Double>() {
@Override
public Double create(int x, int y, int z) {
return valueForBig(x, y, z, factor);
}
});
}
private <V> Tensor<V> createTensor(CoordinateRange range, ValueFactory<V> factory) {
ImmutableSet<Class<? extends TestCoordinate>> dimensions = ImmutableSet.of(XCoordinate.class,
YCoordinate.class, ZCoordinate.class);
Builder<V> builder = ImmutableTensor.builder(dimensions);
for (XCoordinate x : range.getxCoordinates()) {
for (YCoordinate y : range.getyCoordinates()) {
for (ZCoordinate z : range.getzCoordinates()) {
builder.putValueAt(factory.create(x.getValue(), y.getValue(), z.getValue()), Position.of(x, y, z));
}
}
}
return builder.build();
}
interface ValueFactory<V> {
V create(int x, int y, int z);
}
private double valueForBig(int i, int j, int k, double factor) {
return j * i * k * factor;
}
} |
package com.appspot.relaxe.rpc;
import com.appspot.relaxe.types.IntegerType;
import com.appspot.relaxe.types.PrimitiveType;
public class IntegerHolder
extends AbstractPrimitiveHolder<Integer, IntegerType, IntegerHolder> {
private static final long serialVersionUID = -7895663698067736815L;
private Integer value;
public static final IntegerHolder NULL_HOLDER = new IntegerHolder();
// public static final IntegerType TYPE = IntegerType.TYPE;
private static IntegerHolder[] small;
static {
small = new IntegerHolder[256];
for (int i = 0; i < small.length; i++) {
small[i] = new IntegerHolder(i);
}
}
public static IntegerHolder valueOf(int v) {
/**
* Possibly cache small ints later like java.lang.Integer
*/
return (v >= 0 && v < small.length) ? small[v] : new IntegerHolder(v);
// return new IntegerHolder(v);
}
public static IntegerHolder valueOf(Integer v) {
return (v == null) ? NULL_HOLDER : valueOf(v.intValue());
}
public IntegerHolder(int value) {
this.value = Integer.valueOf(value);
}
protected IntegerHolder() {
}
@Override
public Integer value() {
return this.value;
}
@Override
public IntegerType getType() {
return IntegerType.TYPE;
}
@Override
public int getSqlType() {
return PrimitiveType.INTEGER;
}
public static class Factory
implements HolderFactory<Integer, IntegerType, IntegerHolder> {
@Override
public IntegerHolder newHolder(Integer value) {
return IntegerHolder.valueOf(value);
}
}
/**
* Returns <code>this</code>
*/
@Override
public IntegerHolder asIntegerHolder() {
return this;
}
@Override
public IntegerHolder self() {
return this;
}
public static IntegerHolder as(PrimitiveHolder<?, ?, ?> holder) {
return holder.asIntegerHolder();
}
} |
package com.axelby.podax;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.util.Xml;
import com.axelby.podax.R.drawable;
import com.axelby.podax.ui.MainActivity;
import com.axelby.podax.ui.PodcastDetailActivity;
import com.axelby.riasel.Feed;
import com.axelby.riasel.FeedItem;
import com.axelby.riasel.FeedParser;
public class SubscriptionUpdater {
private Context _context;
public SubscriptionUpdater(Context context) {
_context = context;
}
public void update(final long subscriptionId) {
Cursor cursor = null;
try {
if (!Helper.ensureWifi(_context))
return;
Uri subscriptionUri = ContentUris.withAppendedId(SubscriptionProvider.URI, subscriptionId);
String[] projection = new String[] {
SubscriptionProvider.COLUMN_ID,
SubscriptionProvider.COLUMN_TITLE,
SubscriptionProvider.COLUMN_URL,
SubscriptionProvider.COLUMN_ETAG,
SubscriptionProvider.COLUMN_LAST_MODIFIED,
};
final ContentValues subscriptionValues = new ContentValues();
cursor = _context.getContentResolver().query(subscriptionUri, projection,
SubscriptionProvider.COLUMN_ID + " = ?",
new String[] { String.valueOf(subscriptionId) }, null);
if (!cursor.moveToNext())
return;
SubscriptionCursor subscription = new SubscriptionCursor(cursor);
showNotification(subscription);
URL url = new URL(subscription.getUrl());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
if (subscription.getETag() != null)
connection.setRequestProperty("If-None-Match", subscription.getETag());
if (subscription.getLastModified() != null && subscription.getLastModified().getTime() > 0) {
SimpleDateFormat imsFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
connection.setRequestProperty("If-Modified-Since", imsFormat.format(subscription.getLastModified()));
}
int code = connection.getResponseCode();
// only valid response code is 200
// 304 (content not modified) is OK too
if (code != 200) {
return;
}
String eTag = connection.getHeaderField("ETag");
if (eTag != null) {
subscriptionValues.put(SubscriptionProvider.COLUMN_ETAG, eTag);
if (eTag.equals(subscription.getETag()))
return;
}
String encoding = connection.getContentEncoding();
if (encoding == null) {
String contentType = connection.getContentType();
if (contentType != null && contentType.indexOf(";") > -1) {
encoding = contentType.split(";")[1].trim().substring("charset=".length());
}
}
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(connection.getInputStream(), encoding);
FeedParser feedParser = new FeedParser();
feedParser.setOnFeedInfoHandler(new FeedParser.FeedInfoHandler() {
@Override
public void OnFeedInfo(Feed feed) {
subscriptionValues.putAll(feed.getContentValues());
changeKeyString(subscriptionValues, "lastBuildDate", SubscriptionProvider.COLUMN_LAST_UPDATE);
if (feed.getThumbnail() != null)
downloadThumbnail(subscriptionId, feed.getThumbnail());
}
});
feedParser.setOnFeedItemHandler(new FeedParser.FeedItemHandler() {
@Override
public void OnFeedItem(FeedItem item) {
if (item.getMediaURL() == null || item.getMediaURL().length() == 0)
return;
ContentValues podcastValues = item.getContentValues();
podcastValues.put(PodcastProvider.COLUMN_SUBSCRIPTION_ID, subscriptionId);
// translate Riasel keys to old Podax keys
changeKeyString(podcastValues, "mediaURL", PodcastProvider.COLUMN_MEDIA_URL);
changeKeyString(podcastValues, "mediaSize", PodcastProvider.COLUMN_FILE_SIZE);
changeKeyString(podcastValues, "paymentURL", PodcastProvider.COLUMN_PAYMENT);
if (changeKeyLong(podcastValues, "publicationDate", PodcastProvider.COLUMN_PUB_DATE))
podcastValues.put(PodcastProvider.COLUMN_PUB_DATE, podcastValues.getAsLong(PodcastProvider.COLUMN_PUB_DATE) / 1000);
if (podcastValues.containsKey(PodcastProvider.COLUMN_MEDIA_URL)) {
try {
_context.getContentResolver().insert(PodcastProvider.URI, podcastValues);
} catch (IllegalArgumentException e) {
Log.w("Podax", "error while inserting podcast: " + e.getMessage());
}
}
}
});
feedParser.parseFeed(parser);
} catch (XmlPullParserException e) {
// not much we can do about this
Log.w("Podax", "error in subscription xml: " + e.getMessage());
showUpdateErrorNotification(subscription, _context.getString(R.string.rss_not_valid));
}
// finish grabbing subscription values and update
subscriptionValues.put(SubscriptionProvider.COLUMN_LAST_UPDATE, new Date().getTime() / 1000);
_context.getContentResolver().update(subscriptionUri, subscriptionValues, null, null);
writeSubscriptionOPML();
} catch (Exception e) {
Log.w("Podax", "error while updating: " + e.getMessage());
} finally {
if (cursor != null)
cursor.close();
UpdateService.downloadPodcastsSilently(_context);
}
}
private boolean changeKeyString(ContentValues values, String oldKey, String newKey) {
if (values.containsKey(oldKey)) {
values.put(newKey, values.getAsString(oldKey));
values.remove(oldKey);
return true;
}
return false;
};
private boolean changeKeyLong(ContentValues values, String oldKey, String newKey) {
if (values.containsKey(oldKey)) {
values.put(newKey, values.getAsLong(oldKey));
values.remove(oldKey);
return true;
}
return false;
};
private void showUpdateErrorNotification(SubscriptionCursor subscription, String reason) {
Intent notificationIntent = MainActivity.getSubscriptionIntent(_context);
PendingIntent contentIntent = PendingIntent.getActivity(_context, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(_context)
.setSmallIcon(drawable.icon)
.setTicker("Error Updating Subscription")
.setWhen(System.currentTimeMillis())
.setContentTitle("Error updating " + subscription.getTitle())
.setContentText(reason)
.setContentIntent(contentIntent)
.setOngoing(false)
.getNotification();
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager = (NotificationManager) _context.getSystemService(ns);
notificationManager.notify(Constants.SUBSCRIPTION_UPDATE_ERROR, notification);
}
protected void writeSubscriptionOPML() {
try {
File file = new File(_context.getExternalFilesDir(null), "podax.opml");
FileOutputStream output = new FileOutputStream(file);
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(output, "UTF-8");
serializer.startDocument("UTF-8", true);
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag(null, "opml");
serializer.attribute(null, "version", "1.0");
serializer.startTag(null, "head");
serializer.startTag(null, "title");
serializer.text("Podax Subscriptions");
serializer.endTag(null, "title");
serializer.endTag(null, "head");
serializer.startTag(null, "body");
String[] projection = {
SubscriptionProvider.COLUMN_TITLE,
SubscriptionProvider.COLUMN_URL,
};
Cursor c = _context.getContentResolver().query(SubscriptionProvider.URI, projection , null, null, SubscriptionProvider.COLUMN_TITLE);
while (c.moveToNext()) {
SubscriptionCursor sub = new SubscriptionCursor(c);
serializer.startTag(null, "outline");
serializer.attribute(null, "type", "rss");
serializer.attribute(null, "title", sub.getTitle());
serializer.attribute(null, "xmlUrl", sub.getUrl());
serializer.endTag(null, "outline");
}
c.close();
serializer.endTag(null, "body");
serializer.endTag(null, "opml");
serializer.endDocument();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void downloadThumbnail(long subscriptionId, String thumbnailUrl) {
File thumbnailFile = new File(SubscriptionProvider.getThumbnailFilename(subscriptionId));
if (thumbnailFile.exists())
return;
InputStream thumbIn;
try {
thumbIn = new URL(thumbnailUrl).openStream();
FileOutputStream thumbOut = new FileOutputStream(thumbnailFile.getAbsolutePath());
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = thumbIn.read(buffer)) > 0 )
thumbOut.write(buffer, 0, bufferLength);
thumbOut.close();
thumbIn.close();
} catch (IOException e) {
if (thumbnailFile.exists())
thumbnailFile.delete();
}
}
void showNotification(SubscriptionCursor subscription) {
Intent notificationIntent = new Intent(_context, PodcastDetailActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(_context, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(_context)
.setSmallIcon(drawable.icon)
.setWhen(System.currentTimeMillis())
.setContentTitle("Updating " + subscription.getTitle())
.setContentIntent(contentIntent)
.getNotification();
NotificationManager notificationManager = (NotificationManager) _context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Constants.NOTIFICATION_UPDATE, notification);
}
} |
package uk.org.ngo.squeezer.dialogs;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import uk.org.ngo.squeezer.R;
import uk.org.ngo.squeezer.Squeezer;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.preference.DialogPreference;
import android.text.format.Formatter;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
/**
* Shows a preference dialog that allows the user to scan the local network
* for servers, choose a server from the results of the scan, or enter the
* name/address of a server directly.
* <p>
* As far as I can tell it's tricky to show a dialog from another dialog in
* Android (without dismissing the first one), which makes showing a
* ProgressDialog during the scan difficult. Hence the gyrations to enable
* and disable various dialog controls during the scan.
*
* @author nik
*
*/
public class ServerAddressPreference extends DialogPreference {
private static final int DEFAULT_PORT = 9090; // XXX: Dup from
// SqueezerConnectionState
private EditText mServerAddressEditText;
private Button mScanBtn;
private ProgressBar mScanProgressBar;
private Spinner mServersSpinner;
private scanNetworkTask mScanTask;
private boolean mScanInProgress = false;
private ConnectivityManager mConnectivityManager =
(ConnectivityManager) Squeezer.getContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
private ArrayList<String> mDiscoveredServers = new ArrayList<String>();
private ArrayAdapter<String> mAdapter;
private Context mContext;
public ServerAddressPreference(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setDialogLayoutResource(R.layout.server_address_dialog);
}
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
mServerAddressEditText = (EditText) view.findViewById(R.id.server_address);
mScanBtn = (Button) view.findViewById(R.id.scan_btn);
mScanProgressBar = (ProgressBar) view.findViewById(R.id.scan_progress);
mServersSpinner = (Spinner) view.findViewById(R.id.found_servers);
// If there's no server address configured then set the default text
// in the edit box to our IP address, trimmed of the last octet.
String serveraddr = getPersistedString("");
if (serveraddr.length() == 0) {
WifiManager mWifiManager =
(WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
String ipstr = Formatter.formatIpAddress(mWifiInfo.getIpAddress());
int i = ipstr.lastIndexOf(".");
serveraddr = ipstr.substring(0, ++i);
}
// Move the cursor to the end of the address.
mServerAddressEditText.setText(serveraddr);
mServerAddressEditText.setSelection(serveraddr.length());
// Set up the servers spinner.
mAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item,
mDiscoveredServers);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mServersSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
// Only support network scanning on WiFi.
if (mConnectivityManager.getActiveNetworkInfo().getType()
== ConnectivityManager.TYPE_WIFI) {
mScanBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mScanInProgress == false) {
onScanStart();
} else {
}
}
});
} else {
TextView scan_msg = (TextView) view.findViewById(R.id.scan_msg);
scan_msg.setText("Scanning is disabled, because WiFi is not connected.");
mScanBtn.setEnabled(false);
}
}
/**
* Starts scanning for servers.
* <p>
* Disables and enables various parts of the UI.
*/
void onScanStart() {
Log.v("DIALOG", "Start scanning");
mScanBtn.setText("Cancel scan"); // TODO: i18n
mServersSpinner.setVisibility(View.GONE);
mScanProgressBar.setProgress(0);
mScanProgressBar.setVisibility(View.VISIBLE);
mServerAddressEditText.setEnabled(false);
mScanTask = new scanNetworkTask();
mScanTask.execute();
mScanInProgress = true;
}
/**
* Called when server scanning has finished.
* <p>
* Adjusts the UI as necessary.
*/
void onScanFinish() {
mScanBtn.setText("Start scan"); // TODO: i18n
mScanTask.cancel(true);
mScanProgressBar.setVisibility(View.GONE);
mServerAddressEditText.setEnabled(true);
mScanInProgress = false;
// If we only found one address then populate the edittext widget.
// Otherwise, show the spinner so the user can choose a server.
if (mDiscoveredServers.size() == 1) {
mServerAddressEditText.setText(mDiscoveredServers.get(0));
} else {
mServersSpinner.setVisibility(View.VISIBLE);
mServersSpinner.setAdapter(mAdapter);
}
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
// Stop scanning
if (mScanInProgress) {
mScanTask.cancel(true);
mScanInProgress = false;
}
if (positiveResult) {
String addr = mServerAddressEditText.getText().toString();
persistString(addr);
callChangeListener(addr);
}
}
/**
* Inserts the selected address in to the edittext widget.
* <p>
* XXX: Not firing, despite showing multiple items in the menu.
*
* @author nik
*/
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Log.v("Spinner", "onItemSelected called");
Log.v("Spinner", "Selected: " + parent.getItemAtPosition(pos).toString());
mServerAddressEditText.setText(parent.getItemAtPosition(pos).toString());
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
/**
* Scans the local network for servers.
* <p>
* XXX: Likely not safe on orientation changes.
*
* @author nik
*/
private class scanNetworkTask extends AsyncTask<Void, Integer, Integer> {
String TAG = "scanNetworkTask";
@Override
protected void onPreExecute() {
super.onPreExecute();
mDiscoveredServers.clear();
}
// Background thread.
protected Integer doInBackground(Void... arg0) {
WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
WifiManager.WifiLock wifiLock = wm.createWifiLock(TAG);
Log.v(TAG, "Locking WiFi while scanning");
wifiLock.acquire();
WifiInfo wifiInfo = wm.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
// Dumb approach - go from .1 to .254, skipping ourselves.
int subnet = ip & 0x00ffffff;
int lastOctet;
Socket socket;
// XXX: Adjust this before pushing live...
for (lastOctet = 99; lastOctet < 105; lastOctet++) {
int addressToCheck = (lastOctet << 24) | subnet;
if (addressToCheck == ip)
continue;
// Everything else prefers to deal with IP addresses as strings,
// so convert here, and use throughout.
String addrStr = Formatter.formatIpAddress(addressToCheck);
Log.v(TAG, "Will check: " + addrStr);
// Check for cancellation before starting any lengthy activity
if (isCancelled())
break;
// Try and connect. Ignore errors, on success close the
// socket and note the IP address.
socket = new Socket();
try {
socket.connect(new InetSocketAddress(addrStr, DEFAULT_PORT),
500 /* ms timeout */);
} catch (IOException e) {
} // Expected, can be ignored.
if (socket.isConnected()) {
mDiscoveredServers.add(addrStr); // Note the address
try {
socket.close();
} catch (IOException e) {
} // Expected, can be ignored.
}
// Send message that we've checked this one.
publishProgress(lastOctet);
}
Log.v(TAG, "Scanning complete, unlocking WiFi");
wifiLock.release();
return lastOctet;
}
@Override
protected void onProgressUpdate(Integer... values) {
mScanProgressBar.setProgress(values[0]);
}
@Override
protected void onCancelled() {
super.onCancelled();
onScanFinish();
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
onScanFinish();
}
}
} |
package com.dmdirc.addons.ui_swing;
import com.dmdirc.addons.ui_swing.components.MenuBar;
import com.dmdirc.addons.ui_swing.components.LoggingSwingWorker;
import com.dmdirc.addons.ui_swing.components.SnappingJSplitPane;
import com.dmdirc.addons.ui_swing.components.desktopPane.DMDircDesktopPane;
import com.dmdirc.addons.ui_swing.components.statusbar.SwingStatusBar;
import com.dmdirc.addons.ui_swing.framemanager.tree.TreeFrameManager;
import com.dmdirc.FrameContainer;
import com.dmdirc.Main;
import com.dmdirc.ServerManager;
import com.dmdirc.actions.ActionManager;
import com.dmdirc.actions.CoreActionType;
import com.dmdirc.config.IdentityManager;
import com.dmdirc.interfaces.ConfigChangeListener;
import com.dmdirc.ui.IconManager;
import com.dmdirc.ui.WindowManager;
import com.dmdirc.ui.interfaces.FrameManager;
import com.dmdirc.ui.interfaces.FramemanagerPosition;
import com.dmdirc.ui.interfaces.MainWindow;
import com.dmdirc.ui.interfaces.Window;
import com.dmdirc.ui.CoreUIUtils;
import com.dmdirc.ui.interfaces.FrameListener;
import com.dmdirc.util.ReturnableThread;
import java.awt.Dimension;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.MenuSelectionManager;
import javax.swing.WindowConstants;
import net.miginfocom.swing.MigLayout;
/**
* The main application frame.
*/
public final class MainFrame extends JFrame implements WindowListener,
MainWindow, ConfigChangeListener, FrameListener {
/** Logger to use. */
private static final java.util.logging.Logger LOGGER =
java.util.logging.Logger.getLogger(MainFrame.class.getName());
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 9;
/** The main application icon. */
private ImageIcon imageIcon;
/** The frame manager that's being used. */
private FrameManager mainFrameManager;
/** Dekstop pane. */
private DMDircDesktopPane desktopPane;
/** Main panel. */
private JPanel frameManagerPanel;
/** Frame manager position. */
private FramemanagerPosition position;
/** Show version? */
private boolean showVersion;
/** Menu bar. */
private MenuBar menu;
/** Exit code. */
private int exitCode = 0;
/** Swing Controller. */
private SwingController controller;
/** Status bar. */
private SwingStatusBar statusBar;
/**
* Creates new form MainFrame.
*
* @param controller Swing controller
*/
protected MainFrame(final SwingController controller) {
super();
this.controller = controller;
initComponents();
imageIcon =
new ImageIcon(IconManager.getIconManager().getImage("icon"));
setIconImage(imageIcon.getImage());
CoreUIUtils.centreWindow(this);
setVisible(true);
addWindowListener(this);
showVersion = IdentityManager.getGlobalConfig().getOptionBool("ui",
"showversion");
IdentityManager.getGlobalConfig().addChangeListener("ui", "lookandfeel",
this);
IdentityManager.getGlobalConfig().addChangeListener("ui", "showversion",
this);
IdentityManager.getGlobalConfig().addChangeListener("icon", "icon", this);
addWindowFocusListener(new WindowFocusListener() {
/** {@inheritDoc} */
@Override
public void windowGainedFocus(WindowEvent e) {
//Ignore
}
/** {@inheritDoc} */
@Override
public void windowLostFocus(WindowEvent e) {
//TODO: Remove me when we switch to java7
MenuSelectionManager.defaultManager().clearSelectedPath();
}
});
setTitle(getTitlePrefix());
}
/**
* Returns the status bar for this frame.
*
* @return Status bar
*/
public SwingStatusBar getStatusBar() {
return statusBar;
}
/**
* Returns the size of the frame manager.
*
* @return Frame manager size.
*/
public int getFrameManagerSize() {
return UIUtilities.invokeAndWait(new ReturnableThread<Integer>() {
/** {@inheritDoc} */
@Override
public void run() {
if (position == FramemanagerPosition.LEFT ||
position == FramemanagerPosition.RIGHT) {
setObject(frameManagerPanel.getWidth());
} else {
setObject(frameManagerPanel.getHeight());
}
}
});
}
/** {@inheritDoc}. */
@Override
public ImageIcon getIcon() {
return UIUtilities.invokeAndWait(new ReturnableThread<ImageIcon>() {
/** {@inheritDoc} */
@Override
public void run() {
setObject(imageIcon);
}
});
}
/**
* Returns the window that is currently active.
*
* @return The active window
*/
public Window getActiveFrame() {
return UIUtilities.invokeAndWait(new ReturnableThread<Window>() {
/** {@inheritDoc} */
@Override
public void run() {
setObject(desktopPane.getSelectedWindow());
}
});
}
/** {@inheritDoc}. */
@Override
public void setMaximised(final boolean max) {
//Ignore
}
/** {@inheritDoc}. */
@Override
public void setTitle(final String title) {
if (getActiveFrame() != null && getActiveFrame().isMaximum()) {
super.setTitle(getTitlePrefix() + " - " + title);
} else {
super.setTitle(getTitlePrefix());
}
}
/** {@inheritDoc}. */
@Override
public String getTitlePrefix() {
if (showVersion) {
return "DMDirc " + IdentityManager.getGlobalConfig().getOption(
"version", "version");
} else {
return "DMDirc";
}
}
/** {@inheritDoc}. */
@Override
public boolean getMaximised() {
return UIUtilities.invokeAndWait(new ReturnableThread<Boolean>() {
/** {@inheritDoc}. */
@Override
public void run() {
final Window window = getActiveFrame();
if (window == null) {
setObject(false);
} else {
setObject(getActiveFrame().isMaximum());
}
}
});
}
/**
* Returns the desktop pane for the frame.
*
* @return JDesktopPane for the frame
*/
public JDesktopPane getDesktopPane() {
return desktopPane;
}
/**
* {@inheritDoc}.
*
* @param windowEvent Window event
*/
@Override
public void windowOpened(final WindowEvent windowEvent) {
//ignore
}
/**
* {@inheritDoc}.
*
* @param windowEvent Window event
*/
@Override
public void windowClosing(final WindowEvent windowEvent) {
quit(exitCode);
}
/**
* {@inheritDoc}.
*
* @param windowEvent Window event
*/
@Override
public void windowClosed(final WindowEvent windowEvent) {
new Thread(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
Main.quit(exitCode);
}
}, "Quit thread").start();
}
/**
* {@inheritDoc}.
*
* @param windowEvent Window event
*/
@Override
public void windowIconified(final WindowEvent windowEvent) {
ActionManager.processEvent(CoreActionType.CLIENT_MINIMISED, null);
}
/**
* {@inheritDoc}.
*
* @param windowEvent Window event
*/
@Override
public void windowDeiconified(final WindowEvent windowEvent) {
ActionManager.processEvent(CoreActionType.CLIENT_UNMINIMISED, null);
}
/**
* {@inheritDoc}.
*
* @param windowEvent Window event
*/
@Override
public void windowActivated(final WindowEvent windowEvent) {
//ignore
}
/**
* {@inheritDoc}.
*
* @param windowEvent Window event
*/
@Override
public void windowDeactivated(final WindowEvent windowEvent) {
//ignore
}
/** Initialiases the frame managers. */
private void initFrameManagers() {
UIUtilities.invokeAndWait(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final String manager = IdentityManager.getGlobalConfig().
getOption("ui",
"framemanager");
try {
mainFrameManager = (FrameManager) Class.forName(manager).
getConstructor().newInstance();
} catch (Exception ex) {
// Throws craploads of exceptions and we want to handle them all
// the same way, so we might as well catch Exception
mainFrameManager = new TreeFrameManager();
}
WindowManager.addFrameListener(mainFrameManager);
mainFrameManager.setParent(frameManagerPanel);
WindowManager.addFrameListener(MainFrame.this);
}
});
}
/**
* Initialises the components for this frame.
*/
private void initComponents() {
statusBar = new SwingStatusBar(controller, this);
frameManagerPanel = new JPanel();
desktopPane = new DMDircDesktopPane(this);
initFrameManagers();
menu = new MenuBar(controller, this);
Apple.getApple().setMenuBar(menu);
setJMenuBar(menu);
setPreferredSize(new Dimension(800, 600));
getContentPane().setLayout(new MigLayout(
"fill, ins rel, wrap 1, hidemode 2"));
getContentPane().add(initSplitPane(), "grow, push");
getContentPane().add(statusBar,
"hmax 20, wmax 100%-2*rel, wmin 100%-2*rel");
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
pack();
}
/**
* Initialises the split pane.
*
* @return Returns the initialised split pane
*/
private JSplitPane initSplitPane() {
final JSplitPane mainSplitPane =
new SnappingJSplitPane(SnappingJSplitPane.Orientation.HORIZONTAL);
position =
FramemanagerPosition.getPosition(IdentityManager.getGlobalConfig().
getOption("ui", "framemanagerPosition"));
if (position == FramemanagerPosition.UNKNOWN) {
position = FramemanagerPosition.LEFT;
}
if (!mainFrameManager.canPositionVertically() &&
(position == FramemanagerPosition.LEFT ||
position == FramemanagerPosition.RIGHT)) {
position = FramemanagerPosition.BOTTOM;
}
if (!mainFrameManager.canPositionHorizontally() &&
(position == FramemanagerPosition.TOP ||
position == FramemanagerPosition.BOTTOM)) {
position = FramemanagerPosition.LEFT;
}
switch (position) {
case TOP:
mainSplitPane.setTopComponent(frameManagerPanel);
mainSplitPane.setBottomComponent(desktopPane);
mainSplitPane.setResizeWeight(0.0);
mainSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
frameManagerPanel.setPreferredSize(new Dimension(
Integer.MAX_VALUE,
IdentityManager.getGlobalConfig().
getOptionInt("ui", "frameManagerSize")));
break;
case LEFT:
mainSplitPane.setLeftComponent(frameManagerPanel);
mainSplitPane.setRightComponent(desktopPane);
mainSplitPane.setResizeWeight(0.0);
mainSplitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
frameManagerPanel.setPreferredSize(new Dimension(
IdentityManager.getGlobalConfig().getOptionInt("ui",
"frameManagerSize"), Integer.MAX_VALUE));
break;
case BOTTOM:
mainSplitPane.setTopComponent(desktopPane);
mainSplitPane.setBottomComponent(frameManagerPanel);
mainSplitPane.setResizeWeight(1.0);
mainSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
frameManagerPanel.setPreferredSize(new Dimension(
Integer.MAX_VALUE,
IdentityManager.getGlobalConfig().
getOptionInt("ui", "frameManagerSize")));
break;
case RIGHT:
mainSplitPane.setLeftComponent(desktopPane);
mainSplitPane.setRightComponent(frameManagerPanel);
mainSplitPane.setResizeWeight(1.0);
mainSplitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
frameManagerPanel.setPreferredSize(new Dimension(
IdentityManager.getGlobalConfig().getOptionInt("ui",
"frameManagerSize"), Integer.MAX_VALUE));
break;
default:
break;
}
return mainSplitPane;
}
/** {@inheritDoc}. */
@Override
public void quit() {
quit(0);
}
/**
* Exit code call to quit.
*
* @param exitCode Exit code
*/
public void quit(final int exitCode) {
if (exitCode == 0 && IdentityManager.getGlobalConfig().getOptionBool(
"ui", "confirmQuit") && JOptionPane.showConfirmDialog(this,
"You are about to quit DMDirc, are you sure?", "Quit confirm",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE) !=
JOptionPane.YES_OPTION) {
return;
}
this.exitCode = exitCode;
new LoggingSwingWorker() {
/** {@inheritDoc} */
@Override
protected Object doInBackground() throws Exception {
ActionManager.processEvent(CoreActionType.CLIENT_CLOSING, null);
ServerManager.getServerManager().closeAll(IdentityManager.
getGlobalConfig().getOption("general", "closemessage"));
IdentityManager.getConfigIdentity().setOption("ui",
"frameManagerSize",
String.valueOf(getFrameManagerSize()));
return null;
}
/** {@inheritDoc} */
@Override
protected void done() {
super.done();
dispose();
}
}.execute();
}
/** {@inheritDoc} */
@Override
public void configChanged(final String domain, final String key) {
if ("ui".equals(domain)) {
if ("lookandfeel".equals(key)) {
controller.updateLookAndFeel();
} else {
showVersion = IdentityManager.getGlobalConfig().getOptionBool(
"ui",
"showversion");
}
} else {
imageIcon = new ImageIcon(IconManager.getIconManager().getImage(
"icon"));
setIconImage(imageIcon.getImage());
}
}
/** {@inheritDoc}. */
@Override
public void addWindow(final FrameContainer window) {
UIUtilities.invokeAndWait(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
addWindow(window, desktopPane.getAllFrames().length - 1);
}
});
}
/**
* Adds a window to this frame manager.
*
* @param window The server to be added
* @param index Index of the window to be added
*/
public void addWindow(final FrameContainer window, final int index) {
UIUtilities.invokeAndWait(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final JInternalFrame frame = (JInternalFrame) window.getFrame();
// Add the frame
desktopPane.add(frame, index);
}
});
}
/** {@inheritDoc}. */
@Override
public void delWindow(final FrameContainer window) {
UIUtilities.invokeAndWait(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final JInternalFrame frame = (JInternalFrame) window.getFrame();
if (desktopPane.getAllFrames().length == 1) {
setTitle(getTitlePrefix());
}
desktopPane.remove(frame);
}
});
}
/** {@inheritDoc}. */
@Override
public void addWindow(final FrameContainer parent,
final FrameContainer window) {
addWindow(window);
}
/** {@inheritDoc}. */
@Override
public void delWindow(final FrameContainer parent,
final FrameContainer window) {
delWindow(window);
}
} |
package com.ecyrd.jspwiki.filters;
import java.io.*;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import net.sf.akismet.Akismet;
import org.apache.commons.jrcs.diff.*;
import org.apache.commons.jrcs.diff.myers.MyersDiff;
import org.apache.commons.lang.time.StopWatch;
import org.apache.log4j.Logger;
import org.apache.oro.text.regex.*;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.attachment.Attachment;
import com.ecyrd.jspwiki.auth.user.UserProfile;
import com.ecyrd.jspwiki.providers.ProviderException;
import com.ecyrd.jspwiki.ui.EditorManager;
/**
* This is Herb, the JSPWiki spamfilter that can also do choke modifications.
*
* Parameters:
* <ul>
* <li>wordlist - Page name where the regexps are found. Use [{SET spamwords='regexp list separated with spaces'}] on
* that page. Default is "SpamFilterWordList".
* <li>blacklist - The name of an attachment containing the list of spam patterns, one per line. Default is
* "SpamFilterWordList/blacklist.txt"</li>
* <li>errorpage - The page to which the user is redirected. Has a special variable $msg which states the reason. Default is "RejectedMessage".
* <li>pagechangesinminute - How many page changes are allowed/minute. Default is 5.</li>
* <li>similarchanges - How many similar page changes are allowed before the host is banned. Default is 2. (since 2.4.72)</li>
* <li>bantime - How long an IP address stays on the temporary ban list (default is 60 for 60 minutes).</li>
* <li>maxurls - How many URLs can be added to the page before it is considered spam (default is 5)</li>
* <li>akismet-apikey - The Akismet API key (see akismet.org)</li>
* <li>ignoreauthenticated - If set to "true", all authenticated users are ignored and never caught in SpamFilter</li>
* <li>captcha - Sets the captcha technology to use. Current allowed values are "none" and "asirra".</li>
* <li>strategy - Sets the filtering strategy to use. If set to "eager", will stop at the first probable
* match, and won't consider any other tests. This is the default, as it's considerably lighter. If set to "score", will go through all of the tests
* and calculates a score for the spam, which is then compared to a filter level value.
* </ul>
*
* <p>Changes by admin users are ignored in any case.</p>
*
* @since 2.1.112
* @author Janne Jalkanen
*/
public class SpamFilter
extends BasicPageFilter
{
private static final String ATTR_SPAMFILTER_SCORE = "spamfilter.score";
private static final String REASON_REGEXP = "Regexp";
private static final String REASON_IP_BANNED_TEMPORARILY = "IPBannedTemporarily";
private static final String REASON_BOT_TRAP = "BotTrap";
private static final String REASON_AKISMET = "Akismet";
private static final String REASON_TOO_MANY_URLS = "TooManyUrls";
private static final String REASON_SIMILAR_MODIFICATIONS = "SimilarModifications";
private static final String REASON_TOO_MANY_MODIFICATIONS = "TooManyModifications";
private static final String REASON_UTF8_TRAP = "UTF8Trap";
private static final String LISTVAR = "spamwords";
public static final String PROP_WORDLIST = "wordlist";
public static final String PROP_ERRORPAGE = "errorpage";
public static final String PROP_PAGECHANGES = "pagechangesinminute";
public static final String PROP_SIMILARCHANGES = "similarchanges";
public static final String PROP_BANTIME = "bantime";
public static final String PROP_BLACKLIST = "blacklist";
public static final String PROP_MAXURLS = "maxurls";
public static final String PROP_AKISMET_API_KEY = "akismet-apikey";
public static final String PROP_IGNORE_AUTHENTICATED = "ignoreauthenticated";
public static final String PROP_CAPTCHA = "captcha";
public static final String PROP_FILTERSTRATEGY = "strategy";
public static final String STRATEGY_EAGER = "eager";
public static final String STRATEGY_SCORE = "score";
private static final String URL_REGEXP = "(http://|https://|mailto:)([A-Za-z0-9_/\\.\\+\\?\\
private String m_forbiddenWordsPage = "SpamFilterWordList";
private String m_errorPage = "RejectedMessage";
private String m_blacklist = "SpamFilterWordList/blacklist.txt";
private PatternMatcher m_matcher = new Perl5Matcher();
private PatternCompiler m_compiler = new Perl5Compiler();
private Collection m_spamPatterns = null;
private Date m_lastRebuild = new Date( 0L );
static Logger spamlog = Logger.getLogger( "SpamLog" );
static Logger log = Logger.getLogger( SpamFilter.class );
private Vector m_temporaryBanList = new Vector();
private int m_banTime = 60; // minutes
private Vector m_lastModifications = new Vector();
/**
* How many times a single IP address can change a page per minute?
*/
private int m_limitSinglePageChanges = 5;
/**
* How many times can you add the exact same string to a page?
*/
private int m_limitSimilarChanges = 2;
/**
* How many URLs can be added at maximum.
*/
private int m_maxUrls = 10;
private Pattern m_urlPattern;
private Akismet m_akismet;
private String m_akismetAPIKey = null;
private boolean m_useCaptcha = false;
/** The limit at which we consider something to be spam. */
private int m_scoreLimit = 1;
/**
* If set to true, will ignore anyone who is in Authenticated role.
*/
private boolean m_ignoreAuthenticated = false;
private boolean m_stopAtFirstMatch = true;
public void initialize( WikiEngine engine, Properties properties )
{
m_forbiddenWordsPage = properties.getProperty( PROP_WORDLIST,
m_forbiddenWordsPage );
m_errorPage = properties.getProperty( PROP_ERRORPAGE,
m_errorPage );
m_limitSinglePageChanges = TextUtil.getIntegerProperty( properties,
PROP_PAGECHANGES,
m_limitSinglePageChanges );
m_limitSimilarChanges = TextUtil.getIntegerProperty( properties,
PROP_SIMILARCHANGES,
m_limitSimilarChanges );
m_maxUrls = TextUtil.getIntegerProperty( properties,
PROP_MAXURLS,
m_maxUrls );
m_banTime = TextUtil.getIntegerProperty( properties,
PROP_BANTIME,
m_banTime );
m_blacklist = properties.getProperty( PROP_BLACKLIST, m_blacklist );
m_ignoreAuthenticated = TextUtil.getBooleanProperty( properties,
PROP_IGNORE_AUTHENTICATED,
m_ignoreAuthenticated );
m_useCaptcha = properties.getProperty( PROP_CAPTCHA, "" ).equals("asirra");
try
{
m_urlPattern = m_compiler.compile( URL_REGEXP );
}
catch( MalformedPatternException e )
{
log.fatal("Internal error: Someone put in a faulty pattern.",e);
throw new InternalWikiException("Faulty pattern.");
}
m_akismetAPIKey = TextUtil.getStringProperty( properties,
PROP_AKISMET_API_KEY,
m_akismetAPIKey );
m_stopAtFirstMatch = TextUtil.getStringProperty( properties,
PROP_FILTERSTRATEGY,
STRATEGY_EAGER ).equals(STRATEGY_EAGER);
log.info("# Spam filter initialized. Temporary ban time "+m_banTime+
" mins, max page changes/minute: "+m_limitSinglePageChanges );
}
private static final int REJECT = 0;
private static final int ACCEPT = 1;
private static final int NOTE = 2;
private static String log( WikiContext ctx, int type, String source, String message )
{
message = TextUtil.replaceString( message, "\r\n", "\\r\\n" );
message = TextUtil.replaceString( message, "\"", "\\\"" );
String uid = getUniqueID();
String page = ctx.getPage().getName();
String reason = "UNKNOWN";
String addr = ctx.getHttpRequest() != null ? ctx.getHttpRequest().getRemoteAddr() : "-";
switch( type )
{
case REJECT:
reason = "REJECTED";
break;
case ACCEPT:
reason = "ACCEPTED";
break;
case NOTE:
reason = "NOTE";
break;
default:
throw new InternalWikiException("Illegal type "+type);
}
spamlog.info( reason+" "+source+" "+uid+" "+addr+" \""+page+"\" "+message );
return uid;
}
public String preSave( WikiContext context, String content )
throws RedirectException
{
cleanBanList();
refreshBlacklists(context);
String change = getChange( context, content );
if(!ignoreThisUser(context))
{
checkBanList( context, change );
checkSinglePageChange( context, content, change );
checkPatternList(context, content, change);
}
if( !m_stopAtFirstMatch )
{
Integer score = (Integer)context.getVariable(ATTR_SPAMFILTER_SCORE);
if( score != null && score.intValue() >= m_scoreLimit )
{
throw new RedirectException( "Herb says you got too many points",
getRedirectPage(context) );
}
}
log( context, ACCEPT, "-", change );
return content;
}
private void checkStrategy( WikiContext context, String error, String message )
throws RedirectException
{
if( m_stopAtFirstMatch )
{
throw new RedirectException( message, getRedirectPage(context) );
}
Integer score = (Integer)context.getVariable( ATTR_SPAMFILTER_SCORE );
if( score != null )
score = new Integer( score.intValue()+1 );
else
score = new Integer( 1 );
context.setVariable( ATTR_SPAMFILTER_SCORE, score );
}
/**
* Parses a list of patterns and returns a Collection of compiled Pattern
* objects.
*
* @param source
* @param list
* @return
*/
private Collection parseWordList( WikiPage source, String list )
{
ArrayList compiledpatterns = new ArrayList();
if( list != null )
{
StringTokenizer tok = new StringTokenizer( list, " \t\n" );
while( tok.hasMoreTokens() )
{
String pattern = tok.nextToken();
try
{
compiledpatterns.add( m_compiler.compile( pattern ) );
}
catch( MalformedPatternException e )
{
log.debug( "Malformed spam filter pattern "+pattern );
source.setAttribute("error", "Malformed spam filter pattern "+pattern);
}
}
}
return compiledpatterns;
}
/**
* Takes a MT-Blacklist -formatted blacklist and returns a list of compiled
* Pattern objects.
*
* @param list
* @return
*/
private Collection parseBlacklist( String list )
{
ArrayList compiledpatterns = new ArrayList();
if( list != null )
{
try
{
BufferedReader in = new BufferedReader( new StringReader(list) );
String line;
while( (line = in.readLine()) != null )
{
line = line.trim();
if( line.length() == 0 ) continue; // Empty line
if( line.startsWith("#") ) continue; // It's a comment
int ws = line.indexOf(' ');
if( ws == -1 ) ws = line.indexOf('\t');
if( ws != -1 ) line = line.substring(0,ws);
try
{
compiledpatterns.add( m_compiler.compile( line ) );
}
catch( MalformedPatternException e )
{
log.debug( "Malformed spam filter pattern "+line );
}
}
}
catch( IOException e )
{
log.info("Could not read patterns; returning what I got",e);
}
}
return compiledpatterns;
}
/**
* Takes a single page change and performs a load of tests on the content change.
* An admin can modify anything.
*
* @param context
* @param content
* @throws RedirectException
*/
private synchronized void checkSinglePageChange( WikiContext context, String content, String change )
throws RedirectException
{
HttpServletRequest req = context.getHttpRequest();
if( req != null )
{
String addr = req.getRemoteAddr();
int hostCounter = 0;
int changeCounter = 0;
log.debug("Change is "+change);
long time = System.currentTimeMillis()-60*1000L; // 1 minute
for( Iterator i = m_lastModifications.iterator(); i.hasNext(); )
{
Host host = (Host)i.next();
// Check if this item is invalid
if( host.getAddedTime() < time )
{
log.debug("Removed host "+host.getAddress()+" from modification queue (expired)");
i.remove();
continue;
}
// Check if this IP address has been seen before
if( host.getAddress().equals(addr) )
{
hostCounter++;
}
// Check, if this change has been seen before
if( host.getChange() != null && host.getChange().equals(change) )
{
changeCounter++;
}
}
// Now, let's check against the limits.
if( hostCounter >= m_limitSinglePageChanges )
{
Host host = new Host( addr, null );
m_temporaryBanList.add( host );
String uid = log( context, REJECT, REASON_TOO_MANY_MODIFICATIONS, change );
log.info( "SPAM:TooManyModifications ("+uid+"). Added host "+addr+" to temporary ban list for doing too many modifications/minute" );
checkStrategy( context, REASON_TOO_MANY_MODIFICATIONS, "Herb says you look like a spammer, and I trust Herb! (Incident code "+uid+")" );
}
if( changeCounter >= m_limitSimilarChanges )
{
Host host = new Host( addr, null );
m_temporaryBanList.add( host );
String uid = log( context, REJECT, REASON_SIMILAR_MODIFICATIONS, change );
log.info("SPAM:SimilarModifications ("+uid+"). Added host "+addr+" to temporary ban list for doing too many similar modifications" );
checkStrategy( context, REASON_SIMILAR_MODIFICATIONS, "Herb says you look like a spammer, and I trust Herb! (Incident code "+uid+")");
}
// Calculate the number of links in the addition.
String tstChange = change;
int urlCounter = 0;
while( m_matcher.contains(tstChange,m_urlPattern) )
{
MatchResult m = m_matcher.getMatch();
tstChange = tstChange.substring( m.endOffset(0) );
urlCounter++;
}
if( urlCounter > m_maxUrls )
{
Host host = new Host( addr, null );
m_temporaryBanList.add( host );
String uid = log( context, REJECT, REASON_TOO_MANY_URLS, change );
log.info("SPAM:TooManyUrls ("+uid+"). Added host "+addr+" to temporary ban list for adding too many URLs" );
checkStrategy( context, REASON_TOO_MANY_URLS, "Herb says you look like a spammer, and I trust Herb! (Incident code "+uid+")" );
}
// Check bot trap
checkBotTrap( context, change );
// Check UTF-8 mangling
checkUTF8( context, change );
// Do Akismet check. This is good to be the last, because this is the most
// expensive operation.
checkAkismet( context, change );
m_lastModifications.add( new Host( addr, change ) );
}
}
/**
* Checks against the akismet system.
*
* @param context
* @param change
* @throws RedirectException
*/
private void checkAkismet( WikiContext context, String change )
throws RedirectException
{
if( m_akismetAPIKey != null )
{
if( m_akismet == null )
{
log.info("Initializing Akismet spam protection.");
m_akismet = new Akismet( m_akismetAPIKey, context.getEngine().getBaseURL() );
if( !m_akismet.verifyAPIKey() )
{
log.error("Akismet API key cannot be verified. Please check your config.");
m_akismetAPIKey = null;
m_akismet = null;
}
}
HttpServletRequest req = context.getHttpRequest();
if( req != null && m_akismet != null )
{
log.debug("Calling Akismet to check for spam...");
StopWatch sw = new StopWatch();
sw.start();
String ipAddress = req.getRemoteAddr();
String userAgent = req.getHeader("User-Agent");
String referrer = req.getHeader( "Referer");
String permalink = context.getViewURL( context.getPage().getName() );
String commentType = context.getRequestContext().equals(WikiContext.COMMENT) ? "comment" : "edit";
String commentAuthor = context.getCurrentUser().getName();
String commentAuthorEmail = null;
String commentAuthorURL = null;
boolean isSpam = m_akismet.commentCheck( ipAddress,
userAgent,
referrer,
permalink,
commentType,
commentAuthor,
commentAuthorEmail,
commentAuthorURL,
change,
null );
sw.stop();
log.debug("Akismet request done in: "+sw);
if( isSpam )
{
// Host host = new Host( ipAddress, null );
// m_temporaryBanList.add( host );
String uid = log( context, REJECT, REASON_AKISMET, change );
log.info("SPAM:Akismet ("+uid+"). Akismet thinks this change is spam; added host to temporary ban list.");
checkStrategy( context, REASON_AKISMET, "Akismet tells Herb you're a spammer, Herb trusts Akismet, and I trust Herb! (Incident code "+uid+")");
}
}
}
}
/**
* Returns a static string which can be used to detect spambots which
* just wildly fill in all the fields.
*
* @return A string
*/
public static String getBotFieldName()
{
return "submit_auth";
}
/**
* This checks whether an invisible field is available in the request, and
* whether it's contents are suspected spam.
*
* @param context
* @param change
* @throws RedirectException
*/
private void checkBotTrap( WikiContext context, String change ) throws RedirectException
{
HttpServletRequest request = context.getHttpRequest();
if( request != null )
{
String unspam = request.getParameter( getBotFieldName() );
if( unspam != null && unspam.length() > 0 )
{
String uid = log( context, REJECT, REASON_BOT_TRAP, change );
log.info("SPAM:BotTrap ("+uid+"). Wildly behaving bot detected.");
checkStrategy( context, REASON_BOT_TRAP, "Spamming attempt detected. (Incident code "+uid+")");
}
}
}
private void checkUTF8( WikiContext context, String change ) throws RedirectException
{
HttpServletRequest request = context.getHttpRequest();
if( request != null )
{
String utf8field = request.getParameter( "encodingcheck" );
if( utf8field != null && !utf8field.equals("\u3041") )
{
String uid = log( context, REJECT, REASON_UTF8_TRAP, change );
log.info("SPAM:UTF8Trap ("+uid+"). Wildly posting dumb bot detected.");
checkStrategy( context, REASON_UTF8_TRAP, "Spamming attempt detected. (Incident code "+uid+")");
}
}
}
/**
* Goes through the ban list and cleans away any host which has expired from it.
*/
private synchronized void cleanBanList()
{
long now = System.currentTimeMillis();
for( Iterator i = m_temporaryBanList.iterator(); i.hasNext(); )
{
Host host = (Host)i.next();
if( host.getReleaseTime() < now )
{
log.debug("Removed host "+host.getAddress()+" from temporary ban list (expired)");
i.remove();
}
}
}
/**
* Checks the ban list if the IP address of the changer is already on it.
*
* @param context
* @throws RedirectException
*/
private void checkBanList( WikiContext context, String change )
throws RedirectException
{
HttpServletRequest req = context.getHttpRequest();
if( req != null )
{
String remote = req.getRemoteAddr();
long now = System.currentTimeMillis();
for( Iterator i = m_temporaryBanList.iterator(); i.hasNext(); )
{
Host host = (Host)i.next();
if( host.getAddress().equals(remote) )
{
long timeleft = (host.getReleaseTime() - now) / 1000L;
log( context, REJECT, REASON_IP_BANNED_TEMPORARILY, change );
checkStrategy( context, REASON_IP_BANNED_TEMPORARILY, "You have been temporarily banned from modifying this wiki. ("+timeleft+" seconds of ban left)");
}
}
}
}
/**
* If the spam filter notices changes in the black list page, it will refresh
* them automatically.
*
* @param context
*/
private void refreshBlacklists( WikiContext context )
{
try
{
WikiPage source = context.getEngine().getPage( m_forbiddenWordsPage );
Attachment att = context.getEngine().getAttachmentManager().getAttachmentInfo( context, m_blacklist );
boolean rebuild = false;
// Rebuild, if the page or the attachment has changed since.
if( source != null )
{
if( m_spamPatterns == null || m_spamPatterns.isEmpty() || source.getLastModified().after(m_lastRebuild) )
{
rebuild = true;
}
}
if( att != null )
{
if( m_spamPatterns == null || m_spamPatterns.isEmpty() || att.getLastModified().after(m_lastRebuild) )
{
rebuild = true;
}
}
// Do the actual rebuilding. For simplicity's sake, we always rebuild the complete
// filter list regardless of what changed.
if( rebuild )
{
m_lastRebuild = new Date();
m_spamPatterns = parseWordList( source,
(String)source.getAttribute( LISTVAR ) );
log.info("Spam filter reloaded - recognizing "+m_spamPatterns.size()+" patterns from page "+m_forbiddenWordsPage);
if( att != null )
{
InputStream in = context.getEngine().getAttachmentManager().getAttachmentStream(att);
StringWriter out = new StringWriter();
FileUtil.copyContents( new InputStreamReader(in,"UTF-8"), out );
Collection blackList = parseBlacklist( out.toString() );
log.info("...recognizing additional "+blackList.size()+" patterns from blacklist "+m_blacklist);
m_spamPatterns.addAll( blackList );
}
}
}
catch( IOException ex )
{
log.info("Unable to read attachment data, continuing...",ex);
}
catch( ProviderException ex )
{
log.info("Failed to read spam filter attachment, continuing...",ex);
}
}
/**
* Does a check against a known pattern list.
*
* @param context
* @param content
* @param change
* @throws RedirectException
*/
private void checkPatternList(WikiContext context, String content, String change) throws RedirectException
{
// If we have no spam patterns defined, or we're trying to save
// the page containing the patterns, just return.
if( m_spamPatterns == null || context.getPage().getName().equals( m_forbiddenWordsPage ) )
{
return;
}
if( context.getHttpRequest() != null )
change += context.getHttpRequest().getRemoteAddr();
for( Iterator i = m_spamPatterns.iterator(); i.hasNext(); )
{
Pattern p = (Pattern) i.next();
// log.debug("Attempting to match page contents with "+p.getPattern());
if( m_matcher.contains( change, p ) )
{
// Spam filter has a match.
String uid = log( context, REJECT, REASON_REGEXP+"("+p.getPattern()+")", change);
log.info("SPAM:Regexp ("+uid+"). Content matches the spam filter '"+p.getPattern()+"'");
checkStrategy( context, REASON_REGEXP, "Herb says '"+p.getPattern()+"' is a bad spam word and I trust Herb! (Incident code "+uid+")");
}
}
}
/**
* Creates a simple text string describing the added content.
*
* @param context
* @param newText
* @return Empty string, if there is no change.
*/
private static String getChange( WikiContext context, String newText )
{
WikiPage page = context.getPage();
StringBuffer change = new StringBuffer();
WikiEngine engine = context.getEngine();
// Get current page version
try
{
String oldText = engine.getPureText(page.getName(), WikiProvider.LATEST_VERSION);
String[] first = Diff.stringToArray(oldText);
String[] second = Diff.stringToArray(newText);
Revision rev = Diff.diff(first, second, new MyersDiff());
if( rev == null || rev.size() == 0 )
{
return "";
}
for( int i = 0; i < rev.size(); i++ )
{
Delta d = rev.getDelta(i);
if( d instanceof AddDelta )
{
d.getRevised().toString( change, "", "\r\n" );
}
else if( d instanceof ChangeDelta )
{
d.getRevised().toString( change, "", "\r\n" );
}
}
}
catch (DifferentiationFailedException e)
{
log.error( "Diff failed", e );
}
// Don't forget to include the change note, too
String changeNote = (String)page.getAttribute(WikiPage.CHANGENOTE);
if( changeNote != null )
{
change.append("\r\n");
change.append(changeNote);
}
// And author as well
if( page.getAuthor() != null )
{
change.append("\r\n"+page.getAuthor());
}
return change.toString();
}
/**
* Returns true, if this user should be ignored.
*
* @param context
* @return
*/
private boolean ignoreThisUser(WikiContext context)
{
if( context.hasAdminPermissions() )
{
return true;
}
if( m_ignoreAuthenticated && context.getWikiSession().isAuthenticated() )
{
return true;
}
if( context.getVariable("captcha") != null )
{
return true;
}
return false;
}
/**
* Returns a random string of six uppercase characters.
*
* @return A random string
*/
private static String getUniqueID()
{
StringBuffer sb = new StringBuffer();
Random rand = new Random();
for( int i = 0; i < 6; i++ )
{
char x = (char)('A'+rand.nextInt(26));
sb.append(x);
}
return sb.toString();
}
/**
* Returns a page to which we shall redirect, based on the current value
* of the "captcha" parameter.
*
* @param ctx WikiContext
* @return An URL to redirect to
*/
private String getRedirectPage( WikiContext ctx )
{
if( m_useCaptcha )
return ctx.getURL( WikiContext.NONE, "Captcha.jsp", "page="+ctx.getEngine().encodeName(ctx.getPage().getName()) );
return ctx.getURL( WikiContext.VIEW, m_errorPage );
}
/**
* Checks whether the UserProfile matches certain checks.
*
* @param profile
* @return
* @since 2.6.1
*/
public boolean isValidUserProfile( WikiContext context, UserProfile profile )
{
try
{
checkPatternList( context, profile.getEmail(), profile.getEmail() );
checkPatternList( context, profile.getFullname(), profile.getFullname() );
checkPatternList( context, profile.getLoginName(), profile.getLoginName() );
}
catch( RedirectException e )
{
log.info("Detected attempt to create a spammer user account (see above for rejection reason)");
return false;
}
return true;
}
/**
* This method is used to calculate an unique code when submitting the page
* to detect edit conflicts. It currently incorporates the last-modified
* date of the page, and the IP address of the submitter.
*
* @param page The WikiPage under edit
* @param request The HTTP Request
* @since 2.6
* @return A hash value for this page and session
*/
public static final String getSpamHash( WikiPage page, HttpServletRequest request )
{
long lastModified = 0;
if( page.getLastModified() != null )
lastModified = page.getLastModified().getTime();
long remote = request.getRemoteAddr().hashCode();
return Long.toString( lastModified ^ remote );
}
/**
* Returns the name of the hash field to be used in this request.
* The value is unique per session, and once the session has expired,
* you cannot edit anymore.
*
* @param request The page request
* @return The name to be used in the hash field
* @since 2.6
*/
private static String c_hashName;
private static long c_lastUpdate;
/** The HASH_DELAY value is a maximum amount of time that an user can keep
* a session open, because after the value has expired, we will invent a new
* hash field name. By default this is {@value} hours, which should be ample
* time for someone.
*/
private static final long HASH_DELAY = 24;
public static final String getHashFieldName( HttpServletRequest request )
{
String hash = null;
if( request.getSession() != null )
{
hash = (String)request.getSession().getAttribute("_hash");
if( hash == null )
{
hash = c_hashName;
request.getSession().setAttribute( "_hash", hash );
}
}
if( c_hashName == null || c_lastUpdate < (System.currentTimeMillis() - HASH_DELAY*60*60*1000) )
{
c_hashName = getUniqueID().toLowerCase();
c_lastUpdate = System.currentTimeMillis();
}
return hash != null ? hash : c_hashName;
}
/**
* This method checks if the hash value is still valid, i.e. if it exists at all. This
* can occur in two cases: either this is a spam bot which is not adaptive, or it is
* someone who has been editing one page for too long, and their session has expired.
* <p>
* This method puts a redirect to the http response field to page "SessionExpired"
* and logs the incident in the spam log (it may or may not be spam, but it's rather likely
* that it is).
*
* @param context
* @param pageContext
* @return True, if hash is okay. False, if hash is not okay, and you need to redirect.
* @throws IOException If redirection fails
* @since 2.6
*/
public static final boolean checkHash( WikiContext context, PageContext pageContext )
throws IOException
{
String hashName = getHashFieldName( (HttpServletRequest)pageContext.getRequest() );
if( pageContext.getRequest().getParameter(hashName) == null )
{
if( pageContext.getAttribute( hashName ) == null )
{
String change = getChange( context, EditorManager.getEditedText( pageContext ) );
log( context, REJECT, "MissingHash", change );
String redirect = context.getURL(WikiContext.VIEW,"SessionExpired");
((HttpServletResponse)pageContext.getResponse()).sendRedirect( redirect );
return false;
}
}
return true;
}
public static final String insertInputFields( PageContext pageContext )
{
WikiContext ctx = WikiContext.findContext(pageContext);
WikiEngine engine = ctx.getEngine();
StringBuffer sb = new StringBuffer();
if (engine.getContentEncoding().equals("UTF-8"))
{
sb.append("<input name='encodingcheck' type='hidden' value='\u3041' />\n");
}
return sb.toString();
}
/**
* A local class for storing host information.
*
* @author jalkanen
*
* @since
*/
private class Host
{
private long m_addedTime = System.currentTimeMillis();
private long m_releaseTime;
private String m_address;
private String m_change;
public String getAddress()
{
return m_address;
}
public long getReleaseTime()
{
return m_releaseTime;
}
public long getAddedTime()
{
return m_addedTime;
}
public String getChange()
{
return m_change;
}
public Host( String ipaddress, String change )
{
m_address = ipaddress;
m_change = change;
m_releaseTime = System.currentTimeMillis() + m_banTime * 60 * 1000L;
}
}
} |
package us.cyrien.minecordbot.commands.minecraftCommand;
import io.github.hedgehog1029.frame.annotations.Command;
import io.github.hedgehog1029.frame.annotations.Permission;
import io.github.hedgehog1029.frame.annotations.Sender;
import io.github.hedgehog1029.frame.annotations.Text;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import us.cyrien.minecordbot.entity.Messenger;
import us.cyrien.minecordbot.main.Minecordbot;
public class Dme {
@Command(aliases = "dme", usage = "/dme <action>", desc = "/me command but for discord.")
@Permission("minecordbot.dme")
public void command(@Sender CommandSender sender, @Text String arg) {
if(sender instanceof Player) {
Player p = (Player) sender;
for (Player pl : Bukkit.getServer().getOnlinePlayers())
pl.sendMessage(ChatColor.translateAlternateColorCodes('&', "&5* " + "&r" + p.getDisplayName() + " &5" + arg));
new Messenger(Minecordbot.getInstance()).sendMessageToAllBoundChannel("**" + p.getName() + "** " + "_" + arg + "_");
} else {
sender.sendMessage("Only players can do that execute /dme command");
}
}
} |
package com.epictodo.controller.json;
import com.epictodo.model.Task;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Storage {
private static Logger _logger = Logger.getLogger("
private static final String file_name = "storage.txt";
/**
* This method instantiates a GSON Object.
* Method will read JSON Object from memory and translates to JSON.
*
* @return _gson
*/
private static Gson instantiateObject() {
GsonBuilder gson_builder = new GsonBuilder();
gson_builder.setPrettyPrinting()
.serializeNulls()
.disableHtmlEscaping()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson _gson = gson_builder.create();
return _gson;
}
/**
* This method saves ArrayList<Task> from memory object to Json file.
*
* @param file_name
* @param array_list
* @return true
*/
public static boolean saveToJson(String file_name, ArrayList<Task> array_list) {
assert file_name.equalsIgnoreCase(file_name);
_logger.log(Level.INFO, "Filename: \'storage.txt\' has been asserted.");
try {
FileWriter file_writer = new FileWriter(file_name);
Gson _gson = instantiateObject();
String json_result = _gson.toJson(array_list);
if (array_list.isEmpty() || array_list == null) {
_logger.log(Level.WARNING, "ArrayList<Task> is empty.");
file_writer.write("");
} else {
file_writer.write(json_result);
_logger.log(Level.INFO, "Successfully stored JSON results to Storage");
}
file_writer.close();
} catch(IOException ex) {
ex.printStackTrace();
return false;
}
return true;
}
/**
* This method loads the Json file to ArrayList<Task> of memory objects
*
* @param file_name
* @return _result
*/
public static ArrayList<Task> loadDbFile(String file_name) {
ArrayList<Task> _result = new ArrayList<Task>();
assert file_name.equalsIgnoreCase(file_name);
_logger.log(Level.INFO, "Filename: \'storage.txt\' has been asserted.");
try {
FileReader _reader = new FileReader(file_name);
Gson _gson = instantiateObject();
TypeToken<ArrayList<Task>> type_token = new TypeToken<ArrayList<Task>>(){};
_result = _gson.fromJson(_reader, type_token.getType());
} catch(IOException ex) {
ex.printStackTrace();
return null;
}
return _result;
}
} |
package edu.team597;
import edu.team597.support.Utility;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.Timer;
/**
*
* @author Team597
*/
public class Drive {
public static class DriveStateMachine {
//State Machine values
public static final int OPERATOR_CTRL = 0;
public static final int SET_CONTROL = 1;
public static final int INVERT_CTRL = 2;
}
Talon motorRight1;
Talon motorRight2;
Talon motorLeft1;
Talon motorLeft2;
DoubleSolenoid solenoidShifter;
Joystick joystickLeft;
Joystick joystickRight;
Timer timerAutonomous;
Relay driveLEDLightChannel1;
Relay driveLEDLightChannel2;
DigitalInput diBallSettle;
long lastPrint = System.currentTimeMillis();
int driveState = DriveStateMachine.OPERATOR_CTRL;
double motorSpeedSetValueLeft = 0;
double motorSpeedSetValueRight = 0;
boolean invertedMotorSpeed = false;
boolean shifterOnSetValue = false;
double MOTOR_LEFT_DRIVE_SPEED = .5;
double MOTOR_RIGHT_DRIVE_SPEED = .5;
//double DEADZONE_JOYSTICK_THRESHOLD = 0.1;
int autonomousShifterState = 1;
public Drive(Joystick j1, Joystick j2, Relay relayLEDLightChannel1, Relay relayLEDLightChannel2, DigitalInput diBallLimit) {
joystickLeft = j1;
joystickRight = j2;
solenoidShifter = new DoubleSolenoid(3, 4);
motorRight1 = new Talon(1);
motorRight2 = new Talon(2);
motorLeft1 = new Talon(3);
motorLeft2 = new Talon(4);
timerAutonomous = new Timer();
driveLEDLightChannel1 = relayLEDLightChannel1;
driveLEDLightChannel2 = relayLEDLightChannel2;
diBallSettle = diBallLimit;
}
public void Initialize() {
autonomousShifterState = 1;
timerAutonomous.reset();
timerAutonomous.start();
}
public void Periodic() {
autonomousShifterState = 1;
if (System.currentTimeMillis() >= lastPrint) {
System.out.println("!@
System.out.println("SolenoidShifter: " + shifterOnSetValue);
System.out.println("!@#$%^&*()_+!@#$%^&*()_+!@#$%^&*()_+!@#$%^&*()_123456890-123456890");
lastPrint += 1000;
}
//Main Drive State Machine
switch (driveState) {
case DriveStateMachine.OPERATOR_CTRL:
if (invertedMotorSpeed) {
motorRight1.set((-joystickLeft.getY()));
motorRight2.set((-joystickLeft.getY()));
motorLeft1.set((joystickRight.getY()));
motorLeft2.set((joystickRight.getY()));
} else {
motorRight1.set((joystickRight.getY()));
motorRight2.set((joystickRight.getY()));
motorLeft1.set((-joystickLeft.getY()));
motorLeft2.set((-joystickLeft.getY()));
}
//Torque Drive
if (joystickLeft.getRawButton(1)) {
shifterOnSetValue = true;
solenoidShifter.set(DoubleSolenoid.Value.kReverse);
}
//Speed Drive
if (joystickRight.getRawButton(1)) {
shifterOnSetValue = false;
solenoidShifter.set(DoubleSolenoid.Value.kForward);
}
if (shifterOnSetValue) {
solenoidShifter.set(DoubleSolenoid.Value.kReverse);
driveLEDLightChannel1.set(Relay.Value.kOff);
driveLEDLightChannel2.set(Relay.Value.kOn);
} else {
solenoidShifter.set(DoubleSolenoid.Value.kForward);
driveLEDLightChannel1.set(Relay.Value.kOn);
driveLEDLightChannel2.set(Relay.Value.kOff);
}
if (diBallSettle.get() == true) {
if (shifterOnSetValue) {
driveLEDLightChannel1.set(Relay.Value.kOff);
driveLEDLightChannel2.set(Relay.Value.kOn);
}
else {
driveLEDLightChannel1.set(Relay.Value.kOn);
driveLEDLightChannel2.set(Relay.Value.kOff);
}
}
//if (driveLEDLightChannel1.get() != Relay.Value.kForward && driveLEDLightChannel2.get() != Relay.Value.kForward) {
//Invert Drive
if (joystickRight.getRawButton(10)) {
invertedMotorSpeed = true;
}
//Regular Drive
if (joystickRight.getRawButton(11)) {
invertedMotorSpeed = false;
}
break;
case DriveStateMachine.SET_CONTROL:
//Regular Robot Drive Set Value
motorRight1.set(-motorSpeedSetValueRight);
motorRight2.set(-motorSpeedSetValueRight);
motorLeft1.set(motorSpeedSetValueLeft);
motorLeft2.set(motorSpeedSetValueLeft);
//Torque Drive Set Value if true, else Speed
if (shifterOnSetValue) {
solenoidShifter.set(DoubleSolenoid.Value.kReverse);
} else {
solenoidShifter.set(DoubleSolenoid.Value.kForward);
}
/* if (shifterOnSetValue) {
} else {
}*/
break;
}
}
//Enables Operator State if true
public void SetOperatorState(boolean operatorState) {
if (operatorState) {
driveState = DriveStateMachine.OPERATOR_CTRL;
} else {
driveState = DriveStateMachine.SET_CONTROL;
motorSpeedSetValueRight = 0;
motorSpeedSetValueLeft = 0;
shifterOnSetValue = false;
}
}
//Left motors Set Value
public void SetMotorSpeedValueRight(double inputMotorSpeed) {
motorSpeedSetValueRight = Utility.Bound(inputMotorSpeed, -1, 1);
}
//Right motors Set Value
public void SetMotorSpeedValueLeft(double inputMotorSpeed) {
motorSpeedSetValueLeft = Utility.Bound(inputMotorSpeed, -1, 1);
}
//Shifting Set Value
public void SetShifterState(boolean inputShifterOn) {
shifterOnSetValue = inputShifterOn;
if (shifterOnSetValue) {
solenoidShifter.set(DoubleSolenoid.Value.kReverse);
driveLEDLightChannel1.set(Relay.Value.kOff);
driveLEDLightChannel2.set(Relay.Value.kOn);
} else {
solenoidShifter.set(DoubleSolenoid.Value.kForward);
driveLEDLightChannel1.set(Relay.Value.kOn);
driveLEDLightChannel2.set(Relay.Value.kOff);
}
}
} |
package com.fedorvlasov.lazylist;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.Stack;
import java.util.WeakHashMap;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class ImageLoader {
MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
public ImageLoader(Context context){
//Make the background thead low priority. This way it will not affect the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
fileCache=new FileCache(context);
}
final int stub_id=R.drawable.stub;
public void DisplayImage(String url, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad p=new PhotoToLoad(url, imageView);
synchronized(photosToLoad){
photosToLoad.push(p);
photosToLoad.notifyAll();
}
//start thread if it's not started yet
if(photoLoaderThread.getState()==Thread.State.NEW)
photoLoaderThread.start();
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
public void stopThread()
{
photoLoaderThread.interrupt();
}
//stores list of photos to download
private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();
class PhotosLoader extends Thread {
public void run() {
try {
while(true)
{
//thread waits until there are any images to load in the queue
if(photosToLoad.size()==0)
synchronized(photosToLoad){
photosToLoad.wait();
}
if(photosToLoad.size()!=0)
{
PhotoToLoad photoToLoad;
synchronized(photosToLoad){
photoToLoad=photosToLoad.pop();
}
if(imageViewReused(photoToLoad))
continue;
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
continue;
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
if(Thread.interrupted())
break;
}
} catch (InterruptedException e) {
//allow thread to exit
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
if(tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
PhotosLoader photoLoaderThread=new PhotosLoader();
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
} |
package org.wyona.yanel.servlet;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.wyona.security.core.api.Identity;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.api.attributes.VersionableV2;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.map.Map;
import org.wyona.yanel.core.util.ResourceAttributeHelper;
/**
* Generates the Yanel toolbar
*/
class YanelHTMLUI {
private static final String TOOLBAR_KEY = "toolbar";
private String reservedPrefix;
private Map map;
private static Logger log = Logger.getLogger(YanelHTMLUI.class);
YanelHTMLUI(Map map, String reservedPrefix) {
this.reservedPrefix = reservedPrefix;
this.map = map;
}
/**
* Checks if the yanel.toolbar request parameter is set and stores
* the value of the parameter in the session.
* @param request
*/
void switchToolbar(HttpServletRequest request) {
// Check for toolbar ...
String yanelToolbar = request.getParameter("yanel.toolbar");
if(yanelToolbar != null) {
if (yanelToolbar.equals("on")) {
log.info("Turn on toolbar!");
enableToolbar(request);
} else if (yanelToolbar.equals("off")) {
log.info("Turn off toolbar!");
disableToolbar(request);
} else {
log.warn("No such toolbar value: " + yanelToolbar);
}
}
}
/**
* Get toolbar menus
*/
private String getToolbarMenus(Resource resource, HttpServletRequest request) throws ServletException, IOException, Exception {
org.wyona.yanel.servlet.menu.Menu menu = null;
String menuRealmClass = resource.getRealm().getMenuClass();
if (menuRealmClass != null) {
menu = (org.wyona.yanel.servlet.menu.Menu) Class.forName(menuRealmClass).newInstance();
// TODO: Check resource configuration ...
//} else if (RESOURCE) {
} else {
menu = new org.wyona.yanel.servlet.menu.impl.DefaultMenu();
}
final String reservedPrefix = this.reservedPrefix;
final Map map = this.map;
return menu.getAllMenus(resource, request, map, reservedPrefix);
}
/**
* Gets the part of the toolbar which has to be inserted into the html header.
* @param resource
* @param request
* @return
* @throws Exception
*/
private String getToolbarHeader(Resource resource, HttpServletRequest request) throws Exception {
final String reservedPrefix = this.reservedPrefix;
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath());
StringBuilder sb= new StringBuilder();
sb.append("<!-- START: Dynamically added code by " + this.getClass().getName() + " -->");
sb.append(System.getProperty("line.separator"));
sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbar.css\" rel=\"stylesheet\"/>");
sb.append(System.getProperty("line.separator"));
sb.append("<style type=\"text/css\" media=\"screen\">");
sb.append(System.getProperty("line.separator"));
sb.append("#yaneltoolbar_menu li li.haschild{ background: lightgrey url(" + backToRealm + reservedPrefix + "/yanel-img/submenu.gif) no-repeat 98% 50%;}");
sb.append(System.getProperty("line.separator"));
sb.append("#yaneltoolbar_menu li li.haschild:hover{ background: lightsteelblue url(" + backToRealm + reservedPrefix + "/yanel-img/submenu.gif) no-repeat 98% 50%;}");
sb.append("</style>");
sb.append(System.getProperty("line.separator"));
// If browser is Mozilla (gecko engine rv:1.7)
if (request.getHeader("User-Agent").indexOf("rv:1.7") >= 0) {
sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarMozilla.css\" rel=\"stylesheet\"/>");
sb.append(System.getProperty("line.separator"));
}
// If browser is IE
if (request.getHeader("User-Agent").indexOf("compatible; MSIE") >= 0 && request.getHeader("User-Agent").indexOf("Windows") >= 0 ) {
sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarIE.css\" rel=\"stylesheet\"/>");
sb.append(System.getProperty("line.separator"));
sb.append("<style type=\"text/css\" media=\"screen\">");
sb.append(" body{behavior:url(" + backToRealm + reservedPrefix + "/csshover.htc);font-size:100%;}");
sb.append("</style>");
}
// If browser is IE6
if (request.getHeader("User-Agent").indexOf("compatible; MSIE 6") >= 0 && request.getHeader("User-Agent").indexOf("Windows") >= 0 ) {
sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarIE6.css\" rel=\"stylesheet\"/>");
sb.append(System.getProperty("line.separator"));
}
sb.append("<!-- END: Dynamically added code by " + this.getClass().getName() + " -->");
return sb.toString();
}
/**
* Gets the part of the toolbar which has to be inserted into the html body
* right after the opening body tag.
* @param resource
* @return
* @throws Exception
*/
private String getToolbarBodyStart(Resource resource, HttpServletRequest request) throws Exception {
final String reservedPrefix = this.reservedPrefix;
final Map map = this.map;
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath());
StringBuilder buf = new StringBuilder();
buf.append("<div id=\"yaneltoolbar_headerwrap\">");
buf.append("<div id=\"yaneltoolbar_menu\">");
buf.append(getToolbarMenus(resource, request));
buf.append("</div>");
buf.append(getInfo(resource, request));
buf.append("<span id=\"yaneltoolbar_logo\">");
buf.append("<img src=\"" + backToRealm + reservedPrefix + "/yanel_toolbar_logo.png\"/>");
buf.append("</span>");
buf.append("</div>");
buf.append("<div id=\"yaneltoolbar_middlewrap\">");
return buf.toString();
}
/**
* Gets the part of the toolbar which has to be inserted into the html body
* right before the closing body tag.
* @param resource
* @return
* @throws Exception
*/
private String getToolbarBodyEnd(Resource resource, HttpServletRequest request) throws Exception {
return "</div>";
}
/**
* Merges the toolbar and the page content. This will parse the html stream and add
* the toolbar.
* @param response
* @param resource
* @param view
* @throws Exception
*/
void mergeToolbarWithContent(HttpServletRequest request, HttpServletResponse response, Resource resource, View view) throws Exception {
final int INSIDE_TAG = 0;
final int OUTSIDE_TAG = 1;
String encoding = view.getEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
InputStreamReader reader = new InputStreamReader(view.getInputStream(), encoding);
OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), encoding);
int c;
int state = OUTSIDE_TAG;
StringBuffer tagBuf = null;
boolean headExists = false;
int headcount = 0;
int bodycount = 0;
while ((c = reader.read()) != -1) {
switch (state) {
case OUTSIDE_TAG:
if (c == '<') {
tagBuf = new StringBuffer("<");
state = INSIDE_TAG;
} else {
writer.write(c);
}
break;
case INSIDE_TAG:
if (c == '>') {
state = OUTSIDE_TAG;
tagBuf.append((char)c);
String tag = tagBuf.toString();
if (tag.startsWith("<head")) {
headExists = true;
if (headcount == 0) {
writer.write(tag, 0, tag.length());
String toolbarString = getToolbarHeader(resource, request);
writer.write(toolbarString, 0, toolbarString.length());
} else {
writer.write(tag, 0, tag.length());
}
headcount++;
} else if (tag.startsWith("<body")) {
if (!headExists) {
log.warn("No <head> exists. Hence <head> will be added dynamically.");
String headStartTag = "<head>";
writer.write(headStartTag, 0, headStartTag.length());
String toolbarString = getToolbarHeader(resource, request);
writer.write(toolbarString, 0, toolbarString.length());
String headEndTag = "</head>";
writer.write(headEndTag, 0, headEndTag.length());
headExists = true;
}
if (bodycount == 0) {
writer.write(tag, 0, tag.length());
String toolbarString = getToolbarBodyStart(resource, request);
writer.write(toolbarString, 0, toolbarString.length());
} else {
writer.write(tag, 0, tag.length());
}
bodycount++;
} else if (tag.equals("</body>")) {
bodycount
if (bodycount == 0) {
String toolbarString = getToolbarBodyEnd(resource, request);
writer.write(toolbarString, 0, toolbarString.length());
writer.write(tag, 0, tag.length());
} else {
writer.write(tag, 0, tag.length());
}
} else {
writer.write(tag, 0, tag.length());
}
} else {
tagBuf.append((char)c);
}
break;
}
}
writer.flush();
writer.close();
reader.close();
if (!headExists) {
log.warn("Does not seem to be a (X)HTML document: " + request.getRequestURL());
}
}
void enableToolbar(HttpServletRequest request) {
request.getSession(true).setAttribute(TOOLBAR_KEY, "on");
}
void disableToolbar(HttpServletRequest request) {
request.getSession(true).setAttribute(TOOLBAR_KEY, "off");
}
boolean isToolbarEnabled(HttpServletRequest request) {
String toolbarStatus = (String) request.getSession(true).getAttribute(TOOLBAR_KEY);
if (toolbarStatus != null && toolbarStatus.equals("on")) {
String yanelToolbar = request.getParameter("yanel.toolbar");
if(yanelToolbar != null && request.getParameter("yanel.toolbar").equals("suppress")) {
return false;
} else {
return true;
}
}
return false;
}
/**
* Get information such as realm name, user name, etc.
*/
private String getInfo(Resource resource, HttpServletRequest request) throws Exception {
// TODO: i18n
StringBuilder buf = new StringBuilder();
buf.append("<span id=\"yaneltoolbar_info\">");
//buf.append("Version: " + yanel.getVersion() + "-r" + yanel.getRevision() + "  ");
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) {
VersionableV2 versionableRes = (VersionableV2)resource;
if (versionableRes.isCheckedOut()) {
buf.append("Page: <b>" + "Locked by " + versionableRes.getCheckoutUserID() + "</b>  ");
}
}
buf.append("Realm: <b>" + resource.getRealm().getName() + "</b>  ");
Identity identity = YanelServlet.getIdentity(request, map);
if (identity != null && !identity.isWorld()) {
buf.append("User: <b>" + identity.getUsername() + "</b>");
} else {
buf.append("User: <b>Not signed in!</b>");
}
buf.append("</span>");
return buf.toString();
}
} |
package com.fedorvlasov.lazylist;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class ImageLoader {
MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
public ImageLoader(Context context, int stubDrawable){
fileCache=new FileCache(context);
executorService=Executors.newFixedThreadPool(5);
stub_id = stubDrawable;
}
int stub_id;
public void displayImage(String url, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad p=new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
@Override
public void run() {
if(imageViewReused(photoToLoad))
return;
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
if(tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
} |
package mud;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Embedded;
import org.mongodb.morphia.annotations.Id;
import org.mongodb.morphia.annotations.Property;
import org.mongodb.morphia.annotations.Reference;
import org.bson.types.ObjectId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
@Entity("players")
public class MudPlayer {
@Id private String id;
private Date lastSeen;
int sessions;
int interactions;
@Reference
private MudRoom room;
@Embedded("inventory")
private Map<String, MudItem> inventory = new HashMap<String, MudItem>();
public MudPlayer() {
sessions = 0;
interactions = 0;
}
public String getId() {
return id;
}
public void setId(String ID) {
id = ID;
}
public MudRoom getRoom() {
return room;
}
public void setRoom(MudRoom newRoom) {
if (room != null)
room = newRoom;
}
public int addItem(MudItem mudItem) {
return MudItemMapHelper.addItem(inventory, mudItem);
}
public MudItem removeItem(String name) {
return MudItemMapHelper.removeItem(inventory, name);
}
public boolean hasItem(String name) {
return MudItemMapHelper.hasItem(inventory, name);
}
public MudItem getItemIfExists(String name) {
return MudItemMapHelper.getItemIfExists(inventory, name);
}
public List<MudItem> getItemListIfExistsByFullName(String name) {
return MudItemMapHelper.getItemListIfExistsByFullName(inventory, name);
}
public int getInventorySize() {
return inventory.size();
}
public boolean dropItem(String item) {
MudItem mudItem = removeItem(item);
if (mudItem == null)
return false;
room.addItem(mudItem);
return true;
}
public Date getLastSeen() {
return lastSeen;
}
public void updateLastSeen() {
lastSeen = new Date();
}
} |
package com.jmex.effects.water;
import com.jme.math.*;
import com.jme.renderer.AbstractCamera;
import com.jme.renderer.Camera;
import com.jme.renderer.Renderer;
import com.jme.scene.Spatial;
import com.jme.scene.TriMesh;
import com.jme.scene.VBOInfo;
import com.jme.scene.batch.TriangleBatch;
import com.jme.util.Timer;
import com.jme.util.geom.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.glu.GLU;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
/**
* <code>ProjectedGrid</code>
* Projected grid mesh
*
* @author Rikard Herlitz (MrCoder)
*/
public class ProjectedGrid extends TriMesh {
private int sizeX;
private int sizeY;
//x/z step
private static Vector3f calcVec1 = new Vector3f();
private static Vector3f calcVec2 = new Vector3f();
private static Vector3f calcVec3 = new Vector3f();
private TriangleBatch geomBatch;
private int vertQuantity;
private FloatBuffer vertBuf;
private FloatBuffer normBuf;
private FloatBuffer texs;
private IntBuffer indexBuffer;
private float viewPortWidth = 0;
private float viewPortHeight = 0;
private float viewPortLeft = 0;
private float viewPortBottom = 0;
private Quaternion origin = new Quaternion();
private Quaternion direction = new Quaternion();
private Vector2f source = new Vector2f();
private Matrix4f modelViewMatrix = new Matrix4f();
private Matrix4f projectionMatrix = new Matrix4f();
private Matrix4f modelViewProjectionInverse = new Matrix4f();
private Quaternion intersectBottomLeft = new Quaternion();
private Quaternion intersectTopLeft = new Quaternion();
private Quaternion intersectTopRight = new Quaternion();
private Quaternion intersectBottomRight = new Quaternion();
private Matrix4f modelViewMatrix1 = new Matrix4f();
private Matrix4f projectionMatrix1 = new Matrix4f();
private Matrix4f modelViewProjection1 = new Matrix4f();
private Matrix4f modelViewProjectionInverse1 = new Matrix4f();
private Quaternion intersectBottomLeft1 = new Quaternion();
private Quaternion intersectTopLeft1 = new Quaternion();
private Quaternion intersectTopRight1 = new Quaternion();
private Quaternion intersectBottomRight1 = new Quaternion();
private Vector3f camloc = new Vector3f();
private Vector3f camdir = new Vector3f();
private Quaternion pointFinal = new Quaternion();
private Quaternion pointTop = new Quaternion();
private Quaternion pointBottom = new Quaternion();
private Vector3f realPoint = new Vector3f();
public boolean freezeProjector = false;
public boolean useReal = false;
private Vector3f projectorLoc = new Vector3f();
private Vector3f limit = new Vector3f();
private Timer timer;
private Camera cam;
private HeightGenerator heightGenerator;
private float textureScale;
private float[] vertBufArray;
private float[] normBufArray;
private float[] texBufArray;
public ProjectedGrid( String name, Camera cam, int sizeX, int sizeY, float texureScale, HeightGenerator heightGenerator ) {
super( name );
this.sizeX = sizeX;
this.sizeY = sizeY;
this.textureScale = texureScale;
this.heightGenerator = heightGenerator;
this.cam = cam;
timer = Timer.getTimer();
geomBatch = this.getBatch( 0 );
vertQuantity = sizeX * sizeY;
geomBatch.setVertexCount( vertQuantity );
vertBufArray = new float[vertQuantity*3];
normBufArray = new float[vertQuantity*3];
texBufArray = new float[vertQuantity*2];
buildVertices();
buildTextureCoordinates();
buildNormals();
}
public void switchFreeze() {
freezeProjector = !freezeProjector;
}
public void draw( Renderer r ) {
update();
super.draw( r );
}
public void update() {
if( freezeProjector ) return;
float time = timer.getTimeInSeconds();
camloc.set( cam.getLocation() );
camdir.set( cam.getDirection() );
AbstractCamera camera = (AbstractCamera) cam;
viewPortWidth = camera.getWidth();
viewPortHeight = camera.getHeight();
viewPortLeft = camera.getViewPortLeft();
viewPortBottom = camera.getViewPortBottom();
modelViewMatrix.set( camera.getModelViewMatrix() );
projectionMatrix.set( camera.getProjectionMatrix() );
modelViewProjectionInverse.set( modelViewMatrix ).multLocal( projectionMatrix );
modelViewProjectionInverse.invertLocal();
source.set( 0.5f, 0.5f );
getWorldIntersection( source, modelViewProjectionInverse, pointFinal );
pointFinal.multLocal( 1.0f / pointFinal.w );
realPoint.set( pointFinal.x, pointFinal.y, pointFinal.z );
projectorLoc.set( cam.getLocation() );
realPoint.set( projectorLoc ).addLocal( cam.getDirection() );
Matrix4f rangeMatrix = null;
if( useReal ) {
Vector3f fakeLoc = new Vector3f( projectorLoc );
Vector3f fakePoint = new Vector3f( realPoint );
fakeLoc.addLocal( 0, 1000, 0 );
rangeMatrix = getMinMax( fakeLoc, fakePoint, cam );
}
matrixLookAt( projectorLoc, realPoint, modelViewMatrix );
matrixProjection( 55.0f, viewPortWidth / viewPortHeight, cam.getFrustumNear(), cam.getFrustumFar(), projectionMatrix );
modelViewProjectionInverse.set( modelViewMatrix ).multLocal( projectionMatrix );
modelViewProjectionInverse.invertLocal();
if( useReal && rangeMatrix != null ) {
rangeMatrix.multLocal( modelViewProjectionInverse );
modelViewProjectionInverse.set( rangeMatrix );
}
source.set( 0, 0 );
getWorldIntersection( source, modelViewProjectionInverse, intersectBottomLeft );
source.set( 0, 1 );
getWorldIntersection( source, modelViewProjectionInverse, intersectTopLeft );
source.set( 1, 1 );
getWorldIntersection( source, modelViewProjectionInverse, intersectTopRight );
source.set( 1, 0 );
getWorldIntersection( source, modelViewProjectionInverse, intersectBottomRight );
tmpVec.set( cam.getLocation() ).addLocal( cam.getDirection() );
matrixLookAt( cam.getLocation(), tmpVec, null );
matrixProjection( 45.0f, viewPortWidth / viewPortHeight, cam.getFrustumNear(), cam.getFrustumFar(), null );
vertBuf.rewind();
float du = 1.0f / (float) (sizeX - 1);
float dv = 1.0f / (float) (sizeY - 1);
float u = 0, v = 0;
int index = 0;
for( int y = 0; y < sizeY; y++ ) {
for( int x = 0; x < sizeX; x++ ) {
interpolate( intersectTopLeft, intersectTopRight, u, pointTop );
interpolate( intersectBottomLeft, intersectBottomRight, u, pointBottom );
interpolate( pointTop, pointBottom, v, pointFinal );
pointFinal.x /= pointFinal.w;
pointFinal.z /= pointFinal.w;
realPoint.set( pointFinal.x,
heightGenerator.getHeight( pointFinal.x, pointFinal.z, time ),
pointFinal.z );
vertBufArray[index++] = realPoint.x;
vertBufArray[index++] = realPoint.y;
vertBufArray[index++] = realPoint.z;
u += du;
}
v += dv;
u = 0;
}
vertBuf.put( vertBufArray );
texs.rewind();
for( int i = 0; i < vertQuantity; i++ ) {
texBufArray[i*2] = vertBufArray[i*3] * textureScale;
texBufArray[i*2+1] = vertBufArray[i*3+2] * textureScale;
}
texs.put( texBufArray );
normBuf.rewind();
oppositePoint.set( 0, 0, 0 );
adjacentPoint.set( 0, 0, 0 );
rootPoint.set( 0, 0, 0 );
tempNorm.set( 0, 0, 0 );
int adj = 0, opp = 0, normalIndex = 0;
for( int row = 0; row < sizeY; row++ ) {
for( int col = 0; col < sizeX; col++ ) {
if( row == sizeY - 1 ) {
if( col == sizeX - 1 ) { // last row, last col
// up cross left
adj = normalIndex - sizeX;
opp = normalIndex - 1;
}
else { // last row, except for last col
// right cross up
adj = normalIndex + 1;
opp = normalIndex - sizeX;
}
}
else {
if( col == sizeX - 1 ) { // last column except for last row
// left cross down
adj = normalIndex - 1;
opp = normalIndex + sizeX;
}
else { // most cases
// down cross right
adj = normalIndex + sizeX;
opp = normalIndex + 1;
}
}
rootPoint.set(vertBufArray[normalIndex*3],vertBufArray[normalIndex*3+1],vertBufArray[normalIndex*3+2]);
adjacentPoint.set(vertBufArray[adj*3],vertBufArray[adj*3+1],vertBufArray[adj*3+2]);
oppositePoint.set(vertBufArray[opp*3],vertBufArray[opp*3+1],vertBufArray[opp*3+2]);
tempNorm.set( adjacentPoint ).subtractLocal( rootPoint )
.crossLocal( oppositePoint.subtractLocal( rootPoint ) )
.normalizeLocal();
normBufArray[normalIndex*3] = tempNorm.x;
normBufArray[normalIndex*3+1] = tempNorm.y;
normBufArray[normalIndex*3+2] = tempNorm.z;
normalIndex++;
}
}
normBuf.put( normBufArray );
}
private Matrix4f getMinMax( Vector3f fakeLoc, Vector3f fakePoint, Camera cam ) {
Matrix4f rangeMatrix;
matrixLookAt( fakeLoc, fakePoint, modelViewMatrix1 );
matrixProjection( 45.0f, viewPortWidth / viewPortHeight, cam.getFrustumNear(), cam.getFrustumFar(), projectionMatrix1 );
modelViewProjection1.set( modelViewMatrix1 ).multLocal( projectionMatrix1 );
modelViewProjectionInverse1.set( modelViewProjection1 ).invertLocal();
source.set( 0, 0 );
getWorldIntersection( source, modelViewProjectionInverse, intersectBottomLeft1 );
source.set( 0, 1 );
getWorldIntersection( source, modelViewProjectionInverse, intersectTopLeft1 );
source.set( 1, 1 );
getWorldIntersection( source, modelViewProjectionInverse, intersectTopRight1 );
source.set( 1, 0 );
getWorldIntersection( source, modelViewProjectionInverse, intersectBottomRight1 );
Vector3f tmp = new Vector3f();
tmp.set( intersectBottomLeft.x, intersectBottomLeft.y, intersectBottomLeft.z );
modelViewProjection1.mult( tmp, tmp );
intersectBottomLeft.x = tmp.x;
intersectBottomLeft.y = tmp.y;
intersectBottomLeft.z = tmp.z;
tmp.set( intersectTopLeft1.x, intersectTopLeft1.y, intersectTopLeft1.z );
modelViewProjection1.mult( tmp, tmp );
intersectTopLeft1.x = tmp.x;
intersectTopLeft1.y = tmp.y;
intersectTopLeft1.z = tmp.z;
tmp.set( intersectTopRight1.x, intersectTopRight1.y, intersectTopRight1.z );
modelViewProjection1.mult( tmp, tmp );
intersectTopRight1.x = tmp.x;
intersectTopRight1.y = tmp.y;
intersectTopRight1.z = tmp.z;
tmp.set( intersectBottomRight1.x, intersectBottomRight1.y, intersectBottomRight1.z );
modelViewProjection1.mult( tmp, tmp );
intersectBottomRight1.x = tmp.x;
intersectBottomRight1.y = tmp.y;
intersectBottomRight1.z = tmp.z;
// modelViewProjection1.mult( intersectBottomLeft1, intersectBottomLeft1 );
// modelViewProjection1.mult( intersectTopLeft1, intersectTopLeft1 );
// modelViewProjection1.mult( intersectTopRight1, intersectTopRight1 );
// modelViewProjection1.mult( intersectBottomRight1, intersectBottomRight1 );
float minX = Float.MAX_VALUE, minY = Float.MAX_VALUE, maxX = Float.MIN_VALUE, maxY = Float.MIN_VALUE;
if( intersectBottomLeft1.x < minX ) minX = intersectBottomLeft1.x;
if( intersectTopLeft1.x < minX ) minX = intersectTopLeft1.x;
if( intersectTopRight1.x < minX ) minX = intersectTopRight1.x;
if( intersectBottomRight1.x < minX ) minX = intersectBottomRight1.x;
if( intersectBottomLeft1.x > maxX ) maxX = intersectBottomLeft1.x;
if( intersectTopLeft1.x > maxX ) maxX = intersectTopLeft1.x;
if( intersectTopRight1.x > maxX ) maxX = intersectTopRight1.x;
if( intersectBottomRight1.x > maxX ) maxX = intersectBottomRight1.x;
if( intersectBottomLeft1.y < minY ) minY = intersectBottomLeft1.y;
if( intersectTopLeft1.y < minY ) minY = intersectTopLeft1.y;
if( intersectTopRight1.y < minY ) minY = intersectTopRight1.y;
if( intersectBottomRight1.y < minY ) minY = intersectBottomRight1.y;
if( intersectBottomLeft1.y > maxY ) maxY = intersectBottomLeft1.y;
if( intersectTopLeft1.y > maxY ) maxY = intersectTopLeft1.y;
if( intersectTopRight1.y > maxY ) maxY = intersectTopRight1.y;
if( intersectBottomRight1.y > maxY ) maxY = intersectBottomRight1.y;
rangeMatrix = new Matrix4f(
maxX - minX, 0, 0, minX,
0, maxY - minY, 0, minY,
0, 0, 1, 0,
0, 0, 0, 1
);
System.out.println( minX );
System.out.println( maxX );
System.out.println( minY );
System.out.println( maxY );
System.out.println( rangeMatrix );
rangeMatrix.transpose();
return rangeMatrix;
}
private static final FloatBuffer tmp_FloatBuffer = org.lwjgl.BufferUtils.createFloatBuffer( 16 );
private Vector3f localDir = new Vector3f();
private Vector3f localLeft = new Vector3f();
private Vector3f localUp = new Vector3f();
private Vector3f tmpVec = new Vector3f();
private void matrixLookAt( Vector3f location, Vector3f at, Matrix4f result ) {
localDir.set( at ).subtractLocal( location ).normalizeLocal();
localDir.cross( Vector3f.UNIT_Y, localLeft );
localLeft.cross( localDir, localUp );
// set view matrix
GL11.glMatrixMode( GL11.GL_MODELVIEW );
GL11.glLoadIdentity();
GLU.gluLookAt(
location.x,
location.y,
location.z,
at.x,
at.y,
at.z,
localUp.x,
localUp.y,
localUp.z );
if( result != null ) {
tmp_FloatBuffer.rewind();
GL11.glGetFloat( GL11.GL_MODELVIEW_MATRIX, tmp_FloatBuffer );
tmp_FloatBuffer.rewind();
result.readFloatBuffer( tmp_FloatBuffer );
}
}
private void matrixProjection( float fovY, float aspect, float near, float far, Matrix4f result ) {
float h = FastMath.tan( fovY * FastMath.DEG_TO_RAD ) * near * .5f;
float w = h * aspect;
float frustumLeft = -w;
float frustumRight = w;
float frustumBottom = -h;
float frustumTop = h;
float frustumNear = near;
float frustumFar = far;
GL11.glMatrixMode( GL11.GL_PROJECTION );
GL11.glLoadIdentity();
GL11.glFrustum(
frustumLeft,
frustumRight,
frustumBottom,
frustumTop,
frustumNear,
frustumFar );
if( result != null ) {
tmp_FloatBuffer.rewind();
GL11.glGetFloat( GL11.GL_PROJECTION_MATRIX, tmp_FloatBuffer );
tmp_FloatBuffer.rewind();
result.readFloatBuffer( tmp_FloatBuffer );
}
}
private void interpolate( Quaternion beginVec, Quaternion finalVec, float changeAmnt, Quaternion resultVec ) {
resultVec.x = (1 - changeAmnt) * beginVec.x + changeAmnt * finalVec.x;
// resultVec.y = (1 - changeAmnt) * beginVec.y + changeAmnt * finalVec.y;
resultVec.z = (1 - changeAmnt) * beginVec.z + changeAmnt * finalVec.z;
resultVec.w = (1 - changeAmnt) * beginVec.w + changeAmnt * finalVec.w;
}
private void interpolate( Vector3f beginVec, Vector3f finalVec, float changeAmnt, Vector3f resultVec ) {
resultVec.x = (1 - changeAmnt) * beginVec.x + changeAmnt * finalVec.x;
resultVec.y = (1 - changeAmnt) * beginVec.y + changeAmnt * finalVec.y;
resultVec.z = (1 - changeAmnt) * beginVec.z + changeAmnt * finalVec.z;
}
private void getWorldIntersection( Vector2f screenPosition, Matrix4f viewProjectionMatrix, Quaternion store ) {
origin.set( screenPosition.x * 2 - 1, screenPosition.y * 2 - 1, -1, 1 );
direction.set( screenPosition.x * 2 - 1, screenPosition.y * 2 - 1, 1, 1 );
viewProjectionMatrix.mult( origin, origin );
viewProjectionMatrix.mult( direction, direction );
if( cam.getLocation().y > 0 ) {
if( direction.y > 0 ) {
direction.y = 0;
}
}
else {
if( direction.y < 0 ) {
direction.y = 0;
}
}
direction.subtractLocal( origin );
float t = -origin.y / direction.y;
direction.multLocal( t );
store.set( origin );
store.addLocal( direction );
}
public int getType() {
return (Spatial.GEOMETRY | Spatial.TRIMESH);
}
/**
* <code>setDetailTexture</code> copies the texture coordinates from the
* first texture channel to another channel specified by unit, mulitplying
* by the factor specified by repeat so that the texture in that channel
* will be repeated that many times across the block.
*
* @param unit channel to copy coords to
* @param repeat number of times to repeat the texture across and down the
* block
*/
public void setDetailTexture( int unit, int repeat ) {
copyTextureCoords( 0, unit, repeat );
}
/**
* <code>getSurfaceNormal</code> returns the normal of an arbitrary point
* on the terrain. The normal is linearly interpreted from the normals of
* the 4 nearest defined points. If the point provided is not within the
* bounds of the height map, null is returned.
*
* @param position the vector representing the location to find a normal at.
* @param store the Vector3f object to store the result in. If null, a new one
* is created.
* @return the normal vector at the provided location.
*/
public Vector3f getSurfaceNormal( Vector2f position, Vector3f store ) {
return getSurfaceNormal( position.x, position.y, store );
}
/**
* <code>getSurfaceNormal</code> returns the normal of an arbitrary point
* on the terrain. The normal is linearly interpreted from the normals of
* the 4 nearest defined points. If the point provided is not within the
* bounds of the height map, null is returned.
*
* @param position the vector representing the location to find a normal at. Only
* the x and z values are used.
* @param store the Vector3f object to store the result in. If null, a new one
* is created.
* @return the normal vector at the provided location.
*/
public Vector3f getSurfaceNormal( Vector3f position, Vector3f store ) {
return getSurfaceNormal( position.x, position.z, store );
}
/**
* <code>getSurfaceNormal</code> returns the normal of an arbitrary point
* on the terrain. The normal is linearly interpreted from the normals of
* the 4 nearest defined points. If the point provided is not within the
* bounds of the height map, null is returned.
*
* @param x the x coordinate to check.
* @param z the z coordinate to check.
* @param store the Vector3f object to store the result in. If null, a new one
* is created.
* @return the normal unit vector at the provided location.
*/
public Vector3f getSurfaceNormal( float x, float z, Vector3f store ) {
// x /= stepScale.x;
// z /= stepScale.z;
float col = FastMath.floor( x );
float row = FastMath.floor( z );
if( col < 0 || row < 0 || col >= sizeX - 1 || row >= sizeY - 1 ) {
return null;
}
float intOnX = x - col, intOnZ = z - row;
if( store == null ) store = new Vector3f();
Vector3f topLeft = store, topRight = calcVec1, bottomLeft = calcVec2, bottomRight = calcVec3;
int focalSpot = (int) (col + row * sizeX);
// find the heightmap point closest to this position (but will always
// be to the left ( < x) and above (< z) of the spot.
BufferUtils.populateFromBuffer( topLeft, normBuf, focalSpot );
// now find the next point to the right of topLeft's position...
BufferUtils.populateFromBuffer( topRight, normBuf, focalSpot + 1 );
// now find the next point below topLeft's position...
BufferUtils.populateFromBuffer( bottomLeft, normBuf, focalSpot + sizeX );
// now find the next point below and to the right of topLeft's
// position...
BufferUtils.populateFromBuffer( bottomRight, normBuf, focalSpot + sizeX
+ 1 );
// Use linear interpolation to find the height.
topLeft.interpolate( topRight, intOnX );
bottomLeft.interpolate( bottomRight, intOnX );
topLeft.interpolate( bottomLeft, intOnZ );
return topLeft.normalizeLocal();
}
/**
* <code>buildVertices</code> sets up the vertex and index arrays of the
* TriMesh.
*/
private void buildVertices() {
vertBuf = BufferUtils.createVector3Buffer( vertBuf, vertQuantity );
geomBatch.setVertexBuffer( vertBuf );
Vector3f point = new Vector3f();
for( int x = 0; x < sizeX; x++ ) {
for( int y = 0; y < sizeY; y++ ) {
point.set( x, 0, y );
BufferUtils.setInBuffer( point, vertBuf, (x + (y * sizeX)) );
}
}
//set up the indices
int triangleQuantity = ((sizeX - 1) * (sizeY - 1)) * 2;
geomBatch.setTriangleQuantity( triangleQuantity );
indexBuffer = BufferUtils.createIntBuffer( triangleQuantity * 3 );
geomBatch.setIndexBuffer( indexBuffer );
//go through entire array up to the second to last column.
for( int i = 0; i < (sizeX * (sizeY - 1)); i++ ) {
//we want to skip the top row.
if( i % ((sizeX * (i / sizeX + 1)) - 1) == 0 && i != 0 ) {
// System.out.println("skip row: "+i+" cause: "+((sizeY * (i / sizeX + 1)) - 1));
continue;
}
else {
// System.out.println("i: "+i);
}
//set the top left corner.
indexBuffer.put( i );
//set the bottom right corner.
indexBuffer.put( (1 + sizeX) + i );
//set the top right corner.
indexBuffer.put( 1 + i );
//set the top left corner
indexBuffer.put( i );
//set the bottom left corner
indexBuffer.put( sizeX + i );
//set the bottom right corner
indexBuffer.put( (1 + sizeX) + i );
}
}
/**
* <code>buildTextureCoordinates</code> calculates the texture coordinates
* of the terrain.
*/
private void buildTextureCoordinates() {
texs = BufferUtils.createVector2Buffer( vertQuantity );
geomBatch.setTextureBuffer( texs, 0 );
texs.clear();
vertBuf.rewind();
for( int i = 0; i < vertQuantity; i++ ) {
texs.put( vertBuf.get() * textureScale );
vertBuf.get(); // ignore vert y coord.
texs.put( vertBuf.get() * textureScale );
}
}
/**
* <code>buildNormals</code> calculates the normals of each vertex that
* makes up the block of terrain.
*/
Vector3f oppositePoint = new Vector3f();
Vector3f adjacentPoint = new Vector3f();
Vector3f rootPoint = new Vector3f();
Vector3f tempNorm = new Vector3f();
private void buildNormals() {
normBuf = BufferUtils.createVector3Buffer( normBuf, vertQuantity );
geomBatch.setNormalBuffer( normBuf );
oppositePoint.set( 0, 0, 0 );
adjacentPoint.set( 0, 0, 0 );
rootPoint.set( 0, 0, 0 );
tempNorm.set( 0, 0, 0 );
int adj = 0, opp = 0, normalIndex = 0;
for( int row = 0; row < sizeY; row++ ) {
for( int col = 0; col < sizeX; col++ ) {
BufferUtils.populateFromBuffer( rootPoint, vertBuf, normalIndex );
if( row == sizeY - 1 ) {
if( col == sizeX - 1 ) { // last row, last col
// up cross left
adj = normalIndex - sizeX;
opp = normalIndex - 1;
}
else { // last row, except for last col
// right cross up
adj = normalIndex + 1;
opp = normalIndex - sizeX;
}
}
else {
if( col == sizeY - 1 ) { // last column except for last row
// left cross down
adj = normalIndex - 1;
opp = normalIndex + sizeX;
}
else { // most cases
// down cross right
adj = normalIndex + sizeX;
opp = normalIndex + 1;
}
}
BufferUtils.populateFromBuffer( adjacentPoint, vertBuf, adj );
BufferUtils.populateFromBuffer( oppositePoint, vertBuf, opp );
tempNorm.set( adjacentPoint ).subtractLocal( rootPoint )
.crossLocal( oppositePoint.subtractLocal( rootPoint ) )
.normalizeLocal();
BufferUtils.setInBuffer( tempNorm, normBuf, normalIndex );
normalIndex++;
}
}
}
} |
package com.maddyhome.idea.vim;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.components.impl.stores.StorageUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.impl.KeymapImpl;
import com.intellij.openapi.keymap.impl.KeymapManagerImpl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.maddyhome.idea.vim.ui.VimKeymapDialog;
import org.jdom.Document;
import org.jdom.Element;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author oleg
*/
public class VimKeyMapUtil {
private static Logger LOG = Logger.getInstance(VimKeyMapUtil.class);
private static final String VIM_XML = "Vim.xml";
private static final String IDEAVIM_NOTIFICATION_ID = "ideavim";
private static final String IDEAVIM_NOTIFICATION_TITLE = "IdeaVim";
/**
* @return true if keymap was installed or was successfully installed
*/
public static boolean installKeyBoardBindings() {
LOG.debug("Check for keyboard bindings");
final KeymapManagerImpl manager = (KeymapManagerImpl)KeymapManager.getInstance();
final Keymap keymap = manager.getKeymap("Vim");
if (keymap != null) {
return true;
}
final String keyMapsPath = PathManager.getConfigPath() + File.separatorChar + "keymaps";
final LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
final VirtualFile keyMapsFolder = localFileSystem.refreshAndFindFileByPath(keyMapsPath);
if (keyMapsFolder == null) {
LOG.error("Failed to install vim keymap. Empty keymaps folder");
return false;
}
LOG.debug("No vim keyboard installed found. Installing");
String keymapPath = PathManager.getPluginsPath() + File.separatorChar + IDEAVIM_NOTIFICATION_TITLE + File.separatorChar + VIM_XML;
File vimKeyMapFile = new File(keymapPath);
// Look in development path
if (!vimKeyMapFile.exists() || !vimKeyMapFile.isFile()) {
final String resource = VimKeyMapUtil.class.getResource("").toString();
keymapPath = resource.toString().substring("file:".length(), resource.indexOf("out")) + "community/plugins/ideavim/keymap/" + VIM_XML;
vimKeyMapFile = new File(keymapPath);
}
if (!vimKeyMapFile.exists() || !vimKeyMapFile.isFile()) {
final String error = "Installation of the Vim keymap failed because Vim keymap file not found: " + keymapPath;
LOG.error(error);
Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, error, NotificationType.ERROR));
return false;
}
try {
final VirtualFile vimKeyMap2Copy = localFileSystem.refreshAndFindFileByIoFile(vimKeyMapFile);
if (vimKeyMap2Copy == null){
final String error = "Installation of the Vim keymap failed because Vim keymap file not found: " + keymapPath;
LOG.error(error);
Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE, error, NotificationType.ERROR));
return false;
}
final VirtualFile vimKeyMapVFile = localFileSystem.copyFile(VimPlugin.getInstance(), vimKeyMap2Copy, keyMapsFolder, VIM_XML);
final String path = vimKeyMapVFile.getPath();
final Document document = StorageUtil.loadDocument(new FileInputStream(path));
if (document == null) {
LOG.error("Failed to install vim keymap. Vim.xml file is corrupted");
Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE,
"Failed to install vim keymap. Vim.xml file is corrupted", NotificationType.ERROR));
return false;
}
// Prompt user to select the parent for the Vim keyboard
configureVimParentKeymap(path, document, false);
final KeymapImpl vimKeyMap = new KeymapImpl();
final Keymap[] allKeymaps = manager.getAllKeymaps();
vimKeyMap.readExternal(document.getRootElement(), allKeymaps);
manager.addKeymap(vimKeyMap);
return true;
}
catch (Exception e) {
reportError(e);
return false;
}
}
private static void requestRestartOrShutdown(final Project project) {
final ApplicationEx app = ApplicationManagerEx.getApplicationEx();
if (app.isRestartCapable()) {
if (Messages.showDialog(project, "Restart " + ApplicationNamesInfo.getInstance().getProductName() + " to activate changes?",
"Vim keymap changed", new String[]{"&Restart", "&Postpone"}, 0, Messages.getQuestionIcon()) == 0) {
app.restart();
}
} else {
if (Messages.showDialog(project, "Shut down " + ApplicationNamesInfo.getInstance().getProductName() + " to activate changes?",
"Vim keymap changed", new String[]{"&Shut Down", "&Postpone"}, 0, Messages.getQuestionIcon()) == 0){
app.exit(true);
}
}
}
/**
* Changes parent keymap for the Vim
* @return true if document was changed succesfully
*/
private static boolean configureVimParentKeymap(final String path, final Document document, final boolean showNotification) throws IOException {
final Element rootElement = document.getRootElement();
final String parentKeymap = rootElement.getAttributeValue("parent");
final VimKeymapDialog vimKeymapDialog = new VimKeymapDialog(parentKeymap);
vimKeymapDialog.show();
if (vimKeymapDialog.getExitCode() != DialogWrapper.OK_EXIT_CODE){
return false;
}
rootElement.removeAttribute("parent");
final Keymap selectedKeymap = vimKeymapDialog.getSelectedKeymap();
final String keymapName = selectedKeymap.getName();
rootElement.setAttribute("parent", keymapName);
// Save modified keymap to the file
JDOMUtil.writeDocument(document, path, "\n");
if (showNotification) {
Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE,
"Successfully configured vim keymap to be based on " +
selectedKeymap.getPresentableName(),
NotificationType.INFORMATION));
}
return true;
}
/**
* @return true if keymap was switched successfully, false otherwise
*/
public static boolean switchKeymapBindings(final boolean enableVimKeymap) {
LOG.debug("Enabling keymap");
final KeymapManagerImpl manager = (KeymapManagerImpl)KeymapManager.getInstance();
// In case if Vim keymap is already in use or we don't need it, we have nothing to do
if (manager.getActiveKeymap().getName().equals("Vim") == enableVimKeymap){
return false;
}
// Get keymap to enable
final String keymapName2Enable = enableVimKeymap ? "Vim" : VimPlugin.getInstance().getPreviousKeyMap();
if (keymapName2Enable.isEmpty()) {
return false;
}
if (keymapName2Enable.equals(manager.getActiveKeymap().getName())) {
return false;
}
LOG.debug("Enabling keymap:" + keymapName2Enable);
final Keymap keymap = manager.getKeymap(keymapName2Enable);
if (keymap == null) {
Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE,
"Failed to enable keymap: " + keymapName2Enable, NotificationType.ERROR));
LOG.error("Failed to enable keymap: " + keymapName2Enable);
return false;
}
// Save previous keymap to enable after VIM emulation is turned off
if (enableVimKeymap) {
VimPlugin.getInstance().setPreviousKeyMap(manager.getActiveKeymap().getName());
}
manager.setActiveKeymap(keymap);
final String keyMapPresentableName = keymap.getPresentableName();
Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE,
keyMapPresentableName + " keymap was successfully enabled", NotificationType.INFORMATION));
LOG.debug(keyMapPresentableName + " keymap was successfully enabled");
return true;
}
public static void reconfigureParentKeymap(final Project project) {
final VirtualFile vimKeymapFile = getVimKeymapFile();
if (vimKeymapFile == null) {
LOG.error("Failed to find Vim keymap");
Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE,
"Failed to find Vim keymap", NotificationType.ERROR));
return;
}
try {
final String path = vimKeymapFile.getPath();
final Document document = StorageUtil.loadDocument(new FileInputStream(path));
if (document == null) {
LOG.error("Failed to install vim keymap. Vim.xml file is corrupted");
Notifications.Bus.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE,
"Vim.xml file is corrupted", NotificationType.ERROR));
return;
}
// Prompt user to select the parent for the Vim keyboard
if (configureVimParentKeymap(path, document, true)) {
final KeymapManagerImpl manager = (KeymapManagerImpl) KeymapManager.getInstance();
final KeymapImpl vimKeyMap = new KeymapImpl();
final Keymap[] allKeymaps = manager.getAllKeymaps();
vimKeyMap.readExternal(document.getRootElement(), allKeymaps);
manager.addKeymap(vimKeyMap);
requestRestartOrShutdown(project);
}
}
catch (FileNotFoundException e) {
reportError(e);
}
catch (IOException e) {
reportError(e);
}
catch (InvalidDataException e) {
reportError(e);
}
}
private static void reportError(final Exception e) {
LOG.error("Failed to reconfigure vim keymap.\n" + e);
Notifications.Bus
.notify(new Notification(IDEAVIM_NOTIFICATION_ID, IDEAVIM_NOTIFICATION_TITLE,
"Failed to reconfigure vim keymap.\n" + e, NotificationType.ERROR));
}
@Nullable
public static VirtualFile getVimKeymapFile() {
final String keyMapsPath = PathManager.getConfigPath() + File.separatorChar + "keymaps";
final LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
return localFileSystem.refreshAndFindFileByPath(keyMapsPath + File.separatorChar + VIM_XML);
}
} |
package com.mhalka.babytracker;
import java.util.Calendar;
import java.util.GregorianCalendar;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class AlarmReceiver extends BroadcastReceiver {
// Namjesti konstante za preference.
public static final String PREFS_NAME = "BabyTrackerPrefs";
public static final String TRUDNOCA = "PracenjeTrudnoce";
public static final String NOTIFIKACIJA = "Notifikacija";
public static final String DAN = "DanPocetkaPracenja";
public static final String MJESEC = "MjesecPocetkaPracenja";
public static final String GODINA = "GodinaPocetkaPracenja";
public static final String SEDMICA = "TrenutnaSedmicaTrudnoce";
public static final String MJESECI = "TrenutnaStarostBebe";
public static final String RODJENDAN = "BebinPrviRodjendan";
// Konstanta za notifikaciju.
public static final int NOTIFIKACIJA_ID = 0;
// Setiraj varijable.
private NotificationManager notifier;
private String ScrollingText;
private String NotificationText;
@Override
public void onReceive(Context context, Intent intent) {
// Povezi prethodno setirane varijable za elemente forme sa njihovim vrijednostima.
ScrollingText = context.getString(R.string.nove_informacije_scrolling);
NotificationText = context.getString(R.string.nove_informacije_notifikacija);
// Procitaj preference.
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
Boolean pracenjeTrudnoce = settings.getBoolean(TRUDNOCA, true);
Boolean BebinRodjendan = settings.getBoolean(RODJENDAN, false);
Integer SedmicaTrudnoce = settings.getInt(SEDMICA, 1);
Integer StarostBebe = settings.getInt(MJESECI, 1);
// Setiraj vrijednosti varijabli potrebnih za izracunavanje starosti.
Calendar datumPocetkaPracenja = new GregorianCalendar(settings.getInt(GODINA,1920), settings.getInt(MJESEC,0), settings.getInt(DAN,1));
Calendar today = Calendar.getInstance();
if(pracenjeTrudnoce) {
// Izracunaj starost ploda u sedmicama.
long weeksBetween = 0;
while (today.before(datumPocetkaPracenja)) {
today.add(Calendar.DAY_OF_MONTH, 6);
weeksBetween++;
}
int weeks = 43 - ((int) weeksBetween);
// Pokreni notifikaciju ako su ispunjeni svi uslovi.
if((weeks != SedmicaTrudnoce) && (weeks > 0) && (weeks < 43)) {
startNotifikaciju(context);
}
} else {
// Provjeri da li datum rodjenja (mjesec i dan) odgovaraju danasnjem datumu i shodno tome
// pokreni notifikaciju.
if(!BebinRodjendan) {
if(((datumPocetkaPracenja.get(Calendar.YEAR)) < (today.get(Calendar.YEAR))) &&
((datumPocetkaPracenja.get(Calendar.MONTH)) == (today.get(Calendar.MONTH))) &&
((datumPocetkaPracenja.get(Calendar.DAY_OF_MONTH)) == (today.get(Calendar.DAY_OF_MONTH)))) {
// Zapisi u preference da je pokazana notifikacija za ovaj event
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(RODJENDAN, true);
editor.commit();
// Pokreni notifikaciju
startNotifikaciju(context);
}
}
// Izracunaj starost bebe u mjesecima.
long monthsBetween = 0;
while (datumPocetkaPracenja.before(today)) {
today.add(Calendar.MONTH, -1);
monthsBetween++;
}
int months = (int) monthsBetween;
// Pokreni notifikaciju ako su ispunjeni svi uslovi.
if((months != StarostBebe) && (months > 0) && (months < 13)) {
startNotifikaciju(context);
}
}
}
public void startNotifikaciju(Context context) {
notifier = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, ScrollingText, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, SettingsActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(context, context.getText(R.string.app_name), NotificationText, contentIntent);
notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notifier.notify(NOTIFIKACIJA_ID, notification);
}
} |
package com.nullprogram.chess.gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
import com.nullprogram.chess.Game;
import com.nullprogram.chess.Board;
import com.nullprogram.chess.Piece;
import com.nullprogram.chess.Player;
import com.nullprogram.chess.Move;
import com.nullprogram.chess.MoveList;
import com.nullprogram.chess.Position;
/**
* Displays a board and exposes local players.
*
* This swing element displays a game board and can also behave as a
* player as needed.
*/
public class BoardPanel extends JPanel implements MouseListener, Player {
/** Version for object serialization. */
private static final long serialVersionUID = 1L;
/** The board being displayed. */
private Board board;
/** The game engine used when the board is behaving as a player. */
private Game game;
/** The currently selected tile. */
private Position selected = null;
/** The list of moves for the selected tile. */
private MoveList moves = null;
/** The color for the dark tiles on the board. */
static final Color DARK = new Color(0xD1, 0x8B, 0x47);
/** The color for the light tiles on the board. */
static final Color LIGHT = new Color(0xFF, 0xCE, 0x9E);
/** Border color for a selected tile. */
static final Color SELECTED = new Color(0x00, 0xFF, 0xFF);
/** Border color for a highlighted movement tile. */
static final Color MOVEMENT = new Color(0x7F, 0x00, 0x00);
/** Last move highlight color. */
static final Color LAST = new Color(0x00, 0x7F, 0xFF);
/** Padding between the highlight and tile border. */
static final int PADDING = 2;
/** Thickness of highlighting. */
static final int THICKNESS = 3;
/** Minimum size of a tile, in pixels. */
static final int MIN_SIZE = 25;
/** Preferred size of a tile, in pixels. */
static final int PREF_SIZE = 50;
/** The interaction modes. */
private enum Mode {
/** Don't interact with the player. */
WAIT,
/** Interact with the player. */
PLAYER;
}
/** The current interaction mode. */
private Mode mode = Mode.WAIT;
/** Current player making a move, when interactive. */
private Piece.Side side;
/**
* Hidden constructor.
*/
protected BoardPanel() {
}
/**
* Create a new display for given board.
*
* @param displayBoard the board to be displayed
*/
public BoardPanel(final Board displayBoard) {
board = displayBoard;
setPreferredSize(new Dimension(PREF_SIZE * board.getWidth(),
PREF_SIZE * board.getHeight()));
setMinimumSize(new Dimension(MIN_SIZE * board.getWidth(),
MIN_SIZE * board.getHeight()));
addMouseListener(this);
}
/**
* Get the current pixel size of a tile.
*
* @return the current size in pixel of one tile.
*/
private int getTileSize() {
int h = board.getHeight();
int w = board.getWidth();
int sizeX = getWidth() / w;
int sizeY = getHeight() / h;
return Math.min(sizeX, sizeY);
}
/**
* Change the board to be displayed.
*
* @param b the new board
*/
public final void setBoard(final Board b) {
board = b;
}
/**
* Change the board to be displayed.
*
* @return display's board
*/
public final Board getBoard() {
return board;
}
/**
* Standard painting method.
*
* @param g the drawing surface
*/
public final void paintComponent(final Graphics g) {
super.paintComponent(g);
int h = board.getHeight();
int w = board.getWidth();
int size = getTileSize();
/* Draw the background */
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
if ((x + y) % 2 == 0) {
g.setColor(LIGHT);
} else {
g.setColor(DARK);
}
g.fillRect(x * size, y * size, size, size);
}
}
/* Place the pieces */
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
Piece p = board.getPiece(new Position(x, y));
if (p != null) {
BufferedImage tile = p.getImage(size);
g.drawImage(tile, x * size, (h - y - 1) * size, this);
}
}
}
/* Draw last move */
Move last = board.last();
if (last != null) {
g.setColor(LAST);
highlight(g, last.getOrigin());
highlight(g, last.getDest());
}
/* Draw selected square */
if (selected != null) {
g.setColor(SELECTED);
highlight(g, selected);
/* Draw piece moves */
if (moves != null) {
g.setColor(MOVEMENT);
for (Move move : moves) {
highlight(g, move.getDest());
}
}
}
}
/**
* Highlight the given tile on the board using the current color.
*
* @param g the drawing surface
* @param pos position to highlight
*/
private void highlight(final Graphics g, final Position pos) {
int size = getTileSize();
int x = pos.getX() * size;
int y = (board.getHeight() - 1 - pos.getY()) * size;
for (int i = PADDING; i < THICKNESS + PADDING; i++) {
g.drawRect(x + i, y + i,
size - 1 - i * 2, size - 1 - i * 2);
}
}
/** {@inheritDoc} */
public final void mouseReleased(final MouseEvent e) {
switch (e.getButton()) {
case MouseEvent.BUTTON1:
leftClick(e);
break;
default:
/* do nothing */
break;
}
}
/**
* Handle the event when the left button is clicked.
*
* @param e the mouse event
*/
private void leftClick(final MouseEvent e) {
if (mode == Mode.WAIT) {
return;
}
Position pos = getPixelPosition(e.getPoint());
if (!board.inRange(pos)) {
/* Click was outside the board, somehow. */
return;
}
if (pos != null) {
if (pos.equals(selected)) {
/* Deselect */
selected = null;
moves = null;
} else if (moves != null && moves.containsDest(pos)) {
/* Move selected piece */
mode = Mode.WAIT;
game.move(moves.getMoveByDest(pos));
selected = null;
moves = null;
} else {
/* Select this position */
Piece p = board.getPiece(pos);
if (p != null && p.getSide() == side) {
selected = pos;
moves = p.getMoves(true);
}
}
}
repaint();
}
/**
* Determine which tile a pixel point belongs to.
*
* @param p the point
* @return the position on the board
*/
private Position getPixelPosition(final Point p) {
return new Position((int) (p.getX()) / getTileSize(),
board.getWidth() - 1
- (int) (p.getY()) / getTileSize());
}
/**
* Tell the BoardPanel to get a move from the player.
*
* @param currentSide the side who is making the move
*/
public final void setActive(final Piece.Side currentSide) {
side = currentSide;
mode = Mode.PLAYER;
repaint();
}
/**
* Set the current game for this player.
*
* @param currentGame the game for this player
*/
public final void setGame(final Game currentGame) {
game = currentGame;
}
/** {@inheritDoc} */
public void mouseExited(final MouseEvent e) {
/* Do nothing */
}
/** {@inheritDoc} */
public void mouseEntered(final MouseEvent e) {
/* Do nothing */
}
/** {@inheritDoc} */
public void mouseClicked(final MouseEvent e) {
/* Do nothing */
}
/** {@inheritDoc} */
public void mousePressed(final MouseEvent e) {
/* Do nothing */
}
} |
package com.rrbrussell.enigma_gui_swing;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Properties;
//import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* @author Robert R. Russell
* @author robert@rrbrussell.com
*
* The launcher for Swinging Enigma.
*
*/
public class Main extends javax.swing.JFrame {
private static final long serialVersionUID = -129118185558719896L;
private JPanel simpleEnigma;
private JPanel complexEnigma;
private static File privateDirectory;
private static File propertiesFile;
public Main(Properties storedOptions) {
super("Swinging Enigma");
String viewToLoad = storedOptions.getProperty("EngimaView");
String versionToLoad = storedOptions.getProperty("EngimaVersion");
//TODO modify enigma_demonstration_java to provide an interface
}
/**
* @return
*
*/
public static Properties buildDefaultProperties() {
/*
* TODO check if property arguments on the VM command line are
* passed into System.getProperties();
*/
Properties defaultOptions = new Properties(System.getProperties());
defaultOptions.setProperty("EngimaView", "simple");
defaultOptions.setProperty("EnigmaVersion", "M3");
return defaultOptions;
}
/**
* @param defs
* @return
*/
public static Properties loadUserProperties(Properties defs) {
privateDirectory = new File(System.getProperty("user.home"),
File.separator + ".swinging_enigma");
propertiesFile = new File(privateDirectory,
File.separator + "Main.properties");
Properties loadedProperties = null;
if(propertiesFile.exists() && propertiesFile.canRead()) {
loadedProperties = new Properties(defs);
try {
Reader propertiesStore = new FileReader(propertiesFile);
loadedProperties.load(propertiesStore);
propertiesStore.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
loadedProperties = defs;
}
return loadedProperties;
}
/**
* @param args
*/
public static void main(String[] args) {
Properties configuration = Main.buildDefaultProperties();
configuration = Main.loadUserProperties(configuration);
Main launched = new Main(configuration);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.