repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
MoriaDev/MinesOfMoria | app/src/main/java/com/temenoi/minesofmoria/windows/WndError.java | 994 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.temenoi.minesofmoria.windows;
import com.temenoi.minesofmoria.ui.Icons;
public class WndError extends WndTitledMessage {
private static final String TXT_TITLE = "ERROR";
public WndError( String message ) {
super( Icons.WARNING.get(), TXT_TITLE, message );
}
}
| gpl-3.0 |
oleg-pogiba/Android-MVP-Architecture | app/src/main/java/com/marlin86/android_architecture/app/di/modules/GitHubModule.java | 398 | package com.marlin86.android_architecture.app.di.modules;
import com.marlin86.android_architecture.data.net.GitHubApi;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
import retrofit2.Retrofit;
@Module
public class GitHubModule {
@Provides
public GitHubApi providesGitHubApi(@Named("GitHub") Retrofit retrofit) {
return retrofit.create(GitHubApi.class);
}
}
| gpl-3.0 |
Foghrye4/ihl | src/main/java/ihl/explosion/ExplosionVectorBlockV2.java | 14324 | package ihl.explosion;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import ihl.IHLMod;
import ihl.utils.IHLUtils;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.network.play.server.S26PacketMapChunkBulk;
import net.minecraft.util.DamageSource;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.Explosion;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ExplosionEvent;
public class ExplosionVectorBlockV2 {
final Set<Integer> startVectors = new HashSet<Integer>();
public final int[][] directionMasks = new int[8][3];
public final int bits = IHLMod.config.explosionVectorSizeBits;
private final int maxValue = (1 << bits) - 1;
public final int halfValue = (1 << bits - 1) - 1;
private final int maxArraySize = 1 << bits * 3;
// public final int[][] vectors = new int[maxArraySize][2];
public final int[][] vectors = new int[maxArraySize][0];
private final Set<Chunk> chunksToUpdate = new HashSet<Chunk>(64);
private final Map<Integer, ItemStack> cachedDrops = new HashMap<Integer, ItemStack>(128);
final Map<Integer, WorldSavedDataBlastWave> blastWaveByDimensionId = new HashMap<Integer, WorldSavedDataBlastWave>();
private final Map<ExtendedBlockStorage, Entity[]> cachedEntities = new HashMap<ExtendedBlockStorage, Entity[]>();
private final Random random = new Random();
public ExplosionVectorBlockV2() {
this.precalculateExplosion();
startVectors.add(0);
directionMasks[0] = new int[] { 1, 1, 1 };
directionMasks[1] = new int[] { -1, 1, 1 };
directionMasks[2] = new int[] { 1, -1, 1 };
directionMasks[3] = new int[] { 1, 1, -1 };
directionMasks[4] = new int[] { -1, -1, 1 };
directionMasks[5] = new int[] { 1, -1, -1 };
directionMasks[6] = new int[] { -1, 1, -1 };
directionMasks[7] = new int[] { -1, -1, -1 };
}
public int encodeXYZ(int x, int y, int z) {
return x << bits * 2 | y << bits | z;
}
public int[] decodeXYZ(int l) {
return new int[] { l >> bits * 2, l >> bits & maxValue, l & maxValue };
}
public void precalculateExplosion() {
for (int levelRadius = 1; levelRadius <= this.maxValue; levelRadius++)
for (int ix = 0; ix <= levelRadius; ix++)
for (int iy = 0; iy <= levelRadius; iy++) {
for (int iz = (ix == levelRadius || iy == levelRadius) ? 0 : levelRadius; iz <= levelRadius; iz++) {
int vxyz = encodeXYZ(ix, iy, iz);
int[] prevXYZ = new int[] { ix, iy, iz };
reduceCoordinate(prevXYZ, levelRadius);
int pvxyz = encodeXYZ(prevXYZ[0], prevXYZ[1], prevXYZ[2]);
findFreeSpace(pvxyz, vxyz);
}
}
}
private void findFreeSpace(int pvxyz, int vxyz) {
int[] nV = new int[vectors[pvxyz].length+1];
for(int i=0;i<vectors[pvxyz].length;i++){
nV[i]=vectors[pvxyz][i];
}
nV[vectors[pvxyz].length] = vxyz;
vectors[pvxyz] = nV;
}
private void reduceCoordinate(int[] pxyz, int levelRadius) {
float x = pxyz[0]+0.5f;
float y = pxyz[1]+0.5f;
float z = pxyz[2]+0.5f;
float rx = x/levelRadius;
float ry = y/levelRadius;
float rz = z/levelRadius;
while(x>=pxyz[0] && y>=pxyz[1] && z>=pxyz[2]){
x-=rx;
y-=ry;
z-=rz;
}
pxyz[0]=x<0?0:(int)x;
pxyz[1]=y<0?0:(int)y;
pxyz[2]=z<0?0:(int)z;
}
public void breakBlocksAndGetDescendants(World world, int sourceX, int sourceY, int sourceZ, Explosion explosion,
int ev, int power, int[] directionMask) {
power = this.getNewPowerAndProcessBlocks(world, ev, sourceX, sourceY, sourceZ, explosion, power, directionMask);
power = (int) (power * 0.94) - 1;
if (power > 1) {
if (this.vectors[ev].length==0) {
int[] xyz = decodeXYZ(ev);
int xb = xyz[0] >> bits - 1;
int yb = xyz[1] >> bits - 1;
int zb = xyz[2] >> bits - 1;
int hashb = xb << 2 | yb << 1 | zb;
xyz[0] -= xb * halfValue;
xyz[1] -= yb * halfValue;
xyz[2] -= zb * halfValue;
if (hashb == 0 || xb > 1 || yb > 1 || zb > 1) {
throw new ArithmeticException("End vectors shall be higher than half value");
}
int ev2 = encodeXYZ(xyz[0], xyz[1], xyz[2]);
breakBlocksAndGetDescendants(world, sourceX + xb * halfValue * directionMask[0],
sourceY + yb * halfValue * directionMask[1], sourceZ + zb * halfValue * directionMask[2],
explosion, ev2, power, directionMask);
} else {
for (int d1 : this.vectors[ev]) {
breakBlocksAndGetDescendants(world, sourceX, sourceY, sourceZ, explosion, d1, power,
directionMask);
}
}
}
}
private int getNewPowerAndProcessBlocks(World world, int ev, int sourceX, int sourceY, int sourceZ,
Explosion explosion, int power2, int[] directionMask) {
int power1 = power2;
int[] xyz = decodeXYZ(ev);
int absX = xyz[0] * directionMask[0] + sourceX;
int absY = xyz[1] * directionMask[1] + sourceY;
int absZ = xyz[2] * directionMask[2] + sourceZ;
if (absY < 0 || absY >= 256) {
return 0;
}
int absEBSX = absX >> 4;
int absEBSZ = absZ >> 4;
if (world.getChunkProvider().chunkExists(absEBSX, absEBSZ)) {
if (world.getChunkProvider().provideChunk(absEBSX, absEBSZ).getTopFilledSegment() + 24 >= absY) {
int remainingPower = this.tryDestroyBlock(world, absX, absY, absZ, sourceX, sourceY, sourceZ, power1,
explosion);
return remainingPower;
} else {
return 0;
}
} else {
WorldSavedDataBlastWave blastWave = null;
int dimensionId = world.provider.dimensionId;
if (this.blastWaveByDimensionId.containsKey(dimensionId)) {
blastWave = this.blastWaveByDimensionId.get(dimensionId);
} else {
blastWave = new WorldSavedDataBlastWave("blastWave");
this.blastWaveByDimensionId.put(dimensionId, blastWave);
}
long chunkXZKey = ChunkCoordIntPair.chunkXZ2Int(absEBSX, absEBSZ);
blastWave.scheduleExplosionEffectsOnChunkLoad(chunkXZKey, ev, sourceX, sourceY, sourceZ, power1,
directionMask);
return 0;
}
}
public int tryDestroyBlock(World world, int absX, int absY, int absZ, int sourceX, int sourceY, int sourceZ,
int power, Explosion explosion) {
Chunk chunk = world.getChunkProvider().provideChunk(absX >> 4, absZ >> 4);
ExtendedBlockStorage ebs = this.getEBS(chunk, absX, absY, absZ);
if (ebs == null) {
return power;
} else {
Block block = ebs.getBlockByExtId(absX & 15, absY & 15, absZ & 15);
if (block.getBlockHardness(world, absX, absY, absZ) < 0) {
return 0;
} else if (absX == sourceX && absY == sourceY && absZ == sourceZ) {
int array_index = (absY & 15) << 8 | (absZ & 15) << 4 | (absX & 15);
if (ebs.getBlockLSBArray()[array_index] != 0 && ebs.getBlockMSBArray() != null
&& ebs.getBlockMSBArray().get(absX & 15, absY & 15, absZ & 15) != 0) {
ebs.blockRefCount--;
}
ebs.getBlockLSBArray()[array_index] = 0;
if (ebs.getBlockMSBArray() != null) {
ebs.getBlockMSBArray().set(absX & 15, absY & 15, absZ & 15, 0);
}
return power;
} else {
int remainingPower = power
- (int) (block.getExplosionResistance(null, world, absX, absY, absZ, sourceX, sourceY, sourceZ)
* 10f + 0.5f);
if (remainingPower >= 0) {
int array_index = (absY & 15) << 8 | (absZ & 15) << 4 | (absX & 15);
if (ebs.getBlockLSBArray()[array_index] != 0 && ebs.getBlockMSBArray() != null
&& ebs.getBlockMSBArray().get(absX & 15, absY & 15, absZ & 15) != 0) {
ebs.blockRefCount--;
}
ebs.getBlockLSBArray()[array_index] = 0;
if (ebs.getBlockMSBArray() != null) {
ebs.getBlockMSBArray().set(absX & 15, absY & 15, absZ & 15, 0);
}
List<ItemStack> dropsList = block.getDrops(world, absX, absY, absZ,
ebs.getExtBlockMetadata(absX & 15, absY & 15, absZ & 15), 0);
Iterator<ItemStack> drops = dropsList.iterator();
while (drops.hasNext()) {
ItemStack drop = drops.next();
int key = Item.getIdFromItem(drop.getItem()) ^ (drop.getItemDamage() << 16);
if (this.cachedDrops.containsKey(key)) {
this.cachedDrops.get(key).stackSize += drop.stackSize;
} else {
this.cachedDrops.put(key, drop);
}
}
Entity[] entities = this.getFromOrCreateCache(world, ebs, absX, absY, absZ);
if (entities != null && entities[array_index] != null) {
entities[array_index].attackEntityFrom(DamageSource.setExplosionSource(explosion), power / 10f);
}
} else {
block.onNeighborBlockChange(world, absX, absY, absZ, block);
if (random.nextInt(8) == 0) {
if ((++absY & 15) != 0) {
int array_index = (absY & 15) << 8 | (absZ & 15) << 4 | (absX & 15);
if (ebs.getBlockLSBArray()[array_index] == 0 && (ebs.getBlockMSBArray() == null
|| ebs.getBlockMSBArray().get(absX & 15, absY & 15, absZ & 15) == 0)) {
this.placeDrops(world, absX, absY, absZ);
}
}
}
}
return remainingPower;
}
}
}
public Entity[] getFromOrCreateCache(World world, ExtendedBlockStorage ebs, int absX, int absY, int absZ) {
Entity[] entities = this.cachedEntities.get(ebs);
if (entities == null) {
Chunk chunk = world.getChunkProvider().provideChunk(absX >> 4, absZ >> 4);
List<Entity> eList = this.getEntityList(chunk, absX, absY, absZ);
if (eList != null && !eList.isEmpty()) {
entities = new Entity[4096];
Iterator<Entity> eListI = eList.iterator();
this.cachedEntities.put(ebs, entities);
while (eListI.hasNext()) {
Entity entity = eListI.next();
int entityX = (int) entity.boundingBox.minX;
int entityY = (int) entity.boundingBox.minY;
int entityZ = (int) entity.boundingBox.minZ;
int rx = entityX & 15;
int ry = entityY & 15;
int rz = entityZ & 15;
int array_index = ry << 8 | rz << 4 | rx;
entities[array_index] = entity;
}
}
}
return entities;
}
public ExtendedBlockStorage getEBS(Chunk chunk, int absX, int absY, int absZ) {
ExtendedBlockStorage[] ebsA = chunk.getBlockStorageArray();
ExtendedBlockStorage ebs = ebsA[absY >> 4];
if (ebs != null) {
this.chunksToUpdate.add(chunk);
}
return ebs;
}
@SuppressWarnings("unchecked")
public List<Entity> getEntityList(Chunk chunk, int absX, int absY, int absZ) {
return chunk.entityLists[absY >> 4];
}
private void placeDrops(World world, int x, int y, int z) {
Iterator<Entry<Integer, ItemStack>> di = this.cachedDrops.entrySet().iterator();
if (di.hasNext()) {
Entry<Integer, ItemStack> cde = di.next();
while (di.hasNext()) {
cde = di.next();
}
ItemStack stack = cde.getValue();
if (stack != null && stack.getItem() != null && stack.stackSize > 0) {
if (stack.stackSize <= stack.getMaxStackSize()) {
if (stack.stackSize > 0) {
PileTileEntity pte = new PileTileEntity();
pte.xCoord = x;
pte.yCoord = y;
pte.zCoord = z;
pte.setWorldObj(world);
pte.validate();
pte.setContent(stack);
IHLUtils.setBlockAndTileEntityRaw(world, x, y, z, PileBlock.instance, pte);
}
di.remove();
} else {
ItemStack stack1 = stack.copy();
stack1.stackSize = stack.getMaxStackSize();
PileTileEntity pte = new PileTileEntity();
pte.content = stack1;
IHLUtils.setBlockAndTileEntityRaw(world, x, y, z, PileBlock.instance, pte);
stack.stackSize -= stack.getMaxStackSize();
}
}
}
}
public void sendChunkUpdateToPlayersInExplosionAffectedZone(World world, int sourceX, int sourceY, int sourceZ) {
Iterator<Chunk> ci = this.chunksToUpdate.iterator();
while (ci.hasNext()) {
Chunk chunk = ci.next();
chunk.generateSkylightMap();
Arrays.fill(chunk.updateSkylightColumns, true);
chunk.func_150804_b(false);
}
List<Chunk> chunks = new ArrayList<Chunk>();
chunks.addAll(this.chunksToUpdate);
for (Object player : world.playerEntities) {
if (player instanceof EntityPlayerMP) {
EntityPlayerMP playerMP = (EntityPlayerMP) player;
playerMP.playerNetServerHandler.sendPacket(new S26PacketMapChunkBulk(chunks));
}
}
this.chunksToUpdate.clear();
}
public void doExplosion(World world, int sourceX, int sourceY, int sourceZ, final Set<Integer> startVectors1,
int startPower, int[] directionMask, Explosion explosion) {
for (int sv : startVectors1) {
this.breakBlocksAndGetDescendants(world, sourceX - (directionMask[0] < 0 ? 1 : 0),
sourceY - (directionMask[1] < 0 ? 1 : 0), sourceZ - (directionMask[2] < 0 ? 1 : 0), explosion, sv,
startPower, directionMask);
}
// Free and clean resources
this.cachedEntities.clear();
}
public void doExplosion(World world, int sourceX, int sourceY, int sourceZ, final Set<Integer> startVectors1,
int startPower) {
IHLMod.log.info("Starting explosion server");
Explosion explosion = new Explosion(world, null, sourceX, sourceY, sourceZ, 100f);
if (!MinecraftForge.EVENT_BUS.post(new ExplosionEvent.Start(world, explosion))) {
for (int[] directionMask : directionMasks) {
this.doExplosion(world, sourceX, sourceY, sourceZ, startVectors1, startPower, directionMask, explosion);
}
sendChunkUpdateToPlayersInExplosionAffectedZone(world, sourceX, sourceY, sourceZ);
for (Entry<Integer, ItemStack> entry : this.cachedDrops.entrySet()) {
IHLEntityFallingPile fallingPile = new IHLEntityFallingPile(world);
fallingPile.setPosition(sourceX + 0.5d, sourceY + 0.5d, sourceZ + 0.5d);
fallingPile.setEntityItemStack(entry.getValue());
fallingPile.setVelocity(random.nextDouble() - 0.5d, random.nextDouble() * 2,
random.nextDouble() - 0.5d);
world.spawnEntityInWorld(fallingPile);
}
this.cachedDrops.clear();
}
}
} | gpl-3.0 |
tryggvil/eucalyptus | clc/modules/core/src/edu/ucsb/eucalyptus/cloud/NotImplementedException.java | 3842 | /*
* Author: Sunil Soman sunils@cs.ucsb.edu
*/
package edu.ucsb.eucalyptus.cloud;
/*******************************************************************************
* Copyright (c) 2009 Eucalyptus Systems, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, only version 3 of the License.
*
*
* This file is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Please contact Eucalyptus Systems, Inc., 130 Castilian
* Dr., Goleta, CA 93101 USA or visit <http://www.eucalyptus.com/licenses/>
* if you need additional information or have any questions.
*
* This file may incorporate work covered under the following copyright and
* permission notice:
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Regents of the University of California
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with
* or without modification, are permitted provided that the following
* conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. USERS OF
* THIS SOFTWARE ACKNOWLEDGE THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE
* LICENSED MATERIAL, COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS
* SOFTWARE, AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING
* IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, SANTA
* BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, WHICH IN
* THE REGENTS’ DISCRETION MAY INCLUDE, WITHOUT LIMITATION, REPLACEMENT
* OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO IDENTIFIED, OR
* WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT NEEDED TO COMPLY WITH
* ANY SUCH LICENSES OR RIGHTS.
******************************************************************************/
public class NotImplementedException extends EucalyptusCloudException {
String value;
public NotImplementedException()
{
super( "Not Implemented" );
}
public NotImplementedException(String value)
{
super(value);
this.value = value;
}
public String getValue() {
return value;
}
public NotImplementedException(Throwable ex)
{
super("Not Implemented", ex);
}
public NotImplementedException(String message, Throwable ex)
{
super(message,ex);
}
} | gpl-3.0 |
CompEvol/MultiTypeTree | src/multitypetree/util/UtilMethods.java | 1595 | /*
* Copyright (C) 2014 Tim Vaughan <tgvaughan@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package multitypetree.util;
import beast.core.parameter.IntegerParameter;
import beast.evolution.tree.SCMigrationModel;
/**
*
* @author Tim Vaughan <tgvaughan@gmail.com>
*/
public class UtilMethods {
public static double [] getSimulatedHeights(SCMigrationModel migrationModel,
IntegerParameter leafTypes) throws Exception {
// Generate ensemble:
int reps = 100000;
double[] heights = new double[reps];
for (int i = 0; i < reps; i++) {
beast.evolution.tree.StructuredCoalescentMultiTypeTree sctree;
sctree = new beast.evolution.tree.StructuredCoalescentMultiTypeTree();
sctree.initByName(
"migrationModel", migrationModel,
"leafTypes", leafTypes);
heights[i] = sctree.getRoot().getHeight();
}
return heights;
}
}
| gpl-3.0 |
krzyswit2/JSC | src/Main.java | 2245 | /*
Java Scientific Calculator
Copyright (C) 2014 krzygorz
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.HashMap;
import java.util.Scanner;
import com.krzygorz.calculator.gui.CalculatorWindow;
import com.krzygorz.calculator.logic.ExpressionPart;
import com.krzygorz.calculator.misc.Logger;
import com.krzygorz.calculator.misc.SettingsManager;
import com.krzygorz.calculator.parser.MathParser;
public class Main {
//public static HashMap<String, Object> settings = new HashMap<String, Object>();
public static void main(String[] args) {
SettingsManager.loadSettings(args);
for(String i : SettingsManager.getSettings().keySet()){
System.out.println(i + ": " + SettingsManager.getSetting(i));
}
MathParser parser = new MathParser();
Scanner inputScanner = new Scanner(System.in);
System.out.println("enter expression to simplyfy");
String input = inputScanner.nextLine();
try {
ExpressionPart parsedInput = parser.parseString(input);
System.out.println("result tree: " + parsedInput.toString());
System.out.println("value: " + parsedInput.simplyfy());
System.out.println("now trying to do this step by step");
String toOutput = "";
int i = 0;
while(parsedInput.canBeSimplified() && i < 100){
toOutput = toOutput.concat(parsedInput.toString());
toOutput = toOutput.concat(" = ");
parsedInput = parsedInput.nextStepToSimplyfy();
i++;
}
toOutput = toOutput.concat(parsedInput.toString());
System.out.println("result: "+toOutput);
} catch (Exception e) {
e.printStackTrace(System.out);
}
inputScanner.close();
}
}
| gpl-3.0 |
mrdowden/mybatis-demo | src/main/java/com/michaeldowden/store/service/ItemMapper.java | 2118 | package com.michaeldowden.store.service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.michaeldowden.store.model.Bourbon;
import com.michaeldowden.store.utils.LocalDateTimeTypeHandler;
public interface ItemMapper {
@Results(
id = "bourbonResult",
value = {
@Result(property = "id", column = "id", id = true),
@Result(property = "name", column = "name"),
@Result(property = "description", column = "description"),
@Result(property = "price", column = "price", javaType = BigDecimal.class),
@Result(property = "shortname", column = "shortname"),
@Result(property = "lastUpdated", column = "lastUpdated",
javaType = LocalDateTime.class,
typeHandler = LocalDateTimeTypeHandler.class),
@Result(property = "whoUpdated", column = "whoUpdated")
}
)
@Select("SELECT * FROM store.items")
public List<Bourbon> listItems();
@ResultMap("bourbonResult")
@Select("SELECT * FROM store.items WHERE id = #{itemId}")
public Bourbon findBourbon(Integer itemId);
@ResultMap("bourbonResult")
@Select("SELECT * FROM store.items WHERE shortname = #{shortname}")
public Bourbon findBourbonByShortname(String shortname);
@Insert("INSERT INTO items (name, description, price, shortname, lastUpdated, whoUpdated) "
+ "VALUES ( #{name}, #{description}, #{price}, #{shortname}, "
+ "#{lastUpdated,typeHandler=com.michaeldowden.store.utils.LocalDateTimeTypeHandler}, "
+ "#{whoUpdated} )")
public void insertBourbon(Bourbon bourbon);
@Update("UPDATE items SET name = #{name}, description = #{description}, price = #{price}, "
+ "shortname = #{shortname}, lastUpdated = #{lastUpdated,typeHandler=com.michaeldowden.store.utils.LocalDateTimeTypeHandler}, whoUpdated = #{whoUpdated}"
+ "WHERE id = #{id}")
public void updateBourbon(Bourbon bourbon);
}
| gpl-3.0 |
sloanr333/opd-vanilla | src/com/watabou/pixeldungeon/effects/FloatingText.java | 3180 | /*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.watabou.pixeldungeon.effects;
import java.util.ArrayList;
import com.watabou.pixeldungeon.effects.FloatingText;
import com.watabou.pixeldungeon.scenes.GameScene;
import com.watabou.pixeldungeon.scenes.PixelScene;
import com.watabou.noosa.BitmapText;
import com.watabou.noosa.Game;
import com.watabou.pixeldungeon.DungeonTilemap;
import com.watabou.utils.SparseArray;
public class FloatingText extends BitmapText {
private static final float LIFESPAN = 1f;
private static final float DISTANCE = DungeonTilemap.SIZE;
private float timeLeft;
private int key = -1;
private static SparseArray<ArrayList<FloatingText>> stacks = new SparseArray<ArrayList<FloatingText>>();
public FloatingText() {
super();
PixelScene.chooseFont( 9 );
font = PixelScene.font;
scale.set( PixelScene.scale );
speed.y = - DISTANCE / LIFESPAN;
}
@Override
public void update() {
super.update();
if (timeLeft > 0) {
if ((timeLeft -= Game.elapsed) <= 0) {
kill();
} else {
float p = timeLeft / LIFESPAN;
alpha( p > 0.5f ? 1 : p * 2 );
}
}
}
@Override
public void kill() {
if (key != -1) {
stacks.get( key ).remove( this );
key = -1;
}
super.kill();
}
@Override
public void destroy() {
kill();
super.destroy();
}
public void reset( float x, float y, String text, int color ) {
revive();
text( text );
hardlight( color );
measure();
this.x = PixelScene.align( x - width() / 2 );
this.y = y - height();
timeLeft = LIFESPAN;
}
/* STATIC METHODS */
public static void show( float x, float y, String text, int color ) {
GameScene.status().reset( x, y, text, color );
}
public static void show( float x, float y, int key, String text, int color ) {
FloatingText txt = GameScene.status();
txt.reset( x, y, text, color );
push( txt, key );
}
private static void push( FloatingText txt, int key ) {
txt.key = key;
ArrayList<FloatingText> stack = stacks.get( key );
if (stack == null) {
stack = new ArrayList<FloatingText>();
stacks.put( key, stack );
}
if (stack.size() > 0) {
FloatingText below = txt;
int aboveIndex = stack.size() - 1;
while (aboveIndex >= 0) {
FloatingText above = stack.get( aboveIndex );
if (above.y + above.height() > below.y) {
above.y = below.y - above.height();
below = above;
aboveIndex--;
} else {
break;
}
}
}
stack.add( txt );
}
}
| gpl-3.0 |
kyuhlee/SPADE | src/spade/reporter/CDM.java | 27669 | /*
--------------------------------------------------------------------------------
SPADE - Support for Provenance Auditing in Distributed Environments.
Copyright (C) 2015 SRI International
This program is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------
*/
package spade.reporter;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Parser;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.FileUtils;
import com.bbn.tc.schema.avro.cdm18.AbstractObject;
import com.bbn.tc.schema.avro.cdm18.Event;
import com.bbn.tc.schema.avro.cdm18.FileObject;
import com.bbn.tc.schema.avro.cdm18.Host;
import com.bbn.tc.schema.avro.cdm18.HostIdentifier;
import com.bbn.tc.schema.avro.cdm18.HostType;
import com.bbn.tc.schema.avro.cdm18.Interface;
import com.bbn.tc.schema.avro.cdm18.MemoryObject;
import com.bbn.tc.schema.avro.cdm18.NetFlowObject;
import com.bbn.tc.schema.avro.cdm18.Principal;
import com.bbn.tc.schema.avro.cdm18.SHORT;
import com.bbn.tc.schema.avro.cdm18.SrcSinkObject;
import com.bbn.tc.schema.avro.cdm18.Subject;
import com.bbn.tc.schema.avro.cdm18.TCCDMDatum;
import com.bbn.tc.schema.avro.cdm18.UUID;
import com.bbn.tc.schema.avro.cdm18.UnitDependency;
import com.bbn.tc.schema.avro.cdm18.UnnamedPipeObject;
import spade.core.AbstractReporter;
import spade.core.AbstractVertex;
import spade.core.Settings;
import spade.edge.cdm.SimpleEdge;
import spade.reporter.audit.OPMConstants;
import spade.utility.BerkeleyDB;
import spade.utility.CommonFunctions;
import spade.utility.ExternalMemoryMap;
import spade.utility.FileUtility;
import spade.utility.Hasher;
/**
* CDM reporter that reads output of CDM json storage.
*
* Assumes that all vertices are seen before the edges they are a part of.
* If a vertex is not found then edge is not put.
*
*/
public class CDM extends AbstractReporter{
private final Logger logger = Logger.getLogger(this.getClass().getName());
// Keys used in config
private static final String CONFIG_KEY_CACHE_DATABASE_PARENT_PATH = "cacheDatabasePath",
CONFIG_KEY_CACHE_DATABASE_NAME = "verticesDatabaseName",
CONFIG_KEY_CACHE_SIZE = "verticesCacheSize",
CONFIG_KEY_BLOOMFILTER_FALSE_PROBABILITY = "verticesBloomfilterFalsePositiveProbability",
CONFIG_KEY_BLOOMFILTER_EXPECTED_ELEMENTS = "verticesBloomFilterExpectedNumberOfElements",
CONFIG_KEY_SCHEMA = "Schema";
//Reporting variables
private boolean reportingEnabled = false;
private long reportEveryMs;
private long lastReportedTime;
private long linesRead = 0;
private volatile boolean shutdown = false;
private final long THREAD_JOIN_WAIT = 1000; // One second
private final long BUFFER_DRAIN_DELAY = 500;
// External database path for the external memory map
private String dbpath = null;
// Using an external map because can grow arbitrarily
private ExternalMemoryMap<String, AbstractVertex> uuidToVertexMap;
private DataReader dataReader;
// The main thread that processes the file
private Thread datumProcessorThread = new Thread(new Runnable() {
@Override
public void run() {
while(!shutdown){
try{
TCCDMDatum tccdmDatum = null;
while((tccdmDatum = (TCCDMDatum)dataReader.read()) != null){
Object datum = tccdmDatum.getDatum();
processDatum(datum);
}
// EOF
if(tccdmDatum == null){
break;
}
}catch(Exception e){
logger.log(Level.SEVERE, "Error reading/processing file", e);
}
}
while(getBuffer().size() > 0){
if(shutdown){
break;
}
try{
Thread.sleep(BUFFER_DRAIN_DELAY);
}catch(Exception e){
//No need to log this exception
}
if(reportingEnabled){
long currentTime = System.currentTimeMillis();
if((currentTime - lastReportedTime) >= reportEveryMs){
printStats();
lastReportedTime = currentTime;
}
}
}
if(getBuffer().size() > 0){
logger.log(Level.INFO, "File processing partially succeeded");
}else{
logger.log(Level.INFO, "File processing successfully succeeded");
}
doCleanup();
}
}, "CDM-Reporter");
private Map<String, String> readDefaultConfigFile(){
try{
return FileUtility.readConfigFileAsKeyValueMap(
Settings.getDefaultConfigFilePath(this.getClass()),
"="
);
}catch(Exception e){
logger.log(Level.SEVERE, "Failed to load config file", e);
return null;
}
}
private ExternalMemoryMap<String, AbstractVertex> initCacheMap(String tempDirPath, String verticesDatabaseName, String verticesCacheSize,
String verticesBloomfilterFalsePositiveProbability, String verticesBloomfilterExpectedNumberOfElements){
logger.log(Level.INFO, "Argument(s): [{0} = {1}, {2} = {3}, {4} = {5}, {6} = {7}, {8} = {9}]",
new Object[]{CONFIG_KEY_CACHE_DATABASE_PARENT_PATH, tempDirPath,
CONFIG_KEY_CACHE_DATABASE_NAME, verticesDatabaseName,
CONFIG_KEY_CACHE_SIZE, verticesCacheSize,
CONFIG_KEY_BLOOMFILTER_FALSE_PROBABILITY, verticesBloomfilterFalsePositiveProbability,
CONFIG_KEY_BLOOMFILTER_EXPECTED_ELEMENTS, verticesBloomfilterExpectedNumberOfElements});
try{
if(tempDirPath == null || verticesDatabaseName == null || verticesCacheSize == null
|| verticesBloomfilterFalsePositiveProbability == null ||
verticesBloomfilterExpectedNumberOfElements == null){
logger.log(Level.SEVERE, "Null argument(s)");
return null;
}else{
if(!FileUtility.fileExists(tempDirPath)){
if(!FileUtility.mkdirs(tempDirPath)){
logger.log(Level.SEVERE, "Failed to create temp dir at: " + tempDirPath);
return null;
}
}
Integer cacheSize = CommonFunctions.parseInt(verticesCacheSize, null);
if(cacheSize != null){
Double falsePositiveProb = CommonFunctions.parseDouble(verticesBloomfilterFalsePositiveProbability, null);
if(falsePositiveProb != null){
Integer expectedNumberOfElements = CommonFunctions.parseInt(verticesBloomfilterExpectedNumberOfElements, null);
if(expectedNumberOfElements != null){
String timestampedDBName = verticesDatabaseName + "_" + System.currentTimeMillis();
dbpath = tempDirPath + File.separatorChar + timestampedDBName;
if(FileUtility.mkdirs(dbpath)){
ExternalMemoryMap<String, AbstractVertex> externalMap =
new ExternalMemoryMap<String, AbstractVertex>(cacheSize,
new BerkeleyDB<AbstractVertex>(dbpath, timestampedDBName),
falsePositiveProb, expectedNumberOfElements);
// Setting hash to be used as the key because saving vertices by CDM hashes
externalMap.setKeyHashFunction(new Hasher<String>() {
@Override
public String getHash(String t) {
return t;
}
});
return externalMap;
}else{
logger.log(Level.SEVERE, "Failed to create database dir: " + timestampedDBName);
}
}else{
logger.log(Level.SEVERE, "Expected number of elements must be an Integer");
}
}else{
logger.log(Level.SEVERE, "False positive probability must be Floating-Point");
}
}else{
logger.log(Level.SEVERE, "Cache size must be an Integer");
}
}
}catch(Exception e){
logger.log(Level.SEVERE, "Failed to init cache map", e);
}
return null;
}
private void initReporting(String reportingIntervalSecondsConfig){
if(reportingIntervalSecondsConfig != null){
Integer reportingIntervalSeconds = CommonFunctions.parseInt(reportingIntervalSecondsConfig.trim(), null);
if(reportingIntervalSeconds != null){
reportingEnabled = true;
reportEveryMs = reportingIntervalSeconds * 1000;
lastReportedTime = System.currentTimeMillis();
}else{
logger.log(Level.WARNING, "Invalid reporting interval. Reporting disabled.");
}
}
}
@Override
public boolean launch(String arguments) {
String filepath = arguments;
try{
if(FileUtility.fileExists(filepath)){
Map<String, String> configMap = readDefaultConfigFile();
if(configMap != null){
String schemaFilePath = configMap.get(CONFIG_KEY_SCHEMA);
if(FileUtility.fileExists(schemaFilePath)){
initReporting(configMap.get("reportingIntervalSeconds"));
if(filepath.endsWith(".json")){
dataReader = new JsonReader(filepath, schemaFilePath);
}else{
dataReader = new BinaryReader(filepath, schemaFilePath);
}
uuidToVertexMap = initCacheMap(configMap.get(CONFIG_KEY_CACHE_DATABASE_PARENT_PATH),
configMap.get(CONFIG_KEY_CACHE_DATABASE_NAME), configMap.get(CONFIG_KEY_CACHE_SIZE),
configMap.get(CONFIG_KEY_BLOOMFILTER_FALSE_PROBABILITY),
configMap.get(CONFIG_KEY_BLOOMFILTER_EXPECTED_ELEMENTS));
if(uuidToVertexMap != null){
datumProcessorThread.start();
return true;
}else{
return false;
}
}else{
logger.log(Level.SEVERE, "Failed to find schema file at: " + schemaFilePath);
return false;
}
}else{
return false;
}
}else{
logger.log(Level.SEVERE, "Failed to find input filepath at: " + filepath);
return false;
}
}catch(Exception e){
logger.log(Level.SEVERE, "Failed to launch reporter CDM", e);
doCleanup();
}
return false;
}
private void printStats(){
Runtime runtime = Runtime.getRuntime();
long usedMemoryMB = (runtime.totalMemory() - runtime.freeMemory()) / (1024*1024);
long internalBufferSize = getBuffer().size();
logger.log(Level.INFO, "Lines read: {0}, Internal buffer size: {1}, JVM memory in use: {2}MB", new Object[]{linesRead, internalBufferSize, usedMemoryMB});
}
private void processEvent(Event event){
Map<String, String> edgeKeyValues = new HashMap<String, String>();
if(event.getSequence() != null){
edgeKeyValues.put("sequence", String.valueOf(event.getSequence()));
}
if(event.getType() != null){
edgeKeyValues.put("cdm.type", String.valueOf(event.getType()));
}
if(event.getThreadId() != null){
edgeKeyValues.put("threadId", String.valueOf(event.getThreadId()));
}
if(event.getTimestampNanos() != null){
edgeKeyValues.put("timestampNanos", String.valueOf(event.getTimestampNanos()));
}
if(event.getLocation() != null){
edgeKeyValues.put("location", String.valueOf(event.getLocation()));
}
if(event.getSize() != null){
edgeKeyValues.put("size", String.valueOf(event.getSize()));
}
edgeKeyValues.putAll(getValuesFromPropertiesMap(event.getProperties()));
String opmValue = null, operationValue = null;
UUID src1Uuid = null, dst1Uuid = null, // process to/from primary
src2Uuid = null, dst2Uuid = null, //process to/from secondary
src3Uuid = null, dst3Uuid = null; //primary to/from secondary
switch (event.getType()) {
case EVENT_OTHER:
operationValue = edgeKeyValues.get(OPMConstants.EDGE_OPERATION);
if(OPMConstants.OPERATION_TEE.equals(operationValue)
|| OPMConstants.OPERATION_SPLICE.equals(operationValue)){
src1Uuid = event.getSubject();
dst1Uuid = event.getPredicateObject();
src2Uuid = event.getPredicateObject2();
dst2Uuid = event.getSubject();
src3Uuid = event.getPredicateObject2();
dst3Uuid = event.getPredicateObject();
}else if(OPMConstants.OPERATION_VMSPLICE.equals(operationValue)){
src1Uuid = event.getPredicateObject();
dst1Uuid = event.getSubject();
}else if(OPMConstants.OPERATION_INIT_MODULE.equals(operationValue)
|| OPMConstants.OPERATION_FINIT_MODULE.equals(operationValue)){
src1Uuid = event.getSubject();
dst1Uuid = event.getPredicateObject();
}
break;
case EVENT_OPEN:
case EVENT_CLOSE:
opmValue = edgeKeyValues.get(OPMConstants.OPM);
case EVENT_LOADLIBRARY:
case EVENT_RECVMSG:
case EVENT_RECVFROM:
case EVENT_READ:
case EVENT_ACCEPT:
if(opmValue != null){
if(opmValue.equals(OPMConstants.USED)){
src1Uuid = event.getSubject();
dst1Uuid = event.getPredicateObject();
}else if(opmValue.equals(OPMConstants.WAS_GENERATED_BY)){
src1Uuid = event.getPredicateObject();
dst1Uuid = event.getSubject();
}
}else{
src1Uuid = event.getSubject();
dst1Uuid = event.getPredicateObject();
}
break;
case EVENT_EXIT:
case EVENT_UNIT:
case EVENT_FORK:
case EVENT_EXECUTE:
case EVENT_CLONE:
case EVENT_CHANGE_PRINCIPAL:
src1Uuid = event.getPredicateObject();
dst1Uuid = event.getSubject();
break;
case EVENT_CONNECT:
case EVENT_CREATE_OBJECT:
case EVENT_WRITE:
case EVENT_MPROTECT:
case EVENT_SENDTO:
case EVENT_SENDMSG:
case EVENT_UNLINK:
case EVENT_MODIFY_FILE_ATTRIBUTES:
case EVENT_TRUNCATE:
src1Uuid = event.getPredicateObject();
dst1Uuid = event.getSubject();
break;
case EVENT_LINK:
case EVENT_RENAME:
case EVENT_MMAP:
case EVENT_UPDATE:
src1Uuid = event.getSubject();
dst1Uuid = event.getPredicateObject();
src2Uuid = event.getPredicateObject2();
dst2Uuid = event.getSubject();
src3Uuid = event.getPredicateObject2();
dst3Uuid = event.getPredicateObject();
break;
default:
logger.log(Level.WARNING, "Unexpected Event type: " + event.getType());
return;
}
if(src1Uuid != null && dst1Uuid != null){
SimpleEdge edge = new SimpleEdge(
uuidToVertexMap.get(getUUIDAsString(src1Uuid)),
uuidToVertexMap.get(getUUIDAsString(dst1Uuid)));
edge.addAnnotations(edgeKeyValues);
putEdge(edge);
}
if(src2Uuid != null && dst2Uuid != null){
SimpleEdge edge = new SimpleEdge(
uuidToVertexMap.get(getUUIDAsString(src2Uuid)),
uuidToVertexMap.get(getUUIDAsString(dst2Uuid)));
edge.addAnnotations(edgeKeyValues);
putEdge(edge);
}
if(src3Uuid != null && dst3Uuid != null){
SimpleEdge edge = new SimpleEdge(
uuidToVertexMap.get(getUUIDAsString(src3Uuid)),
uuidToVertexMap.get(getUUIDAsString(dst3Uuid)));
edge.addAnnotations(edgeKeyValues);
putEdge(edge);
}
}
private void processDatum(Object datum){
if(reportingEnabled){
linesRead++;
long currentTime = System.currentTimeMillis();
if((currentTime - lastReportedTime) >= reportEveryMs){
printStats();
lastReportedTime = currentTime;
}
}
if(datum != null){
Class<?> datumClass = datum.getClass();
if(datumClass.equals(UnitDependency.class)){
UnitDependency unitDependency = (UnitDependency)datum;
UUID unitUuid = unitDependency.getUnit();//dst
UUID dependentUnitUuid = unitDependency.getDependentUnit();//src
String unitUuidString = getUUIDAsString(unitUuid);
String dependentUnitUuidString = getUUIDAsString(dependentUnitUuid);
AbstractVertex unitVertex = uuidToVertexMap.get(unitUuidString);
AbstractVertex dependentUnitVertex = uuidToVertexMap.get(dependentUnitUuidString);
spade.edge.cdm.SimpleEdge edge = new spade.edge.cdm.SimpleEdge(dependentUnitVertex, unitVertex);
putEdge(edge);
}else if(datumClass.equals(Event.class)){
Event event = (Event)datum;
processEvent(event);
}else{
UUID uuid = null;
AbstractVertex vertex = null;
UUID principalUuid = null;
if(datumClass.equals(Subject.class)){
vertex = new spade.vertex.cdm.Subject();
Subject subject = (Subject)datum;
uuid = subject.getUuid();
if(subject.getCid() != null){
vertex.addAnnotation("pid", String.valueOf(subject.getCid()));
}
if(subject.getParentSubject() != null){
vertex.addAnnotation("parentSubjectUuid", getUUIDAsString(subject.getParentSubject()));
}
if(subject.getLocalPrincipal() != null){
vertex.addAnnotation("localPrincipal", getUUIDAsString(subject.getLocalPrincipal()));
}
principalUuid = subject.getLocalPrincipal();
if(subject.getStartTimestampNanos() != null){
vertex.addAnnotation("startTimestampNanos", String.valueOf(subject.getStartTimestampNanos()));
}
if(subject.getUnitId() != null){
vertex.addAnnotation("unitId", String.valueOf(subject.getUnitId()));
}
if(subject.getIteration() != null){
vertex.addAnnotation("iteration", String.valueOf(subject.getIteration()));
}
if(subject.getCount() != null){
vertex.addAnnotation("count", String.valueOf(subject.getCount()));
}
if(subject.getCmdLine() != null){
vertex.addAnnotation("cmdLine", String.valueOf(subject.getCmdLine()));
}
vertex.addAnnotations(getValuesFromPropertiesMap(subject.getProperties()));
if(subject.getType() != null){
vertex.addAnnotation("cdm.type", String.valueOf(subject.getType()));
}
}else if(datumClass.equals(Principal.class)){
vertex = new spade.vertex.cdm.Principal();
Principal principal = (Principal)datum;
uuid = principal.getUuid();
if(principal.getUserId() != null){
vertex.addAnnotation("userId", String.valueOf(principal.getUserId()));
}
List<CharSequence> groupIds = principal.getGroupIds();
if(groupIds.size() > 0){
vertex.addAnnotation("gid", String.valueOf(groupIds.get(0)));
}
if(groupIds.size() > 1){
vertex.addAnnotation("egid", String.valueOf(groupIds.get(1)));
}
if(groupIds.size() > 2){
vertex.addAnnotation("sgid", String.valueOf(groupIds.get(2)));
}
if(groupIds.size() > 3){
vertex.addAnnotation("fsgid", String.valueOf(groupIds.get(3)));
}
vertex.addAnnotations(getValuesFromPropertiesMap(principal.getProperties()));
vertex.addAnnotation("cdm.type", "Principal");
}else { // artifacts
vertex = new spade.vertex.cdm.Object();
AbstractObject baseObject = null;
if(datumClass.equals(MemoryObject.class)){
MemoryObject memoryObject = (MemoryObject)datum;
uuid = memoryObject.getUuid();
baseObject = memoryObject.getBaseObject();
if(memoryObject.getMemoryAddress() != null){
vertex.addAnnotation("memoryAddress", String.valueOf(memoryObject.getMemoryAddress()));
}
if(memoryObject.getSize() != null){
vertex.addAnnotation("size", String.valueOf(memoryObject.getSize()));
}
vertex.addAnnotation("cdm.type", "MemoryObject");
}else if(datumClass.equals(NetFlowObject.class)){
NetFlowObject netFlowObject = (NetFlowObject)datum;
uuid = netFlowObject.getUuid();
baseObject = netFlowObject.getBaseObject();
if(netFlowObject.getLocalAddress() != null){
vertex.addAnnotation("localAddress", String.valueOf(netFlowObject.getLocalAddress()));
}
if(netFlowObject.getLocalPort() != null){
vertex.addAnnotation("localPort", String.valueOf(netFlowObject.getLocalPort()));
}
if(netFlowObject.getRemoteAddress() != null){
vertex.addAnnotation("remoteAddress", String.valueOf(netFlowObject.getRemoteAddress()));
}
if(netFlowObject.getRemotePort() != null){
vertex.addAnnotation("remotePort", String.valueOf(netFlowObject.getRemotePort()));
}
if(netFlowObject.getIpProtocol() != null){
vertex.addAnnotation("ipProtocol", String.valueOf(netFlowObject.getIpProtocol()));
}
vertex.addAnnotation("cdm.type", "NetFlowObject");
}else if(datumClass.equals(SrcSinkObject.class)){
SrcSinkObject srcSinkObject = (SrcSinkObject)datum;
// unknown
uuid = srcSinkObject.getUuid();
baseObject = srcSinkObject.getBaseObject();
if(srcSinkObject.getFileDescriptor() != null){
vertex.addAnnotation("fileDescriptor", String.valueOf(srcSinkObject.getFileDescriptor()));
}
vertex.addAnnotation("cdm.type", "SrcSinkObject");
}else if(datumClass.equals(UnnamedPipeObject.class)){
UnnamedPipeObject unnamedPipeObject = (UnnamedPipeObject)datum;
uuid = unnamedPipeObject.getUuid();
baseObject = unnamedPipeObject.getBaseObject();
if(unnamedPipeObject.getSourceFileDescriptor() != null){
vertex.addAnnotation("sourceFileDescriptor", String.valueOf(unnamedPipeObject.getSourceFileDescriptor()));
}
if(unnamedPipeObject.getSinkFileDescriptor() != null){
vertex.addAnnotation("sinkFileDescriptor", String.valueOf(unnamedPipeObject.getSinkFileDescriptor()));
}
vertex.addAnnotation("cdm.type", "UnnamedPipeObject");
}else if(datumClass.equals(FileObject.class)){
FileObject fileObject = (FileObject)datum;
uuid = fileObject.getUuid();
baseObject = fileObject.getBaseObject();
if(fileObject.getType() != null){
vertex.addAnnotation("cdm.type", String.valueOf(fileObject.getType()));
}
}else if(datumClass.equals(Host.class)){
Host hostObject = (Host)datum;
uuid = hostObject.getUuid();
CharSequence hostName = hostObject.getHostName();
CharSequence osDetails = hostObject.getOsDetails();
HostType hostType = hostObject.getHostType();
List<HostIdentifier> hostIdentifiers = hostObject.getHostIdentifiers();
List<Interface> interfaces = hostObject.getInterfaces();
vertex.addAnnotation("hostName", String.valueOf(hostName));
vertex.addAnnotation("osDetails", String.valueOf(osDetails));
vertex.addAnnotation("hostType", String.valueOf(hostType));
if(hostIdentifiers != null){
for(HostIdentifier hostIdentifier : hostIdentifiers){
if(hostIdentifier != null){
vertex.addAnnotation(String.valueOf(hostIdentifier.getIdType()),
String.valueOf(hostIdentifier.getIdValue()));
}
}
}
if(interfaces != null){
for(Interface interfaze : interfaces){
if(interfaze != null){
vertex.addAnnotation("name", String.valueOf(interfaze.getName()));
vertex.addAnnotation("macAddress", String.valueOf(interfaze.getMacAddress()));
vertex.addAnnotation("ipAddresses", String.valueOf(interfaze.getIpAddresses()));
}
}
}
vertex.addAnnotation("cdm.type", "Host");
}
vertex.addAnnotations(getValuesFromArtifactAbstractObject(baseObject));
}
if(uuid != null && vertex != null){
String uuidString = getUUIDAsString(uuid);
vertex.addAnnotation("uuid", uuidString);
uuidToVertexMap.put(uuidString, vertex);
putVertex(vertex);
if(principalUuid != null){
AbstractVertex principalVertex = uuidToVertexMap.get(getUUIDAsString(principalUuid));
if(principalVertex != null){
SimpleEdge edge = new SimpleEdge(vertex, principalVertex);
putEdge(edge);
}
}
}
}
}
}
private String getUUIDAsString(UUID uuid){
if(uuid != null){
return Hex.encodeHexString(uuid.bytes());
}
return null;
}
private String getPermissionSHORTAsString(SHORT permission){
if(permission == null){
return null;
}else{
ByteBuffer bb = ByteBuffer.allocate(2);
bb.put(permission.bytes()[0]);
bb.put(permission.bytes()[1]);
int permissionShort = bb.getShort(0);
return Integer.toOctalString(permissionShort);
}
}
private Map<String, String> getValuesFromArtifactAbstractObject(AbstractObject object){
Map<String, String> keyValues = new HashMap<String, String>();
if(object != null){
if(object.getEpoch() != null){
keyValues.put("epoch", String.valueOf(object.getEpoch()));
}
if(object.getPermission() != null){
keyValues.put("permission", new String(getPermissionSHORTAsString(object.getPermission())));
}
keyValues.putAll(getValuesFromPropertiesMap(object.getProperties()));
}
return keyValues;
}
private Map<String, String> getValuesFromPropertiesMap(Map<CharSequence, CharSequence> propertiesMap){
Map<String, String> keyValues = new HashMap<String, String>();
if(propertiesMap != null){
propertiesMap.entrySet().forEach(
entry -> {
if(entry.getValue() != null){
keyValues.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
}
);
}
return keyValues;
}
@Override
public boolean shutdown() {
shutdown = true;
try{
if(datumProcessorThread != null){
datumProcessorThread.join(THREAD_JOIN_WAIT);
}
return true;
}catch(Exception e){
logger.log(Level.SEVERE, "Failed to close file reader", e);
return false;
}
}
private void doCleanup(){
try{
if(uuidToVertexMap != null){
uuidToVertexMap.close();
}
}catch(Exception e){
logger.log(Level.WARNING, "Failed to close cache map", e);
}
try{
if(dbpath != null && FileUtility.fileExists(dbpath)){
FileUtils.forceDelete(new File(dbpath));
}
}catch(Exception e){
logger.log(Level.WARNING, "Failed to delete database dir at: " + dbpath, e);
}
}
}
interface DataReader{
/**
* Must return null to indicate EOF
*
* @return TCCDMDatum object
* @throws Exception
*/
public Object read() throws Exception;
public void close() throws Exception;
/**
* @return The data file being read
*/
public String getDataFilePath();
}
class JsonReader implements DataReader{
private String filepath;
private DatumReader<Object> datumReader;
private Decoder decoder;
public JsonReader(String dataFilepath, String schemaFilepath) throws Exception{
this.filepath = dataFilepath;
Parser parser = new Schema.Parser();
Schema schema = parser.parse(new File(schemaFilepath));
this.datumReader = new SpecificDatumReader<Object>(schema);
this.decoder = DecoderFactory.get().jsonDecoder(schema,
new FileInputStream(new File(dataFilepath)));
}
public Object read() throws Exception{
try{
return datumReader.read(null, decoder);
}catch(EOFException eof){
return null;
}catch(Exception e){
throw e;
}
}
public void close() throws Exception{
// Nothing
}
public String getDataFilePath(){
return filepath;
}
}
class BinaryReader implements DataReader{
private String filepath;
private DataFileReader<Object> dataFileReader;
public BinaryReader(String dataFilepath, String schemaFilepath) throws Exception{
this.filepath = dataFilepath;
Parser parser = new Schema.Parser();
Schema schema = parser.parse(new File(schemaFilepath));
DatumReader<Object> datumReader = new SpecificDatumReader<Object>(schema);
this.dataFileReader = new DataFileReader<>(new File(dataFilepath), datumReader);
}
public Object read() throws Exception{
if(dataFileReader.hasNext()){
return dataFileReader.next();
}else{
return null;
}
}
public void close() throws Exception{
dataFileReader.close();
}
public String getDataFilePath(){
return filepath;
}
}
| gpl-3.0 |
MarkHooijkaas/caas-cordys-svn | src/java/org/kisst/caas/_2_0/template/package-info.java | 539 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.06.21 at 10:05:41 AM CEST
//
@javax.xml.bind.annotation.XmlSchema(namespace = "http://caas.kisst.org/2.0/template", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.kisst.caas._2_0.template;
| gpl-3.0 |
dozzatq/Phoenix | mylibrary/src/main/java/com/github/dozzatq/phoenix/util/Encoder.java | 432 | package com.github.dozzatq.phoenix.util;
import android.support.annotation.NonNull;
import android.util.Base64;
/**
* Created by rodion on 20.11.16.
*/
public class Encoder {
public static String encode(@NonNull String potential)
{
try {
return new String(Base64.encode(potential.getBytes(), Base64.DEFAULT));
}
catch (Exception e)
{
return "";
}
}
}
| gpl-3.0 |
Neschur/KB2 | app/src/main/java/by/siarhei/kb2/app/ui/messages/GuidePostMessage.java | 592 | package by.siarhei.kb2.app.ui.messages;
import by.siarhei.kb2.app.I18n;
import by.siarhei.kb2.app.server.models.Game;
import by.siarhei.kb2.app.server.models.MapPoint;
import java.util.Random;
public class GuidePostMessage extends Message {
private static final int COUNT = 13;
GuidePostMessage(MapPoint mapPoint, Game game, I18n i18n) {
super(mapPoint, game, i18n);
}
@Override
public String getText() {
return i18n.translate("entity_guidePost_message" + ((new Random()).nextInt(COUNT) + 1));
}
@Override
public void action() {
}
}
| gpl-3.0 |
potty-dzmeia/db4o | src/db4oj.tests/src/com/db4o/test/CallbackCanDelete.java | 1701 | /* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/. */
package com.db4o.test;
import com.db4o.*;
public class CallbackCanDelete {
public String _name;
public CallbackCanDelete _next;
public CallbackCanDelete() {
}
public CallbackCanDelete(String name_, CallbackCanDelete next_) {
_name = name_;
_next = next_;
}
public void storeOne(){
Test.deleteAllInstances(this);
_name = "p1";
_next = new CallbackCanDelete("c1", null);
}
public void test(){
ObjectContainer oc = Test.objectContainer();
ObjectSet objectSet = oc.queryByExample(new CallbackCanDelete("p1", null));
CallbackCanDelete ccd = (CallbackCanDelete) objectSet.next();
oc.deactivate(ccd, Integer.MAX_VALUE);
oc.delete(ccd);
}
public boolean objectCanDelete(ObjectContainer container){
container.activate(this, Integer.MAX_VALUE);
Test.ensure(_name.equals("p1"));
Test.ensure(_next != null);
return true;
}
}
| gpl-3.0 |
ldbc/ldbc_driver | src/main/java/com/ldbc/driver/workloads/ldbc/snb/interactive/LdbcQuery14.java | 4742 | package com.ldbc.driver.workloads.ldbc.snb.interactive;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.ldbc.driver.Operation;
import com.ldbc.driver.SerializingMarshallingException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static java.lang.String.format;
public class LdbcQuery14 extends Operation<List<LdbcQuery14Result>>
{
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static final int TYPE = 14;
public static final String PERSON1_ID = "person1Id";
public static final String PERSON2_ID = "person2Id";
private final long person1Id;
private final long person2Id;
public LdbcQuery14( long person1Id, long person2Id )
{
this.person1Id = person1Id;
this.person2Id = person2Id;
}
public long person1Id()
{
return person1Id;
}
public long person2Id()
{
return person2Id;
}
@Override
public Map<String, Object> parameterMap() {
return ImmutableMap.<String, Object>builder()
.put(PERSON1_ID, person1Id)
.put(PERSON2_ID, person2Id)
.build();
}
@Override
public boolean equals( Object o )
{
if ( this == o )
{ return true; }
if ( o == null || getClass() != o.getClass() )
{ return false; }
LdbcQuery14 that = (LdbcQuery14) o;
if ( person1Id != that.person1Id )
{ return false; }
if ( person2Id != that.person2Id )
{ return false; }
return true;
}
@Override
public int hashCode()
{
int result = (int) (person1Id ^ (person1Id >>> 32));
result = 31 * result + (int) (person2Id ^ (person2Id >>> 32));
return result;
}
@Override
public String toString()
{
return "LdbcQuery14{" +
"person1Id=" + person1Id +
", person2Id=" + person2Id +
'}';
}
@Override
public List<LdbcQuery14Result> marshalResult( String serializedResults ) throws SerializingMarshallingException
{
List<List<Object>> resultsAsList;
try
{
resultsAsList = OBJECT_MAPPER.readValue(
serializedResults,
new TypeReference<List<List<Object>>>()
{
}
);
}
catch ( IOException e )
{
throw new SerializingMarshallingException(
format( "Error while parsing serialized results\n%s", serializedResults ), e );
}
List<LdbcQuery14Result> results = new ArrayList<>();
for ( int i = 0; i < resultsAsList.size(); i++ )
{
List<Object> resultAsList = resultsAsList.get( i );
Iterable<Long> personsIdsInPath =
Iterables.transform( (List<Number>) resultAsList.get( 0 ), new Function<Number,Long>()
{
@Override
public Long apply( Number number )
{
return number.longValue();
}
} );
double pathWeight = ((Number) resultAsList.get( 1 )).doubleValue();
results.add(
new LdbcQuery14Result(
personsIdsInPath,
pathWeight
)
);
}
return results;
}
@Override
public String serializeResult( Object resultsObject ) throws SerializingMarshallingException
{
List<LdbcQuery14Result> results = (List<LdbcQuery14Result>) resultsObject;
List<List<Object>> resultsFields = new ArrayList<>();
for ( int i = 0; i < results.size(); i++ )
{
LdbcQuery14Result result = results.get( i );
List<Object> resultFields = new ArrayList<>();
resultFields.add( result.personsIdsInPath() );
resultFields.add( result.pathWeight() );
resultsFields.add( resultFields );
}
try
{
return OBJECT_MAPPER.writeValueAsString( resultsFields );
}
catch ( IOException e )
{
throw new SerializingMarshallingException(
format( "Error while trying to serialize result\n%s", results.toString() ), e );
}
}
@Override
public int type()
{
return TYPE;
}
}
| gpl-3.0 |
gemarcano/SWEN-Fuzzer | src/fuzzer/apps/VVector/VVectorTest.java | 333 | package fuzzer.apps.VVector;
public class VVectorTest {
private boolean mSuccess;
private VVector mVector;
public VVectorTest(VVector aVector)
{
mVector = aVector;
mSuccess = mVector.test();
}
public boolean success()
{
return mSuccess;
}
public String getDescription()
{
return mVector.getDescription();
}
}
| gpl-3.0 |
hernol/ConuWar | AndroidME/src_JSR179_Location/javax/microedition/location/ProximityListener.java | 203 | package javax.microedition.location;
public interface ProximityListener {
void monitoringStateChanged(boolean isMonitoringActive);
void proximityEvent(Coordinates coordinates, Location location);
}
| gpl-3.0 |
iksoiks/concerto-framework-core | src/com/n_micocci/concerto/filters/FiltersHelper.java | 1961 | /*
* Copyright (c) 2016 Christian Micocci. This file is part of Concerto.
*
* Concerto is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Concerto is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Concerto. If not, see <http://www.gnu.org/licenses/>.
*/
package com.n_micocci.concerto.filters;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiMessage;
import javax.sound.midi.ShortMessage;
public final class FiltersHelper {
private FiltersHelper() {
}
/**
* Make ShortMessage from a MidiMessage with status byte overridden
*
* @param midiMessage old MidiMessage
* @param status new status
* @return the ShortMessage from the old MidiMessage with status byte overridden
* @throws InvalidMidiDataException if the new status is not compatible with the old.
*/
public static ShortMessage makeShortMessage(MidiMessage midiMessage, int status) throws InvalidMidiDataException {
byte[] message = midiMessage.getMessage();
ShortMessage shortMessage;
switch (midiMessage.getLength()) {
case 2:
shortMessage = new ShortMessage(status, message[1], 0);
break;
case 3:
shortMessage = new ShortMessage(status, message[1], message[2]);
break;
case 1:
default:
shortMessage = new ShortMessage(status);
break;
}
return shortMessage;
}
}
| gpl-3.0 |
BDE-social-pilot/Harvesters | AthensFinRatioTransformToRdf/rdfFinancialRatioStatsForAthens/src/main/java/main/Main.java | 1453 | package main;
import calculateFinancialRatios.FinRatiosStatsAthens;
/**
*
* @author giorgos, lefteris
*/
public class Main {
public static void main(String[] args) {
FinRatiosStatsAthens process1 = new FinRatiosStatsAthens();
//Set connection string to connect with OpenLink Virtuoso Server which contains triples about municipality budget executions
String connnectionStringToOLV = "jdbc:virtuoso://{ipOfOLV}/:1111/autoReconnect=true/charset=UTF-8/log_enable=2";
//Set username to connect with OpenLink Virtuoso
String usernameOLV = "{usernameOfOLV}";
//Set password to connect with OpenLink Virtuoso
String passwordOLV = "{passwordOfOLV}";
//Set directory where will be stored the output - RDF files
String directoryForStoringRDF = "C:/Users/Lefteris/TestForFinancialRatio/rdf/";
//Set graph's IRI which contains triples for Athens Budget Execution
String graphIRIWithDataForAthens = "http://linkedeconomy.org/AthensBudget";
//Set the date you want to calculate financial ratios for Athens Municipality
String dateForCalculationAthensFinRatioStats = "2016-06-30";
//run method which calculate financial ratios for Athens
process1.executeFinRatiosStatsAthens(connnectionStringToOLV, usernameOLV, passwordOLV, graphIRIWithDataForAthens, dateForCalculationAthensFinRatioStats, directoryForStoringRDF);
}
}
| gpl-3.0 |
WouterSpekkink/MDSLayout | MDSLayoutBuilder.java | 2955 | /* Copyright 2015 Wouter Spekkink
Authors : Wouter Spekkink <wouterspekkink@gmail.com>
Website : http://www.wouterspekkink.org
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
Copyright 2015 Wouter Spekkink. All rights reserved.
The contents of this file are subject to the terms of either the GNU
General Public License Version 3 only ("GPL") or the Common
Development and Distribution License("CDDL") (collectively, the
"License"). You may not use this file except in compliance with the
License. You can obtain a copy of the License at
http://gephi.org/about/legal/license-notice/
or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the
specific language governing permissions and limitations under the
License. When distributing the software, include this License Header
Notice in each file and include the License files at
/cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the
License Header, with the fields enclosed by brackets [] replaced by
your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]"
If you wish your version of this file to be governed by only the CDDL
or only the GPL Version 3, indicate your decision by adding
"[Contributor] elects to include this software in this distribution
under the [CDDL or GPL Version 3] license." If you do not indicate a
single choice of license, a recipient has the option to distribute
your version of this file under either the CDDL, the GPL Version 3 or
to extend the choice of license to its licensees as provided above.
However, if you add GPL Version 3 code and therefore, elected the GPL
Version 3 license, then the option applies only if the new code is
made subject to such option by the copyright holder.
Contributor(s): Wouter Spekkink
The plugin structure was inspired by the structure of the GeoLayout plugin.
*/
package org.wouterspekkink.mdslayout;
import javax.swing.Icon;
import javax.swing.JPanel;
import org.gephi.layout.spi.Layout;
import org.gephi.layout.spi.LayoutBuilder;
import org.gephi.layout.spi.LayoutUI;
import org.openide.util.lookup.ServiceProvider;
@ServiceProvider(service = LayoutBuilder.class)
public class MDSLayoutBuilder implements LayoutBuilder {
private MDSLayoutUI ui = new MDSLayoutUI();
public String getName() {
return "MDS Layout";
}
public LayoutUI getUI() {
return ui;
}
public Layout buildLayout() {
return new MDSLayout(this);
}
private static class MDSLayoutUI implements LayoutUI {
public String getDescription() {
return "Layout for Multidimensional Scaling Results";
}
public Icon getIcon() {
return null;
}
public JPanel getSimplePanel(Layout layout) {
return null;
}
public int getQualityRank() {
return -1;
}
public int getSpeedRank() {
return -1;
}
}
}
| gpl-3.0 |
EverCraft/EverPermissions | src/main/java/fr/evercraft/everpermissions/service/permission/data/EPNode.java | 6210 | /*
* This file is part of EverPermissions.
*
* EverPermissions is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EverPermissions is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EverPermissions. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.evercraft.everpermissions.service.permission.data;
import java.util.HashMap;
import java.util.Map;
import org.spongepowered.api.util.Tristate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
public class EPNode extends HashMap<String, EPNode> {
private static final long serialVersionUID = -3369286570178770580L;
private static final Splitter NODE_SPLITTER = Splitter.on('.');
private Tristate value;
/*
* Constructor
*/
public EPNode() {
super();
this.value = Tristate.UNDEFINED;
}
private EPNode(final Tristate value) {
super();
this.value = value;
}
private EPNode(final Map<String, EPNode> children, final Tristate value) {
super();
this.putAll(children);
this.value = value;
}
/*
* Accesseur
*/
private void setTristate(final Tristate value) {
this.value = value;
}
private Tristate getTristate() {
return this.value;
}
/**
* Clone
* @return Nouveau node
*/
public EPNode copy() {
return new EPNode(this, this.value);
}
/**
* Retourne la valeur de la permission
* @param permission La permission
* @return La valeur de la permission
*/
public Tristate getTristate(final String permission) {
Iterable<String> parts = NODE_SPLITTER.split(permission.toLowerCase());
EPNode currentNode = this;
Tristate lastUndefinedVal = Tristate.UNDEFINED;
for (String str : parts) {
if (!currentNode.containsKey(str)) {
break;
}
currentNode = currentNode.get(str);
if (currentNode.getTristate() != Tristate.UNDEFINED) {
lastUndefinedVal = currentNode.getTristate();
}
}
return lastUndefinedVal;
}
/**
* Retourne une Map avec les permissions et leur valeur
* @return Permission : Valeur
*/
public Map<String, Boolean> asMap() {
ImmutableMap.Builder<String, Boolean> ret = ImmutableMap.builder();
for (Map.Entry<String, EPNode> ent : this.entrySet()) {
populateMap(ret, ent.getKey(), ent.getValue());
}
return ret.build();
}
/**
* Fonction pour créer une Map
* @param values La map
* @param prefix Le prefix
* @param currentNode Le node
*/
private void populateMap(final ImmutableMap.Builder<String, Boolean> values, final String prefix, final EPNode currentNode) {
if (currentNode.getTristate() != Tristate.UNDEFINED) {
values.put(prefix, currentNode.value.asBoolean());
}
for (Map.Entry<String, EPNode> ent : currentNode.entrySet()) {
populateMap(values, prefix + '.' + ent.getKey(), ent.getValue());
}
}
/*
* Fonctions
*/
/**
* Création d'un node à partir d'une map
* @param values Permission : Valeur
* @return Le node
*/
public static EPNode of(final Map<String, Boolean> values) {
return of(values, Tristate.UNDEFINED);
}
/**
* Création d'un node à partir d'une map
* @param values Permission : Valeur
* @param defaultValue La valeur par défaut
* @return Le node
*/
public static EPNode of(final Map<String, Boolean> values, final Tristate defaultValue) {
EPNode newTree = new EPNode(defaultValue);
for (Map.Entry<String, Boolean> value : values.entrySet()) {
Iterable<String> parts = NODE_SPLITTER.split(value.getKey().toLowerCase());
EPNode currentNode = newTree;
for (String part : parts) {
if (currentNode.containsKey(part)) {
currentNode = currentNode.get(part);
} else {
EPNode newNode = new EPNode();
currentNode.put(part, newNode);
currentNode = newNode;
}
}
currentNode.setTristate(Tristate.fromBoolean(value.getValue()));
}
return newTree;
}
/**
* Modifie une permission
* @param node Le node
* @param value La valeur
* @return Le nouveau node
*/
public EPNode withValue(final String node, final Tristate value) {
Iterable<String> parts = NODE_SPLITTER.split(node.toLowerCase());
EPNode newRoot = this.copy();
EPNode currentPtr = newRoot;
for (String part : parts) {
EPNode oldChild = currentPtr.get(part);
EPNode newChild;
if (oldChild == null) {
newChild = new EPNode();
} else {
newChild = oldChild.copy();
}
currentPtr.put(part, newChild);
currentPtr = newChild;
}
currentPtr.setTristate(value);
return newRoot;
}
/**
* Modifie des permissions
* @param values Une map de permission
* @return Le nouveau node
*/
public EPNode withAll(final Map<String, Tristate> values) {
EPNode node = this;
for (Map.Entry<String, Tristate> ent : values.entrySet()) {
node = node.withValue(ent.getKey(), ent.getValue());
}
return node;
}
}
| gpl-3.0 |
Cyancraft/Cyancraft | src/main/java/net/adanicx/cyancraft/CyancraftMod.java | 8365 | package net.adanicx.cyancraft;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLInterModComms.IMCEvent;
import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.ReflectionHelper;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.oredict.OreDictionary;
import net.adanicx.cyancraft.command.SetPlayerModelCommand;
import net.adanicx.cyancraft.configuration.ConfigurationHandler;
import net.adanicx.cyancraft.core.proxy.CommonProxy;
import net.adanicx.cyancraft.entities.ModEntityList;
import net.adanicx.cyancraft.items.ItemEntityEgg;
import net.adanicx.cyancraft.libraries.ModReferences;
import net.adanicx.cyancraft.network.ArmorStandInteractHandler;
import net.adanicx.cyancraft.network.ArmorStandInteractMessage;
import net.adanicx.cyancraft.network.DamageParticlesHandler;
import net.adanicx.cyancraft.network.DamageParticlesMessage;
import net.adanicx.cyancraft.network.SetPlayerModelHandler;
import net.adanicx.cyancraft.network.SetPlayerModelMessage;
import net.adanicx.cyancraft.recipes.BrewingFuelRegistry;
import net.adanicx.cyancraft.recipes.CRecipes;
import net.adanicx.cyancraft.world.CWorldGen;
import net.adanicx.cyancraft.world.OceanTemple;
@Mod(modid = ModReferences.MOD_ID, name = ModReferences.MOD_NAME, version = ModReferences.VERSION_NUMBER, dependencies = ModReferences.DEPENDENCIES, guiFactory = ModReferences.GUI_FACTORY_CLASS)
public class CyancraftMod {
@Instance(ModReferences.MOD_ID)
public static CyancraftMod instance;
@SidedProxy(clientSide = ModReferences.CLIENT_PROXY_CLASS, serverSide = ModReferences.SERVER_PROXY_CLASS)
public static CommonProxy proxy;
public static SimpleNetworkWrapper networkWrapper;
public static CreativeTabs creativeTab = new CreativeTabs(ModReferences.MOD_ID) {
@Override
public Item getTabIconItem() {
return enablePrismarine ? CItems.prismarine_shard : Items.skull;
}
};
public static boolean enableStones = true;
public static boolean enableIronTrapdoor = true;
public static boolean enableMutton = true;
public static boolean enableSponge = true;
public static boolean enablePrismarine = true;
public static boolean enableDoors = true;
public static boolean enableInvertedDaylightSensor = true;
public static boolean enableCoarseDirt = true;
public static boolean enableRedSandstone = true;
public static boolean enableEnchants = true;
public static boolean enableAnvil = true;
public static boolean enableFences = true;
public static boolean enableSilkTouchingMushrooms = true;
public static boolean enableBanners = true;
public static boolean enableSlimeBlock = true;
public static boolean enableArmorStand = true;
public static boolean enableRabbit = true;
public static boolean enableRecipeForPrismarine = true;
public static boolean enableEndermite = true;
public static boolean enableBeetroot = true;
public static boolean enableChorusFruit = true;
public static boolean enableGrassPath = true;
public static boolean enableSticksFromDeadBushes = true;
public static boolean enableBowRendering = true;
public static boolean enableTippedArrows = true;
public static boolean enableLingeringPotions = true;
public static boolean enableBurnableBlocks = true;
public static boolean enableFancySkulls = true;
public static boolean enableSkullDrop = true;
public static boolean enableDmgIndicator = true;
public static boolean enableTransparentAmour = true;
public static boolean enableUpdatedFoodValues = true;
public static boolean enableUpdatedHarvestLevels = true;
public static boolean enableVillagerZombies = true;
public static boolean enableStoneBrickRecipes = true;
public static boolean enableBabyGrowthBoost = true;
public static boolean enableVillagerTurnsIntoWitch = true;
public static boolean enableElytra = true;
public static boolean enableFrostWalker = true;
public static boolean enableMending = true;
public static boolean enableBrewingStands = true;
public static boolean enableDragonRespawn = true;
public static boolean enableColorfulBeacons = true;
public static boolean enablePlayerSkinOverlay = true;
public static boolean enableShearableGolems = true;
public static boolean enableShearableCobwebs = true;
public static boolean enableConcrete = true;
public static boolean enableShulkerStorage = true;
public static int maxStonesPerCluster = 16;
public static boolean isTinkersConstructLoaded = false;
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
ConfigurationHandler.INSTANCE.init(new File(event.getModConfigurationDirectory().getAbsolutePath() + File.separator + ModReferences.MOD_ID + ".cfg"));
GameRegistry.registerWorldGenerator(new CWorldGen(), 0);
CBlocks.init();
CItems.init();
CEnchantments.init();
OceanTemple.makeMap();
NetworkRegistry.INSTANCE.registerGuiHandler(instance, proxy);
networkWrapper = NetworkRegistry.INSTANCE.newSimpleChannel(ModReferences.MOD_ID);
networkWrapper.registerMessage(ArmorStandInteractHandler.class, ArmorStandInteractMessage.class, 0, Side.SERVER);
networkWrapper.registerMessage(DamageParticlesHandler.class, DamageParticlesMessage.class, 1, Side.CLIENT);
networkWrapper.registerMessage(SetPlayerModelHandler.class, SetPlayerModelMessage.class, 2, Side.CLIENT);
}
@EventHandler
public void init(FMLInitializationEvent event) {
NetworkRegistry.INSTANCE.registerGuiHandler(instance, proxy);
CRecipes.init();
proxy.registerEvents();
proxy.registerEntities();
proxy.registerRenderers();
if (ModEntityList.hasEntitiesWithEggs()) {
ModEntityList.entity_egg = new ItemEntityEgg();
GameRegistry.registerItem(ModEntityList.entity_egg, "entity_egg");
OreDictionary.registerOre("mobEgg", ModEntityList.entity_egg);
}
isTinkersConstructLoaded = Loader.isModLoaded("TConstruct");
}
@EventHandler
public void postInit(FMLPostInitializationEvent event) {
Items.blaze_rod.setFull3D();
Blocks.trapped_chest.setCreativeTab(CreativeTabs.tabRedstone);
if (enableUpdatedFoodValues) {
setFinalField(ItemFood.class, Items.carrot, 3, "healAmount", "field_77853_b");
setFinalField(ItemFood.class, Items.baked_potato, 5, "healAmount", "field_77853_b");
}
if (enableUpdatedHarvestLevels) {
Blocks.packed_ice.setHarvestLevel("pickaxe", 0);
Blocks.ladder.setHarvestLevel("axe", 0);
Blocks.melon_block.setHarvestLevel("axe", 0);
}
}
@EventHandler
public void processIMCRequests(IMCEvent event) {
for (IMCMessage message : event.getMessages())
if (message.key.equals("register-brewing-fuel")) {
NBTTagCompound nbt = message.getNBTValue();
ItemStack stack = ItemStack.loadItemStackFromNBT(nbt.getCompoundTag("Fuel"));
int brews = nbt.getInteger("Brews");
BrewingFuelRegistry.registerFuel(stack, brews);
}
}
@EventHandler
public void serverStarting(FMLServerStartingEvent event) {
if (CyancraftMod.enablePlayerSkinOverlay)
event.registerServerCommand(new SetPlayerModelCommand());
}
private void setFinalField(Class<?> cls, Object obj, Object newValue, String... fieldNames) {
try {
Field field = ReflectionHelper.findField(cls, fieldNames);
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(obj, newValue);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| gpl-3.0 |
echosun1996/IPv6SecurityProject | workspace/Android/Android-iBeacon-Demo-master/iBeacon-Demo/android-ibeacon-reference/src/com/radiusnetworks/ibeaconreference/MeterView.java | 12621 | package com.radiusnetworks.ibeaconreference;
/**
* Created by ºú×Ó on 2017/4/26.
*/
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
/**
* Created by xuekai on 2016/10/26.
*/
public class MeterView extends View {
private String color_outcircle = "#DEDEDE";
private String color_bg_outcircle = "#2690F8";
private String color_bg_incircle = "#58ADE4";
private String color_progress = "#87CEEB";
private String color_smart_circle = "#C2B9B0";
private String color_indicator_left = "#E1DCD6";
private String color_indicator_right = "#F4EFE9";
/**
* µ±Ç°½ø¶È
*/
private int progress = 0;
private String category = "";
private String unit = "";
/**
* Òª»µÄÄÚÈݵÄʵ¼Ê¿í¶È
*/
private int contentWidth;
/**
* viewµÄʵ¼Ê¿í¶È
*/
private int viewWidth;
/**
* viewµÄʵ¼Ê¸ß¶È
*/
private int viewHeight;
/**
* Íâ»·ÏߵĿí¶È
*/
private int outCircleWidth = 1;
/**
* Íâ»·µÄ°ë¾¶
*/
private int outCircleRadius = 0;
/**
* ÄÚ»·µÄ°ë¾¶
*/
private int inCircleRedius = 0;
/**
* ÄÚ»·ÓëÍâ»·µÄ¾àÀë
*/
private int outAndInDistance = 0;
/**
* ÄÚ»·µÄ¿í¶È
*/
private int inCircleWidth = 0;
/**
* ¿Ì¶ÈÅ̾àÀëËüÍâÃæµÄÔ²µÄ¾àÀë
*/
private int dialOutCircleDistance = 0;
/**
* ÄÚÈÝÖÐÐĵÄ×ø±ê
*/
private int[] centerPoint = new int[2];
/**
* ¿Ì¶ÈÏßµÄÊýÁ¿
*/
private int dialCount = 0;
/**
* ÿ¸ô¼¸´Î³öÏÖÒ»¸ö³¤Ïß
*/
private int dialPer = 0;
/**
* ³¤Ïߵij¤¶È
*/
private int dialLongLength = 0;
/**
* ¶ÌÏߵij¤¶È
*/
private int dialShortLength = 0;
/**
* ¿Ì¶ÈÏß¾àÀëÔ²ÐÄ×îÔ¶µÄ¾àÀë
*/
private int dialRadius = 0;
/**
* Ô²»¡¿ªÊ¼µÄ½Ç¶È
*/
private int startAngle = 0;
/**
* Ô²»¡»®¹ýµÄ½Ç¶È
*/
private int allAngle = 0;
private Paint mPaint;
/**
* ¿Ì¶ÈÅÌÉÏÊý×ÖµÄÊýÁ¿
*/
private int figureCount = 6;
public MeterView(Context context) {
this(context, null);
}
public MeterView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MeterView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setAntiAlias(true);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
initValues();
}
/**
* ³õʼ»¯³ß´ç
*/
private void initValues() {
viewWidth = getMeasuredWidth();
viewHeight = getMeasuredHeight();
contentWidth = viewWidth > viewHeight ? viewHeight : viewWidth;
outCircleRadius = contentWidth / 2 - outCircleWidth;
outAndInDistance = (int) (contentWidth / 26.5);
inCircleWidth = (int) (contentWidth / 18.7);
centerPoint[0] = viewWidth / 2;
centerPoint[1] = viewHeight / 2;
inCircleRedius = outCircleRadius - outAndInDistance - inCircleWidth / 2;
startAngle = 150;
allAngle = 240;
dialOutCircleDistance = inCircleWidth;
dialCount = 50;
dialPer = 5;
dialLongLength = (int) (dialOutCircleDistance / 1.2);
dialShortLength = (int) (dialLongLength / 1.8);
dialRadius = inCircleRedius - dialOutCircleDistance;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawStatic(canvas);
drawDynamic(canvas);
}
/**
* »æÖƾ²Ì¬µÄ²¿·Ö
*
* @param canvas
*/
private void drawStatic(Canvas canvas) {
drawOutCircle(canvas);
drawCircleWithRound(startAngle, allAngle, inCircleWidth, inCircleRedius, color_outcircle, canvas);
drawDial(startAngle, allAngle, dialCount, dialPer, dialLongLength, dialShortLength, dialRadius, canvas);
drawBackGround(canvas);
drawFigure(canvas, figureCount);
}
private void drawFigure(Canvas canvas, int count) {
int figure = 0;
int angle;
for (int i = 0; i < count; i++) {
figure = (int) (100 / (1f * count - 1) * i);
angle = (int) ((allAngle) / ((count - 1) * 1f) * i) + startAngle;
int[] pointFromAngleAndRadius = getPointFromAngleAndRadius(angle, dialRadius - dialLongLength * 2);
mPaint.setTextSize(15);
mPaint.setTextAlign(Paint.Align.CENTER);
canvas.save();
canvas.rotate(angle + 90, pointFromAngleAndRadius[0], pointFromAngleAndRadius[1]);
canvas.drawText(figure + unit, pointFromAngleAndRadius[0], pointFromAngleAndRadius[1], mPaint);
canvas.restore();
}
}
/**
* »Äڲ㱳¾°
*
* @param canvas
*/
private void drawBackGround(Canvas canvas) {
mPaint.setColor(Color.parseColor(color_bg_outcircle));
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(outCircleRadius / 3 / 2);
canvas.drawCircle(centerPoint[0], centerPoint[1], outCircleRadius / 3, mPaint);
mPaint.setColor(Color.parseColor(color_bg_incircle));
mPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(centerPoint[0], centerPoint[1], (outCircleRadius / 3f / 2), mPaint);
}
/**
* »¿Ì¶ÈÅÌ
*
* @param startAngle ¿ªÊ¼»µÄ½Ç¶È
* @param allAngle ×ܹ²»®¹ýµÄ½Ç¶È
* @param dialCount ×ܹ²µÄÏßµÄÊýÁ¿
* @param per ÿ¸ô¼¸¸ö³öÏÖÒ»´Î³¤Ïß
* @param longLength ³¤ÏÉÅ®µÄ³¤¶È
* @param shortLength ¶ÌÏߵij¤¶È
* @param radius ¾àÀëÔ²ÐÄ×îÔ¶µÄµØ·½µÄ°ë¾¶
*/
private void drawDial(int startAngle, int allAngle, int dialCount, int per, int longLength, int shortLength, int radius, Canvas canvas) {
int length;
int angle;
for (int i = 0; i <= dialCount; i++) {
angle = (int) ((allAngle) / (dialCount * 1f) * i) + startAngle;
if (i % 5 == 0) {
length = longLength;
} else {
length = shortLength;
}
drawSingleDial(angle, length, radius, canvas);
}
}
/**
* »¿Ì¶ÈÖеÄÒ»ÌõÏß
*
* @param angle Ëù´¦µÄ½Ç¶È
* @param length Ïߵij¤¶È
* @param radius ¾àÀëÔ²ÐÄ×îÔ¶µÄµØ·½µÄ°ë¾¶
*/
private void drawSingleDial(int angle, int length, int radius, Canvas canvas) {
int[] startP = getPointFromAngleAndRadius(angle, radius);
int[] endP = getPointFromAngleAndRadius(angle, radius - length);
canvas.drawLine(startP[0], startP[1], endP[0], endP[1], mPaint);
}
/**
* »×îÍâ²ãµÄÔ²
*
* @param canvas
*/
private void drawOutCircle(Canvas canvas) {
mPaint.setStrokeWidth(outCircleWidth);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.parseColor(color_outcircle));
canvas.drawCircle(centerPoint[0], centerPoint[1], outCircleRadius, mPaint);
}
/**
* »æÖƶ¯Ì¬µÄ²¿·Ö
*
* @param canvas
*/
private void drawDynamic(Canvas canvas) {
drawProgress(progress, canvas);
drawIndicator(progress, canvas);
drawCurrentProgressTv(progress, canvas);
}
/**
* »æÖƵ±Ç°½ø¶ÈÊÇÎÄ×Ö
*
* @param progress
* @param canvas
*/
private void drawCurrentProgressTv(int progress, Canvas canvas) {
mPaint.setTextSize(25);
mPaint.setColor(Color.BLACK);
mPaint.setTextAlign(Paint.Align.CENTER);
Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
float baseLine1 = centerPoint[1] + (outCircleRadius / 20f * 11 - fontMetrics.top - fontMetrics.bottom);
canvas.drawText("µ±Ç°"+this.category+progress+unit, centerPoint[0], baseLine1, mPaint);
}
/**
* »Ö¸ÕëÒÔ¼°ËûµÄ±³¾°
*
* @param progress
* @param canvas
*/
private void drawIndicator(int progress, Canvas canvas) {
drawPointer(canvas);
drawIndicatorBg(canvas);
}
/**
* Ö¸ÕëµÄ×îÔ¶´¦µÄ°ë¾¶ºÍ¿Ì¶ÈÏßµÄÒ»Ñù
*/
private void drawPointer(Canvas canvas) {
RectF rectF = new RectF(centerPoint[0] - (int) (outCircleRadius / 3f / 2 / 2),
centerPoint[1] - (int) (outCircleRadius / 3f / 2 / 2), centerPoint[0] + (int) (outCircleRadius / 3f / 2 / 2), centerPoint[1] + (int) (outCircleRadius / 3f / 2 / 2));
int angle = (int) ((allAngle) / (100 * 1f) * progress) + startAngle;
//Ö¸ÕëµÄ¶¨µã×ø±ê
int[] peakPoint = getPointFromAngleAndRadius(angle, dialRadius);
//¶¥µã³¯ÉÏ£¬×ó²àµÄµ×²¿µãµÄ×ø±ê
int[] bottomLeft = getPointFromAngleAndRadius(angle - 90, (int) (outCircleRadius / 3f / 2 / 2));
//¶¥µã³¯ÉÏ£¬ÓÒ²àµÄµ×²¿µãµÄ×ø±ê
int[] bottomRight = getPointFromAngleAndRadius(angle + 90, (int) (outCircleRadius / 3f / 2 / 2));
Path path = new Path();
mPaint.setColor(Color.parseColor(color_indicator_left));
path.moveTo(centerPoint[0], centerPoint[1]);
path.lineTo(peakPoint[0], peakPoint[1]);
path.lineTo(bottomLeft[0], bottomLeft[1]);
path.close();
canvas.drawPath(path, mPaint);
canvas.drawArc(rectF, angle - 180, 100, true, mPaint);
Log.e("InstrumentView", "drawPointer" + angle);
mPaint.setColor(Color.parseColor(color_indicator_right));
path.reset();
path.moveTo(centerPoint[0], centerPoint[1]);
path.lineTo(peakPoint[0], peakPoint[1]);
path.lineTo(bottomRight[0], bottomRight[1]);
path.close();
canvas.drawPath(path, mPaint);
canvas.drawArc(rectF, angle + 80, 100, true, mPaint);
}
private void drawIndicatorBg(Canvas canvas) {
mPaint.setColor(Color.parseColor(color_smart_circle));
mPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(centerPoint[0], centerPoint[1], (outCircleRadius / 3f / 2 / 4), mPaint);
}
/**
* ¸ù¾Ý½ø¶È»½ø¶ÈÌõ
*
* @param progress ×î´ó½ø¶ÈΪ100.×îСΪ0
*/
private void drawProgress(int progress, Canvas canvas) {
float ratio = progress / 100f;
int angle = (int) (allAngle * ratio);
drawCircleWithRound(startAngle, angle, inCircleWidth, inCircleRedius, color_progress, canvas);
}
public int getProgress() {
return progress;
}
public void setProgress(int progress,String category,String unit) {
this.progress = progress;
this.category = category;
this.unit = unit;
invalidate();
}
/**
* »Ò»¸öÁ½¶ËΪԲ»¡µÄÔ²ÐÎÇúÏß
*
* @param startAngle ÇúÏß¿ªÊ¼µÄ½Ç¶È
* @param allAngle ÇúÏß×ß¹ýµÄ½Ç¶È
* @param radius ÇúÏߵİ뾶
* @param width ÇúÏߵĺñ¶È
*/
private void drawCircleWithRound(int startAngle, int allAngle, int width, int radius, String color, Canvas canvas) {
mPaint.setStrokeWidth(width);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.parseColor(color));
RectF rectF = new RectF(centerPoint[0] - radius, centerPoint[1] - radius, centerPoint[0] + radius, centerPoint[1] + radius);
canvas.drawArc(rectF, startAngle, allAngle, false, mPaint);
drawArcRoune(radius, startAngle, width, canvas);
drawArcRoune(radius, startAngle + allAngle, width, canvas);
}
/**
* »æÖÆÔ²»¡Á½¶ËµÄÔ²
*
* @param radius Ô²»¡µÄ°ë¾¶
* @param angle Ëù´¦ÓÚÔ²»¡µÄ¶àÉٶȵÄλÖÃ
* @param width Ô²»¡µÄ¿í¶È
*/
private void drawArcRoune(int radius, int angle, int width, Canvas canvas) {
int[] point = getPointFromAngleAndRadius(angle, radius);
mPaint.setStrokeWidth(0);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(point[0], point[1], width / 2, mPaint);
}
/**
* ¸ù¾Ý½Ç¶ÈºÍ°ë¾¶£¬ÇóÒ»¸öµãµÄ×ø±ê
*
* @param angle
* @param radius
* @return
*/
private int[] getPointFromAngleAndRadius(int angle, int radius) {
double x = radius * Math.cos(angle * Math.PI / 180) + centerPoint[0];
double y = radius * Math.sin(angle * Math.PI / 180) + centerPoint[1];
return new int[]{(int) x, (int) y};
}
} | gpl-3.0 |
SilverHelmet/KnowSim | src/edu/pku/dlib/models/datastructure/ColtSparseVector.java | 2223 | package edu.pku.dlib.models.datastructure;
import cern.colt.list.DoubleArrayList;
import cern.colt.list.IntArrayList;
import cern.colt.matrix.impl.SparseDoubleMatrix1D;
public class ColtSparseVector extends SparseDoubleMatrix1D {
// private static final long serialVersionUID = 1L;
/**
*
*/
private static final long serialVersionUID = 8154426281608727474L;
private double normValue;
// protected JavaIntDoubleHashMap elements;
// protected TroveIntDoubleHashMap elements;
public ColtSparseVector(double[] values) {
this(values.length);
assign(values);
}
public ColtSparseVector(int size) {
this(size,size/1000,0.2,0.5);
}
public ColtSparseVector(int size, int initialCapacity, double minLoadFactor, double maxLoadFactor) {
super(size, initialCapacity, minLoadFactor, maxLoadFactor);
// this.elements = new JavaIntDoubleHashMap();
// this.elements = new TroveIntDoubleHashMap();
}
public double getQuick(int index) {
return elements.get(index);
}
public void setQuick(int index, double value) {
if (value == 0)
this.elements.removeKey(index);
else
this.elements.put(index, value);
}
public void getNonZeros(IntArrayList indexList, DoubleArrayList valueList) {
boolean fillIndexList = indexList != null;
boolean fillValueList = valueList != null;
if (fillIndexList)
indexList.clear();
else {
System.out.println("Wrong use");
return;
}
if (fillValueList)
valueList.clear();
else {
System.out.println("Wrong use");
return;
}
int[] index = elements.keys().elements();
double[] value = elements.values().elements();
indexList.elements(index);
valueList.elements(value);
// for (int i = 0; i < index.size(); ++i) {
// indexList.add(index.get(i));
// valueList.add(value.get(i));
// }
// int s = size;
// for (int i=0; i < s; i++) {
// double value = getQuick(i);
// if (value != 0) {
// if (fillIndexList) indexList.add(i);
// if (fillValueList) valueList.add(value);
// }
// }
}
public void setNormValue(double value) {
this.normValue = value;
}
public double getNormValue () {
return this.normValue;
}
}
| gpl-3.0 |
stephaniefrancois/car-showroom | src/main/java/core/deal/validation/InMemoryPaymentOptionsStepValidationRulesProvider.java | 965 | package core.deal.validation;
import core.deal.model.PaymentOptions;
import core.validation.RuleFor;
import core.validation.ValidationRulesProvider;
import java.util.Arrays;
public final class InMemoryPaymentOptionsStepValidationRulesProvider
extends ValidationRulesProvider<PaymentOptions> {
public InMemoryPaymentOptionsStepValidationRulesProvider() {
addRule(RuleFor.mandatory("Deposit", PaymentOptions::getDeposit));
addRule(RuleFor.minValue(0, "Deposit", PaymentOptions::getDeposit));
addRule(RuleFor.maxValue(1000, "Deposit", PaymentOptions::getDeposit));
addRule(RuleFor.mandatory("First Payment", PaymentOptions::getFirstPaymentDay));
addRule(RuleFor.mandatory("Duration In Months", PaymentOptions::getDurationInMonths));
addRule(RuleFor.allowSetOfValues("Duration In Months",
Arrays.asList("12", "24"),
d -> String.valueOf(d.getDurationInMonths())));
}
}
| gpl-3.0 |
nickapos/myBill | src/main/java/gr/oncrete/nick/mybill/UserInterface/ImportBankStatementTableModel.java | 2313 | /*
* Copyright (C) 2011 nickapos
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package gr.oncrete.nick.mybill.UserInterface;
/**
*
* @author nickapos
*/
/**
* table model class used for the exchange rate tables
*
*
*/
class ImportBankStatementTableModel extends javax.swing.table.DefaultTableModel {
//designate one column to contain booleans
int booleanColumn = 8;
public ImportBankStatementTableModel(String[][] d, String[] cName) {
super(d, cName);
}
public ImportBankStatementTableModel(Object[][] d, String[] cName) {
super(d, cName);
}
public ImportBankStatementTableModel(Object[][] d, String[] cName, int boolColumn) {
super(d, cName);
booleanColumn = boolColumn;
}
@Override
public Class getColumnClass(int c) {
if (c == booleanColumn) {
return java.lang.Boolean.class;
} else {
return java.lang.String.class;
}
}
private boolean[] getcanEditArr(int sizeOfArr, int editPos) {
boolean[] canEdit = new boolean[sizeOfArr];
for (int i = 0; i < sizeOfArr; i++) {
if (i == editPos && editPos < sizeOfArr && editPos >= 0) {
canEdit[i] = true;
} else {
canEdit[i] = false;
}
}
return canEdit;
}
/**
* by overriding this method we can set the table cells editable or not
*
* @param row
* @param column
* @return
*/
@Override
public boolean isCellEditable(int row, int column) {
boolean[] canEdit=this.getcanEditArr(booleanColumn+1, booleanColumn);
return canEdit[column];
}
}
| gpl-3.0 |
466152112/HappyResearch | happyresearch/src/main/java/happy/research/utils/TrustUtils.java | 4992 | package happy.research.utils;
import happy.research.cf.Dataset;
import happy.research.cf.Rating;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.math.FunctionEvaluationException;
import org.apache.commons.math.analysis.UnivariateRealFunction;
import org.apache.commons.math.analysis.integration.TrapezoidIntegrator;
public class TrustUtils
{
/**
* Calculate the confidence between positive feedbacks and negative feedbacks.<br/>
* This method is implemented right: according to paper <i>Formal Trust Model for Multiagent Systems</i>,
* <ul>
* <li>f(0, 4)=0.54</li>
* <li>f(1, 3)=0.35</li>
* <li>f(2, 2)=0.29</li>
* <li>f(3, 1)=0.35</li>
* <li>f(6, 2)=0.46</li>
* <li>f(69, 29)=0.75</li>
* <li>f(500, 100) = 0.87</li>
* </ul>
*
* @param r
* #positive feedbacks
* @param s
* #negative feedbacks
* @return <b>confidence</b> between positive feedbacks and negative feedbacks
* @throws Exception
*/
public static double confidence(final double r, final double s) throws Exception
{
TrapezoidIntegrator integrator = new TrapezoidIntegrator();
final double denominator = denominator(r, s);
UnivariateRealFunction f = new UnivariateRealFunction() {
public double value(double x) throws FunctionEvaluationException
{
double result = Math.pow(x, r) * Math.pow(1 - x, s) - denominator;
return Math.abs(result);
}
};
return 0.5 * integrator.integrate(f, 0.0, 1.0) / denominator;
}
/**
* Profile-level trust, refers to the paper <em>Trust in Recommender Systems</em><br/>
* Note that sets <em>a</em> and <em>b</em> are not ratings of the co-rated items, but ratings of all rated items by
* each user.
*
* @param as
* all ratings of the active user A
* @param bs
* all ratings of the other user
* @param episilon
* acceptable error/distance between two ratings
* @return List<Rating> correctRatings
*/
public static List<Rating> profileTrust(List<Rating> as, List<Rating> bs, double episilon)
{
List<Rating> corrects = new ArrayList<>();
for (Rating ar : as)
{
String itemId = ar.getItemId();
for (Rating br : bs)
{
if (itemId.equals(br.getItemId()))
{
double ai = ar.getRating();
double bi = br.getRating();
double error = Math.abs(ai - bi);
if (error < episilon) corrects.add(br);
break;
}
}
}
return corrects;
}
/**
* K-nearest recommender trust, refers to the paper <em>Trust-Based Collaborative Filtering</em><br/>
* Note that sets <em>a</em> and <em>b</em> are not ratings of the co-rated items, but ratings of all rated items by
* each user.
*
* @param as
* all ratings of the active user A
* @param bs
* all ratings of the other user B
* @return B's trust score regarding to user A
*/
public static double kNRTrust(Map<String, Rating> as, Map<String, Rating> bs)
{
return kNRTrust(as, bs, null);
}
/**
* K-nearest recommender trust, refers to the paper <em>Trust-Based Collaborative Filtering</em><br/>
* Note that sets <em>a</em> and <em>b</em> are not ratings of the co-rated items, but ratings of all rated items by
* each user.
*
* @param as
* {item, rating} all ratings of the active user A
* @param bs
* {item, rating} all ratings of the other user B
* @param testRating
* A's test rating, needs to be excluded from train sets (learn B's trustworthiness)
* @return B's trust score regarding to user A
*/
public static double kNRTrust(Map<String, Rating> as, Map<String, Rating> bs, Rating testRating)
{
double sum = 0.0;
int count = 0;
for (Rating ar : as.values())
{
if (ar == testRating) continue;
String itemId = ar.getItemId();
count++;
double trusti = 0;
if (bs.containsKey(itemId))
{
Rating br = bs.get(itemId);
trusti = 1 - Math.abs(ar.getRating() - br.getRating()) / Dataset.maxScale;
}
sum += trusti;
}
return sum / count;
}
public static double kNRTrust(List<Double> as, List<Double> bs)
{
double sum = 0.0;
int count = 0;
for (int i = 0; i < as.size(); i++)
{
count++;
sum += 1 - Math.abs(as.get(i) - bs.get(i)) / Dataset.maxScale;
}
return sum / count;
}
private static double denominator(final double r, final double s) throws Exception
{
TrapezoidIntegrator integrator = new TrapezoidIntegrator();
UnivariateRealFunction f = new UnivariateRealFunction() {
public double value(double x) throws FunctionEvaluationException
{
return Math.pow(x, r) * Math.pow(1 - x, s);
}
};
return integrator.integrate(f, 0.0, 1.0);
}
public static void main(String[] args) throws Exception
{
System.out.println(confidence(0, 1));
}
}
| gpl-3.0 |
AntonioGabrielAndrade/LIRE-Lab | src/main/java/net/lirelab/search/SetImageToGridClickHandler.java | 1385 | /*
* This file is part of the LIRE-Lab project, a desktop image retrieval tool
* made on top of the LIRE image retrieval Java library.
* Copyright (C) 2017 Antonio Gabriel Pereira de Andrade
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.lirelab.search;
import net.lirelab.collection.Image;
import net.lirelab.custom.collection_grid.ImageClickHandler;
import net.lirelab.custom.single_image_grid.SingleImageGrid;
import javafx.scene.input.MouseEvent;
class SetImageToGridClickHandler implements ImageClickHandler {
private final SingleImageGrid grid;
public SetImageToGridClickHandler(SingleImageGrid grid) {
this.grid = grid;
}
@Override
public void handle(Image image, MouseEvent event) {
grid.setImage(image);
}
}
| gpl-3.0 |
freerouting/freerouting | src/main/java/app/freerouting/board/ForcedViaAlgo.java | 11803 | package app.freerouting.board;
import app.freerouting.geometry.planar.ConvexShape;
import app.freerouting.geometry.planar.IntPoint;
import app.freerouting.geometry.planar.Point;
import app.freerouting.geometry.planar.FloatPoint;
import app.freerouting.geometry.planar.Shape;
import app.freerouting.geometry.planar.TileShape;
import app.freerouting.geometry.planar.Simplex;
import app.freerouting.geometry.planar.IntBox;
import app.freerouting.geometry.planar.Circle;
import app.freerouting.geometry.planar.Vector;
import app.freerouting.geometry.planar.Limits;
import app.freerouting.rules.ViaInfo;
import app.freerouting.library.Padstack;
/**
* Class with static functions for checking and inserting forced vias.
*/
public class ForcedViaAlgo
{
/**
* Checks, if a Via is possible at the input layer after evtl. shoving aside obstacle traces.
* p_room_shape is used for calculating the from_side.
*/
public static ForcedPadAlgo.CheckDrillResult check_layer(double p_via_radius, int p_cl_class, boolean p_attach_smd_allowed,
TileShape p_room_shape, Point p_location, int p_layer,
int[] p_net_no_arr, int p_max_recursion_depth,
int p_max_via_recursion_depth, RoutingBoard p_board)
{
if (p_via_radius <= 0)
{
return ForcedPadAlgo.CheckDrillResult.DRILLABLE;
}
ForcedPadAlgo forced_pad_algo = new ForcedPadAlgo(p_board);
if (!(p_location instanceof IntPoint))
{
return ForcedPadAlgo.CheckDrillResult.NOT_DRILLABLE;
}
ConvexShape via_shape = new Circle((IntPoint) p_location, (int) Math.ceil(p_via_radius));
double check_radius =
p_via_radius + 0.5 * p_board.clearance_value(p_cl_class, p_cl_class, p_layer)
+ p_board.get_min_trace_half_width();
TileShape tile_shape;
boolean is_90_degree;
if (p_board.rules.get_trace_angle_restriction() == AngleRestriction.NINETY_DEGREE)
{
tile_shape = via_shape.bounding_box();
is_90_degree = true;
}
else
{
tile_shape = via_shape.bounding_octagon();
is_90_degree = false;
}
CalcFromSide from_side = calculate_from_side(p_location.to_float(), tile_shape, p_room_shape.to_Simplex(), check_radius, is_90_degree);
if (from_side == null)
{
return ForcedPadAlgo.CheckDrillResult.NOT_DRILLABLE;
}
ForcedPadAlgo.CheckDrillResult result = forced_pad_algo.check_forced_pad(tile_shape, from_side, p_layer, p_net_no_arr,
p_cl_class, p_attach_smd_allowed, null, p_max_recursion_depth, p_max_via_recursion_depth, false, null);
return result;
}
/**
* Checks, if a Via is possible with the input parameter after evtl. shoving aside obstacle traces.
*/
public static boolean check(ViaInfo p_via_info, Point p_location, int[] p_net_no_arr, int p_max_recursion_depth,
int p_max_via_recursion_depth, RoutingBoard p_board)
{
Vector translate_vector = p_location.difference_by(Point.ZERO);
int calc_from_side_offset = p_board.get_min_trace_half_width();
ForcedPadAlgo forced_pad_algo = new ForcedPadAlgo(p_board);
Padstack via_padstack = p_via_info.get_padstack();
for (int i = via_padstack.from_layer(); i <= via_padstack.to_layer(); ++i)
{
Shape curr_pad_shape = via_padstack.get_shape(i);
if (curr_pad_shape == null)
{
continue;
}
curr_pad_shape = (Shape) curr_pad_shape.translate_by(translate_vector);
TileShape tile_shape;
if (p_board.rules.get_trace_angle_restriction() == AngleRestriction.NINETY_DEGREE)
{
tile_shape = curr_pad_shape.bounding_box();
}
else
{
tile_shape = curr_pad_shape.bounding_octagon();
}
CalcFromSide from_side
= forced_pad_algo.calc_from_side(tile_shape, p_location, i, calc_from_side_offset,p_via_info.get_clearance_class());
if (forced_pad_algo.check_forced_pad(tile_shape, from_side, i, p_net_no_arr, p_via_info.get_clearance_class(),
p_via_info.attach_smd_allowed(), null, p_max_recursion_depth, p_max_via_recursion_depth, false, null)
== ForcedPadAlgo.CheckDrillResult.NOT_DRILLABLE)
{
p_board.set_shove_failing_layer(i);
return false;
}
}
return true;
}
/**
* Shoves aside traces, so that a via with the input parameters can be
* inserted without clearance violations. If the shove failed, the database may be damaged, so that an undo
* becomes necessesary.
* p_trace_clearance_class_no and p_trace_pen_halfwidth_arr is provided to make space for starting a trace
* in case the trace width is bigger than the via shape.
* Returns false, if the forced via failed.
*/
public static boolean insert( ViaInfo p_via_info, Point p_location, int[] p_net_no_arr,
int p_trace_clearance_class_no, int [] p_trace_pen_halfwidth_arr, int p_max_recursion_depth,
int p_max_via_recursion_depth, RoutingBoard p_board)
{
Vector translate_vector = p_location.difference_by(Point.ZERO);
int calc_from_side_offset = p_board.get_min_trace_half_width();
ForcedPadAlgo forced_pad_algo = new ForcedPadAlgo(p_board);
Padstack via_padstack = p_via_info.get_padstack();
for (int i = via_padstack.from_layer(); i <= via_padstack.to_layer(); ++i)
{
Shape curr_pad_shape = via_padstack.get_shape(i);
if (curr_pad_shape == null)
{
continue;
}
curr_pad_shape = (Shape) curr_pad_shape.translate_by(translate_vector);
TileShape tile_shape;
Circle start_trace_circle;
if (p_trace_pen_halfwidth_arr[i] > 0 && p_location instanceof IntPoint)
{
start_trace_circle = new Circle((IntPoint) p_location, p_trace_pen_halfwidth_arr[i]);
}
else
{
start_trace_circle = null;
}
TileShape start_trace_shape = null;
if (p_board.rules.get_trace_angle_restriction() == AngleRestriction.NINETY_DEGREE)
{
tile_shape = curr_pad_shape.bounding_box();
if (start_trace_circle != null)
{
start_trace_shape = start_trace_circle.bounding_box();
}
}
else
{
tile_shape = curr_pad_shape.bounding_octagon();
if (start_trace_circle != null)
{
start_trace_shape = start_trace_circle.bounding_octagon();
}
}
CalcFromSide from_side
= forced_pad_algo.calc_from_side(tile_shape, p_location, i, calc_from_side_offset,p_via_info.get_clearance_class());
if (!forced_pad_algo.forced_pad(tile_shape, from_side, i, p_net_no_arr, p_via_info.get_clearance_class(),
p_via_info.attach_smd_allowed(), null, p_max_recursion_depth, p_max_via_recursion_depth))
{
p_board.set_shove_failing_layer(i);
return false;
}
if (start_trace_shape != null)
{
// necessesary in case strart_trace_shape is bigger than tile_shape
if (!forced_pad_algo.forced_pad(start_trace_shape, from_side, i, p_net_no_arr, p_trace_clearance_class_no,
true, null, p_max_recursion_depth, p_max_via_recursion_depth))
{
p_board.set_shove_failing_layer(i);
return false;
}
}
}
p_board.insert_via(via_padstack, p_location, p_net_no_arr, p_via_info.get_clearance_class(),
FixedState.UNFIXED, p_via_info.attach_smd_allowed());
return true;
}
static private CalcFromSide calculate_from_side(FloatPoint p_via_location, TileShape p_via_shape, Simplex p_room_shape, double p_dist, boolean is_90_degree)
{
IntBox via_box = p_via_shape.bounding_box();
for (int i = 0; i < 4; ++i)
{
FloatPoint check_point;
double border_x;
double border_y;
if (i == 0)
{
check_point = new FloatPoint(p_via_location.x, p_via_location.y - p_dist);
border_x = p_via_location.x;
border_y = via_box.ll.y;
}
else if (i == 1)
{
check_point = new FloatPoint(p_via_location.x + p_dist, p_via_location.y);
border_x = via_box.ur.x;
border_y = p_via_location.y;
}
else if (i == 2)
{
check_point = new FloatPoint(p_via_location.x, p_via_location.y + p_dist);
border_x = p_via_location.x;
border_y = via_box.ur.y;
}
else // i == 3
{
check_point = new FloatPoint(p_via_location.x - p_dist, p_via_location.y);
border_x = via_box.ll.x;
border_y = p_via_location.y;
}
if (p_room_shape.contains(check_point))
{
int from_side_no;
if (is_90_degree)
{
from_side_no = i;
}
else
{
from_side_no = 2 * i;
}
FloatPoint curr_border_point = new FloatPoint(border_x, border_y);
return new CalcFromSide(from_side_no, curr_border_point);
}
}
if (is_90_degree)
{
return null;
}
// try the diagonal drections
double dist = p_dist / Limits.sqrt2;
double border_dist = via_box.max_width() / (2 * Limits.sqrt2);
for (int i = 0; i < 4; ++i)
{
FloatPoint check_point;
double border_x;
double border_y;
if (i == 0)
{
check_point = new FloatPoint(p_via_location.x + dist, p_via_location.y - dist);
border_x = p_via_location.x + border_dist;
border_y = p_via_location.y - border_dist;
}
else if (i == 1)
{
check_point = new FloatPoint(p_via_location.x + dist, p_via_location.y + dist);
border_x = p_via_location.x + border_dist;
border_y = p_via_location.y + border_dist;
}
else if (i == 2)
{
check_point = new FloatPoint(p_via_location.x - dist, p_via_location.y + dist);
border_x = p_via_location.x - border_dist;
border_y = p_via_location.y + border_dist;
}
else // i == 3
{
check_point = new FloatPoint(p_via_location.x - dist, p_via_location.y - dist);
border_x = p_via_location.x - border_dist;
border_y = p_via_location.y - border_dist;
}
if (p_room_shape.contains(check_point))
{
int from_side_no = 2 * i + 1;
FloatPoint curr_border_point = new FloatPoint(border_x, border_y);
return new CalcFromSide(from_side_no, curr_border_point);
}
}
return null;
}
}
| gpl-3.0 |
printingin3d/sqljet | src/main/java/org/tmatesoft/sqljet/core/internal/fs/SqlJetFileSystem.java | 8076 | /**
* SqlJetFileSystem.java
* Copyright (C) 2008 TMate Software Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* For information on how to redistribute this software under
* the terms of a license other than GNU General Public License
* contact TMate Software at support@sqljet.com
*/
package org.tmatesoft.sqljet.core.internal.fs;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.EnumSet;
import java.util.Set;
import javax.annotation.Nonnull;
import org.tmatesoft.sqljet.core.SqlJetErrorCode;
import org.tmatesoft.sqljet.core.SqlJetException;
import org.tmatesoft.sqljet.core.internal.ISqlJetFile;
import org.tmatesoft.sqljet.core.internal.ISqlJetFileSystem;
import org.tmatesoft.sqljet.core.internal.SqlJetFileAccesPermission;
import org.tmatesoft.sqljet.core.internal.SqlJetFileOpenPermission;
import org.tmatesoft.sqljet.core.internal.SqlJetFileType;
import org.tmatesoft.sqljet.core.internal.fs.util.SqlJetFileUtil;
/**
* Default implementation of ISqlJetFileSystem.
*
*
* @author TMate Software Ltd.
* @author Sergey Scherbina (sergey.scherbina@gmail.com)
*
*/
public class SqlJetFileSystem implements ISqlJetFileSystem {
private static final String FS_NAME = SqlJetFileSystem.class.getCanonicalName();
/**
* Temporary files are named starting with this prefix followed by random
* alphanumeric characters, and no file extension. They are stored in the
* OS's standard temporary file directory, and are deleted prior to exit.
*
* If SqlJet is being embedded in another program, you may wish to change
* the prefix to reflect your program's name, so that if your program exits
* prematurely, old temporary files can be easily identified.
*
* TODO - specify a way to change SQLJET_TEMP_FILE_PREFIX ( e.g. may be
* system property name as SQLJET_TEMP_FILE_PREFIX ) .
*
* ********************************************************************
*
* Below some from SQLite comments:
*
* 2006-10-31: The default prefix used to be "sqlite_". But then Mcafee
* started using SQLite in their anti-virus product and it started putting
* files with the "sqlite" name in the c:/temp folder. This annoyed many
* windows users. Those users would then do a Google search for "sqlite",
* find the telephone numbers of the developers and call to wake them up at
* night and complain. For this reason, the default name prefix is changed
* to be "sqlite" spelled backwards. So the temp files are still identified,
* but anybody smart enough to figure out the code is also likely smart
* enough to know that calling the developer will not help get rid of the
* file.
*/
private static final String SQLJET_TEMP_FILE_PREFIX = "tejlqs_";
@Override
public String getName() {
return FS_NAME;
}
@SuppressWarnings("resource")
@Override
public @Nonnull ISqlJetFile open(final File path, @Nonnull SqlJetFileType type,
@Nonnull Set<SqlJetFileOpenPermission> permissions) throws SqlJetException {
boolean isExclusive = permissions.contains(SqlJetFileOpenPermission.EXCLUSIVE);
boolean isDelete = permissions.contains(SqlJetFileOpenPermission.DELETEONCLOSE);
boolean isCreate = permissions.contains(SqlJetFileOpenPermission.CREATE);
boolean isReadonly = permissions.contains(SqlJetFileOpenPermission.READONLY);
boolean isReadWrite = !isReadonly;
/*
* Check the following statements are true:
*
* (a) Exactly one of the READWRITE and READONLY flags must be set, and
* (b) if CREATE is set, then READWRITE must also be set, and (c) if
* EXCLUSIVE is set, then CREATE must also be set. (d) if DELETEONCLOSE
* is set, then CREATE must also be set.
*/
assert !isCreate || isReadWrite;
assert !isExclusive || isCreate;
assert !isDelete || isCreate;
/*
* The main DB, main journal, and master journal are never automatically
* deleted
*/
assert SqlJetFileType.MAIN_DB != type || !isDelete;
assert SqlJetFileType.MAIN_JOURNAL != type || !isDelete;
assert SqlJetFileType.MASTER_JOURNAL != type || !isDelete;
final @Nonnull File filePath;
if (null != path) {
try {
filePath = new File(path.getCanonicalPath());
} catch (IOException e) {
// TODO may through exception for missing file.
throw new SqlJetException(SqlJetErrorCode.CANTOPEN, e);
}
} else {
assert isDelete
&& !(isCreate && (SqlJetFileType.MASTER_JOURNAL == type || SqlJetFileType.MAIN_JOURNAL == type));
try {
filePath = getTempFile();
} catch (IOException e) {
throw new SqlJetException(SqlJetErrorCode.CANTOPEN, e);
}
}
if (!isReadWrite && !(filePath.isFile() && filePath.canRead())) {
throw new SqlJetException(SqlJetErrorCode.CANTOPEN);
}
String mode = "rw";
if (isReadonly && !isReadWrite && !isCreate && !isExclusive) {
mode = "r";
} else if (isReadWrite && !isExclusive && filePath.isFile() && !filePath.canWrite() && filePath.canRead()) {
// force opening as read only.
Set<SqlJetFileOpenPermission> ro = EnumSet.copyOf(permissions);
ro.remove(SqlJetFileOpenPermission.CREATE);
ro.add(SqlJetFileOpenPermission.READONLY);
return open(filePath, type, ro);
}
RandomAccessFile file = null;
try {
file = SqlJetFileUtil.openFile(filePath, mode);
} catch (FileNotFoundException e) {
if (isReadWrite && !isExclusive) {
/*
* Failed to open the file for read/write access. Try read-only.
*/
Set<SqlJetFileOpenPermission> ro = EnumSet.copyOf(permissions);
ro.remove(SqlJetFileOpenPermission.CREATE);
ro.add(SqlJetFileOpenPermission.READONLY);
return open(filePath, type, ro);
}
throw new SqlJetException(SqlJetErrorCode.CANTOPEN);
}
return type.noLock() ? new SqlJetNoLockFile(this, file, filePath, permissions)
: new SqlJetFile(this, file, filePath, permissions);
}
/**
* @return
* @throws IOException
*/
@Override
public @Nonnull File getTempFile() throws IOException {
return File.createTempFile(SQLJET_TEMP_FILE_PREFIX, null);
}
@Override
public boolean delete(File path, boolean sync) {
assert null != path;
return SqlJetFileUtil.deleteFile(path, sync);
}
@Override
public boolean access(File path, SqlJetFileAccesPermission permission) throws SqlJetException {
assert null != path;
assert null != permission;
switch (permission) {
case EXISTS:
return path.exists();
case READONLY:
return path.canRead() && !path.canWrite();
case READWRITE:
return path.canRead() && path.canWrite();
default:
throw new SqlJetException(SqlJetErrorCode.INTERNAL,
"Unhandled SqlJetFileAccesPermission value :" + permission.name());
}
}
@Override
public @Nonnull SqlJetMemJournal memJournalOpen() {
return new SqlJetMemJournal();
}
}
| gpl-3.0 |
akardapolov/ASH-Viewer | jfreechart-fse/src/main/java/org/jfree/data/time/TimePeriodValue.java | 5504 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* --------------------
* TimePeriodValue.java
* --------------------
* (C) Copyright 2003-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 22-Apr-2003 : Version 1 (DG);
* 03-Oct-2006 : Added null argument check to constructor (DG);
* 07-Apr-2008 : Added a toString() override for debugging (DG);
*
*/
package org.jfree.data.time;
import java.io.Serializable;
/**
* Represents a time period and an associated value.
*/
public class TimePeriodValue implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 3390443360845711275L;
/** The time period. */
private TimePeriod period;
/** The value associated with the time period. */
private Number value;
/**
* Constructs a new data item.
*
* @param period the time period (<code>null</code> not permitted).
* @param value the value associated with the time period.
*
* @throws IllegalArgumentException if <code>period</code> is
* <code>null</code>.
*/
public TimePeriodValue(TimePeriod period, Number value) {
if (period == null) {
throw new IllegalArgumentException("Null 'period' argument.");
}
this.period = period;
this.value = value;
}
/**
* Constructs a new data item.
*
* @param period the time period (<code>null</code> not permitted).
* @param value the value associated with the time period.
*
* @throws IllegalArgumentException if <code>period</code> is
* <code>null</code>.
*/
public TimePeriodValue(TimePeriod period, double value) {
this(period, new Double(value));
}
/**
* Returns the time period.
*
* @return The time period (never <code>null</code>).
*/
public TimePeriod getPeriod() {
return this.period;
}
/**
* Returns the value.
*
* @return The value (possibly <code>null</code>).
*
* @see #setValue(Number)
*/
public Number getValue() {
return this.value;
}
/**
* Sets the value for this data item.
*
* @param value the new value (<code>null</code> permitted).
*
* @see #getValue()
*/
public void setValue(Number value) {
this.value = value;
}
/**
* Tests this object for equality with the target object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof TimePeriodValue)) {
return false;
}
TimePeriodValue timePeriodValue = (TimePeriodValue) obj;
if (this.period != null ? !this.period.equals(timePeriodValue.period)
: timePeriodValue.period != null) {
return false;
}
if (this.value != null ? !this.value.equals(timePeriodValue.value)
: timePeriodValue.value != null) {
return false;
}
return true;
}
/**
* Returns a hash code value for the object.
*
* @return The hashcode
*/
@Override
public int hashCode() {
int result;
result = (this.period != null ? this.period.hashCode() : 0);
result = 29 * result + (this.value != null ? this.value.hashCode() : 0);
return result;
}
/**
* Clones the object.
* <P>
* Note: no need to clone the period or value since they are immutable
* classes.
*
* @return A clone.
*/
@Override
public Object clone() {
Object clone = null;
try {
clone = super.clone();
}
catch (CloneNotSupportedException e) { // won't get here...
e.printStackTrace();
}
return clone;
}
/**
* Returns a string representing this instance, primarily for use in
* debugging.
*
* @return A string.
*/
@Override
public String toString() {
return "TimePeriodValue[" + getPeriod() + "," + getValue() + "]";
}
}
| gpl-3.0 |
nalimleinad/BlockTrackR | src/main/java/com/Volition21/BlockTrackR/SQL/BTRGetRecords.java | 2113 | /**
BlockTrackR - Minecraft monitoring plugin designed to capture, index, and correlate real-time data in a searchable repository.
Copyright (C) 2015 - Damion (Volition21) Volition21@Hackion.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.Volition21.BlockTrackR.SQL;
import java.util.List;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.text.format.TextColors;
import com.Volition21.BlockTrackR.Utility.BTRDebugger;
public class BTRGetRecords {
BTRSQL BTRsql = new BTRSQL();
List<String> listresults;
public String[] results;
public void getRecords(String X, String Y, String Z, Player player) {
BTRDebugger.DLog("BTRGetRecords");
BTRDebugger.DLog("X: " + X);
BTRDebugger.DLog("Y: " + Y);
BTRDebugger.DLog("Z: " + Z);
listresults = BTRsql.getBlockRecord(X, Y, Z);
results = new String[listresults.size()];
results = listresults.toArray(results);
int length = results.length;
if (length == 0) {
player.sendMessage(Texts.of(TextColors.RED, "No Results"));
} else {
player.sendMessage(Texts.of(TextColors.DARK_AQUA, "BlockTrackR Results @ " + X + "," + Y + "," + Z));
player.sendMessage(Texts.of(TextColors.DARK_RED, "------------------------------"));
for (int i = 0; i < results.length; i++) {
player.sendMessage(Texts.of(TextColors.RED, results[i]));
}
player.sendMessage(Texts.of(TextColors.DARK_RED, "----------------------------"));
}
}
} | gpl-3.0 |
DennisWeyrauch/MetaLanguageParser | MetaLanguageParser/lang/java/unused/_field_set.java | 70 | $$scope$$ void set$$Name$$($$type$$ value) {
this.$$name$$ = value;
} | gpl-3.0 |
astrid/GenoViewer | GenoViewer/src/main/java/hu/astrid/utility/Splitter.java | 2067 | /*
* This file is part of GenoViewer.
*
* GenoViewer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GenoViewer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GenoViewer. If not, see <http://www.gnu.org/licenses/>.
*/
package hu.astrid.utility;
import hu.astrid.core.Color;
import hu.astrid.core.Nucleotide;
import hu.astrid.read.CsRead;
import hu.astrid.read.FastaRead;
import java.util.ArrayList;
import java.util.List;
/**
* Astrid Research Inc.
* Author: zsdoma
* Created: 2009.12.29.
*/
public class Splitter {
public List<List<Nucleotide>> split(FastaRead fastaRead,
int length) {
List<Nucleotide> nucleotides = fastaRead.getSequence();
List<List<Nucleotide>> result = new ArrayList<List<Nucleotide>>();
int count = 0;
List<Nucleotide> line = new ArrayList<Nucleotide>();
for (Nucleotide nucleotide : nucleotides) {
if (count < length) {
line.add(nucleotide);
++count;
} else {
result.add(line);
count = 1;
line = new ArrayList<Nucleotide>();
line.add(nucleotide);
}
}
result.add(line);
return result;
}
public List<List<Color>> split(CsRead cSRead,
int length) {
List<Color> colors = cSRead.getSequence().subList(1, cSRead.getSequence().size());
List<List<Color>> result = new ArrayList<List<Color>>();
int count = 0;
List<Color> line = new ArrayList<Color>();
for (Color color : colors) {
if (count < length) {
line.add(color);
++count;
} else {
result.add(line);
count = 1;
line = new ArrayList<Color>();
line.add(color);
}
}
result.add(line);
return result;
}
}
| gpl-3.0 |
PeterCassetta/pixel-dungeon-rebalanced | java/com/petercassetta/pdrebalanced/actors/buffs/Shadows.java | 2175 | /*
* Pixel Dungeon: Rebalanced
* Copyright (C) 2012-2015 Oleg Dolya
* Copyright (C) 2015 Peter Cassetta
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.petercassetta.pdrebalanced.actors.buffs;
import com.petercassetta.noosa.audio.Sample;
import com.petercassetta.pdrebalanced.Assets;
import com.petercassetta.pdrebalanced.Dungeon;
import com.petercassetta.pdrebalanced.actors.Char;
import com.petercassetta.pdrebalanced.ui.BuffIndicator;
import com.petercassetta.utils.Bundle;
public class Shadows extends Invisibility {
protected float left;
private static final String LEFT = "left";
@Override
public void storeInBundle( Bundle bundle ) {
super.storeInBundle( bundle );
bundle.put( LEFT, left );
}
@Override
public void restoreFromBundle( Bundle bundle ) {
super.restoreFromBundle( bundle );
left = bundle.getFloat( LEFT );
}
@Override
public boolean attachTo( Char target ) {
if (super.attachTo( target )) {
Sample.INSTANCE.play( Assets.SND_MELD );
Dungeon.observe();
return true;
} else {
return false;
}
}
@Override
public void detach() {
super.detach();
Dungeon.observe();
}
@Override
public boolean act() {
if (target.isAlive()) {
spend( TICK * 2 );
if (--left <= 0 || Dungeon.hero.visibleEnemies() > 0) {
detach();
}
} else {
detach();
}
return true;
}
public void prolong() {
left = 2;
}
@Override
public int icon() {
return BuffIndicator.SHADOWS;
}
@Override
public String toString() {
return "Shadowmelded";
}
}
| gpl-3.0 |
ldbc/ldbc_snb_datagen | src/main/java/ldbc/snb/datagen/dictionary/PlaceZOrder.java | 400 | package ldbc.snb.datagen.dictionary;
/**
* Private class used to sort countries by their z-order value.
*/
class PlaceZOrder implements Comparable<PlaceZOrder> {
public int id;
Integer zValue;
PlaceZOrder(int id, int zValue) {
this.id = id;
this.zValue = zValue;
}
public int compareTo(PlaceZOrder obj) {
return zValue.compareTo(obj.zValue);
}
}
| gpl-3.0 |
MusayevKamran/pfur-skis-model-3d | src/main/java/ru/pfur/skis/model/scheme/SemiCycloid.java | 1304 | package ru.pfur.skis.model.scheme;
import ru.pfur.skis.command.AddBarCommand;
import ru.pfur.skis.command.AddNodeCommand;
import ru.pfur.skis.model.Bar;
import ru.pfur.skis.model.Model;
import ru.pfur.skis.model.Node;
/**
* Created by Kamran on 6/2/2016.
*/
public class SemiCycloid implements Scheme {
public SemiCycloid(Model model) {
generate(model);
}
@Override
public void generate(Model model) {
double t;
double s;
Node prev = null;
int num = 0;
for (t = 0; t < Math.PI / 3; t = t + 0.05) {
for (s = 0; s < Math.PI; s = s + 0.05) {
num++;
int x = (int) ((2 * (Math.PI * t + Math.sin(Math.PI * t)) * Math.sin(2 * Math.PI * s)) * 20);
int y = (int) ((8 * (1 + Math.cos(Math.PI * t))) * 20);
int z = (int) ((2 * (Math.PI * t + Math.sin(Math.PI * t)) * Math.cos(2 * Math.PI * s)) * 20);
Node n = new Node(x, y, z);
new AddNodeCommand(model, n);
if (prev != null && prev != n) {
new AddBarCommand(model, new Bar(prev, n));
num++;
}
prev = n;
}
}
}
@Override
public void action(Model model) {
}
}
| gpl-3.0 |
ALIADA/aliada-tool | aliada/aliada-rdfizer/src/main/java/eu/aliada/rdfizer/pipeline/format/marc/frbr/ExpressionDetector.java | 1497 | // ALIADA - Automatic publication under Linked Data paradigm
// of library and museum data
//
// Component: aliada-rdfizer
// Responsible: ALIADA Consortiums
package eu.aliada.rdfizer.pipeline.format.marc.frbr;
import static eu.aliada.shared.Strings.isNotNullAndNotEmpty;
import java.util.List;
import java.util.Map;
import org.w3c.dom.Document;
import eu.aliada.rdfizer.pipeline.format.marc.selector.Expression;
/**
* Class containes "expression" objects which extracts values related with
* Expression entity.
*
* @author Emiliano Cammilletti
* @author Andrea Gazzarini
* @since 1.0
*/
public class ExpressionDetector extends AbstractEntityDetector<String> {
private final List<Expression<Map<String, String>, Document>> expressions;
/**
* Builds a new detector with the following rules.
*
* @param expressions the detection rules.
*/
public ExpressionDetector(final List<Expression<Map<String, String>, Document>> expressions) {
this.expressions = expressions;
}
/**
* This method concat every xpath values for the expression entity
*
* @param target the target document.
* @return the detected value.
*/
String detect(final Document target) {
final StringBuilder buffer = new StringBuilder();
for (final Expression<Map<String, String>, Document> expression : expressions) {
append(buffer, expression.evaluate(target));
}
final String result = buffer.toString().trim();
return isNotNullAndNotEmpty(result) ? result : null;
}
}
| gpl-3.0 |
hernol/ConuWar | AndroidME/src_SwingME_plaf/net/yura/android/plaf/AndroidSprite.java | 3738 | package net.yura.android.plaf;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.Sprite;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RotateDrawable;
public class AndroidSprite extends Sprite {
Drawable spin;
int frame;
public AndroidSprite(Drawable d, int w, int h) {
super(w > 1 ? w : d.getIntrinsicWidth(), h > 1 ? h : d.getIntrinsicHeight());
spin = d;
}
@Override
public void paint(Graphics g) {
Drawable draw;
if (spin instanceof AnimationDrawable) {
draw = ((AnimationDrawable)spin).getFrame(frame);
}
// else if (spin.getClass().getName().equals("android.graphics.drawable.AnimatedRotateDrawable")) {
// int totalFrame = getFrameSequenceLength();
// canvas.rotate((frame*360)/totalFrame, x+width/2, y+height/2);
// draw = spin;
// }
else if (spin instanceof Runnable) {
draw = spin;
}
else if (spin instanceof RotateDrawable) {
spin.setLevel( frame*10000/getFrameSequenceLength() );
draw = spin;
}
else {
draw = spin;
System.out.println("DO NOT KNOW HOW TO DRAW "+spin);
}
android.graphics.Canvas canvas = g.getCanvas();
canvas.save();
draw.setBounds(0, 0, getWidth(), getHeight());
canvas.translate(g.getTranslateX()+getX(), g.getTranslateY()+getY());
draw.draw(canvas);
canvas.restore();
}
@Override
public int getFrameSequenceLength() {
if (spin instanceof AnimationDrawable) {
return ((AnimationDrawable)spin).getNumberOfFrames();
}
// if (spin.getClass().getName().equals("android.graphics.drawable.AnimatedRotateDrawable")) {
// return 12;
// }
if (spin instanceof Runnable) {
return 12; // Android default implementation value.
}
if (spin instanceof RotateDrawable) {
return 12; // a guess, this is used by the SE Xperia X10 Android 1.6 by the inverted spinner
}
return 1; // we do not know how to animate this, so it only has 1 frame
}
private long lastSetFrameTime;
@Override
public void setFrame(int newFrame) {
if (frame != newFrame) {
// HACK 1: android.graphics.drawable.AnimatedRotateDrawable class implements
// Runnable. Calling run() will make it rotate one position. We are
// ignoring the requesting frame, but that is OK for a spinner.
if (spin instanceof Runnable) {
// HACK 2: The same Sprite is shared between animations, and the "newFrame"
// sequence of each of animation is independent, we need to somehow respond
// to only of them, otherwise the spinner will spin a lot faster than intended.
// 1 - If the frame set is the next from the previous one, we accept it.
// 2 - Otherwise we accept it if the latest successful rotation happened
// more than 200 ms ago.
int nextFrame = (frame + 1) % getFrameSequenceLength();
long now = System.currentTimeMillis();
if (newFrame == nextFrame || (now - lastSetFrameTime) > 100) {
frame = newFrame;
((Runnable) spin).run();
lastSetFrameTime = now;
}
}
else {
frame = newFrame;
}
}
}
}
| gpl-3.0 |
giorgianb/FunctionRotator | src/Parser/ParseError.java | 260 | package Parser;
final public class ParseError extends Exception
{
public ParseError (final String message)
{
super (message);
}
public ParseError (final String message, final Throwable cause)
{
super (message, cause);
}
}
| gpl-3.0 |
livingsocial/HiveSwarm | src/main/java/com/livingsocial/hive/udf/InArray.java | 2779 | package com.livingsocial.hive.udf;
import com.livingsocial.hive.utils.KISSInspector;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.serde.Constants;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@Description(name = "in_array", value = "_FUNC_(x, a) - Returns true if x is in the array a")
public class InArray extends GenericUDF {
private ListObjectInspector array_inspector;
private KISSInspector element_inspector;
static final Log LOG = LogFactory.getLog(InArray.class.getName());
@Override
public ObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException {
if(args.length != 2 || !KISSInspector.isPrimitive(args[0]) || !KISSInspector.isList(args[1]))
throw new UDFArgumentException("in_array() takes two arguments: a primitive and an array");
element_inspector = new KISSInspector(args[0]);
array_inspector = (ListObjectInspector) args[1];
return PrimitiveObjectInspectorFactory.writableBooleanObjectInspector;
}
@Override
public BooleanWritable evaluate(DeferredObject[] arguments) throws HiveException {
BooleanWritable found = new BooleanWritable(false);
// if either argument is null, or if the list doesn't contain the same primitives
if(arguments[0].get() == null || arguments[1].get() == null || !element_inspector.sameAsTypeIn(array_inspector))
return found;
Object element = arguments[0].get();
Object elist = arguments[1].get();
for(int i=0; i<array_inspector.getListLength(elist); i++) {
LOG.warn("elem from array: " + element_inspector.get(array_inspector.getListElement(elist, i)));
LOG.warn("elem: " + element_inspector.get(element));
Object listElem = array_inspector.getListElement(elist, i);
if(listElem != null && element_inspector.get(listElem).equals(element_inspector.get(element)))
found.set(true);
}
return found;
}
@Override
public String getDisplayString(String[] children) {
assert (children.length == 2);
return "in_array(" + children[0] + ", " + children[1] + ")";
}
}
| gpl-3.0 |
iterate-ch/cyberduck | core/src/main/java/ch/cyberduck/core/exception/ConnectionTimeoutException.java | 1482 | package ch.cyberduck.core.exception;
/*
* Copyright (c) 2002-2014 David Kocher. All rights reserved.
* http://cyberduck.io/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Bug fixes, suggestions and comments should be sent to:
* feedback@cyberduck.io
*/
import ch.cyberduck.core.LocaleFactory;
public class ConnectionTimeoutException extends BackgroundException {
private static final long serialVersionUID = -7408164299912691588L;
public ConnectionTimeoutException(final String detail, final Throwable cause) {
super(LocaleFactory.localizedString("Connection timed out", "Error"), detail, cause);
}
public ConnectionTimeoutException(final String message, final String detail, final Throwable cause) {
super(message, detail, cause);
}
@Override
public String getHelp() {
return LocaleFactory.localizedString("The connection attempt timed out. The server may be down, " +
"or your network may not be properly configured.", "Support");
}
}
| gpl-3.0 |
railbu/jshoper3x | src/com/jshop/action/backstage/staticspage/FreeMarkerController.java | 3510 | package com.jshop.action.backstage.staticspage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreeMarkerController extends ActionSupport {
private static final long serialVersionUID = 1L;
private String logmsg;
public String getLogmsg() {
return logmsg;
}
public void setLogmsg(String logmsg) {
this.logmsg = logmsg;
}
/**
* 初始化模板引擎数据
* @throws IOException
* @throws TemplateException
*/
public void init(String ftl,String folder,String fileName,Map<String,Object> data,String relativePath) throws IOException, TemplateException{
Writer out = null;
try{
Configuration configuration=new Configuration();
configuration.setServletContextForTemplateLoading(ServletActionContext.getServletContext(), "/"+relativePath);
configuration.setEncoding(Locale.getDefault(), "utf-8");
Template template=configuration.getTemplate(ftl);
template.setEncoding("utf-8");
String path=ServletActionContext.getServletContext().getRealPath("/");
File dir=new File(path+folder);
if(!dir.exists()){
dir.mkdirs();
}
File htmlFile=new File(path+folder+fileName);
out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile),"utf-8"));
template.process(data, out);
}catch(Exception e){
this.setLogmsg("<p style='color:red;'>" + e.getMessage() + "</p>");
}finally{
out.flush();
out.close();
}
}
/**
* 初始化邮件模板引擎数据
* @param ftl
* @param data
* @param relativePath
* @return
* @throws IOException
* @throws TemplateException
*/
public String init(String ftl,Map<String,Object>data,String relativePath) throws IOException, TemplateException{
String htmlText="";
Configuration configuration=new Configuration();
configuration.setServletContextForTemplateLoading(ServletActionContext.getServletContext(), "/"+relativePath);
configuration.setEncoding(Locale.getDefault(), "utf-8");
Template template=configuration.getTemplate(ftl);
template.setEncoding("utf-8");
htmlText=FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
return htmlText;
}
public void init(String ftl,Map<String,Object>root) throws TemplateException, IOException{
Configuration configuration=new Configuration();
configuration.setServletContextForTemplateLoading(ServletActionContext.getServletContext(), "/");
configuration.setEncoding(Locale.CHINA, "UTF-8");
Template template=configuration.getTemplate(ftl);
template.setEncoding("UTF-8");
ActionContext ctx = ActionContext.getContext();
HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);
response.setContentType("text/html;charset="+template.getEncoding());
Writer out=response.getWriter();
template.process(root, out);
out.flush();
}
}
| gpl-3.0 |
ByteSyze/CIS-18B | Assignments/8 - Chess/src/game/chess/piece/ChessPieceController.java | 2209 | package game.chess.piece;
import java.awt.Graphics2D;
import java.awt.Shape;
import game.Game2D;
import game.GameObject;
import game.chess.ChessPlayer;
import game.position.Position;
import game.position.Vector;
public class ChessPieceController implements GameObject
{
private static final float POSITION_SNAP_THRESH = 0.5f;
ChessPiece model;
ChessPieceView view;
/**Indicates whether this piece has been captured or not.*/
private boolean isCaptured = false;
public ChessPieceController(ChessPiece model)
{
this.model = model;
this.view = new ChessPieceView(model);
}
public void update(Game2D game)
{
//TODO use transforms to help with all of this junk.
//Move the ChessPieceView's position towards the ChessPiece's board position
Vector scaledBoardPos = new Vector(model.getBoardPosition());
Vector pos = (Vector)getPosition();
scaledBoardPos.setScale(pos.getScale());
if(pos.distanceSq(scaledBoardPos) > POSITION_SNAP_THRESH)
{
pos.move(new Position((scaledBoardPos.getX()-pos.getX())/500f,(scaledBoardPos.getY()-pos.getY())/500f));
}
else if((pos.getX() != scaledBoardPos.getX()) || (pos.getY() != scaledBoardPos.getY()))
{
pos.setX(scaledBoardPos.getUnscaledX());
pos.setY(scaledBoardPos.getUnscaledY());
}
model.bounds.setRect(view.getPosition().getX()*game.getXScale(), view.getPosition().getY()*game.getYScale(), getComponentWidth()*game.getXScale(), getComponentHeight()*game.getYScale());
}
public void draw(Graphics2D g)
{
view.draw(g);
}
public void highlight(Graphics2D g)
{
view.highlight(g);
}
public void setCaptured(boolean captured)
{
this.isCaptured = captured;
}
public ChessPiece getModel()
{
return model;
}
public ChessPlayer getOwner()
{
return model.getOwner();
}
public Position getPosition()
{
return view.getPosition();
}
public float getComponentHeight()
{
return model.getComponentHeight();
}
public float getComponentWidth()
{
return model.getComponentWidth();
}
public boolean isCaptured()
{
return isCaptured;
}
public boolean isActive()
{
return !isCaptured();
}
public Shape getBounds()
{
return model.getBounds();
}
}
| gpl-3.0 |
Staartvin/Statz | src/me/staartvin/statz/language/StatisticDescription.java | 8584 | package me.staartvin.statz.language;
import me.staartvin.statz.datamanager.player.PlayerStat;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
/**
* Every enumeration value has its path and default value.
* To get the path, do {@link #getPath()}.
* To get the default value, do {@link #getDefault()}.
* <p>
* For the defined value in the lang.yml config, use
* {@link #getConfigValue(Object...)}.
* String objects are expected as input.
*
* @author Staartvin and gomeow
*/
public enum StatisticDescription {
/**
* Joined the server {0} times.
*/
JOINS(PlayerStat.JOINS, "Joined the server {0} times.", "&3Joined the server &2{0}&3 times."),
/**
* Died {0} times on world '{1}'
*/
DEATHS(PlayerStat.DEATHS, "Died {0} times on world '{1}'.", "&3Died &2{0}&3 times."),
/**
* Caught {0} {1} times on world '{2}'
*/
ITEMS_CAUGHT(PlayerStat.ITEMS_CAUGHT, "Caught {0} {1} times on world '{2}'.", "&3Caught" +
" &2{0}&3 " + "items."),
/**
* Placed {0} blocks of {1} on world '{1}'
*/
BLOCKS_PLACED(PlayerStat.BLOCKS_PLACED, "Placed {0} blocks of {1} on " +
"world '{2}'.", "&3Placed &2{0}&3 blocks."),
/**
* Broke {0} blocks of {1} on world '{2}'.
*/
BLOCKS_BROKEN(PlayerStat.BLOCKS_BROKEN, "Broke {0} blocks of {1} on " +
"world " + "'{2}'.", "&3Broke &2{0}&3 blocks."),
/**
* Killed {0} {1}s on world '{2}'.
*/
KILLS_MOBS(PlayerStat.KILLS_MOBS, "Killed {0} {1}s on world '{2}'.", "&3Killed &2{0}&3 " +
"mobs."),
/**
* Killed {0} {1} times on world '{2}'.
*/
KILLS_PLAYERS(PlayerStat.KILLS_PLAYERS, "Killed {0} {1} times on world '{2}'.",
"&3Killed &2{0}&3" +
" players."),
/**
* Played for {0} on world '{1}'.
*/
TIME_PLAYED(PlayerStat.TIME_PLAYED, "Played for {0} on world '{1}'.", "&3Played &2{0}&3."),
/**
* Eaten {0} {1} on world '{2}'.
*/
FOOD_EATEN(PlayerStat.FOOD_EATEN, "Eaten {0} {1} on world '{2}'.", "&3Ate &2{0}&3 " +
"consumables."),
/**
* Took {0} points of damage by {1} on world '{2}'.
*/
DAMAGE_TAKEN(PlayerStat.DAMAGE_TAKEN, "Took {0} points of damage by {1} on world '{2}'" +
".", "&3Took " +
"&2{0}&3 " +
"points of damage."),
/**
* Shorn {0} sheep on world '{1}'.
*/
TIMES_SHORN(PlayerStat.TIMES_SHORN, "Shorn {0} sheep on world '{1}'.", "&3Shorn &2{0}&3 " +
"sheep."),
/**
* Travelled {0} blocks on world '{1}' by {2}.
*/
DISTANCE_TRAVELLED(PlayerStat.DISTANCE_TRAVELLED, "Travelled {0} blocks on world " +
"'{1}' by {2}.",
"&3Travelled " +
"&2{0}&3 blocks."),
/**
* Crafted {0} {1} times on world '{2}'.
*/
ITEMS_CRAFTED(PlayerStat.ITEMS_CRAFTED, "Crafted {0} {1} times on world '{2}'.",
"&3Crafted " +
"&2{0}&3 items."),
/**
* Gained {0} points of xp on world '{1}'
*/
XP_GAINED(PlayerStat.XP_GAINED, "Gained {0} points of xp on world '{1}'.", "&3Gained " +
"&2{0}&3 " +
"points of xp" +
"."),
/**
* Voted {0} times
*/
VOTES(PlayerStat.VOTES, "Voted {0} times.", "&3Voted &2{0}&3 times."),
/**
* Shot {0} arrows on world '{1}'.
*/
ARROWS_SHOT(PlayerStat.ARROWS_SHOT, "Shot {0} arrows on world '{1}'" +
".", "&3Shot " +
"&2{0}&3 " +
"arrows."),
/**
* Slept {0} times in a bed on world '{1}'.
*/
ENTERED_BEDS(PlayerStat.ENTERED_BEDS, "Slept {0} times in a bed on world '{1}'.",
"&3Slept &2{0}&3 " +
"times."),
/**
* Performed {0} {1} times on world '{2}'.
*/
COMMANDS_PERFORMED(PlayerStat.COMMANDS_PERFORMED, "Performed {0} {1} times on " +
"world '{2}'.",
"&3Performed " +
"&2" +
"{0}&3 commands."),
/**
* Kicked {0} times on world '{1}' with reason '{2}'.
*/
TIMES_KICKED(PlayerStat.TIMES_KICKED, "Kicked {0} times on world '{1}' with reason " +
"'{2}'.",
"&3Kicked " +
"&2{0}&3 " +
"times."),
/**
* Broken {0} {1} times on world '{2}'.
*/
TOOLS_BROKEN(PlayerStat.TOOLS_BROKEN, "Broken {0} {1} times on world '{2}'.",
"&3Broken " +
"&2{0}&3 tools."),
/**
* Thrown {0} eggs on world '{1}'.
*/
EGGS_THROWN(PlayerStat.EGGS_THROWN, "Thrown {0} eggs on world '{1}'.", "&3Thrown &2{0}&3" +
" eggs."),
/**
* Changed from {0} to {1} {2} times.
*/
WORLDS_CHANGED(PlayerStat.WORLDS_CHANGED, "Changed from {0} to {1} {2} times.",
"&3Changed worlds " +
"&2{0}&3 times."),
/**
* Filled {0} buckets on world '{1}'.
*/
BUCKETS_FILLED(PlayerStat.BUCKETS_FILLED, "Filled {0} buckets on world '{1}'.",
"&3Filled &2{0}&3 " +
"buckets."),
/**
* Emptied {0} buckets on world '{1}'.
*/
BUCKETS_EMPTIED(PlayerStat.BUCKETS_EMPTIED, "Emptied {0} buckets on world '{1}'.",
"&3Emptied " +
"&2{0}&3 " +
"buckets."),
/**
* Dropped {0} {1} times on world '{2}'.
*/
ITEMS_DROPPED(PlayerStat.ITEMS_DROPPED, "Dropped {0} {1} times on world '{2}'.",
"&3Dropped " +
"&2{0}&3 " +
"items."),
/**
* Picked up {0} {1} times on world '{2}'.
*/
ITEMS_PICKED_UP(PlayerStat.ITEMS_PICKED_UP, "Picked up {0} {1} times on world '{2}'" +
".", "&3Picked " +
"up " +
"&2{0}&3 " +
"items."),
/**
* Teleported from {0} to {1} {2} times because of {3}.
*/
TELEPORTS(PlayerStat.TELEPORTS, "Teleported from {0} to {1} {2} times because of {3}.",
"&3Teleported " +
"&2{0}&3 " +
"times."),
/**
* Traded with {0} Villagers on world '{1}' for item {2}.
*/
VILLAGER_TRADES(PlayerStat.VILLAGER_TRADES, "Traded with {0} Villagers on world " +
"'{1}' for item {2}" +
".",
"&3Traded " +
"with &2{0}&3 Villagers."),;
private static FileConfiguration file;
private String highDetailDesc, totalDesc;
private PlayerStat relatedPlayerStat;
/**
* Statistic enum constructor.
*/
StatisticDescription(PlayerStat correspondingStat, String highDetailDesc, String totalDesc) {
this.highDetailDesc = highDetailDesc;
this.totalDesc = totalDesc;
this.relatedPlayerStat = correspondingStat;
}
/**
* Set the {@code FileConfiguration} to use.
*
* @param config The config to set.
*/
public static void setFile(final FileConfiguration config) {
file = config;
}
/**
* Get the value in the config with certain arguments.
*
* @param args arguments that need to be given. (Can be null)
* @return value in config or otherwise default value
*/
private String getConfigValue(String description, final Object... args) {
if (description == null) {
return null;
}
String value = ChatColor.translateAlternateColorCodes('&', description);
if (args == null)
return value;
else {
if (args.length == 0)
return value;
for (int i = 0; i < args.length; i++) {
value = value.replace("{" + i + "}", args[i].toString());
}
}
return value;
}
/**
* Get the default value of the path.
*
* @return The default value of the path.
*/
public String getHighDetailDescription(final Object... args) {
return getConfigValue(highDetailDesc, args);
}
public String getTotalDescription(final Object... args) {
return getConfigValue(totalDesc, args);
}
/**
* Get the PlayerStat enum that is related to this statistic description.
*
* @return {@link PlayerStat}
*/
public PlayerStat getRelatedPlayerStat() {
return this.relatedPlayerStat;
}
public String getStringIdentifier() {
return relatedPlayerStat.getTableName();
}
public enum DescriptionDetail {HIGH, MEDIUM, LOW}
}
| gpl-3.0 |
noodlewiz/xjavab | xjavab-ext/src/main/java/com/noodlewiz/xjavab/ext/xfixes/QueryVersionReply.java | 1199 | //
// DO NOT MODIFY!!! This file was machine generated. DO NOT MODIFY!!!
//
// Copyright (c) 2014 Vincent W. Chen.
//
// This file is part of XJavaB.
//
// XJavaB is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// XJavaB is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with XJavaB. If not, see <http://www.gnu.org/licenses/>.
//
package com.noodlewiz.xjavab.ext.xfixes;
import com.noodlewiz.xjavab.core.XReply;
public class QueryVersionReply
implements XReply
{
public final long majorVersion;
public final long minorVersion;
public QueryVersionReply(final long majorVersion, final long minorVersion) {
this.majorVersion = majorVersion;
this.minorVersion = minorVersion;
}
}
| gpl-3.0 |
Bombe/ams | src/test/java/net/pterodactylus/util/bits/ByteArrayEncodersTest.java | 812 | package net.pterodactylus.util.bits;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Unit test for {@link ByteArrayEncoders}.
*
* @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
*/
public class ByteArrayEncodersTest {
@Test
public void useConstructorForCompleteCoverage() {
new ByteArrayEncoders();
}
@Test
public void _16BitIntegerCanBeEncodedMsbFirst() {
MatcherAssert.assertThat(ByteArrayEncoders.integer16MsbFirstEncoder().apply(0x89ab),
Matchers.is(new byte[] { (byte) 0x89, (byte) 0xab }));
}
@Test
public void _32BitIntegerCanBeEncodedMsbFirst() {
MatcherAssert.assertThat(ByteArrayEncoders.integer32MsbFirstEncoder().apply(0x12345678),
Matchers.is(new byte[] { 0x12, 0x34, 0x56, 0x78 }));
}
}
| gpl-3.0 |
squallblade/Spigot | src/main/java/net/minecraft/server/ItemDye.java | 7704 | package net.minecraft.server;
// CraftBukkit start
import org.bukkit.entity.Player;
import org.bukkit.event.entity.SheepDyeWoolEvent;
// CraftBukkit end
public class ItemDye extends Item {
public static final String[] a = new String[] { "black", "red", "green", "brown", "blue", "purple", "cyan", "silver", "gray", "pink", "lime", "yellow", "lightBlue", "magenta", "orange", "white"};
public static final int[] b = new int[] { 1973019, 11743532, 3887386, 5320730, 2437522, 8073150, 2651799, 11250603, 4408131, 14188952, 4312372, 14602026, 6719955, 12801229, 15435844, 15790320};
public ItemDye(int i) {
super(i);
this.a(true);
this.setMaxDurability(0);
this.a(CreativeModeTab.l);
}
public String d(ItemStack itemstack) {
int i = MathHelper.a(itemstack.getData(), 0, 15);
return super.getName() + "." + a[i];
}
public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, int i, int j, int k, int l, float f, float f1, float f2) {
if (!entityhuman.a(i, j, k, l, itemstack)) {
return false;
} else {
int i1;
int j1;
int k1;
if (itemstack.getData() == 15) {
i1 = world.getTypeId(i, j, k);
if (i1 == Block.SAPLING.id) {
if (!world.isStatic) {
// CraftBukkit start
Player player = (entityhuman instanceof EntityPlayer) ? (Player) entityhuman.getBukkitEntity() : null;
((BlockSapling) Block.SAPLING).grow(world, i, j, k, world.random, true, player, itemstack);
//--itemstack.count; - called later if the bonemeal attempt was succesful
// CraftBukkit end
}
return true;
}
if (i1 == Block.BROWN_MUSHROOM.id || i1 == Block.RED_MUSHROOM.id) {
// CraftBukkit start
if (!world.isStatic) {
Player player = (entityhuman instanceof EntityPlayer) ? (Player) entityhuman.getBukkitEntity() : null;
((BlockMushroom) Block.byId[i1]).grow(world, i, j, k, world.random, true, player, itemstack);
//--itemstack.count; - called later if the bonemeal attempt was succesful
// CraftBukkit end
}
return true;
}
if (i1 == Block.MELON_STEM.id || i1 == Block.PUMPKIN_STEM.id) {
if (world.getData(i, j, k) == 7) {
return false;
}
if (!world.isStatic) {
((BlockStem) Block.byId[i1]).l(world, i, j, k);
--itemstack.count;
}
return true;
}
if (i1 > 0 && Block.byId[i1] instanceof BlockCrops) {
if (world.getData(i, j, k) == 7) {
return false;
}
if (!world.isStatic) {
((BlockCrops) Block.byId[i1]).c_(world, i, j, k);
--itemstack.count;
}
return true;
}
if (i1 == Block.COCOA.id) {
if (!world.isStatic) {
world.setData(i, j, k, 8 | BlockDirectional.e(world.getData(i, j, k)));
--itemstack.count;
}
return true;
}
if (i1 == Block.GRASS.id) {
if (!world.isStatic) {
--itemstack.count;
label133:
for (j1 = 0; j1 < 128; ++j1) {
k1 = i;
int l1 = j + 1;
int i2 = k;
for (int j2 = 0; j2 < j1 / 16; ++j2) {
k1 += d.nextInt(3) - 1;
l1 += (d.nextInt(3) - 1) * d.nextInt(3) / 2;
i2 += d.nextInt(3) - 1;
if (world.getTypeId(k1, l1 - 1, i2) != Block.GRASS.id || world.t(k1, l1, i2)) {
continue label133;
}
}
if (world.getTypeId(k1, l1, i2) == 0) {
if (d.nextInt(10) != 0) {
if (Block.LONG_GRASS.d(world, k1, l1, i2)) {
world.setTypeIdAndData(k1, l1, i2, Block.LONG_GRASS.id, 1);
}
} else if (d.nextInt(3) != 0) {
if (Block.YELLOW_FLOWER.d(world, k1, l1, i2)) {
world.setTypeId(k1, l1, i2, Block.YELLOW_FLOWER.id);
}
} else if (Block.RED_ROSE.d(world, k1, l1, i2)) {
world.setTypeId(k1, l1, i2, Block.RED_ROSE.id);
}
}
}
}
return true;
}
} else if (itemstack.getData() == 3) {
i1 = world.getTypeId(i, j, k);
j1 = world.getData(i, j, k);
if (i1 == Block.LOG.id && BlockLog.e(j1) == 3) {
if (l == 0) {
return false;
}
if (l == 1) {
return false;
}
if (l == 2) {
--k;
}
if (l == 3) {
++k;
}
if (l == 4) {
--i;
}
if (l == 5) {
++i;
}
if (world.isEmpty(i, j, k)) {
k1 = Block.byId[Block.COCOA.id].getPlacedData(world, i, j, k, l, f, f1, f2, 0);
world.setTypeIdAndData(i, j, k, Block.COCOA.id, k1);
if (!entityhuman.abilities.canInstantlyBuild) {
--itemstack.count;
}
}
return true;
}
}
return false;
}
}
public boolean a(ItemStack itemstack, EntityLiving entityliving) {
if (entityliving instanceof EntitySheep) {
EntitySheep entitysheep = (EntitySheep) entityliving;
int i = BlockCloth.e_(itemstack.getData());
if (!entitysheep.isSheared() && entitysheep.getColor() != i) {
// CraftBukkit start
byte bColor = (byte) i;
SheepDyeWoolEvent event = new SheepDyeWoolEvent((org.bukkit.entity.Sheep) entitysheep.getBukkitEntity(), org.bukkit.DyeColor.getByData(bColor));
entitysheep.world.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return false;
}
i = (byte) event.getColor().getWoolData();
// CraftBukkit end
entitysheep.setColor(i);
--itemstack.count;
}
return true;
} else {
return false;
}
}
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java | 9736 | /**
*
*/
package com.baeldung.examples.security.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;
import javax.sql.DataSource;
import org.springframework.stereotype.Component;
/**
* @author Philippe
*
*/
@Component
public class AccountDAO {
private final DataSource dataSource;
private final EntityManager em;
public AccountDAO(DataSource dataSource, EntityManager em) {
this.dataSource = dataSource;
this.em = em;
}
/**
* Return all accounts owned by a given customer,given his/her external id
*
* @param customerId
* @return
*/
public List<AccountDTO> unsafeFindAccountsByCustomerId(String customerId) {
String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = '" + customerId + "'";
try (Connection c = dataSource.getConnection();
ResultSet rs = c.createStatement()
.executeQuery(sql)) {
List<AccountDTO> accounts = new ArrayList<>();
while (rs.next()) {
AccountDTO acc = AccountDTO.builder()
.customerId(rs.getString("customer_id"))
.branchId(rs.getString("branch_id"))
.accNumber(rs.getString("acc_number"))
.balance(rs.getBigDecimal("balance"))
.build();
accounts.add(acc);
}
return accounts;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
/**
* Return all accounts owned by a given customer,given his/her external id - JPA version
*
* @param customerId
* @return
*/
public List<AccountDTO> unsafeJpaFindAccountsByCustomerId(String customerId) {
String jql = "from Account where customerId = '" + customerId + "'";
TypedQuery<Account> q = em.createQuery(jql, Account.class);
return q.getResultList()
.stream()
.map(a -> AccountDTO.builder()
.accNumber(a.getAccNumber())
.balance(a.getBalance())
.branchId(a.getAccNumber())
.customerId(a.getCustomerId())
.build())
.collect(Collectors.toList());
}
/**
* Return all accounts owned by a given customer,given his/her external id
*
* @param customerId
* @return
*/
public List<AccountDTO> safeFindAccountsByCustomerId(String customerId) {
String sql = "select customer_id, branch_id,acc_number,balance from Accounts where customer_id = ?";
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) {
p.setString(1, customerId);
ResultSet rs = p.executeQuery();
List<AccountDTO> accounts = new ArrayList<>();
while (rs.next()) {
AccountDTO acc = AccountDTO.builder()
.customerId(rs.getString("customerId"))
.branchId(rs.getString("branch_id"))
.accNumber(rs.getString("acc_number"))
.balance(rs.getBigDecimal("balance"))
.build();
accounts.add(acc);
}
return accounts;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
/**
* Return all accounts owned by a given customer,given his/her external id - JPA version
*
* @param customerId
* @return
*/
public List<AccountDTO> safeJpaFindAccountsByCustomerId(String customerId) {
String jql = "from Account where customerId = :customerId";
TypedQuery<Account> q = em.createQuery(jql, Account.class)
.setParameter("customerId", customerId);
return q.getResultList()
.stream()
.map(a -> AccountDTO.builder()
.accNumber(a.getAccNumber())
.balance(a.getBalance())
.branchId(a.getAccNumber())
.customerId(a.getCustomerId())
.build())
.collect(Collectors.toList());
}
/**
* Return all accounts owned by a given customer,given his/her external id - JPA version
*
* @param customerId
* @return
*/
public List<AccountDTO> safeJpaCriteriaFindAccountsByCustomerId(String customerId) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Account> cq = cb.createQuery(Account.class);
Root<Account> root = cq.from(Account.class);
cq.select(root)
.where(cb.equal(root.get(Account_.customerId), customerId));
TypedQuery<Account> q = em.createQuery(cq);
return q.getResultList()
.stream()
.map(a -> AccountDTO.builder()
.accNumber(a.getAccNumber())
.balance(a.getBalance())
.branchId(a.getAccNumber())
.customerId(a.getCustomerId())
.build())
.collect(Collectors.toList());
}
private static final Set<String> VALID_COLUMNS_FOR_ORDER_BY = Stream.of("acc_number", "branch_id", "balance")
.collect(Collectors.toCollection(HashSet::new));
/**
* Return all accounts owned by a given customer,given his/her external id
*
* @param customerId
* @return
*/
public List<AccountDTO> safeFindAccountsByCustomerId(String customerId, String orderBy) {
String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ? ";
if (VALID_COLUMNS_FOR_ORDER_BY.contains(orderBy)) {
sql = sql + " order by " + orderBy;
} else {
throw new IllegalArgumentException("Nice try!");
}
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) {
p.setString(1, customerId);
ResultSet rs = p.executeQuery();
List<AccountDTO> accounts = new ArrayList<>();
while (rs.next()) {
AccountDTO acc = AccountDTO.builder()
.customerId(rs.getString("customerId"))
.branchId(rs.getString("branch_id"))
.accNumber(rs.getString("acc_number"))
.balance(rs.getBigDecimal("balance"))
.build();
accounts.add(acc);
}
return accounts;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
private static final Map<String,SingularAttribute<Account,?>> VALID_JPA_COLUMNS_FOR_ORDER_BY = Stream.of(
new AbstractMap.SimpleEntry<>(Account_.ACC_NUMBER, Account_.accNumber),
new AbstractMap.SimpleEntry<>(Account_.BRANCH_ID, Account_.branchId),
new AbstractMap.SimpleEntry<>(Account_.BALANCE, Account_.balance)
)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
/**
* Return all accounts owned by a given customer,given his/her external id
*
* @param customerId
* @return
*/
public List<AccountDTO> safeJpaFindAccountsByCustomerId(String customerId, String orderBy) {
SingularAttribute<Account,?> orderByAttribute = VALID_JPA_COLUMNS_FOR_ORDER_BY.get(orderBy);
if ( orderByAttribute == null) {
throw new IllegalArgumentException("Nice try!");
}
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Account> cq = cb.createQuery(Account.class);
Root<Account> root = cq.from(Account.class);
cq.select(root)
.where(cb.equal(root.get(Account_.customerId), customerId))
.orderBy(cb.asc(root.get(orderByAttribute)));
TypedQuery<Account> q = em.createQuery(cq);
return q.getResultList()
.stream()
.map(a -> AccountDTO.builder()
.accNumber(a.getAccNumber())
.balance(a.getBalance())
.branchId(a.getAccNumber())
.customerId(a.getCustomerId())
.build())
.collect(Collectors.toList());
}
/**
* Invalid placeholder usage example
*
* @param tableName
* @return
*/
public Long wrongCountRecordsByTableName(String tableName) {
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement("select count(*) from ?")) {
p.setString(1, tableName);
ResultSet rs = p.executeQuery();
rs.next();
return rs.getLong(1);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
/**
* Invalid placeholder usage example - JPA
*
* @param tableName
* @return
*/
public Long wrongJpaCountRecordsByTableName(String tableName) {
String jql = "select count(*) from :tableName";
TypedQuery<Long> q = em.createQuery(jql, Long.class)
.setParameter("tableName", tableName);
return q.getSingleResult();
}
}
| gpl-3.0 |
nitinkaveriappa/HackerRank-Solutions | 30 Days of Code/Day 17 - More Exceptions/Solution.java | 897 | import java.util.*;
import java.io.*;
class Calculator {
// Default constructor is always created by JAVA Compiler
int power(int mN, int mP) throws Exception{
if(mN >= 0 && mP >= 0){
return (int) Math.pow(mN, mP);
}else{
throw new Exception("n and p should be non-negative");
}
}
}
class Solution{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
int p = in.nextInt();
Calculator myCalculator = new Calculator();
try {
int ans = myCalculator.power(n, p);
System.out.println(ans);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
in.close();
}
}
| gpl-3.0 |
mon2au/invoicebinder | invoicebinder/src/main/java/com/invoicebinder/shared/model/UserInfo.java | 2672 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.invoicebinder.shared.model;
import com.google.gwt.user.client.rpc.IsSerializable;
import java.util.Date;
/**
*
* @author mon2
*/
public class UserInfo implements IsSerializable {
private long id;
private String userName;
private String firstName;
private String lastName;
private String primaryEmailAddr;
private String databasePassword;
private String userPassword;
private String userNewPassword;
private String userConfirmPassword;
private String userStatus;
private Date loginTimeStamp;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPrimaryEmailAddr() {
return primaryEmailAddr;
}
public void setPrimaryEmailAddr(String primaryEmailAddr) {
this.primaryEmailAddr = primaryEmailAddr;
}
public String getDatabasePassword() {
return databasePassword;
}
public void setDatabasePassword(String databasePassword) {
this.databasePassword = databasePassword;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserNewPassword() {
return userNewPassword;
}
public void setUserNewPassword(String userNewPassword) {
this.userNewPassword = userNewPassword;
}
public String getUserConfirmPassword() {
return userConfirmPassword;
}
public void setUserConfirmPassword(String userConfirmPassword) {
this.userConfirmPassword = userConfirmPassword;
}
public String getUserStatus() {
return userStatus;
}
public void setUserStatus(String userStatus) {
this.userStatus = userStatus;
}
public Date getLoginTimeStamp() {
return loginTimeStamp;
}
public void setLoginTimeStamp(Date loginTimeStamp) {
this.loginTimeStamp = loginTimeStamp;
}
}
| gpl-3.0 |
mozartframework/cms | src/com/mozartframework/db/filter/FilterCollection.java | 3430 | package com.mozartframework.db.filter;
import java.util.*;
import org.w3c.dom.*;
import com.mozartframework.util.XMLObject;
/**
* Коллекция фильтров. Представляет собой элемент <filter
* id="some-filter/> содержащий вложенные элементы <filter>.
*
* @version $Revision: 1.8 $
* @see FilterCode
*/
public class FilterCollection implements XMLObject {
private String _id;
private List<FilterCode> _filterCodes = new ArrayList<FilterCode>();
private String _formatIn;
private String _formatOut;
/**
* Создает объект.
*/
public FilterCollection(String id, String formatIn, String formatOut) {
_id = id;
_formatIn = formatIn;
_formatOut = formatOut;
}
/**
* Возвращает id.
*/
public String getId() {
return _id;
}
public String getFormatIn() {
return _formatIn;
}
public String getFormatOut() {
return _formatOut;
}
/**
* Добавляет все коды из заданной коллекции.
*/
public void addAll(FilterCollection fc) {
_filterCodes.addAll(fc.getAll());
}
/**
* Добавляет код в коллекцию.
*/
public void add(FilterCode fc) {
_filterCodes.add(fc);
}
/**
* Удаляет код из коллекции.
*/
public boolean remove(FilterCode fc) {
return _filterCodes.remove(fc);
}
/**
* Возвращает список кодов.
*/
public List<FilterCode> getAll() {
return _filterCodes; //Collections.unmodifiableList(filters);
}
/**
* Последовательно вызывает {@link Filter#perform} для всех
* фильтров входящих в коллекцию. При этом на вход первого фильтра
* подается <code>val</code>. На вход каждого последующего фильтра подается
* результат работы предыдущего.
*/
public Object perform(Object val) throws FilterException {
for (FilterCode fc : _filterCodes) {
val = fc.getFilter().perform(val, new FilterConfig(fc.getId(), fc.getParams()));
}
return val;
}
/**
* Возвращает размер коллекции.
*/
public int size() {
return _filterCodes.size();
}
public int hashCode() {
return _id.hashCode();
}
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o == this) {
return true;
}
if (!(o instanceof FilterCollection)) {
return false;
}
FilterCollection fc = (FilterCollection) o;
return (_id.equals(fc._id));
}
public Element toXML(Document owner) {
Element e = owner.createElement("filter");
e.setAttribute("id", _id);
if (_formatIn != null) {
e.setAttribute("format-in", _formatIn);
}
if (_formatOut != null) {
e.setAttribute("format-out", _formatOut);
}
for (FilterCode fc : _filterCodes) {
Element code = fc.toXML(owner);
e.appendChild(code);
}
return e;
}
}
| gpl-3.0 |
highsad/iDesktop-Cross | Controls/src/com/supermap/desktop/ui/controls/DialogResultEvent.java | 451 | package com.supermap.desktop.ui.controls;
import java.util.EventObject;
import com.supermap.mapping.Theme;
/**
* 对话框返回结果事件
* @author zhaosy
*
*/
public class DialogResultEvent extends EventObject {
private transient DialogResult dialogResult;
public DialogResult getDialogResult() {
return dialogResult;
}
public DialogResultEvent(Object source, DialogResult result) {
super(source);
dialogResult = result;
}
}
| gpl-3.0 |
aleatorio12/ProVentasConnector | jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/compilers/JavaScriptEvaluator.java | 5145 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.compilers;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRPropertiesUtil;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperReportsContext;
import net.sf.jasperreports.engine.fill.JREvaluator;
import net.sf.jasperreports.engine.fill.JRFillField;
import net.sf.jasperreports.engine.fill.JRFillParameter;
import net.sf.jasperreports.engine.fill.JRFillVariable;
import net.sf.jasperreports.engine.fill.JasperReportsContextAware;
import net.sf.jasperreports.engine.util.JRClassLoader;
import net.sf.jasperreports.functions.FunctionsUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* JavaScript expression evaluator that compiles expressions at fill time.
*
* @author Lucian Chirita (lucianc@users.sourceforge.net)
* @see JavaScriptCompiler
*/
public class JavaScriptEvaluator extends JREvaluator implements JasperReportsContextAware
{
/**
* Property that determines the optimization level used when compiling expressions.
*
* See <a href="http://www-archive.mozilla.org/rhino/apidocs/org/mozilla/javascript/Context.html#setOptimizationLevel%28int%29"/>
*/
public static final String PROPERTY_OPTIMIZATION_LEVEL = JRPropertiesUtil.PROPERTY_PREFIX
+ "javascript.evaluator.optimization.level";
public static final String EXCEPTION_MESSAGE_KEY_EVALUATOR_LOAD_ERROR = "compilers.javascript.evaluator.load.error";
private static final Log log = LogFactory.getLog(JavaScriptEvaluator.class);
private final JasperReportsContext jrContext;
private final JavaScriptCompileData compileData;
private FunctionsUtil functionsUtil;
private JavaScriptEvaluatorScope evaluatorScope;
private Map<String, Class<?>> loadedTypes = new HashMap<String, Class<?>>();
/**
* Create a JavaScript expression evaluator.
*
* @param compileData the report compile data
*/
public JavaScriptEvaluator(JasperReportsContext jrContext, JavaScriptCompileData compileData)
{
this.jrContext = jrContext;
this.compileData = compileData;
}
@Override
public void setJasperReportsContext(JasperReportsContext context)
{
this.functionsUtil = FunctionsUtil.getInstance(context);
}
protected void customizedInit(
Map<String, JRFillParameter> parametersMap,
Map<String, JRFillField> fieldsMap,
Map<String, JRFillVariable> variablesMap
) throws JRException
{
evaluatorScope = new JavaScriptEvaluatorScope(jrContext, this, functionsUtil);
evaluatorScope.init(parametersMap, fieldsMap, variablesMap);
}
protected Object evaluate(int id) throws Throwable //NOSONAR
{
JavaScriptCompileData.Expression expression = getExpression(id);
return evaluateExpression(expression.getDefaultExpression());
}
protected Object evaluateEstimated(int id) throws Throwable //NOSONAR
{
JavaScriptCompileData.Expression expression = getExpression(id);
return evaluateExpression(expression.getEstimatedExpression());
}
protected Object evaluateOld(int id) throws Throwable //NOSONAR
{
JavaScriptCompileData.Expression expression = getExpression(id);
return evaluateExpression(expression.getOldExpression());
}
protected JavaScriptCompileData.Expression getExpression(int id)
{
return compileData.getExpression(id);
}
/**
* @deprecated Replaced by {@link #evaluateExpression(String)}.
*/
protected Object evaluateExpression(String type, String expression)
{
return evaluateExpression(expression);
}
protected Object evaluateExpression(String expression)
{
return evaluatorScope.evaluateExpression(expression);
}
/**
* @deprecated To be removed.
*/
protected Class<?> getTypeClass(String type)
{
Class<?> typeClass = loadedTypes.get(type);
if (typeClass == null)
{
try
{
typeClass = JRClassLoader.loadClassForName(type);
}
catch (ClassNotFoundException e)
{
throw
new JRRuntimeException(
EXCEPTION_MESSAGE_KEY_EVALUATOR_LOAD_ERROR,
new Object[]{type},
e);
}
loadedTypes.put(type, typeClass);
}
return typeClass;
}
}
| gpl-3.0 |
fjodorver/open-keychain | OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/base/BaseSecurityTokenNfcActivity.java | 43195 | /*
* Copyright (C) 2015 Dominik Schürmann <dominik@dominikschuermann.de>
* Copyright (C) 2015 Vincent Breitmoser <v.breitmoser@mugenguild.com>
* Copyright (C) 2013-2014 Signe Rüsch
* Copyright (C) 2013-2014 Philipp Jakubeit
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sufficientlysecure.keychain.ui.base;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.interfaces.RSAPrivateCrtKey;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.os.AsyncTask;
import android.os.Bundle;
import nordpol.Apdu;
import nordpol.android.TagDispatcher;
import nordpol.android.AndroidCard;
import nordpol.android.OnDiscoveredTagListener;
import nordpol.IsoCard;
import org.bouncycastle.bcpg.HashAlgorithmTags;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Hex;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.pgp.exception.PgpKeyNotFoundException;
import org.sufficientlysecure.keychain.provider.CachedPublicKeyRing;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.service.PassphraseCacheService;
import org.sufficientlysecure.keychain.service.PassphraseCacheService.KeyNotFoundException;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
import org.sufficientlysecure.keychain.service.input.RequiredInputParcel;
import org.sufficientlysecure.keychain.ui.CreateKeyActivity;
import org.sufficientlysecure.keychain.ui.PassphraseDialogActivity;
import org.sufficientlysecure.keychain.ui.ViewKeyActivity;
import org.sufficientlysecure.keychain.ui.dialog.FidesmoInstallDialog;
import org.sufficientlysecure.keychain.ui.dialog.FidesmoPgpInstallDialog;
import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils;
import org.sufficientlysecure.keychain.ui.util.Notify;
import org.sufficientlysecure.keychain.ui.util.Notify.Style;
import org.sufficientlysecure.keychain.util.Iso7816TLV;
import org.sufficientlysecure.keychain.util.Log;
import org.sufficientlysecure.keychain.util.Passphrase;
public abstract class BaseSecurityTokenNfcActivity extends BaseActivity implements OnDiscoveredTagListener {
public static final int REQUEST_CODE_PIN = 1;
public static final String EXTRA_TAG_HANDLING_ENABLED = "tag_handling_enabled";
// Fidesmo constants
private static final String FIDESMO_APPS_AID_PREFIX = "A000000617";
private static final String FIDESMO_APP_PACKAGE = "com.fidesmo.sec.android";
protected Passphrase mPin;
protected Passphrase mAdminPin;
protected boolean mPw1ValidForMultipleSignatures;
protected boolean mPw1ValidatedForSignature;
protected boolean mPw1ValidatedForDecrypt; // Mode 82 does other things; consider renaming?
protected boolean mPw3Validated;
protected TagDispatcher mTagDispatcher;
private IsoCard mIsoCard;
private boolean mTagHandlingEnabled;
private static final int TIMEOUT = 100000;
private byte[] mNfcFingerprints;
private String mNfcUserId;
private byte[] mNfcAid;
/**
* Override to change UI before NFC handling (UI thread)
*/
protected void onNfcPreExecute() {
}
/**
* Override to implement NFC operations (background thread)
*/
protected void doNfcInBackground() throws IOException {
mNfcFingerprints = nfcGetFingerprints();
mNfcUserId = nfcGetUserId();
mNfcAid = nfcGetAid();
}
/**
* Override to handle result of NFC operations (UI thread)
*/
protected void onNfcPostExecute() {
final long subKeyId = KeyFormattingUtils.getKeyIdFromFingerprint(mNfcFingerprints);
try {
CachedPublicKeyRing ring = new ProviderHelper(this).getCachedPublicKeyRing(
KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(subKeyId));
long masterKeyId = ring.getMasterKeyId();
Intent intent = new Intent(this, ViewKeyActivity.class);
intent.setData(KeyRings.buildGenericKeyRingUri(masterKeyId));
intent.putExtra(ViewKeyActivity.EXTRA_SECURITY_TOKEN_AID, mNfcAid);
intent.putExtra(ViewKeyActivity.EXTRA_SECURITY_TOKEN_USER_ID, mNfcUserId);
intent.putExtra(ViewKeyActivity.EXTRA_SECURITY_TOKEN_FINGERPRINTS, mNfcFingerprints);
startActivity(intent);
} catch (PgpKeyNotFoundException e) {
Intent intent = new Intent(this, CreateKeyActivity.class);
intent.putExtra(CreateKeyActivity.EXTRA_NFC_AID, mNfcAid);
intent.putExtra(CreateKeyActivity.EXTRA_NFC_USER_ID, mNfcUserId);
intent.putExtra(CreateKeyActivity.EXTRA_NFC_FINGERPRINTS, mNfcFingerprints);
startActivity(intent);
}
}
/**
* Override to use something different than Notify (UI thread)
*/
protected void onNfcError(String error) {
Notify.create(this, error, Style.WARN).show();
}
/**
* Override to do something when PIN is wrong, e.g., clear passphrases (UI thread)
*/
protected void onNfcPinError(String error) {
onNfcError(error);
}
public void tagDiscovered(final Tag tag) {
// Actual NFC operations are executed in doInBackground to not block the UI thread
if(!mTagHandlingEnabled)
return;
new AsyncTask<Void, Void, IOException>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
onNfcPreExecute();
}
@Override
protected IOException doInBackground(Void... params) {
try {
handleTagDiscovered(tag);
} catch (IOException e) {
return e;
}
return null;
}
@Override
protected void onPostExecute(IOException exception) {
super.onPostExecute(exception);
if (exception != null) {
handleNfcError(exception);
return;
}
onNfcPostExecute();
}
}.execute();
}
protected void pauseTagHandling() {
mTagHandlingEnabled = false;
}
protected void resumeTagHandling() {
mTagHandlingEnabled = true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTagDispatcher = TagDispatcher.get(this, this, false, false, true, false);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mTagHandlingEnabled = savedInstanceState.getBoolean(EXTRA_TAG_HANDLING_ENABLED);
} else {
mTagHandlingEnabled = true;
}
Intent intent = getIntent();
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
throw new AssertionError("should not happen: NfcOperationActivity.onCreate is called instead of onNewIntent!");
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(EXTRA_TAG_HANDLING_ENABLED, mTagHandlingEnabled);
}
/**
* This activity is started as a singleTop activity.
* All new NFC Intents which are delivered to this activity are handled here
*/
@Override
public void onNewIntent(final Intent intent) {
mTagDispatcher.interceptIntent(intent);
}
private void handleNfcError(IOException e) {
if (e instanceof TagLostException) {
onNfcError(getString(R.string.security_token_error_tag_lost));
return;
}
if (e instanceof IsoDepNotSupportedException) {
onNfcError(getString(R.string.security_token_error_iso_dep_not_supported));
return;
}
short status;
if (e instanceof CardException) {
status = ((CardException) e).getResponseCode();
} else {
status = -1;
}
// Wrong PIN, a status of 63CX indicates X attempts remaining.
if ((status & (short) 0xFFF0) == 0x63C0) {
int tries = status & 0x000F;
// hook to do something different when PIN is wrong
onNfcPinError(getResources().getQuantityString(R.plurals.security_token_error_pin, tries, tries));
return;
}
// Otherwise, all status codes are fixed values.
switch (status) {
// These errors should not occur in everyday use; if they are returned, it means we
// made a mistake sending data to the token, or the token is misbehaving.
case 0x6A80: {
onNfcError(getString(R.string.security_token_error_bad_data));
break;
}
case 0x6883: {
onNfcError(getString(R.string.security_token_error_chaining_error));
break;
}
case 0x6B00: {
onNfcError(getString(R.string.security_token_error_header, "P1/P2"));
break;
}
case 0x6D00: {
onNfcError(getString(R.string.security_token_error_header, "INS"));
break;
}
case 0x6E00: {
onNfcError(getString(R.string.security_token_error_header, "CLA"));
break;
}
// These error conditions are more likely to be experienced by an end user.
case 0x6285: {
onNfcError(getString(R.string.security_token_error_terminated));
break;
}
case 0x6700: {
onNfcPinError(getString(R.string.security_token_error_wrong_length));
break;
}
case 0x6982: {
onNfcError(getString(R.string.security_token_error_security_not_satisfied));
break;
}
case 0x6983: {
onNfcError(getString(R.string.security_token_error_authentication_blocked));
break;
}
case 0x6985: {
onNfcError(getString(R.string.security_token_error_conditions_not_satisfied));
break;
}
// 6A88 is "Not Found" in the spec, but Yubikey also returns 6A83 for this in some cases.
case 0x6A88:
case 0x6A83: {
onNfcError(getString(R.string.security_token_error_data_not_found));
break;
}
// 6F00 is a JavaCard proprietary status code, SW_UNKNOWN, and usually represents an
// unhandled exception on the security token.
case 0x6F00: {
onNfcError(getString(R.string.security_token_error_unknown));
break;
}
// 6A82 app not installed on security token!
case 0x6A82: {
if (isFidesmoToken()) {
// Check if the Fidesmo app is installed
if (isAndroidAppInstalled(FIDESMO_APP_PACKAGE)) {
promptFidesmoPgpInstall();
} else {
promptFidesmoAppInstall();
}
} else { // Other (possibly) compatible hardware
onNfcError(getString(R.string.security_token_error_pgp_app_not_installed));
}
break;
}
default: {
onNfcError(getString(R.string.security_token_error, e.getMessage()));
break;
}
}
}
/**
* Called when the system is about to start resuming a previous activity,
* disables NFC Foreground Dispatch
*/
public void onPause() {
super.onPause();
Log.d(Constants.TAG, "BaseNfcActivity.onPause");
mTagDispatcher.disableExclusiveNfc();
}
/**
* Called when the activity will start interacting with the user,
* enables NFC Foreground Dispatch
*/
public void onResume() {
super.onResume();
Log.d(Constants.TAG, "BaseNfcActivity.onResume");
mTagDispatcher.enableExclusiveNfc();
}
protected void obtainSecurityTokenPin(RequiredInputParcel requiredInput) {
try {
Passphrase passphrase = PassphraseCacheService.getCachedPassphrase(this,
requiredInput.getMasterKeyId(), requiredInput.getSubKeyId());
if (passphrase != null) {
mPin = passphrase;
return;
}
Intent intent = new Intent(this, PassphraseDialogActivity.class);
intent.putExtra(PassphraseDialogActivity.EXTRA_REQUIRED_INPUT,
RequiredInputParcel.createRequiredPassphrase(requiredInput));
startActivityForResult(intent, REQUEST_CODE_PIN);
} catch (KeyNotFoundException e) {
throw new AssertionError(
"tried to find passphrase for non-existing key. this is a programming error!");
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_PIN: {
if (resultCode != Activity.RESULT_OK) {
setResult(resultCode);
finish();
return;
}
CryptoInputParcel input = data.getParcelableExtra(PassphraseDialogActivity.RESULT_CRYPTO_INPUT);
mPin = input.getPassphrase();
break;
}
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
/** Handle NFC communication and return a result.
*
* This method is called by onNewIntent above upon discovery of an NFC tag.
* It handles initialization and login to the application, subsequently
* calls either nfcCalculateSignature() or nfcDecryptSessionKey(), then
* finishes the activity with an appropriate result.
*
* On general communication, see also
* http://www.cardwerk.com/smartcards/smartcard_standard_ISO7816-4_annex-a.aspx
*
* References to pages are generally related to the OpenPGP Application
* on ISO SmartCard Systems specification.
*
*/
protected void handleTagDiscovered(Tag tag) throws IOException {
// Connect to the detected tag, setting a couple of settings
mIsoCard = AndroidCard.get(tag);
if (mIsoCard == null) {
throw new IsoDepNotSupportedException("Tag does not support ISO-DEP (ISO 14443-4)");
}
mIsoCard.setTimeout(TIMEOUT); // timeout is set to 100 seconds to avoid cancellation during calculation
mIsoCard.connect();
// SW1/2 0x9000 is the generic "ok" response, which we expect most of the time.
// See specification, page 51
String accepted = "9000";
// Command APDU (page 51) for SELECT FILE command (page 29)
String opening =
"00" // CLA
+ "A4" // INS
+ "04" // P1
+ "00" // P2
+ "06" // Lc (number of bytes)
+ "D27600012401" // Data (6 bytes)
+ "00"; // Le
String response = nfcCommunicate(opening); // activate connection
if ( ! response.endsWith(accepted) ) {
throw new CardException("Initialization failed!", parseCardStatus(response));
}
byte[] pwStatusBytes = nfcGetPwStatusBytes();
mPw1ValidForMultipleSignatures = (pwStatusBytes[0] == 1);
mPw1ValidatedForSignature = false;
mPw1ValidatedForDecrypt = false;
mPw3Validated = false;
doNfcInBackground();
}
public boolean isNfcConnected() {
return mIsoCard.isConnected();
}
/** Return the key id from application specific data stored on tag, or null
* if it doesn't exist.
*
* @param idx Index of the key to return the fingerprint from.
* @return The long key id of the requested key, or null if not found.
*/
public Long nfcGetKeyId(int idx) throws IOException {
byte[] fp = nfcGetMasterKeyFingerprint(idx);
if (fp == null) {
return null;
}
ByteBuffer buf = ByteBuffer.wrap(fp);
// skip first 12 bytes of the fingerprint
buf.position(12);
// the last eight bytes are the key id (big endian, which is default order in ByteBuffer)
return buf.getLong();
}
/** Return fingerprints of all keys from application specific data stored
* on tag, or null if data not available.
*
* @return The fingerprints of all subkeys in a contiguous byte array.
*/
public byte[] nfcGetFingerprints() throws IOException {
String data = "00CA006E00";
byte[] buf = mIsoCard.transceive(Hex.decode(data));
Iso7816TLV tlv = Iso7816TLV.readSingle(buf, true);
Log.d(Constants.TAG, "nfcGetFingerprints() Iso7816TLV tlv data:\n" + tlv.prettyPrint());
Iso7816TLV fptlv = Iso7816TLV.findRecursive(tlv, 0xc5);
if (fptlv == null) {
return null;
}
return fptlv.mV;
}
/** Return the PW Status Bytes from the token. This is a simple DO; no TLV decoding needed.
*
* @return Seven bytes in fixed format, plus 0x9000 status word at the end.
*/
public byte[] nfcGetPwStatusBytes() throws IOException {
String data = "00CA00C400";
return mIsoCard.transceive(Hex.decode(data));
}
/** Return the fingerprint from application specific data stored on tag, or
* null if it doesn't exist.
*
* @param idx Index of the key to return the fingerprint from.
* @return The fingerprint of the requested key, or null if not found.
*/
public byte[] nfcGetMasterKeyFingerprint(int idx) throws IOException {
byte[] data = nfcGetFingerprints();
if (data == null) {
return null;
}
// return the master key fingerprint
ByteBuffer fpbuf = ByteBuffer.wrap(data);
byte[] fp = new byte[20];
fpbuf.position(idx * 20);
fpbuf.get(fp, 0, 20);
return fp;
}
public byte[] nfcGetAid() throws IOException {
String info = "00CA004F00";
return mIsoCard.transceive(Hex.decode(info));
}
public String nfcGetUserId() throws IOException {
String info = "00CA006500";
return getHolderName(nfcCommunicate(info));
}
/**
* Call COMPUTE DIGITAL SIGNATURE command and returns the MPI value
*
* @param hash the hash for signing
* @return a big integer representing the MPI for the given hash
*/
public byte[] nfcCalculateSignature(byte[] hash, int hashAlgo) throws IOException {
if (!mPw1ValidatedForSignature) {
nfcVerifyPin(0x81); // (Verify PW1 with mode 81 for signing)
}
// dsi, including Lc
String dsi;
Log.i(Constants.TAG, "Hash: " + hashAlgo);
switch (hashAlgo) {
case HashAlgorithmTags.SHA1:
if (hash.length != 20) {
throw new IOException("Bad hash length (" + hash.length + ", expected 10!");
}
dsi = "23" // Lc
+ "3021" // Tag/Length of Sequence, the 0x21 includes all following 33 bytes
+ "3009" // Tag/Length of Sequence, the 0x09 are the following header bytes
+ "0605" + "2B0E03021A" // OID of SHA1
+ "0500" // TLV coding of ZERO
+ "0414" + getHex(hash); // 0x14 are 20 hash bytes
break;
case HashAlgorithmTags.RIPEMD160:
if (hash.length != 20) {
throw new IOException("Bad hash length (" + hash.length + ", expected 20!");
}
dsi = "233021300906052B2403020105000414" + getHex(hash);
break;
case HashAlgorithmTags.SHA224:
if (hash.length != 28) {
throw new IOException("Bad hash length (" + hash.length + ", expected 28!");
}
dsi = "2F302D300D06096086480165030402040500041C" + getHex(hash);
break;
case HashAlgorithmTags.SHA256:
if (hash.length != 32) {
throw new IOException("Bad hash length (" + hash.length + ", expected 32!");
}
dsi = "333031300D060960864801650304020105000420" + getHex(hash);
break;
case HashAlgorithmTags.SHA384:
if (hash.length != 48) {
throw new IOException("Bad hash length (" + hash.length + ", expected 48!");
}
dsi = "433041300D060960864801650304020205000430" + getHex(hash);
break;
case HashAlgorithmTags.SHA512:
if (hash.length != 64) {
throw new IOException("Bad hash length (" + hash.length + ", expected 64!");
}
dsi = "533051300D060960864801650304020305000440" + getHex(hash);
break;
default:
throw new IOException("Not supported hash algo!");
}
// Command APDU for PERFORM SECURITY OPERATION: COMPUTE DIGITAL SIGNATURE (page 37)
String apdu =
"002A9E9A" // CLA, INS, P1, P2
+ dsi // digital signature input
+ "00"; // Le
String response = nfcCommunicate(apdu);
// split up response into signature and status
String status = response.substring(response.length()-4);
String signature = response.substring(0, response.length() - 4);
// while we are getting 0x61 status codes, retrieve more data
while (status.substring(0, 2).equals("61")) {
Log.d(Constants.TAG, "requesting more data, status " + status);
// Send GET RESPONSE command
response = nfcCommunicate("00C00000" + status.substring(2));
status = response.substring(response.length()-4);
signature += response.substring(0, response.length()-4);
}
Log.d(Constants.TAG, "final response:" + status);
if (!mPw1ValidForMultipleSignatures) {
mPw1ValidatedForSignature = false;
}
if ( ! "9000".equals(status)) {
throw new CardException("Bad NFC response code: " + status, parseCardStatus(response));
}
// Make sure the signature we received is actually the expected number of bytes long!
if (signature.length() != 256 && signature.length() != 512) {
throw new IOException("Bad signature length! Expected 128 or 256 bytes, got " + signature.length() / 2);
}
return Hex.decode(signature);
}
/**
* Call DECIPHER command
*
* @param encryptedSessionKey the encoded session key
* @return the decoded session key
*/
public byte[] nfcDecryptSessionKey(byte[] encryptedSessionKey) throws IOException {
if (!mPw1ValidatedForDecrypt) {
nfcVerifyPin(0x82); // (Verify PW1 with mode 82 for decryption)
}
String firstApdu = "102a8086fe";
String secondApdu = "002a808603";
String le = "00";
byte[] one = new byte[254];
// leave out first byte:
System.arraycopy(encryptedSessionKey, 1, one, 0, one.length);
byte[] two = new byte[encryptedSessionKey.length - 1 - one.length];
for (int i = 0; i < two.length; i++) {
two[i] = encryptedSessionKey[i + one.length + 1];
}
nfcCommunicate(firstApdu + getHex(one));
String second = nfcCommunicate(secondApdu + getHex(two) + le);
String decryptedSessionKey = getDataField(second);
return Hex.decode(decryptedSessionKey);
}
/** Verifies the user's PW1 or PW3 with the appropriate mode.
*
* @param mode For PW1, this is 0x81 for signing, 0x82 for everything else.
* For PW3 (Admin PIN), mode is 0x83.
*/
public void nfcVerifyPin(int mode) throws IOException {
if (mPin != null || mode == 0x83) {
byte[] pin;
if (mode == 0x83) {
pin = mAdminPin.toStringUnsafe().getBytes();
} else {
pin = mPin.toStringUnsafe().getBytes();
}
// SW1/2 0x9000 is the generic "ok" response, which we expect most of the time.
// See specification, page 51
String accepted = "9000";
String response = nfcTryPin(mode, pin); // login
if (!response.equals(accepted)) {
throw new CardException("Bad PIN!", parseCardStatus(response));
}
if (mode == 0x81) {
mPw1ValidatedForSignature = true;
} else if (mode == 0x82) {
mPw1ValidatedForDecrypt = true;
} else if (mode == 0x83) {
mPw3Validated = true;
}
}
}
/**
* Resets security token, which deletes all keys and data objects.
* This works by entering a wrong PIN and then Admin PIN 4 times respectively.
* Afterwards, the token is reactivated.
*/
public void nfcReset() throws IOException {
String accepted = "9000";
// try wrong PIN 4 times until counter goes to C0
byte[] pin = "XXXXXX".getBytes();
for (int i = 0; i <= 4; i++) {
String response = nfcTryPin(0x81, pin);
if (response.equals(accepted)) { // Should NOT accept!
throw new CardException("Should never happen, XXXXXX has been accepted!", parseCardStatus(response));
}
}
// try wrong Admin PIN 4 times until counter goes to C0
byte[] adminPin = "XXXXXXXX".getBytes();
for (int i = 0; i <= 4; i++) {
String response = nfcTryPin(0x83, adminPin);
if (response.equals(accepted)) { // Should NOT accept!
throw new CardException("Should never happen, XXXXXXXX has been accepted", parseCardStatus(response));
}
}
// reactivate token!
String reactivate1 = "00" + "e6" + "00" + "00";
String reactivate2 = "00" + "44" + "00" + "00";
String response1 = nfcCommunicate(reactivate1);
String response2 = nfcCommunicate(reactivate2);
if (!response1.equals(accepted) || !response2.equals(accepted)) {
throw new CardException("Reactivating failed!", parseCardStatus(response1));
}
}
private String nfcTryPin(int mode, byte[] pin) throws IOException {
// Command APDU for VERIFY command (page 32)
String login =
"00" // CLA
+ "20" // INS
+ "00" // P1
+ String.format("%02x", mode) // P2
+ String.format("%02x", pin.length) // Lc
+ Hex.toHexString(pin);
return nfcCommunicate(login);
}
/** Modifies the user's PW1 or PW3. Before sending, the new PIN will be validated for
* conformance to the token's requirements for key length.
*
* @param pw For PW1, this is 0x81. For PW3 (Admin PIN), mode is 0x83.
* @param newPin The new PW1 or PW3.
*/
public void nfcModifyPin(int pw, byte[] newPin) throws IOException {
final int MAX_PW1_LENGTH_INDEX = 1;
final int MAX_PW3_LENGTH_INDEX = 3;
byte[] pwStatusBytes = nfcGetPwStatusBytes();
if (pw == 0x81) {
if (newPin.length < 6 || newPin.length > pwStatusBytes[MAX_PW1_LENGTH_INDEX]) {
throw new IOException("Invalid PIN length");
}
} else if (pw == 0x83) {
if (newPin.length < 8 || newPin.length > pwStatusBytes[MAX_PW3_LENGTH_INDEX]) {
throw new IOException("Invalid PIN length");
}
} else {
throw new IOException("Invalid PW index for modify PIN operation");
}
byte[] pin;
if (pw == 0x83) {
pin = mAdminPin.toStringUnsafe().getBytes();
} else {
pin = mPin.toStringUnsafe().getBytes();
}
// Command APDU for CHANGE REFERENCE DATA command (page 32)
String changeReferenceDataApdu = "00" // CLA
+ "24" // INS
+ "00" // P1
+ String.format("%02x", pw) // P2
+ String.format("%02x", pin.length + newPin.length) // Lc
+ getHex(pin)
+ getHex(newPin);
String response = nfcCommunicate(changeReferenceDataApdu); // change PIN
if (!response.equals("9000")) {
throw new CardException("Failed to change PIN", parseCardStatus(response));
}
}
/**
* Stores a data object on the token. Automatically validates the proper PIN for the operation.
* Supported for all data objects < 255 bytes in length. Only the cardholder certificate
* (0x7F21) can exceed this length.
*
* @param dataObject The data object to be stored.
* @param data The data to store in the object
*/
public void nfcPutData(int dataObject, byte[] data) throws IOException {
if (data.length > 254) {
throw new IOException("Cannot PUT DATA with length > 254");
}
if (dataObject == 0x0101 || dataObject == 0x0103) {
if (!mPw1ValidatedForDecrypt) {
nfcVerifyPin(0x82); // (Verify PW1 for non-signing operations)
}
} else if (!mPw3Validated) {
nfcVerifyPin(0x83); // (Verify PW3)
}
String putDataApdu = "00" // CLA
+ "DA" // INS
+ String.format("%02x", (dataObject & 0xFF00) >> 8) // P1
+ String.format("%02x", dataObject & 0xFF) // P2
+ String.format("%02x", data.length) // Lc
+ getHex(data);
String response = nfcCommunicate(putDataApdu); // put data
if (!response.equals("9000")) {
throw new CardException("Failed to put data.", parseCardStatus(response));
}
}
/**
* Puts a key on the token in the given slot.
*
* @param slot The slot on the token where the key should be stored:
* 0xB6: Signature Key
* 0xB8: Decipherment Key
* 0xA4: Authentication Key
*/
public void nfcPutKey(int slot, CanonicalizedSecretKey secretKey, Passphrase passphrase)
throws IOException {
if (slot != 0xB6 && slot != 0xB8 && slot != 0xA4) {
throw new IOException("Invalid key slot");
}
RSAPrivateCrtKey crtSecretKey;
try {
secretKey.unlock(passphrase);
crtSecretKey = secretKey.getCrtSecretKey();
} catch (PgpGeneralException e) {
throw new IOException(e.getMessage());
}
// Shouldn't happen; the UI should block the user from getting an incompatible key this far.
if (crtSecretKey.getModulus().bitLength() > 2048) {
throw new IOException("Key too large to export to Security Token.");
}
// Should happen only rarely; all GnuPG keys since 2006 use public exponent 65537.
if (!crtSecretKey.getPublicExponent().equals(new BigInteger("65537"))) {
throw new IOException("Invalid public exponent for smart Security Token.");
}
if (!mPw3Validated) {
nfcVerifyPin(0x83); // (Verify PW3 with mode 83)
}
byte[] header= Hex.decode(
"4D82" + "03A2" // Extended header list 4D82, length of 930 bytes. (page 23)
+ String.format("%02x", slot) + "00" // CRT to indicate targeted key, no length
+ "7F48" + "15" // Private key template 0x7F48, length 21 (decimal, 0x15 hex)
+ "9103" // Public modulus, length 3
+ "928180" // Prime P, length 128
+ "938180" // Prime Q, length 128
+ "948180" // Coefficient (1/q mod p), length 128
+ "958180" // Prime exponent P (d mod (p - 1)), length 128
+ "968180" // Prime exponent Q (d mod (1 - 1)), length 128
+ "97820100" // Modulus, length 256, last item in private key template
+ "5F48" + "820383");// DO 5F48; 899 bytes of concatenated key data will follow
byte[] dataToSend = new byte[934];
byte[] currentKeyObject;
int offset = 0;
System.arraycopy(header, 0, dataToSend, offset, header.length);
offset += header.length;
currentKeyObject = crtSecretKey.getPublicExponent().toByteArray();
System.arraycopy(currentKeyObject, 0, dataToSend, offset, 3);
offset += 3;
// NOTE: For a 2048-bit key, these lengths are fixed. However, bigint includes a leading 0
// in the array to represent sign, so we take care to set the offset to 1 if necessary.
currentKeyObject = crtSecretKey.getPrimeP().toByteArray();
System.arraycopy(currentKeyObject, currentKeyObject.length - 128, dataToSend, offset, 128);
Arrays.fill(currentKeyObject, (byte)0);
offset += 128;
currentKeyObject = crtSecretKey.getPrimeQ().toByteArray();
System.arraycopy(currentKeyObject, currentKeyObject.length - 128, dataToSend, offset, 128);
Arrays.fill(currentKeyObject, (byte)0);
offset += 128;
currentKeyObject = crtSecretKey.getCrtCoefficient().toByteArray();
System.arraycopy(currentKeyObject, currentKeyObject.length - 128, dataToSend, offset, 128);
Arrays.fill(currentKeyObject, (byte)0);
offset += 128;
currentKeyObject = crtSecretKey.getPrimeExponentP().toByteArray();
System.arraycopy(currentKeyObject, currentKeyObject.length - 128, dataToSend, offset, 128);
Arrays.fill(currentKeyObject, (byte)0);
offset += 128;
currentKeyObject = crtSecretKey.getPrimeExponentQ().toByteArray();
System.arraycopy(currentKeyObject, currentKeyObject.length - 128, dataToSend, offset, 128);
Arrays.fill(currentKeyObject, (byte)0);
offset += 128;
currentKeyObject = crtSecretKey.getModulus().toByteArray();
System.arraycopy(currentKeyObject, currentKeyObject.length - 256, dataToSend, offset, 256);
String putKeyCommand = "10DB3FFF";
String lastPutKeyCommand = "00DB3FFF";
// Now we're ready to communicate with the token.
offset = 0;
String response;
while(offset < dataToSend.length) {
int dataRemaining = dataToSend.length - offset;
if (dataRemaining > 254) {
response = nfcCommunicate(
putKeyCommand + "FE" + Hex.toHexString(dataToSend, offset, 254)
);
offset += 254;
} else {
int length = dataToSend.length - offset;
response = nfcCommunicate(
lastPutKeyCommand + String.format("%02x", length)
+ Hex.toHexString(dataToSend, offset, length));
offset += length;
}
if (!response.endsWith("9000")) {
throw new CardException("Key export to Security Token failed", parseCardStatus(response));
}
}
// Clear array with secret data before we return.
Arrays.fill(dataToSend, (byte) 0);
}
/**
* Generates a key on the card in the given slot. If the slot is 0xB6 (the signature key),
* this command also has the effect of resetting the digital signature counter.
* NOTE: This does not set the key fingerprint data object! After calling this command, you
* must construct a public key packet using the returned public key data objects, compute the
* key fingerprint, and store it on the card using: nfcPutData(0xC8, key.getFingerprint())
*
* @param slot The slot on the card where the key should be generated:
* 0xB6: Signature Key
* 0xB8: Decipherment Key
* 0xA4: Authentication Key
* @return the public key data objects, in TLV format. For RSA this will be the public modulus
* (0x81) and exponent (0x82). These may come out of order; proper TLV parsing is required.
*/
public byte[] nfcGenerateKey(int slot) throws IOException {
if (slot != 0xB6 && slot != 0xB8 && slot != 0xA4) {
throw new IOException("Invalid key slot");
}
if (!mPw3Validated) {
nfcVerifyPin(0x83); // (Verify PW3 with mode 83)
}
String generateKeyApdu = "0047800002" + String.format("%02x", slot) + "0000";
String getResponseApdu = "00C00000";
String first = nfcCommunicate(generateKeyApdu);
String second = nfcCommunicate(getResponseApdu);
if (!second.endsWith("9000")) {
throw new IOException("On-card key generation failed");
}
String publicKeyData = getDataField(first) + getDataField(second);
Log.d(Constants.TAG, "Public Key Data Objects: " + publicKeyData);
return Hex.decode(publicKeyData);
}
/**
* Transceive data via NFC encoded as Hex
*/
public String nfcCommunicate(String apdu) throws IOException {
return getHex(mIsoCard.transceive(Hex.decode(apdu)));
}
/**
* Parses out the status word from a JavaCard response string.
*
* @param response A hex string with the response from the token
* @return A short indicating the SW1/SW2, or 0 if a status could not be determined.
*/
short parseCardStatus(String response) {
if (response.length() < 4) {
return 0; // invalid input
}
try {
return Short.parseShort(response.substring(response.length() - 4), 16);
} catch (NumberFormatException e) {
return 0;
}
}
public String getHolderName(String name) {
try {
String slength;
int ilength;
name = name.substring(6);
slength = name.substring(0, 2);
ilength = Integer.parseInt(slength, 16) * 2;
name = name.substring(2, ilength + 2);
name = (new String(Hex.decode(name))).replace('<', ' ');
return name;
} catch (IndexOutOfBoundsException e) {
// try-catch for https://github.com/FluffyKaon/OpenPGP-Card
// Note: This should not happen, but happens with
// https://github.com/FluffyKaon/OpenPGP-Card, thus return an empty string for now!
Log.e(Constants.TAG, "Couldn't get holder name, returning empty string!", e);
return "";
}
}
private String getDataField(String output) {
return output.substring(0, output.length() - 4);
}
public static String getHex(byte[] raw) {
return new String(Hex.encode(raw));
}
public class IsoDepNotSupportedException extends IOException {
public IsoDepNotSupportedException(String detailMessage) {
super(detailMessage);
}
}
public class CardException extends IOException {
private short mResponseCode;
public CardException(String detailMessage, short responseCode) {
super(detailMessage);
mResponseCode = responseCode;
}
public short getResponseCode() {
return mResponseCode;
}
}
private boolean isFidesmoToken() {
if (isNfcConnected()) { // Check if we can still talk to the card
try {
// By trying to select any apps that have the Fidesmo AID prefix we can
// see if it is a Fidesmo device or not
byte[] mSelectResponse = mIsoCard.transceive(Apdu.select(FIDESMO_APPS_AID_PREFIX));
// Compare the status returned by our select with the OK status code
return Apdu.hasStatus(mSelectResponse, Apdu.OK_APDU);
} catch (IOException e) {
Log.e(Constants.TAG, "Card communication failed!", e);
}
}
return false;
}
/**
* Ask user if she wants to install PGP onto her Fidesmo token
*/
private void promptFidesmoPgpInstall() {
FidesmoPgpInstallDialog fidesmoPgpInstallDialog = new FidesmoPgpInstallDialog();
fidesmoPgpInstallDialog.show(getSupportFragmentManager(), "fidesmoPgpInstallDialog");
}
/**
* Show a Dialog to the user informing that Fidesmo App must be installed and with option
* to launch the Google Play store.
*/
private void promptFidesmoAppInstall() {
FidesmoInstallDialog fidesmoInstallDialog = new FidesmoInstallDialog();
fidesmoInstallDialog.show(getSupportFragmentManager(), "fidesmoInstallDialog");
}
/**
* Use the package manager to detect if an application is installed on the phone
* @param uri an URI identifying the application's package
* @return 'true' if the app is installed
*/
private boolean isAndroidAppInstalled(String uri) {
PackageManager mPackageManager = getPackageManager();
boolean mAppInstalled;
try {
mPackageManager.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
mAppInstalled = true;
} catch (PackageManager.NameNotFoundException e) {
Log.e(Constants.TAG, "App not installed on Android device");
mAppInstalled = false;
}
return mAppInstalled;
}
}
| gpl-3.0 |
taylorkelly/BigBrother | src/main/java/me/taylorkelly/bigbrother/commands/VersionCommand.java | 620 | package me.taylorkelly.bigbrother.commands;
import me.taylorkelly.bigbrother.BigBrother;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class VersionCommand implements CommandExecutor {
public VersionCommand(BigBrother plugin) {
}
@Override
public boolean onCommand(CommandSender player, Command arg1, String arg2, String[] arg3) {
player.sendMessage("You're running: " + ChatColor.AQUA.toString() + BigBrother.name + " " + BigBrother.version);
return true;
}
}
| gpl-3.0 |
Arccotangent/pacchat | src/main/java/net/arccotangent/pacchat/crypto/MsgCrypto.java | 3464 | /*
This file is part of PacChat.
PacChat is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PacChat is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PacChat. If not, see <http://www.gnu.org/licenses/>.
*/
package net.arccotangent.pacchat.crypto;
import net.arccotangent.pacchat.logging.Logger;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
public class MsgCrypto {
private static final Logger mc_log = new Logger("CRYPTO/MSGCRYPTO");
public static String encryptAndSignMessage(String msg, RSAPublicKey publicKey, RSAPrivateKey privateKey) {
mc_log.i("Encrypting and signing message.");
mc_log.d("Generating AES key.");
SecretKey aes = AES.generateAESKey();
assert aes != null;
mc_log.d("Encrypting message text.");
byte[] aesCryptedText = AES.encryptBytes(msg.getBytes(), aes);
mc_log.d("Encrypting AES key.");
byte[] cryptedAesKey = RSA.encryptBytes(aes.getEncoded(), publicKey);
mc_log.d("Signing AES key.");
byte[] signature = RSA.signBytes(cryptedAesKey, privateKey);
String cryptedTextB64 = Base64.encodeBase64String(aesCryptedText);
String cryptedKeyB64 = Base64.encodeBase64String(cryptedAesKey);
String signatureB64 = Base64.encodeBase64String(signature);
return cryptedKeyB64 + "\n" + cryptedTextB64 + "\n" + signatureB64;
}
public static PacchatMessage decryptAndVerifyMessage(String cryptedMsg, RSAPrivateKey privateKey, RSAPublicKey publicKey) {
mc_log.i("Decrypting and verifying message.");
String[] messageComponents = cryptedMsg.split("\n");
String cryptedKeyB64 = messageComponents[0];
String cryptedTextB64 = messageComponents[1];
String signatureB64 = messageComponents[2];
mc_log.d("Verifying signature.");
boolean verified = RSA.verifyBytes(Base64.decodeBase64(cryptedKeyB64), Base64.decodeBase64(signatureB64), publicKey);
if (verified)
mc_log.i("Message authenticity verified!");
else {
mc_log.w("**********************************************");
mc_log.w("Message authenticity NOT VERIFIED! Will continue decryption anyway.");
mc_log.w("Someone may be tampering with your connection! This is an unlikely, but not impossible scenario!");
mc_log.w("If you are sure the connection was not tampered with, consider updating the sender's key with the 'getkey' command.");
mc_log.w("**********************************************");
}
mc_log.d("Decrypting AES key.");
DecryptStatus rsa = RSA.decryptBytes(Base64.decodeBase64(cryptedKeyB64), privateKey);
byte[] aesKey = rsa.getMessage();
SecretKey aes = new SecretKeySpec(aesKey, "AES");
mc_log.d("Decrypting message ciphertext.");
DecryptStatus message = AES.decryptBytes(Base64.decodeBase64(cryptedTextB64), aes);
byte[] msg = message.getMessage();
boolean decrypted = message.isDecryptedSuccessfully();
return new PacchatMessage(new String(msg), verified, decrypted);
}
}
| gpl-3.0 |
Wraithaven/Talantra | Talantra/src/net/tal/client/ChunkLoadingOrder.java | 179 | package net.tal.client;
public interface ChunkLoadingOrder
{
public void beginChunkIterator();
public void getNextChunk(int[] i);
public boolean hasNextChunk();
}
| gpl-3.0 |
vandaimer/TrabalhoEs | src/visao/janelas/PainelCarta.java | 665 | package visao.janelas;
import modelo.jogo.CartaAbstrata;
import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JPanel;
import visao.VCarta;
class PainelCarta extends JPanel {
public void mostrarCarta(CartaAbstrata c) {
if (c == null) {
return;
}
VCarta vc = new VCarta(c);
limpar();
Graphics2D g2 = (Graphics2D) getGraphics();
g2.drawImage(vc.obterImagem(), 20, 0, null);
}
public void limpar() {
Graphics2D g2 = (Graphics2D) getGraphics();
g2.setColor(Color.GRAY);
g2.fillRect(0, 0, getWidth(), getHeight());
}
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/ibs/RecreateMassLauncher/src/main/java/ru/ibs/launcher/RecreateMassLauncher.java | 2499 | package ru.ibs.launcher;
import com.google.common.collect.Iterables;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
*
* @author NAnishhenko
*/
//@SpringBootApplication
//@Component
public class RecreateMassLauncher {
private static final int MAX_PROCESSES = 8;
private static final String WAIT = "WAIT";
static boolean isWindowsOS = isWindows();
public static void main(String[] args) throws Exception {
if (args.length == 2 && args[0].equals("-f")) {
File commandsFile = new File(args[1]);
if (commandsFile.exists()) {
String[] commands = new String(Files.readAllBytes(commandsFile.toPath())).split("\n");
List<String> commandList = new ArrayList<>(commands.length);
Collections.addAll(commandList, commands);
List<Process> processList = new ArrayList<Process>(MAX_PROCESSES);
for (List<String> commandsSlice : Iterables.partition(commandList, MAX_PROCESSES)) {
for (String command : commandsSlice) {
String executeString = command.replace("\r", "").replace("\n", "");
if (executeString.equals(WAIT)) {
waitForAllProcesses(processList);
} else {
Process process;
if (isWindowsOS) {
process = Runtime.getRuntime().exec("cmd.exe /c start /wait " + executeString);
} else {
process = Runtime.getRuntime().exec(executeString);
}
processList.add(process);
}
}
waitForAllProcesses(processList);
}
} else {
System.out.println("commandsFile does not exist!");
}
} else {
System.out.println("Usage: -sql [path-to-file with sql generating query]");
}
}
private static void waitForAllProcesses(List<Process> processList) throws InterruptedException {
for (Process process : processList) {
process.waitFor();
}
processList.clear();
}
protected static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().indexOf("win") != -1;
}
}
| gpl-3.0 |
pavelvpster/SourceCodeCrawler | source-code-crawler-step6/src/main/java/org/interactiverobotics/source_code_crawler/step6/IndexMapper.java | 1468 | /*
* IndexMapper.java
*
* Copyright (C) 2016-2018 Pavel Prokhorov (pavelvpster@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.interactiverobotics.source_code_crawler.step6;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
import static org.interactiverobotics.source_code_crawler.common.SourceCodeCrawlerCommon.indexSuperclasses;
/**
* IndexMapper.
*/
public class IndexMapper extends Mapper<Text, Text, Text, Text> {
public void map(final Text key, final Text value, final Context context) {
indexSuperclasses(value.toString(), (superclass, clazz) -> {
try {
context.write(new Text(superclass.trim()), new Text(clazz.trim()));
} catch (final IOException | InterruptedException e) {
}
});
}
}
| gpl-3.0 |
saptarshi1611/Encrypto | Android/app/src/main/java/securedqr/smit/edu/in/app/util/Log.java | 961 | package securedqr.smit.edu.in.app.util;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import android.content.Context;
import android.view.Gravity;
import android.widget.Toast;
/**
* Generate Log file and raise {@link Toast}
*/
public class Log {
/**
* Appends exception messages to Log.txt
* @param e Exception object
* @param context Defines the activity context where the Toast will be displayed
*/
public static void createLog(Exception e, Context context) {
try {
String log=QRCode.filePath+"/log.txt"; //create log file
String s="Oops!\nErrors have been detected\nCheck: "+log;
Toast toast = Toast.makeText(context,s,Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
PrintWriter pw=new PrintWriter((new BufferedWriter(new FileWriter(log, true))));
pw.println("-> "+e.toString());
pw.close();
}catch(Exception e2){}
}
} | gpl-3.0 |
martinmladenov/SoftUni-Solutions | Software Technologies/11. Java Basics - Lab/src/Ex03_3_Integers_Sum.java | 790 | import java.util.Arrays;
import java.util.Scanner;
public class Ex03_3_Integers_Sum {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] arr = Arrays.stream(scan.nextLine().split(" "))
.mapToInt(Integer::parseInt).toArray();
int a = arr[0], b = arr[1], c = arr[2];
if (a + b == c)
System.out.println(Math.min(a, b) + " + " +
Math.max(a, b) + " = " + c);
else if (a + c == b)
System.out.println(Math.min(a, c) + " + " +
Math.max(a, c) + " = " + b);
else if (c + b == a)
System.out.println(Math.min(c, b) + " + " +
Math.max(c, b) + " = " + a);
else System.out.println("No");
}
}
| gpl-3.0 |
yangweijun213/Java | J2SE300/28_51OO/src/cn/bjsxt/oop/testFinal/Animal.java | 439 | package cn.bjsxt.oop.testFinal;
public /*final*/ class Animal { //final修饰类则说明,这个类不能被继承!
public /*final*/ void run(){ //final加到方法前面,意味着该方法不能被子类重写!
System.out.println("跑跑!");
}
}
class Bird extends Animal {
public void run(){
super.run();
System.out.println("我是一个小小小小鸟,飞呀飞不高");
}
}
| gpl-3.0 |
kaibioinfo/sirius | fingerprint_pvalues_oss/src/main/java/de/unijena/bioinf/fingerid/pvalues/Main.java | 4349 |
/*
*
* This file is part of the SIRIUS library for analyzing MS and MS/MS data
*
* Copyright (C) 2013-2020 Kai Dührkop, Markus Fleischauer, Marcus Ludwig, Martin A. Hoffman and Sebastian Böcker,
* Chair of Bioinformatics, Friedrich-Schilller University.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with SIRIUS. If not, see <https://www.gnu.org/licenses/lgpl-3.0.txt>
*/
package de.unijena.bioinf.fingerid.pvalues;
import de.unijena.bioinf.graphUtils.tree.Tree;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
// arg1 is file with fingerprints
// arg2 is tree file
// arg3 is a file with two fingerprints, one POS and one NEG
try {
final FingerprintTree tree = new DotParser().parseFromFile(new File(args[1]));
new ConditionalProbabilitiesEstimator(tree).estimate(readFingerprints(new File(args[0])));
final Iterator<boolean[]> fps = readFingerprints(new File(args[2]));
final boolean[] real = fps.next().clone();
final boolean[] predicted = fps.next();
int distance = 0;
for (Tree<FPVariable> var : tree.nodes) {
final int k = var.getLabel().to;
if (real[k]!=predicted[k]) ++distance;
}
System.out.println(distance);
System.out.println(new TreeDP(tree).computeUnitScores(predicted, distance));
} catch (IOException e) {
e.printStackTrace();
}
}
public static Iterator<boolean[]> readFingerprints(File file) throws IOException {
final BufferedReader reader = new BufferedReader(new FileReader(file));
final String firstLine = reader.readLine();
int column=0;
int fplen=0;
for (int i=0; i < firstLine.length(); ++i) {
// check if current column starts with a lot of ones or zeros
boolean isfp = false;
final int n =firstLine.length()-i;
for (fplen=0; fplen < n; ++fplen) {
final char c = firstLine.charAt(i+fplen);
if (c != '1' && c != '0') break;
}
if (fplen >= 50) {
break;
}
if (firstLine.charAt(i)=='\t') ++column;
}
final int fpcol = column;
final int fplength = fplen;
final boolean[] fp = new boolean[fplength];
return new Iterator<boolean[]>() {
private String currentLine = firstLine;
@Override
public boolean hasNext() {
return currentLine!=null;
}
@Override
public boolean[] next() {
int i=0;
if (fpcol>0) {
int c=fpcol;
for (i=0; i < currentLine.length(); ++i) {
if (currentLine.charAt(i)=='\t') {
if (--c <= 0) {
++i;
break;
}
}
}
}
for (int k=0; k < fplength; ++k) {
fp[k] = currentLine.charAt(i+k)=='1';
}
try {
currentLine = reader.readLine();
if (currentLine==null) reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fp;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
| gpl-3.0 |
peanutydf/edolphin-netframework | base/src/main/java/site/edolphin/compiler/MemoryClassLoader.java | 1204 | package site.edolphin.compiler;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
/**
* Load class from byte[] which is compiled in memory.
*
* @author michael
*/
class MemoryClassLoader extends URLClassLoader {
ClassLoader releatedClassLoader;
// class name to class bytes:
Map<String, byte[]> classBytes = new HashMap<String, byte[]>();
public MemoryClassLoader(Map<String, byte[]> classBytes) {
super(new URL[0], MemoryClassLoader.class.getClassLoader());
this.classBytes.putAll(classBytes);
}
public MemoryClassLoader(Map<String, byte[]> classBytes, ClassLoader releatedClassLoader) {
super(new URL[0], MemoryClassLoader.class.getClassLoader());
this.classBytes.putAll(classBytes);
this.releatedClassLoader = releatedClassLoader;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] buf = classBytes.get(name);
if (buf == null) {
Class<?> res = null;
if (releatedClassLoader != null)
res = releatedClassLoader.loadClass(name);
return res == null? super.findClass(name) : res;
}
classBytes.remove(name);
return defineClass(name, buf, 0, buf.length);
}
}
| gpl-3.0 |
msicsic/jacob | sql/src/main/java/sk/jacob/sql/ddl/TYPE.java | 1405 | package sk.jacob.sql.ddl;
import sk.jacob.sql.dialect.DialectVisitor;
import sk.jacob.sql.dml.DMLClause;
public class TYPE {
public static abstract class Type extends DMLClause {
public final Class columnType;
public Type(Class columnType) {
this.columnType = columnType;
}
}
public static class StringType extends Type {
public final Integer length;
public StringType(Integer length) {
super(String.class);
this.length = length;
}
@Override
public String sql(DialectVisitor visitor) {
return visitor.sql(this);
}
}
public static StringType String(Integer length) {
return new StringType(length);
}
public static class BooleanType extends Type {
public BooleanType() {
super(Boolean.class);
}
@Override
public String sql(DialectVisitor visitor) {
return visitor.sql(this);
}
}
public static BooleanType Boolean() {
return new BooleanType();
}
public static class LongType extends Type {
public LongType() {
super(Long.class);
}
@Override
public String sql(DialectVisitor visitor) {
return visitor.sql(this);
}
}
public static LongType Long() {
return new LongType();
}
}
| gpl-3.0 |
R-Heger/MindstormPrinter | src/de/info_ag/printer/shape/PrintShape3D.java | 932 | package de.info_ag.printer.shape;
import java.util.LinkedList;
public class PrintShape3D {
private LinkedList<PrintShape2D> parts;
private Point startPoint;
private Point end;
public PrintShape3D() {
this(0, 0);
}
public PrintShape3D(int startX, int startY) {
this(new Point(startX, startY));
}
public PrintShape3D(Point startPoint) {
parts = new LinkedList<PrintShape2D>();
this.startPoint = startPoint;
this.end = new Point(0, 0);
}
public void attachLayer(PrintShape2D shape) {
parts.add(shape);
}
public void scale(double scale) {
end.setXCoordinate((int) (end.getXCoordinate() * scale));
end.setYCoordinate((int) (end.getYCoordinate() * scale));
for(int i = 0; i < parts.size(); ++i){
parts.get(i).scale(scale);
}
}
public Point getStartPoint() {
return startPoint;
}
public Point getEnd() {
return end;
}
public LinkedList<PrintShape2D> getParts() {
return parts;
}
}
| gpl-3.0 |
simarpreetsingharora/puautologin | app/src/main/java/simararora/puautologin/widget/WidgetReceiver.java | 1467 | package simararora.puautologin.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import simararora.puautologin.R;
/**
* Created by Simar Arora on 2/14/2015.
* This App is Licensed under GNU General Public License. A copy of this license can be found in the root of this project.
*/
public class WidgetReceiver extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
RemoteViews views;
for (int appWidgetId : appWidgetIds) {
views = new RemoteViews(context.getPackageName(), R.layout.widget);
Intent loginIntent = new Intent(context, LoginService.class);
PendingIntent loginPendingIntent = PendingIntent.getService(context, 0, loginIntent, 0);
Intent logoutIntent = new Intent(context, LogoutService.class);
PendingIntent logoutPendingIntent = PendingIntent.getService(context, 0, logoutIntent, 0);
views.setOnClickPendingIntent(R.id.widgetButtonLogin, loginPendingIntent);
views.setOnClickPendingIntent(R.id.widgetButtonLogout, logoutPendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
| gpl-3.0 |
talek69/curso | stimulsoft/src/com/stimulsoft/report/dictionary/data/StiBytesDataCell.java | 745 | /*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* com.stimulsoft.lib.base64.StiBase64EncoderUtil
*/
package com.stimulsoft.report.dictionary.data;
import com.stimulsoft.lib.base64.StiBase64EncoderUtil;
import com.stimulsoft.report.dictionary.StiDataColumn;
import com.stimulsoft.report.dictionary.data.DataCell;
public class StiBytesDataCell
extends DataCell {
public StiBytesDataCell(StiDataColumn stiDataColumn, byte[] arrby) {
super(stiDataColumn, StiBytesDataCell.getStringValue(arrby));
}
private static String getStringValue(byte[] arrby) {
if (arrby == null) {
return "";
}
return new String(StiBase64EncoderUtil.encode((byte[])arrby));
}
}
| gpl-3.0 |
panduro/karuku | client/src/main/java/generated/CompositeExpression.java | 2710 |
package generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for compositeExpression complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="compositeExpression">
* <complexContent>
* <extension base="{}expression">
* <sequence>
* <element name="firstOperand" type="{}expression" minOccurs="0"/>
* <element name="operation" type="{}operation" minOccurs="0"/>
* <element name="secondOperand" type="{}expression" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "compositeExpression", propOrder = {
"firstOperand",
"operation",
"secondOperand"
})
@XmlRootElement
public class CompositeExpression
extends Expression
{
protected Expression firstOperand;
protected Operation operation;
protected Expression secondOperand;
/**
* Gets the value of the firstOperand property.
*
* @return
* possible object is
* {@link Expression }
*
*/
public Expression getFirstOperand() {
return firstOperand;
}
/**
* Sets the value of the firstOperand property.
*
* @param value
* allowed object is
* {@link Expression }
*
*/
public void setFirstOperand(Expression value) {
this.firstOperand = value;
}
/**
* Gets the value of the operation property.
*
* @return
* possible object is
* {@link Operation }
*
*/
public Operation getOperation() {
return operation;
}
/**
* Sets the value of the operation property.
*
* @param value
* allowed object is
* {@link Operation }
*
*/
public void setOperation(Operation value) {
this.operation = value;
}
/**
* Gets the value of the secondOperand property.
*
* @return
* possible object is
* {@link Expression }
*
*/
public Expression getSecondOperand() {
return secondOperand;
}
/**
* Sets the value of the secondOperand property.
*
* @param value
* allowed object is
* {@link Expression }
*
*/
public void setSecondOperand(Expression value) {
this.secondOperand = value;
}
}
| gpl-3.0 |
robert-olofsson/parjac | src/org/khelekore/parjac/SourceProvider.java | 505 | package org.khelekore.parjac;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.file.Path;
import java.util.Collection;
public interface SourceProvider {
/** Setup for use, will be called before other methods */
void setup (CompilerDiagnosticCollector diagnostics) throws IOException;
/** Get all the input paths */
Collection<Path> getSourcePaths ();
/** Get the source data for a given input path */
CharBuffer getInput (Path path) throws IOException;
} | gpl-3.0 |
McLeodMoores/xl4j | xll-examples/src/main/java/com/mcleodmoores/xl4j/examples/yieldcurve/conventions/OvernightIndexConventionBuilder.java | 2300 | /**
* Copyright (C) 2016 - Present McLeod Moores Software Limited. All rights reserved.
*/
package com.mcleodmoores.xl4j.examples.yieldcurve.conventions;
import com.mcleodmoores.xl4j.v1.util.ArgumentChecker;
import com.opengamma.analytics.financial.instrument.index.OvernightIndex;
import com.opengamma.financial.convention.daycount.DayCount;
import com.opengamma.util.money.Currency;
/**
* Builds a convention for an overnight index.
*/
public final class OvernightIndexConventionBuilder {
/**
* Gets a convention builder.
*
* @return a convention builder
*/
public static OvernightIndexConventionBuilder builder() {
return new OvernightIndexConventionBuilder();
}
private String _name;
private Currency _currency;
private DayCount _dayCount;
private int _publicationLag;
/**
* Restricted constructor.
*/
/* package */OvernightIndexConventionBuilder() {
}
/**
* Sets the convention name.
*
* @param name
* the convention name, not null
* @return the builder
*/
public OvernightIndexConventionBuilder withName(final String name) {
_name = ArgumentChecker.notNull(name, "name");
return this;
}
/**
* Sets the currency.
*
* @param currency
* the currency, not null
* @return the builder
*/
public OvernightIndexConventionBuilder withCurrency(final Currency currency) {
_currency = ArgumentChecker.notNull(currency, "currency");
return this;
}
/**
* Sets the day count.
*
* @param dayCount
* the day count, not null
* @return the builder
*/
public OvernightIndexConventionBuilder withDayCount(final DayCount dayCount) {
_dayCount = ArgumentChecker.notNull(dayCount, "dayCount");
return this;
}
/**
* Sets the publication lag.
*
* @param publicationLag
* the publication lag, not negative
* @return the builder
*/
public OvernightIndexConventionBuilder withPublicationLag(final int publicationLag) {
_publicationLag = ArgumentChecker.notNegative(publicationLag, "publicationLag");
return this;
}
/**
* Builds the convention.
* @return the convention
*/
public OvernightIndex build() {
return new OvernightIndex(_name, _currency, _dayCount, _publicationLag);
}
}
| gpl-3.0 |
ckaestne/CIDE | CIDE_Language_XML_concrete/src/tmp/generated_xhtml/Content_blockquote_Choice118.java | 845 | package tmp.generated_xhtml;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public class Content_blockquote_Choice118 extends Content_blockquote_Choice1 {
public Content_blockquote_Choice118(Element_form element_form, Token firstToken, Token lastToken) {
super(new Property[] {
new PropertyOne<Element_form>("element_form", element_form)
}, firstToken, lastToken);
}
public Content_blockquote_Choice118(Property[] properties, IToken firstToken, IToken lastToken) {
super(properties,firstToken,lastToken);
}
public ASTNode deepCopy() {
return new Content_blockquote_Choice118(cloneProperties(),firstToken,lastToken);
}
public Element_form getElement_form() {
return ((PropertyOne<Element_form>)getProperty("element_form")).getValue();
}
}
| gpl-3.0 |
SonTG/gama | msi.gama.lang.gaml/src-gen/msi/gama/lang/gaml/gaml/impl/S_VarImpl.java | 698 | /**
*/
package msi.gama.lang.gaml.gaml.impl;
import msi.gama.lang.gaml.gaml.GamlPackage;
import msi.gama.lang.gaml.gaml.S_Var;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>SVar</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class S_VarImpl extends S_DefinitionImpl implements S_Var
{
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected S_VarImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return GamlPackage.Literals.SVAR;
}
} //S_VarImpl
| gpl-3.0 |
mateor/pdroid | android-4.0.3_r1/trunk/frameworks/base/services/java/com/android/server/am/ActivityStack.java | 185051 | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.am;
import com.android.internal.app.HeavyWeightSwitcherActivity;
import com.android.internal.os.BatteryStatsImpl;
import com.android.server.am.ActivityManagerService.PendingActivityLaunch;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AppGlobals;
import android.app.IActivityManager;
import android.app.IThumbnailRetriever;
import static android.app.IActivityManager.START_CLASS_NOT_FOUND;
import static android.app.IActivityManager.START_DELIVERED_TO_TOP;
import static android.app.IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
import static android.app.IActivityManager.START_INTENT_NOT_RESOLVED;
import static android.app.IActivityManager.START_PERMISSION_DENIED;
import static android.app.IActivityManager.START_RETURN_INTENT_TO_CALLER;
import static android.app.IActivityManager.START_SUCCESS;
import static android.app.IActivityManager.START_SWITCHES_CANCELED;
import static android.app.IActivityManager.START_TASK_TO_FRONT;
import android.app.IApplicationThread;
import android.app.PendingIntent;
import android.app.ResultInfo;
import android.app.IActivityManager.WaitResult;
import android.content.ComponentName;
import android.content.Context;
import android.content.IIntentSender;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.EventLog;
import android.util.Log;
import android.util.Slog;
import android.view.WindowManagerPolicy;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* State and management of a single stack of activities.
*/
final class ActivityStack {
static final String TAG = ActivityManagerService.TAG;
static final boolean localLOGV = ActivityManagerService.localLOGV;
static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
static final boolean DEBUG_STATES = false;
static final boolean DEBUG_ADD_REMOVE = false;
static final boolean DEBUG_SAVED_STATE = false;
static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
// How long we wait until giving up on the last activity telling us it
// is idle.
static final int IDLE_TIMEOUT = 10*1000;
// How long we wait until giving up on the last activity to pause. This
// is short because it directly impacts the responsiveness of starting the
// next activity.
static final int PAUSE_TIMEOUT = 500;
// How long we can hold the sleep wake lock before giving up.
static final int SLEEP_TIMEOUT = 5*1000;
// How long we can hold the launch wake lock before giving up.
static final int LAUNCH_TIMEOUT = 10*1000;
// How long we wait until giving up on an activity telling us it has
// finished destroying itself.
static final int DESTROY_TIMEOUT = 10*1000;
// How long until we reset a task when the user returns to it. Currently
// disabled.
static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
// How long between activity launches that we consider safe to not warn
// the user about an unexpected activity being launched on top.
static final long START_WARN_TIME = 5*1000;
// Set to false to disable the preview that is shown while a new activity
// is being started.
static final boolean SHOW_APP_STARTING_PREVIEW = true;
enum ActivityState {
INITIALIZING,
RESUMED,
PAUSING,
PAUSED,
STOPPING,
STOPPED,
FINISHING,
DESTROYING,
DESTROYED
}
final ActivityManagerService mService;
final boolean mMainStack;
final Context mContext;
/**
* The back history of all previous (and possibly still
* running) activities. It contains HistoryRecord objects.
*/
final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
/**
* Used for validating app tokens with window manager.
*/
final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();
/**
* List of running activities, sorted by recent usage.
* The first entry in the list is the least recently used.
* It contains HistoryRecord objects.
*/
final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
/**
* List of activities that are waiting for a new activity
* to become visible before completing whatever operation they are
* supposed to do.
*/
final ArrayList<ActivityRecord> mWaitingVisibleActivities
= new ArrayList<ActivityRecord>();
/**
* List of activities that are ready to be stopped, but waiting
* for the next activity to settle down before doing so. It contains
* HistoryRecord objects.
*/
final ArrayList<ActivityRecord> mStoppingActivities
= new ArrayList<ActivityRecord>();
/**
* List of activities that are in the process of going to sleep.
*/
final ArrayList<ActivityRecord> mGoingToSleepActivities
= new ArrayList<ActivityRecord>();
/**
* Animations that for the current transition have requested not to
* be considered for the transition animation.
*/
final ArrayList<ActivityRecord> mNoAnimActivities
= new ArrayList<ActivityRecord>();
/**
* List of activities that are ready to be finished, but waiting
* for the previous activity to settle down before doing so. It contains
* HistoryRecord objects.
*/
final ArrayList<ActivityRecord> mFinishingActivities
= new ArrayList<ActivityRecord>();
/**
* List of people waiting to find out about the next launched activity.
*/
final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
= new ArrayList<IActivityManager.WaitResult>();
/**
* List of people waiting to find out about the next visible activity.
*/
final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
= new ArrayList<IActivityManager.WaitResult>();
/**
* Set when the system is going to sleep, until we have
* successfully paused the current activity and released our wake lock.
* At that point the system is allowed to actually sleep.
*/
final PowerManager.WakeLock mGoingToSleep;
/**
* We don't want to allow the device to go to sleep while in the process
* of launching an activity. This is primarily to allow alarm intent
* receivers to launch an activity and get that to run before the device
* goes back to sleep.
*/
final PowerManager.WakeLock mLaunchingActivity;
/**
* When we are in the process of pausing an activity, before starting the
* next one, this variable holds the activity that is currently being paused.
*/
ActivityRecord mPausingActivity = null;
/**
* This is the last activity that we put into the paused state. This is
* used to determine if we need to do an activity transition while sleeping,
* when we normally hold the top activity paused.
*/
ActivityRecord mLastPausedActivity = null;
/**
* Current activity that is resumed, or null if there is none.
*/
ActivityRecord mResumedActivity = null;
/**
* This is the last activity that has been started. It is only used to
* identify when multiple activities are started at once so that the user
* can be warned they may not be in the activity they think they are.
*/
ActivityRecord mLastStartedActivity = null;
/**
* Set when we know we are going to be calling updateConfiguration()
* soon, so want to skip intermediate config checks.
*/
boolean mConfigWillChange;
/**
* Set to indicate whether to issue an onUserLeaving callback when a
* newly launched activity is being brought in front of us.
*/
boolean mUserLeaving = false;
long mInitialStartTime = 0;
/**
* Set when we have taken too long waiting to go to sleep.
*/
boolean mSleepTimeout = false;
/**
* Dismiss the keyguard after the next activity is displayed?
*/
boolean mDismissKeyguardOnNextActivity = false;
int mThumbnailWidth = -1;
int mThumbnailHeight = -1;
static final int SLEEP_TIMEOUT_MSG = 8;
static final int PAUSE_TIMEOUT_MSG = 9;
static final int IDLE_TIMEOUT_MSG = 10;
static final int IDLE_NOW_MSG = 11;
static final int LAUNCH_TIMEOUT_MSG = 16;
static final int DESTROY_TIMEOUT_MSG = 17;
static final int RESUME_TOP_ACTIVITY_MSG = 19;
final Handler mHandler = new Handler() {
//public Handler() {
// if (localLOGV) Slog.v(TAG, "Handler started!");
//}
public void handleMessage(Message msg) {
switch (msg.what) {
case SLEEP_TIMEOUT_MSG: {
synchronized (mService) {
if (mService.isSleeping()) {
Slog.w(TAG, "Sleep timeout! Sleeping now.");
mSleepTimeout = true;
checkReadyForSleepLocked();
}
}
} break;
case PAUSE_TIMEOUT_MSG: {
ActivityRecord r = (ActivityRecord)msg.obj;
// We don't at this point know if the activity is fullscreen,
// so we need to be conservative and assume it isn't.
Slog.w(TAG, "Activity pause timeout for " + r);
activityPaused(r != null ? r.appToken : null, true);
} break;
case IDLE_TIMEOUT_MSG: {
if (mService.mDidDexOpt) {
mService.mDidDexOpt = false;
Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
nmsg.obj = msg.obj;
mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
return;
}
// We don't at this point know if the activity is fullscreen,
// so we need to be conservative and assume it isn't.
ActivityRecord r = (ActivityRecord)msg.obj;
Slog.w(TAG, "Activity idle timeout for " + r);
activityIdleInternal(r != null ? r.appToken : null, true, null);
} break;
case DESTROY_TIMEOUT_MSG: {
ActivityRecord r = (ActivityRecord)msg.obj;
// We don't at this point know if the activity is fullscreen,
// so we need to be conservative and assume it isn't.
Slog.w(TAG, "Activity destroy timeout for " + r);
activityDestroyed(r != null ? r.appToken : null);
} break;
case IDLE_NOW_MSG: {
ActivityRecord r = (ActivityRecord)msg.obj;
activityIdleInternal(r != null ? r.appToken : null, false, null);
} break;
case LAUNCH_TIMEOUT_MSG: {
if (mService.mDidDexOpt) {
mService.mDidDexOpt = false;
Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
return;
}
synchronized (mService) {
if (mLaunchingActivity.isHeld()) {
Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
mLaunchingActivity.release();
}
}
} break;
case RESUME_TOP_ACTIVITY_MSG: {
synchronized (mService) {
resumeTopActivityLocked(null);
}
} break;
}
}
};
ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
mService = service;
mContext = context;
mMainStack = mainStack;
PowerManager pm =
(PowerManager)context.getSystemService(Context.POWER_SERVICE);
mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
mLaunchingActivity.setReferenceCounted(false);
}
final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
int i = mHistory.size()-1;
while (i >= 0) {
ActivityRecord r = mHistory.get(i);
if (!r.finishing && r != notTop) {
return r;
}
i--;
}
return null;
}
final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
int i = mHistory.size()-1;
while (i >= 0) {
ActivityRecord r = mHistory.get(i);
if (!r.finishing && !r.delayedResume && r != notTop) {
return r;
}
i--;
}
return null;
}
/**
* This is a simplified version of topRunningActivityLocked that provides a number of
* optional skip-over modes. It is intended for use with the ActivityController hook only.
*
* @param token If non-null, any history records matching this token will be skipped.
* @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
*
* @return Returns the HistoryRecord of the next activity on the stack.
*/
final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
int i = mHistory.size()-1;
while (i >= 0) {
ActivityRecord r = mHistory.get(i);
// Note: the taskId check depends on real taskId fields being non-zero
if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)) {
return r;
}
i--;
}
return null;
}
final int indexOfTokenLocked(IBinder token) {
return mHistory.indexOf(ActivityRecord.forToken(token));
}
final int indexOfActivityLocked(ActivityRecord r) {
return mHistory.indexOf(r);
}
final ActivityRecord isInStackLocked(IBinder token) {
ActivityRecord r = ActivityRecord.forToken(token);
if (mHistory.contains(r)) {
return r;
}
return null;
}
private final boolean updateLRUListLocked(ActivityRecord r) {
final boolean hadit = mLRUActivities.remove(r);
mLRUActivities.add(r);
return hadit;
}
/**
* Returns the top activity in any existing task matching the given
* Intent. Returns null if no such task is found.
*/
private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
ComponentName cls = intent.getComponent();
if (info.targetActivity != null) {
cls = new ComponentName(info.packageName, info.targetActivity);
}
TaskRecord cp = null;
final int N = mHistory.size();
for (int i=(N-1); i>=0; i--) {
ActivityRecord r = mHistory.get(i);
if (!r.finishing && r.task != cp
&& r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
cp = r.task;
//Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
// + "/aff=" + r.task.affinity + " to new cls="
// + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
if (r.task.affinity != null) {
if (r.task.affinity.equals(info.taskAffinity)) {
//Slog.i(TAG, "Found matching affinity!");
return r;
}
} else if (r.task.intent != null
&& r.task.intent.getComponent().equals(cls)) {
//Slog.i(TAG, "Found matching class!");
//dump();
//Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
return r;
} else if (r.task.affinityIntent != null
&& r.task.affinityIntent.getComponent().equals(cls)) {
//Slog.i(TAG, "Found matching class!");
//dump();
//Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
return r;
}
}
}
return null;
}
/**
* Returns the first activity (starting from the top of the stack) that
* is the same as the given activity. Returns null if no such activity
* is found.
*/
private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
ComponentName cls = intent.getComponent();
if (info.targetActivity != null) {
cls = new ComponentName(info.packageName, info.targetActivity);
}
final int N = mHistory.size();
for (int i=(N-1); i>=0; i--) {
ActivityRecord r = mHistory.get(i);
if (!r.finishing) {
if (r.intent.getComponent().equals(cls)) {
//Slog.i(TAG, "Found matching class!");
//dump();
//Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
return r;
}
}
}
return null;
}
final void showAskCompatModeDialogLocked(ActivityRecord r) {
Message msg = Message.obtain();
msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
msg.obj = r.task.askedCompatMode ? null : r;
mService.mHandler.sendMessage(msg);
}
final boolean realStartActivityLocked(ActivityRecord r,
ProcessRecord app, boolean andResume, boolean checkConfig)
throws RemoteException {
r.startFreezingScreenLocked(app, 0);
mService.mWindowManager.setAppVisibility(r.appToken, true);
// Have the window manager re-evaluate the orientation of
// the screen based on the new activity order. Note that
// as a result of this, it can call back into the activity
// manager with a new orientation. We don't care about that,
// because the activity is not currently running so we are
// just restarting it anyway.
if (checkConfig) {
Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
mService.mConfiguration,
r.mayFreezeScreenLocked(app) ? r.appToken : null);
mService.updateConfigurationLocked(config, r, false, false);
}
r.app = app;
app.waitingToKill = null;
if (localLOGV) Slog.v(TAG, "Launching: " + r);
int idx = app.activities.indexOf(r);
if (idx < 0) {
app.activities.add(r);
}
mService.updateLruProcessLocked(app, true, true);
try {
if (app.thread == null) {
throw new RemoteException();
}
List<ResultInfo> results = null;
List<Intent> newIntents = null;
if (andResume) {
results = r.results;
newIntents = r.newIntents;
}
if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
+ " icicle=" + r.icicle
+ " with results=" + results + " newIntents=" + newIntents
+ " andResume=" + andResume);
if (andResume) {
EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
System.identityHashCode(r),
r.task.taskId, r.shortComponentName);
}
if (r.isHomeActivity) {
mService.mHomeProcess = app;
}
mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
r.sleeping = false;
r.forceNewConfig = false;
showAskCompatModeDialogLocked(r);
r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
String profileFile = null;
ParcelFileDescriptor profileFd = null;
boolean profileAutoStop = false;
if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
if (mService.mProfileProc == null || mService.mProfileProc == app) {
mService.mProfileProc = app;
profileFile = mService.mProfileFile;
profileFd = mService.mProfileFd;
profileAutoStop = mService.mAutoStopProfiler;
}
}
app.hasShownUi = true;
app.pendingUiClean = true;
if (profileFd != null) {
try {
profileFd = profileFd.dup();
} catch (IOException e) {
profileFd = null;
}
}
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info,
new Configuration(mService.mConfiguration),
r.compat, r.icicle, results, newIntents, !andResume,
mService.isNextTransitionForward(), profileFile, profileFd,
profileAutoStop);
if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
// This may be a heavy-weight process! Note that the package
// manager will ensure that only activity can run in the main
// process of the .apk, which is the only thing that will be
// considered heavy-weight.
if (app.processName.equals(app.info.packageName)) {
if (mService.mHeavyWeightProcess != null
&& mService.mHeavyWeightProcess != app) {
Log.w(TAG, "Starting new heavy weight process " + app
+ " when already running "
+ mService.mHeavyWeightProcess);
}
mService.mHeavyWeightProcess = app;
Message msg = mService.mHandler.obtainMessage(
ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
msg.obj = r;
mService.mHandler.sendMessage(msg);
}
}
} catch (RemoteException e) {
if (r.launchFailed) {
// This is the second time we failed -- finish activity
// and give up.
Slog.e(TAG, "Second failure launching "
+ r.intent.getComponent().flattenToShortString()
+ ", giving up", e);
mService.appDiedLocked(app, app.pid, app.thread);
requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
"2nd-crash");
return false;
}
// This is the first time we failed -- restart process and
// retry.
app.activities.remove(r);
throw e;
}
r.launchFailed = false;
if (updateLRUListLocked(r)) {
Slog.w(TAG, "Activity " + r
+ " being launched, but already in LRU list");
}
if (andResume) {
// As part of the process of launching, ActivityThread also performs
// a resume.
r.state = ActivityState.RESUMED;
if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
+ " (starting new instance)");
r.stopped = false;
mResumedActivity = r;
r.task.touchActiveTime();
if (mMainStack) {
mService.addRecentTaskLocked(r.task);
}
completeResumeLocked(r);
checkReadyForSleepLocked();
if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
r.icicle = null;
r.haveState = false;
} else {
// This activity is not starting in the resumed state... which
// should look like we asked it to pause+stop (but remain visible),
// and it has done so and reported back the current icicle and
// other state.
if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
+ " (starting in stopped state)");
r.state = ActivityState.STOPPED;
r.stopped = true;
}
// Launch the new version setup screen if needed. We do this -after-
// launching the initial activity (that is, home), so that it can have
// a chance to initialize itself while in the background, making the
// switch back to it faster and look better.
if (mMainStack) {
mService.startSetupActivityLocked();
}
return true;
}
private final void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
// Is this activity's application already running?
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid);
if (r.launchTime == 0) {
r.launchTime = SystemClock.uptimeMillis();
if (mInitialStartTime == 0) {
mInitialStartTime = r.launchTime;
}
} else if (mInitialStartTime == 0) {
mInitialStartTime = SystemClock.uptimeMillis();
}
if (app != null && app.thread != null) {
try {
app.addPackage(r.info.packageName);
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
+ r.intent.getComponent().flattenToShortString(), e);
}
// If a dead object exception was thrown -- fall through to
// restart the application.
}
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false);
}
void stopIfSleepingLocked() {
if (mService.isSleeping()) {
if (!mGoingToSleep.isHeld()) {
mGoingToSleep.acquire();
if (mLaunchingActivity.isHeld()) {
mLaunchingActivity.release();
mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
}
}
mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
checkReadyForSleepLocked();
}
}
void awakeFromSleepingLocked() {
mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
mSleepTimeout = false;
if (mGoingToSleep.isHeld()) {
mGoingToSleep.release();
}
// Ensure activities are no longer sleeping.
for (int i=mHistory.size()-1; i>=0; i--) {
ActivityRecord r = mHistory.get(i);
r.setSleeping(false);
}
mGoingToSleepActivities.clear();
}
void activitySleptLocked(ActivityRecord r) {
mGoingToSleepActivities.remove(r);
checkReadyForSleepLocked();
}
void checkReadyForSleepLocked() {
if (!mService.isSleeping()) {
// Do not care.
return;
}
if (!mSleepTimeout) {
if (mResumedActivity != null) {
// Still have something resumed; can't sleep until it is paused.
if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
startPausingLocked(false, true);
return;
}
if (mPausingActivity != null) {
// Still waiting for something to pause; can't sleep yet.
if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
return;
}
if (mStoppingActivities.size() > 0) {
// Still need to tell some activities to stop; can't sleep yet.
if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
+ mStoppingActivities.size() + " activities");
scheduleIdleLocked();
return;
}
ensureActivitiesVisibleLocked(null, 0);
// Make sure any stopped but visible activities are now sleeping.
// This ensures that the activity's onStop() is called.
for (int i=mHistory.size()-1; i>=0; i--) {
ActivityRecord r = mHistory.get(i);
if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
r.setSleeping(true);
}
}
if (mGoingToSleepActivities.size() > 0) {
// Still need to tell some activities to sleep; can't sleep yet.
if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
+ mGoingToSleepActivities.size() + " activities");
return;
}
}
mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
if (mGoingToSleep.isHeld()) {
mGoingToSleep.release();
}
if (mService.mShuttingDown) {
mService.notifyAll();
}
}
public final Bitmap screenshotActivities(ActivityRecord who) {
if (who.noDisplay) {
return null;
}
Resources res = mService.mContext.getResources();
int w = mThumbnailWidth;
int h = mThumbnailHeight;
if (w < 0) {
mThumbnailWidth = w =
res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
mThumbnailHeight = h =
res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
}
if (w > 0) {
return mService.mWindowManager.screenshotApplications(who.appToken, w, h);
}
return null;
}
private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
if (mPausingActivity != null) {
RuntimeException e = new RuntimeException();
Slog.e(TAG, "Trying to pause when pause is already pending for "
+ mPausingActivity, e);
}
ActivityRecord prev = mResumedActivity;
if (prev == null) {
RuntimeException e = new RuntimeException();
Slog.e(TAG, "Trying to pause when nothing is resumed", e);
resumeTopActivityLocked(null);
return;
}
if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
mResumedActivity = null;
mPausingActivity = prev;
mLastPausedActivity = prev;
prev.state = ActivityState.PAUSING;
prev.task.touchActiveTime();
prev.updateThumbnail(screenshotActivities(prev), null);
mService.updateCpuStats();
if (prev.app != null && prev.app.thread != null) {
if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
try {
EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
System.identityHashCode(prev),
prev.shortComponentName);
prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
userLeaving, prev.configChangeFlags);
if (mMainStack) {
mService.updateUsageStats(prev, false);
}
} catch (Exception e) {
// Ignore exception, if process died other code will cleanup.
Slog.w(TAG, "Exception thrown during pause", e);
mPausingActivity = null;
mLastPausedActivity = null;
}
} else {
mPausingActivity = null;
mLastPausedActivity = null;
}
// If we are not going to sleep, we want to ensure the device is
// awake until the next activity is started.
if (!mService.mSleeping && !mService.mShuttingDown) {
mLaunchingActivity.acquire();
if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
// To be safe, don't allow the wake lock to be held for too long.
Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
}
}
if (mPausingActivity != null) {
// Have the window manager pause its key dispatching until the new
// activity has started. If we're pausing the activity just because
// the screen is being turned off and the UI is sleeping, don't interrupt
// key dispatch; the same activity will pick it up again on wakeup.
if (!uiSleeping) {
prev.pauseKeyDispatchingLocked();
} else {
if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
}
// Schedule a pause timeout in case the app doesn't respond.
// We don't give it much time because this directly impacts the
// responsiveness seen by the user.
Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
msg.obj = prev;
mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
} else {
// This activity failed to schedule the
// pause, so just treat it as being paused now.
if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
resumeTopActivityLocked(null);
}
}
final void activityPaused(IBinder token, boolean timeout) {
if (DEBUG_PAUSE) Slog.v(
TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
ActivityRecord r = null;
synchronized (mService) {
int index = indexOfTokenLocked(token);
if (index >= 0) {
r = mHistory.get(index);
mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
if (mPausingActivity == r) {
if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
+ (timeout ? " (due to timeout)" : " (pause complete)"));
r.state = ActivityState.PAUSED;
completePauseLocked();
} else {
EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
System.identityHashCode(r), r.shortComponentName,
mPausingActivity != null
? mPausingActivity.shortComponentName : "(none)");
}
}
}
}
final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
CharSequence description) {
if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
r.icicle = icicle;
r.haveState = true;
r.updateThumbnail(thumbnail, description);
r.stopped = true;
if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
r.state = ActivityState.STOPPED;
if (!r.finishing) {
if (r.configDestroy) {
destroyActivityLocked(r, true, false, "stop-config");
resumeTopActivityLocked(null);
} else {
// Now that this process has stopped, we may want to consider
// it to be the previous app to try to keep around in case
// the user wants to return to it.
ProcessRecord fgApp = null;
if (mResumedActivity != null) {
fgApp = mResumedActivity.app;
} else if (mPausingActivity != null) {
fgApp = mPausingActivity.app;
}
if (r.app != null && fgApp != null && r.app != fgApp
&& r.lastVisibleTime > mService.mPreviousProcessVisibleTime
&& r.app != mService.mHomeProcess) {
mService.mPreviousProcess = r.app;
mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
}
}
}
}
private final void completePauseLocked() {
ActivityRecord prev = mPausingActivity;
if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
if (prev != null) {
if (prev.finishing) {
if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
} else if (prev.app != null) {
if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
if (prev.waitingVisible) {
prev.waitingVisible = false;
mWaitingVisibleActivities.remove(prev);
if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
TAG, "Complete pause, no longer waiting: " + prev);
}
if (prev.configDestroy) {
// The previous is being paused because the configuration
// is changing, which means it is actually stopping...
// To juggle the fact that we are also starting a new
// instance right now, we need to first completely stop
// the current instance before starting the new one.
if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
destroyActivityLocked(prev, true, false, "pause-config");
} else {
mStoppingActivities.add(prev);
if (mStoppingActivities.size() > 3) {
// If we already have a few activities waiting to stop,
// then give up on things going idle and start clearing
// them out.
if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
scheduleIdleLocked();
} else {
checkReadyForSleepLocked();
}
}
} else {
if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
prev = null;
}
mPausingActivity = null;
}
if (!mService.isSleeping()) {
resumeTopActivityLocked(prev);
} else {
checkReadyForSleepLocked();
}
if (prev != null) {
prev.resumeKeyDispatchingLocked();
}
if (prev.app != null && prev.cpuTimeAtResume > 0
&& mService.mBatteryStatsService.isOnBattery()) {
long diff = 0;
synchronized (mService.mProcessStatsThread) {
diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
- prev.cpuTimeAtResume;
}
if (diff > 0) {
BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
synchronized (bsi) {
BatteryStatsImpl.Uid.Proc ps =
bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
prev.info.packageName);
if (ps != null) {
ps.addForegroundTimeLocked(diff);
}
}
}
}
prev.cpuTimeAtResume = 0; // reset it
}
/**
* Once we know that we have asked an application to put an activity in
* the resumed state (either by launching it or explicitly telling it),
* this function updates the rest of our state to match that fact.
*/
private final void completeResumeLocked(ActivityRecord next) {
next.idle = false;
next.results = null;
next.newIntents = null;
// schedule an idle timeout in case the app doesn't do it for us.
Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
msg.obj = next;
mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
if (false) {
// The activity was never told to pause, so just keep
// things going as-is. To maintain our own state,
// we need to emulate it coming back and saying it is
// idle.
msg = mHandler.obtainMessage(IDLE_NOW_MSG);
msg.obj = next;
mHandler.sendMessage(msg);
}
if (mMainStack) {
mService.reportResumedActivityLocked(next);
}
next.clearThumbnail();
if (mMainStack) {
mService.setFocusedActivityLocked(next);
}
next.resumeKeyDispatchingLocked();
ensureActivitiesVisibleLocked(null, 0);
mService.mWindowManager.executeAppTransition();
mNoAnimActivities.clear();
// Mark the point when the activity is resuming
// TODO: To be more accurate, the mark should be before the onCreate,
// not after the onResume. But for subsequent starts, onResume is fine.
if (next.app != null) {
synchronized (mService.mProcessStatsThread) {
next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
}
} else {
next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
}
}
/**
* Make sure that all activities that need to be visible (that is, they
* currently can be seen by the user) actually are.
*/
final void ensureActivitiesVisibleLocked(ActivityRecord top,
ActivityRecord starting, String onlyThisProcess, int configChanges) {
if (DEBUG_VISBILITY) Slog.v(
TAG, "ensureActivitiesVisible behind " + top
+ " configChanges=0x" + Integer.toHexString(configChanges));
// If the top activity is not fullscreen, then we need to
// make sure any activities under it are now visible.
final int count = mHistory.size();
int i = count-1;
while (mHistory.get(i) != top) {
i--;
}
ActivityRecord r;
boolean behindFullscreen = false;
for (; i>=0; i--) {
r = mHistory.get(i);
if (DEBUG_VISBILITY) Slog.v(
TAG, "Make visible? " + r + " finishing=" + r.finishing
+ " state=" + r.state);
if (r.finishing) {
continue;
}
final boolean doThisProcess = onlyThisProcess == null
|| onlyThisProcess.equals(r.processName);
// First: if this is not the current activity being started, make
// sure it matches the current configuration.
if (r != starting && doThisProcess) {
ensureActivityConfigurationLocked(r, 0);
}
if (r.app == null || r.app.thread == null) {
if (onlyThisProcess == null
|| onlyThisProcess.equals(r.processName)) {
// This activity needs to be visible, but isn't even
// running... get it started, but don't resume it
// at this point.
if (DEBUG_VISBILITY) Slog.v(
TAG, "Start and freeze screen for " + r);
if (r != starting) {
r.startFreezingScreenLocked(r.app, configChanges);
}
if (!r.visible) {
if (DEBUG_VISBILITY) Slog.v(
TAG, "Starting and making visible: " + r);
mService.mWindowManager.setAppVisibility(r.appToken, true);
}
if (r != starting) {
startSpecificActivityLocked(r, false, false);
}
}
} else if (r.visible) {
// If this activity is already visible, then there is nothing
// else to do here.
if (DEBUG_VISBILITY) Slog.v(
TAG, "Skipping: already visible at " + r);
r.stopFreezingScreenLocked(false);
} else if (onlyThisProcess == null) {
// This activity is not currently visible, but is running.
// Tell it to become visible.
r.visible = true;
if (r.state != ActivityState.RESUMED && r != starting) {
// If this activity is paused, tell it
// to now show its window.
if (DEBUG_VISBILITY) Slog.v(
TAG, "Making visible and scheduling visibility: " + r);
try {
mService.mWindowManager.setAppVisibility(r.appToken, true);
r.sleeping = false;
r.app.pendingUiClean = true;
r.app.thread.scheduleWindowVisibility(r.appToken, true);
r.stopFreezingScreenLocked(false);
} catch (Exception e) {
// Just skip on any failure; we'll make it
// visible when it next restarts.
Slog.w(TAG, "Exception thrown making visibile: "
+ r.intent.getComponent(), e);
}
}
}
// Aggregate current change flags.
configChanges |= r.configChangeFlags;
if (r.fullscreen) {
// At this point, nothing else needs to be shown
if (DEBUG_VISBILITY) Slog.v(
TAG, "Stopping: fullscreen at " + r);
behindFullscreen = true;
i--;
break;
}
}
// Now for any activities that aren't visible to the user, make
// sure they no longer are keeping the screen frozen.
while (i >= 0) {
r = mHistory.get(i);
if (DEBUG_VISBILITY) Slog.v(
TAG, "Make invisible? " + r + " finishing=" + r.finishing
+ " state=" + r.state
+ " behindFullscreen=" + behindFullscreen);
if (!r.finishing) {
if (behindFullscreen) {
if (r.visible) {
if (DEBUG_VISBILITY) Slog.v(
TAG, "Making invisible: " + r);
r.visible = false;
try {
mService.mWindowManager.setAppVisibility(r.appToken, false);
if ((r.state == ActivityState.STOPPING
|| r.state == ActivityState.STOPPED)
&& r.app != null && r.app.thread != null) {
if (DEBUG_VISBILITY) Slog.v(
TAG, "Scheduling invisibility: " + r);
r.app.thread.scheduleWindowVisibility(r.appToken, false);
}
} catch (Exception e) {
// Just skip on any failure; we'll make it
// visible when it next restarts.
Slog.w(TAG, "Exception thrown making hidden: "
+ r.intent.getComponent(), e);
}
} else {
if (DEBUG_VISBILITY) Slog.v(
TAG, "Already invisible: " + r);
}
} else if (r.fullscreen) {
if (DEBUG_VISBILITY) Slog.v(
TAG, "Now behindFullscreen: " + r);
behindFullscreen = true;
}
}
i--;
}
}
/**
* Version of ensureActivitiesVisible that can easily be called anywhere.
*/
final void ensureActivitiesVisibleLocked(ActivityRecord starting,
int configChanges) {
ActivityRecord r = topRunningActivityLocked(null);
if (r != null) {
ensureActivitiesVisibleLocked(r, starting, null, configChanges);
}
}
/**
* Ensure that the top activity in the stack is resumed.
*
* @param prev The previously resumed activity, for when in the process
* of pausing; can be null to call from elsewhere.
*
* @return Returns true if something is being resumed, or false if
* nothing happened.
*/
final boolean resumeTopActivityLocked(ActivityRecord prev) {
// Find the first activity that is not finishing.
ActivityRecord next = topRunningActivityLocked(null);
// Remember how we'll process this pause/resume situation, and ensure
// that the state is reset however we wind up proceeding.
final boolean userLeaving = mUserLeaving;
mUserLeaving = false;
if (next == null) {
// There are no more activities! Let's just start up the
// Launcher...
if (mMainStack) {
return mService.startHomeActivityLocked();
}
}
next.delayedResume = false;
// If the top activity is the resumed one, nothing to do.
if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
// Make sure we have executed any pending transitions, since there
// should be nothing left to do at this point.
mService.mWindowManager.executeAppTransition();
mNoAnimActivities.clear();
return false;
}
// If we are sleeping, and there is no resumed activity, and the top
// activity is paused, well that is the state we want.
if ((mService.mSleeping || mService.mShuttingDown)
&& mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
// Make sure we have executed any pending transitions, since there
// should be nothing left to do at this point.
mService.mWindowManager.executeAppTransition();
mNoAnimActivities.clear();
return false;
}
// The activity may be waiting for stop, but that is no longer
// appropriate for it.
mStoppingActivities.remove(next);
mGoingToSleepActivities.remove(next);
next.sleeping = false;
mWaitingVisibleActivities.remove(next);
if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
// If we are currently pausing an activity, then don't do anything
// until that is done.
if (mPausingActivity != null) {
if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
return false;
}
// Okay we are now going to start a switch, to 'next'. We may first
// have to pause the current activity, but this is an important point
// where we have decided to go to 'next' so keep track of that.
// XXX "App Redirected" dialog is getting too many false positives
// at this point, so turn off for now.
if (false) {
if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
long now = SystemClock.uptimeMillis();
final boolean inTime = mLastStartedActivity.startTime != 0
&& (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
final int nextUid = next.info.applicationInfo.uid;
if (inTime && lastUid != nextUid
&& lastUid != next.launchedFromUid
&& mService.checkPermission(
android.Manifest.permission.STOP_APP_SWITCHES,
-1, next.launchedFromUid)
!= PackageManager.PERMISSION_GRANTED) {
mService.showLaunchWarningLocked(mLastStartedActivity, next);
} else {
next.startTime = now;
mLastStartedActivity = next;
}
} else {
next.startTime = SystemClock.uptimeMillis();
mLastStartedActivity = next;
}
}
// We need to start pausing the current activity so the top one
// can be resumed...
if (mResumedActivity != null) {
if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
startPausingLocked(userLeaving, false);
return true;
}
if (prev != null && prev != next) {
if (!prev.waitingVisible && next != null && !next.nowVisible) {
prev.waitingVisible = true;
mWaitingVisibleActivities.add(prev);
if (DEBUG_SWITCH) Slog.v(
TAG, "Resuming top, waiting visible to hide: " + prev);
} else {
// The next activity is already visible, so hide the previous
// activity's windows right now so we can show the new one ASAP.
// We only do this if the previous is finishing, which should mean
// it is on top of the one being resumed so hiding it quickly
// is good. Otherwise, we want to do the normal route of allowing
// the resumed activity to be shown so we can decide if the
// previous should actually be hidden depending on whether the
// new one is found to be full-screen or not.
if (prev.finishing) {
mService.mWindowManager.setAppVisibility(prev.appToken, false);
if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
+ prev + ", waitingVisible="
+ (prev != null ? prev.waitingVisible : null)
+ ", nowVisible=" + next.nowVisible);
} else {
if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
+ prev + ", waitingVisible="
+ (prev != null ? prev.waitingVisible : null)
+ ", nowVisible=" + next.nowVisible);
}
}
}
// Launching this app's activity, make sure the app is no longer
// considered stopped.
try {
AppGlobals.getPackageManager().setPackageStoppedState(
next.packageName, false);
} catch (RemoteException e1) {
} catch (IllegalArgumentException e) {
Slog.w(TAG, "Failed trying to unstop package "
+ next.packageName + ": " + e);
}
// We are starting up the next activity, so tell the window manager
// that the previous one will be hidden soon. This way it can know
// to ignore it when computing the desired screen orientation.
if (prev != null) {
if (prev.finishing) {
if (DEBUG_TRANSITION) Slog.v(TAG,
"Prepare close transition: prev=" + prev);
if (mNoAnimActivities.contains(prev)) {
mService.mWindowManager.prepareAppTransition(
WindowManagerPolicy.TRANSIT_NONE, false);
} else {
mService.mWindowManager.prepareAppTransition(prev.task == next.task
? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
: WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
}
mService.mWindowManager.setAppWillBeHidden(prev.appToken);
mService.mWindowManager.setAppVisibility(prev.appToken, false);
} else {
if (DEBUG_TRANSITION) Slog.v(TAG,
"Prepare open transition: prev=" + prev);
if (mNoAnimActivities.contains(next)) {
mService.mWindowManager.prepareAppTransition(
WindowManagerPolicy.TRANSIT_NONE, false);
} else {
mService.mWindowManager.prepareAppTransition(prev.task == next.task
? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
: WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
}
}
if (false) {
mService.mWindowManager.setAppWillBeHidden(prev.appToken);
mService.mWindowManager.setAppVisibility(prev.appToken, false);
}
} else if (mHistory.size() > 1) {
if (DEBUG_TRANSITION) Slog.v(TAG,
"Prepare open transition: no previous");
if (mNoAnimActivities.contains(next)) {
mService.mWindowManager.prepareAppTransition(
WindowManagerPolicy.TRANSIT_NONE, false);
} else {
mService.mWindowManager.prepareAppTransition(
WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
}
}
if (next.app != null && next.app.thread != null) {
if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
// This activity is now becoming visible.
mService.mWindowManager.setAppVisibility(next.appToken, true);
ActivityRecord lastResumedActivity = mResumedActivity;
ActivityState lastState = next.state;
mService.updateCpuStats();
if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
next.state = ActivityState.RESUMED;
mResumedActivity = next;
next.task.touchActiveTime();
if (mMainStack) {
mService.addRecentTaskLocked(next.task);
}
mService.updateLruProcessLocked(next.app, true, true);
updateLRUListLocked(next);
// Have the window manager re-evaluate the orientation of
// the screen based on the new activity order.
boolean updated = false;
if (mMainStack) {
synchronized (mService) {
Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
mService.mConfiguration,
next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
if (config != null) {
next.frozenBeforeDestroy = true;
}
updated = mService.updateConfigurationLocked(config, next, false, false);
}
}
if (!updated) {
// The configuration update wasn't able to keep the existing
// instance of the activity, and instead started a new one.
// We should be all done, but let's just make sure our activity
// is still at the top and schedule another run if something
// weird happened.
ActivityRecord nextNext = topRunningActivityLocked(null);
if (DEBUG_SWITCH) Slog.i(TAG,
"Activity config changed during resume: " + next
+ ", new next: " + nextNext);
if (nextNext != next) {
// Do over!
mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
}
if (mMainStack) {
mService.setFocusedActivityLocked(next);
}
ensureActivitiesVisibleLocked(null, 0);
mService.mWindowManager.executeAppTransition();
mNoAnimActivities.clear();
return true;
}
try {
// Deliver all pending results.
ArrayList a = next.results;
if (a != null) {
final int N = a.size();
if (!next.finishing && N > 0) {
if (DEBUG_RESULTS) Slog.v(
TAG, "Delivering results to " + next
+ ": " + a);
next.app.thread.scheduleSendResult(next.appToken, a);
}
}
if (next.newIntents != null) {
next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
}
EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
System.identityHashCode(next),
next.task.taskId, next.shortComponentName);
next.sleeping = false;
showAskCompatModeDialogLocked(next);
next.app.pendingUiClean = true;
next.app.thread.scheduleResumeActivity(next.appToken,
mService.isNextTransitionForward());
checkReadyForSleepLocked();
} catch (Exception e) {
// Whoops, need to restart this activity!
if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
+ lastState + ": " + next);
next.state = lastState;
mResumedActivity = lastResumedActivity;
Slog.i(TAG, "Restarting because process died: " + next);
if (!next.hasBeenLaunched) {
next.hasBeenLaunched = true;
} else {
if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
mService.mWindowManager.setAppStartingWindow(
next.appToken, next.packageName, next.theme,
mService.compatibilityInfoForPackageLocked(
next.info.applicationInfo),
next.nonLocalizedLabel,
next.labelRes, next.icon, next.windowFlags,
null, true);
}
}
startSpecificActivityLocked(next, true, false);
return true;
}
// From this point on, if something goes wrong there is no way
// to recover the activity.
try {
next.visible = true;
completeResumeLocked(next);
} catch (Exception e) {
// If any exception gets thrown, toss away this
// activity and try the next one.
Slog.w(TAG, "Exception thrown during resume of " + next, e);
requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
"resume-exception");
return true;
}
// Didn't need to use the icicle, and it is now out of date.
if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; didn't need icicle of: " + next);
next.icicle = null;
next.haveState = false;
next.stopped = false;
} else {
// Whoops, need to restart this activity!
if (!next.hasBeenLaunched) {
next.hasBeenLaunched = true;
} else {
if (SHOW_APP_STARTING_PREVIEW) {
mService.mWindowManager.setAppStartingWindow(
next.appToken, next.packageName, next.theme,
mService.compatibilityInfoForPackageLocked(
next.info.applicationInfo),
next.nonLocalizedLabel,
next.labelRes, next.icon, next.windowFlags,
null, true);
}
if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
}
startSpecificActivityLocked(next, true, true);
}
return true;
}
private final void startActivityLocked(ActivityRecord r, boolean newTask,
boolean doResume, boolean keepCurTransition) {
final int NH = mHistory.size();
int addPos = -1;
if (!newTask) {
// If starting in an existing task, find where that is...
boolean startIt = true;
for (int i = NH-1; i >= 0; i--) {
ActivityRecord p = mHistory.get(i);
if (p.finishing) {
continue;
}
if (p.task == r.task) {
// Here it is! Now, if this is not yet visible to the
// user, then just add it without starting; it will
// get started when the user navigates back to it.
addPos = i+1;
if (!startIt) {
if (DEBUG_ADD_REMOVE) {
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
here);
}
mHistory.add(addPos, r);
r.putInHistory();
mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
r.info.screenOrientation, r.fullscreen);
if (VALIDATE_TOKENS) {
validateAppTokensLocked();
}
return;
}
break;
}
if (p.fullscreen) {
startIt = false;
}
}
}
// Place a new activity at top of stack, so it is next to interact
// with the user.
if (addPos < 0) {
addPos = NH;
}
// If we are not placing the new activity frontmost, we do not want
// to deliver the onUserLeaving callback to the actual frontmost
// activity
if (addPos < NH) {
mUserLeaving = false;
if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
}
// Slot the activity into the history stack and proceed
if (DEBUG_ADD_REMOVE) {
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
}
mHistory.add(addPos, r);
r.putInHistory();
r.frontOfTask = newTask;
if (NH > 0) {
// We want to show the starting preview window if we are
// switching to a new task, or the next activity's process is
// not currently running.
boolean showStartingIcon = newTask;
ProcessRecord proc = r.app;
if (proc == null) {
proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
}
if (proc == null || proc.thread == null) {
showStartingIcon = true;
}
if (DEBUG_TRANSITION) Slog.v(TAG,
"Prepare open transition: starting " + r);
if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
mService.mWindowManager.prepareAppTransition(
WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
mNoAnimActivities.add(r);
} else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
mService.mWindowManager.prepareAppTransition(
WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
mNoAnimActivities.remove(r);
} else {
mService.mWindowManager.prepareAppTransition(newTask
? WindowManagerPolicy.TRANSIT_TASK_OPEN
: WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
mNoAnimActivities.remove(r);
}
mService.mWindowManager.addAppToken(
addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
boolean doShow = true;
if (newTask) {
// Even though this activity is starting fresh, we still need
// to reset it to make sure we apply affinities to move any
// existing activities from other tasks in to it.
// If the caller has requested that the target task be
// reset, then do so.
if ((r.intent.getFlags()
&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
resetTaskIfNeededLocked(r, r);
doShow = topRunningNonDelayedActivityLocked(null) == r;
}
}
if (SHOW_APP_STARTING_PREVIEW && doShow) {
// Figure out if we are transitioning from another activity that is
// "has the same starting icon" as the next one. This allows the
// window manager to keep the previous window it had previously
// created, if it still had one.
ActivityRecord prev = mResumedActivity;
if (prev != null) {
// We don't want to reuse the previous starting preview if:
// (1) The current activity is in a different task.
if (prev.task != r.task) prev = null;
// (2) The current activity is already displayed.
else if (prev.nowVisible) prev = null;
}
mService.mWindowManager.setAppStartingWindow(
r.appToken, r.packageName, r.theme,
mService.compatibilityInfoForPackageLocked(
r.info.applicationInfo), r.nonLocalizedLabel,
r.labelRes, r.icon, r.windowFlags,
prev != null ? prev.appToken : null, showStartingIcon);
}
} else {
// If this is the first activity, don't do any fancy animations,
// because there is nothing for it to animate on top of.
mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
r.info.screenOrientation, r.fullscreen);
}
if (VALIDATE_TOKENS) {
validateAppTokensLocked();
}
if (doResume) {
resumeTopActivityLocked(null);
}
}
final void validateAppTokensLocked() {
mValidateAppTokens.clear();
mValidateAppTokens.ensureCapacity(mHistory.size());
for (int i=0; i<mHistory.size(); i++) {
mValidateAppTokens.add(mHistory.get(i).appToken);
}
mService.mWindowManager.validateAppTokens(mValidateAppTokens);
}
/**
* Perform a reset of the given task, if needed as part of launching it.
* Returns the new HistoryRecord at the top of the task.
*/
private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
ActivityRecord newActivity) {
boolean forceReset = (newActivity.info.flags
&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
if (ACTIVITY_INACTIVE_RESET_TIME > 0
&& taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
if ((newActivity.info.flags
&ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
forceReset = true;
}
}
final TaskRecord task = taskTop.task;
// We are going to move through the history list so that we can look
// at each activity 'target' with 'below' either the interesting
// activity immediately below it in the stack or null.
ActivityRecord target = null;
int targetI = 0;
int taskTopI = -1;
int replyChainEnd = -1;
int lastReparentPos = -1;
for (int i=mHistory.size()-1; i>=-1; i--) {
ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
if (below != null && below.finishing) {
continue;
}
if (target == null) {
target = below;
targetI = i;
// If we were in the middle of a reply chain before this
// task, it doesn't appear like the root of the chain wants
// anything interesting, so drop it.
replyChainEnd = -1;
continue;
}
final int flags = target.info.flags;
final boolean finishOnTaskLaunch =
(flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
final boolean allowTaskReparenting =
(flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
if (target.task == task) {
// We are inside of the task being reset... we'll either
// finish this activity, push it out for another task,
// or leave it as-is. We only do this
// for activities that are not the root of the task (since
// if we finish the root, we may no longer have the task!).
if (taskTopI < 0) {
taskTopI = targetI;
}
if (below != null && below.task == task) {
final boolean clearWhenTaskReset =
(target.intent.getFlags()
&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
// If this activity is sending a reply to a previous
// activity, we can't do anything with it now until
// we reach the start of the reply chain.
// XXX note that we are assuming the result is always
// to the previous activity, which is almost always
// the case but we really shouldn't count on.
if (replyChainEnd < 0) {
replyChainEnd = targetI;
}
} else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
&& target.taskAffinity != null
&& !target.taskAffinity.equals(task.affinity)) {
// If this activity has an affinity for another
// task, then we need to move it out of here. We will
// move it as far out of the way as possible, to the
// bottom of the activity stack. This also keeps it
// correctly ordered with any activities we previously
// moved.
ActivityRecord p = mHistory.get(0);
if (target.taskAffinity != null
&& target.taskAffinity.equals(p.task.affinity)) {
// If the activity currently at the bottom has the
// same task affinity as the one we are moving,
// then merge it into the same task.
target.setTask(p.task, p.thumbHolder, false);
if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
+ " out to bottom task " + p.task);
} else {
mService.mCurTask++;
if (mService.mCurTask <= 0) {
mService.mCurTask = 1;
}
target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
null, false);
target.task.affinityIntent = target.intent;
if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
+ " out to new task " + target.task);
}
mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
if (replyChainEnd < 0) {
replyChainEnd = targetI;
}
int dstPos = 0;
ThumbnailHolder curThumbHolder = target.thumbHolder;
for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
p = mHistory.get(srcPos);
if (p.finishing) {
continue;
}
if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
+ " out to target's task " + target.task);
p.setTask(target.task, curThumbHolder, false);
curThumbHolder = p.thumbHolder;
if (DEBUG_ADD_REMOVE) {
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
+ dstPos, here);
}
mHistory.remove(srcPos);
mHistory.add(dstPos, p);
mService.mWindowManager.moveAppToken(dstPos, p.appToken);
mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
dstPos++;
if (VALIDATE_TOKENS) {
validateAppTokensLocked();
}
i++;
}
if (taskTop == p) {
taskTop = below;
}
if (taskTopI == replyChainEnd) {
taskTopI = -1;
}
replyChainEnd = -1;
} else if (forceReset || finishOnTaskLaunch
|| clearWhenTaskReset) {
// If the activity should just be removed -- either
// because it asks for it, or the task should be
// cleared -- then finish it and anything that is
// part of its reply chain.
if (clearWhenTaskReset) {
// In this case, we want to finish this activity
// and everything above it, so be sneaky and pretend
// like these are all in the reply chain.
replyChainEnd = targetI+1;
while (replyChainEnd < mHistory.size() &&
(mHistory.get(
replyChainEnd)).task == task) {
replyChainEnd++;
}
replyChainEnd--;
} else if (replyChainEnd < 0) {
replyChainEnd = targetI;
}
ActivityRecord p = null;
for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
p = mHistory.get(srcPos);
if (p.finishing) {
continue;
}
if (finishActivityLocked(p, srcPos,
Activity.RESULT_CANCELED, null, "reset")) {
replyChainEnd--;
srcPos--;
}
}
if (taskTop == p) {
taskTop = below;
}
if (taskTopI == replyChainEnd) {
taskTopI = -1;
}
replyChainEnd = -1;
} else {
// If we were in the middle of a chain, well the
// activity that started it all doesn't want anything
// special, so leave it all as-is.
replyChainEnd = -1;
}
} else {
// Reached the bottom of the task -- any reply chain
// should be left as-is.
replyChainEnd = -1;
}
} else if (target.resultTo != null && (below == null
|| below.task == target.task)) {
// If this activity is sending a reply to a previous
// activity, we can't do anything with it now until
// we reach the start of the reply chain.
// XXX note that we are assuming the result is always
// to the previous activity, which is almost always
// the case but we really shouldn't count on.
if (replyChainEnd < 0) {
replyChainEnd = targetI;
}
} else if (taskTopI >= 0 && allowTaskReparenting
&& task.affinity != null
&& task.affinity.equals(target.taskAffinity)) {
// We are inside of another task... if this activity has
// an affinity for our task, then either remove it if we are
// clearing or move it over to our task. Note that
// we currently punt on the case where we are resetting a
// task that is not at the top but who has activities above
// with an affinity to it... this is really not a normal
// case, and we will need to later pull that task to the front
// and usually at that point we will do the reset and pick
// up those remaining activities. (This only happens if
// someone starts an activity in a new task from an activity
// in a task that is not currently on top.)
if (forceReset || finishOnTaskLaunch) {
if (replyChainEnd < 0) {
replyChainEnd = targetI;
}
ActivityRecord p = null;
if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
+ targetI + " to " + replyChainEnd);
for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
p = mHistory.get(srcPos);
if (p.finishing) {
continue;
}
if (finishActivityLocked(p, srcPos,
Activity.RESULT_CANCELED, null, "reset")) {
taskTopI--;
lastReparentPos--;
replyChainEnd--;
srcPos--;
}
}
replyChainEnd = -1;
} else {
if (replyChainEnd < 0) {
replyChainEnd = targetI;
}
if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
+ targetI + " to " + replyChainEnd);
for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
ActivityRecord p = mHistory.get(srcPos);
if (p.finishing) {
continue;
}
if (lastReparentPos < 0) {
lastReparentPos = taskTopI;
taskTop = p;
} else {
lastReparentPos--;
}
if (DEBUG_ADD_REMOVE) {
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
+ lastReparentPos, here);
}
mHistory.remove(srcPos);
p.setTask(task, null, false);
mHistory.add(lastReparentPos, p);
if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
+ " from " + srcPos + " to " + lastReparentPos
+ " in to resetting task " + task);
mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
if (VALIDATE_TOKENS) {
validateAppTokensLocked();
}
}
replyChainEnd = -1;
// Now we've moved it in to place... but what if this is
// a singleTop activity and we have put it on top of another
// instance of the same activity? Then we drop the instance
// below so it remains singleTop.
if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
for (int j=lastReparentPos-1; j>=0; j--) {
ActivityRecord p = mHistory.get(j);
if (p.finishing) {
continue;
}
if (p.intent.getComponent().equals(target.intent.getComponent())) {
if (finishActivityLocked(p, j,
Activity.RESULT_CANCELED, null, "replace")) {
taskTopI--;
lastReparentPos--;
}
}
}
}
}
} else if (below != null && below.task != target.task) {
// We hit the botton of a task; the reply chain can't
// pass through it.
replyChainEnd = -1;
}
target = below;
targetI = i;
}
return taskTop;
}
/**
* Perform clear operation as requested by
* {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
* stack to the given task, then look for
* an instance of that activity in the stack and, if found, finish all
* activities on top of it and return the instance.
*
* @param newR Description of the new activity being started.
* @return Returns the old activity that should be continued to be used,
* or null if none was found.
*/
private final ActivityRecord performClearTaskLocked(int taskId,
ActivityRecord newR, int launchFlags) {
int i = mHistory.size();
// First find the requested task.
while (i > 0) {
i--;
ActivityRecord r = mHistory.get(i);
if (r.task.taskId == taskId) {
i++;
break;
}
}
// Now clear it.
while (i > 0) {
i--;
ActivityRecord r = mHistory.get(i);
if (r.finishing) {
continue;
}
if (r.task.taskId != taskId) {
return null;
}
if (r.realActivity.equals(newR.realActivity)) {
// Here it is! Now finish everything in front...
ActivityRecord ret = r;
while (i < (mHistory.size()-1)) {
i++;
r = mHistory.get(i);
if (r.task.taskId != taskId) {
break;
}
if (r.finishing) {
continue;
}
if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
null, "clear")) {
i--;
}
}
// Finally, if this is a normal launch mode (that is, not
// expecting onNewIntent()), then we will finish the current
// instance of the activity so a new fresh one can be started.
if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
&& (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
if (!ret.finishing) {
int index = indexOfTokenLocked(ret.appToken);
if (index >= 0) {
finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
null, "clear");
}
return null;
}
}
return ret;
}
}
return null;
}
/**
* Completely remove all activities associated with an existing
* task starting at a specified index.
*/
private final void performClearTaskAtIndexLocked(int taskId, int i) {
while (i < mHistory.size()) {
ActivityRecord r = mHistory.get(i);
if (r.task.taskId != taskId) {
// Whoops hit the end.
return;
}
if (r.finishing) {
i++;
continue;
}
if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
null, "clear")) {
i++;
}
}
}
/**
* Completely remove all activities associated with an existing task.
*/
private final void performClearTaskLocked(int taskId) {
int i = mHistory.size();
// First find the requested task.
while (i > 0) {
i--;
ActivityRecord r = mHistory.get(i);
if (r.task.taskId == taskId) {
i++;
break;
}
}
// Now find the start and clear it.
while (i > 0) {
i--;
ActivityRecord r = mHistory.get(i);
if (r.finishing) {
continue;
}
if (r.task.taskId != taskId) {
// We hit the bottom. Now finish it all...
performClearTaskAtIndexLocked(taskId, i+1);
return;
}
}
}
/**
* Find the activity in the history stack within the given task. Returns
* the index within the history at which it's found, or < 0 if not found.
*/
private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
int i = mHistory.size();
while (i > 0) {
i--;
ActivityRecord candidate = mHistory.get(i);
if (candidate.task.taskId != task) {
break;
}
if (candidate.realActivity.equals(r.realActivity)) {
return i;
}
}
return -1;
}
/**
* Reorder the history stack so that the activity at the given index is
* brought to the front.
*/
private final ActivityRecord moveActivityToFrontLocked(int where) {
ActivityRecord newTop = mHistory.remove(where);
int top = mHistory.size();
ActivityRecord oldTop = mHistory.get(top-1);
if (DEBUG_ADD_REMOVE) {
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
+ top, here);
}
mHistory.add(top, newTop);
oldTop.frontOfTask = false;
newTop.frontOfTask = true;
return newTop;
}
final int startActivityLocked(IApplicationThread caller,
Intent intent, String resolvedType,
Uri[] grantedUriPermissions,
int grantedMode, ActivityInfo aInfo, IBinder resultTo,
String resultWho, int requestCode,
int callingPid, int callingUid, boolean onlyIfNeeded,
boolean componentSpecified, ActivityRecord[] outActivity) {
int err = START_SUCCESS;
ProcessRecord callerApp = null;
if (caller != null) {
callerApp = mService.getRecordForAppLocked(caller);
if (callerApp != null) {
callingPid = callerApp.pid;
callingUid = callerApp.info.uid;
} else {
Slog.w(TAG, "Unable to find app for caller " + caller
+ " (pid=" + callingPid + ") when starting: "
+ intent.toString());
err = START_PERMISSION_DENIED;
}
}
if (err == START_SUCCESS) {
Slog.i(TAG, "START {" + intent.toShortString(true, true, true) + "} from pid "
+ (callerApp != null ? callerApp.pid : callingPid));
}
ActivityRecord sourceRecord = null;
ActivityRecord resultRecord = null;
if (resultTo != null) {
int index = indexOfTokenLocked(resultTo);
if (DEBUG_RESULTS) Slog.v(
TAG, "Will send result to " + resultTo + " (index " + index + ")");
if (index >= 0) {
sourceRecord = mHistory.get(index);
if (requestCode >= 0 && !sourceRecord.finishing) {
resultRecord = sourceRecord;
}
}
}
int launchFlags = intent.getFlags();
if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
&& sourceRecord != null) {
// Transfer the result target from the source activity to the new
// one being started, including any failures.
if (requestCode >= 0) {
return START_FORWARD_AND_REQUEST_CONFLICT;
}
resultRecord = sourceRecord.resultTo;
resultWho = sourceRecord.resultWho;
requestCode = sourceRecord.requestCode;
sourceRecord.resultTo = null;
if (resultRecord != null) {
resultRecord.removeResultsLocked(
sourceRecord, resultWho, requestCode);
}
}
if (err == START_SUCCESS && intent.getComponent() == null) {
// We couldn't find a class that can handle the given Intent.
// That's the end of that!
err = START_INTENT_NOT_RESOLVED;
}
if (err == START_SUCCESS && aInfo == null) {
// We couldn't find the specific class specified in the Intent.
// Also the end of the line.
err = START_CLASS_NOT_FOUND;
}
if (err != START_SUCCESS) {
if (resultRecord != null) {
sendActivityResultLocked(-1,
resultRecord, resultWho, requestCode,
Activity.RESULT_CANCELED, null);
}
mDismissKeyguardOnNextActivity = false;
return err;
}
final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
callingUid, aInfo.applicationInfo.uid, aInfo.exported);
if (perm != PackageManager.PERMISSION_GRANTED) {
if (resultRecord != null) {
sendActivityResultLocked(-1,
resultRecord, resultWho, requestCode,
Activity.RESULT_CANCELED, null);
}
mDismissKeyguardOnNextActivity = false;
String msg;
if (!aInfo.exported) {
msg = "Permission Denial: starting " + intent.toString()
+ " from " + callerApp + " (pid=" + callingPid
+ ", uid=" + callingUid + ")"
+ " not exported from uid " + aInfo.applicationInfo.uid;
} else {
msg = "Permission Denial: starting " + intent.toString()
+ " from " + callerApp + " (pid=" + callingPid
+ ", uid=" + callingUid + ")"
+ " requires " + aInfo.permission;
}
Slog.w(TAG, msg);
throw new SecurityException(msg);
}
if (mMainStack) {
if (mService.mController != null) {
boolean abort = false;
try {
// The Intent we give to the watcher has the extra data
// stripped off, since it can contain private information.
Intent watchIntent = intent.cloneFilter();
abort = !mService.mController.activityStarting(watchIntent,
aInfo.applicationInfo.packageName);
} catch (RemoteException e) {
mService.mController = null;
}
if (abort) {
if (resultRecord != null) {
sendActivityResultLocked(-1,
resultRecord, resultWho, requestCode,
Activity.RESULT_CANCELED, null);
}
// We pretend to the caller that it was really started, but
// they will just get a cancel result.
mDismissKeyguardOnNextActivity = false;
return START_SUCCESS;
}
}
}
ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
intent, resolvedType, aInfo, mService.mConfiguration,
resultRecord, resultWho, requestCode, componentSpecified);
if (outActivity != null) {
outActivity[0] = r;
}
if (mMainStack) {
if (mResumedActivity == null
|| mResumedActivity.info.applicationInfo.uid != callingUid) {
if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
PendingActivityLaunch pal = new PendingActivityLaunch();
pal.r = r;
pal.sourceRecord = sourceRecord;
pal.grantedUriPermissions = grantedUriPermissions;
pal.grantedMode = grantedMode;
pal.onlyIfNeeded = onlyIfNeeded;
mService.mPendingActivityLaunches.add(pal);
mDismissKeyguardOnNextActivity = false;
return START_SWITCHES_CANCELED;
}
}
if (mService.mDidAppSwitch) {
// This is the second allowed switch since we stopped switches,
// so now just generally allow switches. Use case: user presses
// home (switches disabled, switch to home, mDidAppSwitch now true);
// user taps a home icon (coming from home so allowed, we hit here
// and now allow anyone to switch again).
mService.mAppSwitchesAllowedTime = 0;
} else {
mService.mDidAppSwitch = true;
}
mService.doPendingActivityLaunchesLocked(false);
}
err = startActivityUncheckedLocked(r, sourceRecord,
grantedUriPermissions, grantedMode, onlyIfNeeded, true);
if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
// Someone asked to have the keyguard dismissed on the next
// activity start, but we are not actually doing an activity
// switch... just dismiss the keyguard now, because we
// probably want to see whatever is behind it.
mDismissKeyguardOnNextActivity = false;
mService.mWindowManager.dismissKeyguard();
}
return err;
}
final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
if ((launchFlags &
(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
== (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
// Caller wants to appear on home activity, so before starting
// their own activity we will bring home to the front.
moveHomeToFrontLocked();
}
}
final int startActivityUncheckedLocked(ActivityRecord r,
ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
int grantedMode, boolean onlyIfNeeded, boolean doResume) {
final Intent intent = r.intent;
final int callingUid = r.launchedFromUid;
int launchFlags = intent.getFlags();
// We'll invoke onUserLeaving before onPause only if the launching
// activity did not explicitly state that this is an automated launch.
mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
if (DEBUG_USER_LEAVING) Slog.v(TAG,
"startActivity() => mUserLeaving=" + mUserLeaving);
// If the caller has asked not to resume at this point, we make note
// of this in the record so that we can skip it when trying to find
// the top running activity.
if (!doResume) {
r.delayedResume = true;
}
ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
!= 0 ? r : null;
// If the onlyIfNeeded flag is set, then we can do this if the activity
// being launched is the same as the one making the call... or, as
// a special case, if we do not know the caller then we count the
// current top activity as the caller.
if (onlyIfNeeded) {
ActivityRecord checkedCaller = sourceRecord;
if (checkedCaller == null) {
checkedCaller = topRunningNonDelayedActivityLocked(notTop);
}
if (!checkedCaller.realActivity.equals(r.realActivity)) {
// Caller is not the same as launcher, so always needed.
onlyIfNeeded = false;
}
}
if (sourceRecord == null) {
// This activity is not being started from another... in this
// case we -always- start a new task.
if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
+ intent);
launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
}
} else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
// The original activity who is starting us is running as a single
// instance... this new activity it is starting must go on its
// own task.
launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
} else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
// The activity being started is a single instance... it always
// gets launched into its own task.
launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
}
if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
// For whatever reason this activity is being launched into a new
// task... yet the caller has requested a result back. Well, that
// is pretty messed up, so instead immediately send back a cancel
// and let the new task continue launched as normal without a
// dependency on its originator.
Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
sendActivityResultLocked(-1,
r.resultTo, r.resultWho, r.requestCode,
Activity.RESULT_CANCELED, null);
r.resultTo = null;
}
boolean addingToTask = false;
TaskRecord reuseTask = null;
if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
(launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
// If bring to front is requested, and no result is requested, and
// we can find a task that was started with this same
// component, then instead of launching bring that one to the front.
if (r.resultTo == null) {
// See if there is a task to bring to the front. If this is
// a SINGLE_INSTANCE activity, there can be one and only one
// instance of it in the history, and it is always in its own
// unique task, so we do a special search.
ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
? findTaskLocked(intent, r.info)
: findActivityLocked(intent, r.info);
if (taskTop != null) {
if (taskTop.task.intent == null) {
// This task was started because of movement of
// the activity based on affinity... now that we
// are actually launching it, we can assign the
// base intent.
taskTop.task.setIntent(intent, r.info);
}
// If the target task is not in the front, then we need
// to bring it to the front... except... well, with
// SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
// to have the same behavior as if a new instance was
// being started, which means not bringing it to the front
// if the caller is not itself in the front.
ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
if (curTop != null && curTop.task != taskTop.task) {
r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
boolean callerAtFront = sourceRecord == null
|| curTop.task == sourceRecord.task;
if (callerAtFront) {
// We really do want to push this one into the
// user's face, right now.
moveHomeToFrontFromLaunchLocked(launchFlags);
moveTaskToFrontLocked(taskTop.task, r);
}
}
// If the caller has requested that the target task be
// reset, then do so.
if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
taskTop = resetTaskIfNeededLocked(taskTop, r);
}
if (onlyIfNeeded) {
// We don't need to start a new activity, and
// the client said not to do anything if that
// is the case, so this is it! And for paranoia, make
// sure we have correctly resumed the top activity.
if (doResume) {
resumeTopActivityLocked(null);
}
return START_RETURN_INTENT_TO_CALLER;
}
if ((launchFlags &
(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
== (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
// The caller has requested to completely replace any
// existing task with its new activity. Well that should
// not be too hard...
reuseTask = taskTop.task;
performClearTaskLocked(taskTop.task.taskId);
reuseTask.setIntent(r.intent, r.info);
} else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
// In this situation we want to remove all activities
// from the task up to the one being started. In most
// cases this means we are resetting the task to its
// initial state.
ActivityRecord top = performClearTaskLocked(
taskTop.task.taskId, r, launchFlags);
if (top != null) {
if (top.frontOfTask) {
// Activity aliases may mean we use different
// intents for the top activity, so make sure
// the task now has the identity of the new
// intent.
top.task.setIntent(r.intent, r.info);
}
logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
top.deliverNewIntentLocked(callingUid, r.intent);
} else {
// A special case: we need to
// start the activity because it is not currently
// running, and the caller has asked to clear the
// current task to have this activity at the top.
addingToTask = true;
// Now pretend like this activity is being started
// by the top of its task, so it is put in the
// right place.
sourceRecord = taskTop;
}
} else if (r.realActivity.equals(taskTop.task.realActivity)) {
// In this case the top activity on the task is the
// same as the one being launched, so we take that
// as a request to bring the task to the foreground.
// If the top activity in the task is the root
// activity, deliver this new intent to it if it
// desires.
if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
&& taskTop.realActivity.equals(r.realActivity)) {
logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
if (taskTop.frontOfTask) {
taskTop.task.setIntent(r.intent, r.info);
}
taskTop.deliverNewIntentLocked(callingUid, r.intent);
} else if (!r.intent.filterEquals(taskTop.task.intent)) {
// In this case we are launching the root activity
// of the task, but with a different intent. We
// should start a new instance on top.
addingToTask = true;
sourceRecord = taskTop;
}
} else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
// In this case an activity is being launched in to an
// existing task, without resetting that task. This
// is typically the situation of launching an activity
// from a notification or shortcut. We want to place
// the new activity on top of the current task.
addingToTask = true;
sourceRecord = taskTop;
} else if (!taskTop.task.rootWasReset) {
// In this case we are launching in to an existing task
// that has not yet been started from its front door.
// The current task has been brought to the front.
// Ideally, we'd probably like to place this new task
// at the bottom of its stack, but that's a little hard
// to do with the current organization of the code so
// for now we'll just drop it.
taskTop.task.setIntent(r.intent, r.info);
}
if (!addingToTask && reuseTask == null) {
// We didn't do anything... but it was needed (a.k.a., client
// don't use that intent!) And for paranoia, make
// sure we have correctly resumed the top activity.
if (doResume) {
resumeTopActivityLocked(null);
}
return START_TASK_TO_FRONT;
}
}
}
}
//String uri = r.intent.toURI();
//Intent intent2 = new Intent(uri);
//Slog.i(TAG, "Given intent: " + r.intent);
//Slog.i(TAG, "URI is: " + uri);
//Slog.i(TAG, "To intent: " + intent2);
if (r.packageName != null) {
// If the activity being launched is the same as the one currently
// at the top, then we need to check if it should only be launched
// once.
ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
if (top != null && r.resultTo == null) {
if (top.realActivity.equals(r.realActivity)) {
if (top.app != null && top.app.thread != null) {
if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
// For paranoia, make sure we have correctly
// resumed the top activity.
if (doResume) {
resumeTopActivityLocked(null);
}
if (onlyIfNeeded) {
// We don't need to start a new activity, and
// the client said not to do anything if that
// is the case, so this is it!
return START_RETURN_INTENT_TO_CALLER;
}
top.deliverNewIntentLocked(callingUid, r.intent);
return START_DELIVERED_TO_TOP;
}
}
}
}
} else {
if (r.resultTo != null) {
sendActivityResultLocked(-1,
r.resultTo, r.resultWho, r.requestCode,
Activity.RESULT_CANCELED, null);
}
return START_CLASS_NOT_FOUND;
}
boolean newTask = false;
boolean keepCurTransition = false;
// Should this be considered a new task?
if (r.resultTo == null && !addingToTask
&& (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
if (reuseTask == null) {
// todo: should do better management of integers.
mService.mCurTask++;
if (mService.mCurTask <= 0) {
mService.mCurTask = 1;
}
r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
+ " in new task " + r.task);
} else {
r.setTask(reuseTask, reuseTask, true);
}
newTask = true;
moveHomeToFrontFromLaunchLocked(launchFlags);
} else if (sourceRecord != null) {
if (!addingToTask &&
(launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
// In this case, we are adding the activity to an existing
// task, but the caller has asked to clear that task if the
// activity is already running.
ActivityRecord top = performClearTaskLocked(
sourceRecord.task.taskId, r, launchFlags);
keepCurTransition = true;
if (top != null) {
logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
top.deliverNewIntentLocked(callingUid, r.intent);
// For paranoia, make sure we have correctly
// resumed the top activity.
if (doResume) {
resumeTopActivityLocked(null);
}
return START_DELIVERED_TO_TOP;
}
} else if (!addingToTask &&
(launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
// In this case, we are launching an activity in our own task
// that may already be running somewhere in the history, and
// we want to shuffle it to the front of the stack if so.
int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
if (where >= 0) {
ActivityRecord top = moveActivityToFrontLocked(where);
logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
top.deliverNewIntentLocked(callingUid, r.intent);
if (doResume) {
resumeTopActivityLocked(null);
}
return START_DELIVERED_TO_TOP;
}
}
// An existing activity is starting this new activity, so we want
// to keep the new one in the same task as the one that is starting
// it.
r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
+ " in existing task " + r.task);
} else {
// This not being started from an existing activity, and not part
// of a new task... just put it in the top task, though these days
// this case should never happen.
final int N = mHistory.size();
ActivityRecord prev =
N > 0 ? mHistory.get(N-1) : null;
r.setTask(prev != null
? prev.task
: new TaskRecord(mService.mCurTask, r.info, intent), null, true);
if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
+ " in new guessed " + r.task);
}
if (grantedUriPermissions != null && callingUid > 0) {
for (int i=0; i<grantedUriPermissions.length; i++) {
mService.grantUriPermissionLocked(callingUid, r.packageName,
grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
}
}
mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
intent, r.getUriPermissionsLocked());
if (newTask) {
EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
}
logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
startActivityLocked(r, newTask, doResume, keepCurTransition);
return START_SUCCESS;
}
ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug,
String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
// Collect information about the target of the Intent.
ActivityInfo aInfo;
try {
ResolveInfo rInfo =
AppGlobals.getPackageManager().resolveIntent(
intent, resolvedType,
PackageManager.MATCH_DEFAULT_ONLY
| ActivityManagerService.STOCK_PM_FLAGS);
aInfo = rInfo != null ? rInfo.activityInfo : null;
} catch (RemoteException e) {
aInfo = null;
}
if (aInfo != null) {
// Store the found target back into the intent, because now that
// we have it we never want to do this again. For example, if the
// user navigates back to this point in the history, we should
// always restart the exact same activity.
intent.setComponent(new ComponentName(
aInfo.applicationInfo.packageName, aInfo.name));
// Don't debug things in the system process
if (debug) {
if (!aInfo.processName.equals("system")) {
mService.setDebugApp(aInfo.processName, true, false);
}
}
if (profileFile != null) {
if (!aInfo.processName.equals("system")) {
mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
profileFile, profileFd, autoStopProfiler);
}
}
}
return aInfo;
}
final int startActivityMayWait(IApplicationThread caller, int callingUid,
Intent intent, String resolvedType, Uri[] grantedUriPermissions,
int grantedMode, IBinder resultTo,
String resultWho, int requestCode, boolean onlyIfNeeded,
boolean debug, String profileFile, ParcelFileDescriptor profileFd,
boolean autoStopProfiler, WaitResult outResult, Configuration config) {
// Refuse possible leaked file descriptors
if (intent != null && intent.hasFileDescriptors()) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}
boolean componentSpecified = intent.getComponent() != null;
// Don't modify the client's object!
intent = new Intent(intent);
// Collect information about the target of the Intent.
ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug,
profileFile, profileFd, autoStopProfiler);
synchronized (mService) {
int callingPid;
if (callingUid >= 0) {
callingPid = -1;
} else if (caller == null) {
callingPid = Binder.getCallingPid();
callingUid = Binder.getCallingUid();
} else {
callingPid = callingUid = -1;
}
mConfigWillChange = config != null
&& mService.mConfiguration.diff(config) != 0;
if (DEBUG_CONFIGURATION) Slog.v(TAG,
"Starting activity when config will change = " + mConfigWillChange);
final long origId = Binder.clearCallingIdentity();
if (mMainStack && aInfo != null &&
(aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
// This may be a heavy-weight process! Check to see if we already
// have another, different heavy-weight process running.
if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
if (mService.mHeavyWeightProcess != null &&
(mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
!mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
int realCallingPid = callingPid;
int realCallingUid = callingUid;
if (caller != null) {
ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
if (callerApp != null) {
realCallingPid = callerApp.pid;
realCallingUid = callerApp.info.uid;
} else {
Slog.w(TAG, "Unable to find app for caller " + caller
+ " (pid=" + realCallingPid + ") when starting: "
+ intent.toString());
return START_PERMISSION_DENIED;
}
}
IIntentSender target = mService.getIntentSenderLocked(
IActivityManager.INTENT_SENDER_ACTIVITY, "android",
realCallingUid, null, null, 0, new Intent[] { intent },
new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
Intent newIntent = new Intent();
if (requestCode >= 0) {
// Caller is requesting a result.
newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
}
newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
new IntentSender(target));
if (mService.mHeavyWeightProcess.activities.size() > 0) {
ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
hist.packageName);
newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
hist.task.taskId);
}
newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
aInfo.packageName);
newIntent.setFlags(intent.getFlags());
newIntent.setClassName("android",
HeavyWeightSwitcherActivity.class.getName());
intent = newIntent;
resolvedType = null;
caller = null;
callingUid = Binder.getCallingUid();
callingPid = Binder.getCallingPid();
componentSpecified = true;
try {
ResolveInfo rInfo =
AppGlobals.getPackageManager().resolveIntent(
intent, null,
PackageManager.MATCH_DEFAULT_ONLY
| ActivityManagerService.STOCK_PM_FLAGS);
aInfo = rInfo != null ? rInfo.activityInfo : null;
} catch (RemoteException e) {
aInfo = null;
}
}
}
}
int res = startActivityLocked(caller, intent, resolvedType,
grantedUriPermissions, grantedMode, aInfo,
resultTo, resultWho, requestCode, callingPid, callingUid,
onlyIfNeeded, componentSpecified, null);
if (mConfigWillChange && mMainStack) {
// If the caller also wants to switch to a new configuration,
// do so now. This allows a clean switch, as we are waiting
// for the current activity to pause (so we will not destroy
// it), and have not yet started the next activity.
mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
"updateConfiguration()");
mConfigWillChange = false;
if (DEBUG_CONFIGURATION) Slog.v(TAG,
"Updating to new configuration after starting activity.");
mService.updateConfigurationLocked(config, null, false, false);
}
Binder.restoreCallingIdentity(origId);
if (outResult != null) {
outResult.result = res;
if (res == IActivityManager.START_SUCCESS) {
mWaitingActivityLaunched.add(outResult);
do {
try {
mService.wait();
} catch (InterruptedException e) {
}
} while (!outResult.timeout && outResult.who == null);
} else if (res == IActivityManager.START_TASK_TO_FRONT) {
ActivityRecord r = this.topRunningActivityLocked(null);
if (r.nowVisible) {
outResult.timeout = false;
outResult.who = new ComponentName(r.info.packageName, r.info.name);
outResult.totalTime = 0;
outResult.thisTime = 0;
} else {
outResult.thisTime = SystemClock.uptimeMillis();
mWaitingActivityVisible.add(outResult);
do {
try {
mService.wait();
} catch (InterruptedException e) {
}
} while (!outResult.timeout && outResult.who == null);
}
}
}
return res;
}
}
final int startActivities(IApplicationThread caller, int callingUid,
Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
if (intents == null) {
throw new NullPointerException("intents is null");
}
if (resolvedTypes == null) {
throw new NullPointerException("resolvedTypes is null");
}
if (intents.length != resolvedTypes.length) {
throw new IllegalArgumentException("intents are length different than resolvedTypes");
}
ActivityRecord[] outActivity = new ActivityRecord[1];
int callingPid;
if (callingUid >= 0) {
callingPid = -1;
} else if (caller == null) {
callingPid = Binder.getCallingPid();
callingUid = Binder.getCallingUid();
} else {
callingPid = callingUid = -1;
}
final long origId = Binder.clearCallingIdentity();
try {
synchronized (mService) {
for (int i=0; i<intents.length; i++) {
Intent intent = intents[i];
if (intent == null) {
continue;
}
// Refuse possible leaked file descriptors
if (intent != null && intent.hasFileDescriptors()) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}
boolean componentSpecified = intent.getComponent() != null;
// Don't modify the client's object!
intent = new Intent(intent);
// Collect information about the target of the Intent.
ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false,
null, null, false);
if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
& ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
throw new IllegalArgumentException(
"FLAG_CANT_SAVE_STATE not supported here");
}
int res = startActivityLocked(caller, intent, resolvedTypes[i],
null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
false, componentSpecified, outActivity);
if (res < 0) {
return res;
}
resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
}
}
} finally {
Binder.restoreCallingIdentity(origId);
}
return IActivityManager.START_SUCCESS;
}
void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
long thisTime, long totalTime) {
for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
WaitResult w = mWaitingActivityLaunched.get(i);
w.timeout = timeout;
if (r != null) {
w.who = new ComponentName(r.info.packageName, r.info.name);
}
w.thisTime = thisTime;
w.totalTime = totalTime;
}
mService.notifyAll();
}
void reportActivityVisibleLocked(ActivityRecord r) {
for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
WaitResult w = mWaitingActivityVisible.get(i);
w.timeout = false;
if (r != null) {
w.who = new ComponentName(r.info.packageName, r.info.name);
}
w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
w.thisTime = w.totalTime;
}
mService.notifyAll();
if (mDismissKeyguardOnNextActivity) {
mDismissKeyguardOnNextActivity = false;
mService.mWindowManager.dismissKeyguard();
}
}
void sendActivityResultLocked(int callingUid, ActivityRecord r,
String resultWho, int requestCode, int resultCode, Intent data) {
if (callingUid > 0) {
mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
data, r.getUriPermissionsLocked());
}
if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
+ " : who=" + resultWho + " req=" + requestCode
+ " res=" + resultCode + " data=" + data);
if (mResumedActivity == r && r.app != null && r.app.thread != null) {
try {
ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
list.add(new ResultInfo(resultWho, requestCode,
resultCode, data));
r.app.thread.scheduleSendResult(r.appToken, list);
return;
} catch (Exception e) {
Slog.w(TAG, "Exception thrown sending result to " + r, e);
}
}
r.addResultLocked(null, resultWho, requestCode, resultCode, data);
}
private final void stopActivityLocked(ActivityRecord r) {
if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
|| (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
if (!r.finishing) {
requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
"no-history");
}
} else if (r.app != null && r.app.thread != null) {
if (mMainStack) {
if (mService.mFocusedActivity == r) {
mService.setFocusedActivityLocked(topRunningActivityLocked(null));
}
}
r.resumeKeyDispatchingLocked();
try {
r.stopped = false;
if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
+ " (stop requested)");
r.state = ActivityState.STOPPING;
if (DEBUG_VISBILITY) Slog.v(
TAG, "Stopping visible=" + r.visible + " for " + r);
if (!r.visible) {
mService.mWindowManager.setAppVisibility(r.appToken, false);
}
r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
if (mService.isSleeping()) {
r.setSleeping(true);
}
} catch (Exception e) {
// Maybe just ignore exceptions here... if the process
// has crashed, our death notification will clean things
// up.
Slog.w(TAG, "Exception thrown during pause", e);
// Just in case, assume it to be stopped.
r.stopped = true;
if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
r.state = ActivityState.STOPPED;
if (r.configDestroy) {
destroyActivityLocked(r, true, false, "stop-except");
}
}
}
}
final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
boolean remove) {
int N = mStoppingActivities.size();
if (N <= 0) return null;
ArrayList<ActivityRecord> stops = null;
final boolean nowVisible = mResumedActivity != null
&& mResumedActivity.nowVisible
&& !mResumedActivity.waitingVisible;
for (int i=0; i<N; i++) {
ActivityRecord s = mStoppingActivities.get(i);
if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
+ nowVisible + " waitingVisible=" + s.waitingVisible
+ " finishing=" + s.finishing);
if (s.waitingVisible && nowVisible) {
mWaitingVisibleActivities.remove(s);
s.waitingVisible = false;
if (s.finishing) {
// If this activity is finishing, it is sitting on top of
// everyone else but we now know it is no longer needed...
// so get rid of it. Otherwise, we need to go through the
// normal flow and hide it once we determine that it is
// hidden by the activities in front of it.
if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
mService.mWindowManager.setAppVisibility(s.appToken, false);
}
}
if ((!s.waitingVisible || mService.isSleeping()) && remove) {
if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
if (stops == null) {
stops = new ArrayList<ActivityRecord>();
}
stops.add(s);
mStoppingActivities.remove(i);
N--;
i--;
}
}
return stops;
}
final void scheduleIdleLocked() {
Message msg = Message.obtain();
msg.what = IDLE_NOW_MSG;
mHandler.sendMessage(msg);
}
final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Configuration config) {
if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
ActivityRecord res = null;
ArrayList<ActivityRecord> stops = null;
ArrayList<ActivityRecord> finishes = null;
ArrayList<ActivityRecord> thumbnails = null;
int NS = 0;
int NF = 0;
int NT = 0;
IApplicationThread sendThumbnail = null;
boolean booting = false;
boolean enableScreen = false;
synchronized (mService) {
ActivityRecord r = ActivityRecord.forToken(token);
if (r != null) {
mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
}
// Get the activity record.
int index = indexOfActivityLocked(r);
if (index >= 0) {
res = r;
if (fromTimeout) {
reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
}
// This is a hack to semi-deal with a race condition
// in the client where it can be constructed with a
// newer configuration from when we asked it to launch.
// We'll update with whatever configuration it now says
// it used to launch.
if (config != null) {
r.configuration = config;
}
// No longer need to keep the device awake.
if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
mLaunchingActivity.release();
}
// We are now idle. If someone is waiting for a thumbnail from
// us, we can now deliver.
r.idle = true;
mService.scheduleAppGcsLocked();
if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
sendThumbnail = r.app.thread;
r.thumbnailNeeded = false;
}
// If this activity is fullscreen, set up to hide those under it.
if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
ensureActivitiesVisibleLocked(null, 0);
//Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
if (mMainStack) {
if (!mService.mBooted) {
mService.mBooted = true;
enableScreen = true;
}
}
} else if (fromTimeout) {
reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
}
// Atomically retrieve all of the other things to do.
stops = processStoppingActivitiesLocked(true);
NS = stops != null ? stops.size() : 0;
if ((NF=mFinishingActivities.size()) > 0) {
finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
mFinishingActivities.clear();
}
if ((NT=mService.mCancelledThumbnails.size()) > 0) {
thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
mService.mCancelledThumbnails.clear();
}
if (mMainStack) {
booting = mService.mBooting;
mService.mBooting = false;
}
}
int i;
// Send thumbnail if requested.
if (sendThumbnail != null) {
try {
sendThumbnail.requestThumbnail(token);
} catch (Exception e) {
Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
mService.sendPendingThumbnail(null, token, null, null, true);
}
}
// Stop any activities that are scheduled to do so but have been
// waiting for the next one to start.
for (i=0; i<NS; i++) {
ActivityRecord r = (ActivityRecord)stops.get(i);
synchronized (mService) {
if (r.finishing) {
finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
} else {
stopActivityLocked(r);
}
}
}
// Finish any activities that are scheduled to do so but have been
// waiting for the next one to start.
for (i=0; i<NF; i++) {
ActivityRecord r = (ActivityRecord)finishes.get(i);
synchronized (mService) {
destroyActivityLocked(r, true, false, "finish-idle");
}
}
// Report back to any thumbnail receivers.
for (i=0; i<NT; i++) {
ActivityRecord r = (ActivityRecord)thumbnails.get(i);
mService.sendPendingThumbnail(r, null, null, null, true);
}
if (booting) {
mService.finishBooting();
}
mService.trimApplications();
//dump();
//mWindowManager.dump();
if (enableScreen) {
mService.enableScreenAfterBoot();
}
return res;
}
/**
* @return Returns true if the activity is being finished, false if for
* some reason it is being left as-is.
*/
final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Intent resultData, String reason) {
int index = indexOfTokenLocked(token);
if (DEBUG_RESULTS) Slog.v(
TAG, "Finishing activity @" + index + ": token=" + token
+ ", result=" + resultCode + ", data=" + resultData);
if (index < 0) {
return false;
}
ActivityRecord r = mHistory.get(index);
finishActivityLocked(r, index, resultCode, resultData, reason);
return true;
}
/**
* @return Returns true if this activity has been removed from the history
* list, or false if it is still in the list and will be removed later.
*/
final boolean finishActivityLocked(ActivityRecord r, int index,
int resultCode, Intent resultData, String reason) {
if (r.finishing) {
Slog.w(TAG, "Duplicate finish request for " + r);
return false;
}
r.makeFinishing();
EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
System.identityHashCode(r),
r.task.taskId, r.shortComponentName, reason);
if (index < (mHistory.size()-1)) {
ActivityRecord next = mHistory.get(index+1);
if (next.task == r.task) {
if (r.frontOfTask) {
// The next activity is now the front of the task.
next.frontOfTask = true;
}
if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
// If the caller asked that this activity (and all above it)
// be cleared when the task is reset, don't lose that information,
// but propagate it up to the next activity.
next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
}
}
}
r.pauseKeyDispatchingLocked();
if (mMainStack) {
if (mService.mFocusedActivity == r) {
mService.setFocusedActivityLocked(topRunningActivityLocked(null));
}
}
// send the result
ActivityRecord resultTo = r.resultTo;
if (resultTo != null) {
if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
+ " who=" + r.resultWho + " req=" + r.requestCode
+ " res=" + resultCode + " data=" + resultData);
if (r.info.applicationInfo.uid > 0) {
mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
resultTo.packageName, resultData,
resultTo.getUriPermissionsLocked());
}
resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
resultData);
r.resultTo = null;
}
else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
// Make sure this HistoryRecord is not holding on to other resources,
// because clients have remote IPC references to this object so we
// can't assume that will go away and want to avoid circular IPC refs.
r.results = null;
r.pendingResults = null;
r.newIntents = null;
r.icicle = null;
if (mService.mPendingThumbnails.size() > 0) {
// There are clients waiting to receive thumbnails so, in case
// this is an activity that someone is waiting for, add it
// to the pending list so we can correctly update the clients.
mService.mCancelledThumbnails.add(r);
}
if (mResumedActivity == r) {
boolean endTask = index <= 0
|| (mHistory.get(index-1)).task != r.task;
if (DEBUG_TRANSITION) Slog.v(TAG,
"Prepare close transition: finishing " + r);
mService.mWindowManager.prepareAppTransition(endTask
? WindowManagerPolicy.TRANSIT_TASK_CLOSE
: WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
// Tell window manager to prepare for this one to be removed.
mService.mWindowManager.setAppVisibility(r.appToken, false);
if (mPausingActivity == null) {
if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
startPausingLocked(false, false);
}
} else if (r.state != ActivityState.PAUSING) {
// If the activity is PAUSING, we will complete the finish once
// it is done pausing; else we can just directly finish it here.
if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
return finishCurrentActivityLocked(r, index,
FINISH_AFTER_PAUSE) == null;
} else {
if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
}
return false;
}
private static final int FINISH_IMMEDIATELY = 0;
private static final int FINISH_AFTER_PAUSE = 1;
private static final int FINISH_AFTER_VISIBLE = 2;
private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
int mode) {
final int index = indexOfActivityLocked(r);
if (index < 0) {
return null;
}
return finishCurrentActivityLocked(r, index, mode);
}
private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
int index, int mode) {
// First things first: if this activity is currently visible,
// and the resumed activity is not yet visible, then hold off on
// finishing until the resumed one becomes visible.
if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
if (!mStoppingActivities.contains(r)) {
mStoppingActivities.add(r);
if (mStoppingActivities.size() > 3) {
// If we already have a few activities waiting to stop,
// then give up on things going idle and start clearing
// them out.
scheduleIdleLocked();
} else {
checkReadyForSleepLocked();
}
}
if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
+ " (finish requested)");
r.state = ActivityState.STOPPING;
mService.updateOomAdjLocked();
return r;
}
// make sure the record is cleaned out of other places.
mStoppingActivities.remove(r);
mGoingToSleepActivities.remove(r);
mWaitingVisibleActivities.remove(r);
if (mResumedActivity == r) {
mResumedActivity = null;
}
final ActivityState prevState = r.state;
if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
r.state = ActivityState.FINISHING;
if (mode == FINISH_IMMEDIATELY
|| prevState == ActivityState.STOPPED
|| prevState == ActivityState.INITIALIZING) {
// If this activity is already stopped, we can just finish
// it right now.
return destroyActivityLocked(r, true, true, "finish-imm") ? null : r;
} else {
// Need to go through the full pause cycle to get this
// activity into the stopped state and then finish it.
if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
mFinishingActivities.add(r);
resumeTopActivityLocked(null);
}
return r;
}
/**
* Perform the common clean-up of an activity record. This is called both
* as part of destroyActivityLocked() (when destroying the client-side
* representation) and cleaning things up as a result of its hosting
* processing going away, in which case there is no remaining client-side
* state to destroy so only the cleanup here is needed.
*/
final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
boolean setState) {
if (mResumedActivity == r) {
mResumedActivity = null;
}
if (mService.mFocusedActivity == r) {
mService.mFocusedActivity = null;
}
r.configDestroy = false;
r.frozenBeforeDestroy = false;
if (setState) {
if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
r.state = ActivityState.DESTROYED;
}
// Make sure this record is no longer in the pending finishes list.
// This could happen, for example, if we are trimming activities
// down to the max limit while they are still waiting to finish.
mFinishingActivities.remove(r);
mWaitingVisibleActivities.remove(r);
// Remove any pending results.
if (r.finishing && r.pendingResults != null) {
for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
PendingIntentRecord rec = apr.get();
if (rec != null) {
mService.cancelIntentSenderLocked(rec, false);
}
}
r.pendingResults = null;
}
if (cleanServices) {
cleanUpActivityServicesLocked(r);
}
if (mService.mPendingThumbnails.size() > 0) {
// There are clients waiting to receive thumbnails so, in case
// this is an activity that someone is waiting for, add it
// to the pending list so we can correctly update the clients.
mService.mCancelledThumbnails.add(r);
}
// Get rid of any pending idle timeouts.
mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
}
private final void removeActivityFromHistoryLocked(ActivityRecord r) {
if (r.state != ActivityState.DESTROYED) {
r.makeFinishing();
if (DEBUG_ADD_REMOVE) {
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.i(TAG, "Removing activity " + r + " from stack");
}
mHistory.remove(r);
r.takeFromHistory();
if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
+ " (removed from history)");
r.state = ActivityState.DESTROYED;
mService.mWindowManager.removeAppToken(r.appToken);
if (VALIDATE_TOKENS) {
validateAppTokensLocked();
}
cleanUpActivityServicesLocked(r);
r.removeUriPermissionsLocked();
}
}
/**
* Perform clean-up of service connections in an activity record.
*/
final void cleanUpActivityServicesLocked(ActivityRecord r) {
// Throw away any services that have been bound by this activity.
if (r.connections != null) {
Iterator<ConnectionRecord> it = r.connections.iterator();
while (it.hasNext()) {
ConnectionRecord c = it.next();
mService.removeConnectionLocked(c, null, r);
}
r.connections = null;
}
}
final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
for (int i=mHistory.size()-1; i>=0; i--) {
ActivityRecord r = mHistory.get(i);
if (owner != null && r.app != owner) {
continue;
}
// We can destroy this one if we have its icicle saved and
// it is not in the process of pausing/stopping/finishing.
if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
&& r.state != ActivityState.DESTROYING
&& r.state != ActivityState.DESTROYED) {
destroyActivityLocked(r, true, oomAdj, "trim");
}
}
}
/**
* Destroy the current CLIENT SIDE instance of an activity. This may be
* called both when actually finishing an activity, or when performing
* a configuration switch where we destroy the current client-side object
* but then create a new client-side object for this same HistoryRecord.
*/
final boolean destroyActivityLocked(ActivityRecord r,
boolean removeFromApp, boolean oomAdj, String reason) {
if (DEBUG_SWITCH) Slog.v(
TAG, "Removing activity: token=" + r
+ ", app=" + (r.app != null ? r.app.processName : "(null)"));
EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
System.identityHashCode(r),
r.task.taskId, r.shortComponentName, reason);
boolean removedFromHistory = false;
cleanUpActivityLocked(r, false, false);
final boolean hadApp = r.app != null;
if (hadApp) {
if (removeFromApp) {
int idx = r.app.activities.indexOf(r);
if (idx >= 0) {
r.app.activities.remove(idx);
}
if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
mService.mHeavyWeightProcess = null;
mService.mHandler.sendEmptyMessage(
ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
}
if (r.app.activities.size() == 0) {
// No longer have activities, so update location in
// LRU list.
mService.updateLruProcessLocked(r.app, oomAdj, false);
}
}
boolean skipDestroy = false;
try {
if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
r.configChangeFlags);
} catch (Exception e) {
// We can just ignore exceptions here... if the process
// has crashed, our death notification will clean things
// up.
//Slog.w(TAG, "Exception thrown during finish", e);
if (r.finishing) {
removeActivityFromHistoryLocked(r);
removedFromHistory = true;
skipDestroy = true;
}
}
r.app = null;
r.nowVisible = false;
// If the activity is finishing, we need to wait on removing it
// from the list to give it a chance to do its cleanup. During
// that time it may make calls back with its token so we need to
// be able to find it on the list and so we don't want to remove
// it from the list yet. Otherwise, we can just immediately put
// it in the destroyed state since we are not removing it from the
// list.
if (r.finishing && !skipDestroy) {
if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
+ " (destroy requested)");
r.state = ActivityState.DESTROYING;
Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
msg.obj = r;
mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
} else {
if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
+ " (destroy skipped)");
r.state = ActivityState.DESTROYED;
}
} else {
// remove this record from the history.
if (r.finishing) {
removeActivityFromHistoryLocked(r);
removedFromHistory = true;
} else {
if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
+ " (no app)");
r.state = ActivityState.DESTROYED;
}
}
r.configChangeFlags = 0;
if (!mLRUActivities.remove(r) && hadApp) {
Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
}
return removedFromHistory;
}
final void activityDestroyed(IBinder token) {
synchronized (mService) {
ActivityRecord r = ActivityRecord.forToken(token);
if (r != null) {
mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
}
int index = indexOfActivityLocked(r);
if (index >= 0) {
if (r.state == ActivityState.DESTROYING) {
final long origId = Binder.clearCallingIdentity();
removeActivityFromHistoryLocked(r);
Binder.restoreCallingIdentity(origId);
}
}
}
}
private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
int i = list.size();
if (localLOGV) Slog.v(
TAG, "Removing app " + app + " from list " + list
+ " with " + i + " entries");
while (i > 0) {
i--;
ActivityRecord r = (ActivityRecord)list.get(i);
if (localLOGV) Slog.v(
TAG, "Record #" + i + " " + r + ": app=" + r.app);
if (r.app == app) {
if (localLOGV) Slog.v(TAG, "Removing this entry!");
list.remove(i);
}
}
}
void removeHistoryRecordsForAppLocked(ProcessRecord app) {
removeHistoryRecordsForAppLocked(mLRUActivities, app);
removeHistoryRecordsForAppLocked(mStoppingActivities, app);
removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
removeHistoryRecordsForAppLocked(mFinishingActivities, app);
}
/**
* Move the current home activity's task (if one exists) to the front
* of the stack.
*/
final void moveHomeToFrontLocked() {
TaskRecord homeTask = null;
for (int i=mHistory.size()-1; i>=0; i--) {
ActivityRecord hr = mHistory.get(i);
if (hr.isHomeActivity) {
homeTask = hr.task;
break;
}
}
if (homeTask != null) {
moveTaskToFrontLocked(homeTask, null);
}
}
final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
final int task = tr.taskId;
int top = mHistory.size()-1;
if (top < 0 || (mHistory.get(top)).task.taskId == task) {
// nothing to do!
return;
}
ArrayList<IBinder> moved = new ArrayList<IBinder>();
// Applying the affinities may have removed entries from the history,
// so get the size again.
top = mHistory.size()-1;
int pos = top;
// Shift all activities with this task up to the top
// of the stack, keeping them in the same internal order.
while (pos >= 0) {
ActivityRecord r = mHistory.get(pos);
if (localLOGV) Slog.v(
TAG, "At " + pos + " ckp " + r.task + ": " + r);
if (r.task.taskId == task) {
if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
if (DEBUG_ADD_REMOVE) {
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
}
mHistory.remove(pos);
mHistory.add(top, r);
moved.add(0, r.appToken);
top--;
}
pos--;
}
if (DEBUG_TRANSITION) Slog.v(TAG,
"Prepare to front transition: task=" + tr);
if (reason != null &&
(reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
mService.mWindowManager.prepareAppTransition(
WindowManagerPolicy.TRANSIT_NONE, false);
ActivityRecord r = topRunningActivityLocked(null);
if (r != null) {
mNoAnimActivities.add(r);
}
} else {
mService.mWindowManager.prepareAppTransition(
WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
}
mService.mWindowManager.moveAppTokensToTop(moved);
if (VALIDATE_TOKENS) {
validateAppTokensLocked();
}
finishTaskMoveLocked(task);
EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
}
private final void finishTaskMoveLocked(int task) {
resumeTopActivityLocked(null);
}
/**
* Worker method for rearranging history stack. Implements the function of moving all
* activities for a specific task (gathering them if disjoint) into a single group at the
* bottom of the stack.
*
* If a watcher is installed, the action is preflighted and the watcher has an opportunity
* to premeptively cancel the move.
*
* @param task The taskId to collect and move to the bottom.
* @return Returns true if the move completed, false if not.
*/
final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
Slog.i(TAG, "moveTaskToBack: " + task);
// If we have a watcher, preflight the move before committing to it. First check
// for *other* available tasks, but if none are available, then try again allowing the
// current task to be selected.
if (mMainStack && mService.mController != null) {
ActivityRecord next = topRunningActivityLocked(null, task);
if (next == null) {
next = topRunningActivityLocked(null, 0);
}
if (next != null) {
// ask watcher if this is allowed
boolean moveOK = true;
try {
moveOK = mService.mController.activityResuming(next.packageName);
} catch (RemoteException e) {
mService.mController = null;
}
if (!moveOK) {
return false;
}
}
}
ArrayList<IBinder> moved = new ArrayList<IBinder>();
if (DEBUG_TRANSITION) Slog.v(TAG,
"Prepare to back transition: task=" + task);
final int N = mHistory.size();
int bottom = 0;
int pos = 0;
// Shift all activities with this task down to the bottom
// of the stack, keeping them in the same internal order.
while (pos < N) {
ActivityRecord r = mHistory.get(pos);
if (localLOGV) Slog.v(
TAG, "At " + pos + " ckp " + r.task + ": " + r);
if (r.task.taskId == task) {
if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
if (DEBUG_ADD_REMOVE) {
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
+ bottom, here);
}
mHistory.remove(pos);
mHistory.add(bottom, r);
moved.add(r.appToken);
bottom++;
}
pos++;
}
if (reason != null &&
(reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
mService.mWindowManager.prepareAppTransition(
WindowManagerPolicy.TRANSIT_NONE, false);
ActivityRecord r = topRunningActivityLocked(null);
if (r != null) {
mNoAnimActivities.add(r);
}
} else {
mService.mWindowManager.prepareAppTransition(
WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
}
mService.mWindowManager.moveAppTokensToBottom(moved);
if (VALIDATE_TOKENS) {
validateAppTokensLocked();
}
finishTaskMoveLocked(task);
return true;
}
public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
ActivityRecord resumed = mResumedActivity;
if (resumed != null && resumed.thumbHolder == tr) {
info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
} else {
info.mainThumbnail = tr.lastThumbnail;
}
return info;
}
public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex) {
TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
if (info.root == null) {
Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
return null;
}
if (subTaskIndex < 0) {
// Just remove the entire task.
performClearTaskAtIndexLocked(taskId, info.rootIndex);
return info.root;
}
if (subTaskIndex >= info.subtasks.size()) {
Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
return null;
}
// Remove all of this task's activies starting at the sub task.
TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
performClearTaskAtIndexLocked(taskId, subtask.index);
return subtask.activity;
}
public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
ActivityRecord resumed = mResumedActivity;
final TaskAccessInfo thumbs = new TaskAccessInfo();
// How many different sub-thumbnails?
final int NA = mHistory.size();
int j = 0;
ThumbnailHolder holder = null;
while (j < NA) {
ActivityRecord ar = mHistory.get(j);
if (!ar.finishing && ar.task.taskId == taskId) {
holder = ar.thumbHolder;
break;
}
j++;
}
if (j >= NA) {
return thumbs;
}
thumbs.root = mHistory.get(j);
thumbs.rootIndex = j;
ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
thumbs.subtasks = subtasks;
ActivityRecord lastActivity = null;
while (j < NA) {
ActivityRecord ar = mHistory.get(j);
j++;
if (ar.finishing) {
continue;
}
if (ar.task.taskId != taskId) {
break;
}
lastActivity = ar;
if (ar.thumbHolder != holder && holder != null) {
thumbs.numSubThumbbails++;
holder = ar.thumbHolder;
TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
sub.thumbnail = holder.lastThumbnail;
sub.activity = ar;
sub.index = j-1;
subtasks.add(sub);
}
}
if (lastActivity != null && subtasks.size() > 0) {
if (resumed == lastActivity) {
TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
}
}
if (thumbs.numSubThumbbails > 0) {
thumbs.retriever = new IThumbnailRetriever.Stub() {
public Bitmap getThumbnail(int index) {
if (index < 0 || index >= thumbs.subtasks.size()) {
return null;
}
return thumbs.subtasks.get(index).thumbnail;
}
};
}
return thumbs;
}
private final void logStartActivity(int tag, ActivityRecord r,
TaskRecord task) {
EventLog.writeEvent(tag,
System.identityHashCode(r), task.taskId,
r.shortComponentName, r.intent.getAction(),
r.intent.getType(), r.intent.getDataString(),
r.intent.getFlags());
}
/**
* Make sure the given activity matches the current configuration. Returns
* false if the activity had to be destroyed. Returns true if the
* configuration is the same, or the activity will remain running as-is
* for whatever reason. Ensures the HistoryRecord is updated with the
* correct configuration and all other bookkeeping is handled.
*/
final boolean ensureActivityConfigurationLocked(ActivityRecord r,
int globalChanges) {
if (mConfigWillChange) {
if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
"Skipping config check (will change): " + r);
return true;
}
if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
"Ensuring correct configuration: " + r);
// Short circuit: if the two configurations are the exact same
// object (the common case), then there is nothing to do.
Configuration newConfig = mService.mConfiguration;
if (r.configuration == newConfig && !r.forceNewConfig) {
if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
"Configuration unchanged in " + r);
return true;
}
// We don't worry about activities that are finishing.
if (r.finishing) {
if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
"Configuration doesn't matter in finishing " + r);
r.stopFreezingScreenLocked(false);
return true;
}
// Okay we now are going to make this activity have the new config.
// But then we need to figure out how it needs to deal with that.
Configuration oldConfig = r.configuration;
r.configuration = newConfig;
// Determine what has changed. May be nothing, if this is a config
// that has come back from the app after going idle. In that case
// we just want to leave the official config object now in the
// activity and do nothing else.
final int changes = oldConfig.diff(newConfig);
if (changes == 0 && !r.forceNewConfig) {
if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
"Configuration no differences in " + r);
return true;
}
// If the activity isn't currently running, just leave the new
// configuration and it will pick that up next time it starts.
if (r.app == null || r.app.thread == null) {
if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
"Configuration doesn't matter not running " + r);
r.stopFreezingScreenLocked(false);
r.forceNewConfig = false;
return true;
}
// Figure out how to handle the changes between the configurations.
if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
+ Integer.toHexString(changes) + ", handles=0x"
+ Integer.toHexString(r.info.getRealConfigChanged())
+ ", newConfig=" + newConfig);
}
if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
// Aha, the activity isn't handling the change, so DIE DIE DIE.
r.configChangeFlags |= changes;
r.startFreezingScreenLocked(r.app, globalChanges);
r.forceNewConfig = false;
if (r.app == null || r.app.thread == null) {
if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
"Switch is destroying non-running " + r);
destroyActivityLocked(r, true, false, "config");
} else if (r.state == ActivityState.PAUSING) {
// A little annoying: we are waiting for this activity to
// finish pausing. Let's not do anything now, but just
// flag that it needs to be restarted when done pausing.
if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
"Switch is skipping already pausing " + r);
r.configDestroy = true;
return true;
} else if (r.state == ActivityState.RESUMED) {
// Try to optimize this case: the configuration is changing
// and we need to restart the top, resumed activity.
// Instead of doing the normal handshaking, just say
// "restart!".
if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
"Switch is restarting resumed " + r);
relaunchActivityLocked(r, r.configChangeFlags, true);
r.configChangeFlags = 0;
} else {
if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
"Switch is restarting non-resumed " + r);
relaunchActivityLocked(r, r.configChangeFlags, false);
r.configChangeFlags = 0;
}
// All done... tell the caller we weren't able to keep this
// activity around.
return false;
}
// Default case: the activity can handle this new configuration, so
// hand it over. Note that we don't need to give it the new
// configuration, since we always send configuration changes to all
// process when they happen so it can just use whatever configuration
// it last got.
if (r.app != null && r.app.thread != null) {
try {
if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
} catch (RemoteException e) {
// If process died, whatever.
}
}
r.stopFreezingScreenLocked(false);
return true;
}
private final boolean relaunchActivityLocked(ActivityRecord r,
int changes, boolean andResume) {
List<ResultInfo> results = null;
List<Intent> newIntents = null;
if (andResume) {
results = r.results;
newIntents = r.newIntents;
}
if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
+ " with results=" + results + " newIntents=" + newIntents
+ " andResume=" + andResume);
EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
: EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
r.task.taskId, r.shortComponentName);
r.startFreezingScreenLocked(r.app, 0);
try {
if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
r.forceNewConfig = false;
r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
changes, !andResume, new Configuration(mService.mConfiguration));
// Note: don't need to call pauseIfSleepingLocked() here, because
// the caller will only pass in 'andResume' if this activity is
// currently resumed, which implies we aren't sleeping.
} catch (RemoteException e) {
return false;
}
if (andResume) {
r.results = null;
r.newIntents = null;
if (mMainStack) {
mService.reportResumedActivityLocked(r);
}
}
return true;
}
public void dismissKeyguardOnNextActivityLocked() {
mDismissKeyguardOnNextActivity = true;
}
}
| gpl-3.0 |
sistemi-territoriali/StatPortalOpenData | SpodCkanApi/src/it/sister/statportal/odata/ckan/GroupServlet.java | 6590 | package it.sister.statportal.odata.ckan;
import it.sister.statportal.odata.ckan.entities.Group;
import it.sister.statportal.odata.ckan.entities.User;
import it.sister.statportal.odata.ckan.utils.IJsonConverter;
import it.sister.statportal.odata.ckan.utils.Utils;
import it.sister.statportal.odata.util.config.ConfigReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
/**
* Servlet implementation class GroupServlet
*/
public class GroupServlet extends CkanApiServlet {
protected static boolean exportParentId = false;
protected static final long serialVersionUID = 1L;
protected static final String GROUP_QUERY = "select term_name v1, tid v2 "+
"from view_taxonomy "+
"where voc_machine_name like 'metadata_lu_category'";
protected static String groupInfoQueryByName =
"select distinct vt.*, vm.identifier vm1, vm.uid vm2 "+ "OPTIONAL_PARAMETERS" +
"from view_taxonomy vt "+
"left join view_federated_metadata_taxonomy vmt on vt.term_name = vmt.term_name "+
"left join view_apickan_metadata vm on vmt.nid = vm.nid "+
"where vt.voc_machine_name like 'metadata_lu_category' and vt.term_name like 'to_replace'";
protected static String groupInfoQueryById =
"select distinct vt.*, vm.identifier vm1, vm.uid vm2 "+ "OPTIONAL_PARAMETERS" +
"from view_taxonomy vt "+
"left join view_federated_metadata_taxonomy vmt on vt.term_name = vmt.term_name "+
"left join view_apickan_metadata vm on vmt.nid = vm.nid "+
"where vt.voc_machine_name like 'metadata_lu_category' and vt.tid = to_replace";
/**Campi aggiuntivi da richiedere tramite query SQL*/
protected static String getParentIdSQL = ", vt.parent_tid, vt.parent_name ";
/**
* @see HttpServlet#HttpServlet()
*/
public GroupServlet() {
super();
versionRegex += "rest/group$";
}
@Override
public void init(ServletConfig config) throws ServletException {
//Inizializzazione connessione al DB site e parametri servlet di pubblicazione
super.init(config);
//Custom param config, export del parentId del gruppo. Se non presente si lascia false.
try {
exportParentId = Boolean.parseBoolean(ConfigReader.readConfig("exportGroupParentId", "SpodCkanApi"));
}
catch (Exception e) {}
}
/**
* Fornisce la serializzazione json dell'elenco di nomi di tematiche
* L'elenco sarà costituito da un insieme di nomi nel caso di versione non specificata o versione 1,
* da un insieme di uid nel caso di versione 2.
* @param version1 true se la versione delle api non è specificata o è la 1, false se è la 2
* @return la serializzazione json dell'elenco di nomi di tematiche
*/
@Override
protected String getList(final boolean version1){
return convertToJson(GROUP_QUERY,
new IJsonConverter() {
@Override
public String toJson(ResultSet resultSet) throws SQLException {
ArrayList<String> groupList = new ArrayList<String>();
while(resultSet.next()){
if(version1){
groupList.add(resultSet.getString("v1"));
}else{
groupList.add(resultSet.getObject("v2").toString());
}
}
return Utils.toJson(groupList);
}
});
}
/**
* Fornisce la serializzazione json delle caratteristiche di una tematica. Se la tematica non è
* associata a nessun dato non viene restituito nulla.
* @param group il nome del gruppo (nel caso di versione non specificata o 1) o l'uid del gruppo (versione 2)
* @param version1 true se la versione non è specificata o è la 1, false se è la 2
* @return la serializzazione json delle caratteristiche di una tematica
*/
@Override
protected String getSingle(String group, final boolean version1){
String optionalParameters = "";
if (exportParentId) optionalParameters = getParentIdSQL;
String query = version1 ? groupInfoQueryByName.replaceAll("to_replace", group) :
groupInfoQueryById.replaceAll("to_replace", group);
query = query.replaceAll("OPTIONAL_PARAMETERS", optionalParameters);
return convertToJson(query,
new IJsonConverter() {
@Override
public String toJson(ResultSet resultSet) throws SQLException {
boolean first = true;
Group group = null;
ArrayList<String> dataList = new ArrayList<String>();
while(resultSet.next()){
if(first){
group = buildGroup(resultSet);
first = false;
}
if(version1){
//Name ricavato da link scheda (eliminando prefisso)
String name = resultSet.getString("vm1");
if (name!=null) dataList.add(Utils.removeDataPrefix(name));
}else{
//Uid scheda
Object uid = resultSet.getObject("vm2");
if (uid!=null) dataList.add(uid.toString());
}
}
if(group != null){
group.setPackages(dataList);
}
//Non si restituisce "Non trovato" in caso di nessun risultato come fa CKAN
//perché andrebbe poi gestito nella creazione del grafo per ODINet.
return group != null ? Utils.toJson(group) : /*Utils.toJson("Non trovato")*/ "";
}
});
}
/**
* Costruisce la rappresentazione di una tematica a partire da una riga del db
* @param resultSet il puntatore ad una riga del risultato della query
* @return la rappresentazione di una tematica creata a partire da una riga del db
* @throws SQLException se non riesce a leggere i campi della riga
*/
protected Group buildGroup(ResultSet resultSet) throws SQLException{
Group group = new Group();
group.setUsers(new ArrayList<User>());
group.setDisplay_name(resultSet.getString("term_name"));
group.setDescription(resultSet.getString("term_description"));
group.setTitle(resultSet.getString("term_name"));
group.setCreated("");
group.setApproval_status("approved");
group.setState("active");
group.setExtra(null);
group.setGroups(new String[0]);
group.setImage_url("");
group.setType("group");
group.setId(resultSet.getString("tid"));
group.setTags(new String[0]);
group.setName(resultSet.getString("term_name"));
if (exportParentId) {
String parent_tid = resultSet.getString("parent_tid");
if (parent_tid.equals("0")) parent_tid = null;
group.setParent_id(parent_tid);
group.setParent_name(resultSet.getString("parent_name"));
}
return group;
}
}
| gpl-3.0 |
henwii/TouchTest | ios/src/com/mygdx/game/IOSLauncher.java | 752 | package com.mygdx.game;
import org.robovm.apple.foundation.NSAutoreleasePool;
import org.robovm.apple.uikit.UIApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
import com.mygdx.game.TouchTest;
public class IOSLauncher extends IOSApplication.Delegate {
@Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration();
return new IOSApplication(new TouchTest(), config);
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, IOSLauncher.class);
pool.close();
}
} | gpl-3.0 |
BackupTheBerlios/relayconnector | src/java/org/kisst/cordys/relay/resourcepool/ResourcePool.java | 957 | /**
Copyright 2008, 2009 Mark Hooijkaas
This file is part of the RelayConnector framework.
The RelayConnector framework is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The RelayConnector framework is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the RelayConnector framework. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kisst.cordys.relay.resourcepool;
import org.kisst.cordys.relay.CallContext;
public interface ResourcePool {
public void add(CallContext ctxt);
public void remove(CallContext ctxt);
}
| gpl-3.0 |
derreisende77/MediathekView | src/main/java/mediathek/controller/IoXmlSchreiben.java | 10801 | /*
* MediathekView
* Copyright (C) 2008 W. Xaver
* W.Xaver[at]googlemail.com
* http://zdfmediathk.sourceforge.net/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package mediathek.controller;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import mSearch.Const;
import mSearch.filmlisten.DatenFilmlisteUrl;
import mSearch.tool.Log;
import mSearch.tool.ReplaceList;
import mSearch.tool.SysMsg;
import mediathek.config.Daten;
import mediathek.config.Konstanten;
import mediathek.config.MVConfig;
import mediathek.daten.*;
public class IoXmlSchreiben {
private static XMLStreamWriter writer;
private static OutputStreamWriter out = null;
private static Path xmlFilePath;
public static synchronized void datenSchreiben() {
xmlFilePath = Daten.getMediathekXmlFilePath();
SysMsg.sysMsg("Daten Schreiben nach: " + xmlFilePath.toString());
xmlDatenSchreiben();
}
public static synchronized void exportPset(DatenPset[] pSet, String datei) {
try {
xmlFilePath = Paths.get(datei);
SysMsg.sysMsg("Pset exportieren nach: " + xmlFilePath.toString());
xmlSchreibenStart();
xmlSchreibenPset(pSet);
xmlSchreibenEnde();
} catch (Exception ex) {
Log.errorLog(392846204, ex, "nach: " + datei);
}
}
private static void xmlDatenSchreiben() {
try {
xmlSchreibenStart();
writer.writeCharacters("\n\n");
writer.writeComment("Abos");
writer.writeCharacters("\n");
xmlSchreibenAbo();
writer.writeCharacters("\n\n");
writer.writeComment("Blacklist");
writer.writeCharacters("\n");
xmlSchreibenBlackList();
writer.writeCharacters("\n\n");
writer.writeComment(MVConfig.PARAMETER_INFO);
writer.writeCharacters("\n\n");
writer.writeComment("Programmeinstellungen");
writer.writeCharacters("\n");
xmlSchreibenConfig(MVConfig.SYSTEM, MVConfig.getAll(), true);
writer.writeCharacters("\n");
writer.writeCharacters("\n\n");
writer.writeComment("Programmsets");
writer.writeCharacters("\n");
xmlSchreibenProg();
writer.writeCharacters("\n\n");
writer.writeComment("Ersetzungstabelle");
writer.writeCharacters("\n");
xmlSchreibenErsetzungstabelle();
writer.writeCharacters("\n\n");
writer.writeComment("Downloads");
writer.writeCharacters("\n");
xmlSchreibenDownloads();
writer.writeCharacters("\n\n");
writer.writeComment("Pfade MedienDB");
writer.writeCharacters("\n");
xmlSchreibenMediaPath();
writer.writeCharacters("\n\n");
writer.writeComment("Update Filmliste");
writer.writeCharacters("\n");
xmlSchreibenFilmUpdateServer();
writer.writeCharacters("\n\n");
xmlSchreibenEnde();
} catch (Exception ex) {
Log.errorLog(656328109, ex);
}
}
private static void xmlSchreibenStart() throws IOException, XMLStreamException {
SysMsg.sysMsg("Start Schreiben nach: " + xmlFilePath.toAbsolutePath());
out = new OutputStreamWriter(Files.newOutputStream(xmlFilePath), Const.KODIERUNG_UTF);
XMLOutputFactory outFactory = XMLOutputFactory.newInstance();
writer = outFactory.createXMLStreamWriter(out);
writer.writeStartDocument(Const.KODIERUNG_UTF, "1.0");
writer.writeCharacters("\n");//neue Zeile
writer.writeStartElement(Konstanten.XML_START);
writer.writeCharacters("\n");//neue Zeile
}
private static void xmlSchreibenErsetzungstabelle() {
for (String[] sa : ReplaceList.list) {
xmlSchreibenDaten(ReplaceList.REPLACELIST, ReplaceList.COLUMN_NAMES, sa, false);
}
}
private static void xmlSchreibenProg() {
//Proggruppen schreiben, bei Konfig-Datei
for (DatenPset datenPset : Daten.listePset) {
xmlSchreibenDaten(DatenPset.TAG, DatenPset.XML_NAMES, datenPset.arr, false);
for (DatenProg datenProg : datenPset.getListeProg()) {
xmlSchreibenDaten(DatenProg.TAG, DatenProg.XML_NAMES, datenProg.arr, false);
}
}
}
private static void xmlSchreibenPset(DatenPset[] psetArray) throws XMLStreamException {
// wird beim Export Sets verwendete
writer.writeCharacters("\n\n");
for (DatenPset pset : psetArray) {
xmlSchreibenDaten(DatenPset.TAG, DatenPset.XML_NAMES, pset.arr, true);
for (DatenProg datenProg : pset.getListeProg()) {
xmlSchreibenDaten(DatenProg.TAG, DatenProg.XML_NAMES, datenProg.arr, true);
}
writer.writeCharacters("\n\n");
}
}
private static void xmlSchreibenDownloads() {
//Abo schreiben
for (DatenDownload download : Daten.listeDownloads) {
if (download.isInterrupted()) {
// unterbrochene werden gespeichert, dass die Info "Interrupt" erhalten bleibt
xmlSchreibenDaten(DatenDownload.TAG, DatenDownload.XML_NAMES, download.arr, false);
} else if (!download.istAbo() && !download.isFinished()) {
//Download, (Abo müssen neu angelegt werden)
xmlSchreibenDaten(DatenDownload.TAG, DatenDownload.XML_NAMES, download.arr, false);
}
}
}
private static void xmlSchreibenAbo() {
//Abo schreiben
for (DatenAbo datenAbo : Daten.listeAbo) {
xmlSchreibenDaten(DatenAbo.TAG, DatenAbo.XML_NAMES, datenAbo.arr, false);
}
}
private static void xmlSchreibenMediaPath() {
//Pfade der MedienDB schreiben
for (DatenMediaPath mp : Daten.listeMediaPath) {
xmlSchreibenDaten(DatenMediaPath.TAG, DatenMediaPath.XML_NAMES, mp.arr, false);
}
}
private static void xmlSchreibenBlackList() {
//Blacklist schreiben
for (DatenBlacklist blacklist : Daten.listeBlacklist) {
xmlSchreibenDaten(DatenBlacklist.TAG, DatenBlacklist.XML_NAMES, blacklist.arr, false);
}
}
private static void xmlSchreibenFilmUpdateServer() throws XMLStreamException {
//FilmUpdate schreiben
writer.writeCharacters("\n");
writer.writeComment("Akt-Filmliste");
writer.writeCharacters("\n");
for (DatenFilmlisteUrl datenUrlFilmliste : Daten.filmeLaden.getDownloadUrlsFilmlisten_akt()) {
datenUrlFilmliste.arr[DatenFilmlisteUrl.FILM_UPDATE_SERVER_ART_NR] = DatenFilmlisteUrl.SERVER_ART_AKT;
xmlSchreibenDaten(DatenFilmlisteUrl.FILM_UPDATE_SERVER, DatenFilmlisteUrl.FILM_UPDATE_SERVER_COLUMN_NAMES, datenUrlFilmliste.arr, false);
}
writer.writeCharacters("\n");
writer.writeComment("Diff-Filmliste");
writer.writeCharacters("\n");
for (DatenFilmlisteUrl datenUrlFilmliste : Daten.filmeLaden.getDownloadUrlsFilmlisten_diff()) {
datenUrlFilmliste.arr[DatenFilmlisteUrl.FILM_UPDATE_SERVER_ART_NR] = DatenFilmlisteUrl.SERVER_ART_DIFF;
xmlSchreibenDaten(DatenFilmlisteUrl.FILM_UPDATE_SERVER, DatenFilmlisteUrl.FILM_UPDATE_SERVER_COLUMN_NAMES, datenUrlFilmliste.arr, false);
}
}
private static void xmlSchreibenDaten(String xmlName, String[] xmlSpalten, String[] datenArray, boolean newLine) {
final int xmlMax = datenArray.length;
try {
writer.writeStartElement(xmlName);
if (newLine) {
writer.writeCharacters("\n"); //neue Zeile
}
for (int i = 0; i < xmlMax; ++i) {
if (!datenArray[i].equals("")) {
if (newLine) {
writer.writeCharacters("\t"); //Tab
}
writer.writeStartElement(xmlSpalten[i]);
writer.writeCharacters(datenArray[i]);
writer.writeEndElement();
if (newLine) {
writer.writeCharacters("\n"); //neue Zeile
}
}
}
writer.writeEndElement();
writer.writeCharacters("\n"); //neue Zeile
} catch (Exception ex) {
Log.errorLog(198325017, ex);
}
}
private static void xmlSchreibenConfig(String xmlName, String[][] xmlSpalten, boolean newLine) {
try {
writer.writeStartElement(xmlName);
if (newLine) {
writer.writeCharacters("\n"); //neue Zeile
}
for (String[] xmlSpalte : xmlSpalten) {
if (!MVConfig.Configs.find(xmlSpalte[0])) {
continue; //nur Configs schreiben die es noch gibt
}
if (newLine) {
writer.writeCharacters("\t"); //Tab
}
writer.writeStartElement(xmlSpalte[0]);
writer.writeCharacters(xmlSpalte[1]);
writer.writeEndElement();
if (newLine) {
writer.writeCharacters("\n"); //neue Zeile
}
}
writer.writeEndElement();
writer.writeCharacters("\n"); //neue Zeile
} catch (Exception ex) {
Log.errorLog(951230478, ex);
}
}
private static void xmlSchreibenEnde() throws Exception {
writer.writeEndElement();
writer.writeEndDocument();
writer.flush();
writer.close();
out.close();
SysMsg.sysMsg("geschrieben!");
}
}
| gpl-3.0 |
maruohon/autoverse | src/main/java/fi/dy/masa/autoverse/client/render/model/ModelBase.java | 2633 | package fi.dy.masa.autoverse.client.render.model;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.common.model.IModelState;
public class ModelBase implements IModel
{
protected final ResourceLocation modelLocation;
protected final IBakedModelFactory modelFactory;
protected final ImmutableList<ResourceLocation> modelDependencies;
protected final ImmutableList<ResourceLocation> textureDependencies;
protected final ImmutableMap<String, String> textures;
public ModelBase(ResourceLocation modelLocation,
IBakedModelFactory modelFactory,
ImmutableList<ResourceLocation> modelDependencies,
ImmutableList<ResourceLocation> textureDependencies,
ImmutableMap<String, String> textures)
{
this.modelLocation = modelLocation;
this.modelFactory = modelFactory;
this.modelDependencies = modelDependencies;
this.textureDependencies = textureDependencies;
this.textures = textures;
}
@Override
public List<ResourceLocation> getDependencies()
{
return this.modelDependencies;
}
@Override
public Collection<ResourceLocation> getTextures()
{
return this.textureDependencies;
}
@Override
public IModel retexture(ImmutableMap<String, String> textures)
{
return new ModelBase(this.modelLocation, this.modelFactory, this.modelDependencies, this.textureDependencies, textures);
}
@Override
public IBakedModel bake(IModelState state, VertexFormat format, Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter)
{
return this.modelFactory.createBakedModel(this.modelLocation, this.textures, state, format, bakedTextureGetter);
}
public interface IBakedModelFactory
{
IBakedModel createBakedModel(ResourceLocation modelLocation,
ImmutableMap<String, String> textures,
IModelState state,
VertexFormat format,
Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter);
}
}
| gpl-3.0 |
grtlinux/KIEA_JAVA7 | KIEA_JAVA7/src/tain/kr/com/test/deploy/v01/license/InetAddr.java | 7317 | /**
* Copyright 2014, 2015, 2016 TAIN, Inc. all rights reserved.
*
* Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* -----------------------------------------------------------------
* Copyright 2014, 2015, 2016 TAIN, Inc.
*
*/
package tain.kr.com.test.deploy.v01.license;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.log4j.Logger;
/**
* Code Templates > Comments > Types
*
* <PRE>
* -. FileName : InetAddr.java
* -. Package : tain.kr.com.test.deploy.v01.license
* -. Comment :
* -. Author : taincokr
* -. First Date : 2016. 3. 2. {time}
* </PRE>
*
* @author taincokr
*
*/
public class InetAddr {
private static boolean flag = true;
private static final Logger log = Logger.getLogger(InetAddr.class);
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
private String inetAddrInfo = null;
private InetAddr() {
if (flag) log.debug(">>>>> Object : " + this.getClass().getName());
}
public String getInfo(String expireDate) throws Exception {
if (this.inetAddrInfo == null) {
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
// e.printStackTrace();
throw e;
}
if (flag) log.debug(String.format("%s, %s", inetAddress.getHostName(), inetAddress.getHostAddress()));
if (!flag) {
/*
* normal format : 127.0.0.1
*/
StringBuffer sb = new StringBuffer();
byte[] ip = inetAddress.getAddress();
for (int i=0; i < ip.length; i++) {
sb.append(ip[i] & 0xFF); // bug
if (i != ip.length - 1)
sb.append(".");
}
if (flag) log.debug(sb.toString());
}
if (flag) {
/*
* key format : 999.999.999.999
*/
StringBuffer sb = new StringBuffer();
byte[] ip = inetAddress.getAddress();
for (int i=0; i < ip.length; i++) {
sb.append(String.format("%03d", ip[i] & 0xFF)); // bug
if (i != ip.length - 1)
sb.append(".");
}
if (flag) log.debug(sb.toString());
this.inetAddrInfo = String.format("%s-%s", sb.toString(), expireDate);
}
}
return this.inetAddrInfo;
}
public String getInfo() throws Exception {
return getInfo("202507");
}
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
private static InetAddr instance = null;
public static synchronized InetAddr getInstance() throws Exception {
if (flag) {
if (InetAddr.instance == null) {
InetAddr.instance = new InetAddr();
}
}
return InetAddr.instance;
}
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
/**
*
* Code Templates > Comments > Methods
*
* <PRE>
* -. ClassName : IpAddressTestMain
* -. MethodName : test02
* -. Comment :
* -. Author : taincokr
* -. First Date : 2016. 3. 2. {time}
* </PRE>
*
* @param args
* @throws Exception
*
* [ OUTPUT ]
* (IpAddressTestMain.java:152) - >>>>> tain.kr.com.test.IpAddress.v01.IpAddressTestMain
* (IpAddressTestMain.java:73) - localhost, 127.0.0.1
* (IpAddressTestMain.java:87) - 127.0.0.1
* (IpAddressTestMain.java:102) - 127.000.000.001
* (IpAddressTestMain.java:116) - taincokr-PC, 172.31.16.2
* (IpAddressTestMain.java:130) - 172.31.16.2
* (IpAddressTestMain.java:145) - 172.031.016.002
*
*/
private static void test01(String[] args) throws Exception {
if (flag) {
/*
* for test
*/
StringBuffer sb = new StringBuffer();
byte[] ip = { -4, -3, -2, -1 };
for (int i=0; i < ip.length; i++) {
sb.append(ip[i] & 0xFF); // bug
if (i != ip.length - 1)
sb.append(".");
}
log.debug(sb.toString());
}
if (flag) {
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getLoopbackAddress();
} catch (Exception e) {
e.printStackTrace();
}
log.debug(String.format("%s, %s", inetAddress.getHostName(), inetAddress.getHostAddress()));
if (flag) {
/*
* normal format : 127.0.0.1
*/
StringBuffer sb = new StringBuffer();
byte[] ip = inetAddress.getAddress();
for (int i=0; i < ip.length; i++) {
sb.append(ip[i] & 0xFF); // bug
if (i != ip.length - 1)
sb.append(".");
}
log.debug(sb.toString());
}
if (flag) {
/*
* key format : 999.999.999.999
*/
StringBuffer sb = new StringBuffer();
byte[] ip = inetAddress.getAddress();
for (int i=0; i < ip.length; i++) {
sb.append(String.format("%03d", ip[i] & 0xFF)); // bug
if (i != ip.length - 1)
sb.append(".");
}
log.debug(sb.toString());
}
}
if (flag) {
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
log.debug(String.format("%s, %s", inetAddress.getHostName(), inetAddress.getHostAddress()));
if (flag) {
/*
* normal format : 127.0.0.1
*/
StringBuffer sb = new StringBuffer();
byte[] ip = inetAddress.getAddress();
for (int i=0; i < ip.length; i++) {
sb.append(ip[i] & 0xFF); // bug
if (i != ip.length - 1)
sb.append(".");
}
log.debug(sb.toString());
}
if (flag) {
/*
* key format : 999.999.999.999
*/
StringBuffer sb = new StringBuffer();
byte[] ip = inetAddress.getAddress();
for (int i=0; i < ip.length; i++) {
sb.append(String.format("%03d", ip[i] & 0xFF)); // bug
if (i != ip.length - 1)
sb.append(".");
}
log.debug(sb.toString());
}
}
}
private static void test02(String[] args) throws Exception {
if (flag) {
log.debug(">" + InetAddr.getInstance().getInfo());
log.debug(">" + InetAddr.getInstance().getInfo("201612"));
}
}
public static void main(String[] args) throws Exception {
if (flag) log.debug(">>>>> " + new Object(){}.getClass().getEnclosingClass().getName());
if (flag) test01(args);
if (flag) test02(args);
}
}
| gpl-3.0 |
NicolasNolmans/Simple-Solitaire-master | app/src/main/java/be/kuleuven/drsolitaire/dialogs/DialogPreferenceMusicVolume.java | 2734 | /*
* Copyright (C) 2016 Tobias Bielefeld
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you want to contact me, send me an e-mail at tobias.bielefeld@gmail.com
*/
package be.kuleuven.drsolitaire.dialogs;
import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import java.util.Locale;
import be.kuleuven.drsolitaire.R;
import static be.kuleuven.drsolitaire.SharedData.*;
/*
* custom dialog to set the background music volume. it can be set from 0 (off) to 100%.
*/
public class DialogPreferenceMusicVolume extends DialogPreference implements SeekBar.OnSeekBarChangeListener{
private SeekBar mSeekBar;
private TextView mTextView;
public DialogPreferenceMusicVolume(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.dialog_background_volume);
setDialogIcon(null);
}
@Override
protected void onBindDialogView(View view) {
mTextView = (TextView) view.findViewById(R.id.textView);
mSeekBar = (SeekBar) view.findViewById(R.id.seekBar);
mSeekBar.setOnSeekBarChangeListener(this);
int volume = getSharedInt(PREF_KEY_BACKGROUND_VOLUME,DEFAULT_BACKGROUND_VOLUME);
mSeekBar.setProgress(volume);
setProgressText(volume);
super.onBindDialogView(view);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
setProgressText(i);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int volume = mSeekBar.getProgress();
}
@Override
protected void onDialogClosed(boolean positiveResult) {
// When the user selects "OK", persist the new value
if (positiveResult) {
putSharedInt(PREF_KEY_BACKGROUND_VOLUME,mSeekBar.getProgress());
}
}
private void setProgressText(int value){
mTextView.setText(String.format(Locale.getDefault(),"%s %%",value));
}
}
| gpl-3.0 |
jilm/tools | src/cz/lidinsky/tools/ParserChain.java | 1323 | package cz.lidinsky.tools;
/*
* Copyright 2015 Jiri Lidinsky
*
* This file is part of java tools library.
*
* java tools is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* java tools library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with java tools library. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.HashMap;
public class ParserChain {
private HashMap<Class<?>, Parser<?>> parsers
= new HashMap<Class<?>, Parser<?>>();
public static <T> T parse(ParserChain chain, String text, Class<T> type) {
Parser<T> parser = (Parser<T>)chain.parsers.get(type);
if (parser != null) {
return parser.parse(text);
} else {
throw new CommonException()
.setCode(ExceptionCode.NO_SUCH_ELEMENT);
}
}
public static <T> void add(
ParserChain chain, Class<T> type, Parser<T> parser) {
chain.parsers.put(type, parser);
}
}
| gpl-3.0 |
Boy-ming/MyAnswer | app/src/main/java/com/ming/myanswer/ScaleTextViewActivity.java | 1601 | package com.ming.myanswer;
import android.os.Bundle;
import android.widget.SeekBar;
import com.hanks.htextview.base.HTextView;
public class ScaleTextViewActivity extends BaseActivity {
private HTextView textView, textView2, textView3, textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scale_text_view);
textView = (HTextView) findViewById(R.id.textview);
textView1 = (HTextView) findViewById(R.id.textview1);
textView2 = (HTextView) findViewById(R.id.textview2);
textView3 = (HTextView) findViewById(R.id.textview3);
textView.setOnClickListener(new ClickListener());
textView1.setOnClickListener(new ClickListener());
textView2.setOnClickListener(new ClickListener());
textView3.setOnClickListener(new ClickListener());
((SeekBar) findViewById(R.id.seekbar)).setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setProgress(progress / 100f);
textView1.setProgress(progress / 100f);
textView2.setProgress(progress / 100f);
textView3.setProgress(progress / 100f);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
| gpl-3.0 |
leonardost/ars | src/aprendizadodemaquina/features/superficiais/FeatureTokensTermosCapitalizados.java | 2288 | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyright (C) 2012-2013 LaLiC
*/
package aprendizadodemaquina.features.superficiais;
import anotadorderelacoes.model.Sentenca;
import anotadorderelacoes.model.Termo;
import anotadorderelacoes.model.Token;
import anotadorderelacoes.model.Utilidades;
import aprendizadodemaquina.Feature;
import java.util.ArrayList;
import java.util.List;
/**
* Feature que diz o número de tokens que compõem os termos que iniciam com
* letra maiúscula.
*/
public class FeatureTokensTermosCapitalizados extends Feature {
@Override
public String nome() {
return "numero_tokens_capitalizados_em_termo";
}
@Override
public List<Object> gerar(Sentenca s, Termo t1, Termo t2) {
List<Object> valores = new ArrayList<Object>();
int numeroCapitalizadas = 0;
List<Token> tokens = Utilidades.tokensTermo(s, t1);
for ( Token t : tokens )
if ( Character.isUpperCase( t.getToken().charAt(0) ) )
++numeroCapitalizadas;
valores.add( new Integer(numeroCapitalizadas) );
numeroCapitalizadas = 0;
tokens = Utilidades.tokensTermo(s, t2);
for ( Token t : tokens )
if ( Character.isUpperCase( t.getToken().charAt(0) ) )
++numeroCapitalizadas;
valores.add( new Integer(numeroCapitalizadas) );
return valores;
}
@Override
public int quantosValores() {
return 2;
}
@Override
public String tipo() {
return "NUMERICO";
}
@Override
public String[] valoresPossivis() {
return null;
}
}
| gpl-3.0 |
llbit/chunky | chunky/src/java/se/llbit/chunky/entity/PlayerEntity.java | 36733 | /*
* Copyright (c) 2017 Jesper Öqvist <jesper@llbit.se>
*
* This file is part of Chunky.
*
* Chunky is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Chunky is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Chunky. If not, see <http://www.gnu.org/licenses/>.
*/
package se.llbit.chunky.entity;
import se.llbit.chunky.block.Head;
import se.llbit.chunky.entity.SkullEntity.Kind;
import se.llbit.chunky.renderer.scene.PlayerModel;
import se.llbit.chunky.resources.EntityTexture;
import se.llbit.chunky.resources.Texture;
import se.llbit.chunky.resources.TextureCache;
import se.llbit.chunky.resources.TexturePackLoader;
import se.llbit.chunky.resources.texturepack.ColoredTexture;
import se.llbit.chunky.resources.texturepack.EntityTextureLoader;
import se.llbit.chunky.resources.texturepack.LayeredTextureLoader;
import se.llbit.chunky.resources.texturepack.SimpleTexture;
import se.llbit.chunky.resources.texturepack.TextureFormatError;
import se.llbit.chunky.resources.texturepack.TextureLoader;
import se.llbit.chunky.world.PlayerEntityData;
import se.llbit.chunky.world.material.TextureMaterial;
import se.llbit.chunky.world.model.CubeModel;
import se.llbit.chunky.world.model.JsonModel;
import se.llbit.json.Json;
import se.llbit.json.JsonObject;
import se.llbit.json.JsonParser;
import se.llbit.json.JsonValue;
import se.llbit.log.Log;
import se.llbit.math.Quad;
import se.llbit.math.QuickMath;
import se.llbit.math.Transform;
import se.llbit.math.Vector3;
import se.llbit.math.Vector4;
import se.llbit.math.primitive.Box;
import se.llbit.math.primitive.Primitive;
import se.llbit.nbt.CompoundTag;
import se.llbit.nbt.Tag;
import se.llbit.util.JsonUtil;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;
public class PlayerEntity extends Entity implements Poseable, Geared {
private static final String[] partNames =
{ "all", "head", "chest", "leftArm", "rightArm", "leftLeg", "rightLeg" };
private static final String[] gearSlots =
{ "leftHand", "rightHand", "head", "chest", "legs", "feet" };
public final String uuid;
public JsonObject gear = new JsonObject();
public JsonObject pose = new JsonObject();
public double scale = 1.0;
public double headScale = 1.0;
public PlayerModel model;
public String skin = "";
public PlayerEntity(String uuid, Vector3 position) {
this(uuid, position, 0, 0, new JsonObject());
}
public PlayerEntity(PlayerEntityData data) {
this(data.uuid, new Vector3(data.x, data.y, data.z), data.rotation, data.pitch,
buildGear(data));
}
protected PlayerEntity(String uuid, Vector3 position, double rotationDegrees, double pitchDegrees,
JsonObject gear) {
super(position);
this.uuid = uuid;
this.model = PlayerModel.STEVE;
this.gear = gear;
double rotation = QuickMath.degToRad(180 - rotationDegrees);
JsonObject pose = new JsonObject();
pose.add("all", JsonUtil.vec3ToJson(new Vector3(0, rotation, 0)));
pose.add("head", JsonUtil.vec3ToJson(new Vector3(-QuickMath.degToRad(pitchDegrees), 0, 0)));
pose.add("leftArm", JsonUtil.vec3ToJson(new Vector3(0.4, 0, 0)));
pose.add("rightArm", JsonUtil.vec3ToJson(new Vector3(-0.4, 0, 0)));
pose.add("leftLeg", JsonUtil.vec3ToJson(new Vector3(0.4, 0, 0)));
pose.add("rightLeg", JsonUtil.vec3ToJson(new Vector3(-0.4, 0, 0)));
this.pose = pose;
}
public PlayerEntity(JsonObject settings) {
super(JsonUtil.vec3FromJsonObject(settings.get("position")));
this.model = PlayerModel.get(settings.get("model").stringValue("STEVE"));
this.uuid = settings.get("uuid").stringValue("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
this.skin = settings.get("skin").stringValue("");
this.scale = settings.get("scale").doubleValue(1.0);
this.headScale = settings.get("headScale").doubleValue(1.0);
this.pose = settings.get("pose").object();
this.gear = settings.get("gear").object();
}
static JsonObject parseItem(CompoundTag tag) {
JsonObject item = new JsonObject();
String id = tag.get("id").stringValue("");
item.add("id", id);
Tag color = tag.get("tag").get("display").get("color");
if (!color.isError()) {
item.add("color", color.intValue(0));
}
if (id.equals("minecraft:skull")) {
// Skull type is stored in the damage field.
int damage = tag.get("Damage").shortValue();
item.add("type", damage);
} else if (id.equals("minecraft:player_head")) {
Tag skinTag = tag.get("tag").get("SkullOwner").get("Properties").get("textures").get(0).get("Value");
if (!skinTag.isError()) {
String skinUrl = Head.getTextureUrl(tag.get("tag").asCompound());
if (skinUrl != null && !skinUrl.isEmpty()) {
item.add("skin", skinUrl);
}
}
}
return item;
}
static JsonObject buildGear(PlayerEntityData data) {
JsonObject gear = new JsonObject();
if (!data.chestplate.asCompound().isEmpty()) {
gear.add("chest", parseItem(data.chestplate.asCompound()));
}
if (!data.feet.asCompound().isEmpty()) {
gear.add("feet", parseItem(data.feet.asCompound()));
}
if (!data.head.asCompound().isEmpty()) {
gear.add("head", parseItem(data.head.asCompound()));
}
if (!data.legs.asCompound().isEmpty()) {
gear.add("legs", parseItem(data.legs.asCompound()));
}
return gear;
}
private void poseLimb(Box part, double rotation, Transform transform, Transform offset) {
part.transform(transform);
part.transform(Transform.NONE.rotateY(rotation));
part.transform(offset);
}
private void poseHead(Box part, double rotation, Transform transform,
Transform offset) {
part.transform(transform);
part.transform(Transform.NONE.rotateY(rotation));
part.transform(offset);
}
@Override public Collection<Primitive> primitives(Vector3 offset) {
EntityTexture texture = Texture.steve;
double armWidth = model == PlayerModel.ALEX ? 1.5 : 2;
if (skin.isEmpty()) {
switch (model) {
case ALEX:
texture = Texture.alex;
break;
case STEVE:
texture = Texture.steve;
break;
}
} else {
texture = new EntityTexture();
EntityTextureLoader loader = new EntityTextureLoader(skin, texture);
try {
loader.load(new File(skin));
} catch (IOException | TextureFormatError e) {
Log.warn("Failed to load skin", e);
texture = Texture.steve;
}
}
Vector3 allPose = JsonUtil.vec3FromJsonArray(pose.get("all"));
Vector3 headPose = JsonUtil.vec3FromJsonArray(pose.get("head"));
Vector3 chestPose = JsonUtil.vec3FromJsonArray(pose.get("chest"));
Vector3 leftLegPose = JsonUtil.vec3FromJsonArray(pose.get("leftLeg"));
Vector3 rightLegPose = JsonUtil.vec3FromJsonArray(pose.get("rightLeg"));
Vector3 leftArmPose = JsonUtil.vec3FromJsonArray(pose.get("leftArm"));
Vector3 rightArmPose = JsonUtil.vec3FromJsonArray(pose.get("rightArm"));
Vector3 worldOffset = new Vector3(
position.x + offset.x,
position.y + offset.y,
position.z + offset.z);
Transform worldTransform = Transform.NONE
.scale(scale)
.rotateX(allPose.x)
.rotateY(allPose.y)
.rotateZ(allPose.z)
.translate(worldOffset);
Collection<Primitive> primitives = new LinkedList<>();
if (!shouldHidePlayerHead(gear.get("head").object().get("id").stringValue(""))) {
Box head = new Box(-4 / 16., 4 / 16., -4 / 16., 4 / 16., -4 / 16., 4 / 16.);
head.transform(Transform.NONE
.translate(0, 4 / 16., 0)
.scale(headScale)
.rotateX(headPose.x)
.rotateY(headPose.y)
.rotateZ(headPose.z)
.translate(0, -4 / 16., 0)
.translate(0, 28 / 16., 0)
.chain(worldTransform));
head.addFrontFaces(primitives, texture, texture.headFront);
head.addBackFaces(primitives, texture, texture.headBack);
head.addLeftFaces(primitives, texture, texture.headLeft);
head.addRightFaces(primitives, texture, texture.headRight);
head.addTopFaces(primitives, texture, texture.headTop);
head.addBottomFaces(primitives, texture, texture.headBottom);
Box hat = new Box(-4.25 / 16., 4.25 / 16., -4.25 / 16., 4.25 / 16., -4.25 / 16., 4.25 / 16.);
hat.transform(Transform.NONE
.translate(0, 4 / 16., 0)
.scale(headScale)
.rotateX(headPose.x)
.rotateY(headPose.y)
.rotateZ(headPose.z)
.translate(0, -4 / 16., 0)
.translate(0, 28.2 / 16., 0)
.chain(worldTransform));
hat.addFrontFaces(primitives, texture, texture.hatFront);
hat.addBackFaces(primitives, texture, texture.hatBack);
hat.addLeftFaces(primitives, texture, texture.hatLeft);
hat.addRightFaces(primitives, texture, texture.hatRight);
hat.addTopFaces(primitives, texture, texture.hatTop);
hat.addBottomFaces(primitives, texture, texture.hatBottom);
}
Box chest = new Box(-4 / 16., 4 / 16., -6 / 16., 6 / 16., -2 / 16., 2 / 16.);
chest.transform(Transform.NONE
.translate(0, -5 / 16., 0)
.rotateX(chestPose.x)
.rotateY(chestPose.y)
.rotateZ(chestPose.z)
.translate(0, (5 + 18) / 16., 0)
.chain(worldTransform));
chest.addFrontFaces(primitives, texture, texture.chestFront);
chest.addBackFaces(primitives, texture, texture.chestBack);
chest.addLeftFaces(primitives, texture, texture.chestLeft);
chest.addRightFaces(primitives, texture, texture.chestRight);
chest.addTopFaces(primitives, texture, texture.chestTop);
chest.addBottomFaces(primitives, texture, texture.chestBottom);
Box leftLeg = new Box(-2 / 16., 2 / 16., -6 / 16., 6 / 16., -2 / 16., 2 / 16.);
leftLeg.transform(Transform.NONE.translate(0, -6 / 16., 0)
.rotateX(leftLegPose.x)
.rotateY(leftLegPose.y)
.rotateZ(leftLegPose.z)
.translate(-2 / 16., 12 / 16., 0)
.chain(worldTransform));
leftLeg.addFrontFaces(primitives, texture, texture.leftLegFront);
leftLeg.addBackFaces(primitives, texture, texture.leftLegBack);
leftLeg.addLeftFaces(primitives, texture, texture.leftLegLeft);
leftLeg.addRightFaces(primitives, texture, texture.leftLegRight);
leftLeg.addTopFaces(primitives, texture, texture.leftLegTop);
leftLeg.addBottomFaces(primitives, texture, texture.leftLegBottom);
Box rightLeg = new Box(-2 / 16., 2 / 16., -6 / 16., 6 / 16., -2 / 16., 2 / 16.);
rightLeg.transform(Transform.NONE.translate(0, -6 / 16., 0)
.rotateX(rightLegPose.x)
.rotateY(rightLegPose.y)
.rotateZ(rightLegPose.z)
.translate(2 / 16., 12 / 16., 0)
.chain(worldTransform));
rightLeg.addFrontFaces(primitives, texture, texture.rightLegFront);
rightLeg.addBackFaces(primitives, texture, texture.rightLegBack);
rightLeg.addLeftFaces(primitives, texture, texture.rightLegLeft);
rightLeg.addRightFaces(primitives, texture, texture.rightLegRight);
rightLeg.addTopFaces(primitives, texture, texture.rightLegTop);
rightLeg.addBottomFaces(primitives, texture, texture.rightLegBottom);
Box leftArm = new Box(-armWidth / 16., armWidth / 16., -6 / 16., 6 / 16., -2 / 16., 2 / 16.);
leftArm.transform(Transform.NONE.translate(0, -5 / 16., 0)
.rotateX(leftArmPose.x)
.rotateY(leftArmPose.y)
.rotateZ(leftArmPose.z)
.translate(-(4 + armWidth) / 16., 23 / 16., 0)
.chain(worldTransform));
leftArm.addFrontFaces(primitives, texture, texture.leftArmFront);
leftArm.addBackFaces(primitives, texture, texture.leftArmBack);
leftArm.addLeftFaces(primitives, texture, texture.leftArmLeft);
leftArm.addRightFaces(primitives, texture, texture.leftArmRight);
leftArm.addTopFaces(primitives, texture, texture.leftArmTop);
leftArm.addBottomFaces(primitives, texture, texture.leftArmBottom);
Box rightArm = new Box(-armWidth / 16., armWidth / 16., -6 / 16., 6 / 16., -2 / 16., 2 / 16.);
rightArm.transform(Transform.NONE.translate(0, -5 / 16., 0)
.rotateX(rightArmPose.x)
.rotateY(rightArmPose.y)
.rotateZ(rightArmPose.z)
.translate((4 + armWidth) / 16., 23 / 16., 0)
.chain(worldTransform));
rightArm.addFrontFaces(primitives, texture, texture.rightArmFront);
rightArm.addBackFaces(primitives, texture, texture.rightArmBack);
rightArm.addLeftFaces(primitives, texture, texture.rightArmLeft);
rightArm.addRightFaces(primitives, texture, texture.rightArmRight);
rightArm.addTopFaces(primitives, texture, texture.rightArmTop);
rightArm.addBottomFaces(primitives, texture, texture.rightArmBottom);
addArmor(primitives, gear, pose, armWidth, worldTransform, headScale);
return primitives;
}
private static boolean shouldHidePlayerHead(String helmetItemId) {
switch (helmetItemId) {
case "minecraft:skull":
case "minecraft:skeleton_skull":
case "minecraft:player_head":
case "minecraft:zombie_head":
case "minecraft:wither_skeleton_skull":
case "minecraft:creeper_head":
case "minecraft:dragon_head":
return true;
default:
return false;
}
}
public static void addArmor(Collection<Primitive> faces,
JsonObject gear,
JsonObject pose,
double armWidth,
Transform worldTransform,
double headScale) {
Vector3 headPose = JsonUtil.vec3FromJsonArray(pose.get("head"));
Vector3 chestPose = JsonUtil.vec3FromJsonArray(pose.get("chest"));
Vector3 leftArmPose = JsonUtil.vec3FromJsonArray(pose.get("leftArm"));
Vector3 rightArmPose = JsonUtil.vec3FromJsonArray(pose.get("rightArm"));
Vector3 leftLegPose = JsonUtil.vec3FromJsonArray(pose.get("leftLeg"));
Vector3 rightLegPose = JsonUtil.vec3FromJsonArray(pose.get("rightLeg"));
JsonObject headItem = gear.get("head").object();
if (!headItem.isEmpty()) {
Transform transform = Transform.NONE
.translate(-0.5, -0.5, -0.5)
.translate(0, 4.2 / 16.0, 0)
.scale(headScale)
.rotateX(headPose.x)
.rotateY(headPose.y)
.rotateZ(headPose.z)
.translate(0, (28 - 4) / 16.0, 0)
.chain(worldTransform);
String headItemId = headItem.get("id").asString("");
if (headItemId.equals("minecraft:dragon_head")) {
SkullEntity skull = new SkullEntity(new Vector3(), Kind.DRAGON, 0, 1);
faces.addAll(skull.dragonHeadPrimitives(Transform.NONE.translate(0.5, 0.5, 0.5).scale(1.2).chain(transform)));
} else if (headItemId.equals("minecraft:carved_pumpkin")) {
Box hat = new Box(-4.25 / 16., 4.25 / 16., -4.25 / 16., 4.25 / 16., -4.25 / 16., 4.25 / 16.);
hat.transform(Transform.NONE
.translate(0, 4 / 16., 0)
.scale(headScale)
.rotateX(headPose.x)
.rotateY(headPose.y)
.rotateZ(headPose.z)
.translate(0, -4 / 16., 0)
.translate(0, 28.2 / 16., 0)
.chain(worldTransform));
hat.addFrontFaces(faces, Texture.pumpkinFront, new Vector4(0, 1, 0, 1));
hat.addBackFaces(faces, Texture.pumpkinSide, new Vector4(1, 0, 0, 1));
hat.addLeftFaces(faces, Texture.pumpkinSide, new Vector4(0, 1, 0, 1));
hat.addRightFaces(faces, Texture.pumpkinSide, new Vector4(0, 1, 0, 1));
hat.addTopFaces(faces, Texture.pumpkinTop, new Vector4(1, 0, 1, 0));
hat.addBottomFaces(faces, Texture.pumpkinTop, new Vector4(0, 1, 0, 1));
} else {
addModel(faces, getHelmModel(headItem), transform);
}
}
// Add chest armor.
JsonObject chestItem = gear.get("chest").object();
if (!chestItem.isEmpty() && !chestItem.get("id").asString("").equals("minecraft:elytra")) {
// TODO render the elytra
Transform transform = Transform.NONE
.translate(0, -5 / 16.0, 0)
.rotateX(chestPose.x)
.rotateY(chestPose.y)
.rotateZ(chestPose.z)
.translate(0, (5 + 18) / 16.0, 0)
.chain(worldTransform);
addModel(faces, getChestModel(chestItem), transform);
transform = Transform.NONE
.translate(-0.5, -14 / 16., -0.5)
.rotateX(leftArmPose.x)
.rotateY(leftArmPose.y)
.rotateZ(leftArmPose.z)
.translate(-(4 + armWidth) / 16., 23 / 16., 0)
.chain(worldTransform);
addModel(faces, getLeftPauldron(chestItem), transform);
transform = Transform.NONE
.translate(-0.5, -14 / 16., -0.5)
.rotateX(rightArmPose.x)
.rotateY(rightArmPose.y)
.rotateZ(rightArmPose.z)
.translate((4 + armWidth) / 16., 23 / 16., 0)
.chain(worldTransform);
addModel(faces, getRightPauldron(chestItem), transform);
}
// Add leggings.
JsonObject legs = gear.get("legs").object();
if (!legs.isEmpty()) {
Transform transform = Transform.NONE
.translate(0, -5 / 16.0, 0)
.rotateX(chestPose.x)
.rotateY(chestPose.y)
.rotateZ(chestPose.z)
.translate(0, (5 + 18) / 16.0, 0)
.chain(worldTransform);
addModel(faces, getLeggingsModel(legs), transform);
transform = Transform.NONE
.translate(0, -6 / 16.0, 0)
.rotateX(leftLegPose.x)
.rotateY(leftLegPose.y)
.rotateZ(leftLegPose.z)
.translate(-2 / 16., 12 / 16., 0)
.chain(worldTransform);
addModel(faces, getLeftLeg(legs), transform);
transform = Transform.NONE
.translate(0, -6 / 16.0, 0)
.rotateX(rightLegPose.x)
.rotateY(rightLegPose.y)
.rotateZ(rightLegPose.z)
.translate(2 / 16., 12 / 16., 0)
.chain(worldTransform);
addModel(faces, getRightLeg(legs), transform);
}
JsonObject feet = gear.get("feet").object();
if (!feet.isEmpty()) {
Transform transform = Transform.NONE
.translate(0, -6 / 16.0, 0)
.rotateX(leftLegPose.x)
.rotateY(leftLegPose.y)
.rotateZ(leftLegPose.z)
.translate(-2 / 16., 12 / 16., 0)
.chain(worldTransform);
addModel(faces, getLeftBoot(feet), transform);
transform = Transform.NONE
.translate(0, -6 / 16.0, 0)
.rotateX(rightLegPose.x)
.rotateY(rightLegPose.y)
.rotateZ(rightLegPose.z)
.translate(2 / 16., 12 / 16., 0)
.chain(worldTransform);
addModel(faces, getRightBoot(feet), transform);
}
}
private static final String chestJson =
"{\"elements\":[{\"from\":[-4.4,-6,-2.4],\"to\":[4.4,6,2.4],\"faces\":{\"east\":{\"uv\":[7,10,8,16],\"texture\":\"#texture\"},\"west\":{\"uv\":[4,10,5,16],\"texture\":\"#texture\"},\"north\":{\"uv\":[8,10,10,16],\"texture\":\"#texture\"},\"south\":{\"uv\":[5,10,7,16],\"texture\":\"#texture\"}}}]}";
private static final String leggingsJson =
"{\"elements\":[{\"from\":[-4.2,-6,-2.2],\"to\":[4.2,6,2.2],\"faces\":{\"east\":{\"uv\":[7,10,8,16],\"texture\":\"#texture\"},\"west\":{\"uv\":[4,10,5,16],\"texture\":\"#texture\"},\"north\":{\"uv\":[8,10,10,16],\"texture\":\"#texture\"},\"south\":{\"uv\":[5,10,7,16],\"texture\":\"#texture\"}}}]}";
private static final String helmJson =
"{\"elements\":[{\"from\":[3,3,3],\"to\":[13,13,13],\"faces\":{\"up\":{\"uv\":[2,0,4,4],\"texture\":\"#texture\"},\"east\":{\"uv\":[0,4,2,8],\"texture\":\"#texture\"},\"west\":{\"uv\":[4,4,6,8],\"texture\":\"#texture\"},\"north\":{\"uv\":[2,4,4,8],\"texture\":\"#texture\"},\"south\":{\"uv\":[6,4,8,8],\"texture\":\"#texture\"}}}]}";
private static final String headJson =
"{\"elements\":[{\"from\":[4,4,4],\"to\":[12,12,12],\"faces\":{\"up\":{\"uv\":[4,2,2,0],\"texture\":\"#texture\"},\"down\":{\"uv\":[4,0,6,2],\"texture\":\"#texture\"},\"east\":{\"uv\":[6,2,4,4],\"texture\":\"#texture\"},\"west\":{\"uv\":[2,2,0,4],\"texture\":\"#texture\"},\"north\":{\"uv\":[2,2,4,4],\"texture\":\"#texture\"},\"south\":{\"uv\":[6,2,8,4],\"texture\":\"#texture\"}}},{\"from\":[3.75,3.75,3.75],\"to\":[12.25,12.25,12.25],\"faces\":{\"up\":{\"uv\":[12,2,10,0],\"texture\":\"#texture\"},\"down\":{\"uv\":[12,0,14,2],\"texture\":\"#texture\"},\"east\":{\"uv\":[14,2,12,4],\"texture\":\"#texture\"},\"west\":{\"uv\":[10,2,8,4],\"texture\":\"#texture\"},\"north\":{\"uv\":[10,2,12,4],\"texture\":\"#texture\"},\"south\":{\"uv\":[14,2,14,4],\"texture\":\"#texture\"}}}]}";
// The difference between skullJson/headJson is that skullJson is textured with a half as tall texture and has no hat.
private static final String skullJson =
"{\"elements\":[{\"from\":[4,4,4],\"to\":[12,12,12],\"faces\":{\"up\":{\"uv\":[2,0,4,4],\"texture\":\"#texture\"},\"down\":{\"uv\":[4,0,6,4],\"texture\":\"#texture\"},\"east\":{\"uv\":[6,4,4,8],\"texture\":\"#texture\"},\"west\":{\"uv\":[2,4,0,8],\"texture\":\"#texture\"},\"north\":{\"uv\":[2,4,4,8],\"texture\":\"#texture\"},\"south\":{\"uv\":[6,4,8,8],\"texture\":\"#texture\"}}}]}";
private static final String leftPauldron =
"{\"elements\":[{\"from\":[5,0,5],\"to\":[11,16,11],\"faces\":{\"up\":{\"uv\":[11,8,12,10],\"texture\":\"#texture\"},\"east\":{\"uv\":[12,10,13,16],\"texture\":\"#texture\"},\"west\":{\"uv\":[10,10,11,16],\"texture\":\"#texture\"},\"north\":{\"uv\":[13,10,14,16],\"texture\":\"#texture\"},\"south\":{\"uv\":[11,10,12,16],\"texture\":\"#texture\"}}}]}";
private static final String rightPauldron =
"{\"elements\":[{\"from\":[5,0,5],\"to\":[11,16,11],\"faces\":{\"up\":{\"uv\":[12,8,11,10],\"texture\":\"#texture\"},\"east\":{\"uv\":[11,10,10,16],\"texture\":\"#texture\"},\"west\":{\"uv\":[13,10,12,16],\"texture\":\"#texture\"},\"north\":{\"uv\":[14,10,13,16],\"texture\":\"#texture\"},\"south\":{\"uv\":[12,10,11,16],\"texture\":\"#texture\"}}}]}";
private static final String leftLeg =
"{\"elements\":[{\"from\":[-2.2,-6.2,-2.2],\"to\":[2.2,6.2,2.2],\"faces\":{\"up\":{\"uv\":[1,8,2,10],\"texture\":\"#texture\"},\"east\":{\"uv\":[3,10,2,16],\"texture\":\"#texture\"},\"west\":{\"uv\":[1,10,0,16],\"texture\":\"#texture\"},\"north\":{\"uv\":[2,10,1,16],\"texture\":\"#texture\"},\"south\":{\"uv\":[4,10,3,16],\"texture\":\"#texture\"}}}]}";
private static final String rightLeg =
"{\"elements\":[{\"from\":[-2.2,-6.2,-2.2],\"to\":[2.2,6.2,2.2],\"faces\":{\"up\":{\"uv\":[1,8,2,10],\"texture\":\"#texture\"},\"east\":{\"uv\":[0,10,1,16],\"texture\":\"#texture\"},\"west\":{\"uv\":[2,10,3,16],\"texture\":\"#texture\"},\"north\":{\"uv\":[1,10,2,16],\"texture\":\"#texture\"},\"south\":{\"uv\":[3,10,4,16],\"texture\":\"#texture\"}}}]}";
private static final String leftBoot =
"{\"elements\":[{\"from\":[-2.5,-6.5,-2.5],\"to\":[2.5,6.5,2.5],\"faces\":{\"down\":{\"uv\":[2,8,3,10],\"texture\":\"#texture\"},\"east\":{\"uv\":[3,10,2,16],\"texture\":\"#texture\"},\"west\":{\"uv\":[1,10,0,16],\"texture\":\"#texture\"},\"north\":{\"uv\":[2,10,1,16],\"texture\":\"#texture\"},\"south\":{\"uv\":[4,10,3,16],\"texture\":\"#texture\"}}}]}";
private static final String rightBoot =
"{\"elements\":[{\"from\":[-2.5,-6.5,-2.5],\"to\":[2.5,6.5,2.5],\"faces\":{\"down\":{\"uv\":[3,8,2,10],\"texture\":\"#texture\"},\"east\":{\"uv\":[0,10,1,16],\"texture\":\"#texture\"},\"west\":{\"uv\":[2,10,3,16],\"texture\":\"#texture\"},\"north\":{\"uv\":[1,10,2,16],\"texture\":\"#texture\"},\"south\":{\"uv\":[3,10,4,16],\"texture\":\"#texture\"}}}]}";
private static void addModel(Collection<Primitive> primitives, CubeModel model,
Transform baseTransform) {
for (int i = 0; i < model.quads.length; ++i) {
Quad quad = model.quads[i];
Texture texture = model.textures[i];
quad.addTriangles(primitives, new TextureMaterial(texture), baseTransform);
}
}
static CubeModel getChestModel(JsonObject item) {
JsonObject json = parseJson(chestJson);
Map<String, Texture> textureMap = Collections.singletonMap("#texture", getTexture(item));
return new CubeModel(JsonModel.fromJson(json), 16, textureMap);
}
private static CubeModel getLeggingsModel(JsonObject item) {
JsonObject json = parseJson(leggingsJson);
Map<String, Texture> textureMap = Collections.singletonMap("#texture", getTexture(item));
return new CubeModel(JsonModel.fromJson(json), 16, textureMap);
}
static CubeModel getLeftPauldron(JsonObject item) {
JsonObject json = parseJson(leftPauldron);
Map<String, Texture> textureMap = Collections.singletonMap("#texture", getTexture(item));
return new CubeModel(JsonModel.fromJson(json), 16, textureMap);
}
static CubeModel getRightPauldron(JsonObject item) {
JsonObject json = parseJson(rightPauldron);
Map<String, Texture> textureMap = Collections.singletonMap("#texture", getTexture(item));
return new CubeModel(JsonModel.fromJson(json), 16, textureMap);
}
private static CubeModel getLeftLeg(JsonObject item) {
JsonObject json = parseJson(leftLeg);
Map<String, Texture> textureMap = Collections.singletonMap("#texture", getTexture(item));
return new CubeModel(JsonModel.fromJson(json), 16, textureMap);
}
private static CubeModel getRightLeg(JsonObject item) {
JsonObject json = parseJson(rightLeg);
Map<String, Texture> textureMap = Collections.singletonMap("#texture", getTexture(item));
return new CubeModel(JsonModel.fromJson(json), 16, textureMap);
}
private static CubeModel getLeftBoot(JsonObject item) {
JsonObject json = parseJson(leftBoot);
Map<String, Texture> textureMap = Collections.singletonMap("#texture", getTexture(item));
return new CubeModel(JsonModel.fromJson(json), 16, textureMap);
}
private static CubeModel getRightBoot(JsonObject item) {
JsonObject json = parseJson(rightBoot);
Map<String, Texture> textureMap = Collections.singletonMap("#texture", getTexture(item));
return new CubeModel(JsonModel.fromJson(json), 16, textureMap);
}
static CubeModel getHelmModel(JsonObject item) {
String id = item.get("id").asString("");
JsonObject json = parseJson(helmJson);
if (id.equals("minecraft:skull")) {
// Reference: https://minecraft.gamepedia.com/Mob_head#Data_values
int type = item.get("type").asInt(3);
switch (type) {
case 0:
// Skeleton skull.
json = parseJson(skullJson);
break;
case 1:
// Wither skeleton skull.
json = parseJson(skullJson);
break;
case 2:
// Zombie head.
json = parseJson(headJson);
break;
case 3:
// Steve head.
json = parseJson(headJson);
break;
case 4:
// Creeper head.
json = parseJson(skullJson);
break;
case 5:
// Dragon head.
json = parseJson(skullJson);
break;
}
} else if (id.equals("minecraft:player_head") || id.equals("minecraft:zombie_head")) {
json = parseJson(headJson);
} else if (id.equals("minecraft:skeleton_skull") || id.equals("minecraft:wither_skeleton_skull")
|| id.equals("minecraft:creeper_head")) {
json = parseJson(skullJson);
}
Map<String, Texture> textureMap = Collections.singletonMap("#texture", getTexture(item));
return new CubeModel(JsonModel.fromJson(json), 16, textureMap);
}
public static JsonObject parseJson(String helmetJson) {
try (ByteArrayInputStream in = new ByteArrayInputStream(helmetJson.getBytes());
JsonParser parser = new JsonParser(in)) {
return parser.parse().object();
} catch (IOException | JsonParser.SyntaxError e) {
Log.warn("Failed to parse JSON", e);
return new JsonObject();
}
}
private Transform withScale(Transform transform) {
if (scale == 1.0) {
return transform;
} else {
return transform.scale(scale);
}
}
@Override public JsonValue toJson() {
JsonObject json = new JsonObject();
json.add("kind", "player");
json.add("uuid", uuid);
json.add("position", position.toJson());
json.add("model", model.name());
json.add("skin", skin);
json.add("pose", pose);
json.add("gear", gear);
json.add("scale", scale);
json.add("headScale", headScale);
return json;
}
static Texture getTexture(JsonObject item) {
String id = item.get("id").asString("");
if (TextureCache.containsKey(item)) {
return TextureCache.get(item);
}
Texture texture = new Texture();
String textureId = id; // Texture ID is used for log messages.
if (id.startsWith("minecraft:")) {
TextureLoader loader = null;
switch (id.substring("minecraft:".length())) {
case "skull": {
// Reference: https://minecraft.gamepedia.com/Mob_head#Data_values
int type = item.get("type").asInt(3);
switch (type) {
case 0:
// Skeleton skull.
textureId = "entity/skeleton/skeleton";
break;
case 1:
// Wither skeleton skull.
textureId = "entity/skeleton/wither_skeleton";
break;
case 2:
// Zombie head.
textureId = "entity/zombie/zombie";
break;
case 3:
// Steve head.
textureId = "entity/steve";
break;
case 4:
// Creeper head.
textureId = "entity/creeper/creeper";
break;
case 5:
// Dragon head.
textureId = "entity/enderdragon/dragon";
break;
}
loader = simpleTexture(textureId, texture);
break;
}
case "skeleton_skull":
loader = simpleTexture("entity/skeleton/skeleton", texture);
break;
case "wither_skeleton_skull":
loader = simpleTexture("entity/skeleton/wither_skeleton", texture);
break;
case "zombie_head":
loader = simpleTexture("entity/zombie/zombie", texture);
break;
case "creeper_head":
loader = simpleTexture("entity/creeper/creeper", texture);
break;
case "dragon_head":
loader = simpleTexture("entity/enderdragon/dragon", texture);
break;
case "leather_boots":
case "leather_helmet":
case "leather_chestplate":
loader = leatherTexture("models/armor/leather_layer_1",
item.get("color").intValue(0x96613A), texture);
break;
case "leather_leggings":
loader = leatherTexture("models/armor/leather_layer_2",
item.get("color").intValue(0x96613A), texture);
break;
case "golden_boots":
case "golden_helmet":
case "golden_chestplate":
loader = simpleTexture("models/armor/gold_layer_1", texture);
break;
case "golden_leggings":
loader = simpleTexture("models/armor/gold_layer_2", texture);
break;
case "iron_boots":
case "iron_helmet":
case "iron_chestplate":
loader = simpleTexture("models/armor/iron_layer_1", texture);
break;
case "iron_leggings":
loader = simpleTexture("models/armor/iron_layer_2", texture);
break;
case "chainmail_boots":
case "chainmail_helmet":
case "chainmail_chestplate":
loader = simpleTexture("models/armor/chainmail_layer_1", texture);
break;
case "chainmail_leggings":
loader = simpleTexture("models/armor/chainmail_layer_2", texture);
break;
case "diamond_boots":
case "diamond_helmet":
case "diamond_chestplate":
loader = simpleTexture("models/armor/diamond_layer_1", texture);
break;
case "diamond_leggings":
loader = simpleTexture("models/armor/diamond_layer_2", texture);
break;
case "netherite_boots":
case "netherite_helmet":
case "netherite_chestplate":
loader = simpleTexture("models/armor/netherite_layer_1", texture);
break;
case "netherite_leggings":
loader = simpleTexture("models/armor/netherite_layer_2", texture);
break;
case "turtle_helmet":
loader = simpleTexture("models/armor/turtle_layer_1", texture);
break;
case "player_head":
String skin = item.get("skin").asString("");
if (!skin.isEmpty()) {
texture = HeadEntity.downloadTexture(skin);
} else {
loader = simpleTexture("entity/steve", texture);
}
break;
case "carved_pumpkin":
// nothing to do but this item is supported
break;
default:
Log.warnf("Unknown item ID: %s%n", id);
}
if (loader != null) {
// TODO: defer loading.
Map<String, TextureLoader> toLoad = Collections.singletonMap(textureId, loader);
Log.infof("Loading textures: %s", toLoad.keySet().toString());
Collection<Map.Entry<String, TextureLoader>> missing =
TexturePackLoader.loadTextures(toLoad.entrySet());
for (Map.Entry<String, TextureLoader> tex : missing) {
Log.warnf("Failed to load texture: %s", tex.getValue());
}
}
}
TextureCache.put(item, texture);
return texture;
}
private static TextureLoader simpleTexture(String id, Texture texture) {
return new SimpleTexture("assets/minecraft/textures/" + id, texture);
}
private static TextureLoader leatherTexture(String id, int color, Texture texture) {
String textureName = "assets/minecraft/textures/" + id;
return new LayeredTextureLoader(textureName + "_overlay", texture,
new ColoredTexture(textureName, color, texture));
}
public static PlayerEntity fromJson(JsonObject json) {
return new PlayerEntity(json);
}
@Override public String toString() {
return "player: " + uuid;
}
@Override public int hashCode() {
return uuid.hashCode();
}
@Override public boolean equals(Object obj) {
if (obj instanceof PlayerEntity) {
return ((PlayerEntity) obj).uuid.equals(uuid);
}
return false;
}
public void setTexture(String path) {
skin = path;
}
public void randomPoseAndLook() {
Random random = new Random(System.currentTimeMillis());
randomPose(random);
randomLook(random);
}
public void randomPose() {
Random random = new Random(System.currentTimeMillis());
randomPose(random);
}
private void randomPose(Random random) {
double leftLegPose = (random.nextFloat() - 0.5) * QuickMath.HALF_PI;
double rightLegPose = -leftLegPose;
double leftArmPose = (random.nextFloat() - 0.5) * QuickMath.HALF_PI;
double rightArmPose = -leftArmPose;
pose.add("leftArm", JsonUtil.vec3ToJson(new Vector3(leftArmPose, 0, 0)));
pose.add("rightArm", JsonUtil.vec3ToJson(new Vector3(rightArmPose, 0, 0)));
pose.add("leftLeg", JsonUtil.vec3ToJson(new Vector3(leftLegPose, 0, 0)));
pose.add("rightLeg", JsonUtil.vec3ToJson(new Vector3(rightLegPose, 0, 0)));
}
private void randomLook(Random random) {
pose.set("rotation", Json.of((random.nextFloat() - 0.5) * QuickMath.TAU));
double headYaw = 0.4 * (random.nextFloat() - 0.5) * QuickMath.HALF_PI;
double pitch = (random.nextFloat() - 0.5) * QuickMath.HALF_PI;
pose.add("head", JsonUtil.vec3ToJson(new Vector3(pitch, headYaw, 0)));
}
@Override public String[] partNames() {
return partNames;
}
@Override public double getScale() {
return scale;
}
@Override public void setScale(double value) {
scale = value;
}
@Override public double getHeadScale() {
return headScale;
}
@Override public void setHeadScale(double value) {
headScale = value;
}
@Override public JsonObject getPose() {
return pose;
}
@Override public String[] gearSlots() {
return gearSlots;
}
@Override public JsonObject getGear() {
return gear;
}
}
| gpl-3.0 |
OpenWatch/OpenWatch-Android | app/OpenWatch/src/org/ale/openwatch/http/HttpClient.java | 5370 | package org.ale.openwatch.http;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.util.Log;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.PersistentCookieStore;
import org.ale.openwatch.R;
import org.ale.openwatch.SECRETS;
import org.ale.openwatch.constants.Constants;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.InputStream;
import java.security.*;
public class HttpClient {
private static final String TAG = "HttpClient";
private static final boolean USE_SSL_PINNING = true;
public static String USER_AGENT = null;
// Cache http clients
private static AsyncHttpClient asyncHttpClient;
/**
* Returns a new AsyncHttpClient initialized with a PersistentCookieStore
*
* @param c
* the context used to get SharePreferences for cookie
* persistence and sslsocketfactory creation
* @return an initialized AsyncHttpClient
*/
public static AsyncHttpClient setupAsyncHttpClient(Context c) {
if(asyncHttpClient != null){
//Log.i("setupAsyncHttpClient","client cached");
return asyncHttpClient;
}else{
//Log.i("setupAsyncHttpClient","client not cached");
}
AsyncHttpClient httpClient = setupVanillaAsyncHttpClient();
PersistentCookieStore cookie_store = new PersistentCookieStore(c);
httpClient.setCookieStore(cookie_store);
// List cookies = cookie_store.getCookies();
// Log.i(TAG, "Setting cookie store. size: " +
// cookie_store.getCookies().size());
if(USER_AGENT == null){
USER_AGENT = Constants.USER_AGENT_BASE;
try {
PackageInfo pInfo = c.getPackageManager().getPackageInfo(
c.getPackageName(), 0);
USER_AGENT += pInfo.versionName;
} catch (NameNotFoundException e) {
Log.e(TAG, "Unable to read PackageName in RegisterApp");
e.printStackTrace();
USER_AGENT += "unknown";
}
USER_AGENT += " (Android API " + Build.VERSION.RELEASE + ")";
}
httpClient.setUserAgent(USER_AGENT);
// Pin SSL cert if not hitting dev endpoint
if(!Constants.USE_DEV_ENDPOINTS && USE_SSL_PINNING){
httpClient.setSSLSocketFactory(createApacheOWSSLSocketFactory(c));
}
asyncHttpClient = httpClient;
return asyncHttpClient;
}
// For non ssl, no-cookie store use
private static AsyncHttpClient setupVanillaAsyncHttpClient() {
return new AsyncHttpClient();
}
public static DefaultHttpClient setupDefaultHttpClient(Context c){
//if(defaultHttpClient != null)
// return defaultHttpClient;
DefaultHttpClient httpClient = new DefaultHttpClient();
PersistentCookieStore cookie_store = new PersistentCookieStore(c);
httpClient.setCookieStore(cookie_store);
SSLSocketFactory socketFactory;
try {
// Pin SSL cert if not hitting dev endpoint
if(!Constants.USE_DEV_ENDPOINTS && USE_SSL_PINNING){
socketFactory = new SSLSocketFactory(loadOWKeyStore(c));
Scheme sch = new Scheme("https", socketFactory, 443);
httpClient.getConnectionManager().getSchemeRegistry().register(sch);
}
//defaultHttpClient = httpClient;
//return defaultHttpClient;
return httpClient;
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* For Android-Async-Http's AsyncClient
*
* @param context
* @return
*/
public static SSLSocketFactory createApacheOWSSLSocketFactory(
Context context) {
try {
// Pass the keystore to the SSLSocketFactory. The factory is
// responsible
// for the verification of the server certificate.
SSLSocketFactory sf = new SSLSocketFactory(loadOWKeyStore(context));
// Hostname verification from certificate
// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
return sf;
} catch (Exception e) {
throw new AssertionError(e);
}
}
private static KeyStore loadOWKeyStore(Context c) {
KeyStore trusted = null;
try {
// Get an instance of the Bouncy Castle KeyStore format
trusted = KeyStore.getInstance("BKS");
// Get the raw resource, which contains the keystore with
// your trusted certificates (root and any intermediate certs)
InputStream in = c.getResources().openRawResource(R.raw.owkeystore);
try {
// Initialize the keystore with the provided trusted
// certificates
// Also provide the password of the keystore
trusted.load(in, SECRETS.SSL_KEYSTORE_PASS.toCharArray());
} finally {
in.close();
}
} catch (Exception e) {
throw new AssertionError(e);
}
return trusted;
}
public static void clearCookieStore(Context c){
PersistentCookieStore cookie_store = new PersistentCookieStore(c);
cookie_store.clear();
}
}
| gpl-3.0 |
Rahulpurohit/AndroidMVP-Dagger2-JavaRx-ActiveAndroidORM | app/src/main/java/prohit/androiddevelopertest/utill/BaseScheduler.java | 216 | package prohit.androiddevelopertest.utill;
import rx.Scheduler;
/**
* Created by Rahul Purohit on 11/8/2016.
*/
public interface BaseScheduler {
Scheduler mainThread();
Scheduler backgroundThread();
}
| gpl-3.0 |
OpenSourceConsulting/athena-peacock | controller/src/main/java/com/athena/peacock/controller/web/common/dto/BaseDto.java | 2977 | /*
* Athena Peacock Project - Server Provisioning Engine for IDC or Cloud
*
* Copyright (C) 2013 Open Source Consulting, Inc. All rights reserved by Open Source Consulting, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Revision History
* Author Date Description
* --------------- ---------------- ------------
* Sang-cheon Park 2013. 8. 25. First Draft.
*/
package com.athena.peacock.controller.web.common.dto;
import java.io.Serializable;
import java.util.Date;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
/**
* <pre>
*
* </pre>
* @author Sang-cheon Park
* @version 1.0
*/
public class BaseDto implements Serializable {
private static final long serialVersionUID = 1L;
private Integer regUserId;
private Date regDt;
private Integer updUserId;
private Date updDt;
/** 페이징 관련 */
private int start;
private int limit = 10;
/**
* @return the regUserId
*/
public Integer getRegUserId() {
return regUserId;
}
/**
* @param regUserId the regUserId to set
*/
public void setRegUserId(Integer regUserId) {
this.regUserId = regUserId;
}
/**
* @return the regDt
*/
public Date getRegDt() {
return regDt;
}
/**
* @param regDt the regDt to set
*/
public void setRegDt(Date regDt) {
this.regDt = regDt;
}
/**
* @return the updUserId
*/
public Integer getUpdUserId() {
return updUserId;
}
/**
* @param updUserId the updUserId to set
*/
public void setUpdUserId(Integer updUserId) {
this.updUserId = updUserId;
}
/**
* @return the updDt
*/
public Date getUpdDt() {
return updDt;
}
/**
* @param updDt the updDt to set
*/
public void setUpdDt(Date updDt) {
this.updDt = updDt;
}
/**
* @return the start
*/
public int getStart() {
return start;
}
/**
* @param start the start to set
*/
public void setStart(int start) {
this.start = start;
}
/**
* @return the limit
*/
public int getLimit() {
return limit;
}
/**
* @param limit the limit to set
*/
public void setLimit(int limit) {
this.limit = limit;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
//end of BaseDto.java | gpl-3.0 |
jpchanson/OpenDMS | src/tomoBay/model/sql/queries/concreteQueries/UpdatePrestigeStockReq.java | 3224 | package tomoBay.model.sql.queries.concreteQueries;
/** Copyright(C) 2015 Jan P.C. Hanson & Tomo Motor Parts Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import tomoBay.model.sql.ConnectionManager;
import tomoBay.model.sql.queries.AbstractDBQuery;
/**
* This class represents a query that updates the prestige specific parts table of the database
* with data representing the amount of required stock, given a particular part number.
*
* @author Jan P.C. Hanson
*
*/
public class UpdatePrestigeStockReq implements AbstractDBQuery
{
/**reference to the JDBC Statement**/
private PreparedStatement statement_M = null;
/**reference to the JDBC Database connection**/
private Connection connection_M = null;
/**SQL query string**/
private String query ="UPDATE parts_prestige SET required=? WHERE partNo=?";
/**
* default constructor
*/
public UpdatePrestigeStockReq()
{super();}
/**
* execute the query
* @param parameter an array of strings where the 0th element is the parameter for the
* first column, the 1st element is the parameter for the 2nd column and so on.
* This query only needs 2 inputs columns so any element above the 1st element will be ignored.
* - col1 = required:int(6)
* - col2 = partNo:varchar(50)
* @return List<String[]> representing the results of the query. The list contains only 1
* String[] which in turn contains only 1 element, this is the resultcode for the query.
* @throws SQLException
*/
public List<String[]> execute(String[] parameter) throws SQLException
{
List<String[]> res = new ArrayList<String[]>();
this.initQuery();
this.statement_M.setInt(1, Integer.parseInt(parameter[0])); //required
this.statement_M.setString(2, parameter[1]);
int resultCode = statement_M.executeUpdate();
this.connection_M.commit();
this.cleanup();
res.add(new String[] {resultCode+""});
return res;
}
/**
* initialise the connection and statement and set transaction variables.
* @throws SQLException
*/
private void initQuery() throws SQLException
{
this.connection_M = ConnectionManager.instance().getConnection();
this.connection_M.setAutoCommit(false);
statement_M = connection_M.prepareStatement(query);
}
/**
* do cleanup after the query has been executed
* @throws SQLException
*/
private void cleanup() throws SQLException
{
if (statement_M != null) {statement_M.close();}
if (connection_M != null) {connection_M.close();}
}
} | gpl-3.0 |
CMPUT301F15T03/301p | T03/app/src/main/java/ca/ualberta/cmput301/t03/trading/TradeOfferComposeActivity.java | 15506 | /*
* Copyright (C) 2015 Kyle O'Shaughnessy, Ross Anderson, Michelle Mabuyo, John Slevinsky, Udey Rishi, Quentin Lautischer
* Photography equipment trading application for CMPUT 301 at the University of Alberta.
*
* This file is part of "Trading Post"
*
* "Trading Post" is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ca.ualberta.cmput301.t03.trading;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import org.parceler.Parcels;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import ca.ualberta.cmput301.t03.Observable;
import ca.ualberta.cmput301.t03.Observer;
import ca.ualberta.cmput301.t03.PrimaryUser;
import ca.ualberta.cmput301.t03.R;
import ca.ualberta.cmput301.t03.TradeApp;
import ca.ualberta.cmput301.t03.common.exceptions.ExceptionUtils;
import com.udeyrishi.androidelasticsearchdatamanager.exceptions.ServiceNotAvailableException;
import ca.ualberta.cmput301.t03.inventory.Inventory;
import ca.ualberta.cmput301.t03.inventory.Item;
import ca.ualberta.cmput301.t03.inventory.ItemsAdapter;
import ca.ualberta.cmput301.t03.trading.exceptions.IllegalTradeModificationException;
import ca.ualberta.cmput301.t03.user.User;
/**
* The view portion of the TradeOfferCompose triplet. this is the view a user will see when
* they wish to compose a trade with another user and their item.
*/
public class TradeOfferComposeActivity extends AppCompatActivity implements Observer{
private final Activity activity = this;
public final static String EXTRA_PREV_TRADE_UUID = "prevuuid";
private Trade model;
private TradeOfferComposeController controller;
private TextView ownerUsername;
private Button offerButton;
private Button cancelButton;
private Button addItemButton;
private ListView ownerItemListView;
private ItemsAdapter<Inventory> ownerItemAdapter;
private ListView borrowerItemListView;
private ItemsAdapter<Inventory> borrowerItemAdapter;
private Inventory borrowerInventory;
private Inventory ownerInventory;
private Inventory ownerItems;
private Inventory borrowerItems;
private Button requestItemButton;
/**
* Sets up the view with all components, the model, and the controller
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trade_offer_compose);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getIntent().hasExtra(EXTRA_PREV_TRADE_UUID)) {
UUID previousUUID = (UUID) getIntent().getSerializableExtra(EXTRA_PREV_TRADE_UUID);
}
ownerUsername = (TextView) findViewById(R.id.tradeComposeOtherUser);
offerButton = (Button) findViewById(R.id.tradeComposeOffer);
cancelButton = (Button) findViewById(R.id.tradeComposeCancel);
addItemButton = (Button) findViewById(R.id.tradeComposeAddItem);
requestItemButton = (Button) findViewById(R.id.tradeComposeRequestItem);
AdapterView.OnItemClickListener deleteItemListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Item item = (Item) parent.getItemAtPosition(position);
borrowerItems.removeItem(item);
}
};
ownerItemListView = (ListView) findViewById(R.id.tradeComposeOwnerItem);
ownerItemListView.setOnItemClickListener(deleteItemListener);
borrowerItemListView = (ListView) findViewById(R.id.tradeComposeBorrowerItems);
borrowerItemListView.setOnItemClickListener(deleteItemListener);
AsyncTask worker = new AsyncTask() {
@Override
protected Object doInBackground(Object[] params) {
try {
if (getIntent().hasExtra(EXTRA_PREV_TRADE_UUID)) {
UUID prevUUID = (UUID) getIntent().getSerializableExtra(EXTRA_PREV_TRADE_UUID);
Trade prevTrade = new Trade(prevUUID, TradeApp.getContext());
model = new Trade(prevTrade.getOwner(),
prevTrade.getBorrower(),
prevTrade.getOwnersItems(),
prevTrade.getBorrowersItems(),
TradeApp.getContext());
} else {
model = new Trade(Parcels.<User>unwrap(getIntent().getParcelableExtra("trade/compose/borrower")),
Parcels.<User>unwrap(getIntent().getParcelableExtra("trade/compose/owner")),
new Inventory(),
new Inventory() {{
addItem(Parcels.<Item>unwrap(getIntent().getParcelableExtra("trade/compose/item")));
}},
TradeApp.getContext());
}
model.getBorrower().getTradeList().addTrade(model);
model.addObserver(model.getBorrower());
model.getOwner().getTradeList().addTrade(model);
model.addObserver(model.getOwner());
} catch (IOException e) {
throw new RuntimeException("Primary User failed to get TradeList");
} catch (ServiceNotAvailableException e) {
ExceptionUtils.toastLong("Trade failed to create: app is offline");
activity.finish();
}
controller = new TradeOfferComposeController(TradeApp.getContext(), model);
ownerItems = model.getOwnersItems();
ownerItems.addObserver(TradeOfferComposeActivity.this);
try {
borrowerItems = model.getBorrowersItems();
borrowerItems.addObserver(TradeOfferComposeActivity.this);
} catch (ServiceNotAvailableException e) {
ExceptionUtils.toastLong("Failed to get borrowers items: app is offline");
activity.finish();
}
try {
borrowerInventory = model.getBorrower().getInventory();
} catch (IOException e) {
borrowerInventory = new Inventory();
} catch (ServiceNotAvailableException e) {
borrowerInventory = new Inventory();
}
try {
ownerInventory = model.getOwner().getInventory();
} catch (IOException e) {
ownerInventory = new Inventory();
Log.e("Error","Failed to fetch owner inventory: " + e.getMessage());
} catch (ServiceNotAvailableException e) {
ownerInventory = new Inventory();
Log.e("Error", "Failed to fetch owner inventory: " + e.getMessage());
}
return Boolean.FALSE;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
afterFieldsInitialized();
}
};
worker.execute();
}
/**
* Call me after the models have been fetched asynchronously.
*
* Binds the models to their view adapters and
* sets up the rest of the ui widgets to perform
* their actions.
*
*/
private void afterFieldsInitialized() {
ownerItemAdapter = new ItemsAdapter<Inventory>(TradeApp.getContext(), ownerItems);
ownerItemListView.setAdapter(ownerItemAdapter);
borrowerItemAdapter = new ItemsAdapter<Inventory>(TradeApp.getContext(), borrowerItems);
borrowerItemListView.setAdapter(borrowerItemAdapter);
requestItemButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createAddTradeItemDialog(ownerInventory, ownerItems).show();
}
});
addItemButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createAddTradeItemDialog(borrowerInventory, borrowerItems).show();
}
});
ownerUsername.setText(model.getOwner().getUsername());
offerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncTask worker = new AsyncTask() {
Boolean appIsOffline = Boolean.FALSE;
@Override
protected Object doInBackground(Object[] params) {
try {
controller.offerTrade();
} catch (ServiceNotAvailableException e) {
appIsOffline = Boolean.TRUE;
}
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
ExceptionUtils.toastShort("Trade offered!");
if (appIsOffline) {
ExceptionUtils.toastLong("Failed to offer trade: app is offline");
}
}
};
worker.execute();
activity.finish();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncTask worker = new AsyncTask() {
private Boolean appIsOffline = Boolean.FALSE;
@Override
protected Object doInBackground(Object[] params) {
try {
controller.cancelTrade();
} catch (ServiceNotAvailableException e) {
appIsOffline = Boolean.TRUE;
}
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
ExceptionUtils.toastShort("Trade canceled");
if (appIsOffline) {
ExceptionUtils.toastLong("Failed to cancel trade: app is offline");
}
}
};
worker.execute();
activity.finish();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (ownerItems != null){
ownerItems.removeObserver(this);
}
if (borrowerItems != null){
borrowerItems.removeObserver(this);
}
}
/**
* {@inheritDoc}
*
* @param menu
* @return
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.trade_offer_compose, menu);
return true;
}
/**
* {@inheritDoc}
*
* @param item
* @return
*/
@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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Factory method to build an alert dialog, used for adding inventory items to trades.
*
* browseModel and tradeItemsModel should belong to the same party (owner OR borrower)
*
* @param browseModel the Inventory that contains one party's full inventory
* @param tradeItemsModel the Inventory that contains one party's offered or requested
* trade items.
* @return an AlertDialog
*/
private AlertDialog createAddTradeItemDialog(Inventory browseModel, final Inventory tradeItemsModel) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
View dialogContent = View.inflate(this, R.layout.trade_item_picker_list, null);
ListView itemsListView = (ListView) dialogContent.findViewById(R.id.tradeItemListView);
ItemsAdapter<Inventory> inv = new ItemsAdapter<>(getApplicationContext(), browseModel);
itemsListView.setAdapter(inv);
itemsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Item selected = (Item) parent.getItemAtPosition(position);
tradeItemsModel.addItem(selected);
}
});
builder.setView(dialogContent); //todo this ui is kind of gross
builder.setTitle("Add Trade Item");
builder.setCancelable(false);
builder.setNegativeButton("Done", null);
builder.setView(dialogContent);
AlertDialog d = builder.create();
return d;
}
@Override
public void update(Observable observable) {
AsyncTask setBorrowersItems = new AsyncTask() {
@Override
protected Object doInBackground(Object[] params) {
try {
model.setBorrowersItems(borrowerItems);
} catch (IllegalTradeModificationException e) {
e.printStackTrace();
} catch (ServiceNotAvailableException e) {
e.printStackTrace();
}
return null;
}
};
setBorrowersItems.execute();
runOnUiThread(new Runnable() {
@Override
public void run() {
borrowerItemAdapter.notifyDataSetChanged();
ownerItemAdapter.notifyDataSetChanged();
}
});
}
}
| gpl-3.0 |
ALIADA/aliada-tool | aliada/aliada-rdfizer/src/main/java/eu/aliada/rdfizer/pipeline/format/marc/frbr/FamilyDetector.java | 1427 | // ALIADA - Automatic publication under Linked Data paradigm
// of library and museum data
//
// Component: aliada-rdfizer
// Responsible: ALIADA Consortiums
package eu.aliada.rdfizer.pipeline.format.marc.frbr;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.w3c.dom.Document;
import eu.aliada.rdfizer.pipeline.format.marc.selector.Expression;
/**
* Class for detecting entity Person.
* Class containes "expression" objects which extracts values related with Family entity.
*
* @author Emiliano Cammilletti
* @since 1.0
*/
public class FamilyDetector extends AbstractEntityDetector<Map<String, List<String>>> {
private final List<Expression<Map<String, List<String>>, Document>> expressions;
/**
* Builds a new detector with the following rules.
*
* @param expressions the subsequent detection rules.
*/
public FamilyDetector(final List<Expression<Map<String, List<String>>, Document>> expressions) {
this.expressions = expressions;
}
/**
* This method detect every xpath values for the person entity
*
* @param target the target
* @return the value
*/
Map<String, List<String>> detect(final Document target) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (final Expression<Map<String, List<String>>, Document> expression : expressions) {
put(expression.evaluate(target),map);
}
return map;
}
}
| gpl-3.0 |
Gurgy/Cypher | src/main/java/com/github/cypher/gui/root/roomcollection/room/settings/SettingsPresenter.java | 535 | package com.github.cypher.gui.root.roomcollection.room.settings;
import com.github.cypher.eventbus.ToggleEvent;
import com.github.cypher.settings.Settings;
import com.github.cypher.model.Client;
import com.google.common.eventbus.EventBus;
import javafx.fxml.FXML;
import javax.inject.Inject;
public class SettingsPresenter {
@Inject
private Client client;
@Inject
private Settings settings;
@Inject
private EventBus eventBus;
@FXML
private void hideRoomSettings() {
eventBus.post(ToggleEvent.HIDE_ROOM_SETTINGS);
}
}
| gpl-3.0 |
maximova136/EffectiveTravel-client | app/src/main/java/com/et/adapters/StationsListAdapter.java | 1759 | package com.et.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.et.R;
import com.et.response.object.StationObject;
import com.et.stations.StationsList;
import java.util.List;
public class StationsListAdapter extends BaseAdapter {
private Context ctx;
private LayoutInflater lInflater;
private List<StationObject> stations;
public StationsListAdapter(Context context, List<StationObject> _stations) {
ctx = context;
stations = _stations;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// кол-во элементов
@Override
public int getCount() {
return stations.size();
}
// элемент по позиции
@Override
public StationObject getItem(int position) {
return stations.get(position);
}
// id по позиции
@Override
public long getItemId(int position) {
return position;
}
// пункт списка
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// используем созданные, но не используемые view
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.stations_list_item, parent, false);
}
StationObject station = getItem(position);
// заполняем View в пункте списка данными
((TextView) view.findViewById(R.id.StationItem)).setText(station.getTitle());
return view;
}
}
| gpl-3.0 |
Numerios/ComplexWiring | common/num/complexwiring/world/ore/secondary/classic/BlockOreSecondaryClassic.java | 1321 | package num.complexwiring.world.ore.secondary.classic;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.util.IIcon;
import num.complexwiring.lib.Reference;
import num.complexwiring.world.ore.secondary.BlockOreSecondary;
import java.util.List;
public class BlockOreSecondaryClassic extends BlockOreSecondary {
public BlockOreSecondaryClassic() {
super();
setBlockName(Reference.MOD_ID.toLowerCase() + ".world.ore.secondary.classic");
}
@Override
public IIcon getIcon(int side, int meta) {
return EnumOreSecondaryClassic.VALID[meta].icon;
}
@Override
public void registerBlockIcons(IIconRegister ir) {
for (EnumOreSecondaryClassic oreSecondary : EnumOreSecondaryClassic.VALID) {
oreSecondary.registerIcon(ir);
}
}
@Override
public void getSubBlocks(Item item, CreativeTabs tab, List list) {
for (EnumOreSecondaryClassic oreSecondary : EnumOreSecondaryClassic.VALID) {
list.add(oreSecondary.getIS(1));
}
}
public void registerOres() {
for (EnumOreSecondaryClassic oreSecondary : EnumOreSecondaryClassic.VALID) {
oreSecondary.registerOre();
}
}
} | gpl-3.0 |
kristotammeoja/ks | s1tbx-io/src/main/java/org/esa/nest/dataio/EnhancedRandomAccessFile.java | 51751 | /*
* Copyright 1997-2006 Unidata Program Center/University Corporation for
* Atmospheric Research, P.O. Box 3000, Boulder, CO 80307,
* support@unidata.ucar.edu.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at
* your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* ImageI/O-Ext - OpenSource Java Image translation Library
* http://www.geo-solutions.it/
* https://imageio-ext.dev.java.net/
* (C) 2007 - 2008, GeoSolutions
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.esa.nest.dataio;
import java.io.*;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
/**
* @author Simone Giannecchini, GeoSolutions.
* <p/>
* -- NOTES from a class we derived this class from --
* <p/>
* <p/>
* RandomAccessFile.java. By Russ Rew, based on BufferedRandomAccessFile by Alex
* McManus, based on Sun's source code for java.io.RandomAccessFile. For Alex
* McManus version from which this derives, see his <a
* href="http://www.aber.ac.uk/~agm/Java.html"> Freeware Java Classes</a>.
* <p/>
* A buffered drop-in replacement for java.io.RandomAccessFile. Instances of
* this class realise substantial speed increases over java.io.RandomAccessFile
* through the use of buffering. This is a subclass of Object, as it was not
* possible to subclass java.io.RandomAccessFile because many of the methods are
* final. However, if it is necessary to use RandomAccessFile and
* java.io.RandomAccessFile interchangeably, both classes implement the
* DataInput and DataOutput interfaces.
* @author Alex McManus
* @author Russ Rew
* @author john caron
* @version $Id: EnhancedRandomAccessFile.java,v 1.2 2011-08-17 19:18:57 lveci Exp $
* @todo optimize {@link #readLine()}
* @task {@link ByteOrder} is not respected with writing
* @see DataInput
* @see DataOutput
* @see java.io.RandomAccessFile
*/
public final class EnhancedRandomAccessFile implements DataInput, DataOutput {
/**
* _more_
*/
static public final int BIG_ENDIAN = 0;
/**
* _more_
*/
static public final int LITTLE_ENDIAN = 1;
// debug leaks - keep track of open files
/**
* The default buffer size, in bytes.
*/
public static final int DEFAULT_BUFFER_SIZE = 32768;
/**
* _more_
*/
protected File file;
/**
* The underlying java.io.RandomAccessFile.
*/
protected java.io.RandomAccessFile eraf;
/**
* The offset in bytes from the eraf start, of the next read or write
* operation.
*/
protected long filePosition;
/**
* The buffer used to load the data.
*/
protected byte buffer[];
/**
* The offset in bytes of the start of the buffer, from the start of the
* eraf.
*/
protected long bufferStart;
/**
* The offset in bytes of the end of the data in the buffer, from the start
* of the eraf. This can be calculated from
* <code>bufferStart + dataSize</code>, but it is cached to speed up the
* read( ) method.
*/
protected long dataEnd;
/**
* The size of the data stored in the buffer, in bytes. This may be less
* than the size of the buffer.
*/
protected int dataSize;
/**
* True if we are at the end of the eraf.
*/
protected boolean endOfFile;
/**
* The access mode of the eraf.
*/
protected boolean readonly;
/**
* The current endian (big or little) mode of the eraf.
*/
protected boolean bigEndian;
/**
* True if the data in the buffer has been modified.
*/
boolean bufferModified = false;
/**
* make sure eraf is this long when closed
*/
protected long minLength = 0;
/**
* _more_
*
* @param bufferSize _more_
*/
protected EnhancedRandomAccessFile(int bufferSize) {
eraf = null;
readonly = true;
init(bufferSize);
}
/**
* Constructor, default buffer size.
*
* @param file file of the eraf
* @param mode same as for java.io.RandomAccessFile
* @throws IOException
*/
public EnhancedRandomAccessFile(File file, String mode)
throws IOException {
this(file, mode, DEFAULT_BUFFER_SIZE);
}
/**
* Constructor.
*
* @param file file of the eraf
* @param mode same as for java.io.RandomAccessFile
* @param bufferSize size of buffer to use.
* @throws IOException
*/
public EnhancedRandomAccessFile(File file, String mode, int bufferSize)
throws IOException {
this.file = file;
this.eraf = new java.io.RandomAccessFile(file, mode);
this.readonly = mode.equals("r");
init(bufferSize);
}
public java.io.RandomAccessFile getRandomAccessFile() {
return this.eraf;
}
/**
* _more_
*
* @param bufferSize _more_
*/
private void init(int bufferSize) {
// Initialise the buffer
bufferStart = 0;
dataEnd = 0;
dataSize = 0;
filePosition = 0;
buffer = new byte[bufferSize];
endOfFile = false;
}
/**
* Close the eraf, and release any associated system resources.
*
* @throws IOException if an I/O error occurrs.
*/
public void close() throws IOException {
if (eraf == null) {
return;
}
// If we are writing and the buffer has been modified, flush the
// contents of the buffer.
if (!readonly && bufferModified) {
eraf.seek(bufferStart);
eraf.write(buffer, 0, dataSize);
}
// may need to extend eraf, in case no fill is neing used
// may need to truncate eraf in case overwriting a longer eraf
// use only if minLength is set (by N3iosp)
if (!readonly && (minLength != 0) && (minLength != eraf.length())) {
eraf.setLength(minLength);
// System.out.println("TRUNCATE!!! minlength="+minLength);
}
// Close the underlying eraf object.
eraf.close();
}
/**
* Close silently the underlying {@link RandomAccessFile}
*/
public void finalize() {
try {
close();
} catch (IOException ex) {
}
}
/**
* Return true if eraf pointer is at end of eraf.
*
* @return _more_
*/
public boolean isAtEndOfFile() {
return endOfFile;
}
// Create channel from eraf
/**
* _more_
*
* @return _more_
*/
public FileChannel getChannel() {
if (eraf == null) {
return null;
}
try {
eraf.seek(0);
} catch (IOException e) {
e.printStackTrace();
}
return eraf.getChannel();
}
/**
* Set the position in the eraf for the next read or write.
*
* @param pos the offset (in bytes) from the start of the eraf.
* @throws IOException if an I/O error occurrs.
*/
public long seek(long pos) throws IOException {
// If the seek is into the buffer, just update the eraf pointer.
if ((pos >= bufferStart) && (pos < dataEnd)) {
filePosition = pos;
return filePosition;
}
// If the current buffer is modified, write it to disk.
if (bufferModified) {
flush();
}
// need new buffer
bufferStart = pos;
filePosition = pos;
eraf.seek(pos);
//if(readonly)
// dataSize = eraf.read(buffer, 0, buffer.length);
//else
// dataSize = eraf.read(buffer, 0, 1);
if (readonly)
dataSize = read_(pos, buffer, 0, buffer.length);
else
dataSize = read_(pos, buffer, 0, 1);
if (dataSize <= 0) {
dataSize = 0;
endOfFile = true;
} else {
endOfFile = false;
}
// Cache the position of the buffer end.
dataEnd = bufferStart + dataSize;
return filePosition;
}
/**
* Returns the current position in the eraf, where the next read or write
* will occur.
*
* @return the offset from the start of the eraf in bytes.
* @throws IOException if an I/O error occurrs.
*/
public long getFilePointer() throws IOException {
return filePosition;
}
/**
* Get the eraf file, or name.
*
* @return _more_
*/
public File getFile() {
return file;
}
/**
* Get the length of the eraf. The data in the buffer (which may not have
* been written the disk yet) is taken into account.
*
* @return the length of the eraf in bytes.
* @throws IOException if an I/O error occurrs.
*/
public long length() throws IOException {
long fileLength = eraf.length();
if (fileLength < dataEnd) {
return dataEnd;
} else {
return fileLength;
}
}
/**
* Change the current endian mode. Subsequent reads of short, int, float,
* double, long, char will use this. Does not currently effect writes.
*
* @param bo
*/
public void setByteOrder(final ByteOrder bo) {
this.bigEndian = (bo == ByteOrder.BIG_ENDIAN);
}
public ByteOrder getByteOrder() {
return bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN;
}
/**
* Returns the opaque eraf descriptor object associated with this eraf.
*
* @return the eraf descriptor object associated with this eraf.
* @throws IOException if an I/O error occurs.
*/
public FileDescriptor getFD() throws IOException {
return (eraf == null) ? null : eraf.getFD();
}
/**
* Copy the contents of the buffer to the disk.
*
* @throws IOException if an I/O error occurrs.
*/
public void flush() throws IOException {
if (bufferModified) {
eraf.seek(bufferStart);
eraf.write(buffer, 0, dataSize);
bufferModified = false;
}
}
/**
* Make sure eraf is at least this long when its closed. needed when not
* using fill mode, and not all data is written.
*
* @param minLength _more_
*/
public void setMinLength(long minLength) {
this.minLength = minLength;
}
// ////////////////////////////////////////////////////////////////////////////////////////////
// Read primitives.
//
/**
* Read a byte of data from the eraf, blocking until data is available.
*
* @return the next byte of data, or -1 if the end of the eraf is reached.
* @throws IOException if an I/O error occurrs.
*/
public int read() throws IOException {
// If the eraf position is within the data, return the byte...
if (filePosition < dataEnd) {
final int pos = (int) (filePosition - bufferStart);
filePosition++;
return (buffer[pos] & 0xff);
// ...or should we indicate EOF...
} else if (endOfFile) {
return -1;
// ...or seek to fill the buffer, and try again.
} else {
seek(filePosition);
return read();
}
}
/**
* Read up to <code>len</code> bytes into an array, at a specified offset.
* This will block until at least one byte has been read.
*
* @param b the byte array to receive the bytes.
* @param off the offset in the array where copying will start.
* @param len the number of bytes to copy.
* @return the actual number of bytes read, or -1 if there is not more data
* due to the end of the eraf being reached.
* @throws IOException if an I/O error occurrs.
*/
public int readBytes(byte b[], int off, int len) throws IOException {
// Check for end of eraf.
if (endOfFile) {
return -1;
}
// See how many bytes are available in the buffer - if none,
// seek to the eraf position to update the buffer and try again.
final int bytesAvailable = (int) (dataEnd - filePosition);
if (bytesAvailable < 1) {
seek(filePosition);
return readBytes(b, off, len);
}
// Copy as much as we can.
final int copyLength = (bytesAvailable >= len) ? len : bytesAvailable;
System.arraycopy(buffer, (int) (filePosition - bufferStart), b, off, copyLength);
filePosition += copyLength;
// If there is more to copy...
if (copyLength < len) {
int extraCopy = len - copyLength;
// If the amount remaining is more than a buffer's length, read it
// directly from the eraf.
if (extraCopy > buffer.length) {
eraf.seek(filePosition);
extraCopy = eraf.read(b, off + copyLength, len - copyLength);
// ...or read a new buffer full, and copy as much as possible...
} else {
seek(filePosition);
if (!endOfFile) {
extraCopy = (extraCopy > dataSize) ? dataSize : extraCopy;
System.arraycopy(buffer, 0, b, off + copyLength, extraCopy);
} else {
extraCopy = -1;
}
}
// If we did manage to copy any more, update the eraf position and
// return the amount copied.
if (extraCopy > 0) {
filePosition += extraCopy;
return copyLength + extraCopy;
}
}
// Return the amount copied.
return copyLength;
}
/**
* read directly, without going through the buffer
*
* @param pos _more_
* @param b _more_
* @param offset _more_
* @param len _more_
* @return _more_
* @throws IOException _more_
*/
private int read_(long pos, byte[] b, int offset, int len)
throws IOException {
eraf.seek(pos);
return eraf.read(b, offset, len);
}
/**
* Read up to <code>len</code> bytes into an array, at a specified offset.
* This will block until at least one byte has been read.
*
* @param b the byte array to receive the bytes.
* @param off the offset in the array where copying will start.
* @param len the number of bytes to copy.
* @return the actual number of bytes read, or -1 if there is not more data
* due to the end of the eraf being reached.
* @throws IOException if an I/O error occurrs.
*/
public int read(byte b[], int off, int len) throws IOException {
return readBytes(b, off, len);
}
/**
* Read up to <code>b.length( )</code> bytes into an array. This will
* block until at least one byte has been read.
*
* @param b the byte array to receive the bytes.
* @return the actual number of bytes read, or -1 if there is not more data
* due to the end of the eraf being reached.
* @throws IOException if an I/O error occurrs.
*/
public int read(byte b[]) throws IOException {
return readBytes(b, 0, b.length);
}
/**
* Reads <code>b.length</code> bytes from this eraf into the byte array.
* This method reads repeatedly from the eraf until all the bytes are read.
* This method blocks until all the bytes are read, the end of the stream is
* detected, or an exception is thrown.
*
* @param b the buffer into which the data is read.
* @throws EOFException if this eraf reaches the end before reading all the bytes.
* @throws IOException if an I/O error occurs.
*/
public void readFully(byte b[]) throws IOException {
readFully(b, 0, b.length);
}
/**
* Reads exactly <code>len</code> bytes from this eraf into the byte
* array. This method reads repeatedly from the eraf until all the bytes are
* read. This method blocks until all the bytes are read, the end of the
* stream is detected, or an exception is thrown.
*
* @param b the buffer into which the data is read.
* @param off the start offset of the data.
* @param len the number of bytes to read.
* @throws EOFException if this eraf reaches the end before reading all the bytes.
* @throws IOException if an I/O error occurs.
*/
public void readFully(byte b[], int off, int len) throws IOException {
int n = 0;
while (n < len) {
final int count = this.read(b, off + n, len - n);
if (count < 0) {
throw new EOFException();
}
n += count;
}
}
/**
* Skips exactly <code>n</code> bytes of input. This method blocks until
* all the bytes are skipped, the end of the stream is detected, or an
* exception is thrown.
*
* @param n the number of bytes to be skipped.
* @return the number of bytes skipped, which is always <code>n</code>.
* @throws EOFException if this eraf reaches the end before skipping all the
* bytes.
* @throws IOException if an I/O error occurs.
*/
public int skipBytes(int n) throws IOException {
seek(filePosition + n);
return n;
}
/**
* Skips exactly <code>n</code> bytes of input. This method blocks until
* all the bytes are skipped, the end of the stream is detected, or an
* exception is thrown.
*
* @param n the number of bytes to be skipped.
* @return the number of bytes skipped, which is always <code>n</code>.
* @throws EOFException if this eraf reaches the end before skipping all the
* bytes.
* @throws IOException if an I/O error occurs.
*/
public long skipBytes(long n) throws IOException {
seek(filePosition + n);
return n;
}
/**
* Unread the last byte read. This method should not be used more than once
* between reading operations, or strange things might happen.
*/
public void unread() {
filePosition--;
}
//
// Write primitives.
//
/**
* Write a byte to the eraf. If the eraf has not been opened for writing, an
* IOException will be raised only when an attempt is made to write the
* buffer to the eraf.
* <p/>
* Caveat: the effects of seek( )ing beyond the end of the eraf are
* undefined.
*
* @param b _more_
* @throws IOException if an I/O error occurrs.
*/
public void write(int b) throws IOException {
// If the eraf position is within the block of data...
if (filePosition < dataEnd) {
buffer[(int) (filePosition++ - bufferStart)] = (byte) b;
bufferModified = true;
// ...or (assuming that seek will not allow the eraf pointer
// to move beyond the end of the eraf) get the correct block of
// data...
} else {
// If there is room in the buffer, expand it...
if (dataSize != buffer.length) {
buffer[(int) (filePosition++ - bufferStart)] = (byte) b;
bufferModified = true;
dataSize++;
dataEnd++;
// ...or do another seek to get a new buffer, and start again...
} else {
seek(filePosition);
write(b);
}
}
}
/**
* Write <code>len</code> bytes from an array to the eraf.
*
* @param b the array containing the data.
* @param off the offset in the array to the data.
* @param len the length of the data.
* @throws IOException if an I/O error occurrs.
*/
public void writeBytes(byte b[], int off, int len) throws IOException {
// If the amount of data is small (less than a full buffer)...
if (len < buffer.length) {
// If any of the data fits within the buffer...
int spaceInBuffer = 0;
int copyLength = 0;
if (filePosition >= bufferStart) {
spaceInBuffer = (int) ((bufferStart + buffer.length) - filePosition);
}
if (spaceInBuffer > 0) {
// Copy as much as possible to the buffer.
copyLength = (spaceInBuffer > len) ? len : spaceInBuffer;
System.arraycopy(b, off, buffer,
(int) (filePosition - bufferStart), copyLength);
bufferModified = true;
final long myDataEnd = filePosition + copyLength;
dataEnd = (myDataEnd > dataEnd) ? myDataEnd : dataEnd;
dataSize = (int) (dataEnd - bufferStart);
filePosition += copyLength;
// /System.out.println("--copy to buffer "+copyLength+" "+len);
}
// If there is any data remaining, move to the new position and copy
// to
// the new buffer.
if (copyLength < len) {
// System.out.println("--need more "+copyLength+" "+len+" space=
// "+spaceInBuffer);
seek(filePosition); // triggers a flush
System.arraycopy(b, off + copyLength, buffer,
(int) (filePosition - bufferStart), len - copyLength);
bufferModified = true;
final long myDataEnd = filePosition + (len - copyLength);
dataEnd = (myDataEnd > dataEnd) ? myDataEnd : dataEnd;
dataSize = (int) (dataEnd - bufferStart);
filePosition += (len - copyLength);
}
// ...or write a lot of data...
} else {
// Flush the current buffer, and write this data to the eraf.
if (bufferModified) {
flush();
bufferStart = dataEnd = dataSize = 0;
// eraf.seek(filePosition); // JC added Oct 21, 2004
}
eraf.seek(filePosition); // moved per Steve Cerruti; Jan 14, 2005
eraf.write(b, off, len);
// System.out.println("--write at "+filePosition+" "+len);
filePosition += len;
}
}
/**
* Writes <code>b.length</code> bytes from the specified byte array
* starting at offset <code>off</code> to this eraf.
*
* @param b the data.
* @throws IOException if an I/O error occurs.
*/
public void write(byte b[]) throws IOException {
writeBytes(b, 0, b.length);
}
/**
* Writes <code>len</code> bytes from the specified byte array starting at
* offset <code>off</code> to this eraf.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @throws IOException if an I/O error occurs.
*/
public void write(byte b[], int off, int len) throws IOException {
writeBytes(b, off, len);
}
//
// DataInput methods.
//
/**
* Reads a <code>boolean</code> from this eraf. This method reads a single
* byte from the eraf. A value of <code>0</code> represents
* <code>false</code>. Any other value represents <code>true</code>.
* This method blocks until the byte is read, the end of the stream is
* detected, or an exception is thrown.
*
* @return the <code>boolean</code> value read.
* @throws EOFException if this eraf has reached the end.
* @throws IOException if an I/O error occurs.
*/
public boolean readBoolean() throws IOException {
final int ch = this.read();
if (ch < 0) {
throw new EOFException();
}
return (ch != 0);
}
/**
* Reads a signed 8-bit value from this eraf. This method reads a byte from
* the eraf. If the byte read is <code>b</code>, where
* <code>0 <= b <= 255</code>, then the result
* is:
* <ul>
* <code>
* (byte)(b)
* </code>
* </ul>
* <p/>
* This method blocks until the byte is read, the end of the stream is
* detected, or an exception is thrown.
*
* @return the next byte of this eraf as a signed 8-bit <code>byte</code>.
* @throws EOFException if this eraf has reached the end.
* @throws IOException if an I/O error occurs.
*/
public byte readByte() throws IOException {
final int ch = this.read();
if (ch < 0) {
throw new EOFException();
}
return (byte) (ch);
}
/**
* Reads an unsigned 8-bit number from this eraf. This method reads a byte
* from this eraf and returns that byte.
* <p/>
* This method blocks until the byte is read, the end of the stream is
* detected, or an exception is thrown.
*
* @return the next byte of this eraf, interpreted as an unsigned 8-bit
* number.
* @throws EOFException if this eraf has reached the end.
* @throws IOException if an I/O error occurs.
*/
public int readUnsignedByte() throws IOException {
final int ch = this.read();
if (ch < 0) {
throw new EOFException();
}
return ch;
}
/**
* Reads a signed 16-bit number from this eraf. The method reads 2 bytes
* from this eraf. If the two bytes read, in order, are <code>b1</code>
* and <code>b2</code>, where each of the two values is between
* <code>0</code> and <code>255</code>, inclusive, then the result is
* equal to:
* <ul>
* <code>
* (short)((b1 << 8) | b2)
* </code>
* </ul>
* <p/>
* This method blocks until the two bytes are read, the end of the stream is
* detected, or an exception is thrown.
*
* @return the next two bytes of this eraf, interpreted as a signed 16-bit
* number.
* @throws EOFException if this eraf reaches the end before reading two bytes.
* @throws IOException if an I/O error occurs.
*/
public short readShort() throws IOException {
final byte b[] = new byte[2];
if (read(b, 0, 2) < 0) {
throw new EOFException();
}
if (bigEndian) {
return (short) (((b[0] & 0xFF) << 8) + (b[1] & 0xFF));
} else {
return (short) (((b[1] & 0xFF) << 8) + (b[0] & 0xFF));
}
}
/**
* _more_
*
* @param pa _more_
* @param start _more_
* @param n _more_
* @throws IOException _more_
*/
public void readShort(short[] pa, int start, int n) throws IOException {
for (int i = start, end = n + start; i < end; i++) {
pa[i] = readShort();
}
}
/**
* Reads an unsigned 16-bit number from this eraf. This method reads two
* bytes from the eraf. If the bytes read, in order, are <code>b1</code>
* and <code>b2</code>, where
* <code>0 <= b1, b2 <= 255</code>, then the
* result is equal to:
* <ul>
* <code>
* (b1 << 8) | b2
* </code>
* </ul>
* <p/>
* This method blocks until the two bytes are read, the end of the stream is
* detected, or an exception is thrown.
*
* @return the next two bytes of this eraf, interpreted as an unsigned
* 16-bit integer.
* @throws EOFException if this eraf reaches the end before reading two bytes.
* @throws IOException if an I/O error occurs.
*/
public int readUnsignedShort() throws IOException {
final byte b[] = new byte[2];
if (read(b, 0, 2) < 0) {
throw new EOFException();
}
if (bigEndian) {
return ((b[0] & 0xFF) << 8) + (b[1] & 0xFF) & 0xFFFF;
} else {
return ((b[1] & 0xFF) << 8) + (b[0] & 0xFF) & 0xFFFF;
}
}
/**
* Reads a Unicode character from this eraf. This method reads two bytes
* from the eraf. If the bytes read, in order, are <code>b1</code> and
* <code>b2</code>, where
* <code>0 <= b1, b2 <= 255</code>, then
* the result is equal to:
* <ul>
* <code>
* (char)((b1 << 8) | b2)
* </code>
* </ul>
* <p/>
* This method blocks until the two bytes are read, the end of the stream is
* detected, or an exception is thrown.
*
* @return the next two bytes of this eraf as a Unicode character.
* @throws EOFException if this eraf reaches the end before reading two bytes.
* @throws IOException if an I/O error occurs.
*/
public char readChar() throws IOException {
final byte b[] = new byte[2];
if (read(b, 0, 2) < 0) {
throw new EOFException();
}
if (bigEndian) {
return (char) (((b[0] & 0xFF) << 8) + (b[1] & 0xFF));
} else {
return (char) (((b[1] & 0xFF) << 8) + (b[0] & 0xFF));
}
}
/**
* Reads a signed 32-bit integer from this eraf. This method reads 4 bytes
* from the eraf. If the bytes read, in order, are <code>b1</code>,
* <code>b2</code>, <code>b3</code>, and <code>b4</code>, where
* <code>0 <= b1, b2, b3, b4 <= 255</code>,
* then the result is equal to:
* <ul>
* <code>
* (b1 << 24) | (b2 << 16) + (b3 << 8) + b4
* </code>
* </ul>
* <p/>
* This method blocks until the four bytes are read, the end of the stream
* is detected, or an exception is thrown.
*
* @return the next four bytes of this eraf, interpreted as an
* <code>int</code>.
* @throws EOFException if this eraf reaches the end before reading four bytes.
* @throws IOException if an I/O error occurs.
*/
public int readInt() throws IOException {
final byte b[] = new byte[4];
if (read(b, 0, 4) < 0) {
throw new EOFException();
}
if (bigEndian) {
return (((b[0] & 0xFF) << 24) + ((b[1] & 0xFF) << 16)
+ ((b[2] & 0xFF) << 8) + ((b[3] & 0xFF)));
} else {
return (((b[3] & 0xFF) << 24) + ((b[2] & 0xFF) << 16)
+ ((b[1] & 0xFF) << 8) + ((b[0] & 0xFF)));
}
}
public long readUnsignedInt() throws IOException {
// retaining only the first 4 bytes, ignoring sign when extending
return ((long) readInt()) & 0xFFFFFFFFL;
}
/**
* Read an integer at the given position, bypassing all buffering.
*
* @param pos read a byte at this position
* @return The int that was read
* @throws IOException
*/
public int readIntUnbuffered(long pos) throws IOException {
final byte[] bb = new byte[4];
read_(pos, bb, 0, 4);
final int ch1 = bb[0] & 0xFF;
final int ch2 = bb[1] & 0xFF;
final int ch3 = bb[2] & 0xFF;
final int ch4 = bb[3] & 0xFF;
if ((ch1 | ch2 | ch3 | ch4) < 0) {
throw new EOFException();
}
if (bigEndian) {
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
} else {
return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
}
}
/**
* Reads a signed 24-bit integer from this eraf. This method reads 3 bytes
* from the eraf. If the bytes read, in order, are <code>b1</code>,
* <code>b2</code>, and <code>b3</code>, where
* <code>0 <= b1, b2, b3 <= 255</code>, then
* the result is equal to:
* <ul>
* <code>
* (b1 << 16) | (b2 << 8) + (b3 << 0)
* </code>
* </ul>
* <p/>
* This method blocks until the three bytes are read, the end of the stream
* is detected, or an exception is thrown.
*
* @param pa _more_
* @param start _more_
* @param n _more_
* @throws EOFException if this eraf reaches the end before reading four bytes.
* @throws IOException if an I/O error occurs.
*/
public void readInt(int[] pa, int start, int n) throws IOException {
for (int i = start, end = n + start; i < end; i++) {
pa[i] = readInt();
}
}
/**
* Reads a signed 64-bit integer from this eraf. This method reads eight
* bytes from the eraf. If the bytes read, in order, are <code>b1</code>,
* <code>b2</code>, <code>b3</code>, <code>b4</code>,
* <code>b5</code>, <code>b6</code>, <code>b7</code>, and
* <code>b8,</code> where:
* <ul>
* <code>
* 0 <= b1, b2, b3, b4, b5, b6, b7, b8 <=255,
* </code>
* </ul>
* <p/>
* then the result is equal to:
* <p/>
* <blockquote>
* <p/>
* <pre>
* ((long) b1 << 56) + ((long) b2 << 48) + ((long) b3 << 40) + ((long) b4 << 32)
* + ((long) b5 << 24) + ((long) b6 << 16) + ((long) b7 << 8) + b8
* </pre>
* <p/>
* </blockquote>
* <p/>
* This method blocks until the eight bytes are read, the end of the stream
* is detected, or an exception is thrown.
*
* @return the next eight bytes of this eraf, interpreted as a
* <code>long</code>.
* @throws EOFException if this eraf reaches the end before reading eight bytes.
* @throws IOException if an I/O error occurs.
*/
public long readLong() throws IOException {
final byte b[] = new byte[8];
if (read(b, 0, 8) < 0) {
throw new EOFException();
}
if (bigEndian) {
return (((b[0] & 0xFFL) << 56) + ((b[1] & 0xFFL) << 48)
+ ((b[2] & 0xFFL) << 40) + ((b[3] & 0xFFL) << 32)
+ ((b[4] & 0xFFL) << 24) + ((b[5] & 0xFFL) << 16)
+ ((b[6] & 0xFFL) << 8) + ((b[7] & 0xFFL)));
} else {
return (((b[7] & 0xFFL) << 56) + ((b[6] & 0xFFL) << 48)
+ ((b[5] & 0xFFL) << 40) + ((b[4] & 0xffL) << 32)
+ ((b[3] & 0xFFL) << 24) + ((b[2] & 0xFFL) << 16)
+ ((b[1] & 0xFFL) << 8) + ((b[0] & 0xFFL)));
}
}
/**
* _more_
*
* @param pa _more_
* @param start _more_
* @param n _more_
* @throws IOException _more_
*/
public void readLong(long[] pa, int start, int n) throws IOException {
for (int i = start, end = n + start; i < end; i++) {
pa[i] = readLong();
}
}
/**
* Reads a <code>float</code> from this eraf. This method reads an
* <code>int</code> value as if by the <code>readInt</code> method and
* then converts that <code>int</code> to a <code>float</code> using the
* <code>intBitsToFloat</code> method in class <code>Float</code>.
* <p/>
* This method blocks until the four bytes are read, the end of the stream
* is detected, or an exception is thrown.
*
* @return the next four bytes of this eraf, interpreted as a
* <code>float</code>.
* @throws EOFException if this eraf reaches the end before reading four bytes.
* @throws IOException if an I/O error occurs.
* @see java.io.RandomAccessFile#readInt()
* @see java.lang.Float#intBitsToFloat(int)
*/
public float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
/**
* _more_
*
* @param pa _more_
* @param start _more_
* @param n _more_
* @throws IOException _more_
*/
public void readFloat(float[] pa, int start, int n) throws IOException {
for (int i = start, end = n + start; i < end; i++) {
pa[i] = Float.intBitsToFloat(readInt());
}
}
/**
* Reads a <code>double</code> from this eraf. This method reads a
* <code>long</code> value as if by the <code>readLong</code> method and
* then converts that <code>long</code> to a <code>double</code> using
* the <code>longBitsToDouble</code> method in class <code>Double</code>.
* <p/>
* This method blocks until the eight bytes are read, the end of the stream
* is detected, or an exception is thrown.
*
* @return the next eight bytes of this eraf, interpreted as a
* <code>double</code>.
* @throws EOFException if this eraf reaches the end before reading eight bytes.
* @throws IOException if an I/O error occurs.
* @see java.io.RandomAccessFile#readLong()
* @see java.lang.Double#longBitsToDouble(long)
*/
public double readDouble() throws IOException {
return Double.longBitsToDouble(readLong());
}
/**
* _more_
*
* @param pa _more_
* @param start _more_
* @param n _more_
* @throws IOException _more_
*/
public void readDouble(double[] pa, int start, int n) throws IOException {
for (int i = start, end = n + start; i < end; i++) {
pa[i] = Double.longBitsToDouble(readLong());
}
}
/**
* Reads the next line of text from this eraf. This method successively
* reads bytes from the eraf until it reaches the end of a line of text.
* <p/>
* <p/>
* A line of text is terminated by a carriage-return character (<code>'\r'</code>),
* a newline character (<code>'\n'</code>), a carriage-return
* character immediately followed by a newline character, or the end of the
* input stream. The line-terminating character(s), if any, are included as
* part of the string returned.
* <p/>
* <p/>
* This method blocks until a newline character is read, a carriage return
* and the byte following it are read (to see if it is a newline), the end
* of the stream is detected, or an exception is thrown.
*
* @return the next line of text from this eraf.
* @throws IOException if an I/O error occurs.
* @task we can optimize this
*/
public String readLine() throws IOException {
final StringBuilder input = new StringBuilder();
int c;
while (((c = read()) != -1) && (c != '\n')) {
input.append((char) c);
}
if ((c == -1) && (input.length() == 0)) {
return null;
}
return input.toString();
}
/**
* Reads in a string from this eraf. The string has been encoded using a
* modified UTF-8 format.
* <p/>
* The first two bytes are read as if by <code>readUnsignedShort</code>.
* This value gives the number of following bytes that are in the encoded
* string, not the length of the resulting string. The following bytes are
* then interpreted as bytes encoding characters in the UTF-8 format and are
* converted into characters.
* <p/>
* This method blocks until all the bytes are read, the end of the stream is
* detected, or an exception is thrown.
*
* @return a Unicode string.
* @throws EOFException if this eraf reaches the end before reading all the bytes.
* @throws IOException if an I/O error occurs.
* @throws UTFDataFormatException if the bytes do not represent valid UTF-8 encoding of a
* Unicode string.
* @see java.io.RandomAccessFile#readUnsignedShort()
*/
public String readUTF() throws IOException {
return DataInputStream.readUTF(this);
}
/**
* Read a String of knoen length.
*
* @param nbytes number of bytes to read
* @return String wrapping the bytes.
* @throws IOException
*/
public String readString(int nbytes) throws IOException {
final byte[] data = new byte[nbytes];
readFully(data);
return new String(data);
}
//
// DataOutput methods.
//
/**
* Writes a <code>boolean</code> to the eraf as a 1-byte value. The value
* <code>true</code> is written out as the value <code>(byte)1</code>;
* the value <code>false</code> is written out as the value
* <code>(byte)0</code>.
*
* @param v a <code>boolean</code> value to be written.
* @throws IOException if an I/O error occurs.
*/
public void writeBoolean(boolean v) throws IOException {
write(v ? 1 : 0);
}
/**
* _more_
*
* @param pa _more_
* @param start _more_
* @param n _more_
* @throws IOException _more_
*/
public void writeBoolean(boolean[] pa, int start, int n) throws IOException {
for (int i = start, end = start + n; i < end; i++) {
writeBoolean(pa[i]);
}
}
/**
* Writes a <code>byte</code> to the eraf as a 1-byte value.
*
* @param v a <code>byte</code> value to be written.
* @throws IOException if an I/O error occurs.
*/
public void writeByte(int v) throws IOException {
write(v);
}
/**
* Writes a <code>short</code> to the eraf as two bytes, high byte first.
*
* @param v a <code>short</code> to be written.
* @throws IOException if an I/O error occurs.
*/
public void writeShort(int v) throws IOException {
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
}
/**
* _more_
*
* @param pa _more_
* @param start _more_
* @param n _more_
* @throws IOException _more_
*/
public void writeShort(short[] pa, int start, int n) throws IOException {
for (int i = start, end = start + n; i < end; i++) {
writeShort(pa[i]);
}
}
/**
* Writes a <code>char</code> to the eraf as a 2-byte value, high byte
* first.
*
* @param v a <code>char</code> value to be written.
* @throws IOException if an I/O error occurs.
*/
public void writeChar(int v) throws IOException {
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
}
/**
* _more_
*
* @param pa _more_
* @param start _more_
* @param n _more_
* @throws IOException _more_
*/
public void writeChar(char[] pa, int start, int n) throws IOException {
for (int i = start, end = start + n; i < end; i++) {
writeChar(pa[i]);
}
}
/**
* Writes an <code>int</code> to the eraf as four bytes, high byte first.
*
* @param v an <code>int</code> to be written.
* @throws IOException if an I/O error occurs.
*/
public void writeInt(int v) throws IOException {
write((v >>> 24) & 0xFF);
write((v >>> 16) & 0xFF);
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
}
/**
* _more_
*
* @param pa _more_
* @param start _more_
* @param n _more_
* @throws IOException _more_
*/
public void writeInt(int[] pa, int start, int n) throws IOException {
for (int i = start, end = start + n; i < end; i++) {
writeInt(pa[i]);
}
}
/**
* Writes a <code>long</code> to the eraf as eight bytes, high byte first.
*
* @param v a <code>long</code> to be written.
* @throws IOException if an I/O error occurs.
*/
public void writeLong(long v) throws IOException {
if (bigEndian) {
write((int) (v >>> 56) & 0xFF);
write((int) (v >>> 48) & 0xFF);
write((int) (v >>> 40) & 0xFF);
write((int) (v >>> 32) & 0xFF);
write((int) (v >>> 24) & 0xFF);
write((int) (v >>> 16) & 0xFF);
write((int) (v >>> 8) & 0xFF);
write((int) (v >>> 0) & 0xFF);
} else {
write((int) (v >>> 0) & 0xFF);
write((int) (v >>> 8) & 0xFF);
write((int) (v >>> 16) & 0xFF);
write((int) (v >>> 24) & 0xFF);
write((int) (v >>> 32) & 0xFF);
write((int) (v >>> 40) & 0xFF);
write((int) (v >>> 48) & 0xFF);
write((int) (v >>> 56) & 0xFF);
}
}
/**
* _more_
*
* @param pa _more_
* @param start _more_
* @param n _more_
* @throws IOException _more_
*/
public void writeLong(long[] pa, int start, int n) throws IOException {
for (int i = start, end = start + n; i < end; i++) {
writeLong(pa[i]);
}
}
/**
* Converts the float argument to an <code>int</code> using the
* <code>floatToIntBits</code> method in class <code>Float</code>, and
* then writes that <code>int</code> value to the eraf as a 4-byte
* quantity, high byte first.
*
* @param v a <code>float</code> value to be written.
* @throws IOException if an I/O error occurs.
* @see java.lang.Float#floatToIntBits(float)
*/
public void writeFloat(float v) throws IOException {
writeInt(Float.floatToIntBits(v));
}
/**
* _more_
*
* @param pa _more_
* @param start _more_
* @param n _more_
* @throws IOException _more_
*/
public void writeFloat(float[] pa, int start, int n) throws IOException {
for (int i = start, end = start + n; i < end; i++) {
writeFloat(pa[i]);
}
}
/**
* Converts the double argument to a <code>long</code> using the
* <code>doubleToLongBits</code> method in class <code>Double</code>,
* and then writes that <code>long</code> value to the eraf as an 8-byte
* quantity, high byte first.
*
* @param v a <code>double</code> value to be written.
* @throws IOException if an I/O error occurs.
* @see java.lang.Double#doubleToLongBits(double)
*/
public void writeDouble(double v) throws IOException {
writeLong(Double.doubleToLongBits(v));
}
/**
* _more_
*
* @param pa _more_
* @param start _more_
* @param n _more_
* @throws IOException _more_
*/
public void writeDouble(double[] pa, int start, int n) throws IOException {
for (int i = start, end = start + n; i < end; i++) {
writeDouble(pa[i]);
}
}
/**
* Writes the string to the eraf as a sequence of bytes. Each character in
* the string is written out, in sequence, by discarding its high eight
* bits.
*
* @param s a string of bytes to be written.
* @throws IOException if an I/O error occurs.
*/
public void writeBytes(String s) throws IOException {
final int len = s.length();
for (int i = 0; i < len; i++) {
write((byte) s.charAt(i));
}
}
/**
* Writes the character array to the eraf as a sequence of bytes. Each
* character in the string is written out, in sequence, by discarding its
* high eight bits.
*
* @param b a character array of bytes to be written.
* @param off the index of the first character to write.
* @param len the number of characters to write.
* @throws IOException if an I/O error occurs.
*/
public void writeBytes(char b[], int off, int len) throws IOException {
for (int i = off; i < len; i++) {
write((byte) b[i]);
}
}
/**
* Writes a string to the eraf as a sequence of characters. Each character
* is written to the data output stream as if by the <code>writeChar</code>
* method.
*
* @param s a <code>String</code> value to be written.
* @throws IOException if an I/O error occurs.
* @see java.io.RandomAccessFile#writeChar(int)
*/
public void writeChars(String s) throws IOException {
final int len = s.length();
for (int i = 0; i < len; i++) {
final int v = s.charAt(i);
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
}
}
/**
* Writes a string to the eraf using UTF-8 encoding in a machine-independent
* manner.
* <p/>
* First, two bytes are written to the eraf as if by the
* <code>writeShort</code> method giving the number of bytes to follow.
* This value is the number of bytes actually written out, not the length of
* the string. Following the length, each character of the string is output,
* in sequence, using the UTF-8 encoding for each character.
*
* @param str a string to be written.
* @throws IOException if an I/O error occurs.
*/
public void writeUTF(String str) throws IOException {
final int strlen = str.length();
int utflen = 0;
for (int i = 0; i < strlen; i++) {
final int c = str.charAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
utflen++;
} else if (c > 0x07FF) {
utflen += 3;
} else {
utflen += 2;
}
}
if (utflen > 65535) {
throw new UTFDataFormatException();
}
write((utflen >>> 8) & 0xFF);
write((utflen >>> 0) & 0xFF);
for (int i = 0; i < strlen; i++) {
final int c = str.charAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
write(c);
} else if (c > 0x07FF) {
write(0xE0 | ((c >> 12) & 0x0F));
write(0x80 | ((c >> 6) & 0x3F));
write(0x80 | ((c >> 0) & 0x3F));
} else {
write(0xC0 | ((c >> 6) & 0x1F));
write(0x80 | ((c >> 0) & 0x3F));
}
}
}
/**
* Create a string representation of this object.
*
* @return a string representation of the state of the object.
*/
public String toString() {
return "fp=" + filePosition + ", bs=" + bufferStart + ", de=" + dataEnd
+ ", ds=" + dataSize + ", bl=" + buffer.length + ", readonly="
+ readonly + ", bm=" + bufferModified;
}
/**
* Support for FileCache.
*/
protected boolean cached;
protected String location;
/**
* _more_
*
* @param cached _more_
*/
public void setCached(boolean cached) {
this.cached = cached;
}
/**
* _more_
*
* @return _more_
*/
public boolean isCached() {
return cached;
}
/**
* _more_
*
* @throws IOException _more_
*/
public void synch() throws IOException {
}
public String getLocation() {
return location;
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | frameworks/base/packages/SystemUI/src/com/android/systemui/settings/BrightnessController.java | 11129 | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.settings;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IPowerManager;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.UserHandle;
import android.provider.Settings;
import android.widget.CompoundButton;
import android.widget.ImageView;
import com.android.systemui.R;
import java.util.ArrayList;
public class BrightnessController implements ToggleSlider.Listener {
private static final String TAG = "StatusBar.BrightnessController";
private static final boolean SHOW_AUTOMATIC_ICON = false;
/**
* {@link android.provider.Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ} uses the range [-1, 1].
* Using this factor, it is converted to [0, BRIGHTNESS_ADJ_RESOLUTION] for the SeekBar.
*/
private static final float BRIGHTNESS_ADJ_RESOLUTION = 100;
private final int mMinimumBacklight;
private final int mMaximumBacklight;
private final Context mContext;
private final ImageView mIcon;
private final ToggleSlider mControl;
private final boolean mAutomaticAvailable;
private final IPowerManager mPower;
private final CurrentUserTracker mUserTracker;
private final Handler mHandler;
private final BrightnessObserver mBrightnessObserver;
private ArrayList<BrightnessStateChangeCallback> mChangeCallbacks =
new ArrayList<BrightnessStateChangeCallback>();
private boolean mAutomatic;
private boolean mListening;
private boolean mExternalChange;
public interface BrightnessStateChangeCallback {
public void onBrightnessLevelChanged();
}
/** ContentObserver to watch brightness **/
private class BrightnessObserver extends ContentObserver {
private final Uri BRIGHTNESS_MODE_URI =
Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS_MODE);
private final Uri BRIGHTNESS_URI =
Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
private final Uri BRIGHTNESS_ADJ_URI =
Settings.System.getUriFor(Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ);
public BrightnessObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
onChange(selfChange, null);
}
@Override
public void onChange(boolean selfChange, Uri uri) {
if (selfChange) return;
try {
mExternalChange = true;
if (BRIGHTNESS_MODE_URI.equals(uri)) {
updateMode();
updateSlider();
} else if (BRIGHTNESS_URI.equals(uri) && !mAutomatic) {
updateSlider();
} else if (BRIGHTNESS_ADJ_URI.equals(uri) && mAutomatic) {
updateSlider();
} else {
updateMode();
updateSlider();
}
for (BrightnessStateChangeCallback cb : mChangeCallbacks) {
cb.onBrightnessLevelChanged();
}
} finally {
mExternalChange = false;
}
}
public void startObserving() {
final ContentResolver cr = mContext.getContentResolver();
cr.unregisterContentObserver(this);
cr.registerContentObserver(
BRIGHTNESS_MODE_URI,
false, this, UserHandle.USER_ALL);
cr.registerContentObserver(
BRIGHTNESS_URI,
false, this, UserHandle.USER_ALL);
cr.registerContentObserver(
BRIGHTNESS_ADJ_URI,
false, this, UserHandle.USER_ALL);
}
public void stopObserving() {
final ContentResolver cr = mContext.getContentResolver();
cr.unregisterContentObserver(this);
}
}
public BrightnessController(Context context, ImageView icon, ToggleSlider control) {
mContext = context;
mIcon = icon;
mControl = control;
mHandler = new Handler();
mUserTracker = new CurrentUserTracker(mContext) {
@Override
public void onUserSwitched(int newUserId) {
updateMode();
updateSlider();
}
};
mBrightnessObserver = new BrightnessObserver(mHandler);
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
mMinimumBacklight = pm.getMinimumScreenBrightnessSetting();
mMaximumBacklight = pm.getMaximumScreenBrightnessSetting();
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_SENSOR_LIGHT)) {
mAutomaticAvailable = context.getResources().getBoolean(
com.android.internal.R.bool.config_automatic_brightness_available);
} else {
mAutomaticAvailable = false;
final CompoundButton toggle = (CompoundButton)control.findViewById(R.id.toggle);
toggle.setClickable(false);
}
mPower = IPowerManager.Stub.asInterface(ServiceManager.getService("power"));
}
public void addStateChangedCallback(BrightnessStateChangeCallback cb) {
mChangeCallbacks.add(cb);
}
public boolean removeStateChangedCallback(BrightnessStateChangeCallback cb) {
return mChangeCallbacks.remove(cb);
}
@Override
public void onInit(ToggleSlider control) {
// Do nothing
}
public void registerCallbacks() {
if (mListening) {
return;
}
mBrightnessObserver.startObserving();
mUserTracker.startTracking();
// Update the slider and mode before attaching the listener so we don't
// receive the onChanged notifications for the initial values.
updateMode();
updateSlider();
mControl.setOnChangedListener(this);
mListening = true;
}
/** Unregister all call backs, both to and from the controller */
public void unregisterCallbacks() {
if (!mListening) {
return;
}
mBrightnessObserver.stopObserving();
mUserTracker.stopTracking();
mControl.setOnChangedListener(null);
mListening = false;
}
@Override
public void onChanged(ToggleSlider view, boolean tracking, boolean automatic, int value) {
updateIcon(mAutomatic);
if (mExternalChange) return;
if (!mAutomatic) {
final int val = value + mMinimumBacklight;
setBrightness(val);
if (!tracking) {
AsyncTask.execute(new Runnable() {
public void run() {
Settings.System.putIntForUser(mContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, val,
UserHandle.USER_CURRENT);
}
});
}
} else {
final float adj = value / (BRIGHTNESS_ADJ_RESOLUTION / 2f) - 1;
setBrightnessAdj(adj);
if (!tracking) {
AsyncTask.execute(new Runnable() {
public void run() {
Settings.System.putFloatForUser(mContext.getContentResolver(),
Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, adj,
UserHandle.USER_CURRENT);
}
});
}
}
for (BrightnessStateChangeCallback cb : mChangeCallbacks) {
cb.onBrightnessLevelChanged();
}
}
private void setMode(int mode) {
Settings.System.putIntForUser(mContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE, mode,
mUserTracker.getCurrentUserId());
}
private void setBrightness(int brightness) {
try {
mPower.setTemporaryScreenBrightnessSettingOverride(brightness);
} catch (RemoteException ex) {
}
}
private void setBrightnessAdj(float adj) {
try {
mPower.setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(adj);
} catch (RemoteException ex) {
}
}
private void updateIcon(boolean automatic) {
if (mIcon != null) {
mIcon.setImageResource(automatic && SHOW_AUTOMATIC_ICON ?
com.android.systemui.R.drawable.ic_qs_brightness_auto_on :
com.android.systemui.R.drawable.ic_qs_brightness_auto_off);
}
}
/** Fetch the brightness mode from the system settings and update the icon */
private void updateMode() {
if (mAutomaticAvailable) {
int automatic;
automatic = Settings.System.getIntForUser(mContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
UserHandle.USER_CURRENT);
mAutomatic = automatic != Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;
updateIcon(mAutomatic);
} else {
mControl.setChecked(false);
updateIcon(false /*automatic*/);
}
}
/** Fetch the brightness from the system settings and update the slider */
private void updateSlider() {
if (mAutomatic) {
float value = Settings.System.getFloatForUser(mContext.getContentResolver(),
Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0,
UserHandle.USER_CURRENT);
mControl.setMax((int) BRIGHTNESS_ADJ_RESOLUTION);
mControl.setValue((int) ((value + 1) * BRIGHTNESS_ADJ_RESOLUTION / 2f));
} else {
int value;
value = Settings.System.getIntForUser(mContext.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, mMaximumBacklight,
UserHandle.USER_CURRENT);
mControl.setMax(mMaximumBacklight - mMinimumBacklight);
mControl.setValue(value - mMinimumBacklight);
}
}
}
| gpl-3.0 |
xuejike/jkBindUtils | jkBindUtilsDemo/src/com/jkBindUtils/demo/VIActivity.java | 1959 | package com.jkBindUtils.demo;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ListView;
import com.jkBindUtils.bindAdapter.ViewIdBindAdapter;
import com.jkBindUtils.bindAdapter.ViewPropertyBindAdapter;
import com.jkBindUtils.demo.view.BookItemView;
import com.jkBindUtils.demo.vo.IdVBook;
import com.jkBindUtils.demo.vo.PBook;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Created by xuejike on 2014/12/22.
*/
public class VIActivity extends Activity {
private ListView listview;
private LinkedList<Drawable> drawables;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listview = (ListView)findViewById(R.id.listView);
Resources resources = getResources();
drawables = new LinkedList<Drawable>();
drawables.add(resources.getDrawable(R.drawable.b1));
drawables.add(resources.getDrawable(R.drawable.b2));
drawables.add(resources.getDrawable(R.drawable.b3));
drawables.add(resources.getDrawable(R.drawable.b4));
drawables.add(resources.getDrawable(R.drawable.b5));
drawables.add(resources.getDrawable(R.drawable.b6));
drawables.add(resources.getDrawable(R.drawable.b7));
String title = getIntent().getStringExtra("title");
setTitle(title);
listview.setAdapter(getViewIdBindAdapter());
}
// 在javabean 上注解上 布局文件 ,自动进行绑定
private ViewIdBindAdapter getViewIdBindAdapter(){
List list=new ArrayList();
for (int i=0;i<30;i++){
list.add(new IdVBook("图书标题"+i,drawables.get(i%drawables.size())));
}
ViewIdBindAdapter adapter =new ViewIdBindAdapter(this,list);
return adapter;
}
} | gpl-3.0 |
structr/structr | structr-core/src/main/java/org/structr/core/property/TargetId.java | 3788 | /*
* Copyright (C) 2010-2021 Structr GmbH
*
* This file is part of Structr <http://structr.org>.
*
* Structr is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Structr is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Structr. If not, see <http://www.gnu.org/licenses/>.
*/
package org.structr.core.property;
import java.util.Collections;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.structr.api.Predicate;
import org.structr.api.search.SortType;
import org.structr.common.SecurityContext;
import org.structr.common.error.FrameworkException;
import org.structr.core.GraphObject;
import org.structr.core.converter.PropertyConverter;
import org.structr.core.graph.CreationContainer;
import org.structr.core.graph.RelationshipInterface;
/**
*
*
*/
public class TargetId extends Property<String> {
private static final Logger logger = LoggerFactory.getLogger(TargetId.class.getName());
public TargetId(final String name) {
super(name);
passivelyIndexed();
}
@Override
public Class relatedType() {
return null;
}
@Override
public String getProperty(SecurityContext securityContext, GraphObject obj, boolean applyConverter) {
return getProperty(securityContext, obj, applyConverter, null);
}
@Override
public String getProperty(SecurityContext securityContext, GraphObject obj, boolean applyConverter, final Predicate<GraphObject> predicate) {
if (obj instanceof RelationshipInterface) {
return ((RelationshipInterface)obj).getTargetNodeId();
}
return null;
}
@Override
public boolean isCollection() {
return false;
}
@Override
public SortType getSortType() {
return SortType.Default;
}
@Override
public Object setProperty(SecurityContext securityContext, GraphObject obj, String value) throws FrameworkException {
if (obj instanceof RelationshipInterface) {
try {
((RelationshipInterface)obj).setTargetNodeId(value);
} catch (FrameworkException fex) {
throw fex;
} catch (Throwable t) {
logger.warn("", t);
}
} else if (obj instanceof CreationContainer) {
((CreationContainer)obj).setProperty(jsonName, value);
}
return null;
}
@Override
public Object fixDatabaseProperty(Object value) {
return null;
}
@Override
public String typeName() {
return null;
}
@Override
public Class valueType() {
return String.class;
}
@Override
public PropertyConverter<String, ?> databaseConverter(SecurityContext securityContext) {
return null;
}
@Override
public PropertyConverter<String, ?> databaseConverter(SecurityContext securityContext, GraphObject entity) {
return null;
}
@Override
public PropertyConverter<?, String> inputConverter(SecurityContext securityContext) {
return null;
}
// ----- OpenAPI -----
@Override
public Object getExampleValue(final String type, final String viewName) {
return null;
}
@Override
public Map<String, Object> describeOpenAPIOutputSchema(String type, String viewName) {
return null;
}
@Override
public Map<String, Object> describeOpenAPIOutputType(final String type, final String viewName, final int level) {
return Collections.EMPTY_MAP;
}
@Override
public Map<String, Object> describeOpenAPIInputType(final String type, final String viewName, final int level) {
return Collections.EMPTY_MAP;
}
}
| gpl-3.0 |
OlafLee/RankSys | RankSys-mf/src/main/java/es/uam/eps/ir/ranksys/mf/als/HKVFactorizer.java | 5529 | /*
* Copyright (C) 2015 Information Retrieval Group at Universidad Autonoma
* de Madrid, http://ir.ii.uam.es
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package es.uam.eps.ir.ranksys.mf.als;
import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.DoubleMatrix2D;
import cern.colt.matrix.impl.DenseDoubleMatrix1D;
import cern.colt.matrix.impl.DenseDoubleMatrix2D;
import cern.colt.matrix.linalg.Algebra;
import cern.colt.matrix.linalg.LUDecompositionQuick;
import es.uam.eps.ir.ranksys.fast.preference.FastPreferenceData;
import es.uam.eps.ir.ranksys.fast.preference.TransposedPreferenceData;
import java.util.function.DoubleUnaryOperator;
/**
* Implicit matrix factorization of Hu, Koren and Volinsky.
*
* Y. Hu, Y. Koren, C. Volinsky. Collaborative filtering for implicit feedback
* datasets. ICDM 2008.
*
* @author Saúl Vargas (saul.vargas@uam.es)
*
* @param <U> type of the users
* @param <I> type of the items
*/
public class HKVFactorizer<U, I> extends ALSFactorizer<U, I> {
private static final Algebra ALG = new Algebra();
private final double lambdaP;
private final double lambdaQ;
private final DoubleUnaryOperator confidence;
/**
* Constructor. Same regularization factor for user and item matrices.
*
* @param lambda regularization factor
* @param confidence confidence function
* @param numIter number of iterations
*/
public HKVFactorizer(double lambda, DoubleUnaryOperator confidence, int numIter) {
this(lambda, lambda, confidence, numIter);
}
/**
* Constructor. Different regularization factors for user and item matrices.
*
* @param lambdaP regularization factor for user matrix
* @param lambdaQ regularization factor for item matrix
* @param confidence confidence function
* @param numIter number of iterations
*/
public HKVFactorizer(double lambdaP, double lambdaQ, DoubleUnaryOperator confidence, int numIter) {
super(numIter);
this.lambdaP = lambdaP;
this.lambdaQ = lambdaQ;
this.confidence = confidence;
}
@Override
public double error(DenseDoubleMatrix2D p, DenseDoubleMatrix2D q, FastPreferenceData<U, I, ?> data) {
double error = data.getUidxWithPreferences().parallel().mapToDouble(uidx -> {
DoubleMatrix1D pu = p.viewRow(uidx);
DoubleMatrix1D su = q.zMult(pu, null);
double err1 = data.getUidxPreferences(uidx).mapToDouble(iv -> {
double rui = iv.v;
double sui = su.getQuick(iv.idx);
double cui = confidence.applyAsDouble(rui);
return cui * (rui - sui) * (rui - sui) - confidence.applyAsDouble(0) * sui * sui;
}).sum();
double err2 = confidence.applyAsDouble(0) * su.assign(x -> x * x).zSum();
return err1 + err2;
}).sum();
return error;
}
@Override
public void set_minP(final DenseDoubleMatrix2D p, final DenseDoubleMatrix2D q, FastPreferenceData<U, I, ?> data) {
set_min(p, q, confidence, lambdaP, data);
}
@Override
public void set_minQ(final DenseDoubleMatrix2D q, final DenseDoubleMatrix2D p, FastPreferenceData<U, I, ?> data) {
set_min(q, p, confidence, lambdaQ, new TransposedPreferenceData<>(data));
}
private static <U, I, O> void set_min(final DenseDoubleMatrix2D p, final DenseDoubleMatrix2D q, DoubleUnaryOperator confidence, double lambda, FastPreferenceData<U, I, O> data) {
final int K = p.columns();
DenseDoubleMatrix2D A1P = new DenseDoubleMatrix2D(K, K);
q.zMult(q, A1P, 1.0, 0.0, true, false);
for (int k = 0; k < K; k++) {
A1P.setQuick(k, k, lambda + A1P.getQuick(k, k));
}
DenseDoubleMatrix2D[] A2P = new DenseDoubleMatrix2D[q.rows()];
data.getIidxWithPreferences().parallel().forEach(iidx -> {
A2P[iidx] = new DenseDoubleMatrix2D(K, K);
DoubleMatrix1D qi = q.viewRow(iidx);
ALG.multOuter(qi, qi, A2P[iidx]);
});
data.getUidxWithPreferences().parallel().forEach(uidx -> {
DoubleMatrix2D A = new DenseDoubleMatrix2D(K, K);
DoubleMatrix1D b = new DenseDoubleMatrix1D(K);
A.assign(A1P);
b.assign(0.0);
data.getUidxPreferences(uidx).forEach(iv -> {
int iidx = iv.idx;
double rui = iv.v;
double cui = confidence.applyAsDouble(rui);
DoubleMatrix1D qi = q.viewRow(iidx);
A.assign(A2P[iidx], (x, y) -> x + y * (cui - 1.0));
b.assign(qi, (x, y) -> x + y * rui * cui);
});
LUDecompositionQuick lu = new LUDecompositionQuick(0);
lu.decompose(A);
lu.solve(b);
p.viewRow(uidx).assign(b);
});
}
}
| gpl-3.0 |