id
int64 | file_name
string | file_path
string | content
string | size
int64 | language
string | extension
string | total_lines
int64 | avg_line_length
float64 | max_line_length
int64 | alphanum_fraction
float64 | repo_name
string | repo_stars
int64 | repo_forks
int64 | repo_open_issues
int64 | repo_license
string | repo_extraction_date
string | exact_duplicates_redpajama
bool | near_duplicates_redpajama
bool | exact_duplicates_githubcode
bool | exact_duplicates_stackv2
bool | exact_duplicates_stackv1
bool | near_duplicates_githubcode
bool | near_duplicates_stackv1
bool | near_duplicates_stackv2
bool | length
int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,198,048
|
XMLSimpleType.java
|
keerath_openjdk-8-source/jaxp/src/com/sun/org/apache/xerces/internal/impl/dtd/XMLSimpleType.java
|
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package com.sun.org.apache.xerces.internal.impl.dtd;
import com.sun.org.apache.xerces.internal.impl.dv.DatatypeValidator;
/**
*/
public class XMLSimpleType {
//
// Constants
//
/** TYPE_CDATA */
public static final short TYPE_CDATA = 0;
/** TYPE_ENTITY */
public static final short TYPE_ENTITY = 1;
/** TYPE_ENUMERATION */
public static final short TYPE_ENUMERATION = 2;
/** TYPE_ID */
public static final short TYPE_ID = 3;
/** TYPE_IDREF */
public static final short TYPE_IDREF = 4;
/** TYPE_NMTOKEN */
public static final short TYPE_NMTOKEN = 5;
/** TYPE_NOTATION */
public static final short TYPE_NOTATION = 6;
/** TYPE_NAMED */
public static final short TYPE_NAMED = 7;
/** DEFAULT_TYPE_DEFAULT */
public static final short DEFAULT_TYPE_DEFAULT = 3;
/** DEFAULT_TYPE_FIXED */
public static final short DEFAULT_TYPE_FIXED = 1;
/** DEFAULT_TYPE_IMPLIED */
public static final short DEFAULT_TYPE_IMPLIED = 0;
/** DEFAULT_TYPE_REQUIRED */
public static final short DEFAULT_TYPE_REQUIRED = 2;
//
// Data
//
/** type */
public short type;
/** name */
public String name;
/** enumeration */
public String[] enumeration;
/** list */
public boolean list;
/** defaultType */
public short defaultType;
/** defaultValue */
public String defaultValue;
/** non-normalized defaultValue */
public String nonNormalizedDefaultValue;
/** datatypeValidator */
public DatatypeValidator datatypeValidator;
//
// Methods
//
/**
* setValues
*
* @param type
* @param name
* @param enumeration
* @param list
* @param defaultType
* @param defaultValue
* @param nonNormalizedDefaultValue
* @param datatypeValidator
*/
public void setValues(short type, String name, String[] enumeration,
boolean list, short defaultType,
String defaultValue, String nonNormalizedDefaultValue,
DatatypeValidator datatypeValidator) {
this.type = type;
this.name = name;
// REVISIT: Should this be a copy? -Ac
if (enumeration != null && enumeration.length > 0) {
this.enumeration = new String[enumeration.length];
System.arraycopy(enumeration, 0, this.enumeration, 0, this.enumeration.length);
}
else {
this.enumeration = null;
}
this.list = list;
this.defaultType = defaultType;
this.defaultValue = defaultValue;
this.nonNormalizedDefaultValue = nonNormalizedDefaultValue;
this.datatypeValidator = datatypeValidator;
} // setValues(short,String,String[],boolean,short,String,String,DatatypeValidator)
/** Set values. */
public void setValues(XMLSimpleType simpleType) {
type = simpleType.type;
name = simpleType.name;
// REVISIT: Should this be a copy? -Ac
if (simpleType.enumeration != null && simpleType.enumeration.length > 0) {
enumeration = new String[simpleType.enumeration.length];
System.arraycopy(simpleType.enumeration, 0, enumeration, 0, enumeration.length);
}
else {
enumeration = null;
}
list = simpleType.list;
defaultType = simpleType.defaultType;
defaultValue = simpleType.defaultValue;
nonNormalizedDefaultValue = simpleType.nonNormalizedDefaultValue;
datatypeValidator = simpleType.datatypeValidator;
} // setValues(XMLSimpleType)
/**
* clear
*/
public void clear() {
this.type = -1;
this.name = null;
this.enumeration = null;
this.list = false;
this.defaultType = -1;
this.defaultValue = null;
this.nonNormalizedDefaultValue = null;
this.datatypeValidator = null;
} // clear
} // class XMLSimpleType
| 6,886
|
Java
|
.java
| 178
| 33.213483
| 92
| 0.666167
|
keerath/openjdk-8-source
| 39
| 26
| 0
|
GPL-2.0
|
9/4/2024, 7:24:11 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 6,886
|
2,861,426
|
CliHandler.java
|
Lugia0529_JavaChat/ChatServer/src/Core/CliHandler.java
|
/*
* Copyright (C) 2011 Lugia Programming Team
*
* 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 Core;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CliHandler implements Runnable
{
private BufferedReader in;
public CliHandler() throws Exception
{
System.out.printf("\nInitializing Cli Command Handler.\n");
in = new BufferedReader(new InputStreamReader(System.in));
}
public void run()
{
System.out.printf("Cli Command Handler started.\n");
String command;
try
{
while(true)
{
command = in.readLine().trim();
if (command.isEmpty())
continue;
System.out.printf("Command Receive: %s\n", command);
if (command.equals("uptime"))
System.out.printf("Server Uptime: %dsec.\n", (System.currentTimeMillis() - Main.startupTime) / 1000);
else if (command.equals("clist"))
System.out.printf("Current Client List Size: %d\n", Main.clientList.size());
else
System.out.printf("Unknown Command: %s\n", command);
}
}
catch(Exception e){}
}
}
| 1,956
|
Java
|
.java
| 50
| 30.1
| 121
| 0.638706
|
Lugia0529/JavaChat
| 5
| 4
| 0
|
GPL-3.0
|
9/4/2024, 10:27:57 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 1,956
|
697,146
|
TestClientCallback.java
|
mathgladiator_adama-lang/web/src/test/java/org/adamalang/web/client/TestClientCallback.java
|
/*
* Adama Platform and Language
* Copyright (C) 2021 - 2024 by Adama Platform Engineering, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.adamalang.web.client;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.adamalang.common.Json;
import org.junit.Assert;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class TestClientCallback {
private final CountDownLatch closeLatch;
private final CountDownLatch pingLatch;
private final CountDownLatch firstLatch;
private final CountDownLatch failureLatch;
private final CountDownLatch failedToConnectLatch;
private final CountDownLatch disconnectLatch;
private String data;
private Throwable exception;
private ArrayList<String> writes;
private HashMap<Integer, Mailbox> mailboxes;
public final HashMap<String, String> headers;
public TestClientCallback() {
this.closeLatch = new CountDownLatch(1);
this.firstLatch = new CountDownLatch(1);
this.failureLatch = new CountDownLatch(1);
this.failedToConnectLatch = new CountDownLatch(1);
this.pingLatch = new CountDownLatch(1);
this.disconnectLatch = new CountDownLatch(1);
this.data = "";
this.writes = new ArrayList<>();
this.mailboxes = new HashMap<>();
this.headers = new HashMap<>();
}
public void awaitClosed() throws Exception {
Assert.assertTrue(closeLatch.await(5000, TimeUnit.MILLISECONDS));
}
public void awaitPing() throws Exception {
Assert.assertTrue(pingLatch.await(5000, TimeUnit.MILLISECONDS));
}
public void awaitFailure() throws Exception {
Assert.assertTrue(failureLatch.await(5000, TimeUnit.MILLISECONDS));
}
public void awaitFailedToConnect() throws Exception {
Assert.assertTrue(failedToConnectLatch.await(5000, TimeUnit.MILLISECONDS));
}
public void awaitFirst() throws Exception {
Assert.assertTrue(firstLatch.await(25000, TimeUnit.MILLISECONDS));
}
public void assertData(String data) {
Assert.assertEquals(data, this.data);
}
public void assertData(int write, String data) {
Assert.assertEquals(data, this.writes.get(write));
}
public void assertDataPrefix(int write, String data) {
Assert.assertTrue(this.writes.get(write).startsWith(data));
}
public void assertDataPrefix(String prefix) {
Assert.assertTrue(this.data.startsWith(prefix));
}
public void closed() {
closeLatch.countDown();
}
public void failed(Throwable exception) {
this.exception = exception;
failureLatch.countDown();
}
public void failedToConnect() {
failedToConnectLatch.countDown();
}
public void awaitDisconnect() throws Exception {
Assert.assertTrue(disconnectLatch.await(5000, TimeUnit.MILLISECONDS));
}
public boolean keepPings = false;
public void successfulResponse(String data) {
if (!data.contains("ping") || keepPings) {
this.data += data;
}
writes.add(data);
firstLatch.countDown();
try {
ObjectNode node = Json.parseJsonObject(data);
if (node.has("ping")) {
pingLatch.countDown();
}
if (node.has("status")) {
if ("disconnected".equals(node.get("status").textValue())) {
disconnectLatch.countDown();
}
}
if (node.has("id")) {
JsonNode idNode = node.get("id");
if (idNode != null && idNode.isInt()) {
getOrCreate(idNode.asInt()).deliver(data);
}
}
if (node.has("failure")) {
JsonNode idNode = node.get("failure");
if (idNode != null && idNode.isInt()) {
getOrCreate(idNode.asInt()).deliver(data);
}
}
if (node.has("deliver")) {
JsonNode idNode = node.get("deliver");
if (idNode != null && idNode.isInt()) {
getOrCreate(idNode.asInt()).deliver(data);
}
}
} catch (Exception ex) {
}
}
public synchronized Mailbox getOrCreate(int id) {
Mailbox mailbox = mailboxes.get(id);
if (mailbox == null) {
mailbox = new Mailbox();
mailboxes.put(id, mailbox);
}
return mailbox;
}
public class Mailbox {
private final ArrayList<String> writes;
private final HashSet<CountDownLatch> arrivals;
private final CountDownLatch firstLatch;
public Mailbox() {
this.arrivals = new HashSet<>();
writes = new ArrayList<>();
this.firstLatch = new CountDownLatch(1);
}
public synchronized void deliver(String data) {
firstLatch.countDown();
writes.add(data);
for (CountDownLatch latch : arrivals) {
latch.countDown();
}
}
public synchronized CountDownLatch latch(int c) {
CountDownLatch latch = new CountDownLatch(c);
arrivals.add(latch);
return latch;
}
public void assertData(int at, String data) {
Assert.assertEquals(data, writes.get(at));
}
public void awaitFirst() throws Exception {
Assert.assertTrue(firstLatch.await(5000, TimeUnit.MILLISECONDS));
}
}
}
| 5,762
|
Java
|
.java
| 166
| 30
| 79
| 0.709898
|
mathgladiator/adama-lang
| 107
| 15
| 14
|
AGPL-3.0
|
9/4/2024, 7:08:19 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| true
| true
| 5,762
|
3,032,812
|
BlockJukebox.java
|
SelfMadeSystem_PasteL/src/main/java/net/minecraft/block/BlockJukebox.java
|
package net.minecraft.block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
public class BlockJukebox extends BlockContainer
{
public static final PropertyBool HAS_RECORD = PropertyBool.create("has_record");
private static final String __OBFID = "CL_00000260";
protected BlockJukebox()
{
super(Material.wood);
this.setDefaultState(this.blockState.getBaseState().withProperty(HAS_RECORD, Boolean.valueOf(false)));
this.setCreativeTab(CreativeTabs.tabDecorations);
}
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ)
{
if (((Boolean)state.getValue(HAS_RECORD)).booleanValue())
{
this.dropRecord(worldIn, pos, state);
state = state.withProperty(HAS_RECORD, Boolean.valueOf(false));
worldIn.setBlockState(pos, state, 2);
return true;
}
else
{
return false;
}
}
public void insertRecord(World worldIn, BlockPos pos, IBlockState state, ItemStack recordStack)
{
if (!worldIn.isRemote)
{
TileEntity var5 = worldIn.getTileEntity(pos);
if (var5 instanceof BlockJukebox.TileEntityJukebox)
{
((BlockJukebox.TileEntityJukebox)var5).setRecord(new ItemStack(recordStack.getItem(), 1, recordStack.getMetadata()));
worldIn.setBlockState(pos, state.withProperty(HAS_RECORD, Boolean.valueOf(true)), 2);
}
}
}
private void dropRecord(World worldIn, BlockPos pos, IBlockState state)
{
if (!worldIn.isRemote)
{
TileEntity var4 = worldIn.getTileEntity(pos);
if (var4 instanceof BlockJukebox.TileEntityJukebox)
{
BlockJukebox.TileEntityJukebox var5 = (BlockJukebox.TileEntityJukebox)var4;
ItemStack var6 = var5.getRecord();
if (var6 != null)
{
worldIn.playAuxSFX(1005, pos, 0);
worldIn.func_175717_a(pos, (String)null);
var5.setRecord((ItemStack)null);
float var7 = 0.7F;
double var8 = (double)(worldIn.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.5D;
double var10 = (double)(worldIn.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.2D + 0.6D;
double var12 = (double)(worldIn.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.5D;
ItemStack var14 = var6.copy();
EntityItem var15 = new EntityItem(worldIn, (double)pos.getX() + var8, (double)pos.getY() + var10, (double)pos.getZ() + var12, var14);
var15.setDefaultPickupDelay();
worldIn.spawnEntityInWorld(var15);
}
}
}
}
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
this.dropRecord(worldIn, pos, state);
super.breakBlock(worldIn, pos, state);
}
/**
* Spawns this Block's drops into the World as EntityItems.
*
* @param chance The chance that each Item is actually spawned (1.0 = always, 0.0 = never)
* @param fortune The player's fortune level
*/
public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, IBlockState state, float chance, int fortune)
{
if (!worldIn.isRemote)
{
super.dropBlockAsItemWithChance(worldIn, pos, state, chance, 0);
}
}
/**
* Returns a new instance of a block's tile entity class. Called on placing the block.
*/
public TileEntity createNewTileEntity(World worldIn, int meta)
{
return new BlockJukebox.TileEntityJukebox();
}
public boolean hasComparatorInputOverride()
{
return true;
}
public int getComparatorInputOverride(World worldIn, BlockPos pos)
{
TileEntity var3 = worldIn.getTileEntity(pos);
if (var3 instanceof BlockJukebox.TileEntityJukebox)
{
ItemStack var4 = ((BlockJukebox.TileEntityJukebox)var3).getRecord();
if (var4 != null)
{
return Item.getIdFromItem(var4.getItem()) + 1 - Item.getIdFromItem(Items.record_13);
}
}
return 0;
}
/**
* The type of render function that is called for this block
*/
public int getRenderType()
{
return 3;
}
/**
* Convert the given metadata into a BlockState for this Block
*/
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(HAS_RECORD, Boolean.valueOf(meta > 0));
}
/**
* Convert the BlockState into the correct metadata value
*/
public int getMetaFromState(IBlockState state)
{
return ((Boolean)state.getValue(HAS_RECORD)).booleanValue() ? 1 : 0;
}
protected BlockState createBlockState()
{
return new BlockState(this, new IProperty[] {HAS_RECORD});
}
public static class TileEntityJukebox extends TileEntity
{
private ItemStack record;
private static final String __OBFID = "CL_00000261";
public void readFromNBT(NBTTagCompound compound)
{
super.readFromNBT(compound);
if (compound.hasKey("RecordItem", 10))
{
this.setRecord(ItemStack.loadItemStackFromNBT(compound.getCompoundTag("RecordItem")));
}
else if (compound.getInteger("Record") > 0)
{
this.setRecord(new ItemStack(Item.getItemById(compound.getInteger("Record")), 1, 0));
}
}
public void writeToNBT(NBTTagCompound compound)
{
super.writeToNBT(compound);
if (this.getRecord() != null)
{
compound.setTag("RecordItem", this.getRecord().writeToNBT(new NBTTagCompound()));
}
}
public ItemStack getRecord()
{
return this.record;
}
public void setRecord(ItemStack recordStack)
{
this.record = recordStack;
this.markDirty();
}
}
}
| 6,940
|
Java
|
.java
| 181
| 29.436464
| 159
| 0.631853
|
SelfMadeSystem/PasteL
| 5
| 0
| 0
|
GPL-3.0
|
9/4/2024, 10:43:25 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 6,940
|
3,144,919
|
Connector.java
|
franciscaconcha_ProyectoLogisim/src/com/cburch/logisim/tools/move/Connector.java
|
/* Copyright (c) 2010, Carl Burch. License information is located in the
* com.cburch.logisim.Main source code and at www.cburch.com/logisim/. */
package com.cburch.logisim.tools.move;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Set;
import com.cburch.logisim.circuit.ReplacementMap;
import com.cburch.logisim.circuit.Wire;
import com.cburch.logisim.data.Direction;
import com.cburch.logisim.data.Location;
class Connector {
private static final int MAX_SECONDS = 10;
private static final int MAX_ORDERING_TRIES = 10;
private static final int MAX_SEARCH_ITERATIONS = 20000;
private Connector() { }
static final String ALLOW_NEITHER = "neither";
static final String ALLOW_VERTICAL = "vert";
static final String ALLOW_HORIZONTAL = "horz";
static MoveResult computeWires(MoveRequest req) {
MoveGesture gesture = req.getMoveGesture();
int dx = req.getDeltaX();
int dy = req.getDeltaY();
ArrayList<ConnectionData> baseConnects;
baseConnects = new ArrayList<ConnectionData>(gesture.getConnections());
ArrayList<ConnectionData> impossible = pruneImpossible(baseConnects,
gesture.getFixedAvoidanceMap(), dx, dy);
AvoidanceMap selAvoid = AvoidanceMap.create(gesture.getSelected(), dx, dy);
HashMap<ConnectionData,Set<Location>> pathLocs;
pathLocs = new HashMap<ConnectionData,Set<Location>>();
HashMap<ConnectionData,List<SearchNode>> initNodes;
initNodes = new HashMap<ConnectionData,List<SearchNode>>();
for (ConnectionData conn : baseConnects) {
HashSet<Location> connLocs = new HashSet<Location>();
ArrayList<SearchNode> connNodes = new ArrayList<SearchNode>();
processConnection(conn, dx, dy, connLocs, connNodes, selAvoid);
pathLocs.put(conn, connLocs);
initNodes.put(conn, connNodes);
}
MoveResult bestResult = null;
int tries;
switch (baseConnects.size()) {
case 0: tries = 0; break;
case 1: tries = 1; break;
case 2: tries = 2; break;
case 3: tries = 8; break;
default: tries = MAX_ORDERING_TRIES;
}
long stopTime = System.currentTimeMillis() + MAX_SECONDS * 1000;
for (int tryNum = 0; tryNum < tries && stopTime - System.currentTimeMillis() > 0; tryNum++) {
if (ConnectorThread.isOverrideRequested()) {
return null;
}
ArrayList<ConnectionData> connects;
connects = new ArrayList<ConnectionData>(baseConnects);
if (tryNum < 2) {
sortConnects(connects, dx, dy);
if (tryNum == 1) {
Collections.reverse(connects);
}
} else {
Collections.shuffle(connects);
}
MoveResult candidate = tryList(req, gesture, connects, dx, dy,
pathLocs, initNodes, stopTime);
if (candidate == null) {
return null;
} else if (bestResult == null) {
bestResult = candidate;
} else {
int unsatisfied1 = bestResult.getUnsatisifiedConnections().size();
int unsatisfied2 = candidate.getUnsatisifiedConnections().size();
if (unsatisfied2 < unsatisfied1) {
bestResult = candidate;
} else if (unsatisfied2 == unsatisfied1) {
int dist1 = bestResult.getTotalDistance();
int dist2 = candidate.getTotalDistance();
if (dist2 < dist1) {
bestResult = candidate;
}
}
}
}
if (bestResult == null) { // should only happen for no connections
bestResult = new MoveResult(req, new ReplacementMap(), impossible, 0);
} else {
bestResult.addUnsatisfiedConnections(impossible);
}
return bestResult;
}
private static ArrayList<ConnectionData> pruneImpossible(
ArrayList<ConnectionData> connects, AvoidanceMap avoid, int dx, int dy) {
ArrayList<Wire> pathWires = new ArrayList<Wire>();
for (ConnectionData conn : connects) {
for (Wire w : conn.getWirePath()) {
pathWires.add(w);
}
}
ArrayList<ConnectionData> impossible = new ArrayList<ConnectionData>();
for (Iterator<ConnectionData> it = connects.iterator(); it.hasNext(); ) {
ConnectionData conn = it.next();
Location dest = conn.getLocation().translate(dx, dy);
if (avoid.get(dest) != null) {
boolean isInPath = false;
for (Wire w : pathWires) {
if (w.contains(dest)) {
isInPath = true;
break;
}
}
if (!isInPath) {
it.remove();
impossible.add(conn);
}
}
}
return impossible;
}
/** Creates a list of the connections to make, sorted according to their
* location. If, for example, we are moving an east-facing AND gate
* southeast, then we prefer to connect the inputs from the top down to
* minimize the chances that the created wires will interfere with each
* other - but if we are moving that gate northeast, we prefer to connect
* the inputs from the bottom up.
*/
private static void sortConnects(ArrayList<ConnectionData> connects,
final int dx, final int dy) {
Collections.sort(connects, new Comparator<ConnectionData>() {
public int compare(ConnectionData ac, ConnectionData bc) {
Location a = ac.getLocation();
Location b = bc.getLocation();
int abx = a.getX() - b.getX();
int aby = a.getY() - b.getY();
return abx * dx + aby * dy;
}
});
}
private static void processConnection(ConnectionData conn, int dx, int dy,
HashSet<Location> connLocs, ArrayList<SearchNode> connNodes,
AvoidanceMap selAvoid) {
Location cur = conn.getLocation();
Location dest = cur.translate(dx, dy);
if (selAvoid.get(cur) == null) {
Direction preferred = conn.getDirection();
if (preferred == null) {
if (Math.abs(dx) > Math.abs(dy)) {
preferred = dx > 0 ? Direction.EAST : Direction.WEST;
} else {
preferred = dy > 0 ? Direction.SOUTH : Direction.NORTH;
}
}
connLocs.add(cur);
connNodes.add(new SearchNode(conn, cur, preferred, dest));
}
for (Wire w : conn.getWirePath()) {
for (Location loc : w) {
if (selAvoid.get(loc) == null || loc.equals(dest)) {
boolean added = connLocs.add(loc);
if (added) {
Direction dir = null;
if (w.endsAt(loc)) {
if (w.isVertical()) {
int y0 = loc.getY();
int y1 = w.getOtherEnd(loc).getY();
dir = y0 < y1 ? Direction.NORTH : Direction.SOUTH;
} else {
int x0 = loc.getX();
int x1 = w.getOtherEnd(loc).getX();
dir = x0 < x1 ? Direction.WEST : Direction.EAST;
}
}
connNodes.add(new SearchNode(conn, loc, dir, dest));
}
}
}
}
}
private static MoveResult tryList(MoveRequest req,
MoveGesture gesture, ArrayList<ConnectionData> connects,
int dx, int dy, HashMap<ConnectionData,Set<Location>> pathLocs,
HashMap<ConnectionData,List<SearchNode>> initNodes, long stopTime) {
AvoidanceMap avoid = gesture.getFixedAvoidanceMap().cloneMap();
avoid.markAll(gesture.getSelected(), dx, dy);
ReplacementMap replacements = new ReplacementMap();
ArrayList<ConnectionData> unconnected = new ArrayList<ConnectionData>();
int totalDistance = 0;
for (ConnectionData conn : connects) {
if (ConnectorThread.isOverrideRequested()) {
return null;
}
if (System.currentTimeMillis() - stopTime > 0) {
unconnected.add(conn);
continue;
}
List<SearchNode> connNodes = initNodes.get(conn);
Set<Location> connPathLocs = pathLocs.get(conn);
SearchNode n = findShortestPath(connNodes, connPathLocs, avoid);
if (n != null) { // normal case - a path was found
totalDistance += n.getDistance();
ArrayList<Location> path = convertToPath(n);
processPath(path, conn, avoid, replacements, connPathLocs);
} else if (ConnectorThread.isOverrideRequested()) {
return null; // search was aborted: return null to indicate this
} else {
unconnected.add(conn);
}
}
return new MoveResult(req, replacements, unconnected, totalDistance);
}
private static SearchNode findShortestPath(List<SearchNode> nodes,
Set<Location> pathLocs, AvoidanceMap avoid) {
PriorityQueue<SearchNode> q = new PriorityQueue<SearchNode>(nodes);
HashSet<SearchNode> visited = new HashSet<SearchNode>();
int iters = 0;
while (!q.isEmpty() && iters < MAX_SEARCH_ITERATIONS) {
iters++;
SearchNode n = q.remove();
if (iters % 64 == 0 && ConnectorThread.isOverrideRequested()
|| n == null) {
return null;
}
if (n.isDestination()) {
return n;
}
boolean added = visited.add(n);
if (!added) {
continue;
}
Location loc = n.getLocation();
Direction dir = n.getDirection();
int neighbors = 3;
Object allowed = avoid.get(loc);
if (allowed != null && n.isStart() && pathLocs.contains(loc)) {
allowed = null;
}
if (allowed == ALLOW_NEITHER) {
neighbors = 0;
} else if (allowed == ALLOW_VERTICAL) {
if (dir == null) {
dir = Direction.NORTH;
neighbors = 2;
} else if (dir == Direction.NORTH || dir == Direction.SOUTH) {
neighbors = 1;
} else {
neighbors = 0;
}
} else if (allowed == ALLOW_HORIZONTAL) {
if (dir == null) {
dir = Direction.EAST;
neighbors = 2;
} else if (dir == Direction.EAST || dir == Direction.WEST) {
neighbors = 1;
} else {
neighbors = 0;
}
} else {
if (dir == null) {
dir = Direction.NORTH;
neighbors = 4;
} else {
neighbors = 3;
}
}
for (int i = 0; i < neighbors; i++) {
Direction oDir;
switch (i) {
case 0:
oDir = dir;
break;
case 1:
oDir = neighbors == 2 ? dir.reverse() : dir.getLeft();
break;
case 2:
oDir = dir.getRight();
break;
default: // must be 3
oDir = dir.reverse();
}
SearchNode o = n.next(oDir, allowed != null);
if (o != null && !visited.contains(o)) {
q.add(o);
}
}
}
return null;
}
private static ArrayList<Location> convertToPath(SearchNode last) {
SearchNode next = last;
SearchNode prev = last.getPrevious();
ArrayList<Location> ret = new ArrayList<Location>();
ret.add(next.getLocation());
while (prev != null) {
if (prev.getDirection() != next.getDirection()) {
ret.add(prev.getLocation());
}
next = prev;
prev = prev.getPrevious();
}
if (!ret.get(ret.size() - 1).equals(next.getLocation())) {
ret.add(next.getLocation());
}
Collections.reverse(ret);
return ret;
}
private static void processPath(ArrayList<Location> path, ConnectionData conn,
AvoidanceMap avoid, ReplacementMap repl, Set<Location> unmarkable) {
Iterator<Location> pathIt = path.iterator();
Location loc0 = pathIt.next();
if (!loc0.equals(conn.getLocation())) {
Location pathLoc = conn.getWirePathStart();
boolean found = loc0.equals(pathLoc);
for (Wire w : conn.getWirePath()) {
Location nextLoc = w.getOtherEnd(pathLoc);
if (found) { // existing wire will be removed
repl.remove(w);
avoid.unmarkWire(w, nextLoc, unmarkable);
} else if (w.contains(loc0)) { // wires after this will be removed
found = true;
if (!loc0.equals(nextLoc)) {
avoid.unmarkWire(w, nextLoc, unmarkable);
Wire shortenedWire = Wire.create(pathLoc, loc0);
repl.replace(w, shortenedWire);
avoid.markWire(shortenedWire, 0, 0);
}
}
pathLoc = nextLoc;
}
}
while (pathIt.hasNext()) {
Location loc1 = pathIt.next();
Wire newWire = Wire.create(loc0, loc1);
repl.add(newWire);
avoid.markWire(newWire, 0, 0);
loc0 = loc1;
}
}
}
| 11,426
|
Java
|
.java
| 342
| 29.154971
| 95
| 0.681489
|
franciscaconcha/ProyectoLogisim
| 4
| 1
| 9
|
GPL-2.0
|
9/4/2024, 11:00:44 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| true
| true
| 11,426
|
1,639,761
|
SignerInfo.java
|
srisatish_openjdk/jdk/src/share/classes/sun/security/pkcs/SignerInfo.java
|
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.pkcs;
import java.io.OutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.X509Certificate;
import java.security.*;
import java.util.ArrayList;
import sun.security.util.*;
import sun.security.x509.AlgorithmId;
import sun.security.x509.X500Name;
import sun.security.x509.KeyUsageExtension;
import sun.security.x509.PKIXExtensions;
import sun.misc.HexDumpEncoder;
/**
* A SignerInfo, as defined in PKCS#7's signedData type.
*
* @author Benjamin Renaud
*/
public class SignerInfo implements DerEncoder {
BigInteger version;
X500Name issuerName;
BigInteger certificateSerialNumber;
AlgorithmId digestAlgorithmId;
AlgorithmId digestEncryptionAlgorithmId;
byte[] encryptedDigest;
PKCS9Attributes authenticatedAttributes;
PKCS9Attributes unauthenticatedAttributes;
public SignerInfo(X500Name issuerName,
BigInteger serial,
AlgorithmId digestAlgorithmId,
AlgorithmId digestEncryptionAlgorithmId,
byte[] encryptedDigest) {
this.version = BigInteger.ONE;
this.issuerName = issuerName;
this.certificateSerialNumber = serial;
this.digestAlgorithmId = digestAlgorithmId;
this.digestEncryptionAlgorithmId = digestEncryptionAlgorithmId;
this.encryptedDigest = encryptedDigest;
}
public SignerInfo(X500Name issuerName,
BigInteger serial,
AlgorithmId digestAlgorithmId,
PKCS9Attributes authenticatedAttributes,
AlgorithmId digestEncryptionAlgorithmId,
byte[] encryptedDigest,
PKCS9Attributes unauthenticatedAttributes) {
this.version = BigInteger.ONE;
this.issuerName = issuerName;
this.certificateSerialNumber = serial;
this.digestAlgorithmId = digestAlgorithmId;
this.authenticatedAttributes = authenticatedAttributes;
this.digestEncryptionAlgorithmId = digestEncryptionAlgorithmId;
this.encryptedDigest = encryptedDigest;
this.unauthenticatedAttributes = unauthenticatedAttributes;
}
/**
* Parses a PKCS#7 signer info.
*/
public SignerInfo(DerInputStream derin)
throws IOException, ParsingException
{
this(derin, false);
}
/**
* Parses a PKCS#7 signer info.
*
* <p>This constructor is used only for backwards compatibility with
* PKCS#7 blocks that were generated using JDK1.1.x.
*
* @param derin the ASN.1 encoding of the signer info.
* @param oldStyle flag indicating whether or not the given signer info
* is encoded according to JDK1.1.x.
*/
public SignerInfo(DerInputStream derin, boolean oldStyle)
throws IOException, ParsingException
{
// version
version = derin.getBigInteger();
// issuerAndSerialNumber
DerValue[] issuerAndSerialNumber = derin.getSequence(2);
byte[] issuerBytes = issuerAndSerialNumber[0].toByteArray();
issuerName = new X500Name(new DerValue(DerValue.tag_Sequence,
issuerBytes));
certificateSerialNumber = issuerAndSerialNumber[1].getBigInteger();
// digestAlgorithmId
DerValue tmp = derin.getDerValue();
digestAlgorithmId = AlgorithmId.parse(tmp);
// authenticatedAttributes
if (oldStyle) {
// In JDK1.1.x, the authenticatedAttributes are always present,
// encoded as an empty Set (Set of length zero)
derin.getSet(0);
} else {
// check if set of auth attributes (implicit tag) is provided
// (auth attributes are OPTIONAL)
if ((byte)(derin.peekByte()) == (byte)0xA0) {
authenticatedAttributes = new PKCS9Attributes(derin);
}
}
// digestEncryptionAlgorithmId - little RSA naming scheme -
// signature == encryption...
tmp = derin.getDerValue();
digestEncryptionAlgorithmId = AlgorithmId.parse(tmp);
// encryptedDigest
encryptedDigest = derin.getOctetString();
// unauthenticatedAttributes
if (oldStyle) {
// In JDK1.1.x, the unauthenticatedAttributes are always present,
// encoded as an empty Set (Set of length zero)
derin.getSet(0);
} else {
// check if set of unauth attributes (implicit tag) is provided
// (unauth attributes are OPTIONAL)
if (derin.available() != 0
&& (byte)(derin.peekByte()) == (byte)0xA1) {
unauthenticatedAttributes =
new PKCS9Attributes(derin, true);// ignore unsupported attrs
}
}
// all done
if (derin.available() != 0) {
throw new ParsingException("extra data at the end");
}
}
public void encode(DerOutputStream out) throws IOException {
derEncode(out);
}
/**
* DER encode this object onto an output stream.
* Implements the <code>DerEncoder</code> interface.
*
* @param out
* the output stream on which to write the DER encoding.
*
* @exception IOException on encoding error.
*/
public void derEncode(OutputStream out) throws IOException {
DerOutputStream seq = new DerOutputStream();
seq.putInteger(version);
DerOutputStream issuerAndSerialNumber = new DerOutputStream();
issuerName.encode(issuerAndSerialNumber);
issuerAndSerialNumber.putInteger(certificateSerialNumber);
seq.write(DerValue.tag_Sequence, issuerAndSerialNumber);
digestAlgorithmId.encode(seq);
// encode authenticated attributes if there are any
if (authenticatedAttributes != null)
authenticatedAttributes.encode((byte)0xA0, seq);
digestEncryptionAlgorithmId.encode(seq);
seq.putOctetString(encryptedDigest);
// encode unauthenticated attributes if there are any
if (unauthenticatedAttributes != null)
unauthenticatedAttributes.encode((byte)0xA1, seq);
DerOutputStream tmp = new DerOutputStream();
tmp.write(DerValue.tag_Sequence, seq);
out.write(tmp.toByteArray());
}
/*
* Returns the (user) certificate pertaining to this SignerInfo.
*/
public X509Certificate getCertificate(PKCS7 block)
throws IOException
{
return block.getCertificate(certificateSerialNumber, issuerName);
}
/*
* Returns the certificate chain pertaining to this SignerInfo.
*/
public ArrayList<X509Certificate> getCertificateChain(PKCS7 block)
throws IOException
{
X509Certificate userCert;
userCert = block.getCertificate(certificateSerialNumber, issuerName);
if (userCert == null)
return null;
ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
certList.add(userCert);
X509Certificate[] pkcsCerts = block.getCertificates();
if (pkcsCerts == null
|| userCert.getSubjectDN().equals(userCert.getIssuerDN())) {
return certList;
}
Principal issuer = userCert.getIssuerDN();
int start = 0;
while (true) {
boolean match = false;
int i = start;
while (i < pkcsCerts.length) {
if (issuer.equals(pkcsCerts[i].getSubjectDN())) {
// next cert in chain found
certList.add(pkcsCerts[i]);
// if selected cert is self-signed, we're done
// constructing the chain
if (pkcsCerts[i].getSubjectDN().equals(
pkcsCerts[i].getIssuerDN())) {
start = pkcsCerts.length;
} else {
issuer = pkcsCerts[i].getIssuerDN();
X509Certificate tmpCert = pkcsCerts[start];
pkcsCerts[start] = pkcsCerts[i];
pkcsCerts[i] = tmpCert;
start++;
}
match = true;
break;
} else {
i++;
}
}
if (!match)
break;
}
return certList;
}
/* Returns null if verify fails, this signerInfo if
verify succeeds. */
SignerInfo verify(PKCS7 block, byte[] data)
throws NoSuchAlgorithmException, SignatureException {
try {
ContentInfo content = block.getContentInfo();
if (data == null) {
data = content.getContentBytes();
}
String digestAlgname = getDigestAlgorithmId().getName();
if (digestAlgname.equalsIgnoreCase("SHA"))
digestAlgname = "SHA1";
byte[] dataSigned;
// if there are authenticate attributes, get the message
// digest and compare it with the digest of data
if (authenticatedAttributes == null) {
dataSigned = data;
} else {
// first, check content type
ObjectIdentifier contentType = (ObjectIdentifier)
authenticatedAttributes.getAttributeValue(
PKCS9Attribute.CONTENT_TYPE_OID);
if (contentType == null ||
!contentType.equals(content.contentType))
return null; // contentType does not match, bad SignerInfo
// now, check message digest
byte[] messageDigest = (byte[])
authenticatedAttributes.getAttributeValue(
PKCS9Attribute.MESSAGE_DIGEST_OID);
if (messageDigest == null) // fail if there is no message digest
return null;
MessageDigest md = MessageDigest.getInstance(digestAlgname);
byte[] computedMessageDigest = md.digest(data);
if (messageDigest.length != computedMessageDigest.length)
return null;
for (int i = 0; i < messageDigest.length; i++) {
if (messageDigest[i] != computedMessageDigest[i])
return null;
}
// message digest attribute matched
// digest of original data
// the data actually signed is the DER encoding of
// the authenticated attributes (tagged with
// the "SET OF" tag, not 0xA0).
dataSigned = authenticatedAttributes.getDerEncoding();
}
// put together digest algorithm and encryption algorithm
// to form signing algorithm
String encryptionAlgname =
getDigestEncryptionAlgorithmId().getName();
if (encryptionAlgname.equalsIgnoreCase("SHA1withDSA"))
encryptionAlgname = "DSA";
String algname = digestAlgname + "with" + encryptionAlgname;
Signature sig = Signature.getInstance(algname);
X509Certificate cert = getCertificate(block);
if (cert == null) {
return null;
}
if (cert.hasUnsupportedCriticalExtension()) {
throw new SignatureException("Certificate has unsupported "
+ "critical extension(s)");
}
// Make sure that if the usage of the key in the certificate is
// restricted, it can be used for digital signatures.
// XXX We may want to check for additional extensions in the
// future.
boolean[] keyUsageBits = cert.getKeyUsage();
if (keyUsageBits != null) {
KeyUsageExtension keyUsage;
try {
// We don't care whether or not this extension was marked
// critical in the certificate.
// We're interested only in its value (i.e., the bits set)
// and treat the extension as critical.
keyUsage = new KeyUsageExtension(keyUsageBits);
} catch (IOException ioe) {
throw new SignatureException("Failed to parse keyUsage "
+ "extension");
}
boolean digSigAllowed = ((Boolean)keyUsage.get(
KeyUsageExtension.DIGITAL_SIGNATURE)).booleanValue();
boolean nonRepuAllowed = ((Boolean)keyUsage.get(
KeyUsageExtension.NON_REPUDIATION)).booleanValue();
if (!digSigAllowed && !nonRepuAllowed) {
throw new SignatureException("Key usage restricted: "
+ "cannot be used for "
+ "digital signatures");
}
}
PublicKey key = cert.getPublicKey();
sig.initVerify(key);
sig.update(dataSigned);
if (sig.verify(encryptedDigest)) {
return this;
}
} catch (IOException e) {
throw new SignatureException("IO error verifying signature:\n" +
e.getMessage());
} catch (InvalidKeyException e) {
throw new SignatureException("InvalidKey: " + e.getMessage());
}
return null;
}
/* Verify the content of the pkcs7 block. */
SignerInfo verify(PKCS7 block)
throws NoSuchAlgorithmException, SignatureException {
return verify(block, null);
}
public BigInteger getVersion() {
return version;
}
public X500Name getIssuerName() {
return issuerName;
}
public BigInteger getCertificateSerialNumber() {
return certificateSerialNumber;
}
public AlgorithmId getDigestAlgorithmId() {
return digestAlgorithmId;
}
public PKCS9Attributes getAuthenticatedAttributes() {
return authenticatedAttributes;
}
public AlgorithmId getDigestEncryptionAlgorithmId() {
return digestEncryptionAlgorithmId;
}
public byte[] getEncryptedDigest() {
return encryptedDigest;
}
public PKCS9Attributes getUnauthenticatedAttributes() {
return unauthenticatedAttributes;
}
public String toString() {
HexDumpEncoder hexDump = new HexDumpEncoder();
String out = "";
out += "Signer Info for (issuer): " + issuerName + "\n";
out += "\tversion: " + Debug.toHexString(version) + "\n";
out += "\tcertificateSerialNumber: " +
Debug.toHexString(certificateSerialNumber) + "\n";
out += "\tdigestAlgorithmId: " + digestAlgorithmId + "\n";
if (authenticatedAttributes != null) {
out += "\tauthenticatedAttributes: " + authenticatedAttributes +
"\n";
}
out += "\tdigestEncryptionAlgorithmId: " + digestEncryptionAlgorithmId +
"\n";
out += "\tencryptedDigest: " + "\n" +
hexDump.encodeBuffer(encryptedDigest) + "\n";
if (unauthenticatedAttributes != null) {
out += "\tunauthenticatedAttributes: " +
unauthenticatedAttributes + "\n";
}
return out;
}
}
| 16,901
|
Java
|
.java
| 392
| 31.691327
| 80
| 0.606695
|
srisatish/openjdk
| 14
| 22
| 0
|
GPL-2.0
|
9/4/2024, 8:10:41 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 16,901
|
2,084,229
|
CraftCrops.java
|
FukkitMC_fukkit/src/main/java/org/bukkit/craftbukkit/block/impl/CraftCrops.java
|
/**
* Automatically generated file, changes will be lost.
*/
package org.bukkit.craftbukkit.block.impl;
public final class CraftCrops extends org.bukkit.craftbukkit.block.data.CraftBlockData implements org.bukkit.block.data.Ageable {
public CraftCrops() {
super();
}
public CraftCrops(net.minecraft.world.level.block.state.IBlockData state) {
super(state);
}
// org.bukkit.craftbukkit.block.data.CraftAgeable
private static final net.minecraft.world.level.block.state.properties.BlockStateInteger AGE = getInteger(net.minecraft.world.level.block.BlockCrops.class, "age");
@Override
public int getAge() {
return get(AGE);
}
@Override
public void setAge(int age) {
set(AGE, age);
}
@Override
public int getMaximumAge() {
return getMax(AGE);
}
}
| 853
|
Java
|
.java
| 26
| 27.576923
| 166
| 0.70696
|
FukkitMC/fukkit
| 19
| 3
| 2
|
LGPL-3.0
|
9/4/2024, 8:28:58 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 853
|
2,562,499
|
ChangeLeaderEvent.java
|
Yoress_ARP/AC-Game/src/com/aionemu/gameserver/model/team2/common/events/ChangeLeaderEvent.java
|
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning. If not, see <http://www.gnu.org/licenses/>.
*
*
* Credits goes to all Open Source Core Developer Groups listed below Please do not change here something, ragarding the developer credits, except the
* "developed by XXXX". Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". Everybody knows that this
* Emulator Core was developed by Aion Lightning
*
* @-Aion-Unique-
* @-Aion-Lightning
* @Aion-Engine
* @Aion-Extreme
* @Aion-NextGen
* @Aion-Core Dev.
*/
package com.aionemu.gameserver.model.team2.common.events;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.team2.TemporaryPlayerTeam;
import com.aionemu.gameserver.model.team2.group.events.ChangeGroupLeaderEvent;
/**
* @author ATracer
*/
public abstract class ChangeLeaderEvent<T extends TemporaryPlayerTeam<?>> extends AbstractTeamPlayerEvent<T> {
private static final Logger log = LoggerFactory.getLogger(ChangeGroupLeaderEvent.class);
public ChangeLeaderEvent(T team, Player eventPlayer) {
super(team, eventPlayer);
}
/**
* New leader either is null or should be online
*/
@Override
public boolean checkCondition() {
return eventPlayer == null || eventPlayer.isOnline();
}
@Override
public boolean apply(Player player) {
if (!player.getObjectId().equals(team.getLeader().getObjectId()) && player.isOnline()) {
changeLeaderTo(player);
return false;
}
return true;
}
/**
* @param oldLeader
*/
protected void checkLeaderChanged(Player oldLeader) {
if (team.isLeader(oldLeader)) {
log.info("TEAM2: leader is not changed, total: {}, online: {}", team.size(), team.onlineMembers());
}
}
protected abstract void changeLeaderTo(Player player);
}
| 2,557
|
Java
|
.java
| 62
| 37.725806
| 151
| 0.747875
|
Yoress/ARP
| 7
| 5
| 0
|
GPL-3.0
|
9/4/2024, 9:49:28 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| true
| true
| true
| 2,557
|
1,270,128
|
ComparatorCreatorBasic.java
|
poolborges_unicenta-pos/kriolos-opos-base/src/main/java/com/openbravo/data/loader/ComparatorCreatorBasic.java
|
// KriolOS POS
// Copyright (c) 2019-2023 KriolOS
//
// 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.openbravo.data.loader;
import java.util.Comparator;
/**
*
* @author JG uniCenta
*/
public class ComparatorCreatorBasic implements ComparatorCreator {
private String[] m_sHeaders;
private Datas[] m_aDatas;
private int[] m_iAvailableIndexes;
/** Creates a new instance of ComparatorCreatorBasic
* @param sHeaders
* @param aDatas
* @param iAvailableIndexes */
public ComparatorCreatorBasic(String[] sHeaders, Datas[] aDatas, int[] iAvailableIndexes) {
m_sHeaders = sHeaders;
m_aDatas = aDatas;
m_iAvailableIndexes = iAvailableIndexes;
}
/**
*
* @param sHeaders
* @param aDatas
*/
public ComparatorCreatorBasic(String[] sHeaders, Datas[] aDatas) {
m_sHeaders = sHeaders;
m_aDatas = aDatas;
m_iAvailableIndexes = new int[aDatas.length];
for (int i = 0; i < aDatas.length; i++) {
m_iAvailableIndexes[i] = i;
}
}
/**
*
* @return
*/
public String[] getHeaders() {
String[] sTempHeaders = new String[m_iAvailableIndexes.length];
for (int i = 0; i < m_iAvailableIndexes.length; i++) {
sTempHeaders[i] = m_sHeaders[m_iAvailableIndexes[i]];
}
return sTempHeaders;
}
/**
*
* @param aiOrderBy
* @return
*/
public Comparator createComparator(int[] aiOrderBy) {
return new ComparatorBasic(aiOrderBy);
}
/**
*
*/
public class ComparatorBasic implements Comparator {
private int[] m_aiOrderBy;
/** Creates a new instance of ComparatorBasic
* @param aiOrderBy */
public ComparatorBasic(int[] aiOrderBy) {
m_aiOrderBy = aiOrderBy;
}
public int compare(Object o1, Object o2) {
if (o1 == null) {
if (o2 == null) {
return 0;
} else {
return -1;
}
} else if (o2 == null) {
return +1;
} else {
// ninguno de los dos es nulo...
Object[] ao1 = (Object[]) o1;
Object[] ao2 = (Object[]) o2;
for (int i = 0; i < m_aiOrderBy.length; i++) {
int result = m_aDatas[m_iAvailableIndexes[m_aiOrderBy[i]]].compare(ao1[m_iAvailableIndexes[m_aiOrderBy[i]]], ao2[m_iAvailableIndexes[m_aiOrderBy[i]]]);
if (result != 0) {
return result;
}
}
return 0;
}
}
}
}
| 3,427
|
Java
|
.java
| 100
| 25.64
| 171
| 0.575711
|
poolborges/unicenta-pos
| 37
| 38
| 3
|
GPL-3.0
|
9/4/2024, 7:29:55 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 3,427
|
633,491
|
BufferedTextWindow.java
|
sblendorio_petscii-bbs/src/main/java/org/zmpp/windowing/BufferedTextWindow.java
|
/*
* Created on 2008/04/23
* Copyright (c) 2005-2010, Wei-ju Wu.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of Wei-ju Wu nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.zmpp.windowing;
import java.util.ArrayList;
import java.util.List;
/**
* BufferedTextWindow is part of the BufferedScreenModel, it represents a
* buffer for continuously flowing text.
* @author Wei-ju Wu
* @version 1.5
*/
public class BufferedTextWindow {
private List<AnnotatedText> textBuffer;
private TextAnnotation currentAnnotation = new TextAnnotation(
TextAnnotation.FONT_NORMAL, TextAnnotation.TEXTSTYLE_ROMAN);
private StringBuilder currentRun;
private boolean isBuffered;
/**
* Constructor.
*/
public BufferedTextWindow() {
reset();
}
/**
* Reset the window state.
*/
public void reset() {
textBuffer = new ArrayList<AnnotatedText>();
currentRun = new StringBuilder();
isBuffered = true;
}
/**
* Retrieves the currently active annotation.
* @return active annotation
*/
public TextAnnotation getCurrentAnnotation() { return currentAnnotation; }
/**
* Determines whether this window is buffered.
* @return true if buffered, false otherwise
*/
public boolean isBuffered() { return isBuffered; }
/**
* Sets the buffered flag.
* @param flag true to set to buffered, false to unbuffered
*/
public void setBuffered(boolean flag) { isBuffered = flag; }
/**
* Sets the window's current font.
* @param font font number
* @return previous font number
*/
public char setCurrentFont(char font) {
char previousFont = currentAnnotation.getFont();
// no need to start a new run if the font is the same
if (previousFont != font) {
startNewAnnotatedRun(currentAnnotation.deriveFont(font));
}
return previousFont;
}
/**
* Sets the window's current text style.
* @param style text style number
*/
public void setCurrentTextStyle(int style) {
startNewAnnotatedRun(currentAnnotation.deriveStyle(style));
}
/**
* Sets this window's current background color.
* @param color color number
*/
public void setBackground(int color) {
startNewAnnotatedRun(currentAnnotation.deriveBackground(color));
}
/**
* Sets this window's current foreground color.
* @param color color number
*/
public void setForeground(int color) {
startNewAnnotatedRun(currentAnnotation.deriveForeground(color));
}
/**
* Retrieves this window's current background color.
* @return current background color
*/
public int getBackground() { return currentAnnotation.getBackground(); }
/**
* Retrieves this window's current foreground color.
* @return current foreground color
*/
public int getForeground() { return currentAnnotation.getForeground(); }
/**
* Begins a new text run with the specified annotation.
* @param annotation the annotation for the text run
*/
private void startNewAnnotatedRun(TextAnnotation annotation) {
textBuffer.add(new AnnotatedText(currentAnnotation, currentRun.toString()));
currentRun = new StringBuilder();
currentAnnotation = annotation;
}
/**
* Appends a character to the current text run.
* @param zchar character to print
*/
public void printChar(char zchar) {
currentRun.append(zchar);
}
/**
* Returns this window's buffer.
* @return buffer
*/
public List<AnnotatedText> getBuffer() {
flush();
List<AnnotatedText> result = textBuffer;
textBuffer = new ArrayList<AnnotatedText>();
return result;
}
/**
* Flushes pending output into
*/
private void flush() {
if (currentRun.length() > 0) {
textBuffer.add(new AnnotatedText(currentAnnotation,
currentRun.toString()));
currentRun = new StringBuilder();
}
}
/**
* Override toString().
* @return the string representation
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (AnnotatedText str : textBuffer) {
String line = str.getText().replace('\r', '\n');
builder.append(line);
}
return builder.toString();
}
}
| 5,589
|
Java
|
.java
| 166
| 29.951807
| 80
| 0.728163
|
sblendorio/petscii-bbs
| 119
| 16
| 13
|
MPL-2.0
|
9/4/2024, 7:08:18 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 5,589
|
341,930
|
ArrayBlockingQueue.java
|
google_desugar_jdk_libs/jdk11/src/libcore/ojluni/src/main/java/java/util/concurrent/ArrayBlockingQueue.java
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java.util.concurrent;
import java.lang.ref.WeakReference;
import java.util.AbstractQueue;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
// BEGIN android-note
// removed link to collections framework docs
// END android-note
/**
* A bounded {@linkplain BlockingQueue blocking queue} backed by an
* array. This queue orders elements FIFO (first-in-first-out). The
* <em>head</em> of the queue is that element that has been on the
* queue the longest time. The <em>tail</em> of the queue is that
* element that has been on the queue the shortest time. New elements
* are inserted at the tail of the queue, and the queue retrieval
* operations obtain elements at the head of the queue.
*
* <p>This is a classic "bounded buffer", in which a
* fixed-sized array holds elements inserted by producers and
* extracted by consumers. Once created, the capacity cannot be
* changed. Attempts to {@code put} an element into a full queue
* will result in the operation blocking; attempts to {@code take} an
* element from an empty queue will similarly block.
*
* <p>This class supports an optional fairness policy for ordering
* waiting producer and consumer threads. By default, this ordering
* is not guaranteed. However, a queue constructed with fairness set
* to {@code true} grants threads access in FIFO order. Fairness
* generally decreases throughput but reduces variability and avoids
* starvation.
*
* <p>This class and its iterator implement all of the
* <em>optional</em> methods of the {@link Collection} and {@link
* Iterator} interfaces.
*
* @since 1.5
* @author Doug Lea
* @param <E> the type of elements held in this queue
*/
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
/**
* Serialization ID. This class relies on default serialization
* even for the items array, which is default-serialized, even if
* it is empty. Otherwise it could not be declared final, which is
* necessary here.
*/
private static final long serialVersionUID = -817911632652898426L;
/** The queued items */
final Object[] items;
/** items index for next take, poll, peek or remove */
int takeIndex;
/** items index for next put, offer, or add */
int putIndex;
/** Number of elements in the queue */
int count;
/*
* Concurrency control uses the classic two-condition algorithm
* found in any textbook.
*/
/** Main lock guarding all access */
final ReentrantLock lock;
/** Condition for waiting takes */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;
/**
* Shared state for currently active iterators, or null if there
* are known not to be any. Allows queue operations to update
* iterator state.
*/
transient Itrs itrs;
// Internal helper methods
/**
* Circularly decrements array index i.
*/
final int dec(int i) {
return ((i == 0) ? items.length : i) - 1;
}
/**
* Returns item at index i.
*/
@SuppressWarnings("unchecked")
final E itemAt(int i) {
return (E) items[i];
}
/**
* Inserts element at current put position, advances, and signals.
* Call only when holding lock.
*/
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
items[putIndex] = x;
if (++putIndex == items.length) putIndex = 0;
count++;
notEmpty.signal();
}
/**
* Extracts element at current take position, advances, and signals.
* Call only when holding lock.
*/
private E dequeue() {
// assert lock.getHoldCount() == 1;
// assert items[takeIndex] != null;
final Object[] items = this.items;
@SuppressWarnings("unchecked")
E x = (E) items[takeIndex];
items[takeIndex] = null;
if (++takeIndex == items.length) takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
notFull.signal();
return x;
}
/**
* Deletes item at array index removeIndex.
* Utility for remove(Object) and iterator.remove.
* Call only when holding lock.
*/
void removeAt(final int removeIndex) {
// assert lock.getHoldCount() == 1;
// assert items[removeIndex] != null;
// assert removeIndex >= 0 && removeIndex < items.length;
final Object[] items = this.items;
if (removeIndex == takeIndex) {
// removing front item; just advance
items[takeIndex] = null;
if (++takeIndex == items.length) takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
} else {
// an "interior" remove
// slide over all others up through putIndex.
for (int i = removeIndex, putIndex = this.putIndex;;) {
int pred = i;
if (++i == items.length) i = 0;
if (i == putIndex) {
items[pred] = null;
this.putIndex = pred;
break;
}
items[pred] = items[i];
}
count--;
if (itrs != null)
itrs.removedAt(removeIndex);
}
notFull.signal();
}
/**
* Creates an {@code ArrayBlockingQueue} with the given (fixed)
* capacity and default access policy.
*
* @param capacity the capacity of this queue
* @throws IllegalArgumentException if {@code capacity < 1}
*/
public ArrayBlockingQueue(int capacity) {
this(capacity, false);
}
/**
* Creates an {@code ArrayBlockingQueue} with the given (fixed)
* capacity and the specified access policy.
*
* @param capacity the capacity of this queue
* @param fair if {@code true} then queue accesses for threads blocked
* on insertion or removal, are processed in FIFO order;
* if {@code false} the access order is unspecified.
* @throws IllegalArgumentException if {@code capacity < 1}
*/
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new Object[capacity];
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
/**
* Creates an {@code ArrayBlockingQueue} with the given (fixed)
* capacity, the specified access policy and initially containing the
* elements of the given collection,
* added in traversal order of the collection's iterator.
*
* @param capacity the capacity of this queue
* @param fair if {@code true} then queue accesses for threads blocked
* on insertion or removal, are processed in FIFO order;
* if {@code false} the access order is unspecified.
* @param c the collection of elements to initially contain
* @throws IllegalArgumentException if {@code capacity} is less than
* {@code c.size()}, or less than 1.
* @throws NullPointerException if the specified collection or any
* of its elements are null
*/
public ArrayBlockingQueue(int capacity, boolean fair,
Collection<? extends E> c) {
this(capacity, fair);
final ReentrantLock lock = this.lock;
lock.lock(); // Lock only for visibility, not mutual exclusion
try {
int i = 0;
try {
for (E e : c)
items[i++] = Objects.requireNonNull(e);
} catch (ArrayIndexOutOfBoundsException ex) {
throw new IllegalArgumentException();
}
count = i;
putIndex = (i == capacity) ? 0 : i;
} finally {
lock.unlock();
}
}
/**
* Inserts the specified element at the tail of this queue if it is
* possible to do so immediately without exceeding the queue's capacity,
* returning {@code true} upon success and throwing an
* {@code IllegalStateException} if this queue is full.
*
* @param e the element to add
* @return {@code true} (as specified by {@link Collection#add})
* @throws IllegalStateException if this queue is full
* @throws NullPointerException if the specified element is null
*/
public boolean add(E e) {
return super.add(e);
}
/**
* Inserts the specified element at the tail of this queue if it is
* possible to do so immediately without exceeding the queue's capacity,
* returning {@code true} upon success and {@code false} if this queue
* is full. This method is generally preferable to method {@link #add},
* which can fail to insert an element only by throwing an exception.
*
* @throws NullPointerException if the specified element is null
*/
public boolean offer(E e) {
Objects.requireNonNull(e);
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (count == items.length)
return false;
else {
enqueue(e);
return true;
}
} finally {
lock.unlock();
}
}
/**
* Inserts the specified element at the tail of this queue, waiting
* for space to become available if the queue is full.
*
* @throws InterruptedException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public void put(E e) throws InterruptedException {
Objects.requireNonNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await();
enqueue(e);
} finally {
lock.unlock();
}
}
/**
* Inserts the specified element at the tail of this queue, waiting
* up to the specified wait time for space to become available if
* the queue is full.
*
* @throws InterruptedException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
Objects.requireNonNull(e);
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length) {
if (nanos <= 0L)
return false;
nanos = notFull.awaitNanos(nanos);
}
enqueue(e);
return true;
} finally {
lock.unlock();
}
}
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (count == 0) ? null : dequeue();
} finally {
lock.unlock();
}
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0) {
if (nanos <= 0L)
return null;
nanos = notEmpty.awaitNanos(nanos);
}
return dequeue();
} finally {
lock.unlock();
}
}
public E peek() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return itemAt(takeIndex); // null when queue is empty
} finally {
lock.unlock();
}
}
// this doc comment is overridden to remove the reference to collections
// greater in size than Integer.MAX_VALUE
/**
* Returns the number of elements in this queue.
*
* @return the number of elements in this queue
*/
public int size() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
// this doc comment is a modified copy of the inherited doc comment,
// without the reference to unlimited queues.
/**
* Returns the number of additional elements that this queue can ideally
* (in the absence of memory or resource constraints) accept without
* blocking. This is always equal to the initial capacity of this queue
* less the current {@code size} of this queue.
*
* <p>Note that you <em>cannot</em> always tell if an attempt to insert
* an element will succeed by inspecting {@code remainingCapacity}
* because it may be the case that another thread is about to
* insert or remove an element.
*/
public int remainingCapacity() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return items.length - count;
} finally {
lock.unlock();
}
}
/**
* Removes a single instance of the specified element from this queue,
* if it is present. More formally, removes an element {@code e} such
* that {@code o.equals(e)}, if this queue contains one or more such
* elements.
* Returns {@code true} if this queue contained the specified element
* (or equivalently, if this queue changed as a result of the call).
*
* <p>Removal of interior elements in circular array based queues
* is an intrinsically slow and disruptive operation, so should
* be undertaken only in exceptional circumstances, ideally
* only when the queue is known not to be accessible by other
* threads.
*
* @param o element to be removed from this queue, if present
* @return {@code true} if this queue changed as a result of the call
*/
public boolean remove(Object o) {
if (o == null) return false;
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (count > 0) {
final Object[] items = this.items;
final int putIndex = this.putIndex;
int i = takeIndex;
do {
if (o.equals(items[i])) {
removeAt(i);
return true;
}
if (++i == items.length) i = 0;
} while (i != putIndex);
}
return false;
} finally {
lock.unlock();
}
}
/**
* Returns {@code true} if this queue contains the specified element.
* More formally, returns {@code true} if and only if this queue contains
* at least one element {@code e} such that {@code o.equals(e)}.
*
* @param o object to be checked for containment in this queue
* @return {@code true} if this queue contains the specified element
*/
public boolean contains(Object o) {
if (o == null) return false;
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (count > 0) {
final Object[] items = this.items;
final int putIndex = this.putIndex;
int i = takeIndex;
do {
if (o.equals(items[i]))
return true;
if (++i == items.length) i = 0;
} while (i != putIndex);
}
return false;
} finally {
lock.unlock();
}
}
/**
* Returns an array containing all of the elements in this queue, in
* proper sequence.
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this queue. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this queue
*/
public Object[] toArray() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
final Object[] items = this.items;
final int end = takeIndex + count;
final Object[] a = Arrays.copyOfRange(items, takeIndex, end);
if (end != putIndex)
System.arraycopy(items, 0, a, items.length - takeIndex, putIndex);
return a;
} finally {
lock.unlock();
}
}
/**
* Returns an array containing all of the elements in this queue, in
* proper sequence; the runtime type of the returned array is that of
* the specified array. If the queue fits in the specified array, it
* is returned therein. Otherwise, a new array is allocated with the
* runtime type of the specified array and the size of this queue.
*
* <p>If this queue fits in the specified array with room to spare
* (i.e., the array has more elements than this queue), the element in
* the array immediately following the end of the queue is set to
* {@code null}.
*
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
* <p>Suppose {@code x} is a queue known to contain only strings.
* The following code can be used to dump the queue into a newly
* allocated array of {@code String}:
*
* <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
*
* Note that {@code toArray(new Object[0])} is identical in function to
* {@code toArray()}.
*
* @param a the array into which the elements of the queue are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose
* @return an array containing all of the elements in this queue
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this queue
* @throws NullPointerException if the specified array is null
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
final Object[] items = this.items;
final int count = this.count;
final int firstLeg = Math.min(items.length - takeIndex, count);
if (a.length < count) {
a = (T[]) Arrays.copyOfRange(items, takeIndex, takeIndex + count,
a.getClass());
} else {
System.arraycopy(items, takeIndex, a, 0, firstLeg);
if (a.length > count)
a[count] = null;
}
if (firstLeg < count)
System.arraycopy(items, 0, a, firstLeg, putIndex);
return a;
} finally {
lock.unlock();
}
}
public String toString() {
return Helpers.collectionToString(this);
}
/**
* Atomically removes all of the elements from this queue.
* The queue will be empty after this call returns.
*/
public void clear() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
int k = count;
if (k > 0) {
final Object[] items = this.items;
final int putIndex = this.putIndex;
int i = takeIndex;
do {
items[i] = null;
if (++i == items.length) i = 0;
} while (i != putIndex);
takeIndex = putIndex;
count = 0;
if (itrs != null)
itrs.queueIsEmpty();
for (; k > 0 && lock.hasWaiters(notFull); k--)
notFull.signal();
}
} finally {
lock.unlock();
}
}
/**
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
public int drainTo(Collection<? super E> c) {
return drainTo(c, Integer.MAX_VALUE);
}
/**
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
public int drainTo(Collection<? super E> c, int maxElements) {
Objects.requireNonNull(c);
if (c == this)
throw new IllegalArgumentException();
if (maxElements <= 0)
return 0;
final Object[] items = this.items;
final ReentrantLock lock = this.lock;
lock.lock();
try {
int n = Math.min(maxElements, count);
int take = takeIndex;
int i = 0;
try {
while (i < n) {
@SuppressWarnings("unchecked")
E x = (E) items[take];
c.add(x);
items[take] = null;
if (++take == items.length) take = 0;
i++;
}
return n;
} finally {
// Restore invariants even if c.add() threw
if (i > 0) {
count -= i;
takeIndex = take;
if (itrs != null) {
if (count == 0)
itrs.queueIsEmpty();
else if (i > take)
itrs.takeIndexWrapped();
}
for (; i > 0 && lock.hasWaiters(notFull); i--)
notFull.signal();
}
}
} finally {
lock.unlock();
}
}
/**
* Returns an iterator over the elements in this queue in proper sequence.
* The elements will be returned in order from first (head) to last (tail).
*
* <p>The returned iterator is
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* @return an iterator over the elements in this queue in proper sequence
*/
public Iterator<E> iterator() {
return new Itr();
}
/**
* Shared data between iterators and their queue, allowing queue
* modifications to update iterators when elements are removed.
*
* This adds a lot of complexity for the sake of correctly
* handling some uncommon operations, but the combination of
* circular-arrays and supporting interior removes (i.e., those
* not at head) would cause iterators to sometimes lose their
* places and/or (re)report elements they shouldn't. To avoid
* this, when a queue has one or more iterators, it keeps iterator
* state consistent by:
*
* (1) keeping track of the number of "cycles", that is, the
* number of times takeIndex has wrapped around to 0.
* (2) notifying all iterators via the callback removedAt whenever
* an interior element is removed (and thus other elements may
* be shifted).
*
* These suffice to eliminate iterator inconsistencies, but
* unfortunately add the secondary responsibility of maintaining
* the list of iterators. We track all active iterators in a
* simple linked list (accessed only when the queue's lock is
* held) of weak references to Itr. The list is cleaned up using
* 3 different mechanisms:
*
* (1) Whenever a new iterator is created, do some O(1) checking for
* stale list elements.
*
* (2) Whenever takeIndex wraps around to 0, check for iterators
* that have been unused for more than one wrap-around cycle.
*
* (3) Whenever the queue becomes empty, all iterators are notified
* and this entire data structure is discarded.
*
* So in addition to the removedAt callback that is necessary for
* correctness, iterators have the shutdown and takeIndexWrapped
* callbacks that help remove stale iterators from the list.
*
* Whenever a list element is examined, it is expunged if either
* the GC has determined that the iterator is discarded, or if the
* iterator reports that it is "detached" (does not need any
* further state updates). Overhead is maximal when takeIndex
* never advances, iterators are discarded before they are
* exhausted, and all removals are interior removes, in which case
* all stale iterators are discovered by the GC. But even in this
* case we don't increase the amortized complexity.
*
* Care must be taken to keep list sweeping methods from
* reentrantly invoking another such method, causing subtle
* corruption bugs.
*/
class Itrs {
/**
* Node in a linked list of weak iterator references.
*/
private class Node extends WeakReference<Itr> {
Node next;
Node(Itr iterator, Node next) {
super(iterator);
this.next = next;
}
}
/** Incremented whenever takeIndex wraps around to 0 */
int cycles;
/** Linked list of weak iterator references */
private Node head;
/** Used to expunge stale iterators */
private Node sweeper;
private static final int SHORT_SWEEP_PROBES = 4;
private static final int LONG_SWEEP_PROBES = 16;
Itrs(Itr initial) {
register(initial);
}
/**
* Sweeps itrs, looking for and expunging stale iterators.
* If at least one was found, tries harder to find more.
* Called only from iterating thread.
*
* @param tryHarder whether to start in try-harder mode, because
* there is known to be at least one iterator to collect
*/
void doSomeSweeping(boolean tryHarder) {
// assert lock.getHoldCount() == 1;
// assert head != null;
int probes = tryHarder ? LONG_SWEEP_PROBES : SHORT_SWEEP_PROBES;
Node o, p;
final Node sweeper = this.sweeper;
boolean passedGo; // to limit search to one full sweep
if (sweeper == null) {
o = null;
p = head;
passedGo = true;
} else {
o = sweeper;
p = o.next;
passedGo = false;
}
for (; probes > 0; probes--) {
if (p == null) {
if (passedGo)
break;
o = null;
p = head;
passedGo = true;
}
final Itr it = p.get();
final Node next = p.next;
if (it == null || it.isDetached()) {
// found a discarded/exhausted iterator
probes = LONG_SWEEP_PROBES; // "try harder"
// unlink p
p.clear();
p.next = null;
if (o == null) {
head = next;
if (next == null) {
// We've run out of iterators to track; retire
itrs = null;
return;
}
}
else
o.next = next;
} else {
o = p;
}
p = next;
}
this.sweeper = (p == null) ? null : o;
}
/**
* Adds a new iterator to the linked list of tracked iterators.
*/
void register(Itr itr) {
// assert lock.getHoldCount() == 1;
head = new Node(itr, head);
}
/**
* Called whenever takeIndex wraps around to 0.
*
* Notifies all iterators, and expunges any that are now stale.
*/
void takeIndexWrapped() {
// assert lock.getHoldCount() == 1;
cycles++;
for (Node o = null, p = head; p != null;) {
final Itr it = p.get();
final Node next = p.next;
if (it == null || it.takeIndexWrapped()) {
// unlink p
// assert it == null || it.isDetached();
p.clear();
p.next = null;
if (o == null)
head = next;
else
o.next = next;
} else {
o = p;
}
p = next;
}
if (head == null) // no more iterators to track
itrs = null;
}
/**
* Called whenever an interior remove (not at takeIndex) occurred.
*
* Notifies all iterators, and expunges any that are now stale.
*/
void removedAt(int removedIndex) {
for (Node o = null, p = head; p != null;) {
final Itr it = p.get();
final Node next = p.next;
if (it == null || it.removedAt(removedIndex)) {
// unlink p
// assert it == null || it.isDetached();
p.clear();
p.next = null;
if (o == null)
head = next;
else
o.next = next;
} else {
o = p;
}
p = next;
}
if (head == null) // no more iterators to track
itrs = null;
}
/**
* Called whenever the queue becomes empty.
*
* Notifies all active iterators that the queue is empty,
* clears all weak refs, and unlinks the itrs datastructure.
*/
void queueIsEmpty() {
// assert lock.getHoldCount() == 1;
for (Node p = head; p != null; p = p.next) {
Itr it = p.get();
if (it != null) {
p.clear();
it.shutdown();
}
}
head = null;
itrs = null;
}
/**
* Called whenever an element has been dequeued (at takeIndex).
*/
void elementDequeued() {
// assert lock.getHoldCount() == 1;
if (count == 0)
queueIsEmpty();
else if (takeIndex == 0)
takeIndexWrapped();
}
}
/**
* Iterator for ArrayBlockingQueue.
*
* To maintain weak consistency with respect to puts and takes, we
* read ahead one slot, so as to not report hasNext true but then
* not have an element to return.
*
* We switch into "detached" mode (allowing prompt unlinking from
* itrs without help from the GC) when all indices are negative, or
* when hasNext returns false for the first time. This allows the
* iterator to track concurrent updates completely accurately,
* except for the corner case of the user calling Iterator.remove()
* after hasNext() returned false. Even in this case, we ensure
* that we don't remove the wrong element by keeping track of the
* expected element to remove, in lastItem. Yes, we may fail to
* remove lastItem from the queue if it moved due to an interleaved
* interior remove while in detached mode.
*/
private class Itr implements Iterator<E> {
/** Index to look for new nextItem; NONE at end */
private int cursor;
/** Element to be returned by next call to next(); null if none */
private E nextItem;
/** Index of nextItem; NONE if none, REMOVED if removed elsewhere */
private int nextIndex;
/** Last element returned; null if none or not detached. */
private E lastItem;
/** Index of lastItem, NONE if none, REMOVED if removed elsewhere */
private int lastRet;
/** Previous value of takeIndex, or DETACHED when detached */
private int prevTakeIndex;
/** Previous value of iters.cycles */
private int prevCycles;
/** Special index value indicating "not available" or "undefined" */
private static final int NONE = -1;
/**
* Special index value indicating "removed elsewhere", that is,
* removed by some operation other than a call to this.remove().
*/
private static final int REMOVED = -2;
/** Special value for prevTakeIndex indicating "detached mode" */
private static final int DETACHED = -3;
Itr() {
// assert lock.getHoldCount() == 0;
lastRet = NONE;
final ReentrantLock lock = ArrayBlockingQueue.this.lock;
lock.lock();
try {
if (count == 0) {
// assert itrs == null;
cursor = NONE;
nextIndex = NONE;
prevTakeIndex = DETACHED;
} else {
final int takeIndex = ArrayBlockingQueue.this.takeIndex;
prevTakeIndex = takeIndex;
nextItem = itemAt(nextIndex = takeIndex);
cursor = incCursor(takeIndex);
if (itrs == null) {
itrs = new Itrs(this);
} else {
itrs.register(this); // in this order
itrs.doSomeSweeping(false);
}
prevCycles = itrs.cycles;
// assert takeIndex >= 0;
// assert prevTakeIndex == takeIndex;
// assert nextIndex >= 0;
// assert nextItem != null;
}
} finally {
lock.unlock();
}
}
boolean isDetached() {
// assert lock.getHoldCount() == 1;
return prevTakeIndex < 0;
}
private int incCursor(int index) {
// assert lock.getHoldCount() == 1;
if (++index == items.length) index = 0;
if (index == putIndex) index = NONE;
return index;
}
/**
* Returns true if index is invalidated by the given number of
* dequeues, starting from prevTakeIndex.
*/
private boolean invalidated(int index, int prevTakeIndex,
long dequeues, int length) {
if (index < 0)
return false;
int distance = index - prevTakeIndex;
if (distance < 0)
distance += length;
return dequeues > distance;
}
/**
* Adjusts indices to incorporate all dequeues since the last
* operation on this iterator. Call only from iterating thread.
*/
private void incorporateDequeues() {
// assert lock.getHoldCount() == 1;
// assert itrs != null;
// assert !isDetached();
// assert count > 0;
final int cycles = itrs.cycles;
final int takeIndex = ArrayBlockingQueue.this.takeIndex;
final int prevCycles = this.prevCycles;
final int prevTakeIndex = this.prevTakeIndex;
if (cycles != prevCycles || takeIndex != prevTakeIndex) {
final int len = items.length;
// how far takeIndex has advanced since the previous
// operation of this iterator
long dequeues = (cycles - prevCycles) * len
+ (takeIndex - prevTakeIndex);
// Check indices for invalidation
if (invalidated(lastRet, prevTakeIndex, dequeues, len))
lastRet = REMOVED;
if (invalidated(nextIndex, prevTakeIndex, dequeues, len))
nextIndex = REMOVED;
if (invalidated(cursor, prevTakeIndex, dequeues, len))
cursor = takeIndex;
if (cursor < 0 && nextIndex < 0 && lastRet < 0)
detach();
else {
this.prevCycles = cycles;
this.prevTakeIndex = takeIndex;
}
}
}
/**
* Called when itrs should stop tracking this iterator, either
* because there are no more indices to update (cursor < 0 &&
* nextIndex < 0 && lastRet < 0) or as a special exception, when
* lastRet >= 0, because hasNext() is about to return false for the
* first time. Call only from iterating thread.
*/
private void detach() {
// Switch to detached mode
// assert lock.getHoldCount() == 1;
// assert cursor == NONE;
// assert nextIndex < 0;
// assert lastRet < 0 || nextItem == null;
// assert lastRet < 0 ^ lastItem != null;
if (prevTakeIndex >= 0) {
// assert itrs != null;
prevTakeIndex = DETACHED;
// try to unlink from itrs (but not too hard)
itrs.doSomeSweeping(true);
}
}
/**
* For performance reasons, we would like not to acquire a lock in
* hasNext in the common case. To allow for this, we only access
* fields (i.e. nextItem) that are not modified by update operations
* triggered by queue modifications.
*/
public boolean hasNext() {
// assert lock.getHoldCount() == 0;
if (nextItem != null)
return true;
noNext();
return false;
}
private void noNext() {
final ReentrantLock lock = ArrayBlockingQueue.this.lock;
lock.lock();
try {
// assert cursor == NONE;
// assert nextIndex == NONE;
if (!isDetached()) {
// assert lastRet >= 0;
incorporateDequeues(); // might update lastRet
if (lastRet >= 0) {
lastItem = itemAt(lastRet);
// assert lastItem != null;
detach();
}
}
// assert isDetached();
// assert lastRet < 0 ^ lastItem != null;
} finally {
lock.unlock();
}
}
public E next() {
// assert lock.getHoldCount() == 0;
final E x = nextItem;
if (x == null)
throw new NoSuchElementException();
final ReentrantLock lock = ArrayBlockingQueue.this.lock;
lock.lock();
try {
if (!isDetached())
incorporateDequeues();
// assert nextIndex != NONE;
// assert lastItem == null;
lastRet = nextIndex;
final int cursor = this.cursor;
if (cursor >= 0) {
nextItem = itemAt(nextIndex = cursor);
// assert nextItem != null;
this.cursor = incCursor(cursor);
} else {
nextIndex = NONE;
nextItem = null;
}
} finally {
lock.unlock();
}
return x;
}
public void remove() {
// assert lock.getHoldCount() == 0;
final ReentrantLock lock = ArrayBlockingQueue.this.lock;
lock.lock();
try {
if (!isDetached())
incorporateDequeues(); // might update lastRet or detach
final int lastRet = this.lastRet;
this.lastRet = NONE;
if (lastRet >= 0) {
if (!isDetached())
removeAt(lastRet);
else {
final E lastItem = this.lastItem;
// assert lastItem != null;
this.lastItem = null;
if (itemAt(lastRet) == lastItem)
removeAt(lastRet);
}
} else if (lastRet == NONE)
throw new IllegalStateException();
// else lastRet == REMOVED and the last returned element was
// previously asynchronously removed via an operation other
// than this.remove(), so nothing to do.
if (cursor < 0 && nextIndex < 0)
detach();
} finally {
lock.unlock();
// assert lastRet == NONE;
// assert lastItem == null;
}
}
/**
* Called to notify the iterator that the queue is empty, or that it
* has fallen hopelessly behind, so that it should abandon any
* further iteration, except possibly to return one more element
* from next(), as promised by returning true from hasNext().
*/
void shutdown() {
// assert lock.getHoldCount() == 1;
cursor = NONE;
if (nextIndex >= 0)
nextIndex = REMOVED;
if (lastRet >= 0) {
lastRet = REMOVED;
lastItem = null;
}
prevTakeIndex = DETACHED;
// Don't set nextItem to null because we must continue to be
// able to return it on next().
//
// Caller will unlink from itrs when convenient.
}
private int distance(int index, int prevTakeIndex, int length) {
int distance = index - prevTakeIndex;
if (distance < 0)
distance += length;
return distance;
}
/**
* Called whenever an interior remove (not at takeIndex) occurred.
*
* @return true if this iterator should be unlinked from itrs
*/
boolean removedAt(int removedIndex) {
// assert lock.getHoldCount() == 1;
if (isDetached())
return true;
final int takeIndex = ArrayBlockingQueue.this.takeIndex;
final int prevTakeIndex = this.prevTakeIndex;
final int len = items.length;
// distance from prevTakeIndex to removedIndex
final int removedDistance =
len * (itrs.cycles - this.prevCycles
+ ((removedIndex < takeIndex) ? 1 : 0))
+ (removedIndex - prevTakeIndex);
// assert itrs.cycles - this.prevCycles >= 0;
// assert itrs.cycles - this.prevCycles <= 1;
// assert removedDistance > 0;
// assert removedIndex != takeIndex;
int cursor = this.cursor;
if (cursor >= 0) {
int x = distance(cursor, prevTakeIndex, len);
if (x == removedDistance) {
if (cursor == putIndex)
this.cursor = cursor = NONE;
}
else if (x > removedDistance) {
// assert cursor != prevTakeIndex;
this.cursor = cursor = dec(cursor);
}
}
int lastRet = this.lastRet;
if (lastRet >= 0) {
int x = distance(lastRet, prevTakeIndex, len);
if (x == removedDistance)
this.lastRet = lastRet = REMOVED;
else if (x > removedDistance)
this.lastRet = lastRet = dec(lastRet);
}
int nextIndex = this.nextIndex;
if (nextIndex >= 0) {
int x = distance(nextIndex, prevTakeIndex, len);
if (x == removedDistance)
this.nextIndex = nextIndex = REMOVED;
else if (x > removedDistance)
this.nextIndex = nextIndex = dec(nextIndex);
}
if (cursor < 0 && nextIndex < 0 && lastRet < 0) {
this.prevTakeIndex = DETACHED;
return true;
}
return false;
}
/**
* Called whenever takeIndex wraps around to zero.
*
* @return true if this iterator should be unlinked from itrs
*/
boolean takeIndexWrapped() {
// assert lock.getHoldCount() == 1;
if (isDetached())
return true;
if (itrs.cycles - prevCycles > 1) {
// All the elements that existed at the time of the last
// operation are gone, so abandon further iteration.
shutdown();
return true;
}
return false;
}
// /** Uncomment for debugging. */
// public String toString() {
// return ("cursor=" + cursor + " " +
// "nextIndex=" + nextIndex + " " +
// "lastRet=" + lastRet + " " +
// "nextItem=" + nextItem + " " +
// "lastItem=" + lastItem + " " +
// "prevCycles=" + prevCycles + " " +
// "prevTakeIndex=" + prevTakeIndex + " " +
// "size()=" + size() + " " +
// "remainingCapacity()=" + remainingCapacity());
// }
}
/**
* Returns a {@link Spliterator} over the elements in this queue.
*
* <p>The returned spliterator is
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
* {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
*
* @implNote
* The {@code Spliterator} implements {@code trySplit} to permit limited
* parallelism.
*
* @return a {@code Spliterator} over the elements in this queue
* @since 1.8
*/
public Spliterator<E> spliterator() {
return Spliterators.spliterator
(this, (Spliterator.ORDERED |
Spliterator.NONNULL |
Spliterator.CONCURRENT));
}
}
| 49,380
|
Java
|
.java
| 1,273
| 28.018853
| 82
| 0.54777
|
google/desugar_jdk_libs
| 347
| 25
| 0
|
GPL-2.0
|
9/4/2024, 7:06:38 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 49,380
|
266,804
|
Logging.java
|
openjdk-mirror_jdk7u-jdk/src/share/classes/java/util/logging/Logging.java
|
/*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util.logging;
import java.util.Enumeration;
import java.util.List;
import java.util.ArrayList;
/**
* Logging is the implementation class of LoggingMXBean.
*
* The <tt>LoggingMXBean</tt> interface provides a standard
* method for management access to the individual
* java.util.Logger objects available at runtime.
*
* @author Ron Mann
* @author Mandy Chung
* @since 1.5
*
* @see javax.management
* @see java.util.Logger
* @see java.util.LogManager
*/
class Logging implements LoggingMXBean {
private static LogManager logManager = LogManager.getLogManager();
/** Constructor of Logging which is the implementation class
* of LoggingMXBean.
*/
Logging() {
}
public List<String> getLoggerNames() {
Enumeration loggers = logManager.getLoggerNames();
ArrayList<String> array = new ArrayList<>();
for (; loggers.hasMoreElements();) {
array.add((String) loggers.nextElement());
}
return array;
}
private static String EMPTY_STRING = "";
public String getLoggerLevel(String loggerName) {
Logger l = logManager.getLogger(loggerName);
if (l == null) {
return null;
}
Level level = l.getLevel();
if (level == null) {
return EMPTY_STRING;
} else {
return level.getName();
}
}
public void setLoggerLevel(String loggerName, String levelName) {
if (loggerName == null) {
throw new NullPointerException("loggerName is null");
}
Logger logger = logManager.getLogger(loggerName);
if (logger == null) {
throw new IllegalArgumentException("Logger " + loggerName +
"does not exist");
}
Level level = null;
if (levelName != null) {
// parse will throw IAE if logLevel is invalid
level = Level.parse(levelName);
}
logger.setLevel(level);
}
public String getParentLoggerName( String loggerName ) {
Logger l = logManager.getLogger( loggerName );
if (l == null) {
return null;
}
Logger p = l.getParent();
if (p == null) {
// root logger
return EMPTY_STRING;
} else {
return p.getName();
}
}
}
| 3,571
|
Java
|
.java
| 101
| 29.415842
| 79
| 0.665316
|
openjdk-mirror/jdk7u-jdk
| 525
| 429
| 6
|
GPL-2.0
|
9/4/2024, 7:05:59 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 3,571
|
5,116,338
|
ImportVmParameters.java
|
jtux270_translate/ovirt/3.6_source/backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/action/ImportVmParameters.java
|
package org.ovirt.engine.core.common.action;
import java.io.Serializable;
import java.util.Map;
import javax.validation.Valid;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.core.compat.Guid;
public class ImportVmParameters extends VmOperationParameterBase implements Serializable {
private static final long serialVersionUID = -6514416097090370831L;
@Valid
private VM vm;
private Guid sourceDomainId;
private Guid destDomainId;
private Guid vdsGroupId;
private Map<Guid, Disk> diskMap;
private Guid storagePoolId;
private Map<Guid, Guid> imageToDestinationDomainMap;
private boolean imagesExistOnTargetStorageDomain;
private Guid cpuProfileId;
private boolean copyCollapse;
private boolean forceOverride;
private Guid containerId;
private Guid storageDomainId;
private boolean importAsNewEntity;
public ImportVmParameters() {
sourceDomainId = Guid.Empty;
destDomainId = Guid.Empty;
}
public ImportVmParameters(VM vm, Guid sourceStorageDomainId, Guid destStorageDomainId, Guid storagePoolId,
Guid vdsGroupId) {
super(vm.getId());
containerId = vm.getId();
sourceDomainId = sourceStorageDomainId;
destDomainId = destStorageDomainId;
setVm(vm);
setStorageDomainId(destStorageDomainId);
this.setStoragePoolId(storagePoolId);
setVdsGroupId(vdsGroupId);
}
public VM getVm() {
return vm;
}
public void setVm(VM vm) {
this.vm = vm;
}
public Guid getSourceDomainId() {
return sourceDomainId;
}
public Guid getDestDomainId() {
return destDomainId;
}
public Guid getVdsGroupId() {
return vdsGroupId;
}
public void setVdsGroupId(Guid vdsGroupId) {
this.vdsGroupId = vdsGroupId;
}
public void setDestDomainId(Guid destDomainId) {
this.destDomainId = destDomainId;
}
public void setSourceDomainId(Guid sourceDomainId) {
this.sourceDomainId = sourceDomainId;
}
public Map<Guid, Disk> getDiskMap() {
return diskMap;
}
public void setDiskMap(Map<Guid, Disk> diskMap) {
this.diskMap = diskMap;
}
public Guid getStoragePoolId() {
return storagePoolId;
}
public void setStoragePoolId(Guid storagePoolId) {
this.storagePoolId = storagePoolId;
}
public Guid getStorageDomainId() {
return storageDomainId;
}
public void setStorageDomainId(Guid storageDomainId) {
this.storageDomainId = storageDomainId;
}
public Map<Guid, Guid> getImageToDestinationDomainMap() {
return imageToDestinationDomainMap;
}
public void setImageToDestinationDomainMap(Map<Guid, Guid> imageToDestinationDomainMap) {
this.imageToDestinationDomainMap = imageToDestinationDomainMap;
}
public boolean isImagesExistOnTargetStorageDomain() {
return imagesExistOnTargetStorageDomain;
}
public void setImagesExistOnTargetStorageDomain(boolean imagesExistOnTargetStorageDomain) {
this.imagesExistOnTargetStorageDomain = imagesExistOnTargetStorageDomain;
}
public Guid getCpuProfileId() {
return cpuProfileId;
}
public void setCpuProfileId(Guid cpuProfileId) {
this.cpuProfileId = cpuProfileId;
}
public boolean getCopyCollapse() {
return copyCollapse;
}
public void setCopyCollapse(boolean copyCollapse) {
this.copyCollapse = copyCollapse;
}
public boolean getForceOverride() {
return forceOverride;
}
public void setForceOverride(boolean forceOverride) {
this.forceOverride = forceOverride;
}
public Guid getContainerId() {
return containerId;
}
public void setContainerId(Guid containerId) {
this.containerId = containerId;
}
public boolean isImportAsNewEntity() {
return importAsNewEntity;
}
public void setImportAsNewEntity(boolean importAsNewEntity) {
this.importAsNewEntity = importAsNewEntity;
}
}
| 4,207
|
Java
|
.java
| 124
| 27.629032
| 110
| 0.722195
|
jtux270/translate
| 1
| 0
| 23
|
GPL-3.0
|
9/5/2024, 12:41:44 AM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 4,207
|
4,049,477
|
VectorSumCombiner.java
|
bharcode_MachineLearning/CustomMahout/core/src/main/java/org/apache/mahout/common/mapreduce/VectorSumCombiner.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.common.mapreduce;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.mahout.math.VectorWritable;
import org.apache.mahout.math.hadoop.similarity.cooccurrence.Vectors;
import java.io.IOException;
public class VectorSumCombiner
extends Reducer<WritableComparable<?>, VectorWritable, WritableComparable<?>, VectorWritable> {
private final VectorWritable result = new VectorWritable();
@Override
protected void reduce(WritableComparable<?> key, Iterable<VectorWritable> values, Context ctx)
throws IOException, InterruptedException {
result.set(Vectors.sum(values.iterator()));
ctx.write(key, result);
}
}
| 1,537
|
Java
|
.java
| 32
| 45.09375
| 101
| 0.781333
|
bharcode/MachineLearning
| 2
| 5
| 0
|
GPL-2.0
|
9/5/2024, 12:01:05 AM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 1,537
|
1,138,695
|
XResources_fr.java
|
srnsw_xena/plugins/office/ext/src/xalan-j_2_7_1/src/org/apache/xml/utils/res/XResources_fr.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
package org.apache.xml.utils.res;
//
// LangResources_fr.properties
//
/**
* The French resource bundle.
* @xsl.usage internal
*/
public class XResources_fr extends XResourceBundle
{
/**
* Get the association list.
*
* @return The association list.
*/
public Object[][] getContents()
{
return new Object[][]
{
{ "ui_language", "fr" }, { "help_language", "fr" }, { "language", "fr" },
{ "alphabet", new CharArrayWrapper(
new char[]{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z' }) },
{ "tradAlphabet", new CharArrayWrapper(
new char[]{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z' }) },
//language orientation
{ "orientation", "LeftToRight" },
//language numbering
{ "numbering", "additive" },
// largest numerical value
//{"MaxNumericalValue", new Integer()},
//These would not be used for EN. Only used for traditional numbering
//{"numberGroups", new int[]{10,1}},
//These only used for mutiplicative-additive numbering
//{"multiplier", "10"},
//{"multiplierChar", "M"},
//{"digits", new char[]{'a','b','c','d','e','f','g','h','i'}},
//{"digits", new char[]{0x10D0,0x10D1,0x10D2,0x10D3,0x10D4,0x10D5,0x10D6,0x10D7,0x10D8}},
//{"tens", new char[]{0x10D9,0x10DA,0x10DB,0x10DC,0x10DD,0x10DE,0x10DF,0x10E0,0x10E1}},
//hundreds, etc...
//{"tables", new String[]{"tens", "digits"}}
};
}
}
| 2,552
|
Java
|
.java
| 67
| 32.656716
| 94
| 0.586332
|
srnsw/xena
| 38
| 9
| 0
|
GPL-3.0
|
9/4/2024, 7:16:25 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 2,552
|
108,578
|
Connection.java
|
guang19_framework-learning/tomcat9.0-source/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/test/driver/Connection.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.jdbc.test.driver;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import org.apache.tomcat.jdbc.pool.PooledConnection;
public class Connection implements java.sql.Connection {
Properties info;
public Connection(Properties info) {
this.info = info;
}
public String getUsername() {
return info.getProperty(PooledConnection.PROP_USER);
}
public String getPassword() {
return info.getProperty(PooledConnection.PROP_PASSWORD);
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public void close() throws SQLException {
Driver.disconnectCount.incrementAndGet();
}
@Override
public void commit() throws SQLException {
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return null;
}
@Override
public Blob createBlob() throws SQLException {
return null;
}
@Override
public Clob createClob() throws SQLException {
return null;
}
@Override
public NClob createNClob() throws SQLException {
return null;
}
@Override
public SQLXML createSQLXML() throws SQLException {
return null;
}
@Override
public Statement createStatement() throws SQLException {
return new org.apache.tomcat.jdbc.test.driver.Statement();
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return new org.apache.tomcat.jdbc.test.driver.Statement();
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return new org.apache.tomcat.jdbc.test.driver.Statement();
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return null;
}
@Override
public boolean getAutoCommit() throws SQLException {
return false;
}
@Override
public String getCatalog() throws SQLException {
return null;
}
@Override
public Properties getClientInfo() throws SQLException {
return null;
}
@Override
public String getClientInfo(String name) throws SQLException {
return null;
}
@Override
public int getHoldability() throws SQLException {
return 0;
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
return null;
}
@Override
public int getTransactionIsolation() throws SQLException {
return 0;
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return null;
}
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public boolean isClosed() throws SQLException {
return false;
}
@Override
public boolean isReadOnly() throws SQLException {
return false;
}
@Override
public boolean isValid(int timeout) throws SQLException {
return false;
}
@Override
public String nativeSQL(String sql) throws SQLException {
return null;
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
return new org.apache.tomcat.jdbc.test.driver.Statement();
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return new org.apache.tomcat.jdbc.test.driver.Statement();
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return new org.apache.tomcat.jdbc.test.driver.Statement();
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return new org.apache.tomcat.jdbc.test.driver.Statement();
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return new org.apache.tomcat.jdbc.test.driver.Statement();
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return new org.apache.tomcat.jdbc.test.driver.Statement();
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return new org.apache.tomcat.jdbc.test.driver.Statement();
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return new org.apache.tomcat.jdbc.test.driver.Statement();
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return new org.apache.tomcat.jdbc.test.driver.Statement();
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
}
@Override
public void rollback() throws SQLException {
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
}
@Override
public void setCatalog(String catalog) throws SQLException {
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
}
@Override
public void setHoldability(int holdability) throws SQLException {
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
}
@Override
public Savepoint setSavepoint() throws SQLException {
return null;
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
return null;
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public void setSchema(String schema) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public String getSchema() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void abort(Executor executor) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getNetworkTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
}
| 8,478
|
Java
|
.java
| 252
| 28.170635
| 150
| 0.723829
|
guang19/framework-learning
| 1,174
| 238
| 8
|
GPL-3.0
|
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 8,478
|
3,137,681
|
XmlHelper.java
|
crypto-coder_open-cyclos/src/nl/strohalm/cyclos/utils/XmlHelper.java
|
/*
This file is part of Cyclos (www.cyclos.org).
A project of the Social Trade Organisation (www.socialtrade.org).
Cyclos 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.
Cyclos 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 Cyclos; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package nl.strohalm.cyclos.utils;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class XmlHelper {
/**
* Removes all child nodes from the given element
*/
public static void clear(final Element element) {
if (element == null) {
return;
}
Node node;
while ((node = element.getFirstChild()) != null) {
element.removeChild(node);
}
}
/**
* Returns a list of children (class Element) with the given tag name
*/
public static List<Element> getChilden(final Element element, final String tagName) {
final List<Element> children = new ArrayList<Element>();
final NodeList nodes = element.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
final Node item = nodes.item(i);
if (!(item instanceof Element)) {
continue;
}
final Element elem = (Element) item;
if (tagName.equals(elem.getTagName())) {
children.add(elem);
}
}
return children;
}
/**
* Reads the DOM Document from an input stream
*/
public static Document readDocument(final InputStream in) {
return readDocument(new InputSource(in));
}
/**
* Reads the DOM Document from a XML string
*/
public static Document readDocument(final String xml) {
return readDocument(new InputSource(new StringReader(xml)));
}
/**
* Returns the content of the given node as string
*/
public static String toString(final Node node) {
final StringWriter out = new StringWriter();
write(node, new StreamResult(out));
return out.toString();
}
/**
* Writes the content of the given node into the given stream
*/
public static void writeNode(final Node node, final OutputStream out) {
write(node, new StreamResult(out));
}
private static Document readDocument(final InputSource inputSource) {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder;
try {
documentBuilder = factory.newDocumentBuilder();
} catch (final ParserConfigurationException e) {
throw new RuntimeException("Error creating the document builder", e);
}
try {
return documentBuilder.parse(inputSource);
} catch (final Exception e) {
throw new RuntimeException("Error parsing xml file", e);
}
}
private static void write(final Node node, final Result result) {
try {
// Prepare the DOM document for writing
final Source source = new DOMSource(node);
// Write the DOM document to the file
final Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
} catch (final TransformerConfigurationException e) {
} catch (final TransformerException e) {
}
}
}
| 4,687
|
Java
|
.java
| 121
| 32.115702
| 90
| 0.687266
|
crypto-coder/open-cyclos
| 4
| 9
| 0
|
GPL-2.0
|
9/4/2024, 10:59:44 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 4,687
|
1,140,208
|
Eval.java
|
srnsw_xena/plugins/office/ext/src/poi-3.2-FINAL/src/java/org/apache/poi/hssf/record/formula/eval/Eval.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created on May 8, 2005
*
*/
package org.apache.poi.hssf.record.formula.eval;
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*
*/
public interface Eval {
}
| 977
|
Java
|
.java
| 27
| 34.814815
| 74
| 0.765823
|
srnsw/xena
| 38
| 9
| 0
|
GPL-3.0
|
9/4/2024, 7:16:25 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 977
|
377,790
|
ImageViewTargetFactory.java
|
mozilla-mobile_FirefoxLite/third_party/glide/library/src/main/java/com/bumptech/glide/request/target/ImageViewTargetFactory.java
|
package com.bumptech.glide.request.target;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
/**
* A factory responsible for producing the correct type of
* {@link com.bumptech.glide.request.target.Target} for a given {@link android.view.View} subclass.
*/
public class ImageViewTargetFactory {
@SuppressWarnings("unchecked")
public <Z> Target<Z> buildTarget(ImageView view, Class<Z> clazz) {
if (Bitmap.class.equals(clazz)) {
return (Target<Z>) new BitmapImageViewTarget(view);
} else if (Drawable.class.isAssignableFrom(clazz)) {
return (Target<Z>) new DrawableImageViewTarget(view);
} else {
throw new IllegalArgumentException(
"Unhandled class: " + clazz + ", try .as*(Class).transcode(ResourceTranscoder)");
}
}
}
| 833
|
Java
|
.java
| 21
| 36
| 99
| 0.737948
|
mozilla-mobile/FirefoxLite
| 282
| 95
| 0
|
MPL-2.0
|
9/4/2024, 7:06:52 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 833
|
1,843,861
|
BlockNode.java
|
TominoCZ_FancyBlockParticles/src_1.12.x/main/java/com/TominoCZ/FBP/node/BlockNode.java
|
package com.TominoCZ.FBP.node;
import com.TominoCZ.FBP.particle.FBPParticleBlock;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
public class BlockNode
{
public IBlockState state;
public Block originalBlock;
public int meta;
public FBPParticleBlock particle;
public BlockNode(IBlockState s, FBPParticleBlock p)
{
particle = p;
state = s;
originalBlock = s.getBlock();
meta = originalBlock.getMetaFromState(s);
}
}
| 490
|
Java
|
.java
| 18
| 23.833333
| 53
| 0.779221
|
TominoCZ/FancyBlockParticles
| 18
| 8
| 53
|
GPL-3.0
|
9/4/2024, 8:20:48 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 490
|
5,031,898
|
ProgressLoggerFactory.java
|
cams7_gradle-samples/plugin/core/src/main/groovy/org/gradle/logging/ProgressLoggerFactory.java
|
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.logging;
import org.gradle.TaskExecutionLogger;
public interface ProgressLoggerFactory {
/**
* Creates a new long-running operation which has not been started.
*
* @param loggerCategory The logger category.
* @return The progress logger for the operation.
*/
ProgressLogger newOperation(String loggerCategory);
/**
* Creates a new long-running operation which has not been started.
*
* @param loggerCategory The logger category.
* @return The progress logger for the operation.
*/
ProgressLogger newOperation(Class loggerCategory);
ProgressLogger newOperation(Class<TaskExecutionLogger> taskExecutionLoggerClass, ProgressLogger parent);
}
| 1,349
|
Java
|
.java
| 34
| 36.058824
| 108
| 0.753435
|
cams7/gradle-samples
| 1
| 0
| 0
|
GPL-2.0
|
9/5/2024, 12:39:20 AM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 1,349
|
3,603,280
|
XMLWriter.java
|
fetorres_autoML-multiData/arx/arxUI/src/org/deidentifier/arx/gui/worker/io/XMLWriter.java
|
/*
* ARX: Powerful Data Anonymization
* Copyright 2012 - 2016 Fabian Prasser, Florian Kohlmayer and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.deidentifier.arx.gui.worker.io;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Stack;
import org.apache.commons.lang.StringEscapeUtils;
import org.deidentifier.arx.ARXLattice.ARXNode;
import org.deidentifier.arx.ARXLattice.Anonymity;
/**
* A writer for XML documents that can handle common objects from the ARX model.
*
* @author Fabian Prasser
*/
public class XMLWriter {
/** The current prefix for indentation. */
private StringBuilder prefix = new StringBuilder();
/** A backing string builder. */
private StringBuilder sBuilder = null;
/** A backing file builder. */
private FileBuilder fBuilder = null;
/** The current stack of nested elements. */
private Stack<String> elements = new Stack<String>();
/**
* Creates a new writer backed by a StringBuilder.
*
* @throws IOException
*/
public XMLWriter() throws IOException{
this.sBuilder = new StringBuilder();
}
/**
* Creates a new writer backed by the given FileBuilder.
*
* @param builder
* @throws IOException
*/
public XMLWriter(FileBuilder builder) throws IOException{
this.fBuilder = builder;
}
/**
* Intend the document.
*
* @param element
* @throws IOException
*/
public void indent(String element) throws IOException{
elements.push(element);
this.append(prefix.toString());
this.append("<"); //$NON-NLS-1$
this.append(element);
this.append(">\n"); //$NON-NLS-1$
this.prefix.append("\t"); //$NON-NLS-1$
}
/**
* Intend the document.
*
* @param element
* @param attribute
* @param value
* @throws IOException
*/
public void indent(String element, String attribute, int value) throws IOException{
elements.push(element);
this.append(prefix.toString());
this.append("<"); //$NON-NLS-1$
this.append(element);
this.append(" "); //$NON-NLS-1$
this.append(attribute);
this.append("=\""); //$NON-NLS-1$
this.append(String.valueOf(value));
this.append("\""); //$NON-NLS-1$
this.append(">\n"); //$NON-NLS-1$
this.prefix.append("\t"); //$NON-NLS-1$
}
/**
* Returns a string representation.
*
* @return
*/
public String toString(){
return sBuilder.toString();
}
/**
* Unintend.
*
* @throws IOException
*/
public void unindent() throws IOException{
this.prefix.setLength(this.prefix.length()-1);
String element = elements.pop();
this.append(prefix.toString());
this.append("</"); //$NON-NLS-1$
this.append(element);
this.append(">\n"); //$NON-NLS-1$
}
/**
* Appends the string.
*
* @param string
* @throws IOException
*/
public void write(String string) throws IOException {
this.append(string);
}
/**
* Create an element.
*
* @param attribute
* @param anonymity
* @throws IOException
*/
public void write(String attribute, Anonymity anonymity) throws IOException {
write(attribute, anonymity.toString());
}
/**
* Create an element.
*
* @param attribute
* @param array
* @param map
* @throws IOException
*/
public void write(String attribute, ARXNode[] array, Map<String, Integer> map) throws IOException {
StringBuilder builder = new StringBuilder();
for (int j = 0; j < array.length; j++) {
builder.append(map.get(Arrays.toString(array[j].getTransformation())));
if (j < (array.length - 1)) {
builder.append(","); //$NON-NLS-1$
}
}
write(attribute, builder.toString());
}
/**
* Create an element.
*
* @param attribute
* @param value
* @throws IOException
*/
public void write(String attribute, boolean value) throws IOException{
write(attribute, String.valueOf(value));
}
/**
* Create an element.
*
* @param attribute
* @param value
* @throws IOException
*/
public void write(String attribute, char value) throws IOException{
write(attribute, String.valueOf(value));
}
/**
* Create an element.
*
* @param attribute
* @param value
* @throws IOException
*/
public void write(String attribute, double value) throws IOException{
write(attribute, String.valueOf(value));
}
/**
* Create an element.
*
* @param attribute
* @param array
* @throws IOException
*/
public void write(String attribute, int[] array) throws IOException {
write(attribute, Arrays.toString(array));
}
/**
* Create an element.
*
* @param attribute
* @param value
* @throws IOException
*/
public void write(String attribute, long value) throws IOException{
write(attribute, String.valueOf(value));
}
/**
* Create an element.
*
* @param attribute
* @param value
* @throws IOException
*/
public void write(String attribute, String value) throws IOException{
this.append(prefix.toString());
this.append("<"); //$NON-NLS-1$
this.append(attribute);
this.append(">"); //$NON-NLS-1$
this.append(StringEscapeUtils.escapeXml(value));
this.append("</"); //$NON-NLS-1$
this.append(attribute);
this.append(">\n"); //$NON-NLS-1$
}
/**
* Append stuff to the backing builder.
*
* @param value
* @throws IOException
*/
private void append(String value) throws IOException{
if (fBuilder != null) fBuilder.append(value);
else sBuilder.append(value);
}
}
| 6,166
|
Java
|
.java
| 226
| 23.185841
| 100
| 0.667062
|
fetorres/autoML-multiData
| 3
| 0
| 0
|
GPL-3.0
|
9/4/2024, 11:34:56 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 6,166
|
2,961,857
|
Slf4JLogger.java
|
JuanJoseFJ_ProyectoPacientes/mysql-connector-java-5.1.43/src/com/mysql/jdbc/log/Slf4JLogger.java
|
/*
Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/J is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.
There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
this software, see the FOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
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.
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 St, Fifth
Floor, Boston, MA 02110-1301 USA
*/
package com.mysql.jdbc.log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Slf4JLogger implements Log {
private Logger log;
public Slf4JLogger(String name) {
this.log = LoggerFactory.getLogger(name);
}
public boolean isDebugEnabled() {
return this.log.isDebugEnabled();
}
public boolean isErrorEnabled() {
return this.log.isErrorEnabled();
}
public boolean isFatalEnabled() {
return this.log.isErrorEnabled();
}
public boolean isInfoEnabled() {
return this.log.isInfoEnabled();
}
public boolean isTraceEnabled() {
return this.log.isTraceEnabled();
}
public boolean isWarnEnabled() {
return this.log.isWarnEnabled();
}
public void logDebug(Object msg) {
this.log.debug(msg.toString());
}
public void logDebug(Object msg, Throwable thrown) {
this.log.debug(msg.toString(), thrown);
}
public void logError(Object msg) {
this.log.error(msg.toString());
}
public void logError(Object msg, Throwable thrown) {
this.log.error(msg.toString(), thrown);
}
public void logFatal(Object msg) {
this.log.error(msg.toString());
}
public void logFatal(Object msg, Throwable thrown) {
this.log.error(msg.toString(), thrown);
}
public void logInfo(Object msg) {
this.log.info(msg.toString());
}
public void logInfo(Object msg, Throwable thrown) {
this.log.info(msg.toString(), thrown);
}
public void logTrace(Object msg) {
this.log.trace(msg.toString());
}
public void logTrace(Object msg, Throwable thrown) {
this.log.trace(msg.toString(), thrown);
}
public void logWarn(Object msg) {
this.log.warn(msg.toString());
}
public void logWarn(Object msg, Throwable thrown) {
this.log.warn(msg.toString(), thrown);
}
}
| 3,046
|
Java
|
.java
| 80
| 32.4875
| 91
| 0.700477
|
JuanJoseFJ/ProyectoPacientes
| 5
| 1
| 0
|
GPL-3.0
|
9/4/2024, 10:38:53 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 3,046
|
4,894,740
|
DrawAutoGrowWidthAttribute.java
|
jbjonesjr_geoproponis/external/odfdom-java-0.8.10-incubating-sources/org/odftoolkit/odfdom/dom/attribute/draw/DrawAutoGrowWidthAttribute.java
|
/************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
*
* Use is subject to license terms.
*
* 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. You can also
* obtain a copy of the License at http://odftoolkit.org/docs/license.txt
*
* 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.
*
************************************************************************/
/*
* This file is automatically generated.
* Don't edit manually.
*/
package org.odftoolkit.odfdom.dom.attribute.draw;
import org.odftoolkit.odfdom.dom.OdfDocumentNamespace;
import org.odftoolkit.odfdom.pkg.OdfAttribute;
import org.odftoolkit.odfdom.pkg.OdfFileDom;
import org.odftoolkit.odfdom.pkg.OdfName;
/**
* DOM implementation of OpenDocument attribute {@odf.attribute draw:auto-grow-width}.
*
*/
public class DrawAutoGrowWidthAttribute extends OdfAttribute {
public static final OdfName ATTRIBUTE_NAME = OdfName.newName(OdfDocumentNamespace.DRAW, "auto-grow-width");
/**
* Create the instance of OpenDocument attribute {@odf.attribute draw:auto-grow-width}.
*
* @param ownerDocument The type is <code>OdfFileDom</code>
*/
public DrawAutoGrowWidthAttribute(OdfFileDom ownerDocument) {
super(ownerDocument, ATTRIBUTE_NAME);
}
/**
* Returns the attribute name.
*
* @return the <code>OdfName</code> for {@odf.attribute draw:auto-grow-width}.
*/
@Override
public OdfName getOdfName() {
return ATTRIBUTE_NAME;
}
/**
* @return Returns the name of this attribute.
*/
@Override
public String getName() {
return ATTRIBUTE_NAME.getLocalName();
}
/**
* @param value The <code>boolean</code> value of the attribute.
*/
public void setBooleanValue(boolean value) {
super.setValue(String.valueOf(value));
}
/**
* @return Returns the <code>boolean</code> value of the attribute
*/
public boolean booleanValue() {
String val = super.getValue();
try {
return Boolean.parseBoolean(val);
} catch (NumberFormatException e) {
// TODO: validation handling/logging
throw (e);
}
}
/**
* Returns the default value of {@odf.attribute draw:auto-grow-width}.
*
* @return the default value as <code>String</code> dependent of its element name
* return <code>null</code> if the default value does not exist
*/
@Override
public String getDefault() {
return null;
}
/**
* Default value indicator. As the attribute default value is dependent from its element, the attribute has only a default, when a parent element exists.
*
* @return <code>true</code> if {@odf.attribute draw:auto-grow-width} has an element parent
* otherwise return <code>false</code> as undefined.
*/
@Override
public boolean hasDefault() {
return false;
}
/**
* @return Returns whether this attribute is known to be of type ID (i.e. xml:id ?)
*/
@Override
public boolean isId() {
return false;
}
}
| 3,472
|
Java
|
.java
| 106
| 30.330189
| 154
| 0.70811
|
jbjonesjr/geoproponis
| 1
| 0
| 0
|
GPL-2.0
|
9/5/2024, 12:35:10 AM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 3,472
|
2,505,848
|
AbstractDisplay.java
|
CBSkarmory_AWGW/src/main/java/info/gridworld/gui/AbstractDisplay.java
|
/*
* AP(r) Computer Science GridWorld Case Study:
* Copyright(c) 2002-2006 College Entrance Examination Board
* (http://www.collegeboard.com).
*
* This code 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.
*
* This code 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.
*
* @author Julie Zelenski
* @author Cay Horstmann
*/
package info.gridworld.gui;
import java.awt.Rectangle;
import java.beans.*;
import java.lang.reflect.*;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.BasicStroke;
/**
* This class provides common implementation code for drawing objects. It will
* translate, scale, and rotate the graphics system as needed and then invoke
* its abstract <code>draw</code> method. Subclasses of this abstract class
* define <code>draw</code> to display an object in a fixed size and
* orientation. <br />
* This code is not tested on the AP CS A and AB exams. It contains GUI
* implementation details that are not intended to be understood by AP CS
* students.
*/
public abstract class AbstractDisplay implements Display
{
/**
* Draw the given object. Subclasses should implement this method to draw
* the occupant facing North in a cell of size (1,1) centered around (0,0) on
* the drawing surface. (All scaling/rotating has been done beforehand).
* @param obj the occupant we want to draw
* @param comp the component on which to draw
* @param g2 the graphics context
*/
abstract public void draw(Object obj, Component comp, Graphics2D g2);
/**
* Draw the given object. Scales and rotates the coordinate appropriately
* then invokes the simple draw method above that is only responsible for
* drawing a unit-length occupant facing North.
* @param obj the occupant we want to draw
* @param comp the component on which to draw
* @param g2 the graphics context
* @param rect rectangle in which to draw
*/
public void draw(Object obj, Component comp, Graphics2D g2, Rectangle rect)
{
float scaleFactor = Math.min(rect.width, rect.height);
g2 = (Graphics2D) g2.create();
// Translate to center of the object
g2.translate(rect.x + rect.width / 2.0, rect.y + rect.height / 2.0);
// Rotate drawing surface before drawing to capture object's
// orientation (direction).
if (obj != null)
{
Integer direction = (Integer) getProperty(obj, "direction");
int rotationInDegrees = direction == null ? 0 : direction
.intValue();
g2.rotate(Math.toRadians(rotationInDegrees));
}
// Scale to size of rectangle, adjust stroke back to 1-pixel wide
g2.scale(scaleFactor, scaleFactor);
g2.setStroke(new BasicStroke(1.0f / scaleFactor));
draw(obj, comp, g2);
}
public static Object getProperty(Object obj, String propertyName)
{
if (obj == null)
return null;
try
{
BeanInfo info = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
for (int i = 0; i < descriptors.length; i++)
{
if (descriptors[i].getName().equals(propertyName))
{
Method getter = descriptors[i].getReadMethod();
if (getter == null)
return null;
try {
return getter.invoke(obj);
} catch (Exception ex) {
System.out.println(descriptors[i].getName());
return null;
}
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
}
| 4,148
|
Java
|
.java
| 105
| 31.885714
| 81
| 0.643371
|
CBSkarmory/AWGW
| 7
| 1
| 3
|
GPL-3.0
|
9/4/2024, 9:42:51 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 4,148
|
5,116,709
|
CreateVGVDSCommandParameters.java
|
jtux270_translate/ovirt/3.6_source/backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/vdscommands/CreateVGVDSCommandParameters.java
|
package org.ovirt.engine.core.common.vdscommands;
import java.util.ArrayList;
import java.util.List;
import org.ovirt.engine.core.common.utils.ToStringBuilder;
import org.ovirt.engine.core.compat.Guid;
public class CreateVGVDSCommandParameters extends ValidateStorageDomainVDSCommandParameters {
public CreateVGVDSCommandParameters(Guid vdsId, Guid storageDomainId, ArrayList<String> deviceList, boolean force) {
super(vdsId, storageDomainId);
setDeviceList(deviceList);
setForce(force);
}
private List<String> privateDeviceList;
public List<String> getDeviceList() {
return privateDeviceList;
}
private void setDeviceList(List<String> value) {
privateDeviceList = value;
}
private boolean force;
public boolean isForce() {
return force;
}
public void setForce(boolean force) {
this.force = force;
}
public CreateVGVDSCommandParameters() {
}
@Override
protected ToStringBuilder appendAttributes(ToStringBuilder tsb) {
return super.appendAttributes(tsb)
.append("deviceList", getDeviceList())
.append("force", isForce());
}
}
| 1,200
|
Java
|
.java
| 34
| 29.147059
| 120
| 0.720346
|
jtux270/translate
| 1
| 0
| 23
|
GPL-3.0
|
9/5/2024, 12:41:44 AM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 1,200
|
745,408
|
ShortcutPackage.java
|
LawnchairLauncher_Lawnchair-V1/app/src/main/java/ch/deletescape/lawnchair/shortcuts/backport/ShortcutPackage.java
|
package ch.deletescape.lawnchair.shortcuts.backport;
import android.content.ComponentName;
import android.content.Context;
import android.content.res.Resources;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import ch.deletescape.lawnchair.shortcuts.ShortcutInfoCompat;
public class ShortcutPackage {
private final Context mContext;
private final String mPackageName;
private final Resources mResources;
private final Map<ComponentName, ShortcutParser> mShortcutsMap = new HashMap<>();
private final ArrayList<ShortcutInfoCompat> mShortcutsList = new ArrayList<>();
public ShortcutPackage(Context context, String packageName) throws Exception {
mContext = context;
mPackageName = packageName;
mResources = mContext.createPackageContext(mPackageName, Context.CONTEXT_IGNORE_SECURITY)
.getResources();
Map<ComponentName, Integer> resMap = new ShortcutPackageParser(context, packageName).getShortcutsMap();
for (Map.Entry<ComponentName, Integer> entry : resMap.entrySet()) {
ShortcutParser shortcutParser = new ShortcutParser(mContext, mResources, mPackageName, entry.getKey(), entry.getValue());
mShortcutsMap.put(entry.getKey(), shortcutParser);
mShortcutsList.addAll(shortcutParser.getShortcutsList());
}
}
Map<ComponentName, ShortcutParser> getShortcutsMap() {
return mShortcutsMap;
}
ArrayList<ShortcutInfoCompat> getAllShortcuts() {
return mShortcutsList;
}
}
| 1,563
|
Java
|
.java
| 33
| 41.181818
| 133
| 0.753785
|
LawnchairLauncher/Lawnchair-V1
| 93
| 43
| 0
|
GPL-3.0
|
9/4/2024, 7:08:37 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| true
| true
| true
| 1,563
|
2,143,371
|
GuiControls.java
|
xgraza_nebula-1_6_4/src/main/java/net/minecraft/client/gui/GuiControls.java
|
package net.minecraft.client.gui;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.client.settings.KeyBinding;
public class GuiControls extends GuiScreen
{
private static final GameSettings.Options[] field_146492_g = new GameSettings.Options[] {GameSettings.Options.INVERT_MOUSE, GameSettings.Options.SENSITIVITY, GameSettings.Options.TOUCHSCREEN};
private GuiScreen field_146496_h;
protected String field_146495_a = "Controls";
private GameSettings field_146497_i;
public KeyBinding field_146491_f = null;
private GuiKeyBindingList field_146494_r;
private GuiButton field_146493_s;
private static final String __OBFID = "CL_00000736";
public GuiControls(GuiScreen par1GuiScreen, GameSettings par2GameSettings)
{
this.field_146496_h = par1GuiScreen;
this.field_146497_i = par2GameSettings;
}
/**
* Adds the buttons (and other controls) to the screen in question.
*/
public void initGui()
{
this.field_146494_r = new GuiKeyBindingList(this, this.mc);
this.buttonList.add(new GuiButton(200, this.width / 2 - 155, this.height - 29, 150, 20, I18n.format("gui.done", new Object[0])));
this.buttonList.add(this.field_146493_s = new GuiButton(201, this.width / 2 - 155 + 160, this.height - 29, 150, 20, I18n.format("controls.resetAll", new Object[0])));
this.field_146495_a = I18n.format("controls.title", new Object[0]);
int var1 = 0;
GameSettings.Options[] var2 = field_146492_g;
int var3 = var2.length;
for (int var4 = 0; var4 < var3; ++var4)
{
GameSettings.Options var5 = var2[var4];
if (var5.getEnumFloat())
{
this.buttonList.add(new GuiOptionSlider(var5.returnEnumOrdinal(), this.width / 2 - 155 + var1 % 2 * 160, 18 + 24 * (var1 >> 1), var5));
}
else
{
this.buttonList.add(new GuiOptionButton(var5.returnEnumOrdinal(), this.width / 2 - 155 + var1 % 2 * 160, 18 + 24 * (var1 >> 1), var5, this.field_146497_i.getKeyBinding(var5)));
}
++var1;
}
}
protected void actionPerformed(GuiButton p_146284_1_)
{
if (p_146284_1_.id == 200)
{
this.mc.displayGuiScreen(this.field_146496_h);
}
else if (p_146284_1_.id == 201)
{
KeyBinding[] var2 = this.mc.gameSettings.keyBindings;
int var3 = var2.length;
for (int var4 = 0; var4 < var3; ++var4)
{
KeyBinding var5 = var2[var4];
var5.setKeyCode(var5.getKeyCodeDefault());
}
KeyBinding.resetKeyBindingArrayAndHash();
}
else if (p_146284_1_.id < 100 && p_146284_1_ instanceof GuiOptionButton)
{
this.field_146497_i.setOptionValue(((GuiOptionButton)p_146284_1_).func_146136_c(), 1);
p_146284_1_.displayString = this.field_146497_i.getKeyBinding(GameSettings.Options.getEnumOptions(p_146284_1_.id));
}
}
/**
* Called when the mouse is clicked.
*/
protected void mouseClicked(int par1, int par2, int par3)
{
if (this.field_146491_f != null)
{
this.field_146497_i.setKeyCodeSave(this.field_146491_f, -100 + par3);
this.field_146491_f = null;
KeyBinding.resetKeyBindingArrayAndHash();
}
else if (par3 != 0 || !this.field_146494_r.func_148179_a(par1, par2, par3))
{
super.mouseClicked(par1, par2, par3);
}
}
protected void mouseMovedOrUp(int p_146286_1_, int p_146286_2_, int p_146286_3_)
{
if (p_146286_3_ != 0 || !this.field_146494_r.func_148181_b(p_146286_1_, p_146286_2_, p_146286_3_))
{
super.mouseMovedOrUp(p_146286_1_, p_146286_2_, p_146286_3_);
}
}
/**
* Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e).
*/
protected void keyTyped(char par1, int par2)
{
if (this.field_146491_f != null)
{
if (par2 == 1)
{
this.field_146497_i.setKeyCodeSave(this.field_146491_f, 0);
}
else
{
this.field_146497_i.setKeyCodeSave(this.field_146491_f, par2);
}
this.field_146491_f = null;
KeyBinding.resetKeyBindingArrayAndHash();
}
else
{
super.keyTyped(par1, par2);
}
}
/**
* Draws the screen and all the components in it.
*/
public void drawScreen(int par1, int par2, float par3)
{
this.drawDefaultBackground();
this.field_146494_r.func_148128_a(par1, par2, par3);
this.drawCenteredString(this.fontRendererObj, this.field_146495_a, this.width / 2, 8, 16777215);
boolean var4 = true;
KeyBinding[] var5 = this.field_146497_i.keyBindings;
int var6 = var5.length;
for (int var7 = 0; var7 < var6; ++var7)
{
KeyBinding var8 = var5[var7];
if (var8.getKeyCode() != var8.getKeyCodeDefault())
{
var4 = false;
break;
}
}
this.field_146493_s.enabled = !var4;
super.drawScreen(par1, par2, par3);
}
}
| 5,421
|
Java
|
.java
| 138
| 30.210145
| 196
| 0.596771
|
xgraza/nebula-1.6.4
| 16
| 6
| 3
|
GPL-3.0
|
9/4/2024, 8:30:36 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| true
| true
| true
| 5,421
|
1,844,625
|
package-info.java
|
indic-ocr_LibreOCR/source/jodd/util/cl/package-info.java
|
// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. 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 HOLDER 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.
/**
* Class loaders works.
*/
package jodd.util.cl;
| 1,436
|
Java
|
.java
| 28
| 50.214286
| 78
| 0.783381
|
indic-ocr/LibreOCR
| 15
| 2
| 4
|
MPL-2.0
|
9/4/2024, 8:20:48 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 1,436
|
2,617,236
|
CommandConstraint.java
|
miroapp_miro-plantuml/src/main/kotlin/net/sourceforge/plantuml/timingdiagram/command/CommandConstraint.java
|
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2023, Arnaud Roques
*
* Project Info: http://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* http://plantuml.com/patreon (only 1$ per month!)
* http://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* PlantUML 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.
*
* PlantUML 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
*
* Original Author: Arnaud Roques
*
*
*/
package net.sourceforge.plantuml.timingdiagram.command;
import net.sourceforge.plantuml.LineLocation;
import net.sourceforge.plantuml.command.CommandExecutionResult;
import net.sourceforge.plantuml.command.SingleLineCommand2;
import net.sourceforge.plantuml.command.regex.IRegex;
import net.sourceforge.plantuml.command.regex.RegexConcat;
import net.sourceforge.plantuml.command.regex.RegexLeaf;
import net.sourceforge.plantuml.command.regex.RegexOptional;
import net.sourceforge.plantuml.command.regex.RegexResult;
import net.sourceforge.plantuml.timingdiagram.Player;
import net.sourceforge.plantuml.timingdiagram.TimeTick;
import net.sourceforge.plantuml.timingdiagram.TimingDiagram;
public class CommandConstraint extends SingleLineCommand2<TimingDiagram> {
public CommandConstraint() {
super(getRegexConcat());
}
private static IRegex getRegexConcat() {
return RegexConcat.build(CommandConstraint.class.getName(), RegexLeaf.start(), //
new RegexLeaf("PART1", "(" + CommandTimeMessage.PLAYER_CODE + ")?"), //
TimeTickBuilder.expressionAtWithArobase("TIME1"), //
RegexLeaf.spaceZeroOrMore(), //
new RegexLeaf("\\<"), //
new RegexLeaf("ARROW", "(-+)"), //
new RegexLeaf("\\>"), //
RegexLeaf.spaceZeroOrMore(), //
TimeTickBuilder.expressionAtWithArobase("TIME2"), //
RegexLeaf.spaceZeroOrMore(), //
new RegexOptional( //
new RegexConcat( //
new RegexLeaf(":"), //
RegexLeaf.spaceZeroOrMore(), //
new RegexLeaf("MESSAGE", "(.*)") //
)), //
RegexLeaf.spaceZeroOrMore(), RegexLeaf.end());
}
@Override
final protected CommandExecutionResult executeArg(TimingDiagram diagram, LineLocation location, RegexResult arg) {
final String part1 = arg.get("PART1", 0);
final Player player1;
if (part1 == null) {
player1 = diagram.getLastPlayer();
if (player1 == null) {
return CommandExecutionResult.error("You have to provide a participant");
}
} else {
player1 = diagram.getPlayer(part1);
if (player1 == null) {
return CommandExecutionResult.error("No such participant " + part1);
}
}
final TimeTick tick1 = TimeTickBuilder.parseTimeTick("TIME1", arg, diagram);
if (tick1 == null) {
return CommandExecutionResult.error("Unknown time label");
}
final TimeTick restore = diagram.getNow();
diagram.updateNow(tick1);
final TimeTick tick2 = TimeTickBuilder.parseTimeTick("TIME2", arg, diagram);
diagram.updateNow(restore);
if (tick2 == null) {
return CommandExecutionResult.error("Unknown time label");
}
player1.createConstraint(tick1, tick2, arg.get("MESSAGE", 0));
return CommandExecutionResult.ok();
}
}
| 3,904
|
Java
|
.java
| 100
| 36.05
| 115
| 0.715377
|
miroapp/miro-plantuml
| 7
| 5
| 0
|
GPL-3.0
|
9/4/2024, 9:51:14 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 3,904
|
2,961,437
|
R.java
|
SomebodyLuo_LawrenceARCamera/rajawali/build/generated/source/r/release/org/rajawali3d/R.java
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package org.rajawali3d;
public final class R {
public static final class attr {
/** <p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>multisample</code></td><td>1</td><td></td></tr>
<tr><td><code>coverage</code></td><td>2</td><td></td></tr>
</table>
*/
public static int antiAliasingType=0x7f010000;
/** <p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int bitsAlpha=0x7f010001;
/** <p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int bitsBlue=0x7f010002;
/** <p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int bitsDepth=0x7f010003;
/** <p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int bitsGreen=0x7f010004;
/** <p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int bitsRed=0x7f010005;
/** <p>Must be a floating point value, such as "<code>1.2</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int frameRate=0x7f010006;
/** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int isTransparent=0x7f010007;
/** <p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static int multiSampleCount=0x7f010008;
/** <p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>RENDER_WHEN_DIRTY</code></td><td>0</td><td></td></tr>
<tr><td><code>RENDER_CONTINUOUS</code></td><td>1</td><td></td></tr>
</table>
*/
public static int renderMode=0x7f010009;
}
public static final class id {
public static int RENDER_CONTINUOUS=0x7f030002;
public static int RENDER_WHEN_DIRTY=0x7f030003;
public static int coverage=0x7f030000;
public static int multisample=0x7f030001;
}
public static final class raw {
public static int blend_add_fragment_shader=0x7f020000;
public static int blend_screen_fragment_shader=0x7f020001;
public static int blur_fragment_shader=0x7f020002;
public static int color_threshold_shader=0x7f020003;
public static int copy_fragment_shader=0x7f020004;
public static int fog_fragment_shader=0x7f020005;
public static int fxaa_fragment_shader=0x7f020006;
public static int fxaa_vertex_shader=0x7f020007;
public static int grey_scale_fragment_shader=0x7f020008;
public static int minimal_vertex_shader=0x7f020009;
public static int scanline_fragment_shader=0x7f02000a;
public static int sepia_fragment_shader=0x7f02000b;
public static int vignette_fragment_shader=0x7f02000c;
}
public static final class styleable {
/** Attributes that can be used with a SurfaceView.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #SurfaceView_antiAliasingType org.rajawali3d:antiAliasingType}</code></td><td></td></tr>
<tr><td><code>{@link #SurfaceView_bitsAlpha org.rajawali3d:bitsAlpha}</code></td><td></td></tr>
<tr><td><code>{@link #SurfaceView_bitsBlue org.rajawali3d:bitsBlue}</code></td><td></td></tr>
<tr><td><code>{@link #SurfaceView_bitsDepth org.rajawali3d:bitsDepth}</code></td><td></td></tr>
<tr><td><code>{@link #SurfaceView_bitsGreen org.rajawali3d:bitsGreen}</code></td><td></td></tr>
<tr><td><code>{@link #SurfaceView_bitsRed org.rajawali3d:bitsRed}</code></td><td></td></tr>
<tr><td><code>{@link #SurfaceView_frameRate org.rajawali3d:frameRate}</code></td><td></td></tr>
<tr><td><code>{@link #SurfaceView_isTransparent org.rajawali3d:isTransparent}</code></td><td></td></tr>
<tr><td><code>{@link #SurfaceView_multiSampleCount org.rajawali3d:multiSampleCount}</code></td><td></td></tr>
<tr><td><code>{@link #SurfaceView_renderMode org.rajawali3d:renderMode}</code></td><td></td></tr>
</table>
@see #SurfaceView_antiAliasingType
@see #SurfaceView_bitsAlpha
@see #SurfaceView_bitsBlue
@see #SurfaceView_bitsDepth
@see #SurfaceView_bitsGreen
@see #SurfaceView_bitsRed
@see #SurfaceView_frameRate
@see #SurfaceView_isTransparent
@see #SurfaceView_multiSampleCount
@see #SurfaceView_renderMode
*/
public static final int[] SurfaceView = {
0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003,
0x7f010004, 0x7f010005, 0x7f010006, 0x7f010007,
0x7f010008, 0x7f010009
};
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#antiAliasingType}
attribute's value can be found in the {@link #SurfaceView} array.
<p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>multisample</code></td><td>1</td><td></td></tr>
<tr><td><code>coverage</code></td><td>2</td><td></td></tr>
</table>
@attr name org.rajawali3d:antiAliasingType
*/
public static int SurfaceView_antiAliasingType = 0;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#bitsAlpha}
attribute's value can be found in the {@link #SurfaceView} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:bitsAlpha
*/
public static int SurfaceView_bitsAlpha = 1;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#bitsBlue}
attribute's value can be found in the {@link #SurfaceView} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:bitsBlue
*/
public static int SurfaceView_bitsBlue = 2;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#bitsDepth}
attribute's value can be found in the {@link #SurfaceView} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:bitsDepth
*/
public static int SurfaceView_bitsDepth = 3;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#bitsGreen}
attribute's value can be found in the {@link #SurfaceView} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:bitsGreen
*/
public static int SurfaceView_bitsGreen = 4;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#bitsRed}
attribute's value can be found in the {@link #SurfaceView} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:bitsRed
*/
public static int SurfaceView_bitsRed = 5;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#frameRate}
attribute's value can be found in the {@link #SurfaceView} array.
<p>Must be a floating point value, such as "<code>1.2</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:frameRate
*/
public static int SurfaceView_frameRate = 6;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#isTransparent}
attribute's value can be found in the {@link #SurfaceView} array.
<p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:isTransparent
*/
public static int SurfaceView_isTransparent = 7;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#multiSampleCount}
attribute's value can be found in the {@link #SurfaceView} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:multiSampleCount
*/
public static int SurfaceView_multiSampleCount = 8;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#renderMode}
attribute's value can be found in the {@link #SurfaceView} array.
<p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>RENDER_WHEN_DIRTY</code></td><td>0</td><td></td></tr>
<tr><td><code>RENDER_CONTINUOUS</code></td><td>1</td><td></td></tr>
</table>
@attr name org.rajawali3d:renderMode
*/
public static int SurfaceView_renderMode = 9;
/** Attributes that can be used with a TextureView.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #TextureView_antiAliasingType org.rajawali3d:antiAliasingType}</code></td><td></td></tr>
<tr><td><code>{@link #TextureView_bitsAlpha org.rajawali3d:bitsAlpha}</code></td><td></td></tr>
<tr><td><code>{@link #TextureView_bitsBlue org.rajawali3d:bitsBlue}</code></td><td></td></tr>
<tr><td><code>{@link #TextureView_bitsDepth org.rajawali3d:bitsDepth}</code></td><td></td></tr>
<tr><td><code>{@link #TextureView_bitsGreen org.rajawali3d:bitsGreen}</code></td><td></td></tr>
<tr><td><code>{@link #TextureView_bitsRed org.rajawali3d:bitsRed}</code></td><td></td></tr>
<tr><td><code>{@link #TextureView_frameRate org.rajawali3d:frameRate}</code></td><td></td></tr>
<tr><td><code>{@link #TextureView_multiSampleCount org.rajawali3d:multiSampleCount}</code></td><td></td></tr>
<tr><td><code>{@link #TextureView_renderMode org.rajawali3d:renderMode}</code></td><td></td></tr>
</table>
@see #TextureView_antiAliasingType
@see #TextureView_bitsAlpha
@see #TextureView_bitsBlue
@see #TextureView_bitsDepth
@see #TextureView_bitsGreen
@see #TextureView_bitsRed
@see #TextureView_frameRate
@see #TextureView_multiSampleCount
@see #TextureView_renderMode
*/
public static final int[] TextureView = {
0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003,
0x7f010004, 0x7f010005, 0x7f010006, 0x7f010008,
0x7f010009
};
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#antiAliasingType}
attribute's value can be found in the {@link #TextureView} array.
<p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>multisample</code></td><td>1</td><td></td></tr>
<tr><td><code>coverage</code></td><td>2</td><td></td></tr>
</table>
@attr name org.rajawali3d:antiAliasingType
*/
public static int TextureView_antiAliasingType = 0;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#bitsAlpha}
attribute's value can be found in the {@link #TextureView} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:bitsAlpha
*/
public static int TextureView_bitsAlpha = 1;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#bitsBlue}
attribute's value can be found in the {@link #TextureView} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:bitsBlue
*/
public static int TextureView_bitsBlue = 2;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#bitsDepth}
attribute's value can be found in the {@link #TextureView} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:bitsDepth
*/
public static int TextureView_bitsDepth = 3;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#bitsGreen}
attribute's value can be found in the {@link #TextureView} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:bitsGreen
*/
public static int TextureView_bitsGreen = 4;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#bitsRed}
attribute's value can be found in the {@link #TextureView} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:bitsRed
*/
public static int TextureView_bitsRed = 5;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#frameRate}
attribute's value can be found in the {@link #TextureView} array.
<p>Must be a floating point value, such as "<code>1.2</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:frameRate
*/
public static int TextureView_frameRate = 6;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#multiSampleCount}
attribute's value can be found in the {@link #TextureView} array.
<p>Must be an integer value, such as "<code>100</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name org.rajawali3d:multiSampleCount
*/
public static int TextureView_multiSampleCount = 7;
/**
<p>This symbol is the offset where the {@link org.rajawali3d.R.attr#renderMode}
attribute's value can be found in the {@link #TextureView} array.
<p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>RENDER_WHEN_DIRTY</code></td><td>0</td><td></td></tr>
<tr><td><code>RENDER_CONTINUOUS</code></td><td>1</td><td></td></tr>
</table>
@attr name org.rajawali3d:renderMode
*/
public static int TextureView_renderMode = 8;
};
}
| 20,750
|
Java
|
.java
| 424
| 42.356132
| 120
| 0.633639
|
SomebodyLuo/LawrenceARCamera
| 5
| 8
| 0
|
GPL-3.0
|
9/4/2024, 10:38:53 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| true
| true
| 20,750
|
1,493,591
|
CM_RELEASE_OBJECT.java
|
MobiusDevelopment_Mobius_AionEmu/java/com/aionemu/gameserver/network/aion/clientpackets/CM_RELEASE_OBJECT.java
|
/*
* This file is part of the Aion-Emu project.
*
* 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.aionemu.gameserver.network.aion.clientpackets;
import com.aionemu.gameserver.model.TaskId;
import com.aionemu.gameserver.model.gameobjects.UseableItemObject;
import com.aionemu.gameserver.model.gameobjects.VisibleObject;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.AionClientPacket;
import com.aionemu.gameserver.network.aion.AionConnection.State;
import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE;
import com.aionemu.gameserver.world.World;
/**
* @author Rolandas
*/
public class CM_RELEASE_OBJECT extends AionClientPacket
{
int targetObjectId;
public CM_RELEASE_OBJECT(int opcode, State state, State... restStates)
{
super(opcode, state, restStates);
}
@Override
protected void readImpl()
{
targetObjectId = readD();
}
@Override
protected void runImpl()
{
final Player player = getConnection().getActivePlayer();
if (player == null)
{
return;
}
if (player.getController().hasTask(TaskId.HOUSE_OBJECT_USE))
{
final VisibleObject object = World.getInstance().findVisibleObject(targetObjectId);
if ((object instanceof UseableItemObject) && !player.getController().hasScheduledTask(TaskId.HOUSE_OBJECT_USE))
{
}
else
{
player.getController().cancelTask(TaskId.HOUSE_OBJECT_USE);
sendPacket(SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OBJECT_CANCEL_USE);
}
}
}
}
| 2,189
|
Java
|
.java
| 62
| 31.806452
| 115
| 0.756501
|
MobiusDevelopment/Mobius_AionEmu
| 24
| 22
| 0
|
GPL-3.0
|
9/4/2024, 7:53:54 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| true
| true
| true
| 2,189
|
2,575,350
|
PipelineSetup.java
|
JPortal-system_system/jdk12-06222165c35f/test/micro/org/openjdk/bench/java/util/stream/pipeline/PipelineSetup.java
|
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.java.util.stream.pipeline;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.TimeUnit;
import java.util.stream.LongStream;
/**
* Benchmark tests the pipeline construction costs.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class PipelineSetup {
/**
* This is one of the few benchmarks where measuring running time makes sense.
*/
@Param("100000")
private int size;
@Benchmark
public Object baseline_newObject() {
return new Object();
}
@Benchmark
public LongStream seq_test00() {
return LongStream.range(0, size);
}
@Benchmark
public LongStream seq_test01() {
return LongStream.range(0, size)
.filter((x) -> false);
}
@Benchmark
public LongStream seq_test02() {
return LongStream.range(0, size)
.filter((x) -> false)
.filter((x) -> false);
}
@Benchmark
public LongStream seq_test04() {
return LongStream.range(0, size)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false);
}
@Benchmark
public LongStream seq_test08() {
return LongStream.range(0, size)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false);
}
@Benchmark
public LongStream seq_test16() {
return LongStream.range(0, size)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false);
}
@Benchmark
public LongStream par_test00() {
return LongStream.range(0, size).parallel();
}
@Benchmark
public LongStream par_test01() {
return LongStream.range(0, size).parallel()
.filter((x) -> false);
}
@Benchmark
public LongStream par_test02() {
return LongStream.range(0, size).parallel()
.filter((x) -> false)
.filter((x) -> false);
}
@Benchmark
public LongStream par_test04() {
return LongStream.range(0, size).parallel()
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false);
}
@Benchmark
public LongStream par_test08() {
return LongStream.range(0, size).parallel()
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false);
}
@Benchmark
public LongStream par_test16() {
return LongStream.range(0, size).parallel()
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false)
.filter((x) -> false);
}
}
| 5,556
|
Java
|
.java
| 159
| 25.616352
| 82
| 0.549907
|
JPortal-system/system
| 7
| 2
| 1
|
GPL-3.0
|
9/4/2024, 9:49:36 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 5,556
|
265,234
|
JobPriority.java
|
openjdk-mirror_jdk7u-jdk/src/share/classes/javax/print/attribute/standard/JobPriority.java
|
/*
* Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.print.attribute.standard;
import javax.print.attribute.Attribute;
import javax.print.attribute.IntegerSyntax;
import javax.print.attribute.PrintRequestAttribute;
import javax.print.attribute.PrintJobAttribute;
/**
* Class JobPriority is an integer valued printing attribute class that
* specifies a print job's priority.
* <P>
* If a JobPriority attribute is specified for a Print Job, it specifies a
* priority for scheduling the job. A higher value specifies a higher priority.
* The value 1 indicates the lowest possible priority. The value 100 indicates
* the highest possible priority. Among those jobs that are ready to print, a
* printer must print all jobs with a priority value of <I>n</I> before printing
* those with a priority value of <I>n</I>-1 for all <I>n.</I>
* <P>
* If the client does not specify a JobPriority attribute for a Print Job and
* the printer does support the JobPriority attribute, the printer must use an
* implementation-defined default JobPriority value.
* <P>
* The client can always specify any job priority value from 1 to 100 for a job.
* However, a Print Service instance may support fewer than 100 different
* job priority levels. If this is the case, the Print Service instance
* automatically maps the client-specified job priority value to one of the
* supported job priority levels, dividing the 100 job priority values equally
* among the available job priority levels.
* <P>
* <B>IPP Compatibility:</B> The integer value gives the IPP integer value. The
* category name returned by <CODE>getName()</CODE> gives the IPP attribute
* name.
* <P>
*
* @author Alan Kaminsky
*/
public final class JobPriority extends IntegerSyntax
implements PrintRequestAttribute, PrintJobAttribute {
private static final long serialVersionUID = -4599900369040602769L;
/**
* Construct a new job priority attribute with the given integer value.
*
* @param value Integer value.
*
* @exception IllegalArgumentException
* (Unchecked exception) Thrown if <CODE>value</CODE> is less than 1
* or greater than 100.
*/
public JobPriority(int value) {
super (value, 1, 100);
}
/**
* Returns whether this job priority attribute is equivalent to the passed
* in object. To be equivalent, all of the following conditions must be
* true:
* <OL TYPE=1>
* <LI>
* <CODE>object</CODE> is not null.
* <LI>
* <CODE>object</CODE> is an instance of class JobPriority.
* <LI>
* This job priority attribute's value and <CODE>object</CODE>'s value
* are equal.
* </OL>
*
* @param object Object to compare to.
*
* @return True if <CODE>object</CODE> is equivalent to this job
* priority attribute, false otherwise.
*/
public boolean equals(Object object) {
return (super.equals (object) && object instanceof JobPriority);
}
/**
* Get the printing attribute class which is to be used as the "category"
* for this printing attribute value.
* <P>
* For class JobPriority, the category is class JobPriority itself.
*
* @return Printing attribute class (category), an instance of class
* {@link java.lang.Class java.lang.Class}.
*/
public final Class<? extends Attribute> getCategory() {
return JobPriority.class;
}
/**
* Get the name of the category of which this attribute value is an
* instance.
* <P>
* For class JobPriority, the category name is <CODE>"job-priority"</CODE>.
*
* @return Attribute category name.
*/
public final String getName() {
return "job-priority";
}
}
| 4,964
|
Java
|
.java
| 119
| 37.756303
| 80
| 0.718007
|
openjdk-mirror/jdk7u-jdk
| 525
| 429
| 6
|
GPL-2.0
|
9/4/2024, 7:05:59 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 4,964
|
3,525,484
|
RFXComResponse.java
|
andrey-desman_openhab-hdl/bundles/binding/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/RFXComResponse.java
|
/**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.rfxcom.internal;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.openhab.binding.rfxcom.internal.messages.RFXComTransmitterMessage;
/**
* The Response of a Command is always a {@link RFXComTransmitterMessage}. This implements
* a very simple {@link Future} for that type.
*
* @author Jürgen Richtsfeld
* @since 1.7
*/
class RFXComResponse implements Future<RFXComTransmitterMessage> {
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
private RFXComTransmitterMessage result = null;
private boolean done = false;
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
lock.lock();
try {
return done;
} finally {
lock.unlock();
}
}
@Override
public RFXComTransmitterMessage get() throws InterruptedException,
ExecutionException {
lock.lock();
try {
if(!done) {
condition.await();
}
return result;
} finally {
lock.unlock();
}
}
@Override
public RFXComTransmitterMessage get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
lock.lock();
try {
if(!done) {
final boolean timedOut = !condition.await(timeout, unit);
if(timedOut) {
throw new TimeoutException("waiting timed out");
}
}
return result;
} finally {
lock.unlock();
}
}
public void set(final RFXComTransmitterMessage result) {
lock.lock();
try {
this.result = result;
this.done = true;
condition.signalAll();
} finally {
lock.unlock();
}
}
}
| 2,270
|
Java
|
.java
| 86
| 23.581395
| 90
| 0.755074
|
andrey-desman/openhab-hdl
| 3
| 4
| 1
|
EPL-1.0
|
9/4/2024, 11:31:25 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 2,270
|
1,202,082
|
EventRequestManager.java
|
keerath_openjdk-8-source/jdk/src/share/classes/com/sun/jdi/request/EventRequestManager.java
|
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.jdi.request;
import com.sun.jdi.*;
import java.util.List;
/**
* Manages the creation and deletion of {@link EventRequest}s. A single
* implementor of this interface exists in a particuar VM and
* is accessed through {@link VirtualMachine#eventRequestManager()}
*
* @see EventRequest
* @see com.sun.jdi.event.Event
* @see BreakpointRequest
* @see com.sun.jdi.event.BreakpointEvent
* @see VirtualMachine
*
* @author Robert Field
* @since 1.3
*/
@jdk.Exported
public interface EventRequestManager extends Mirror {
/**
* Creates a new disabled {@link ClassPrepareRequest}.
* The new event request is added to the list managed by this
* EventRequestManager. Use {@link EventRequest#enable()} to
* activate this event request.
*
* @return the created {@link ClassPrepareRequest}
*/
ClassPrepareRequest createClassPrepareRequest();
/**
* Creates a new disabled {@link ClassUnloadRequest}.
* The new event request is added to the list managed by this
* EventRequestManager. Use {@link EventRequest#enable()} to
* activate this event request.
*
* @return the created {@link ClassUnloadRequest}
*/
ClassUnloadRequest createClassUnloadRequest();
/**
* Creates a new disabled {@link ThreadStartRequest}.
* The new event request is added to the list managed by this
* EventRequestManager. Use {@link EventRequest#enable()} to
* activate this event request.
*
* @return the created {@link ThreadStartRequest}
*/
ThreadStartRequest createThreadStartRequest();
/**
* Creates a new disabled {@link ThreadDeathRequest}.
* The new event request is added to the list managed by this
* EventRequestManager. Use {@link EventRequest#enable()} to
* activate this event request.
*
* @return the created {@link ThreadDeathRequest}
*/
ThreadDeathRequest createThreadDeathRequest();
/**
* Creates a new disabled {@link ExceptionRequest}.
* The new event request is added to the list managed by this
* EventRequestManager. Use {@link EventRequest#enable()} to
* activate this event request.
* <P>
* A specific exception type and its subclasses can be selected
* for exception events. Caught exceptions, uncaught exceptions,
* or both can be selected. Note, however, that
* at the time an exception is thrown, it is not always
* possible to determine whether it is truly caught. See
* {@link com.sun.jdi.event.ExceptionEvent#catchLocation} for
* details.
* @param refType If non-null, specifies that exceptions which are
* instances of refType will be reported. Note: this
* will include instances of sub-types. If null,
* all instances will be reported
* @param notifyCaught If true, caught exceptions will be reported.
* @param notifyUncaught If true, uncaught exceptions will be reported.
*
* @return the created {@link ExceptionRequest}
*/
ExceptionRequest createExceptionRequest(ReferenceType refType,
boolean notifyCaught,
boolean notifyUncaught);
/**
* Creates a new disabled {@link MethodEntryRequest}.
* The new event request is added to the list managed by this
* EventRequestManager. Use {@link EventRequest#enable()} to
* activate this event request.
*
* @return the created {@link MethodEntryRequest}
*/
MethodEntryRequest createMethodEntryRequest();
/**
* Creates a new disabled {@link MethodExitRequest}.
* The new event request is added to the list managed by this
* EventRequestManager. Use {@link EventRequest#enable()} to
* activate this event request.
*
* @return the created {@link MethodExitRequest}
*/
MethodExitRequest createMethodExitRequest();
/**
* Creates a new disabled {@link MonitorContendedEnterRequest}.
* The new event request is added to the list managed by this
* EventRequestManager. Use {@link EventRequest#enable()} to
* activate this event request.
*
* Not all target virtual machines support this operation.
* Use {@link VirtualMachine#canRequestMonitorEvents()}
* to determine if the operation is supported.
*
* @return the created {@link MonitorContendedEnterRequest}
* @throws java.lang.UnsupportedOperationException if
* the target VM does not support this
* operation.
*
* @since 1.6
*/
MonitorContendedEnterRequest createMonitorContendedEnterRequest();
/**
* Creates a new disabled {@link MonitorContendedEnteredRequest}.
* The new event request is added to the list managed by this
* EventRequestManager. Use {@link EventRequest#enable()} to
* activate this event request.
*
* Not all target virtual machines support this operation.
* Use {@link VirtualMachine#canRequestMonitorEvents()}
* to determine if the operation is supported.
*
* @return the created {@link MonitorContendedEnteredRequest}
* @throws java.lang.UnsupportedOperationException if
* the target VM does not support this
* operation.
*
* @since 1.6
*/
MonitorContendedEnteredRequest createMonitorContendedEnteredRequest();
/**
* Creates a new disabled {@link MonitorWaitRequest}.
* The new event request is added to the list managed by this
* EventRequestManager. Use {@link EventRequest#enable()} to
* activate this event request.
*
* Not all target virtual machines support this operation.
* Use {@link VirtualMachine#canRequestMonitorEvents()}
* to determine if the operation is supported.
*
* @return the created {@link MonitorWaitRequest}
* @throws java.lang.UnsupportedOperationException if
* the target VM does not support this
* operation.
*
* @since 1.6
*/
MonitorWaitRequest createMonitorWaitRequest();
/**
* Creates a new disabled {@link MonitorWaitedRequest}.
* The new event request is added to the list managed by this
* EventRequestManager. Use {@link EventRequest#enable()} to
* activate this event request.
*
* Not all target virtual machines support this operation.
* Use {@link VirtualMachine#canRequestMonitorEvents()}
* to determine if the operation is supported.
*
* @return the created {@link MonitorWaitedRequest}
* @throws java.lang.UnsupportedOperationException if
* the target VM does not support this
* operation.
*
* @since 1.6
*/
MonitorWaitedRequest createMonitorWaitedRequest();
/**
* Creates a new disabled {@link StepRequest}.
* The new event request is added to the list managed by this
* EventRequestManager. Use {@link EventRequest#enable()} to
* activate this event request.
* <p>
* The returned request will control stepping only in the specified
* <code>thread</code>; all other threads will be unaffected.
* A <code>size</code>value of {@link com.sun.jdi.request.StepRequest#STEP_MIN} will generate a
* step event each time the code index changes. It represents the
* smallest step size available and often maps to the instruction
* level.
* A <code>size</code> value of {@link com.sun.jdi.request.StepRequest#STEP_LINE} will generate a
* step event each time the source line changes unless line number information is not available,
* in which case a STEP_MIN will be done instead. For example, no line number information is
* available during the execution of a method that has been rendered obsolete by
* by a {@link com.sun.jdi.VirtualMachine#redefineClasses} operation.
* A <code>depth</code> value of {@link com.sun.jdi.request.StepRequest#STEP_INTO} will generate
* step events in any called methods. A <code>depth</code> value
* of {@link com.sun.jdi.request.StepRequest#STEP_OVER} restricts step events to the current frame
* or caller frames. A <code>depth</code> value of {@link com.sun.jdi.request.StepRequest#STEP_OUT}
* restricts step events to caller frames only. All depth
* restrictions are relative to the call stack immediately before the
* step takes place.
* <p>
* Only one pending step request is allowed per thread.
* <p>
* Note that a typical debugger will want to cancel stepping
* after the first step is detected. Thus a next line method
* would do the following:
* <code>
* <pre>
* EventRequestManager mgr = myVM.{@link VirtualMachine#eventRequestManager eventRequestManager}();
* StepRequest request = mgr.createStepRequest(myThread,
* StepRequest.{@link StepRequest#STEP_LINE STEP_LINE},
* StepRequest.{@link StepRequest#STEP_OVER STEP_OVER});
* request.{@link EventRequest#addCountFilter addCountFilter}(1); // next step only
* request.enable();
* myVM.{@link VirtualMachine#resume resume}();
* </pre>
* </code>
*
* @param thread the thread in which to step
* @param depth the step depth
* @param size the step size
* @return the created {@link StepRequest}
* @throws DuplicateRequestException if there is already a pending
* step request for the specified thread.
* @throws IllegalArgumentException if the size or depth arguments
* contain illegal values.
*/
StepRequest createStepRequest(ThreadReference thread,
int size,
int depth);
/**
* Creates a new disabled {@link BreakpointRequest}.
* The given {@link Location} must have a valid
* (that is, non-negative) code index. The new
* breakpoint is added to the list managed by this
* EventRequestManager. Multiple breakpoints at the
* same location are permitted. Use {@link EventRequest#enable()} to
* activate this event request.
*
* @param location the location of the new breakpoint.
* @return the created {@link BreakpointRequest}
* @throws NativeMethodException if location is within a native method.
*/
BreakpointRequest createBreakpointRequest(Location location);
/**
* Creates a new disabled watchpoint which watches accesses to the
* specified field. The new
* watchpoint is added to the list managed by this
* EventRequestManager. Multiple watchpoints on the
* same field are permitted.
* Use {@link EventRequest#enable()} to
* activate this event request.
* <P>
* Not all target virtual machines support this operation.
* Use {@link VirtualMachine#canWatchFieldAccess()}
* to determine if the operation is supported.
*
* @param field the field to watch
* @return the created watchpoint
* @throws java.lang.UnsupportedOperationException if
* the target virtual machine does not support this
* operation.
*/
AccessWatchpointRequest createAccessWatchpointRequest(Field field);
/**
* Creates a new disabled watchpoint which watches accesses to the
* specified field. The new
* watchpoint is added to the list managed by this
* EventRequestManager. Multiple watchpoints on the
* same field are permitted.
* Use {@link EventRequest#enable()} to
* activate this event request.
* <P>
* Not all target virtual machines support this operation.
* Use {@link VirtualMachine#canWatchFieldModification()}
* to determine if the operation is supported.
*
* @param field the field to watch
* @return the created watchpoint
* @throws java.lang.UnsupportedOperationException if
* the target virtual machine does not support this
* operation.
*/
ModificationWatchpointRequest createModificationWatchpointRequest(Field field);
/**
* Creates a new disabled {@link VMDeathRequest}.
* The new request is added to the list managed by this
* EventRequestManager.
* Use {@link EventRequest#enable()} to
* activate this event request.
* <P>
* This request (if enabled) will cause a
* {@link com.sun.jdi.event.VMDeathEvent}
* to be sent on termination of the target VM.
* <P>
* A VMDeathRequest with a suspend policy of
* {@link EventRequest#SUSPEND_ALL SUSPEND_ALL}
* can be used to assure processing of incoming
* {@link EventRequest#SUSPEND_NONE SUSPEND_NONE} or
* {@link EventRequest#SUSPEND_EVENT_THREAD SUSPEND_EVENT_THREAD}
* events before VM death. If all event processing is being
* done in the same thread as event sets are being read,
* enabling the request is all that is needed since the VM
* will be suspended until the {@link com.sun.jdi.event.EventSet}
* containing the {@link com.sun.jdi.event.VMDeathEvent}
* is resumed.
* <P>
* Not all target virtual machines support this operation.
* Use {@link VirtualMachine#canRequestVMDeathEvent()}
* to determine if the operation is supported.
*
* @return the created request
* @throws java.lang.UnsupportedOperationException if
* the target VM does not support this
* operation.
*
* @since 1.4
*/
VMDeathRequest createVMDeathRequest();
/**
* Removes an eventRequest. The eventRequest is disabled and
* the removed from the requests managed by this
* EventRequestManager. Once the eventRequest is deleted, no
* operations (for example, {@link EventRequest#setEnabled})
* are permitted - attempts to do so will generally cause an
* {@link InvalidRequestStateException}.
* No other eventRequests are effected.
* <P>
* Because this method changes the underlying lists of event
* requests, attempting to directly delete from a list returned
* by a request accessor (e.g. below):
* <PRE>
* Iterator iter = requestManager.stepRequests().iterator();
* while (iter.hasNext()) {
* requestManager.deleteEventRequest(iter.next());
* }
* </PRE>
* may cause a {@link java.util.ConcurrentModificationException}.
* Instead use
* {@link #deleteEventRequests(List) deleteEventRequests(List)}
* or copy the list before iterating.
*
* @param eventRequest the eventRequest to remove
*/
void deleteEventRequest(EventRequest eventRequest);
/**
* Removes a list of {@link EventRequest}s.
*
* @see #deleteEventRequest(EventRequest)
*
* @param eventRequests the list of eventRequests to remove
*/
void deleteEventRequests(List<? extends EventRequest> eventRequests);
/**
* Remove all breakpoints managed by this EventRequestManager.
*
* @see #deleteEventRequest(EventRequest)
*/
void deleteAllBreakpoints();
/**
* Return an unmodifiable list of the enabled and disabled step requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the all {@link StepRequest} objects.
*/
List<StepRequest> stepRequests();
/**
* Return an unmodifiable list of the enabled and disabled class prepare requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the all {@link ClassPrepareRequest} objects.
*/
List<ClassPrepareRequest> classPrepareRequests();
/**
* Return an unmodifiable list of the enabled and disabled class unload requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the all {@link ClassUnloadRequest} objects.
*/
List<ClassUnloadRequest> classUnloadRequests();
/**
* Return an unmodifiable list of the enabled and disabled thread start requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the all {@link ThreadStartRequest} objects.
*/
List<ThreadStartRequest> threadStartRequests();
/**
* Return an unmodifiable list of the enabled and disabled thread death requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the all {@link ThreadDeathRequest} objects.
*/
List<ThreadDeathRequest> threadDeathRequests();
/**
* Return an unmodifiable list of the enabled and disabled exception requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the all {@link ExceptionRequest} objects.
*/
List<ExceptionRequest> exceptionRequests();
/**
* Return an unmodifiable list of the enabled and disabled breakpoint requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the list of all {@link BreakpointRequest} objects.
*/
List<BreakpointRequest> breakpointRequests();
/**
* Return an unmodifiable list of the enabled and disabled access
* watchpoint requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the all {@link AccessWatchpointRequest} objects.
*/
List<AccessWatchpointRequest> accessWatchpointRequests();
/**
* Return an unmodifiable list of the enabled and disabled modification
* watchpoint requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the all {@link ModificationWatchpointRequest} objects.
*/
List<ModificationWatchpointRequest> modificationWatchpointRequests();
/**
* Return an unmodifiable list of the enabled and disabled method entry requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the list of all {@link MethodEntryRequest} objects.
*/
List<MethodEntryRequest> methodEntryRequests();
/**
* Return an unmodifiable list of the enabled and disabled method exit requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the list of all {@link MethodExitRequest} objects.
*/
List<MethodExitRequest> methodExitRequests();
/**
* Return an unmodifiable list of the enabled and disabled monitor contended enter requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the list of all {@link MonitorContendedEnterRequest} objects.
*
* @since 1.6
*/
List<MonitorContendedEnterRequest> monitorContendedEnterRequests();
/**
* Return an unmodifiable list of the enabled and disabled monitor contended entered requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the list of all {@link MonitorContendedEnteredRequest} objects.
*
* @since 1.6
*/
List<MonitorContendedEnteredRequest> monitorContendedEnteredRequests();
/**
* Return an unmodifiable list of the enabled and disabled monitor wait requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the list of all {@link MonitorWaitRequest} objects.
*
* @since 1.6
*/
List<MonitorWaitRequest> monitorWaitRequests();
/**
* Return an unmodifiable list of the enabled and disabled monitor waited requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* @return the list of all {@link MonitorWaitedRequest} objects.
*
* @since 1.6
*/
List<MonitorWaitedRequest> monitorWaitedRequests();
/**
* Return an unmodifiable list of the enabled and disabled VM death requests.
* This list is a live view of these requests and thus changes as requests
* are added and deleted.
* Note: the unsolicited VMDeathEvent does not have a
* corresponding request.
* @return the list of all {@link VMDeathRequest} objects.
*
* @since 1.4
*/
List<VMDeathRequest> vmDeathRequests();
}
| 21,913
|
Java
|
.java
| 504
| 37.628968
| 108
| 0.696696
|
keerath/openjdk-8-source
| 39
| 26
| 0
|
GPL-2.0
|
9/4/2024, 7:24:11 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 21,913
|
2,392,485
|
CellReader.java
|
OSBI_saiku-mondrian/src/main/java/mondrian/rolap/CellReader.java
|
/*
// This software is subject to the terms of the Eclipse Public License v1.0
// Agreement, available at the following URL:
// http://www.eclipse.org/legal/epl-v10.html.
// You must accept the terms of that agreement to use this software.
//
// Copyright (C) 2001-2005 Julian Hyde
// Copyright (C) 2005-2009 Pentaho and others
// All Rights Reserved.
//
// jhyde, 10 August, 2001
*/
package mondrian.rolap;
import mondrian.olap.Util;
/**
* A <code>CellReader</code> finds the cell value for the current context
* held by <code>evaluator</code>.
*
* <p>It returns:<ul>
* <li><code>null</code> if the source is unable to evaluate the cell (for
* example, <code>AggregatingCellReader</code> does not have the cell
* in its cache). This value should only be returned if the caller is
* expecting it.</li>
* <li>{@link Util#nullValue} if the cell evaluates to null</li>
* <li>{@link mondrian.olap.Util.ErrorCellValue} if the cell evaluates to an
* error</li>
* <li>an Object representing a value (often a {@link Double} or a {@link
* java.math.BigDecimal}), otherwise</li>
* </ul>
*
* @author jhyde
* @since 10 August, 2001
*/
interface CellReader {
/**
* Returns the value of the cell which has the context described by the
* evaluator.
* A cell could have optional compound member coordinates usually specified
* using the Aggregate function. These compound members are contained in the
* evaluator.
*
* <p>If no aggregation contains the required cell, returns null.
*
* <p>If the value is null, returns {@link Util#nullValue}.
*
* @return Cell value, or null if not found, or {@link Util#nullValue} if
* the value is null
*/
Object get(RolapEvaluator evaluator);
/**
* Returns the number of times this cell reader has told a lie
* (since creation), because the required cell value is not in the
* cache.
*/
int getMissCount();
/**
* @return whether thus cell reader has any pending cell requests that are
* not loaded yet.
*/
boolean isDirty();
}
// End CellReader.java
| 2,126
|
Java
|
.java
| 62
| 30.919355
| 80
| 0.693055
|
OSBI/saiku-mondrian
| 8
| 11
| 1
|
EPL-1.0
|
9/4/2024, 9:19:01 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 2,126
|
5,085,805
|
R.java
|
czhongzhi_WSX_KFQ/WSX_KFQ/KFQ4_B/library_p2refresh/build/generated/source/r/release/com/handmark/pulltorefresh/library/R.java
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.handmark.pulltorefresh.library;
public final class R {
public static final class anim {
public static int slide_in_from_bottom=0x7f040000;
public static int slide_in_from_top=0x7f040001;
public static int slide_out_to_bottom=0x7f040002;
public static int slide_out_to_top=0x7f040003;
}
public static final class attr {
/** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
*/
public static int ptrAdapterViewBackground=0x7f010010;
/** <p>Must be one or more (separated by '|') of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>rotate</code></td><td>0x0</td><td></td></tr>
<tr><td><code>flip</code></td><td>0x1</td><td></td></tr>
</table>
*/
public static int ptrAnimationStyle=0x7f01000c;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static int ptrDrawable=0x7f010006;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static int ptrDrawableBottom=0x7f010012;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static int ptrDrawableEnd=0x7f010008;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static int ptrDrawableStart=0x7f010007;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static int ptrDrawableTop=0x7f010011;
/** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
*/
public static int ptrHeaderBackground=0x7f010001;
/** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
*/
public static int ptrHeaderSubTextColor=0x7f010003;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static int ptrHeaderTextAppearance=0x7f01000a;
/** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
*/
public static int ptrHeaderTextColor=0x7f010002;
/** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a boolean value, either "<code>true</code>" or "<code>false</code>".
*/
public static int ptrListViewExtrasEnabled=0x7f01000e;
/** <p>Must be one or more (separated by '|') of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>disabled</code></td><td>0x0</td><td></td></tr>
<tr><td><code>pullFromStart</code></td><td>0x1</td><td></td></tr>
<tr><td><code>pullFromEnd</code></td><td>0x2</td><td></td></tr>
<tr><td><code>both</code></td><td>0x3</td><td></td></tr>
<tr><td><code>manualOnly</code></td><td>0x4</td><td></td></tr>
<tr><td><code>pullDownFromTop</code></td><td>0x1</td><td></td></tr>
<tr><td><code>pullUpFromBottom</code></td><td>0x2</td><td></td></tr>
</table>
*/
public static int ptrMode=0x7f010004;
/** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a boolean value, either "<code>true</code>" or "<code>false</code>".
*/
public static int ptrOverScroll=0x7f010009;
/** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
*/
public static int ptrRefreshableViewBackground=0x7f010000;
/** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a boolean value, either "<code>true</code>" or "<code>false</code>".
*/
public static int ptrRotateDrawableWhilePulling=0x7f01000f;
/** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a boolean value, either "<code>true</code>" or "<code>false</code>".
*/
public static int ptrScrollingWhileRefreshingEnabled=0x7f01000d;
/** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a boolean value, either "<code>true</code>" or "<code>false</code>".
*/
public static int ptrShowIndicator=0x7f010005;
/** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static int ptrSubHeaderTextAppearance=0x7f01000b;
}
public static final class dimen {
public static int header_footer_left_right_padding=0x7f050000;
public static int header_footer_top_bottom_padding=0x7f050001;
public static int indicator_corner_radius=0x7f050002;
public static int indicator_internal_padding=0x7f050003;
public static int indicator_right_padding=0x7f050004;
}
public static final class drawable {
public static int default_ptr_flip=0x7f020000;
public static int default_ptr_rotate=0x7f020001;
public static int indicator_arrow=0x7f020002;
public static int indicator_bg_bottom=0x7f020003;
public static int indicator_bg_top=0x7f020004;
}
public static final class id {
public static int both=0x7f060003;
public static int disabled=0x7f060004;
public static int fl_inner=0x7f06000c;
public static int flip=0x7f06000a;
public static int gridview=0x7f060000;
public static int manualOnly=0x7f060005;
public static int pullDownFromTop=0x7f060006;
public static int pullFromEnd=0x7f060007;
public static int pullFromStart=0x7f060008;
public static int pullUpFromBottom=0x7f060009;
public static int pull_to_refresh_image=0x7f06000d;
public static int pull_to_refresh_progress=0x7f06000e;
public static int pull_to_refresh_sub_text=0x7f060010;
public static int pull_to_refresh_text=0x7f06000f;
public static int rotate=0x7f06000b;
public static int scrollview=0x7f060001;
public static int webview=0x7f060002;
}
public static final class layout {
public static int pull_to_refresh_header_horizontal=0x7f030000;
public static int pull_to_refresh_header_vertical=0x7f030001;
}
public static final class string {
public static int pull_to_refresh_from_bottom_pull_label=0x7f070000;
public static int pull_to_refresh_from_bottom_refreshing_label=0x7f070001;
public static int pull_to_refresh_from_bottom_release_label=0x7f070002;
public static int pull_to_refresh_pull_label=0x7f070003;
public static int pull_to_refresh_refreshing_label=0x7f070004;
public static int pull_to_refresh_release_label=0x7f070005;
}
public static final class styleable {
/** Attributes that can be used with a PullToRefresh.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #PullToRefresh_ptrAdapterViewBackground com.handmark.pulltorefresh.library:ptrAdapterViewBackground}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrAnimationStyle com.handmark.pulltorefresh.library:ptrAnimationStyle}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrDrawable com.handmark.pulltorefresh.library:ptrDrawable}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrDrawableBottom com.handmark.pulltorefresh.library:ptrDrawableBottom}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrDrawableEnd com.handmark.pulltorefresh.library:ptrDrawableEnd}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrDrawableStart com.handmark.pulltorefresh.library:ptrDrawableStart}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrDrawableTop com.handmark.pulltorefresh.library:ptrDrawableTop}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrHeaderBackground com.handmark.pulltorefresh.library:ptrHeaderBackground}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrHeaderSubTextColor com.handmark.pulltorefresh.library:ptrHeaderSubTextColor}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrHeaderTextAppearance com.handmark.pulltorefresh.library:ptrHeaderTextAppearance}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrHeaderTextColor com.handmark.pulltorefresh.library:ptrHeaderTextColor}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrListViewExtrasEnabled com.handmark.pulltorefresh.library:ptrListViewExtrasEnabled}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrMode com.handmark.pulltorefresh.library:ptrMode}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrOverScroll com.handmark.pulltorefresh.library:ptrOverScroll}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrRefreshableViewBackground com.handmark.pulltorefresh.library:ptrRefreshableViewBackground}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrRotateDrawableWhilePulling com.handmark.pulltorefresh.library:ptrRotateDrawableWhilePulling}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrScrollingWhileRefreshingEnabled com.handmark.pulltorefresh.library:ptrScrollingWhileRefreshingEnabled}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrShowIndicator com.handmark.pulltorefresh.library:ptrShowIndicator}</code></td><td></td></tr>
<tr><td><code>{@link #PullToRefresh_ptrSubHeaderTextAppearance com.handmark.pulltorefresh.library:ptrSubHeaderTextAppearance}</code></td><td></td></tr>
</table>
@see #PullToRefresh_ptrAdapterViewBackground
@see #PullToRefresh_ptrAnimationStyle
@see #PullToRefresh_ptrDrawable
@see #PullToRefresh_ptrDrawableBottom
@see #PullToRefresh_ptrDrawableEnd
@see #PullToRefresh_ptrDrawableStart
@see #PullToRefresh_ptrDrawableTop
@see #PullToRefresh_ptrHeaderBackground
@see #PullToRefresh_ptrHeaderSubTextColor
@see #PullToRefresh_ptrHeaderTextAppearance
@see #PullToRefresh_ptrHeaderTextColor
@see #PullToRefresh_ptrListViewExtrasEnabled
@see #PullToRefresh_ptrMode
@see #PullToRefresh_ptrOverScroll
@see #PullToRefresh_ptrRefreshableViewBackground
@see #PullToRefresh_ptrRotateDrawableWhilePulling
@see #PullToRefresh_ptrScrollingWhileRefreshingEnabled
@see #PullToRefresh_ptrShowIndicator
@see #PullToRefresh_ptrSubHeaderTextAppearance
*/
public static final int[] PullToRefresh = {
0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003,
0x7f010004, 0x7f010005, 0x7f010006, 0x7f010007,
0x7f010008, 0x7f010009, 0x7f01000a, 0x7f01000b,
0x7f01000c, 0x7f01000d, 0x7f01000e, 0x7f01000f,
0x7f010010, 0x7f010011, 0x7f010012
};
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrAdapterViewBackground}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
@attr name com.handmark.pulltorefresh.library:ptrAdapterViewBackground
*/
public static int PullToRefresh_ptrAdapterViewBackground = 16;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrAnimationStyle}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>Must be one or more (separated by '|') of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>rotate</code></td><td>0x0</td><td></td></tr>
<tr><td><code>flip</code></td><td>0x1</td><td></td></tr>
</table>
@attr name com.handmark.pulltorefresh.library:ptrAnimationStyle
*/
public static int PullToRefresh_ptrAnimationStyle = 12;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrDrawable}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name com.handmark.pulltorefresh.library:ptrDrawable
*/
public static int PullToRefresh_ptrDrawable = 6;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrDrawableBottom}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name com.handmark.pulltorefresh.library:ptrDrawableBottom
*/
public static int PullToRefresh_ptrDrawableBottom = 18;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrDrawableEnd}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name com.handmark.pulltorefresh.library:ptrDrawableEnd
*/
public static int PullToRefresh_ptrDrawableEnd = 8;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrDrawableStart}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name com.handmark.pulltorefresh.library:ptrDrawableStart
*/
public static int PullToRefresh_ptrDrawableStart = 7;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrDrawableTop}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name com.handmark.pulltorefresh.library:ptrDrawableTop
*/
public static int PullToRefresh_ptrDrawableTop = 17;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrHeaderBackground}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
@attr name com.handmark.pulltorefresh.library:ptrHeaderBackground
*/
public static int PullToRefresh_ptrHeaderBackground = 1;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrHeaderSubTextColor}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
@attr name com.handmark.pulltorefresh.library:ptrHeaderSubTextColor
*/
public static int PullToRefresh_ptrHeaderSubTextColor = 3;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrHeaderTextAppearance}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name com.handmark.pulltorefresh.library:ptrHeaderTextAppearance
*/
public static int PullToRefresh_ptrHeaderTextAppearance = 10;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrHeaderTextColor}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
@attr name com.handmark.pulltorefresh.library:ptrHeaderTextColor
*/
public static int PullToRefresh_ptrHeaderTextColor = 2;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrListViewExtrasEnabled}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a boolean value, either "<code>true</code>" or "<code>false</code>".
@attr name com.handmark.pulltorefresh.library:ptrListViewExtrasEnabled
*/
public static int PullToRefresh_ptrListViewExtrasEnabled = 14;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrMode}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>Must be one or more (separated by '|') of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>disabled</code></td><td>0x0</td><td></td></tr>
<tr><td><code>pullFromStart</code></td><td>0x1</td><td></td></tr>
<tr><td><code>pullFromEnd</code></td><td>0x2</td><td></td></tr>
<tr><td><code>both</code></td><td>0x3</td><td></td></tr>
<tr><td><code>manualOnly</code></td><td>0x4</td><td></td></tr>
<tr><td><code>pullDownFromTop</code></td><td>0x1</td><td></td></tr>
<tr><td><code>pullUpFromBottom</code></td><td>0x2</td><td></td></tr>
</table>
@attr name com.handmark.pulltorefresh.library:ptrMode
*/
public static int PullToRefresh_ptrMode = 4;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrOverScroll}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a boolean value, either "<code>true</code>" or "<code>false</code>".
@attr name com.handmark.pulltorefresh.library:ptrOverScroll
*/
public static int PullToRefresh_ptrOverScroll = 9;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrRefreshableViewBackground}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
@attr name com.handmark.pulltorefresh.library:ptrRefreshableViewBackground
*/
public static int PullToRefresh_ptrRefreshableViewBackground = 0;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrRotateDrawableWhilePulling}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a boolean value, either "<code>true</code>" or "<code>false</code>".
@attr name com.handmark.pulltorefresh.library:ptrRotateDrawableWhilePulling
*/
public static int PullToRefresh_ptrRotateDrawableWhilePulling = 15;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrScrollingWhileRefreshingEnabled}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a boolean value, either "<code>true</code>" or "<code>false</code>".
@attr name com.handmark.pulltorefresh.library:ptrScrollingWhileRefreshingEnabled
*/
public static int PullToRefresh_ptrScrollingWhileRefreshingEnabled = 13;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrShowIndicator}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a boolean value, either "<code>true</code>" or "<code>false</code>".
@attr name com.handmark.pulltorefresh.library:ptrShowIndicator
*/
public static int PullToRefresh_ptrShowIndicator = 5;
/**
<p>This symbol is the offset where the {@link com.handmark.pulltorefresh.library.R.attr#ptrSubHeaderTextAppearance}
attribute's value can be found in the {@link #PullToRefresh} array.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
@attr name com.handmark.pulltorefresh.library:ptrSubHeaderTextAppearance
*/
public static int PullToRefresh_ptrSubHeaderTextAppearance = 11;
};
}
| 27,768
|
Java
|
.java
| 413
| 59.723971
| 178
| 0.651986
|
czhongzhi/WSX_KFQ
| 1
| 0
| 0
|
GPL-2.0
|
9/5/2024, 12:40:46 AM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 27,768
|
3,728,589
|
PhysicsCollisionObject.java
|
SteveSmith16384_AresDogfighter/jme_source/com/jme3/bullet/collision/PhysicsCollisionObject.java
|
/*
* Copyright (c) 2009-2012 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.bullet.collision;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.export.*;
import java.io.IOException;
/**
* Base class for collision objects (PhysicsRigidBody, PhysicsGhostObject)
* @author normenhansen
*/
public abstract class PhysicsCollisionObject implements Savable {
protected CollisionShape collisionShape;
public static final int COLLISION_GROUP_NONE = 0x00000000;
public static final int COLLISION_GROUP_01 = 0x00000001;
public static final int COLLISION_GROUP_02 = 0x00000002;
public static final int COLLISION_GROUP_03 = 0x00000004;
public static final int COLLISION_GROUP_04 = 0x00000008;
public static final int COLLISION_GROUP_05 = 0x00000010;
public static final int COLLISION_GROUP_06 = 0x00000020;
public static final int COLLISION_GROUP_07 = 0x00000040;
public static final int COLLISION_GROUP_08 = 0x00000080;
public static final int COLLISION_GROUP_09 = 0x00000100;
public static final int COLLISION_GROUP_10 = 0x00000200;
public static final int COLLISION_GROUP_11 = 0x00000400;
public static final int COLLISION_GROUP_12 = 0x00000800;
public static final int COLLISION_GROUP_13 = 0x00001000;
public static final int COLLISION_GROUP_14 = 0x00002000;
public static final int COLLISION_GROUP_15 = 0x00004000;
public static final int COLLISION_GROUP_16 = 0x00008000;
protected int collisionGroup = 0x00000001;
protected int collisionGroupsMask = 0x00000001;
private Object userObject;
/**
* Sets a CollisionShape to this physics object, note that the object should
* not be in the physics space when adding a new collision shape as it is rebuilt
* on the physics side.
* @param collisionShape the CollisionShape to set
*/
public void setCollisionShape(CollisionShape collisionShape) {
this.collisionShape = collisionShape;
}
/**
* @return the CollisionShape of this PhysicsNode, to be able to reuse it with
* other physics nodes (increases performance)
*/
public CollisionShape getCollisionShape() {
return collisionShape;
}
/**
* Returns the collision group for this collision shape
* @return
*/
public int getCollisionGroup() {
return collisionGroup;
}
/**
* Sets the collision group number for this physics object. <br>
* The groups are integer bit masks and some pre-made variables are available in CollisionObject.
* All physics objects are by default in COLLISION_GROUP_01.<br>
* Two object will collide when <b>one</b> of the partys has the
* collisionGroup of the other in its collideWithGroups set.
* @param collisionGroup the collisionGroup to set
*/
public void setCollisionGroup(int collisionGroup) {
this.collisionGroup = collisionGroup;
}
/**
* Add a group that this object will collide with.<br>
* Two object will collide when <b>one</b> of the partys has the
* collisionGroup of the other in its collideWithGroups set.<br>
* @param collisionGroup
*/
public void addCollideWithGroup(int collisionGroup) {
this.collisionGroupsMask = this.collisionGroupsMask | collisionGroup;
}
/**
* Remove a group from the list this object collides with.
* @param collisionGroup
*/
public void removeCollideWithGroup(int collisionGroup) {
this.collisionGroupsMask = this.collisionGroupsMask & ~collisionGroup;
}
/**
* Directly set the bitmask for collision groups that this object collides with.
* @param collisionGroups
*/
public void setCollideWithGroups(int collisionGroups) {
this.collisionGroupsMask = collisionGroups;
}
/**
* Gets the bitmask of collision groups that this object collides with.
* @return
*/
public int getCollideWithGroups() {
return collisionGroupsMask;
}
/**
* @return the userObject
*/
public Object getUserObject() {
return userObject;
}
/**
* @param userObject the userObject to set
*/
public void setUserObject(Object userObject) {
this.userObject = userObject;
}
@Override
public void write(JmeExporter e) throws IOException {
OutputCapsule capsule = e.getCapsule(this);
capsule.write(collisionGroup, "collisionGroup", 0x00000001);
capsule.write(collisionGroupsMask, "collisionGroupsMask", 0x00000001);
capsule.write(collisionShape, "collisionShape", null);
}
@Override
public void read(JmeImporter e) throws IOException {
InputCapsule capsule = e.getCapsule(this);
collisionGroup = capsule.readInt("collisionGroup", 0x00000001);
collisionGroupsMask = capsule.readInt("collisionGroupsMask", 0x00000001);
CollisionShape shape = (CollisionShape) capsule.readSavable("collisionShape", null);
collisionShape = shape;
}
}
| 6,562
|
Java
|
.java
| 153
| 37.915033
| 101
| 0.735533
|
SteveSmith16384/AresDogfighter
| 3
| 0
| 0
|
GPL-3.0
|
9/4/2024, 11:40:04 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 6,562
|
4,257,317
|
NullPrimitiveTests.java
|
rockleeprc_sourcecode/spring-framework/spring-aop/src/test/java/org/springframework/aop/framework/NullPrimitiveTests.java
|
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.aop.AopInvocationException;
import static org.junit.Assert.*;
/**
* Test for SPR-4675. A null value returned from around advice is very hard to debug if
* the caller expects a primitive.
*
* @author Dave Syer
*/
public class NullPrimitiveTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
static interface Foo {
int getValue();
}
@Test
public void testNullPrimitiveWithJdkProxy() {
class SimpleFoo implements Foo {
@Override
public int getValue() {
return 100;
}
}
SimpleFoo target = new SimpleFoo();
ProxyFactory factory = new ProxyFactory(target);
factory.addAdvice(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
return null;
}
});
Foo foo = (Foo) factory.getProxy();
thrown.expect(AopInvocationException.class);
thrown.expectMessage("Foo.getValue()");
assertEquals(0, foo.getValue());
}
public static class Bar {
public int getValue() {
return 100;
}
}
@Test
public void testNullPrimitiveWithCglibProxy() {
Bar target = new Bar();
ProxyFactory factory = new ProxyFactory(target);
factory.addAdvice(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
return null;
}
});
Bar bar = (Bar) factory.getProxy();
thrown.expect(AopInvocationException.class);
thrown.expectMessage("Bar.getValue()");
assertEquals(0, bar.getValue());
}
}
| 2,365
|
Java
|
.java
| 77
| 27.987013
| 87
| 0.762115
|
rockleeprc/sourcecode
| 2
| 2
| 0
|
GPL-3.0
|
9/5/2024, 12:07:03 AM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 2,365
|
1,022,940
|
WeightedOutcome.java
|
joliciel-informatique_talismane/talismane_utils/src/main/java/com/joliciel/talismane/utils/WeightedOutcome.java
|
///////////////////////////////////////////////////////////////////////////////
//Copyright (C) 2014 Joliciel Informatique
//
//This file is part of Talismane.
//
//Talismane is free software: you can redistribute it and/or modify
//it under the terms of the GNU Affero General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Talismane 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 Affero General Public License for more details.
//
//You should have received a copy of the GNU Affero General Public License
//along with Talismane. If not, see <http://www.gnu.org/licenses/>.
//////////////////////////////////////////////////////////////////////////////
package com.joliciel.talismane.utils;
import java.io.Serializable;
/**
* An outcome/value pair that orders automatically in descending order (from
* highest to lowest weight).
*
* @author Assaf Urieli
*
*/
public class WeightedOutcome<T> implements Comparable<WeightedOutcome<T>>, Serializable {
private static final long serialVersionUID = 6970237630148498476L;
private T outcome;
private double weight;
private transient double weightLog;
private transient boolean weightLogCalculated = false;
public WeightedOutcome(T outcome, double weight) {
this.outcome = outcome;
this.weight = weight;
}
public void setOutcome(T outcome) {
this.outcome = outcome;
}
public void setWeight(double value) {
this.weight = value;
this.weightLogCalculated = false;
}
public T getOutcome() {
return outcome;
}
public double getWeight() {
return weight;
}
public double getWeightLog() {
if (!weightLogCalculated) {
weightLog = Math.log(weight);
weightLogCalculated = true;
}
return weightLog;
}
@Override
public int compareTo(WeightedOutcome<T> o) {
if (this.getWeight() < o.getWeight()) {
return 1;
} else if (this.getWeight() > o.getWeight()) {
return -1;
} else {
int nameCompare = this.getOutcome().toString().compareTo(o.getOutcome().toString());
if (nameCompare != 0)
return nameCompare;
return this.hashCode() - o.hashCode();
}
}
@Override
public String toString() {
return "[" + outcome + "," + weight + "]";
}
}
| 2,468
|
Java
|
.java
| 75
| 29.586667
| 90
| 0.673384
|
joliciel-informatique/talismane
| 49
| 14
| 6
|
AGPL-3.0
|
9/4/2024, 7:11:02 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 2,468
|
1,514,122
|
Block.java
|
semuxproject_evm/src/main/java/org/ethereum/vm/client/Block.java
|
/**
* Copyright (c) [2018] [ The Semux Developers ]
* Copyright (c) [2016] [ <ether.camp> ]
*
* This program 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.vm.client;
import java.math.BigInteger;
public interface Block {
long getGasLimit();
byte[] getParentHash();
byte[] getCoinbase();
long getTimestamp();
long getNumber();
BigInteger getDifficulty();
}
| 1,020
|
Java
|
.java
| 27
| 35
| 78
| 0.739086
|
semuxproject/evm
| 28
| 10
| 5
|
LGPL-3.0
|
9/4/2024, 7:55:26 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 1,020
|
4,127,111
|
ReferenceSystem.java
|
xionghuiCoder_db4o/src/main/java/com/db4o/internal/references/ReferenceSystem.java
|
/* 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.internal.references;
import com.db4o.foundation.*;
import com.db4o.internal.*;
/**
* @exclude
*/
public interface ReferenceSystem {
public void addNewReference(ObjectReference ref);
public void addExistingReference(ObjectReference ref);
public void commit();
public ObjectReference referenceForId(int id);
public ObjectReference referenceForObject(Object obj);
public void removeReference(ObjectReference ref);
public void rollback();
public void traverseReferences(Visitor4 visitor);
public void discarded();
}
| 1,234
|
Java
|
.java
| 28
| 42
| 71
| 0.810447
|
xionghuiCoder/db4o
| 2
| 1
| 0
|
AGPL-3.0
|
9/5/2024, 12:03:50 AM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 1,234
|
1,543,263
|
BCMotionEvent5.java
|
lowtraxx_TSVNC/TSVNC/src/main/java/com/antlersoft/android/bc/BCMotionEvent5.java
|
/**
* Copyright (c) 2010 Michael A. MacDonald
*/
package com.antlersoft.android.bc;
import android.view.MotionEvent;
/**
* @author Michael A. MacDonald
*
*/
class BCMotionEvent5 implements IBCMotionEvent {
/* (non-Javadoc)
* @see com.antlersoft.android.bc.IBCMotionEvent#getPointerCount(android.view.MotionEvent)
*/
@Override
public int getPointerCount(MotionEvent evt) {
return evt.getPointerCount();
}
}
| 425
|
Java
|
.java
| 18
| 21.555556
| 91
| 0.769231
|
lowtraxx/TSVNC
| 25
| 3
| 7
|
GPL-2.0
|
9/4/2024, 7:58:20 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 425
|
415,541
|
MIDletStateChangeException.java
|
mozilla_pluotsorbet/java/midp/javax/microedition/midlet/MIDletStateChangeException.java
|
/*
*
*
* Copyright 1990-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* 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 version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package javax.microedition.midlet;
import java.lang.String;
/**
* Signals that a requested <code>MIDlet</code> state change failed. This
* exception is thrown by the <code>MIDlet</code> in response to
* state change calls
* into the application via the <code>MIDlet</code> interface
*
* @see MIDlet
* @since MIDP 1.0
*/
public class MIDletStateChangeException extends Exception {
/**
* Constructs an exception with no specified detail message.
*/
public MIDletStateChangeException() {}
/**
* Constructs an exception with the specified detail message.
*
* @param s the detail message
*/
public MIDletStateChangeException(String s) {
super(s);
}
}
| 1,760
|
Java
|
.java
| 50
| 32.22
| 73
| 0.740741
|
mozilla/pluotsorbet
| 237
| 46
| 290
|
GPL-2.0
|
9/4/2024, 7:07:11 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| true
| true
| 1,760
|
1,727,098
|
TRTrackerBTScraperImpl.java
|
academictorrents_AcademicTorrents-Downloader/frostwire-merge/org/gudy/azureus2/core3/tracker/client/impl/bt/TRTrackerBTScraperImpl.java
|
/*
* Created on 14-Feb-2005
* Created by Paul Gardner
* Copyright (C) 2004, 2005, 2006 Aelitis, All Rights Reserved.
*
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* AELITIS, SAS au capital de 46,603.30 euros
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*
*/
package org.gudy.azureus2.core3.tracker.client.impl.bt;
import java.net.URL;
import org.gudy.azureus2.core3.internat.MessageText;
import org.gudy.azureus2.core3.torrent.TOTorrent;
import org.gudy.azureus2.core3.tracker.client.TRTrackerAnnouncer;
import org.gudy.azureus2.core3.tracker.client.TRTrackerScraperResponse;
import org.gudy.azureus2.core3.tracker.client.impl.TRTrackerScraperImpl;
import org.gudy.azureus2.core3.tracker.client.impl.TRTrackerScraperResponseImpl;
import org.gudy.azureus2.core3.util.AEMonitor;
import org.gudy.azureus2.core3.util.TorrentUtils;
import org.gudy.azureus2.plugins.download.DownloadScrapeResult;
/**
* @author parg
*
*/
public class
TRTrackerBTScraperImpl
{
protected static TRTrackerBTScraperImpl singleton;
protected static AEMonitor class_mon = new AEMonitor( "TRTrackerBTScraper" );
private TRTrackerScraperImpl scraper;
private TrackerChecker tracker_checker;
public static TRTrackerBTScraperImpl
create(
TRTrackerScraperImpl _scraper )
{
try{
class_mon.enter();
if ( singleton == null ){
singleton = new TRTrackerBTScraperImpl( _scraper );
}
return( singleton );
}finally{
class_mon.exit();
}
}
protected
TRTrackerBTScraperImpl(
TRTrackerScraperImpl _scraper )
{
scraper = _scraper;
tracker_checker = new TrackerChecker( this );
}
protected TRTrackerScraperImpl
getScraper()
{
return( scraper );
}
public void
setScrape(
TOTorrent torrent,
URL url,
DownloadScrapeResult result )
{
if ( torrent != null && result != null ){
TRTrackerScraperResponseImpl resp = tracker_checker.getHashData( torrent, url );
URL result_url = result.getURL();
boolean update_is_dht = TorrentUtils.isDecentralised( result_url );
// only override details if underlying scrape is failing or this is an update
// to an existing dht-backup result
if ( resp != null &&
( resp.getStatus() == TRTrackerScraperResponse.ST_ERROR ||
( resp.isDHTBackup() && update_is_dht ))){
resp.setDHTBackup( update_is_dht );
resp.setScrapeStartTime( result.getScrapeStartTime());
// leave nextScrapeStartTime alone as we still want the existing
// scraping mechanism to kick in and check the torrent's tracker
resp.setStatus(
result.getResponseType()==DownloadScrapeResult.RT_SUCCESS?
TRTrackerScraperResponse.ST_ONLINE:
TRTrackerScraperResponse.ST_ERROR,
result.getStatus() + " (" + (update_is_dht?MessageText.getString( "dht.backup.only" ):(result_url==null?"<null>":result_url.getHost())) + ")");
// call this last before dispatching listeners as it does another dispatch by itself ~~
resp.setSeedsPeers( result.getSeedCount(), result.getNonSeedCount());
scraper.scrapeReceived( resp );
}
}
}
public TRTrackerScraperResponse
scrape(
TOTorrent torrent,
URL target_url,
boolean force )
{
if (torrent == null){
return null;
}
if ( force ){
tracker_checker.syncUpdate( torrent, target_url );
}
TRTrackerScraperResponse res = tracker_checker.getHashData( torrent, target_url );
// System.out.println( "scrape: " + torrent + " -> " + (res==null?"null":""+res.getSeeds()));
return( res );
}
public TRTrackerScraperResponse
peekScrape(
TOTorrent torrent,
URL target_url )
{
if ( torrent == null ){
return null;
}
TRTrackerScraperResponse res = tracker_checker.peekHashData( torrent, target_url );
return( res );
}
public TRTrackerScraperResponse
scrape(
TRTrackerAnnouncer tracker_client )
{
TRTrackerScraperResponse res = tracker_checker.getHashData( tracker_client );
// System.out.println( "scrape: " + tracker_client + " -> " + (res==null?"null":""+res.getSeeds()));
return( res );
}
public void
remove(
TOTorrent torrent )
{
tracker_checker.removeHash( torrent );
}
}
| 4,916
|
Java
|
.java
| 141
| 31.170213
| 149
| 0.741672
|
academictorrents/AcademicTorrents-Downloader
| 16
| 2
| 0
|
GPL-2.0
|
9/4/2024, 8:16:18 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 4,916
|
714,024
|
DecisionAlternative_XLOAD_GETX_Resolved.java
|
pietrobraione_jbse/src/main/java/jbse/tree/DecisionAlternative_XLOAD_GETX_Resolved.java
|
package jbse.tree;
import static jbse.mem.Util.isSymbolicReference;
import jbse.val.Value;
/**
* {@link DecisionAlternative_XLOAD_GETX} for the case where
* the value loaded on the operand stack is a previously resolved
* symbolic reference or a primitive (either symbolic or concrete)
* value.
*
* @author Pietro Braione
*/
public final class DecisionAlternative_XLOAD_GETX_Resolved
extends DecisionAlternative_XLOAD_GETX implements DecisionAlternative_XYLOAD_GETX_Resolved {
private static final int HASH_CODE = 1;
private final Value valueToLoad;
private final boolean isConcrete;
public DecisionAlternative_XLOAD_GETX_Resolved(Value valueToLoad) {
super(ALT_CODE + "_Resolved", HASH_CODE);
this.valueToLoad = valueToLoad;
this.isConcrete = (valueToLoad == null ? true : !isSymbolicReference(valueToLoad)); //a null valueToLoad is only produced by Algo_INVOKEMETA_Metacircular
}
@Override
public Value getValueToLoad() {
return this.valueToLoad;
}
@Override
public void accept(VisitorDecisionAlternative_XLOAD_GETX v) throws Exception {
v.visitDecisionAlternative_XLOAD_GETX_Resolved(this);
}
@Override
public boolean trivial() {
return true;
}
@Override
public boolean concrete() {
return this.isConcrete;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return true;
}
@Override
public int hashCode() {
return HASH_CODE;
}
}
| 1,719
|
Java
|
.java
| 55
| 25.363636
| 161
| 0.67896
|
pietrobraione/jbse
| 102
| 29
| 10
|
GPL-3.0
|
9/4/2024, 7:08:19 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 1,719
|
1,728,156
|
NetworkConnection.java
|
academictorrents_AcademicTorrents-Downloader/vuze/com/aelitis/azureus/core/networkmanager/NetworkConnection.java
|
/*
* Created on Feb 21, 2005
* Created by Alon Rohter
* Copyright (C) 2004-2005 Aelitis, All Rights Reserved.
*
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* AELITIS, SAS au capital de 46,603.30 euros
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*
*/
package com.aelitis.azureus.core.networkmanager;
import java.nio.ByteBuffer;
/**
* Represents a managed network connection, over which messages can be sent and received.
*/
public interface
NetworkConnection
extends NetworkConnectionBase
{
/**
* Connect this connection's transport, i.e. establish the network connection.
* If this connection is already established (from an incoming connection for example),
* then this provides a mechanism to register the connection listener, in which case
* connectSuccess() will be called immediately.
* @param listener notified on connect success or failure
*/
public void connect( int priority, ConnectionListener listener );
public void connect( ByteBuffer initial_outbound_data, int priority, ConnectionListener listener );
/**
* Close and shutdown this connection.
*/
public void close( String reason );
/**
* Begin processing incoming and outgoing message queues.
* @param upload_group upload rate limit group to use
* @param download_group download rate limit group to use
*/
public void startMessageProcessing();
/**
* Upgrade the connection to high-speed transfer processing.
* @param enable true for high-speed processing, false for normal processing
*/
public void enableEnhancedMessageProcessing( boolean enable, int partition_id );
/**
* Decouples the transport from this network connection so it can be reused
* @return null if detach failed
*/
public Transport detachTransport();
/**
* Get the connection's data transport interface.
* @return the transport - MAY BE NULL if not yet fully connected
*/
public Transport getTransport();
public boolean isConnected();
public Object
setUserData(
Object key,
Object value );
public Object
getUserData(
Object key );
/**
* Listener for notification of connection events.
*/
public interface ConnectionListener {
/**
* The connection establishment process has started,
* i.e. the connection is actively being attempted.
* @return modified connect timeout
*/
public int connectStarted( int default_connect_timeout );
/**
* The connection attempt succeeded.
* The connection is now established.
* NOTE: Called only during initial connect attempt.
*/
public void connectSuccess( ByteBuffer remaining_initial_data );
/**
* The connection attempt failed.
* NOTE: Called only during initial connect attempt.
* @param failure_msg failure reason
*/
public void connectFailure( Throwable failure_msg );
/**
* Handle exception thrown by this connection.
* NOTE: Can be called at any time during connection lifetime.
* @param error exception
*/
public void exceptionThrown( Throwable error );
public Object getConnectionProperty( String property_name);
public String
getDescription();
}
}
| 3,949
|
Java
|
.java
| 105
| 33.352381
| 101
| 0.738417
|
academictorrents/AcademicTorrents-Downloader
| 16
| 2
| 0
|
GPL-2.0
|
9/4/2024, 8:16:18 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 3,949
|
3,925,080
|
ThresholdingOutputStream.java
|
wiyarmir_GPT-Organize/src/org/apache/commons/io/output/ThresholdingOutputStream.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
/**
* An output stream which triggers an event when a specified number of bytes of
* data have been written to it. The event can be used, for example, to throw
* an exception if a maximum has been reached, or to switch the underlying
* stream type when the threshold is exceeded.
* <p>
* This class overrides all <code>OutputStream</code> methods. However, these
* overrides ultimately call the corresponding methods in the underlying output
* stream implementation.
* <p>
* NOTE: This implementation may trigger the event <em>before</em> the threshold
* is actually reached, since it triggers when a pending write operation would
* cause the threshold to be exceeded.
*
* @author <a href="mailto:martinc@apache.org">Martin Cooper</a>
*
* @version $Id: ThresholdingOutputStream.java 540714 2007-05-22 19:39:44Z niallp $
*/
public abstract class ThresholdingOutputStream
extends OutputStream
{
// ----------------------------------------------------------- Data members
/**
* The threshold at which the event will be triggered.
*/
private int threshold;
/**
* The number of bytes written to the output stream.
*/
private long written;
/**
* Whether or not the configured threshold has been exceeded.
*/
private boolean thresholdExceeded;
// ----------------------------------------------------------- Constructors
/**
* Constructs an instance of this class which will trigger an event at the
* specified threshold.
*
* @param threshold The number of bytes at which to trigger an event.
*/
public ThresholdingOutputStream(int threshold)
{
this.threshold = threshold;
}
// --------------------------------------------------- OutputStream methods
/**
* Writes the specified byte to this output stream.
*
* @param b The byte to be written.
*
* @exception IOException if an error occurs.
*/
public void write(int b) throws IOException
{
checkThreshold(1);
getStream().write(b);
written++;
}
/**
* Writes <code>b.length</code> bytes from the specified byte array to this
* output stream.
*
* @param b The array of bytes to be written.
*
* @exception IOException if an error occurs.
*/
public void write(byte b[]) throws IOException
{
checkThreshold(b.length);
getStream().write(b);
written += b.length;
}
/**
* Writes <code>len</code> bytes from the specified byte array starting at
* offset <code>off</code> to this output stream.
*
* @param b The byte array from which the data will be written.
* @param off The start offset in the byte array.
* @param len The number of bytes to write.
*
* @exception IOException if an error occurs.
*/
public void write(byte b[], int off, int len) throws IOException
{
checkThreshold(len);
getStream().write(b, off, len);
written += len;
}
/**
* Flushes this output stream and forces any buffered output bytes to be
* written out.
*
* @exception IOException if an error occurs.
*/
public void flush() throws IOException
{
getStream().flush();
}
/**
* Closes this output stream and releases any system resources associated
* with this stream.
*
* @exception IOException if an error occurs.
*/
public void close() throws IOException
{
try
{
flush();
}
catch (IOException ignored)
{
// ignore
}
getStream().close();
}
// --------------------------------------------------------- Public methods
/**
* Returns the threshold, in bytes, at which an event will be triggered.
*
* @return The threshold point, in bytes.
*/
public int getThreshold()
{
return threshold;
}
/**
* Returns the number of bytes that have been written to this output stream.
*
* @return The number of bytes written.
*/
public long getByteCount()
{
return written;
}
/**
* Determines whether or not the configured threshold has been exceeded for
* this output stream.
*
* @return <code>true</code> if the threshold has been reached;
* <code>false</code> otherwise.
*/
public boolean isThresholdExceeded()
{
return (written > threshold);
}
// ------------------------------------------------------ Protected methods
/**
* Checks to see if writing the specified number of bytes would cause the
* configured threshold to be exceeded. If so, triggers an event to allow
* a concrete implementation to take action on this.
*
* @param count The number of bytes about to be written to the underlying
* output stream.
*
* @exception IOException if an error occurs.
*/
protected void checkThreshold(int count) throws IOException
{
if (!thresholdExceeded && (written + count > threshold))
{
thresholdExceeded = true;
thresholdReached();
}
}
/**
* Resets the byteCount to zero. You can call this from
* {@link #thresholdReached()} if you want the event to be triggered again.
*/
protected void resetByteCount()
{
this.thresholdExceeded = false;
this.written = 0;
}
// ------------------------------------------------------- Abstract methods
/**
* Returns the underlying output stream, to which the corresponding
* <code>OutputStream</code> methods in this class will ultimately delegate.
*
* @return The underlying output stream.
*
* @exception IOException if an error occurs.
*/
protected abstract OutputStream getStream() throws IOException;
/**
* Indicates that the configured threshold has been reached, and that a
* subclass should take whatever action necessary on this event. This may
* include changing the underlying output stream.
*
* @exception IOException if an error occurs.
*/
protected abstract void thresholdReached() throws IOException;
}
| 7,237
|
Java
|
.java
| 213
| 28.323944
| 83
| 0.631089
|
wiyarmir/GPT-Organize
| 2
| 0
| 0
|
GPL-3.0
|
9/4/2024, 11:53:14 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 7,237
|
1,218,637
|
ServiceRepresentationsResource.java
|
eclipse-archived_concierge/bundles/org.eclipse.concierge.service.rest/src/org/osgi/impl/service/rest/resources/ServiceRepresentationsResource.java
|
/*******************************************************************************
* Copyright (c) 2015 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Jan S. Rellermeyer, IBM Research - initial API and implementation
*******************************************************************************/
package org.osgi.impl.service.rest.resources;
import org.osgi.framework.ServiceReference;
import org.osgi.impl.service.rest.PojoReflector;
import org.osgi.impl.service.rest.RestService;
import org.osgi.impl.service.rest.pojos.ServiceRepresentationList;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.Variant;
/**
* The service representations resource, a list of the full representations of
* all services.
*
* @author Jan S. Rellermeyer, IBM Research
*/
public class ServiceRepresentationsResource extends
AbstractOSGiResource<ServiceRepresentationList> {
private static final MediaType MEDIA_TYPE = MediaType.valueOf("application/org.osgi.services.representations");
public ServiceRepresentationsResource() {
super(PojoReflector.getReflector(ServiceRepresentationList.class), MEDIA_TYPE);
}
@Override
public Representation get(final Variant variant) {
try {
final String filter = getQuery().getFirstValue(RestService.FILTER_ID_KEY);
final ServiceReference<?>[] srefs = getBundleContext()
.getAllServiceReferences(null, filter);
return getRepresentation(new ServiceRepresentationList(srefs), variant);
} catch (final Exception e) {
return ERROR(e, variant);
}
}
}
| 2,006
|
Java
|
.java
| 45
| 42.288889
| 112
| 0.736438
|
eclipse-archived/concierge
| 33
| 22
| 24
|
EPL-1.0
|
9/4/2024, 7:25:01 PM (Europe/Amsterdam)
| false
| true
| false
| true
| true
| false
| true
| true
| 2,006
|
1,662,503
|
ObjectSerializer.java
|
mdaniel_svn-caucho-com-resin/modules/hessian/src/com/caucho/hessian/io/ObjectSerializer.java
|
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
/**
* Serializing an object.
*/
public interface ObjectSerializer {
public Serializer getObjectSerializer();
}
| 2,411
|
Java
|
.java
| 55
| 41.854545
| 74
| 0.761581
|
mdaniel/svn-caucho-com-resin
| 18
| 17
| 0
|
GPL-2.0
|
9/4/2024, 8:12:19 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 2,411
|
4,762,802
|
lr_parser.java
|
k9ert_struktor/src/java_cup/runtime/lr_parser.java
|
package java_cup.runtime;
import java.util.Stack;
/** This class implements a skeleton table driven LR parser. In general,
* LR parsers are a form of bottom up shift-reduce parsers. Shift-reduce
* parsers act by shifting input onto a parse stack until the Symbols
* matching the right hand side of a production appear on the top of the
* stack. Once this occurs, a reduce is performed. This involves removing
* the Symbols corresponding to the right hand side of the production
* (the so called "handle") and replacing them with the non-terminal from
* the left hand side of the production. <p>
*
* To control the decision of whether to shift or reduce at any given point,
* the parser uses a state machine (the "viable prefix recognition machine"
* built by the parser generator). The current state of the machine is placed
* on top of the parse stack (stored as part of a Symbol object representing
* a terminal or non terminal). The parse action table is consulted
* (using the current state and the current lookahead Symbol as indexes) to
* determine whether to shift or to reduce. When the parser shifts, it
* changes to a new state by pushing a new Symbol (containing a new state)
* onto the stack. When the parser reduces, it pops the handle (right hand
* side of a production) off the stack. This leaves the parser in the state
* it was in before any of those Symbols were matched. Next the reduce-goto
* table is consulted (using the new state and current lookahead Symbol as
* indexes) to determine a new state to go to. The parser then shifts to
* this goto state by pushing the left hand side Symbol of the production
* (also containing the new state) onto the stack.<p>
*
* This class actually provides four LR parsers. The methods parse() and
* debug_parse() provide two versions of the main parser (the only difference
* being that debug_parse() emits debugging trace messages as it parses).
* In addition to these main parsers, the error recovery mechanism uses two
* more. One of these is used to simulate "parsing ahead" in the input
* without carrying out actions (to verify that a potential error recovery
* has worked), and the other is used to parse through buffered "parse ahead"
* input in order to execute all actions and re-synchronize the actual parser
* configuration.<p>
*
* This is an abstract class which is normally filled out by a subclass
* generated by the JavaCup parser generator. In addition to supplying
* the actual parse tables, generated code also supplies methods which
* invoke various pieces of user supplied code, provide access to certain
* special Symbols (e.g., EOF and error), etc. Specifically, the following
* abstract methods are normally supplied by generated code:
* <dl compact>
* <dt> short[][] production_table()
* <dd> Provides a reference to the production table (indicating the index of
* the left hand side non terminal and the length of the right hand side
* for each production in the grammar).
* <dt> short[][] action_table()
* <dd> Provides a reference to the parse action table.
* <dt> short[][] reduce_table()
* <dd> Provides a reference to the reduce-goto table.
* <dt> int start_state()
* <dd> Indicates the index of the start state.
* <dt> int start_production()
* <dd> Indicates the index of the starting production.
* <dt> int EOF_sym()
* <dd> Indicates the index of the EOF Symbol.
* <dt> int error_sym()
* <dd> Indicates the index of the error Symbol.
* <dt> Symbol do_action()
* <dd> Executes a piece of user supplied action code. This always comes at
* the point of a reduce in the parse, so this code also allocates and
* fills in the left hand side non terminal Symbol object that is to be
* pushed onto the stack for the reduce.
* <dt> void init_actions()
* <dd> Code to initialize a special object that encapsulates user supplied
* actions (this object is used by do_action() to actually carry out the
* actions).
* </dl>
*
* In addition to these routines that <i>must</i> be supplied by the
* generated subclass there are also a series of routines that <i>may</i>
* be supplied. These include:
* <dl>
* <dt> Symbol scan()
* <dd> Used to get the next input Symbol from the scanner.
* <dt> Scanner getScanner()
* <dd> Used to provide a scanner for the default implementation of
* scan().
* <dt> int error_sync_size()
* <dd> This determines how many Symbols past the point of an error
* must be parsed without error in order to consider a recovery to
* be valid. This defaults to 3. Values less than 2 are not
* recommended.
* <dt> void report_error(String message, Object info)
* <dd> This method is called to report an error. The default implementation
* simply prints a message to System.err and where the error occurred.
* This method is often replaced in order to provide a more sophisticated
* error reporting mechanism.
* <dt> void report_fatal_error(String message, Object info)
* <dd> This method is called when a fatal error that cannot be recovered from
* is encountered. In the default implementation, it calls
* report_error() to emit a message, then throws an exception.
* <dt> void syntax_error(Symbol cur_token)
* <dd> This method is called as soon as syntax error is detected (but
* before recovery is attempted). In the default implementation it
* invokes: report_error("Syntax error", null);
* <dt> void unrecovered_syntax_error(Symbol cur_token)
* <dd> This method is called if syntax error recovery fails. In the default
* implementation it invokes:<br>
* report_fatal_error("Couldn't repair and continue parse", null);
* </dl>
*
* @see java_cup.runtime.Symbol
* @see java_cup.runtime.Symbol
* @see java_cup.runtime.virtual_parse_stack
* @version last updated: 7/3/96
* @author Frank Flannery
*/
public abstract class lr_parser {
/*-----------------------------------------------------------*/
/*--- Constructor(s) ----------------------------------------*/
/*-----------------------------------------------------------*/
/**
* Simple constructor.
*/
public lr_parser() {
}
/**
* Constructor that sets the default scanner. [CSA/davidm]
*/
public lr_parser(Scanner s) {
this(s,new DefaultSymbolFactory()); // TUM 20060327 old cup v10 Symbols as default
}
/**
* Constructor that sets the default scanner and a SymbolFactory
*/
public lr_parser(Scanner s, SymbolFactory symfac) {
this(); // in case default constructor someday does something
symbolFactory = symfac;
setScanner(s);
}
public SymbolFactory symbolFactory;// = new DefaultSymbolFactory();
/**
* Whenever creation of a new Symbol is necessary, one should use this factory.
*/
public SymbolFactory getSymbolFactory(){
return symbolFactory;
}
/*-----------------------------------------------------------*/
/*--- (Access to) Static (Class) Variables ------------------*/
/*-----------------------------------------------------------*/
/** The default number of Symbols after an error we much match to consider
* it recovered from.
*/
protected final static int _error_sync_size = 3;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** The number of Symbols after an error we much match to consider it
* recovered from.
*/
protected int error_sync_size() {return _error_sync_size; }
/*-----------------------------------------------------------*/
/*--- (Access to) Instance Variables ------------------------*/
/*-----------------------------------------------------------*/
/** Table of production information (supplied by generated subclass).
* This table contains one entry per production and is indexed by
* the negative-encoded values (reduce actions) in the action_table.
* Each entry has two parts, the index of the non-terminal on the
* left hand side of the production, and the number of Symbols
* on the right hand side.
*/
public abstract short[][] production_table();
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** The action table (supplied by generated subclass). This table is
* indexed by state and terminal number indicating what action is to
* be taken when the parser is in the given state (i.e., the given state
* is on top of the stack) and the given terminal is next on the input.
* States are indexed using the first dimension, however, the entries for
* a given state are compacted and stored in adjacent index, value pairs
* which are searched for rather than accessed directly (see get_action()).
* The actions stored in the table will be either shifts, reduces, or
* errors. Shifts are encoded as positive values (one greater than the
* state shifted to). Reduces are encoded as negative values (one less
* than the production reduced by). Error entries are denoted by zero.
*
* @see java_cup.runtime.lr_parser#get_action
*/
public abstract short[][] action_table();
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** The reduce-goto table (supplied by generated subclass). This
* table is indexed by state and non-terminal number and contains
* state numbers. States are indexed using the first dimension, however,
* the entries for a given state are compacted and stored in adjacent
* index, value pairs which are searched for rather than accessed
* directly (see get_reduce()). When a reduce occurs, the handle
* (corresponding to the RHS of the matched production) is popped off
* the stack. The new top of stack indicates a state. This table is
* then indexed by that state and the LHS of the reducing production to
* indicate where to "shift" to.
*
* @see java_cup.runtime.lr_parser#get_reduce
*/
public abstract short[][] reduce_table();
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** The index of the start state (supplied by generated subclass). */
public abstract int start_state();
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** The index of the start production (supplied by generated subclass). */
public abstract int start_production();
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** The index of the end of file terminal Symbol (supplied by generated
* subclass).
*/
public abstract int EOF_sym();
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** The index of the special error Symbol (supplied by generated subclass). */
public abstract int error_sym();
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Internal flag to indicate when parser should quit. */
protected boolean _done_parsing = false;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** This method is called to indicate that the parser should quit. This is
* normally called by an accept action, but can be used to cancel parsing
* early in other circumstances if desired.
*/
public void done_parsing()
{
_done_parsing = true;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/* Global parse state shared by parse(), error recovery, and
* debugging routines */
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Indication of the index for top of stack (for use by actions). */
protected int tos;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** The current lookahead Symbol. */
protected Symbol cur_token;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** The parse stack itself. */
protected Stack stack = new Stack();
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Direct reference to the production table. */
protected short[][] production_tab;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Direct reference to the action table. */
protected short[][] action_tab;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Direct reference to the reduce-goto table. */
protected short[][] reduce_tab;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** This is the scanner object used by the default implementation
* of scan() to get Symbols. To avoid name conflicts with existing
* code, this field is private. [CSA/davidm] */
private Scanner _scanner;
/**
* Simple accessor method to set the default scanner.
*/
public void setScanner(Scanner s) { _scanner = s; }
/**
* Simple accessor method to get the default scanner.
*/
public Scanner getScanner() { return _scanner; }
/*-----------------------------------------------------------*/
/*--- General Methods ---------------------------------------*/
/*-----------------------------------------------------------*/
/** Perform a bit of user supplied action code (supplied by generated
* subclass). Actions are indexed by an internal action number assigned
* at parser generation time.
*
* @param act_num the internal index of the action to be performed.
* @param parser the parser object we are acting for.
* @param stack the parse stack of that object.
* @param top the index of the top element of the parse stack.
*/
public abstract Symbol do_action(
int act_num,
lr_parser parser,
Stack stack,
int top)
throws java.lang.Exception;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** User code for initialization inside the parser. Typically this
* initializes the scanner. This is called before the parser requests
* the first Symbol. Here this is just a placeholder for subclasses that
* might need this and we perform no action. This method is normally
* overridden by the generated code using this contents of the "init with"
* clause as its body.
*/
public void user_init() throws java.lang.Exception { }
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Initialize the action object. This is called before the parser does
* any parse actions. This is filled in by generated code to create
* an object that encapsulates all action code.
*/
protected abstract void init_actions() throws java.lang.Exception;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Get the next Symbol from the input (supplied by generated subclass).
* Once end of file has been reached, all subsequent calls to scan
* should return an EOF Symbol (which is Symbol number 0). By default
* this method returns getScanner().next_token(); this implementation
* can be overriden by the generated parser using the code declared in
* the "scan with" clause. Do not recycle objects; every call to
* scan() should return a fresh object.
*/
public Symbol scan() throws java.lang.Exception {
Symbol sym = getScanner().next_token();
return (sym!=null) ? sym : getSymbolFactory().newSymbol("END_OF_FILE",EOF_sym());
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Report a fatal error. This method takes a message string and an
* additional object (to be used by specializations implemented in
* subclasses). Here in the base class a very simple implementation
* is provided which reports the error then throws an exception.
*
* @param message an error message.
* @param info an extra object reserved for use by specialized subclasses.
*/
public void report_fatal_error(
String message,
Object info)
throws java.lang.Exception
{
/* stop parsing (not really necessary since we throw an exception, but) */
done_parsing();
/* use the normal error message reporting to put out the message */
report_error(message, info);
/* throw an exception */
throw new Exception("Can't recover from previous error(s)");
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Report a non fatal error (or warning). This method takes a message
* string and an additional object (to be used by specializations
* implemented in subclasses). Here in the base class a very simple
* implementation is provided which simply prints the message to
* System.err.
*
* @param message an error message.
* @param info an extra object reserved for use by specialized subclasses.
*/
public void report_error(String message, Object info)
{
System.err.print(message);
System.err.flush();
if (info instanceof Symbol)
if (((Symbol)info).left != -1)
System.err.println(" at character " + ((Symbol)info).left +
" of input");
else System.err.println("");
else System.err.println("");
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** This method is called when a syntax error has been detected and recovery
* is about to be invoked. Here in the base class we just emit a
* "Syntax error" error message.
*
* @param cur_token the current lookahead Symbol.
*/
public void syntax_error(Symbol cur_token)
{
report_error("Syntax error", cur_token);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** This method is called if it is determined that syntax error recovery
* has been unsuccessful. Here in the base class we report a fatal error.
*
* @param cur_token the current lookahead Symbol.
*/
public void unrecovered_syntax_error(Symbol cur_token)
throws java.lang.Exception
{
report_fatal_error("Couldn't repair and continue parse", cur_token);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Fetch an action from the action table. The table is broken up into
* rows, one per state (rows are indexed directly by state number).
* Within each row, a list of index, value pairs are given (as sequential
* entries in the table), and the list is terminated by a default entry
* (denoted with a Symbol index of -1). To find the proper entry in a row
* we do a linear or binary search (depending on the size of the row).
*
* @param state the state index of the action being accessed.
* @param sym the Symbol index of the action being accessed.
*/
protected final short get_action(int state, int sym)
{
short tag;
int first, last, probe;
short[] row = action_tab[state];
/* linear search if we are < 10 entries */
if (row.length < 20)
for (probe = 0; probe < row.length; probe++)
{
/* is this entry labeled with our Symbol or the default? */
tag = row[probe++];
if (tag == sym || tag == -1)
{
/* return the next entry */
return row[probe];
}
}
/* otherwise binary search */
else
{
first = 0;
last = (row.length-1)/2 - 1; /* leave out trailing default entry */
while (first <= last)
{
probe = (first+last)/2;
if (sym == row[probe*2])
return row[probe*2+1];
else if (sym > row[probe*2])
first = probe+1;
else
last = probe-1;
}
/* not found, use the default at the end */
return row[row.length-1];
}
/* shouldn't happened, but if we run off the end we return the
default (error == 0) */
return 0;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Fetch a state from the reduce-goto table. The table is broken up into
* rows, one per state (rows are indexed directly by state number).
* Within each row, a list of index, value pairs are given (as sequential
* entries in the table), and the list is terminated by a default entry
* (denoted with a Symbol index of -1). To find the proper entry in a row
* we do a linear search.
*
* @param state the state index of the entry being accessed.
* @param sym the Symbol index of the entry being accessed.
*/
protected final short get_reduce(int state, int sym)
{
short tag;
short[] row = reduce_tab[state];
/* if we have a null row we go with the default */
if (row == null)
return -1;
for (int probe = 0; probe < row.length; probe++)
{
/* is this entry labeled with our Symbol or the default? */
tag = row[probe++];
if (tag == sym || tag == -1)
{
/* return the next entry */
return row[probe];
}
}
/* if we run off the end we return the default (error == -1) */
return -1;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** This method provides the main parsing routine. It returns only when
* done_parsing() has been called (typically because the parser has
* accepted, or a fatal error has been reported). See the header
* documentation for the class regarding how shift/reduce parsers operate
* and how the various tables are used.
*/
public Symbol parse() throws java.lang.Exception
{
/* the current action code */
int act;
/* the Symbol/stack element returned by a reduce */
Symbol lhs_sym = null;
/* information about production being reduced with */
short handle_size, lhs_sym_num;
/* set up direct reference to tables to drive the parser */
production_tab = production_table();
action_tab = action_table();
reduce_tab = reduce_table();
/* initialize the action encapsulation object */
init_actions();
/* do user initialization */
user_init();
/* get the first token */
cur_token = scan();
/* push dummy Symbol with start state to get us underway */
stack.removeAllElements();
stack.push(getSymbolFactory().startSymbol("START", 0, start_state()));
tos = 0;
/* continue until we are told to stop */
for (_done_parsing = false; !_done_parsing; )
{
/* Check current token for freshness. */
if (cur_token.used_by_parser)
throw new Error("Symbol recycling detected (fix your scanner).");
/* current state is always on the top of the stack */
/* look up action out of the current state with the current input */
act = get_action(((Symbol)stack.peek()).parse_state, cur_token.sym);
/* decode the action -- > 0 encodes shift */
if (act > 0)
{
/* shift to the encoded state by pushing it on the stack */
cur_token.parse_state = act-1;
cur_token.used_by_parser = true;
stack.push(cur_token);
tos++;
/* advance to the next Symbol */
cur_token = scan();
}
/* if its less than zero, then it encodes a reduce action */
else if (act < 0)
{
/* perform the action for the reduce */
lhs_sym = do_action((-act)-1, this, stack, tos);
/* look up information about the production */
lhs_sym_num = production_tab[(-act)-1][0];
handle_size = production_tab[(-act)-1][1];
/* pop the handle off the stack */
for (int i = 0; i < handle_size; i++)
{
stack.pop();
tos--;
}
/* look up the state to go to from the one popped back to */
act = get_reduce(((Symbol)stack.peek()).parse_state, lhs_sym_num);
/* shift to that state */
lhs_sym.parse_state = act;
lhs_sym.used_by_parser = true;
stack.push(lhs_sym);
tos++;
}
/* finally if the entry is zero, we have an error */
else if (act == 0)
{
/* call user syntax error reporting routine */
syntax_error(cur_token);
/* try to error recover */
if (!error_recovery(false))
{
/* if that fails give up with a fatal syntax error */
unrecovered_syntax_error(cur_token);
/* just in case that wasn't fatal enough, end parse */
done_parsing();
} else {
lhs_sym = (Symbol)stack.peek();
}
}
}
return lhs_sym;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Write a debugging message to System.err for the debugging version
* of the parser.
*
* @param mess the text of the debugging message.
*/
public void debug_message(String mess)
{
System.err.println(mess);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Dump the parse stack for debugging purposes. */
public void dump_stack()
{
if (stack == null)
{
debug_message("# Stack dump requested, but stack is null");
return;
}
debug_message("============ Parse Stack Dump ============");
/* dump the stack */
for (int i=0; i<stack.size(); i++)
{
debug_message("Symbol: " + ((Symbol)stack.elementAt(i)).sym +
" State: " + ((Symbol)stack.elementAt(i)).parse_state);
}
debug_message("==========================================");
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Do debug output for a reduce.
*
* @param prod_num the production we are reducing with.
* @param nt_num the index of the LHS non terminal.
* @param rhs_size the size of the RHS.
*/
public void debug_reduce(int prod_num, int nt_num, int rhs_size)
{
debug_message("# Reduce with prod #" + prod_num + " [NT=" + nt_num +
", " + "SZ=" + rhs_size + "]");
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Do debug output for shift.
*
* @param shift_tkn the Symbol being shifted onto the stack.
*/
public void debug_shift(Symbol shift_tkn)
{
debug_message("# Shift under term #" + shift_tkn.sym +
" to state #" + shift_tkn.parse_state);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Do debug output for stack state. [CSA]
*/
public void debug_stack() {
StringBuffer sb=new StringBuffer("## STACK:");
for (int i=0; i<stack.size(); i++) {
Symbol s = (Symbol) stack.elementAt(i);
sb.append(" <state "+s.parse_state+", sym "+s.sym+">");
if ((i%3)==2 || (i==(stack.size()-1))) {
debug_message(sb.toString());
sb = new StringBuffer(" ");
}
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Perform a parse with debugging output. This does exactly the
* same things as parse(), except that it calls debug_shift() and
* debug_reduce() when shift and reduce moves are taken by the parser
* and produces various other debugging messages.
*/
public Symbol debug_parse()
throws java.lang.Exception
{
/* the current action code */
int act;
/* the Symbol/stack element returned by a reduce */
Symbol lhs_sym = null;
/* information about production being reduced with */
short handle_size, lhs_sym_num;
/* set up direct reference to tables to drive the parser */
production_tab = production_table();
action_tab = action_table();
reduce_tab = reduce_table();
debug_message("# Initializing parser");
/* initialize the action encapsulation object */
init_actions();
/* do user initialization */
user_init();
/* the current Symbol */
cur_token = scan();
debug_message("# Current Symbol is #" + cur_token.sym);
/* push dummy Symbol with start state to get us underway */
stack.removeAllElements();
stack.push(getSymbolFactory().startSymbol("START",0, start_state()));
tos = 0;
/* continue until we are told to stop */
for (_done_parsing = false; !_done_parsing; )
{
/* Check current token for freshness. */
if (cur_token.used_by_parser)
throw new Error("Symbol recycling detected (fix your scanner).");
/* current state is always on the top of the stack */
//debug_stack();
/* look up action out of the current state with the current input */
act = get_action(((Symbol)stack.peek()).parse_state, cur_token.sym);
/* decode the action -- > 0 encodes shift */
if (act > 0)
{
/* shift to the encoded state by pushing it on the stack */
cur_token.parse_state = act-1;
cur_token.used_by_parser = true;
debug_shift(cur_token);
stack.push(cur_token);
tos++;
/* advance to the next Symbol */
cur_token = scan();
debug_message("# Current token is " + cur_token);
}
/* if its less than zero, then it encodes a reduce action */
else if (act < 0)
{
/* perform the action for the reduce */
lhs_sym = do_action((-act)-1, this, stack, tos);
/* look up information about the production */
lhs_sym_num = production_tab[(-act)-1][0];
handle_size = production_tab[(-act)-1][1];
debug_reduce((-act)-1, lhs_sym_num, handle_size);
/* pop the handle off the stack */
for (int i = 0; i < handle_size; i++)
{
stack.pop();
tos--;
}
/* look up the state to go to from the one popped back to */
act = get_reduce(((Symbol)stack.peek()).parse_state, lhs_sym_num);
debug_message("# Reduce rule: top state " +
((Symbol)stack.peek()).parse_state +
", lhs sym " + lhs_sym_num + " -> state " + act);
/* shift to that state */
lhs_sym.parse_state = act;
lhs_sym.used_by_parser = true;
stack.push(lhs_sym);
tos++;
debug_message("# Goto state #" + act);
}
/* finally if the entry is zero, we have an error */
else if (act == 0)
{
/* call user syntax error reporting routine */
syntax_error(cur_token);
/* try to error recover */
if (!error_recovery(true))
{
/* if that fails give up with a fatal syntax error */
unrecovered_syntax_error(cur_token);
/* just in case that wasn't fatal enough, end parse */
done_parsing();
} else {
lhs_sym = (Symbol)stack.peek();
}
}
}
return lhs_sym;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/* Error recovery code */
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Attempt to recover from a syntax error. This returns false if recovery
* fails, true if it succeeds. Recovery happens in 4 steps. First we
* pop the parse stack down to a point at which we have a shift out
* of the top-most state on the error Symbol. This represents the
* initial error recovery configuration. If no such configuration is
* found, then we fail. Next a small number of "lookahead" or "parse
* ahead" Symbols are read into a buffer. The size of this buffer is
* determined by error_sync_size() and determines how many Symbols beyond
* the error must be matched to consider the recovery a success. Next,
* we begin to discard Symbols in attempt to get past the point of error
* to a point where we can continue parsing. After each Symbol, we attempt
* to "parse ahead" though the buffered lookahead Symbols. The "parse ahead"
* process simulates that actual parse, but does not modify the real
* parser's configuration, nor execute any actions. If we can parse all
* the stored Symbols without error, then the recovery is considered a
* success. Once a successful recovery point is determined, we do an
* actual parse over the stored input -- modifying the real parse
* configuration and executing all actions. Finally, we return the the
* normal parser to continue with the overall parse.
*
* @param debug should we produce debugging messages as we parse.
*/
protected boolean error_recovery(boolean debug)
throws java.lang.Exception
{
if (debug) debug_message("# Attempting error recovery");
/* first pop the stack back into a state that can shift on error and
do that shift (if that fails, we fail) */
if (!find_recovery_config(debug))
{
if (debug) debug_message("# Error recovery fails");
return false;
}
/* read ahead to create lookahead we can parse multiple times */
read_lookahead();
/* repeatedly try to parse forward until we make it the required dist */
for (;;)
{
/* try to parse forward, if it makes it, bail out of loop */
if (debug) debug_message("# Trying to parse ahead");
if (try_parse_ahead(debug))
{
break;
}
/* if we are now at EOF, we have failed */
if (lookahead[0].sym == EOF_sym())
{
if (debug) debug_message("# Error recovery fails at EOF");
return false;
}
/* otherwise, we consume another Symbol and try again */
// BUG FIX by Bruce Hutton
// Computer Science Department, University of Auckland,
// Auckland, New Zealand.
// It is the first token that is being consumed, not the one
// we were up to parsing
if (debug)
debug_message("# Consuming Symbol #" + lookahead[ 0 ].sym);
restart_lookahead();
}
/* we have consumed to a point where we can parse forward */
if (debug) debug_message("# Parse-ahead ok, going back to normal parse");
/* do the real parse (including actions) across the lookahead */
parse_lookahead(debug);
/* we have success */
return true;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Determine if we can shift under the special error Symbol out of the
* state currently on the top of the (real) parse stack.
*/
protected boolean shift_under_error()
{
/* is there a shift under error Symbol */
return get_action(((Symbol)stack.peek()).parse_state, error_sym()) > 0;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Put the (real) parse stack into error recovery configuration by
* popping the stack down to a state that can shift on the special
* error Symbol, then doing the shift. If no suitable state exists on
* the stack we return false
*
* @param debug should we produce debugging messages as we parse.
*/
protected boolean find_recovery_config(boolean debug)
{
Symbol error_token;
int act;
if (debug) debug_message("# Finding recovery state on stack");
/* Remember the right-position of the top symbol on the stack */
Symbol right = ((Symbol)stack.peek());// TUM 20060327 removed .right
Symbol left = right;// TUM 20060327 removed .left
/* pop down until we can shift under error Symbol */
while (!shift_under_error())
{
/* pop the stack */
if (debug)
debug_message("# Pop stack by one, state was # " +
((Symbol)stack.peek()).parse_state);
left = ((Symbol)stack.pop()); // TUM 20060327 removed .left
tos--;
/* if we have hit bottom, we fail */
if (stack.empty())
{
if (debug) debug_message("# No recovery state found on stack");
return false;
}
}
/* state on top of the stack can shift under error, find the shift */
act = get_action(((Symbol)stack.peek()).parse_state, error_sym());
if (debug)
{
debug_message("# Recover state found (#" +
((Symbol)stack.peek()).parse_state + ")");
debug_message("# Shifting on error to state #" + (act-1));
}
/* build and shift a special error Symbol */
error_token = getSymbolFactory().newSymbol("ERROR",error_sym(), left, right);
error_token.parse_state = act-1;
error_token.used_by_parser = true;
stack.push(error_token);
tos++;
return true;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Lookahead Symbols used for attempting error recovery "parse aheads". */
protected Symbol lookahead[];
/** Position in lookahead input buffer used for "parse ahead". */
protected int lookahead_pos;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Read from input to establish our buffer of "parse ahead" lookahead
* Symbols.
*/
protected void read_lookahead() throws java.lang.Exception
{
/* create the lookahead array */
lookahead = new Symbol[error_sync_size()];
/* fill in the array */
for (int i = 0; i < error_sync_size(); i++)
{
lookahead[i] = cur_token;
cur_token = scan();
}
/* start at the beginning */
lookahead_pos = 0;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Return the current lookahead in our error "parse ahead" buffer. */
protected Symbol cur_err_token() { return lookahead[lookahead_pos]; }
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Advance to next "parse ahead" input Symbol. Return true if we have
* input to advance to, false otherwise.
*/
protected boolean advance_lookahead()
{
/* advance the input location */
lookahead_pos++;
/* return true if we didn't go off the end */
return lookahead_pos < error_sync_size();
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Reset the parse ahead input to one Symbol past where we started error
* recovery (this consumes one new Symbol from the real input).
*/
protected void restart_lookahead() throws java.lang.Exception
{
/* move all the existing input over */
for (int i = 1; i < error_sync_size(); i++)
lookahead[i-1] = lookahead[i];
/* read a new Symbol into the last spot */
// BUG Fix by Bruce Hutton
// Computer Science Department, University of Auckland,
// Auckland, New Zealand. [applied 5-sep-1999 by csa]
// The following two lines were out of order!!
lookahead[error_sync_size()-1] = cur_token;
cur_token = scan();
/* reset our internal position marker */
lookahead_pos = 0;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Do a simulated parse forward (a "parse ahead") from the current
* stack configuration using stored lookahead input and a virtual parse
* stack. Return true if we make it all the way through the stored
* lookahead input without error. This basically simulates the action of
* parse() using only our saved "parse ahead" input, and not executing any
* actions.
*
* @param debug should we produce debugging messages as we parse.
*/
protected boolean try_parse_ahead(boolean debug)
throws java.lang.Exception
{
int act;
short lhs, rhs_size;
/* create a virtual stack from the real parse stack */
virtual_parse_stack vstack = new virtual_parse_stack(stack);
/* parse until we fail or get past the lookahead input */
for (;;)
{
/* look up the action from the current state (on top of stack) */
act = get_action(vstack.top(), cur_err_token().sym);
/* if its an error, we fail */
if (act == 0) return false;
/* > 0 encodes a shift */
if (act > 0)
{
/* push the new state on the stack */
vstack.push(act-1);
if (debug) debug_message("# Parse-ahead shifts Symbol #" +
cur_err_token().sym + " into state #" + (act-1));
/* advance simulated input, if we run off the end, we are done */
if (!advance_lookahead()) return true;
}
/* < 0 encodes a reduce */
else
{
/* if this is a reduce with the start production we are done */
if ((-act)-1 == start_production())
{
if (debug) debug_message("# Parse-ahead accepts");
return true;
}
/* get the lhs Symbol and the rhs size */
lhs = production_tab[(-act)-1][0];
rhs_size = production_tab[(-act)-1][1];
/* pop handle off the stack */
for (int i = 0; i < rhs_size; i++)
vstack.pop();
if (debug)
debug_message("# Parse-ahead reduces: handle size = " +
rhs_size + " lhs = #" + lhs + " from state #" + vstack.top());
/* look up goto and push it onto the stack */
vstack.push(get_reduce(vstack.top(), lhs));
if (debug)
debug_message("# Goto state #" + vstack.top());
}
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Parse forward using stored lookahead Symbols. In this case we have
* already verified that parsing will make it through the stored lookahead
* Symbols and we are now getting back to the point at which we can hand
* control back to the normal parser. Consequently, this version of the
* parser performs all actions and modifies the real parse configuration.
* This returns once we have consumed all the stored input or we accept.
*
* @param debug should we produce debugging messages as we parse.
*/
protected void parse_lookahead(boolean debug)
throws java.lang.Exception
{
/* the current action code */
int act;
/* the Symbol/stack element returned by a reduce */
Symbol lhs_sym = null;
/* information about production being reduced with */
short handle_size, lhs_sym_num;
/* restart the saved input at the beginning */
lookahead_pos = 0;
if (debug)
{
debug_message("# Reparsing saved input with actions");
debug_message("# Current Symbol is #" + cur_err_token().sym);
debug_message("# Current state is #" +
((Symbol)stack.peek()).parse_state);
}
/* continue until we accept or have read all lookahead input */
while(!_done_parsing)
{
/* current state is always on the top of the stack */
/* look up action out of the current state with the current input */
act =
get_action(((Symbol)stack.peek()).parse_state, cur_err_token().sym);
/* decode the action -- > 0 encodes shift */
if (act > 0)
{
/* shift to the encoded state by pushing it on the stack */
cur_err_token().parse_state = act-1;
cur_err_token().used_by_parser = true;
if (debug) debug_shift(cur_err_token());
stack.push(cur_err_token());
tos++;
/* advance to the next Symbol, if there is none, we are done */
if (!advance_lookahead())
{
if (debug) debug_message("# Completed reparse");
/* scan next Symbol so we can continue parse */
// BUGFIX by Chris Harris <ckharris@ucsd.edu>:
// correct a one-off error by commenting out
// this next line.
/*cur_token = scan();*/
/* go back to normal parser */
return;
}
if (debug)
debug_message("# Current Symbol is #" + cur_err_token().sym);
}
/* if its less than zero, then it encodes a reduce action */
else if (act < 0)
{
/* perform the action for the reduce */
lhs_sym = do_action((-act)-1, this, stack, tos);
/* look up information about the production */
lhs_sym_num = production_tab[(-act)-1][0];
handle_size = production_tab[(-act)-1][1];
if (debug) debug_reduce((-act)-1, lhs_sym_num, handle_size);
/* pop the handle off the stack */
for (int i = 0; i < handle_size; i++)
{
stack.pop();
tos--;
}
/* look up the state to go to from the one popped back to */
act = get_reduce(((Symbol)stack.peek()).parse_state, lhs_sym_num);
/* shift to that state */
lhs_sym.parse_state = act;
lhs_sym.used_by_parser = true;
stack.push(lhs_sym);
tos++;
if (debug) debug_message("# Goto state #" + act);
}
/* finally if the entry is zero, we have an error
(shouldn't happen here, but...)*/
else if (act == 0)
{
report_fatal_error("Syntax error", lhs_sym);
return;
}
}
}
/*-----------------------------------------------------------*/
/** Utility function: unpacks parse tables from strings */
protected static short[][] unpackFromStrings(String[] sa)
{
// Concatanate initialization strings.
StringBuffer sb = new StringBuffer(sa[0]);
for (int i=1; i<sa.length; i++)
sb.append(sa[i]);
int n=0; // location in initialization string
int size1 = (((int)sb.charAt(n))<<16) | ((int)sb.charAt(n+1)); n+=2;
short[][] result = new short[size1][];
for (int i=0; i<size1; i++) {
int size2 = (((int)sb.charAt(n))<<16) | ((int)sb.charAt(n+1)); n+=2;
result[i] = new short[size2];
for (int j=0; j<size2; j++)
result[i][j] = (short) (sb.charAt(n++)-2);
}
return result;
}
}
| 44,822
|
Java
|
.java
| 1,052
| 37.39924
| 90
| 0.59915
|
k9ert/struktor
| 1
| 1
| 0
|
GPL-2.0
|
9/5/2024, 12:30:20 AM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 44,822
|
2,575,263
|
Javac.java
|
JPortal-system_system/jdk12-06222165c35f/test/micro/org/openjdk/bench/javax/tools/Javac.java
|
/*
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.bench.javax.tools;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
public class Javac {
private List<JavaSourceFromString> compilationUnits;
private JavaCompiler compiler;
private StandardJavaFileManager fileManager;
@Setup
public void prepare() {
String helloWorld = "class Apan { \n" + " public static void main(String args[]) {\n"
+ " System.out.println(\"hej apa\");\n" + " }\n" + "}\n";
compiler = ToolProvider.getSystemJavaCompiler();
fileManager = compiler.getStandardFileManager(null, null, null);
compilationUnits = new ArrayList<>();
compilationUnits.add(new JavaSourceFromString("Apan", helloWorld));
}
@Benchmark
public Boolean testCompile() throws Exception {
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
return task.call();
}
private static class JavaSourceFromString extends SimpleJavaFileObject {
final String code;
JavaSourceFromString(String name, String code) {
super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension),
Kind.SOURCE);
this.code = code;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
}
| 3,083
|
Java
|
.java
| 72
| 38.347222
| 116
| 0.737841
|
JPortal-system/system
| 7
| 2
| 1
|
GPL-3.0
|
9/4/2024, 9:49:36 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 3,083
|
723,655
|
NinePartRenderer.java
|
cogtool_cogtool/java/edu/cmu/cs/hcii/cogtool/uimodel/NinePartRenderer.java
|
/*******************************************************************************
* CogTool Copyright Notice and Distribution Terms
* CogTool 1.3, Copyright (c) 2005-2013 Carnegie Mellon University
* This software is distributed under the terms of the FSF Lesser
* Gnu Public License (see LGPL.txt).
*
* CogTool 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.
*
* CogTool 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 CogTool; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* CogTool makes use of several third-party components, with the
* following notices:
*
* Eclipse SWT version 3.448
* Eclipse GEF Draw2D version 3.2.1
*
* Unless otherwise indicated, all Content made available by the Eclipse
* Foundation is provided to you under the terms and conditions of the Eclipse
* Public License Version 1.0 ("EPL"). A copy of the EPL is provided with this
* Content and is also available at http://www.eclipse.org/legal/epl-v10.html.
*
* CLISP version 2.38
*
* Copyright (c) Sam Steingold, Bruno Haible 2001-2006
* This software is distributed under the terms of the FSF Gnu Public License.
* See COPYRIGHT file in clisp installation folder for more information.
*
* ACT-R 6.0
*
* Copyright (c) 1998-2007 Dan Bothell, Mike Byrne, Christian Lebiere &
* John R Anderson.
* This software is distributed under the terms of the FSF Lesser
* Gnu Public License (see LGPL.txt).
*
* Apache Jakarta Commons-Lang 2.1
*
* This product contains software developed by the Apache Software Foundation
* (http://www.apache.org/)
*
* jopt-simple version 1.0
*
* Copyright (c) 2004-2013 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Mozilla XULRunner 1.9.0.5
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/.
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The J2SE(TM) Java Runtime Environment version 5.0
*
* Copyright 2009 Sun Microsystems, Inc., 4150
* Network Circle, Santa Clara, California 95054, U.S.A. All
* rights reserved. U.S.
* See the LICENSE file in the jre folder for more information.
******************************************************************************/
package edu.cmu.cs.hcii.cogtool.uimodel;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.graphics.Image;
public class NinePartRenderer extends ImageRenderer
{
protected static String NINE_PART_LOCATION =
"edu/cmu/cs/hcii/cogtool/resources/widgets/9part/";
// Depending on the state of the widget, imageParts is either defaultSet
// or altSet
protected Image[] imageParts = null;
protected Image[] defaultSet = null;
protected Image[] altSet = null;
protected String skinName;
protected NinePartRenderer(GraphicalWidget<?> parent,
String widgetName,
String skin,
int labelStyle,
int area,
DefaultSEUIModel override)
{
super(parent, widgetName, skin, labelStyle, area, override);
skinName = skin;
defaultSet = getNinePartImages(skinName, widgetName, "");
try {
altSet = getNinePartImages(skinName, widgetName, "s");
}
catch (Exception e) {
// "alt" images don't necessarily exist for all widgets
altSet = null;
}
imageParts = defaultSet;
}
/**
* Loads the nine images needed by a nine-part image
* artist. Assumes that the images have names of the form
* <skin>/<name>/<name><number>.jpg.
*/
protected Image[] getNinePartImages(String skin, String name, String suffix)
{
Image[] iAry = new Image[9];
for (int i = 0; i < iAry.length; i++) {
iAry[i] = getImage(NINE_PART_LOCATION + skin + "/" + name + "/"
+ i + suffix + "." + FILETYPE);
}
return iAry;
}// getNinePartImages
public void paintBackground(Graphics g)
{
if ((imageParts == null) ||
(imageParts.length == 0) ||
(imageParts[0] == null))
{
return;
}
g.pushState();
try {
// This is the clip to the figure. We must clip to this the whole time!
Rectangle mainClip = getBounds();
g.setClip(mainClip);
// This will represent temporary clips while drawing the 9part.
// All subClips must be a union of mainClip and something else.
Rectangle subClip = mainClip;
// This is the top and left of the 9-part tiled image.
// widgetBounds.x and .y should both always be 0 since we want to fill
// the space we have been given.
int topOfImg = widgetBounds.x;
int leftOfImg = widgetBounds.y;
// These variables represent the distances between the actual edges
// of the 9-part tiling and the edge of the center area of the 9-part.
// we will assume we have all images so no error checking is needed.
int leftSize = imageParts[0].getBounds().width;
int rightSize = imageParts[2].getBounds().width;
int topSize = imageParts[0].getBounds().height;
int bottomSize = imageParts[6].getBounds().height;
// These variables represent the absolute coordinates
// of the edges of the center area.
int rightOfCenter =
leftOfImg + widgetBounds.width - rightSize;
int leftOfCenter = leftOfImg + leftSize;
int topOfCenter = topOfImg + topSize;
int bottomOfCenter =
topOfImg + widgetBounds.height - bottomSize;
// These are variables for when I am drawing a row of images.
int drawX;
int drawY;
// When I am drawing a row of images, these variables store the
// dimension of the image I'm drawing.
int imgWidth;
int imgHeight;
// Setting the subclip for drawing the center area.
subClip = mainClip;
subClip =
subClip.getIntersection(
new Rectangle(leftOfCenter,
topOfCenter,
rightOfCenter - leftOfCenter + 2,
bottomOfCenter - topOfCenter + 2));
g.setClip(subClip);
if (imageParts[4] != null) {
imgWidth = imageParts[4].getBounds().width;
imgHeight = imageParts[4].getBounds().height;
for (drawX = leftOfCenter;
drawX < rightOfCenter;
drawX += imgWidth)
{
for (drawY = topOfCenter;
drawY < bottomOfCenter;
drawY += imgHeight)
{
g.drawImage(imageParts[4], drawX, drawY);
}
}
}
// Setting the subclip for drawing horizontal rows.
subClip = mainClip;
subClip =
subClip.getIntersection(
new Rectangle(leftOfCenter,
topOfImg,
rightOfCenter - leftOfCenter + 2,
widgetBounds.height));
g.setClip(subClip);
// Drawing the top row.
if (imageParts[1] != null) {
imgWidth = imageParts[1].getBounds().width;
for (drawX = leftOfCenter;
drawX < rightOfCenter;
drawX += imgWidth)
{
g.drawImage(imageParts[1], drawX, topOfImg);
}
}
// Drawing the bottom row.
if (imageParts[7] != null) {
imgWidth = imageParts[7].getBounds().width;
for (drawX = leftOfCenter;
drawX < rightOfCenter;
drawX += imgWidth)
{
g.drawImage(imageParts[7], drawX, bottomOfCenter);
}
}
// Setting the subclip for drawing vertical rows.
subClip = mainClip;
subClip =
subClip.getIntersection(
new Rectangle(leftOfImg,
topOfCenter,
widgetBounds.width,
bottomOfCenter - topOfCenter + 2));
g.setClip(subClip);
// Drawing the left side row.
if (imageParts[3] != null) {
imgHeight = imageParts[3].getBounds().height;
for (drawY = topOfCenter;
drawY < bottomOfCenter;
drawY += imgHeight)
{
g.drawImage(imageParts[3], leftOfImg, drawY);
}
}
// Drawing the right side row.
if (imageParts[5] != null) {
imgHeight = imageParts[5].getBounds().height;
for (drawY = topOfCenter;
drawY < bottomOfCenter;
drawY += imgHeight)
{
g.drawImage(imageParts[5], rightOfCenter, drawY);
}
}
// Reset the clip to the main clip, the entire size of the frame.
g.setClip(mainClip);
// Drawing the top left corner.
if (imageParts[0] != null) {
g.drawImage(imageParts[0], leftOfImg, topOfImg);
}
// Drawing the top right corner.
if (imageParts[2] != null) {
g.drawImage(imageParts[2], rightOfCenter, topOfImg);
}
// Drawing the bottom left corner.
if (imageParts[6] != null) {
g.drawImage(imageParts[6], leftOfImg, bottomOfCenter);
}
// Drawing the bottom right corner.
if (imageParts[8] != null) {
g.drawImage(imageParts[8], rightOfCenter, bottomOfCenter);
}
}
finally {
g.popState();
}
} // paintBackground
public void paintForeground(Graphics g)
{
if (label != null) {
label.paint(g);
}
}
}
| 12,671
|
Java
|
.java
| 292
| 32.10274
| 83
| 0.574996
|
cogtool/cogtool
| 98
| 25
| 16
|
LGPL-2.1
|
9/4/2024, 7:08:37 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 12,671
|
1,203,825
|
JTree.java
|
keerath_openjdk-8-source/jdk/src/share/classes/javax/swing/JTree.java
|
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.util.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.tree.*;
import javax.swing.text.Position;
import javax.accessibility.*;
import sun.swing.SwingUtilities2;
import sun.swing.SwingUtilities2.Section;
import static sun.swing.SwingUtilities2.Section.*;
/**
* <a name="jtree_description"></a>
* A control that displays a set of hierarchical data as an outline.
* You can find task-oriented documentation and examples of using trees in
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/tree.html">How to Use Trees</a>,
* a section in <em>The Java Tutorial.</em>
* <p>
* A specific node in a tree can be identified either by a
* <code>TreePath</code> (an object
* that encapsulates a node and all of its ancestors), or by its
* display row, where each row in the display area displays one node.
* An <i>expanded</i> node is a non-leaf node (as identified by
* <code>TreeModel.isLeaf(node)</code> returning false) that will displays
* its children when all its ancestors are <i>expanded</i>.
* A <i>collapsed</i>
* node is one which hides them. A <i>hidden</i> node is one which is
* under a collapsed ancestor. All of a <i>viewable</i> nodes parents
* are expanded, but may or may not be displayed. A <i>displayed</i> node
* is both viewable and in the display area, where it can be seen.
* </p>
* The following <code>JTree</code> methods use "visible" to mean "displayed":
* <ul>
* <li><code>isRootVisible()</code>
* <li><code>setRootVisible()</code>
* <li><code>scrollPathToVisible()</code>
* <li><code>scrollRowToVisible()</code>
* <li><code>getVisibleRowCount()</code>
* <li><code>setVisibleRowCount()</code>
* </ul>
* The next group of <code>JTree</code> methods use "visible" to mean
* "viewable" (under an expanded parent):
* <ul>
* <li><code>isVisible()</code>
* <li><code>makeVisible()</code>
* </ul>
* If you are interested in knowing when the selection changes implement
* the <code>TreeSelectionListener</code> interface and add the instance
* using the method <code>addTreeSelectionListener</code>.
* <code>valueChanged</code> will be invoked when the
* selection changes, that is if the user clicks twice on the same
* node <code>valueChanged</code> will only be invoked once.
* <p>
* If you are interested in detecting either double-click events or when
* a user clicks on a node, regardless of whether or not it was selected,
* we recommend you do the following:
* </p>
* <pre>
* final JTree tree = ...;
*
* MouseListener ml = new MouseAdapter() {
* public void <b>mousePressed</b>(MouseEvent e) {
* int selRow = tree.getRowForLocation(e.getX(), e.getY());
* TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
* if(selRow != -1) {
* if(e.getClickCount() == 1) {
* mySingleClick(selRow, selPath);
* }
* else if(e.getClickCount() == 2) {
* myDoubleClick(selRow, selPath);
* }
* }
* }
* };
* tree.addMouseListener(ml);
* </pre>
* NOTE: This example obtains both the path and row, but you only need to
* get the one you're interested in.
* <p>
* To use <code>JTree</code> to display compound nodes
* (for example, nodes containing both
* a graphic icon and text), subclass {@link TreeCellRenderer} and use
* {@link #setCellRenderer} to tell the tree to use it. To edit such nodes,
* subclass {@link TreeCellEditor} and use {@link #setCellEditor}.
* </p>
* <p>
* Like all <code>JComponent</code> classes, you can use {@link InputMap} and
* {@link ActionMap}
* to associate an {@link Action} object with a {@link KeyStroke}
* and execute the action under specified conditions.
* </p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*</p>
* @beaninfo
* attribute: isContainer false
* description: A component that displays a set of hierarchical data as an outline.
*
* @author Rob Davis
* @author Ray Ryan
* @author Scott Violet
*/
@SuppressWarnings("serial")
public class JTree extends JComponent implements Scrollable, Accessible
{
/**
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "TreeUI";
/**
* The model that defines the tree displayed by this object.
*/
transient protected TreeModel treeModel;
/**
* Models the set of selected nodes in this tree.
*/
transient protected TreeSelectionModel selectionModel;
/**
* True if the root node is displayed, false if its children are
* the highest visible nodes.
*/
protected boolean rootVisible;
/**
* The cell used to draw nodes. If <code>null</code>, the UI uses a default
* <code>cellRenderer</code>.
*/
transient protected TreeCellRenderer cellRenderer;
/**
* Height to use for each display row. If this is <= 0 the renderer
* determines the height for each row.
*/
protected int rowHeight;
private boolean rowHeightSet = false;
/**
* Maps from <code>TreePath</code> to <code>Boolean</code>
* indicating whether or not the
* particular path is expanded. This ONLY indicates whether a
* given path is expanded, and NOT if it is visible or not. That
* information must be determined by visiting all the parent
* paths and seeing if they are visible.
*/
transient private Hashtable<TreePath, Boolean> expandedState;
/**
* True if handles are displayed at the topmost level of the tree.
* <p>
* A handle is a small icon that displays adjacent to the node which
* allows the user to click once to expand or collapse the node. A
* common interface shows a plus sign (+) for a node which can be
* expanded and a minus sign (-) for a node which can be collapsed.
* Handles are always shown for nodes below the topmost level.
* <p>
* If the <code>rootVisible</code> setting specifies that the root
* node is to be displayed, then that is the only node at the topmost
* level. If the root node is not displayed, then all of its
* children are at the topmost level of the tree. Handles are
* always displayed for nodes other than the topmost.
* <p>
* If the root node isn't visible, it is generally a good to make
* this value true. Otherwise, the tree looks exactly like a list,
* and users may not know that the "list entries" are actually
* tree nodes.
*
* @see #rootVisible
*/
protected boolean showsRootHandles;
private boolean showsRootHandlesSet = false;
/**
* Creates a new event and passed it off the
* <code>selectionListeners</code>.
*/
protected transient TreeSelectionRedirector selectionRedirector;
/**
* Editor for the entries. Default is <code>null</code>
* (tree is not editable).
*/
transient protected TreeCellEditor cellEditor;
/**
* Is the tree editable? Default is false.
*/
protected boolean editable;
/**
* Is this tree a large model? This is a code-optimization setting.
* A large model can be used when the cell height is the same for all
* nodes. The UI will then cache very little information and instead
* continually message the model. Without a large model the UI caches
* most of the information, resulting in fewer method calls to the model.
* <p>
* This value is only a suggestion to the UI. Not all UIs will
* take advantage of it. Default value is false.
*/
protected boolean largeModel;
/**
* Number of rows to make visible at one time. This value is used for
* the <code>Scrollable</code> interface. It determines the preferred
* size of the display area.
*/
protected int visibleRowCount;
/**
* If true, when editing is to be stopped by way of selection changing,
* data in tree changing or other means <code>stopCellEditing</code>
* is invoked, and changes are saved. If false,
* <code>cancelCellEditing</code> is invoked, and changes
* are discarded. Default is false.
*/
protected boolean invokesStopCellEditing;
/**
* If true, when a node is expanded, as many of the descendants are
* scrolled to be visible.
*/
protected boolean scrollsOnExpand;
private boolean scrollsOnExpandSet = false;
/**
* Number of mouse clicks before a node is expanded.
*/
protected int toggleClickCount;
/**
* Updates the <code>expandedState</code>.
*/
transient protected TreeModelListener treeModelListener;
/**
* Used when <code>setExpandedState</code> is invoked,
* will be a <code>Stack</code> of <code>Stack</code>s.
*/
transient private Stack<Stack<TreePath>> expandedStack;
/**
* Lead selection path, may not be <code>null</code>.
*/
private TreePath leadPath;
/**
* Anchor path.
*/
private TreePath anchorPath;
/**
* True if paths in the selection should be expanded.
*/
private boolean expandsSelectedPaths;
/**
* This is set to true for the life of the <code>setUI</code> call.
*/
private boolean settingUI;
/** If true, mouse presses on selections initiate a drag operation. */
private boolean dragEnabled;
/**
* The drop mode for this component.
*/
private DropMode dropMode = DropMode.USE_SELECTION;
/**
* The drop location.
*/
private transient DropLocation dropLocation;
/**
* A subclass of <code>TransferHandler.DropLocation</code> representing
* a drop location for a <code>JTree</code>.
*
* @see #getDropLocation
* @since 1.6
*/
public static final class DropLocation extends TransferHandler.DropLocation {
private final TreePath path;
private final int index;
private DropLocation(Point p, TreePath path, int index) {
super(p);
this.path = path;
this.index = index;
}
/**
* Returns the index where the dropped data should be inserted
* with respect to the path returned by <code>getPath()</code>.
* <p>
* For drop modes <code>DropMode.USE_SELECTION</code> and
* <code>DropMode.ON</code>, this index is unimportant (and it will
* always be <code>-1</code>) as the only interesting data is the
* path over which the drop operation occurred.
* <p>
* For drop mode <code>DropMode.INSERT</code>, this index
* indicates the index at which the data should be inserted into
* the parent path represented by <code>getPath()</code>.
* <code>-1</code> indicates that the drop occurred over the
* parent itself, and in most cases should be treated as inserting
* into either the beginning or the end of the parent's list of
* children.
* <p>
* For <code>DropMode.ON_OR_INSERT</code>, this value will be
* an insert index, as described above, or <code>-1</code> if
* the drop occurred over the path itself.
*
* @return the child index
* @see #getPath
*/
public int getChildIndex() {
return index;
}
/**
* Returns the path where dropped data should be placed in the
* tree.
* <p>
* Interpretation of this value depends on the drop mode set on the
* component. If the drop mode is <code>DropMode.USE_SELECTION</code>
* or <code>DropMode.ON</code>, the return value is the path in the
* tree over which the data has been (or will be) dropped.
* <code>null</code> indicates that the drop is over empty space,
* not associated with a particular path.
* <p>
* If the drop mode is <code>DropMode.INSERT</code>, the return value
* refers to the path that should become the parent of the new data,
* in which case <code>getChildIndex()</code> indicates where the
* new item should be inserted into this parent path. A
* <code>null</code> path indicates that no parent path has been
* determined, which can happen for multiple reasons:
* <ul>
* <li>The tree has no model
* <li>There is no root in the tree
* <li>The root is collapsed
* <li>The root is a leaf node
* </ul>
* It is up to the developer to decide if and how they wish to handle
* the <code>null</code> case.
* <p>
* If the drop mode is <code>DropMode.ON_OR_INSERT</code>,
* <code>getChildIndex</code> can be used to determine whether the
* drop is on top of the path itself (<code>-1</code>) or the index
* at which it should be inserted into the path (values other than
* <code>-1</code>).
*
* @return the drop path
* @see #getChildIndex
*/
public TreePath getPath() {
return path;
}
/**
* Returns a string representation of this drop location.
* This method is intended to be used for debugging purposes,
* and the content and format of the returned string may vary
* between implementations.
*
* @return a string representation of this drop location
*/
public String toString() {
return getClass().getName()
+ "[dropPoint=" + getDropPoint() + ","
+ "path=" + path + ","
+ "childIndex=" + index + "]";
}
}
/**
* The row to expand during DnD.
*/
private int expandRow = -1;
@SuppressWarnings("serial")
private class TreeTimer extends Timer {
public TreeTimer() {
super(2000, null);
setRepeats(false);
}
public void fireActionPerformed(ActionEvent ae) {
JTree.this.expandRow(expandRow);
}
}
/**
* A timer to expand nodes during drop.
*/
private TreeTimer dropTimer;
/**
* When <code>addTreeExpansionListener</code> is invoked,
* and <code>settingUI</code> is true, this ivar gets set to the passed in
* <code>Listener</code>. This listener is then notified first in
* <code>fireTreeCollapsed</code> and <code>fireTreeExpanded</code>.
* <p>This is an ugly workaround for a way to have the UI listener
* get notified before other listeners.
*/
private transient TreeExpansionListener uiTreeExpansionListener;
/**
* Max number of stacks to keep around.
*/
private static int TEMP_STACK_SIZE = 11;
//
// Bound property names
//
/** Bound property name for <code>cellRenderer</code>. */
public final static String CELL_RENDERER_PROPERTY = "cellRenderer";
/** Bound property name for <code>treeModel</code>. */
public final static String TREE_MODEL_PROPERTY = "model";
/** Bound property name for <code>rootVisible</code>. */
public final static String ROOT_VISIBLE_PROPERTY = "rootVisible";
/** Bound property name for <code>showsRootHandles</code>. */
public final static String SHOWS_ROOT_HANDLES_PROPERTY = "showsRootHandles";
/** Bound property name for <code>rowHeight</code>. */
public final static String ROW_HEIGHT_PROPERTY = "rowHeight";
/** Bound property name for <code>cellEditor</code>. */
public final static String CELL_EDITOR_PROPERTY = "cellEditor";
/** Bound property name for <code>editable</code>. */
public final static String EDITABLE_PROPERTY = "editable";
/** Bound property name for <code>largeModel</code>. */
public final static String LARGE_MODEL_PROPERTY = "largeModel";
/** Bound property name for selectionModel. */
public final static String SELECTION_MODEL_PROPERTY = "selectionModel";
/** Bound property name for <code>visibleRowCount</code>. */
public final static String VISIBLE_ROW_COUNT_PROPERTY = "visibleRowCount";
/** Bound property name for <code>messagesStopCellEditing</code>. */
public final static String INVOKES_STOP_CELL_EDITING_PROPERTY = "invokesStopCellEditing";
/** Bound property name for <code>scrollsOnExpand</code>. */
public final static String SCROLLS_ON_EXPAND_PROPERTY = "scrollsOnExpand";
/** Bound property name for <code>toggleClickCount</code>. */
public final static String TOGGLE_CLICK_COUNT_PROPERTY = "toggleClickCount";
/** Bound property name for <code>leadSelectionPath</code>.
* @since 1.3 */
public final static String LEAD_SELECTION_PATH_PROPERTY = "leadSelectionPath";
/** Bound property name for anchor selection path.
* @since 1.3 */
public final static String ANCHOR_SELECTION_PATH_PROPERTY = "anchorSelectionPath";
/** Bound property name for expands selected paths property
* @since 1.3 */
public final static String EXPANDS_SELECTED_PATHS_PROPERTY = "expandsSelectedPaths";
/**
* Creates and returns a sample <code>TreeModel</code>.
* Used primarily for beanbuilders to show something interesting.
*
* @return the default <code>TreeModel</code>
*/
protected static TreeModel getDefaultTreeModel() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("JTree");
DefaultMutableTreeNode parent;
parent = new DefaultMutableTreeNode("colors");
root.add(parent);
parent.add(new DefaultMutableTreeNode("blue"));
parent.add(new DefaultMutableTreeNode("violet"));
parent.add(new DefaultMutableTreeNode("red"));
parent.add(new DefaultMutableTreeNode("yellow"));
parent = new DefaultMutableTreeNode("sports");
root.add(parent);
parent.add(new DefaultMutableTreeNode("basketball"));
parent.add(new DefaultMutableTreeNode("soccer"));
parent.add(new DefaultMutableTreeNode("football"));
parent.add(new DefaultMutableTreeNode("hockey"));
parent = new DefaultMutableTreeNode("food");
root.add(parent);
parent.add(new DefaultMutableTreeNode("hot dogs"));
parent.add(new DefaultMutableTreeNode("pizza"));
parent.add(new DefaultMutableTreeNode("ravioli"));
parent.add(new DefaultMutableTreeNode("bananas"));
return new DefaultTreeModel(root);
}
/**
* Returns a <code>TreeModel</code> wrapping the specified object.
* If the object is:<ul>
* <li>an array of <code>Object</code>s,
* <li>a <code>Hashtable</code>, or
* <li>a <code>Vector</code>
* </ul>then a new root node is created with each of the incoming
* objects as children. Otherwise, a new root is created with
* a value of {@code "root"}.
*
* @param value the <code>Object</code> used as the foundation for
* the <code>TreeModel</code>
* @return a <code>TreeModel</code> wrapping the specified object
*/
protected static TreeModel createTreeModel(Object value) {
DefaultMutableTreeNode root;
if((value instanceof Object[]) || (value instanceof Hashtable) ||
(value instanceof Vector)) {
root = new DefaultMutableTreeNode("root");
DynamicUtilTreeNode.createChildren(root, value);
}
else {
root = new DynamicUtilTreeNode("root", value);
}
return new DefaultTreeModel(root, false);
}
/**
* Returns a <code>JTree</code> with a sample model.
* The default model used by the tree defines a leaf node as any node
* without children.
*
* @see DefaultTreeModel#asksAllowsChildren
*/
public JTree() {
this(getDefaultTreeModel());
}
/**
* Returns a <code>JTree</code> with each element of the
* specified array as the
* child of a new root node which is not displayed.
* By default, the tree defines a leaf node as any node without
* children.
*
* @param value an array of <code>Object</code>s
* @see DefaultTreeModel#asksAllowsChildren
*/
public JTree(Object[] value) {
this(createTreeModel(value));
this.setRootVisible(false);
this.setShowsRootHandles(true);
expandRoot();
}
/**
* Returns a <code>JTree</code> with each element of the specified
* <code>Vector</code> as the
* child of a new root node which is not displayed. By default, the
* tree defines a leaf node as any node without children.
*
* @param value a <code>Vector</code>
* @see DefaultTreeModel#asksAllowsChildren
*/
public JTree(Vector<?> value) {
this(createTreeModel(value));
this.setRootVisible(false);
this.setShowsRootHandles(true);
expandRoot();
}
/**
* Returns a <code>JTree</code> created from a <code>Hashtable</code>
* which does not display with root.
* Each value-half of the key/value pairs in the <code>HashTable</code>
* becomes a child of the new root node. By default, the tree defines
* a leaf node as any node without children.
*
* @param value a <code>Hashtable</code>
* @see DefaultTreeModel#asksAllowsChildren
*/
public JTree(Hashtable<?,?> value) {
this(createTreeModel(value));
this.setRootVisible(false);
this.setShowsRootHandles(true);
expandRoot();
}
/**
* Returns a <code>JTree</code> with the specified
* <code>TreeNode</code> as its root,
* which displays the root node.
* By default, the tree defines a leaf node as any node without children.
*
* @param root a <code>TreeNode</code> object
* @see DefaultTreeModel#asksAllowsChildren
*/
public JTree(TreeNode root) {
this(root, false);
}
/**
* Returns a <code>JTree</code> with the specified <code>TreeNode</code>
* as its root, which
* displays the root node and which decides whether a node is a
* leaf node in the specified manner.
*
* @param root a <code>TreeNode</code> object
* @param asksAllowsChildren if false, any node without children is a
* leaf node; if true, only nodes that do not allow
* children are leaf nodes
* @see DefaultTreeModel#asksAllowsChildren
*/
public JTree(TreeNode root, boolean asksAllowsChildren) {
this(new DefaultTreeModel(root, asksAllowsChildren));
}
/**
* Returns an instance of <code>JTree</code> which displays the root node
* -- the tree is created using the specified data model.
*
* @param newModel the <code>TreeModel</code> to use as the data model
*/
@ConstructorProperties({"model"})
public JTree(TreeModel newModel) {
super();
expandedStack = new Stack<Stack<TreePath>>();
toggleClickCount = 2;
expandedState = new Hashtable<TreePath, Boolean>();
setLayout(null);
rowHeight = 16;
visibleRowCount = 20;
rootVisible = true;
selectionModel = new DefaultTreeSelectionModel();
cellRenderer = null;
scrollsOnExpand = true;
setOpaque(true);
expandsSelectedPaths = true;
updateUI();
setModel(newModel);
}
/**
* Returns the L&F object that renders this component.
*
* @return the <code>TreeUI</code> object that renders this component
*/
public TreeUI getUI() {
return (TreeUI)ui;
}
/**
* Sets the L&F object that renders this component.
* <p>
* This is a bound property.
*
* @param ui the <code>TreeUI</code> L&F object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
*/
public void setUI(TreeUI ui) {
if (this.ui != ui) {
settingUI = true;
uiTreeExpansionListener = null;
try {
super.setUI(ui);
}
finally {
settingUI = false;
}
}
}
/**
* Notification from the <code>UIManager</code> that the L&F has changed.
* Replaces the current UI object with the latest version from the
* <code>UIManager</code>.
*
* @see JComponent#updateUI
*/
public void updateUI() {
setUI((TreeUI)UIManager.getUI(this));
SwingUtilities.updateRendererOrEditorUI(getCellRenderer());
SwingUtilities.updateRendererOrEditorUI(getCellEditor());
}
/**
* Returns the name of the L&F class that renders this component.
*
* @return the string "TreeUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/**
* Returns the current <code>TreeCellRenderer</code>
* that is rendering each cell.
*
* @return the <code>TreeCellRenderer</code> that is rendering each cell
*/
public TreeCellRenderer getCellRenderer() {
return cellRenderer;
}
/**
* Sets the <code>TreeCellRenderer</code> that will be used to
* draw each cell.
* <p>
* This is a bound property.
*
* @param x the <code>TreeCellRenderer</code> that is to render each cell
* @beaninfo
* bound: true
* description: The TreeCellRenderer that will be used to draw
* each cell.
*/
public void setCellRenderer(TreeCellRenderer x) {
TreeCellRenderer oldValue = cellRenderer;
cellRenderer = x;
firePropertyChange(CELL_RENDERER_PROPERTY, oldValue, cellRenderer);
invalidate();
}
/**
* Determines whether the tree is editable. Fires a property
* change event if the new setting is different from the existing
* setting.
* <p>
* This is a bound property.
*
* @param flag a boolean value, true if the tree is editable
* @beaninfo
* bound: true
* description: Whether the tree is editable.
*/
public void setEditable(boolean flag) {
boolean oldValue = this.editable;
this.editable = flag;
firePropertyChange(EDITABLE_PROPERTY, oldValue, flag);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
(oldValue ? AccessibleState.EDITABLE : null),
(flag ? AccessibleState.EDITABLE : null));
}
}
/**
* Returns true if the tree is editable.
*
* @return true if the tree is editable
*/
public boolean isEditable() {
return editable;
}
/**
* Sets the cell editor. A <code>null</code> value implies that the
* tree cannot be edited. If this represents a change in the
* <code>cellEditor</code>, the <code>propertyChange</code>
* method is invoked on all listeners.
* <p>
* This is a bound property.
*
* @param cellEditor the <code>TreeCellEditor</code> to use
* @beaninfo
* bound: true
* description: The cell editor. A null value implies the tree
* cannot be edited.
*/
public void setCellEditor(TreeCellEditor cellEditor) {
TreeCellEditor oldEditor = this.cellEditor;
this.cellEditor = cellEditor;
firePropertyChange(CELL_EDITOR_PROPERTY, oldEditor, cellEditor);
invalidate();
}
/**
* Returns the editor used to edit entries in the tree.
*
* @return the <code>TreeCellEditor</code> in use,
* or <code>null</code> if the tree cannot be edited
*/
public TreeCellEditor getCellEditor() {
return cellEditor;
}
/**
* Returns the <code>TreeModel</code> that is providing the data.
*
* @return the <code>TreeModel</code> that is providing the data
*/
public TreeModel getModel() {
return treeModel;
}
/**
* Sets the <code>TreeModel</code> that will provide the data.
* <p>
* This is a bound property.
*
* @param newModel the <code>TreeModel</code> that is to provide the data
* @beaninfo
* bound: true
* description: The TreeModel that will provide the data.
*/
public void setModel(TreeModel newModel) {
clearSelection();
TreeModel oldModel = treeModel;
if(treeModel != null && treeModelListener != null)
treeModel.removeTreeModelListener(treeModelListener);
if (accessibleContext != null) {
if (treeModel != null) {
treeModel.removeTreeModelListener((TreeModelListener)accessibleContext);
}
if (newModel != null) {
newModel.addTreeModelListener((TreeModelListener)accessibleContext);
}
}
treeModel = newModel;
clearToggledPaths();
if(treeModel != null) {
if(treeModelListener == null)
treeModelListener = createTreeModelListener();
if(treeModelListener != null)
treeModel.addTreeModelListener(treeModelListener);
// Mark the root as expanded, if it isn't a leaf.
if(treeModel.getRoot() != null &&
!treeModel.isLeaf(treeModel.getRoot())) {
expandedState.put(new TreePath(treeModel.getRoot()),
Boolean.TRUE);
}
}
firePropertyChange(TREE_MODEL_PROPERTY, oldModel, treeModel);
invalidate();
}
/**
* Returns true if the root node of the tree is displayed.
*
* @return true if the root node of the tree is displayed
* @see #rootVisible
*/
public boolean isRootVisible() {
return rootVisible;
}
/**
* Determines whether or not the root node from
* the <code>TreeModel</code> is visible.
* <p>
* This is a bound property.
*
* @param rootVisible true if the root node of the tree is to be displayed
* @see #rootVisible
* @beaninfo
* bound: true
* description: Whether or not the root node
* from the TreeModel is visible.
*/
public void setRootVisible(boolean rootVisible) {
boolean oldValue = this.rootVisible;
this.rootVisible = rootVisible;
firePropertyChange(ROOT_VISIBLE_PROPERTY, oldValue, this.rootVisible);
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
}
}
/**
* Sets the value of the <code>showsRootHandles</code> property,
* which specifies whether the node handles should be displayed.
* The default value of this property depends on the constructor
* used to create the <code>JTree</code>.
* Some look and feels might not support handles;
* they will ignore this property.
* <p>
* This is a bound property.
*
* @param newValue <code>true</code> if root handles should be displayed;
* otherwise, <code>false</code>
* @see #showsRootHandles
* @see #getShowsRootHandles
* @beaninfo
* bound: true
* description: Whether the node handles are to be
* displayed.
*/
public void setShowsRootHandles(boolean newValue) {
boolean oldValue = showsRootHandles;
TreeModel model = getModel();
showsRootHandles = newValue;
showsRootHandlesSet = true;
firePropertyChange(SHOWS_ROOT_HANDLES_PROPERTY, oldValue,
showsRootHandles);
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
}
invalidate();
}
/**
* Returns the value of the <code>showsRootHandles</code> property.
*
* @return the value of the <code>showsRootHandles</code> property
* @see #showsRootHandles
*/
public boolean getShowsRootHandles()
{
return showsRootHandles;
}
/**
* Sets the height of each cell, in pixels. If the specified value
* is less than or equal to zero the current cell renderer is
* queried for each row's height.
* <p>
* This is a bound property.
*
* @param rowHeight the height of each cell, in pixels
* @beaninfo
* bound: true
* description: The height of each cell.
*/
public void setRowHeight(int rowHeight)
{
int oldValue = this.rowHeight;
this.rowHeight = rowHeight;
rowHeightSet = true;
firePropertyChange(ROW_HEIGHT_PROPERTY, oldValue, this.rowHeight);
invalidate();
}
/**
* Returns the height of each row. If the returned value is less than
* or equal to 0 the height for each row is determined by the
* renderer.
*
*/
public int getRowHeight()
{
return rowHeight;
}
/**
* Returns true if the height of each display row is a fixed size.
*
* @return true if the height of each row is a fixed size
*/
public boolean isFixedRowHeight()
{
return (rowHeight > 0);
}
/**
* Specifies whether the UI should use a large model.
* (Not all UIs will implement this.) Fires a property change
* for the LARGE_MODEL_PROPERTY.
* <p>
* This is a bound property.
*
* @param newValue true to suggest a large model to the UI
* @see #largeModel
* @beaninfo
* bound: true
* description: Whether the UI should use a
* large model.
*/
public void setLargeModel(boolean newValue) {
boolean oldValue = largeModel;
largeModel = newValue;
firePropertyChange(LARGE_MODEL_PROPERTY, oldValue, newValue);
}
/**
* Returns true if the tree is configured for a large model.
*
* @return true if a large model is suggested
* @see #largeModel
*/
public boolean isLargeModel() {
return largeModel;
}
/**
* Determines what happens when editing is interrupted by selecting
* another node in the tree, a change in the tree's data, or by some
* other means. Setting this property to <code>true</code> causes the
* changes to be automatically saved when editing is interrupted.
* <p>
* Fires a property change for the INVOKES_STOP_CELL_EDITING_PROPERTY.
*
* @param newValue true means that <code>stopCellEditing</code> is invoked
* when editing is interrupted, and data is saved; false means that
* <code>cancelCellEditing</code> is invoked, and changes are lost
* @beaninfo
* bound: true
* description: Determines what happens when editing is interrupted,
* selecting another node in the tree, a change in the
* tree's data, or some other means.
*/
public void setInvokesStopCellEditing(boolean newValue) {
boolean oldValue = invokesStopCellEditing;
invokesStopCellEditing = newValue;
firePropertyChange(INVOKES_STOP_CELL_EDITING_PROPERTY, oldValue,
newValue);
}
/**
* Returns the indicator that tells what happens when editing is
* interrupted.
*
* @return the indicator that tells what happens when editing is
* interrupted
* @see #setInvokesStopCellEditing
*/
public boolean getInvokesStopCellEditing() {
return invokesStopCellEditing;
}
/**
* Sets the <code>scrollsOnExpand</code> property,
* which determines whether the
* tree might scroll to show previously hidden children.
* If this property is <code>true</code> (the default),
* when a node expands
* the tree can use scrolling to make
* the maximum possible number of the node's descendants visible.
* In some look and feels, trees might not need to scroll when expanded;
* those look and feels will ignore this property.
* <p>
* This is a bound property.
*
* @param newValue <code>false</code> to disable scrolling on expansion;
* <code>true</code> to enable it
* @see #getScrollsOnExpand
*
* @beaninfo
* bound: true
* description: Indicates if a node descendant should be scrolled when expanded.
*/
public void setScrollsOnExpand(boolean newValue) {
boolean oldValue = scrollsOnExpand;
scrollsOnExpand = newValue;
scrollsOnExpandSet = true;
firePropertyChange(SCROLLS_ON_EXPAND_PROPERTY, oldValue,
newValue);
}
/**
* Returns the value of the <code>scrollsOnExpand</code> property.
*
* @return the value of the <code>scrollsOnExpand</code> property
*/
public boolean getScrollsOnExpand() {
return scrollsOnExpand;
}
/**
* Sets the number of mouse clicks before a node will expand or close.
* The default is two.
* <p>
* This is a bound property.
*
* @since 1.3
* @beaninfo
* bound: true
* description: Number of clicks before a node will expand/collapse.
*/
public void setToggleClickCount(int clickCount) {
int oldCount = toggleClickCount;
toggleClickCount = clickCount;
firePropertyChange(TOGGLE_CLICK_COUNT_PROPERTY, oldCount,
clickCount);
}
/**
* Returns the number of mouse clicks needed to expand or close a node.
*
* @return number of mouse clicks before node is expanded
* @since 1.3
*/
public int getToggleClickCount() {
return toggleClickCount;
}
/**
* Configures the <code>expandsSelectedPaths</code> property. If
* true, any time the selection is changed, either via the
* <code>TreeSelectionModel</code>, or the cover methods provided by
* <code>JTree</code>, the <code>TreePath</code>s parents will be
* expanded to make them visible (visible meaning the parent path is
* expanded, not necessarily in the visible rectangle of the
* <code>JTree</code>). If false, when the selection
* changes the nodes parent is not made visible (all its parents expanded).
* This is useful if you wish to have your selection model maintain paths
* that are not always visible (all parents expanded).
* <p>
* This is a bound property.
*
* @param newValue the new value for <code>expandsSelectedPaths</code>
*
* @since 1.3
* @beaninfo
* bound: true
* description: Indicates whether changes to the selection should make
* the parent of the path visible.
*/
public void setExpandsSelectedPaths(boolean newValue) {
boolean oldValue = expandsSelectedPaths;
expandsSelectedPaths = newValue;
firePropertyChange(EXPANDS_SELECTED_PATHS_PROPERTY, oldValue,
newValue);
}
/**
* Returns the <code>expandsSelectedPaths</code> property.
* @return true if selection changes result in the parent path being
* expanded
* @since 1.3
* @see #setExpandsSelectedPaths
*/
public boolean getExpandsSelectedPaths() {
return expandsSelectedPaths;
}
/**
* Turns on or off automatic drag handling. In order to enable automatic
* drag handling, this property should be set to {@code true}, and the
* tree's {@code TransferHandler} needs to be {@code non-null}.
* The default value of the {@code dragEnabled} property is {@code false}.
* <p>
* The job of honoring this property, and recognizing a user drag gesture,
* lies with the look and feel implementation, and in particular, the tree's
* {@code TreeUI}. When automatic drag handling is enabled, most look and
* feels (including those that subclass {@code BasicLookAndFeel}) begin a
* drag and drop operation whenever the user presses the mouse button over
* an item and then moves the mouse a few pixels. Setting this property to
* {@code true} can therefore have a subtle effect on how selections behave.
* <p>
* If a look and feel is used that ignores this property, you can still
* begin a drag and drop operation by calling {@code exportAsDrag} on the
* tree's {@code TransferHandler}.
*
* @param b whether or not to enable automatic drag handling
* @exception HeadlessException if
* <code>b</code> is <code>true</code> and
* <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #getDragEnabled
* @see #setTransferHandler
* @see TransferHandler
* @since 1.4
*
* @beaninfo
* description: determines whether automatic drag handling is enabled
* bound: false
*/
public void setDragEnabled(boolean b) {
if (b && GraphicsEnvironment.isHeadless()) {
throw new HeadlessException();
}
dragEnabled = b;
}
/**
* Returns whether or not automatic drag handling is enabled.
*
* @return the value of the {@code dragEnabled} property
* @see #setDragEnabled
* @since 1.4
*/
public boolean getDragEnabled() {
return dragEnabled;
}
/**
* Sets the drop mode for this component. For backward compatibility,
* the default for this property is <code>DropMode.USE_SELECTION</code>.
* Usage of one of the other modes is recommended, however, for an
* improved user experience. <code>DropMode.ON</code>, for instance,
* offers similar behavior of showing items as selected, but does so without
* affecting the actual selection in the tree.
* <p>
* <code>JTree</code> supports the following drop modes:
* <ul>
* <li><code>DropMode.USE_SELECTION</code></li>
* <li><code>DropMode.ON</code></li>
* <li><code>DropMode.INSERT</code></li>
* <li><code>DropMode.ON_OR_INSERT</code></li>
* </ul>
* <p>
* The drop mode is only meaningful if this component has a
* <code>TransferHandler</code> that accepts drops.
*
* @param dropMode the drop mode to use
* @throws IllegalArgumentException if the drop mode is unsupported
* or <code>null</code>
* @see #getDropMode
* @see #getDropLocation
* @see #setTransferHandler
* @see TransferHandler
* @since 1.6
*/
public final void setDropMode(DropMode dropMode) {
if (dropMode != null) {
switch (dropMode) {
case USE_SELECTION:
case ON:
case INSERT:
case ON_OR_INSERT:
this.dropMode = dropMode;
return;
}
}
throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for tree");
}
/**
* Returns the drop mode for this component.
*
* @return the drop mode for this component
* @see #setDropMode
* @since 1.6
*/
public final DropMode getDropMode() {
return dropMode;
}
/**
* Calculates a drop location in this component, representing where a
* drop at the given point should insert data.
*
* @param p the point to calculate a drop location for
* @return the drop location, or <code>null</code>
*/
DropLocation dropLocationForPoint(Point p) {
DropLocation location = null;
int row = getClosestRowForLocation(p.x, p.y);
Rectangle bounds = getRowBounds(row);
TreeModel model = getModel();
Object root = (model == null) ? null : model.getRoot();
TreePath rootPath = (root == null) ? null : new TreePath(root);
TreePath child;
TreePath parent;
boolean outside = row == -1
|| p.y < bounds.y
|| p.y >= bounds.y + bounds.height;
switch(dropMode) {
case USE_SELECTION:
case ON:
if (outside) {
location = new DropLocation(p, null, -1);
} else {
location = new DropLocation(p, getPathForRow(row), -1);
}
break;
case INSERT:
case ON_OR_INSERT:
if (row == -1) {
if (root != null && !model.isLeaf(root) && isExpanded(rootPath)) {
location = new DropLocation(p, rootPath, 0);
} else {
location = new DropLocation(p, null, -1);
}
break;
}
boolean checkOn = dropMode == DropMode.ON_OR_INSERT
|| !model.isLeaf(getPathForRow(row).getLastPathComponent());
Section section = SwingUtilities2.liesInVertical(bounds, p, checkOn);
if(section == LEADING) {
child = getPathForRow(row);
parent = child.getParentPath();
} else if (section == TRAILING) {
int index = row + 1;
if (index >= getRowCount()) {
if (model.isLeaf(root) || !isExpanded(rootPath)) {
location = new DropLocation(p, null, -1);
} else {
parent = rootPath;
index = model.getChildCount(root);
location = new DropLocation(p, parent, index);
}
break;
}
child = getPathForRow(index);
parent = child.getParentPath();
} else {
assert checkOn;
location = new DropLocation(p, getPathForRow(row), -1);
break;
}
if (parent != null) {
location = new DropLocation(p, parent,
model.getIndexOfChild(parent.getLastPathComponent(),
child.getLastPathComponent()));
} else if (checkOn || !model.isLeaf(root)) {
location = new DropLocation(p, rootPath, -1);
} else {
location = new DropLocation(p, null, -1);
}
break;
default:
assert false : "Unexpected drop mode";
}
if (outside || row != expandRow) {
cancelDropTimer();
}
if (!outside && row != expandRow) {
if (isCollapsed(row)) {
expandRow = row;
startDropTimer();
}
}
return location;
}
/**
* Called to set or clear the drop location during a DnD operation.
* In some cases, the component may need to use it's internal selection
* temporarily to indicate the drop location. To help facilitate this,
* this method returns and accepts as a parameter a state object.
* This state object can be used to store, and later restore, the selection
* state. Whatever this method returns will be passed back to it in
* future calls, as the state parameter. If it wants the DnD system to
* continue storing the same state, it must pass it back every time.
* Here's how this is used:
* <p>
* Let's say that on the first call to this method the component decides
* to save some state (because it is about to use the selection to show
* a drop index). It can return a state object to the caller encapsulating
* any saved selection state. On a second call, let's say the drop location
* is being changed to something else. The component doesn't need to
* restore anything yet, so it simply passes back the same state object
* to have the DnD system continue storing it. Finally, let's say this
* method is messaged with <code>null</code>. This means DnD
* is finished with this component for now, meaning it should restore
* state. At this point, it can use the state parameter to restore
* said state, and of course return <code>null</code> since there's
* no longer anything to store.
*
* @param location the drop location (as calculated by
* <code>dropLocationForPoint</code>) or <code>null</code>
* if there's no longer a valid drop location
* @param state the state object saved earlier for this component,
* or <code>null</code>
* @param forDrop whether or not the method is being called because an
* actual drop occurred
* @return any saved state for this component, or <code>null</code> if none
*/
Object setDropLocation(TransferHandler.DropLocation location,
Object state,
boolean forDrop) {
Object retVal = null;
DropLocation treeLocation = (DropLocation)location;
if (dropMode == DropMode.USE_SELECTION) {
if (treeLocation == null) {
if (!forDrop && state != null) {
setSelectionPaths(((TreePath[][])state)[0]);
setAnchorSelectionPath(((TreePath[][])state)[1][0]);
setLeadSelectionPath(((TreePath[][])state)[1][1]);
}
} else {
if (dropLocation == null) {
TreePath[] paths = getSelectionPaths();
if (paths == null) {
paths = new TreePath[0];
}
retVal = new TreePath[][] {paths,
{getAnchorSelectionPath(), getLeadSelectionPath()}};
} else {
retVal = state;
}
setSelectionPath(treeLocation.getPath());
}
}
DropLocation old = dropLocation;
dropLocation = treeLocation;
firePropertyChange("dropLocation", old, dropLocation);
return retVal;
}
/**
* Called to indicate to this component that DnD is done.
* Allows for us to cancel the expand timer.
*/
void dndDone() {
cancelDropTimer();
dropTimer = null;
}
/**
* Returns the location that this component should visually indicate
* as the drop location during a DnD operation over the component,
* or {@code null} if no location is to currently be shown.
* <p>
* This method is not meant for querying the drop location
* from a {@code TransferHandler}, as the drop location is only
* set after the {@code TransferHandler}'s <code>canImport</code>
* has returned and has allowed for the location to be shown.
* <p>
* When this property changes, a property change event with
* name "dropLocation" is fired by the component.
*
* @return the drop location
* @see #setDropMode
* @see TransferHandler#canImport(TransferHandler.TransferSupport)
* @since 1.6
*/
public final DropLocation getDropLocation() {
return dropLocation;
}
private void startDropTimer() {
if (dropTimer == null) {
dropTimer = new TreeTimer();
}
dropTimer.start();
}
private void cancelDropTimer() {
if (dropTimer != null && dropTimer.isRunning()) {
expandRow = -1;
dropTimer.stop();
}
}
/**
* Returns <code>isEditable</code>. This is invoked from the UI before
* editing begins to insure that the given path can be edited. This
* is provided as an entry point for subclassers to add filtered
* editing without having to resort to creating a new editor.
*
* @return true if every parent node and the node itself is editable
* @see #isEditable
*/
public boolean isPathEditable(TreePath path) {
return isEditable();
}
/**
* Overrides <code>JComponent</code>'s <code>getToolTipText</code>
* method in order to allow
* renderer's tips to be used if it has text set.
* <p>
* NOTE: For <code>JTree</code> to properly display tooltips of its
* renderers, <code>JTree</code> must be a registered component with the
* <code>ToolTipManager</code>. This can be done by invoking
* <code>ToolTipManager.sharedInstance().registerComponent(tree)</code>.
* This is not done automatically!
*
* @param event the <code>MouseEvent</code> that initiated the
* <code>ToolTip</code> display
* @return a string containing the tooltip or <code>null</code>
* if <code>event</code> is null
*/
public String getToolTipText(MouseEvent event) {
String tip = null;
if(event != null) {
Point p = event.getPoint();
int selRow = getRowForLocation(p.x, p.y);
TreeCellRenderer r = getCellRenderer();
if(selRow != -1 && r != null) {
TreePath path = getPathForRow(selRow);
Object lastPath = path.getLastPathComponent();
Component rComponent = r.getTreeCellRendererComponent
(this, lastPath, isRowSelected(selRow),
isExpanded(selRow), getModel().isLeaf(lastPath), selRow,
true);
if(rComponent instanceof JComponent) {
MouseEvent newEvent;
Rectangle pathBounds = getPathBounds(path);
p.translate(-pathBounds.x, -pathBounds.y);
newEvent = new MouseEvent(rComponent, event.getID(),
event.getWhen(),
event.getModifiers(),
p.x, p.y,
event.getXOnScreen(),
event.getYOnScreen(),
event.getClickCount(),
event.isPopupTrigger(),
MouseEvent.NOBUTTON);
tip = ((JComponent)rComponent).getToolTipText(newEvent);
}
}
}
// No tip from the renderer get our own tip
if (tip == null) {
tip = getToolTipText();
}
return tip;
}
/**
* Called by the renderers to convert the specified value to
* text. This implementation returns <code>value.toString</code>, ignoring
* all other arguments. To control the conversion, subclass this
* method and use any of the arguments you need.
*
* @param value the <code>Object</code> to convert to text
* @param selected true if the node is selected
* @param expanded true if the node is expanded
* @param leaf true if the node is a leaf node
* @param row an integer specifying the node's display row, where 0 is
* the first row in the display
* @param hasFocus true if the node has the focus
* @return the <code>String</code> representation of the node's value
*/
public String convertValueToText(Object value, boolean selected,
boolean expanded, boolean leaf, int row,
boolean hasFocus) {
if(value != null) {
String sValue = value.toString();
if (sValue != null) {
return sValue;
}
}
return "";
}
//
// The following are convenience methods that get forwarded to the
// current TreeUI.
//
/**
* Returns the number of viewable nodes. A node is viewable if all of its
* parents are expanded. The root is only included in this count if
* {@code isRootVisible()} is {@code true}. This returns {@code 0} if
* the UI has not been set.
*
* @return the number of viewable nodes
*/
public int getRowCount() {
TreeUI tree = getUI();
if(tree != null)
return tree.getRowCount(this);
return 0;
}
/**
* Selects the node identified by the specified path. If any
* component of the path is hidden (under a collapsed node), and
* <code>getExpandsSelectedPaths</code> is true it is
* exposed (made viewable).
*
* @param path the <code>TreePath</code> specifying the node to select
*/
public void setSelectionPath(TreePath path) {
getSelectionModel().setSelectionPath(path);
}
/**
* Selects the nodes identified by the specified array of paths.
* If any component in any of the paths is hidden (under a collapsed
* node), and <code>getExpandsSelectedPaths</code> is true
* it is exposed (made viewable).
*
* @param paths an array of <code>TreePath</code> objects that specifies
* the nodes to select
*/
public void setSelectionPaths(TreePath[] paths) {
getSelectionModel().setSelectionPaths(paths);
}
/**
* Sets the path identifies as the lead. The lead may not be selected.
* The lead is not maintained by <code>JTree</code>,
* rather the UI will update it.
* <p>
* This is a bound property.
*
* @param newPath the new lead path
* @since 1.3
* @beaninfo
* bound: true
* description: Lead selection path
*/
public void setLeadSelectionPath(TreePath newPath) {
TreePath oldValue = leadPath;
leadPath = newPath;
firePropertyChange(LEAD_SELECTION_PATH_PROPERTY, oldValue, newPath);
}
/**
* Sets the path identified as the anchor.
* The anchor is not maintained by <code>JTree</code>, rather the UI will
* update it.
* <p>
* This is a bound property.
*
* @param newPath the new anchor path
* @since 1.3
* @beaninfo
* bound: true
* description: Anchor selection path
*/
public void setAnchorSelectionPath(TreePath newPath) {
TreePath oldValue = anchorPath;
anchorPath = newPath;
firePropertyChange(ANCHOR_SELECTION_PATH_PROPERTY, oldValue, newPath);
}
/**
* Selects the node at the specified row in the display.
*
* @param row the row to select, where 0 is the first row in
* the display
*/
public void setSelectionRow(int row) {
int[] rows = { row };
setSelectionRows(rows);
}
/**
* Selects the nodes corresponding to each of the specified rows
* in the display. If a particular element of <code>rows</code> is
* < 0 or >= <code>getRowCount</code>, it will be ignored.
* If none of the elements
* in <code>rows</code> are valid rows, the selection will
* be cleared. That is it will be as if <code>clearSelection</code>
* was invoked.
*
* @param rows an array of ints specifying the rows to select,
* where 0 indicates the first row in the display
*/
public void setSelectionRows(int[] rows) {
TreeUI ui = getUI();
if(ui != null && rows != null) {
int numRows = rows.length;
TreePath[] paths = new TreePath[numRows];
for(int counter = 0; counter < numRows; counter++) {
paths[counter] = ui.getPathForRow(this, rows[counter]);
}
setSelectionPaths(paths);
}
}
/**
* Adds the node identified by the specified <code>TreePath</code>
* to the current selection. If any component of the path isn't
* viewable, and <code>getExpandsSelectedPaths</code> is true it is
* made viewable.
* <p>
* Note that <code>JTree</code> does not allow duplicate nodes to
* exist as children under the same parent -- each sibling must be
* a unique object.
*
* @param path the <code>TreePath</code> to add
*/
public void addSelectionPath(TreePath path) {
getSelectionModel().addSelectionPath(path);
}
/**
* Adds each path in the array of paths to the current selection. If
* any component of any of the paths isn't viewable and
* <code>getExpandsSelectedPaths</code> is true, it is
* made viewable.
* <p>
* Note that <code>JTree</code> does not allow duplicate nodes to
* exist as children under the same parent -- each sibling must be
* a unique object.
*
* @param paths an array of <code>TreePath</code> objects that specifies
* the nodes to add
*/
public void addSelectionPaths(TreePath[] paths) {
getSelectionModel().addSelectionPaths(paths);
}
/**
* Adds the path at the specified row to the current selection.
*
* @param row an integer specifying the row of the node to add,
* where 0 is the first row in the display
*/
public void addSelectionRow(int row) {
int[] rows = { row };
addSelectionRows(rows);
}
/**
* Adds the paths at each of the specified rows to the current selection.
*
* @param rows an array of ints specifying the rows to add,
* where 0 indicates the first row in the display
*/
public void addSelectionRows(int[] rows) {
TreeUI ui = getUI();
if(ui != null && rows != null) {
int numRows = rows.length;
TreePath[] paths = new TreePath[numRows];
for(int counter = 0; counter < numRows; counter++)
paths[counter] = ui.getPathForRow(this, rows[counter]);
addSelectionPaths(paths);
}
}
/**
* Returns the last path component of the selected path. This is
* a convenience method for
* {@code getSelectionModel().getSelectionPath().getLastPathComponent()}.
* This is typically only useful if the selection has one path.
*
* @return the last path component of the selected path, or
* <code>null</code> if nothing is selected
* @see TreePath#getLastPathComponent
*/
public Object getLastSelectedPathComponent() {
TreePath selPath = getSelectionModel().getSelectionPath();
if(selPath != null)
return selPath.getLastPathComponent();
return null;
}
/**
* Returns the path identified as the lead.
* @return path identified as the lead
*/
public TreePath getLeadSelectionPath() {
return leadPath;
}
/**
* Returns the path identified as the anchor.
* @return path identified as the anchor
* @since 1.3
*/
public TreePath getAnchorSelectionPath() {
return anchorPath;
}
/**
* Returns the path to the first selected node.
*
* @return the <code>TreePath</code> for the first selected node,
* or <code>null</code> if nothing is currently selected
*/
public TreePath getSelectionPath() {
return getSelectionModel().getSelectionPath();
}
/**
* Returns the paths of all selected values.
*
* @return an array of <code>TreePath</code> objects indicating the selected
* nodes, or <code>null</code> if nothing is currently selected
*/
public TreePath[] getSelectionPaths() {
TreePath[] selectionPaths = getSelectionModel().getSelectionPaths();
return (selectionPaths != null && selectionPaths.length > 0) ? selectionPaths : null;
}
/**
* Returns all of the currently selected rows. This method is simply
* forwarded to the <code>TreeSelectionModel</code>.
* If nothing is selected <code>null</code> or an empty array will
* be returned, based on the <code>TreeSelectionModel</code>
* implementation.
*
* @return an array of integers that identifies all currently selected rows
* where 0 is the first row in the display
*/
public int[] getSelectionRows() {
return getSelectionModel().getSelectionRows();
}
/**
* Returns the number of nodes selected.
*
* @return the number of nodes selected
*/
public int getSelectionCount() {
return selectionModel.getSelectionCount();
}
/**
* Returns the smallest selected row. If the selection is empty, or
* none of the selected paths are viewable, {@code -1} is returned.
*
* @return the smallest selected row
*/
public int getMinSelectionRow() {
return getSelectionModel().getMinSelectionRow();
}
/**
* Returns the largest selected row. If the selection is empty, or
* none of the selected paths are viewable, {@code -1} is returned.
*
* @return the largest selected row
*/
public int getMaxSelectionRow() {
return getSelectionModel().getMaxSelectionRow();
}
/**
* Returns the row index corresponding to the lead path.
*
* @return an integer giving the row index of the lead path,
* where 0 is the first row in the display; or -1
* if <code>leadPath</code> is <code>null</code>
*/
public int getLeadSelectionRow() {
TreePath leadPath = getLeadSelectionPath();
if (leadPath != null) {
return getRowForPath(leadPath);
}
return -1;
}
/**
* Returns true if the item identified by the path is currently selected.
*
* @param path a <code>TreePath</code> identifying a node
* @return true if the node is selected
*/
public boolean isPathSelected(TreePath path) {
return getSelectionModel().isPathSelected(path);
}
/**
* Returns true if the node identified by row is selected.
*
* @param row an integer specifying a display row, where 0 is the first
* row in the display
* @return true if the node is selected
*/
public boolean isRowSelected(int row) {
return getSelectionModel().isRowSelected(row);
}
/**
* Returns an <code>Enumeration</code> of the descendants of the
* path <code>parent</code> that
* are currently expanded. If <code>parent</code> is not currently
* expanded, this will return <code>null</code>.
* If you expand/collapse nodes while
* iterating over the returned <code>Enumeration</code>
* this may not return all
* the expanded paths, or may return paths that are no longer expanded.
*
* @param parent the path which is to be examined
* @return an <code>Enumeration</code> of the descendents of
* <code>parent</code>, or <code>null</code> if
* <code>parent</code> is not currently expanded
*/
public Enumeration<TreePath> getExpandedDescendants(TreePath parent) {
if(!isExpanded(parent))
return null;
Enumeration<TreePath> toggledPaths = expandedState.keys();
Vector<TreePath> elements = null;
TreePath path;
Object value;
if(toggledPaths != null) {
while(toggledPaths.hasMoreElements()) {
path = toggledPaths.nextElement();
value = expandedState.get(path);
// Add the path if it is expanded, a descendant of parent,
// and it is visible (all parents expanded). This is rather
// expensive!
if(path != parent && value != null &&
((Boolean)value).booleanValue() &&
parent.isDescendant(path) && isVisible(path)) {
if (elements == null) {
elements = new Vector<TreePath>();
}
elements.addElement(path);
}
}
}
if (elements == null) {
Set<TreePath> empty = Collections.emptySet();
return Collections.enumeration(empty);
}
return elements.elements();
}
/**
* Returns true if the node identified by the path has ever been
* expanded.
* @return true if the <code>path</code> has ever been expanded
*/
public boolean hasBeenExpanded(TreePath path) {
return (path != null && expandedState.get(path) != null);
}
/**
* Returns true if the node identified by the path is currently expanded,
*
* @param path the <code>TreePath</code> specifying the node to check
* @return false if any of the nodes in the node's path are collapsed,
* true if all nodes in the path are expanded
*/
public boolean isExpanded(TreePath path) {
if(path == null)
return false;
Object value;
do{
value = expandedState.get(path);
if(value == null || !((Boolean)value).booleanValue())
return false;
} while( (path=path.getParentPath())!=null );
return true;
}
/**
* Returns true if the node at the specified display row is currently
* expanded.
*
* @param row the row to check, where 0 is the first row in the
* display
* @return true if the node is currently expanded, otherwise false
*/
public boolean isExpanded(int row) {
TreeUI tree = getUI();
if(tree != null) {
TreePath path = tree.getPathForRow(this, row);
if(path != null) {
Boolean value = expandedState.get(path);
return (value != null && value.booleanValue());
}
}
return false;
}
/**
* Returns true if the value identified by path is currently collapsed,
* this will return false if any of the values in path are currently
* not being displayed.
*
* @param path the <code>TreePath</code> to check
* @return true if any of the nodes in the node's path are collapsed,
* false if all nodes in the path are expanded
*/
public boolean isCollapsed(TreePath path) {
return !isExpanded(path);
}
/**
* Returns true if the node at the specified display row is collapsed.
*
* @param row the row to check, where 0 is the first row in the
* display
* @return true if the node is currently collapsed, otherwise false
*/
public boolean isCollapsed(int row) {
return !isExpanded(row);
}
/**
* Ensures that the node identified by path is currently viewable.
*
* @param path the <code>TreePath</code> to make visible
*/
public void makeVisible(TreePath path) {
if(path != null) {
TreePath parentPath = path.getParentPath();
if(parentPath != null) {
expandPath(parentPath);
}
}
}
/**
* Returns true if the value identified by path is currently viewable,
* which means it is either the root or all of its parents are expanded.
* Otherwise, this method returns false.
*
* @return true if the node is viewable, otherwise false
*/
public boolean isVisible(TreePath path) {
if(path != null) {
TreePath parentPath = path.getParentPath();
if(parentPath != null)
return isExpanded(parentPath);
// Root.
return true;
}
return false;
}
/**
* Returns the <code>Rectangle</code> that the specified node will be drawn
* into. Returns <code>null</code> if any component in the path is hidden
* (under a collapsed parent).
* <p>
* Note:<br>
* This method returns a valid rectangle, even if the specified
* node is not currently displayed.
*
* @param path the <code>TreePath</code> identifying the node
* @return the <code>Rectangle</code> the node is drawn in,
* or <code>null</code>
*/
public Rectangle getPathBounds(TreePath path) {
TreeUI tree = getUI();
if(tree != null)
return tree.getPathBounds(this, path);
return null;
}
/**
* Returns the <code>Rectangle</code> that the node at the specified row is
* drawn in.
*
* @param row the row to be drawn, where 0 is the first row in the
* display
* @return the <code>Rectangle</code> the node is drawn in
*/
public Rectangle getRowBounds(int row) {
return getPathBounds(getPathForRow(row));
}
/**
* Makes sure all the path components in path are expanded (except
* for the last path component) and scrolls so that the
* node identified by the path is displayed. Only works when this
* <code>JTree</code> is contained in a <code>JScrollPane</code>.
*
* @param path the <code>TreePath</code> identifying the node to
* bring into view
*/
public void scrollPathToVisible(TreePath path) {
if(path != null) {
makeVisible(path);
Rectangle bounds = getPathBounds(path);
if(bounds != null) {
scrollRectToVisible(bounds);
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
}
}
}
}
/**
* Scrolls the item identified by row until it is displayed. The minimum
* of amount of scrolling necessary to bring the row into view
* is performed. Only works when this <code>JTree</code> is contained in a
* <code>JScrollPane</code>.
*
* @param row an integer specifying the row to scroll, where 0 is the
* first row in the display
*/
public void scrollRowToVisible(int row) {
scrollPathToVisible(getPathForRow(row));
}
/**
* Returns the path for the specified row. If <code>row</code> is
* not visible, or a {@code TreeUI} has not been set, <code>null</code>
* is returned.
*
* @param row an integer specifying a row
* @return the <code>TreePath</code> to the specified node,
* <code>null</code> if <code>row < 0</code>
* or <code>row >= getRowCount()</code>
*/
public TreePath getPathForRow(int row) {
TreeUI tree = getUI();
if(tree != null)
return tree.getPathForRow(this, row);
return null;
}
/**
* Returns the row that displays the node identified by the specified
* path.
*
* @param path the <code>TreePath</code> identifying a node
* @return an integer specifying the display row, where 0 is the first
* row in the display, or -1 if any of the elements in path
* are hidden under a collapsed parent.
*/
public int getRowForPath(TreePath path) {
TreeUI tree = getUI();
if(tree != null)
return tree.getRowForPath(this, path);
return -1;
}
/**
* Ensures that the node identified by the specified path is
* expanded and viewable. If the last item in the path is a
* leaf, this will have no effect.
*
* @param path the <code>TreePath</code> identifying a node
*/
public void expandPath(TreePath path) {
// Only expand if not leaf!
TreeModel model = getModel();
if(path != null && model != null &&
!model.isLeaf(path.getLastPathComponent())) {
setExpandedState(path, true);
}
}
/**
* Ensures that the node in the specified row is expanded and
* viewable.
* <p>
* If <code>row</code> is < 0 or >= <code>getRowCount</code> this
* will have no effect.
*
* @param row an integer specifying a display row, where 0 is the
* first row in the display
*/
public void expandRow(int row) {
expandPath(getPathForRow(row));
}
/**
* Ensures that the node identified by the specified path is
* collapsed and viewable.
*
* @param path the <code>TreePath</code> identifying a node
*/
public void collapsePath(TreePath path) {
setExpandedState(path, false);
}
/**
* Ensures that the node in the specified row is collapsed.
* <p>
* If <code>row</code> is < 0 or >= <code>getRowCount</code> this
* will have no effect.
*
* @param row an integer specifying a display row, where 0 is the
* first row in the display
*/
public void collapseRow(int row) {
collapsePath(getPathForRow(row));
}
/**
* Returns the path for the node at the specified location.
*
* @param x an integer giving the number of pixels horizontally from
* the left edge of the display area, minus any left margin
* @param y an integer giving the number of pixels vertically from
* the top of the display area, minus any top margin
* @return the <code>TreePath</code> for the node at that location
*/
public TreePath getPathForLocation(int x, int y) {
TreePath closestPath = getClosestPathForLocation(x, y);
if(closestPath != null) {
Rectangle pathBounds = getPathBounds(closestPath);
if(pathBounds != null &&
x >= pathBounds.x && x < (pathBounds.x + pathBounds.width) &&
y >= pathBounds.y && y < (pathBounds.y + pathBounds.height))
return closestPath;
}
return null;
}
/**
* Returns the row for the specified location.
*
* @param x an integer giving the number of pixels horizontally from
* the left edge of the display area, minus any left margin
* @param y an integer giving the number of pixels vertically from
* the top of the display area, minus any top margin
* @return the row corresponding to the location, or -1 if the
* location is not within the bounds of a displayed cell
* @see #getClosestRowForLocation
*/
public int getRowForLocation(int x, int y) {
return getRowForPath(getPathForLocation(x, y));
}
/**
* Returns the path to the node that is closest to x,y. If
* no nodes are currently viewable, or there is no model, returns
* <code>null</code>, otherwise it always returns a valid path. To test if
* the node is exactly at x, y, get the node's bounds and
* test x, y against that.
*
* @param x an integer giving the number of pixels horizontally from
* the left edge of the display area, minus any left margin
* @param y an integer giving the number of pixels vertically from
* the top of the display area, minus any top margin
* @return the <code>TreePath</code> for the node closest to that location,
* <code>null</code> if nothing is viewable or there is no model
*
* @see #getPathForLocation
* @see #getPathBounds
*/
public TreePath getClosestPathForLocation(int x, int y) {
TreeUI tree = getUI();
if(tree != null)
return tree.getClosestPathForLocation(this, x, y);
return null;
}
/**
* Returns the row to the node that is closest to x,y. If no nodes
* are viewable or there is no model, returns -1. Otherwise,
* it always returns a valid row. To test if the returned object is
* exactly at x, y, get the bounds for the node at the returned
* row and test x, y against that.
*
* @param x an integer giving the number of pixels horizontally from
* the left edge of the display area, minus any left margin
* @param y an integer giving the number of pixels vertically from
* the top of the display area, minus any top margin
* @return the row closest to the location, -1 if nothing is
* viewable or there is no model
*
* @see #getRowForLocation
* @see #getRowBounds
*/
public int getClosestRowForLocation(int x, int y) {
return getRowForPath(getClosestPathForLocation(x, y));
}
/**
* Returns true if the tree is being edited. The item that is being
* edited can be obtained using <code>getSelectionPath</code>.
*
* @return true if the user is currently editing a node
* @see #getSelectionPath
*/
public boolean isEditing() {
TreeUI tree = getUI();
if(tree != null)
return tree.isEditing(this);
return false;
}
/**
* Ends the current editing session.
* (The <code>DefaultTreeCellEditor</code>
* object saves any edits that are currently in progress on a cell.
* Other implementations may operate differently.)
* Has no effect if the tree isn't being edited.
* <blockquote>
* <b>Note:</b><br>
* To make edit-saves automatic whenever the user changes
* their position in the tree, use {@link #setInvokesStopCellEditing}.
* </blockquote>
*
* @return true if editing was in progress and is now stopped,
* false if editing was not in progress
*/
public boolean stopEditing() {
TreeUI tree = getUI();
if(tree != null)
return tree.stopEditing(this);
return false;
}
/**
* Cancels the current editing session. Has no effect if the
* tree isn't being edited.
*/
public void cancelEditing() {
TreeUI tree = getUI();
if(tree != null)
tree.cancelEditing(this);
}
/**
* Selects the node identified by the specified path and initiates
* editing. The edit-attempt fails if the <code>CellEditor</code>
* does not allow
* editing for the specified item.
*
* @param path the <code>TreePath</code> identifying a node
*/
public void startEditingAtPath(TreePath path) {
TreeUI tree = getUI();
if(tree != null)
tree.startEditingAtPath(this, path);
}
/**
* Returns the path to the element that is currently being edited.
*
* @return the <code>TreePath</code> for the node being edited
*/
public TreePath getEditingPath() {
TreeUI tree = getUI();
if(tree != null)
return tree.getEditingPath(this);
return null;
}
//
// Following are primarily convenience methods for mapping from
// row based selections to path selections. Sometimes it is
// easier to deal with these than paths (mouse downs, key downs
// usually just deal with index based selections).
// Since row based selections require a UI many of these won't work
// without one.
//
/**
* Sets the tree's selection model. When a <code>null</code> value is
* specified an empty
* <code>selectionModel</code> is used, which does not allow selections.
* <p>
* This is a bound property.
*
* @param selectionModel the <code>TreeSelectionModel</code> to use,
* or <code>null</code> to disable selections
* @see TreeSelectionModel
* @beaninfo
* bound: true
* description: The tree's selection model.
*/
public void setSelectionModel(TreeSelectionModel selectionModel) {
if(selectionModel == null)
selectionModel = EmptySelectionModel.sharedInstance();
TreeSelectionModel oldValue = this.selectionModel;
if (this.selectionModel != null && selectionRedirector != null) {
this.selectionModel.removeTreeSelectionListener
(selectionRedirector);
}
if (accessibleContext != null) {
this.selectionModel.removeTreeSelectionListener((TreeSelectionListener)accessibleContext);
selectionModel.addTreeSelectionListener((TreeSelectionListener)accessibleContext);
}
this.selectionModel = selectionModel;
if (selectionRedirector != null) {
this.selectionModel.addTreeSelectionListener(selectionRedirector);
}
firePropertyChange(SELECTION_MODEL_PROPERTY, oldValue,
this.selectionModel);
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
}
/**
* Returns the model for selections. This should always return a
* non-<code>null</code> value. If you don't want to allow anything
* to be selected
* set the selection model to <code>null</code>, which forces an empty
* selection model to be used.
*
* @see #setSelectionModel
*/
public TreeSelectionModel getSelectionModel() {
return selectionModel;
}
/**
* Returns the paths (inclusive) between the specified rows. If
* the specified indices are within the viewable set of rows, or
* bound the viewable set of rows, then the indices are
* constrained by the viewable set of rows. If the specified
* indices are not within the viewable set of rows, or do not
* bound the viewable set of rows, then an empty array is
* returned. For example, if the row count is {@code 10}, and this
* method is invoked with {@code -1, 20}, then the specified
* indices are constrained to the viewable set of rows, and this is
* treated as if invoked with {@code 0, 9}. On the other hand, if
* this were invoked with {@code -10, -1}, then the specified
* indices do not bound the viewable set of rows, and an empty
* array is returned.
* <p>
* The parameters are not order dependent. That is, {@code
* getPathBetweenRows(x, y)} is equivalent to
* {@code getPathBetweenRows(y, x)}.
* <p>
* An empty array is returned if the row count is {@code 0}, or
* the specified indices do not bound the viewable set of rows.
*
* @param index0 the first index in the range
* @param index1 the last index in the range
* @return the paths (inclusive) between the specified row indices
*/
protected TreePath[] getPathBetweenRows(int index0, int index1) {
TreeUI tree = getUI();
if (tree != null) {
int rowCount = getRowCount();
if (rowCount > 0 && !((index0 < 0 && index1 < 0) ||
(index0 >= rowCount && index1 >= rowCount))){
index0 = Math.min(rowCount - 1, Math.max(index0, 0));
index1 = Math.min(rowCount - 1, Math.max(index1, 0));
int minIndex = Math.min(index0, index1);
int maxIndex = Math.max(index0, index1);
TreePath[] selection = new TreePath[
maxIndex - minIndex + 1];
for(int counter = minIndex; counter <= maxIndex; counter++) {
selection[counter - minIndex] =
tree.getPathForRow(this, counter);
}
return selection;
}
}
return new TreePath[0];
}
/**
* Selects the rows in the specified interval (inclusive). If
* the specified indices are within the viewable set of rows, or bound
* the viewable set of rows, then the specified rows are constrained by
* the viewable set of rows. If the specified indices are not within the
* viewable set of rows, or do not bound the viewable set of rows, then
* the selection is cleared. For example, if the row count is {@code
* 10}, and this method is invoked with {@code -1, 20}, then the
* specified indices bounds the viewable range, and this is treated as
* if invoked with {@code 0, 9}. On the other hand, if this were
* invoked with {@code -10, -1}, then the specified indices do not
* bound the viewable set of rows, and the selection is cleared.
* <p>
* The parameters are not order dependent. That is, {@code
* setSelectionInterval(x, y)} is equivalent to
* {@code setSelectionInterval(y, x)}.
*
* @param index0 the first index in the range to select
* @param index1 the last index in the range to select
*/
public void setSelectionInterval(int index0, int index1) {
TreePath[] paths = getPathBetweenRows(index0, index1);
this.getSelectionModel().setSelectionPaths(paths);
}
/**
* Adds the specified rows (inclusive) to the selection. If the
* specified indices are within the viewable set of rows, or bound
* the viewable set of rows, then the specified indices are
* constrained by the viewable set of rows. If the indices are not
* within the viewable set of rows, or do not bound the viewable
* set of rows, then the selection is unchanged. For example, if
* the row count is {@code 10}, and this method is invoked with
* {@code -1, 20}, then the specified indices bounds the viewable
* range, and this is treated as if invoked with {@code 0, 9}. On
* the other hand, if this were invoked with {@code -10, -1}, then
* the specified indices do not bound the viewable set of rows,
* and the selection is unchanged.
* <p>
* The parameters are not order dependent. That is, {@code
* addSelectionInterval(x, y)} is equivalent to
* {@code addSelectionInterval(y, x)}.
*
* @param index0 the first index in the range to add to the selection
* @param index1 the last index in the range to add to the selection
*/
public void addSelectionInterval(int index0, int index1) {
TreePath[] paths = getPathBetweenRows(index0, index1);
if (paths != null && paths.length > 0) {
this.getSelectionModel().addSelectionPaths(paths);
}
}
/**
* Removes the specified rows (inclusive) from the selection. If
* the specified indices are within the viewable set of rows, or bound
* the viewable set of rows, then the specified indices are constrained by
* the viewable set of rows. If the specified indices are not within the
* viewable set of rows, or do not bound the viewable set of rows, then
* the selection is unchanged. For example, if the row count is {@code
* 10}, and this method is invoked with {@code -1, 20}, then the
* specified range bounds the viewable range, and this is treated as
* if invoked with {@code 0, 9}. On the other hand, if this were
* invoked with {@code -10, -1}, then the specified range does not
* bound the viewable set of rows, and the selection is unchanged.
* <p>
* The parameters are not order dependent. That is, {@code
* removeSelectionInterval(x, y)} is equivalent to
* {@code removeSelectionInterval(y, x)}.
*
* @param index0 the first row to remove from the selection
* @param index1 the last row to remove from the selection
*/
public void removeSelectionInterval(int index0, int index1) {
TreePath[] paths = getPathBetweenRows(index0, index1);
if (paths != null && paths.length > 0) {
this.getSelectionModel().removeSelectionPaths(paths);
}
}
/**
* Removes the node identified by the specified path from the current
* selection.
*
* @param path the <code>TreePath</code> identifying a node
*/
public void removeSelectionPath(TreePath path) {
this.getSelectionModel().removeSelectionPath(path);
}
/**
* Removes the nodes identified by the specified paths from the
* current selection.
*
* @param paths an array of <code>TreePath</code> objects that
* specifies the nodes to remove
*/
public void removeSelectionPaths(TreePath[] paths) {
this.getSelectionModel().removeSelectionPaths(paths);
}
/**
* Removes the row at the index <code>row</code> from the current
* selection.
*
* @param row the row to remove
*/
public void removeSelectionRow(int row) {
int[] rows = { row };
removeSelectionRows(rows);
}
/**
* Removes the rows that are selected at each of the specified
* rows.
*
* @param rows an array of ints specifying display rows, where 0 is
* the first row in the display
*/
public void removeSelectionRows(int[] rows) {
TreeUI ui = getUI();
if(ui != null && rows != null) {
int numRows = rows.length;
TreePath[] paths = new TreePath[numRows];
for(int counter = 0; counter < numRows; counter++)
paths[counter] = ui.getPathForRow(this, rows[counter]);
removeSelectionPaths(paths);
}
}
/**
* Clears the selection.
*/
public void clearSelection() {
getSelectionModel().clearSelection();
}
/**
* Returns true if the selection is currently empty.
*
* @return true if the selection is currently empty
*/
public boolean isSelectionEmpty() {
return getSelectionModel().isSelectionEmpty();
}
/**
* Adds a listener for <code>TreeExpansion</code> events.
*
* @param tel a TreeExpansionListener that will be notified when
* a tree node is expanded or collapsed (a "negative
* expansion")
*/
public void addTreeExpansionListener(TreeExpansionListener tel) {
if (settingUI) {
uiTreeExpansionListener = tel;
}
listenerList.add(TreeExpansionListener.class, tel);
}
/**
* Removes a listener for <code>TreeExpansion</code> events.
*
* @param tel the <code>TreeExpansionListener</code> to remove
*/
public void removeTreeExpansionListener(TreeExpansionListener tel) {
listenerList.remove(TreeExpansionListener.class, tel);
if (uiTreeExpansionListener == tel) {
uiTreeExpansionListener = null;
}
}
/**
* Returns an array of all the <code>TreeExpansionListener</code>s added
* to this JTree with addTreeExpansionListener().
*
* @return all of the <code>TreeExpansionListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public TreeExpansionListener[] getTreeExpansionListeners() {
return listenerList.getListeners(TreeExpansionListener.class);
}
/**
* Adds a listener for <code>TreeWillExpand</code> events.
*
* @param tel a <code>TreeWillExpandListener</code> that will be notified
* when a tree node will be expanded or collapsed (a "negative
* expansion")
*/
public void addTreeWillExpandListener(TreeWillExpandListener tel) {
listenerList.add(TreeWillExpandListener.class, tel);
}
/**
* Removes a listener for <code>TreeWillExpand</code> events.
*
* @param tel the <code>TreeWillExpandListener</code> to remove
*/
public void removeTreeWillExpandListener(TreeWillExpandListener tel) {
listenerList.remove(TreeWillExpandListener.class, tel);
}
/**
* Returns an array of all the <code>TreeWillExpandListener</code>s added
* to this JTree with addTreeWillExpandListener().
*
* @return all of the <code>TreeWillExpandListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public TreeWillExpandListener[] getTreeWillExpandListeners() {
return listenerList.getListeners(TreeWillExpandListener.class);
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the <code>path</code> parameter.
*
* @param path the <code>TreePath</code> indicating the node that was
* expanded
* @see EventListenerList
*/
public void fireTreeExpanded(TreePath path) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeExpansionEvent e = null;
if (uiTreeExpansionListener != null) {
e = new TreeExpansionEvent(this, path);
uiTreeExpansionListener.treeExpanded(e);
}
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeExpansionListener.class &&
listeners[i + 1] != uiTreeExpansionListener) {
// Lazily create the event:
if (e == null)
e = new TreeExpansionEvent(this, path);
((TreeExpansionListener)listeners[i+1]).
treeExpanded(e);
}
}
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the <code>path</code> parameter.
*
* @param path the <code>TreePath</code> indicating the node that was
* collapsed
* @see EventListenerList
*/
public void fireTreeCollapsed(TreePath path) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeExpansionEvent e = null;
if (uiTreeExpansionListener != null) {
e = new TreeExpansionEvent(this, path);
uiTreeExpansionListener.treeCollapsed(e);
}
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeExpansionListener.class &&
listeners[i + 1] != uiTreeExpansionListener) {
// Lazily create the event:
if (e == null)
e = new TreeExpansionEvent(this, path);
((TreeExpansionListener)listeners[i+1]).
treeCollapsed(e);
}
}
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the <code>path</code> parameter.
*
* @param path the <code>TreePath</code> indicating the node that was
* expanded
* @see EventListenerList
*/
public void fireTreeWillExpand(TreePath path) throws ExpandVetoException {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeExpansionEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeWillExpandListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeExpansionEvent(this, path);
((TreeWillExpandListener)listeners[i+1]).
treeWillExpand(e);
}
}
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the <code>path</code> parameter.
*
* @param path the <code>TreePath</code> indicating the node that was
* expanded
* @see EventListenerList
*/
public void fireTreeWillCollapse(TreePath path) throws ExpandVetoException {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeExpansionEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeWillExpandListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeExpansionEvent(this, path);
((TreeWillExpandListener)listeners[i+1]).
treeWillCollapse(e);
}
}
}
/**
* Adds a listener for <code>TreeSelection</code> events.
*
* @param tsl the <code>TreeSelectionListener</code> that will be notified
* when a node is selected or deselected (a "negative
* selection")
*/
public void addTreeSelectionListener(TreeSelectionListener tsl) {
listenerList.add(TreeSelectionListener.class,tsl);
if(listenerList.getListenerCount(TreeSelectionListener.class) != 0
&& selectionRedirector == null) {
selectionRedirector = new TreeSelectionRedirector();
selectionModel.addTreeSelectionListener(selectionRedirector);
}
}
/**
* Removes a <code>TreeSelection</code> listener.
*
* @param tsl the <code>TreeSelectionListener</code> to remove
*/
public void removeTreeSelectionListener(TreeSelectionListener tsl) {
listenerList.remove(TreeSelectionListener.class,tsl);
if(listenerList.getListenerCount(TreeSelectionListener.class) == 0
&& selectionRedirector != null) {
selectionModel.removeTreeSelectionListener
(selectionRedirector);
selectionRedirector = null;
}
}
/**
* Returns an array of all the <code>TreeSelectionListener</code>s added
* to this JTree with addTreeSelectionListener().
*
* @return all of the <code>TreeSelectionListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public TreeSelectionListener[] getTreeSelectionListeners() {
return listenerList.getListeners(TreeSelectionListener.class);
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type.
*
* @param e the <code>TreeSelectionEvent</code> to be fired;
* generated by the
* <code>TreeSelectionModel</code>
* when a node is selected or deselected
* @see EventListenerList
*/
protected void fireValueChanged(TreeSelectionEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
// TreeSelectionEvent e = null;
if (listeners[i]==TreeSelectionListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((TreeSelectionListener)listeners[i+1]).valueChanged(e);
}
}
}
/**
* Sent when the tree has changed enough that we need to resize
* the bounds, but not enough that we need to remove the
* expanded node set (e.g nodes were expanded or collapsed, or
* nodes were inserted into the tree). You should never have to
* invoke this, the UI will invoke this as it needs to.
*/
public void treeDidChange() {
revalidate();
repaint();
}
/**
* Sets the number of rows that are to be displayed.
* This will only work if the tree is contained in a
* <code>JScrollPane</code>,
* and will adjust the preferred size and size of that scrollpane.
* <p>
* This is a bound property.
*
* @param newCount the number of rows to display
* @beaninfo
* bound: true
* description: The number of rows that are to be displayed.
*/
public void setVisibleRowCount(int newCount) {
int oldCount = visibleRowCount;
visibleRowCount = newCount;
firePropertyChange(VISIBLE_ROW_COUNT_PROPERTY, oldCount,
visibleRowCount);
invalidate();
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
}
}
/**
* Returns the number of rows that are displayed in the display area.
*
* @return the number of rows displayed
*/
public int getVisibleRowCount() {
return visibleRowCount;
}
/**
* Expands the root path, assuming the current TreeModel has been set.
*/
private void expandRoot() {
TreeModel model = getModel();
if(model != null && model.getRoot() != null) {
expandPath(new TreePath(model.getRoot()));
}
}
/**
* Returns the TreePath to the next tree element that
* begins with a prefix. To handle the conversion of a
* <code>TreePath</code> into a String, <code>convertValueToText</code>
* is used.
*
* @param prefix the string to test for a match
* @param startingRow the row for starting the search
* @param bias the search direction, either
* Position.Bias.Forward or Position.Bias.Backward.
* @return the TreePath of the next tree element that
* starts with the prefix; otherwise null
* @exception IllegalArgumentException if prefix is null
* or startingRow is out of bounds
* @since 1.4
*/
public TreePath getNextMatch(String prefix, int startingRow,
Position.Bias bias) {
int max = getRowCount();
if (prefix == null) {
throw new IllegalArgumentException();
}
if (startingRow < 0 || startingRow >= max) {
throw new IllegalArgumentException();
}
prefix = prefix.toUpperCase();
// start search from the next/previous element froom the
// selected element
int increment = (bias == Position.Bias.Forward) ? 1 : -1;
int row = startingRow;
do {
TreePath path = getPathForRow(row);
String text = convertValueToText(
path.getLastPathComponent(), isRowSelected(row),
isExpanded(row), true, row, false);
if (text.toUpperCase().startsWith(prefix)) {
return path;
}
row = (row + increment + max) % max;
} while (row != startingRow);
return null;
}
// Serialization support.
private void writeObject(ObjectOutputStream s) throws IOException {
Vector<Object> values = new Vector<Object>();
s.defaultWriteObject();
// Save the cellRenderer, if its Serializable.
if(cellRenderer != null && cellRenderer instanceof Serializable) {
values.addElement("cellRenderer");
values.addElement(cellRenderer);
}
// Save the cellEditor, if its Serializable.
if(cellEditor != null && cellEditor instanceof Serializable) {
values.addElement("cellEditor");
values.addElement(cellEditor);
}
// Save the treeModel, if its Serializable.
if(treeModel != null && treeModel instanceof Serializable) {
values.addElement("treeModel");
values.addElement(treeModel);
}
// Save the selectionModel, if its Serializable.
if(selectionModel != null && selectionModel instanceof Serializable) {
values.addElement("selectionModel");
values.addElement(selectionModel);
}
Object expandedData = getArchivableExpandedState();
if(expandedData != null) {
values.addElement("expandedState");
values.addElement(expandedData);
}
s.writeObject(values);
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
// Create an instance of expanded state.
expandedState = new Hashtable<TreePath, Boolean>();
expandedStack = new Stack<Stack<TreePath>>();
Vector<?> values = (Vector)s.readObject();
int indexCounter = 0;
int maxCounter = values.size();
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("cellRenderer")) {
cellRenderer = (TreeCellRenderer)values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("cellEditor")) {
cellEditor = (TreeCellEditor)values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("treeModel")) {
treeModel = (TreeModel)values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("selectionModel")) {
selectionModel = (TreeSelectionModel)values.elementAt(++indexCounter);
indexCounter++;
}
if(indexCounter < maxCounter && values.elementAt(indexCounter).
equals("expandedState")) {
unarchiveExpandedState(values.elementAt(++indexCounter));
indexCounter++;
}
// Reinstall the redirector.
if(listenerList.getListenerCount(TreeSelectionListener.class) != 0) {
selectionRedirector = new TreeSelectionRedirector();
selectionModel.addTreeSelectionListener(selectionRedirector);
}
// Listener to TreeModel.
if(treeModel != null) {
treeModelListener = createTreeModelListener();
if(treeModelListener != null)
treeModel.addTreeModelListener(treeModelListener);
}
}
/**
* Returns an object that can be archived indicating what nodes are
* expanded and what aren't. The objects from the model are NOT
* written out.
*/
private Object getArchivableExpandedState() {
TreeModel model = getModel();
if(model != null) {
Enumeration<TreePath> paths = expandedState.keys();
if(paths != null) {
Vector<Object> state = new Vector<Object>();
while(paths.hasMoreElements()) {
TreePath path = paths.nextElement();
Object archivePath;
try {
archivePath = getModelIndexsForPath(path);
} catch (Error error) {
archivePath = null;
}
if(archivePath != null) {
state.addElement(archivePath);
state.addElement(expandedState.get(path));
}
}
return state;
}
}
return null;
}
/**
* Updates the expanded state of nodes in the tree based on the
* previously archived state <code>state</code>.
*/
private void unarchiveExpandedState(Object state) {
if(state instanceof Vector) {
Vector<?> paths = (Vector)state;
for(int counter = paths.size() - 1; counter >= 0; counter--) {
Boolean eState = (Boolean)paths.elementAt(counter--);
TreePath path;
try {
path = getPathForIndexs((int[])paths.elementAt(counter));
if(path != null)
expandedState.put(path, eState);
} catch (Error error) {}
}
}
}
/**
* Returns an array of integers specifying the indexs of the
* components in the <code>path</code>. If <code>path</code> is
* the root, this will return an empty array. If <code>path</code>
* is <code>null</code>, <code>null</code> will be returned.
*/
private int[] getModelIndexsForPath(TreePath path) {
if(path != null) {
TreeModel model = getModel();
int count = path.getPathCount();
int[] indexs = new int[count - 1];
Object parent = model.getRoot();
for(int counter = 1; counter < count; counter++) {
indexs[counter - 1] = model.getIndexOfChild
(parent, path.getPathComponent(counter));
parent = path.getPathComponent(counter);
if(indexs[counter - 1] < 0)
return null;
}
return indexs;
}
return null;
}
/**
* Returns a <code>TreePath</code> created by obtaining the children
* for each of the indices in <code>indexs</code>. If <code>indexs</code>
* or the <code>TreeModel</code> is <code>null</code>, it will return
* <code>null</code>.
*/
private TreePath getPathForIndexs(int[] indexs) {
if(indexs == null)
return null;
TreeModel model = getModel();
if(model == null)
return null;
int count = indexs.length;
Object parent = model.getRoot();
TreePath parentPath = new TreePath(parent);
for(int counter = 0; counter < count; counter++) {
parent = model.getChild(parent, indexs[counter]);
if(parent == null)
return null;
parentPath = parentPath.pathByAddingChild(parent);
}
return parentPath;
}
/**
* <code>EmptySelectionModel</code> is a <code>TreeSelectionModel</code>
* that does not allow anything to be selected.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
@SuppressWarnings("serial")
protected static class EmptySelectionModel extends
DefaultTreeSelectionModel
{
/**
* The single instance of {@code EmptySelectionModel}.
*/
protected static final EmptySelectionModel sharedInstance =
new EmptySelectionModel();
/**
* Returns the single instance of {@code EmptySelectionModel}.
*
* @return single instance of {@code EmptySelectionModel}
*/
static public EmptySelectionModel sharedInstance() {
return sharedInstance;
}
/**
* This is overriden to do nothing; {@code EmptySelectionModel}
* does not allow a selection.
*
* @param paths the paths to select; this is ignored
*/
public void setSelectionPaths(TreePath[] paths) {}
/**
* This is overriden to do nothing; {@code EmptySelectionModel}
* does not allow a selection.
*
* @param paths the paths to add to the selection; this is ignored
*/
public void addSelectionPaths(TreePath[] paths) {}
/**
* This is overriden to do nothing; {@code EmptySelectionModel}
* does not allow a selection.
*
* @param paths the paths to remove; this is ignored
*/
public void removeSelectionPaths(TreePath[] paths) {}
/**
* This is overriden to do nothing; {@code EmptySelectionModel}
* does not allow a selection.
*
* @param mode the selection mode; this is ignored
* @since 1.7
*/
public void setSelectionMode(int mode) {
}
/**
* This is overriden to do nothing; {@code EmptySelectionModel}
* does not allow a selection.
*
* @param mapper the {@code RowMapper} instance; this is ignored
* @since 1.7
*/
public void setRowMapper(RowMapper mapper) {
}
/**
* This is overriden to do nothing; {@code EmptySelectionModel}
* does not allow a selection.
*
* @param listener the listener to add; this is ignored
* @since 1.7
*/
public void addTreeSelectionListener(TreeSelectionListener listener) {
}
/**
* This is overriden to do nothing; {@code EmptySelectionModel}
* does not allow a selection.
*
* @param listener the listener to remove; this is ignored
* @since 1.7
*/
public void removeTreeSelectionListener(
TreeSelectionListener listener) {
}
/**
* This is overriden to do nothing; {@code EmptySelectionModel}
* does not allow a selection.
*
* @param listener the listener to add; this is ignored
* @since 1.7
*/
public void addPropertyChangeListener(
PropertyChangeListener listener) {
}
/**
* This is overriden to do nothing; {@code EmptySelectionModel}
* does not allow a selection.
*
* @param listener the listener to remove; this is ignored
* @since 1.7
*/
public void removePropertyChangeListener(
PropertyChangeListener listener) {
}
}
/**
* Handles creating a new <code>TreeSelectionEvent</code> with the
* <code>JTree</code> as the
* source and passing it off to all the listeners.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
@SuppressWarnings("serial")
protected class TreeSelectionRedirector implements Serializable,
TreeSelectionListener
{
/**
* Invoked by the <code>TreeSelectionModel</code> when the
* selection changes.
*
* @param e the <code>TreeSelectionEvent</code> generated by the
* <code>TreeSelectionModel</code>
*/
public void valueChanged(TreeSelectionEvent e) {
TreeSelectionEvent newE;
newE = (TreeSelectionEvent)e.cloneWithSource(JTree.this);
fireValueChanged(newE);
}
} // End of class JTree.TreeSelectionRedirector
//
// Scrollable interface
//
/**
* Returns the preferred display size of a <code>JTree</code>. The height is
* determined from <code>getVisibleRowCount</code> and the width
* is the current preferred width.
*
* @return a <code>Dimension</code> object containing the preferred size
*/
public Dimension getPreferredScrollableViewportSize() {
int width = getPreferredSize().width;
int visRows = getVisibleRowCount();
int height = -1;
if(isFixedRowHeight())
height = visRows * getRowHeight();
else {
TreeUI ui = getUI();
if (ui != null && visRows > 0) {
int rc = ui.getRowCount(this);
if (rc >= visRows) {
Rectangle bounds = getRowBounds(visRows - 1);
if (bounds != null) {
height = bounds.y + bounds.height;
}
}
else if (rc > 0) {
Rectangle bounds = getRowBounds(0);
if (bounds != null) {
height = bounds.height * visRows;
}
}
}
if (height == -1) {
height = 16 * visRows;
}
}
return new Dimension(width, height);
}
/**
* Returns the amount to increment when scrolling. The amount is
* the height of the first displayed row that isn't completely in view
* or, if it is totally displayed, the height of the next row in the
* scrolling direction.
*
* @param visibleRect the view area visible within the viewport
* @param orientation either <code>SwingConstants.VERTICAL</code>
* or <code>SwingConstants.HORIZONTAL</code>
* @param direction less than zero to scroll up/left,
* greater than zero for down/right
* @return the "unit" increment for scrolling in the specified direction
* @see JScrollBar#setUnitIncrement(int)
*/
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation, int direction) {
if(orientation == SwingConstants.VERTICAL) {
Rectangle rowBounds;
int firstIndex = getClosestRowForLocation
(0, visibleRect.y);
if(firstIndex != -1) {
rowBounds = getRowBounds(firstIndex);
if(rowBounds.y != visibleRect.y) {
if(direction < 0) {
// UP
return Math.max(0, (visibleRect.y - rowBounds.y));
}
return (rowBounds.y + rowBounds.height - visibleRect.y);
}
if(direction < 0) { // UP
if(firstIndex != 0) {
rowBounds = getRowBounds(firstIndex - 1);
return rowBounds.height;
}
}
else {
return rowBounds.height;
}
}
return 0;
}
return 4;
}
/**
* Returns the amount for a block increment, which is the height or
* width of <code>visibleRect</code>, based on <code>orientation</code>.
*
* @param visibleRect the view area visible within the viewport
* @param orientation either <code>SwingConstants.VERTICAL</code>
* or <code>SwingConstants.HORIZONTAL</code>
* @param direction less than zero to scroll up/left,
* greater than zero for down/right.
* @return the "block" increment for scrolling in the specified direction
* @see JScrollBar#setBlockIncrement(int)
*/
public int getScrollableBlockIncrement(Rectangle visibleRect,
int orientation, int direction) {
return (orientation == SwingConstants.VERTICAL) ? visibleRect.height :
visibleRect.width;
}
/**
* Returns false to indicate that the width of the viewport does not
* determine the width of the table, unless the preferred width of
* the tree is smaller than the viewports width. In other words:
* ensure that the tree is never smaller than its viewport.
*
* @return whether the tree should track the width of the viewport
* @see Scrollable#getScrollableTracksViewportWidth
*/
public boolean getScrollableTracksViewportWidth() {
Container parent = SwingUtilities.getUnwrappedParent(this);
if (parent instanceof JViewport) {
return parent.getWidth() > getPreferredSize().width;
}
return false;
}
/**
* Returns false to indicate that the height of the viewport does not
* determine the height of the table, unless the preferred height
* of the tree is smaller than the viewports height. In other words:
* ensure that the tree is never smaller than its viewport.
*
* @return whether the tree should track the height of the viewport
* @see Scrollable#getScrollableTracksViewportHeight
*/
public boolean getScrollableTracksViewportHeight() {
Container parent = SwingUtilities.getUnwrappedParent(this);
if (parent instanceof JViewport) {
return parent.getHeight() > getPreferredSize().height;
}
return false;
}
/**
* Sets the expanded state of this <code>JTree</code>.
* If <code>state</code> is
* true, all parents of <code>path</code> and path are marked as
* expanded. If <code>state</code> is false, all parents of
* <code>path</code> are marked EXPANDED, but <code>path</code> itself
* is marked collapsed.<p>
* This will fail if a <code>TreeWillExpandListener</code> vetos it.
*/
protected void setExpandedState(TreePath path, boolean state) {
if(path != null) {
// Make sure all parents of path are expanded.
Stack<TreePath> stack;
TreePath parentPath = path.getParentPath();
if (expandedStack.size() == 0) {
stack = new Stack<TreePath>();
}
else {
stack = expandedStack.pop();
}
try {
while(parentPath != null) {
if(isExpanded(parentPath)) {
parentPath = null;
}
else {
stack.push(parentPath);
parentPath = parentPath.getParentPath();
}
}
for(int counter = stack.size() - 1; counter >= 0; counter--) {
parentPath = stack.pop();
if(!isExpanded(parentPath)) {
try {
fireTreeWillExpand(parentPath);
} catch (ExpandVetoException eve) {
// Expand vetoed!
return;
}
expandedState.put(parentPath, Boolean.TRUE);
fireTreeExpanded(parentPath);
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).
fireVisibleDataPropertyChange();
}
}
}
}
finally {
if (expandedStack.size() < TEMP_STACK_SIZE) {
stack.removeAllElements();
expandedStack.push(stack);
}
}
if(!state) {
// collapse last path.
Object cValue = expandedState.get(path);
if(cValue != null && ((Boolean)cValue).booleanValue()) {
try {
fireTreeWillCollapse(path);
}
catch (ExpandVetoException eve) {
return;
}
expandedState.put(path, Boolean.FALSE);
fireTreeCollapsed(path);
if (removeDescendantSelectedPaths(path, false) &&
!isPathSelected(path)) {
// A descendant was selected, select the parent.
addSelectionPath(path);
}
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).
fireVisibleDataPropertyChange();
}
}
}
else {
// Expand last path.
Object cValue = expandedState.get(path);
if(cValue == null || !((Boolean)cValue).booleanValue()) {
try {
fireTreeWillExpand(path);
}
catch (ExpandVetoException eve) {
return;
}
expandedState.put(path, Boolean.TRUE);
fireTreeExpanded(path);
if (accessibleContext != null) {
((AccessibleJTree)accessibleContext).
fireVisibleDataPropertyChange();
}
}
}
}
}
/**
* Returns an <code>Enumeration</code> of <code>TreePaths</code>
* that have been expanded that
* are descendants of <code>parent</code>.
*/
protected Enumeration<TreePath>
getDescendantToggledPaths(TreePath parent)
{
if(parent == null)
return null;
Vector<TreePath> descendants = new Vector<TreePath>();
Enumeration<TreePath> nodes = expandedState.keys();
while(nodes.hasMoreElements()) {
TreePath path = nodes.nextElement();
if(parent.isDescendant(path))
descendants.addElement(path);
}
return descendants.elements();
}
/**
* Removes any descendants of the <code>TreePaths</code> in
* <code>toRemove</code>
* that have been expanded.
*
* @param toRemove an enumeration of the paths to remove; a value of
* {@code null} is ignored
* @throws ClassCastException if {@code toRemove} contains an
* element that is not a {@code TreePath}; {@code null}
* values are ignored
*/
protected void
removeDescendantToggledPaths(Enumeration<TreePath> toRemove)
{
if(toRemove != null) {
while(toRemove.hasMoreElements()) {
Enumeration<?> descendants = getDescendantToggledPaths
(toRemove.nextElement());
if(descendants != null) {
while(descendants.hasMoreElements()) {
expandedState.remove(descendants.nextElement());
}
}
}
}
}
/**
* Clears the cache of toggled tree paths. This does NOT send out
* any <code>TreeExpansionListener</code> events.
*/
protected void clearToggledPaths() {
expandedState.clear();
}
/**
* Creates and returns an instance of <code>TreeModelHandler</code>.
* The returned
* object is responsible for updating the expanded state when the
* <code>TreeModel</code> changes.
* <p>
* For more information on what expanded state means, see the
* <a href=#jtree_description>JTree description</a> above.
*/
protected TreeModelListener createTreeModelListener() {
return new TreeModelHandler();
}
/**
* Removes any paths in the selection that are descendants of
* <code>path</code>. If <code>includePath</code> is true and
* <code>path</code> is selected, it will be removed from the selection.
*
* @return true if a descendant was selected
* @since 1.3
*/
protected boolean removeDescendantSelectedPaths(TreePath path,
boolean includePath) {
TreePath[] toRemove = getDescendantSelectedPaths(path, includePath);
if (toRemove != null) {
getSelectionModel().removeSelectionPaths(toRemove);
return true;
}
return false;
}
/**
* Returns an array of paths in the selection that are descendants of
* <code>path</code>. The returned array may contain <code>null</code>s.
*/
private TreePath[] getDescendantSelectedPaths(TreePath path,
boolean includePath) {
TreeSelectionModel sm = getSelectionModel();
TreePath[] selPaths = (sm != null) ? sm.getSelectionPaths() :
null;
if(selPaths != null) {
boolean shouldRemove = false;
for(int counter = selPaths.length - 1; counter >= 0; counter--) {
if(selPaths[counter] != null &&
path.isDescendant(selPaths[counter]) &&
(!path.equals(selPaths[counter]) || includePath))
shouldRemove = true;
else
selPaths[counter] = null;
}
if(!shouldRemove) {
selPaths = null;
}
return selPaths;
}
return null;
}
/**
* Removes any paths from the selection model that are descendants of
* the nodes identified by in <code>e</code>.
*/
void removeDescendantSelectedPaths(TreeModelEvent e) {
TreePath pPath = SwingUtilities2.getTreePath(e, getModel());
Object[] oldChildren = e.getChildren();
TreeSelectionModel sm = getSelectionModel();
if (sm != null && pPath != null && oldChildren != null &&
oldChildren.length > 0) {
for (int counter = oldChildren.length - 1; counter >= 0;
counter--) {
// Might be better to call getDescendantSelectedPaths
// numerous times, then push to the model.
removeDescendantSelectedPaths(pPath.pathByAddingChild
(oldChildren[counter]), true);
}
}
}
/**
* Listens to the model and updates the <code>expandedState</code>
* accordingly when nodes are removed, or changed.
*/
protected class TreeModelHandler implements TreeModelListener {
public void treeNodesChanged(TreeModelEvent e) { }
public void treeNodesInserted(TreeModelEvent e) { }
public void treeStructureChanged(TreeModelEvent e) {
if(e == null)
return;
// NOTE: If I change this to NOT remove the descendants
// and update BasicTreeUIs treeStructureChanged method
// to update descendants in response to a treeStructureChanged
// event, all the children of the event won't collapse!
TreePath parent = SwingUtilities2.getTreePath(e, getModel());
if(parent == null)
return;
if (parent.getPathCount() == 1) {
// New root, remove everything!
clearToggledPaths();
if(treeModel.getRoot() != null &&
!treeModel.isLeaf(treeModel.getRoot())) {
// Mark the root as expanded, if it isn't a leaf.
expandedState.put(parent, Boolean.TRUE);
}
}
else if(expandedState.get(parent) != null) {
Vector<TreePath> toRemove = new Vector<TreePath>(1);
boolean isExpanded = isExpanded(parent);
toRemove.addElement(parent);
removeDescendantToggledPaths(toRemove.elements());
if(isExpanded) {
TreeModel model = getModel();
if(model == null || model.isLeaf
(parent.getLastPathComponent()))
collapsePath(parent);
else
expandedState.put(parent, Boolean.TRUE);
}
}
removeDescendantSelectedPaths(parent, false);
}
public void treeNodesRemoved(TreeModelEvent e) {
if(e == null)
return;
TreePath parent = SwingUtilities2.getTreePath(e, getModel());
Object[] children = e.getChildren();
if(children == null)
return;
TreePath rPath;
Vector<TreePath> toRemove
= new Vector<TreePath>(Math.max(1, children.length));
for(int counter = children.length - 1; counter >= 0; counter--) {
rPath = parent.pathByAddingChild(children[counter]);
if(expandedState.get(rPath) != null)
toRemove.addElement(rPath);
}
if(toRemove.size() > 0)
removeDescendantToggledPaths(toRemove.elements());
TreeModel model = getModel();
if(model == null || model.isLeaf(parent.getLastPathComponent()))
expandedState.remove(parent);
removeDescendantSelectedPaths(e);
}
}
/**
* <code>DynamicUtilTreeNode</code> can wrap
* vectors/hashtables/arrays/strings and
* create the appropriate children tree nodes as necessary. It is
* dynamic in that it will only create the children as necessary.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
@SuppressWarnings("serial")
public static class DynamicUtilTreeNode extends DefaultMutableTreeNode {
/**
* Does the this <code>JTree</code> have children?
* This property is currently not implemented.
*/
protected boolean hasChildren;
/** Value to create children with. */
protected Object childValue;
/** Have the children been loaded yet? */
protected boolean loadedChildren;
/**
* Adds to parent all the children in <code>children</code>.
* If <code>children</code> is an array or vector all of its
* elements are added is children, otherwise if <code>children</code>
* is a hashtable all the key/value pairs are added in the order
* <code>Enumeration</code> returns them.
*/
public static void createChildren(DefaultMutableTreeNode parent,
Object children) {
if(children instanceof Vector) {
Vector<?> childVector = (Vector)children;
for(int counter = 0, maxCounter = childVector.size();
counter < maxCounter; counter++)
parent.add(new DynamicUtilTreeNode
(childVector.elementAt(counter),
childVector.elementAt(counter)));
}
else if(children instanceof Hashtable) {
Hashtable<?,?> childHT = (Hashtable)children;
Enumeration<?> keys = childHT.keys();
Object aKey;
while(keys.hasMoreElements()) {
aKey = keys.nextElement();
parent.add(new DynamicUtilTreeNode(aKey,
childHT.get(aKey)));
}
}
else if(children instanceof Object[]) {
Object[] childArray = (Object[])children;
for(int counter = 0, maxCounter = childArray.length;
counter < maxCounter; counter++)
parent.add(new DynamicUtilTreeNode(childArray[counter],
childArray[counter]));
}
}
/**
* Creates a node with the specified object as its value and
* with the specified children. For the node to allow children,
* the children-object must be an array of objects, a
* <code>Vector</code>, or a <code>Hashtable</code> -- even
* if empty. Otherwise, the node is not
* allowed to have children.
*
* @param value the <code>Object</code> that is the value for the
* new node
* @param children an array of <code>Object</code>s, a
* <code>Vector</code>, or a <code>Hashtable</code>
* used to create the child nodes; if any other
* object is specified, or if the value is
* <code>null</code>,
* then the node is not allowed to have children
*/
public DynamicUtilTreeNode(Object value, Object children) {
super(value);
loadedChildren = false;
childValue = children;
if(children != null) {
if(children instanceof Vector)
setAllowsChildren(true);
else if(children instanceof Hashtable)
setAllowsChildren(true);
else if(children instanceof Object[])
setAllowsChildren(true);
else
setAllowsChildren(false);
}
else
setAllowsChildren(false);
}
/**
* Returns true if this node allows children. Whether the node
* allows children depends on how it was created.
*
* @return true if this node allows children, false otherwise
* @see JTree.DynamicUtilTreeNode
*/
public boolean isLeaf() {
return !getAllowsChildren();
}
/**
* Returns the number of child nodes.
*
* @return the number of child nodes
*/
public int getChildCount() {
if(!loadedChildren)
loadChildren();
return super.getChildCount();
}
/**
* Loads the children based on <code>childValue</code>.
* If <code>childValue</code> is a <code>Vector</code>
* or array each element is added as a child,
* if <code>childValue</code> is a <code>Hashtable</code>
* each key/value pair is added in the order that
* <code>Enumeration</code> returns the keys.
*/
protected void loadChildren() {
loadedChildren = true;
createChildren(this, childValue);
}
/**
* Subclassed to load the children, if necessary.
*/
public TreeNode getChildAt(int index) {
if(!loadedChildren)
loadChildren();
return super.getChildAt(index);
}
/**
* Subclassed to load the children, if necessary.
*/
public Enumeration children() {
if(!loadedChildren)
loadChildren();
return super.children();
}
}
void setUIProperty(String propertyName, Object value) {
if (propertyName == "rowHeight") {
if (!rowHeightSet) {
setRowHeight(((Number)value).intValue());
rowHeightSet = false;
}
} else if (propertyName == "scrollsOnExpand") {
if (!scrollsOnExpandSet) {
setScrollsOnExpand(((Boolean)value).booleanValue());
scrollsOnExpandSet = false;
}
} else if (propertyName == "showsRootHandles") {
if (!showsRootHandlesSet) {
setShowsRootHandles(((Boolean)value).booleanValue());
showsRootHandlesSet = false;
}
} else {
super.setUIProperty(propertyName, value);
}
}
/**
* Returns a string representation of this <code>JTree</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JTree</code>.
*/
protected String paramString() {
String rootVisibleString = (rootVisible ?
"true" : "false");
String showsRootHandlesString = (showsRootHandles ?
"true" : "false");
String editableString = (editable ?
"true" : "false");
String largeModelString = (largeModel ?
"true" : "false");
String invokesStopCellEditingString = (invokesStopCellEditing ?
"true" : "false");
String scrollsOnExpandString = (scrollsOnExpand ?
"true" : "false");
return super.paramString() +
",editable=" + editableString +
",invokesStopCellEditing=" + invokesStopCellEditingString +
",largeModel=" + largeModelString +
",rootVisible=" + rootVisibleString +
",rowHeight=" + rowHeight +
",scrollsOnExpand=" + scrollsOnExpandString +
",showsRootHandles=" + showsRootHandlesString +
",toggleClickCount=" + toggleClickCount +
",visibleRowCount=" + visibleRowCount;
}
/////////////////
// Accessibility support
////////////////
/**
* Gets the AccessibleContext associated with this JTree.
* For JTrees, the AccessibleContext takes the form of an
* AccessibleJTree.
* A new AccessibleJTree instance is created if necessary.
*
* @return an AccessibleJTree that serves as the
* AccessibleContext of this JTree
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJTree();
}
return accessibleContext;
}
/**
* This class implements accessibility support for the
* <code>JTree</code> class. It provides an implementation of the
* Java Accessibility API appropriate to tree user-interface elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
@SuppressWarnings("serial")
protected class AccessibleJTree extends AccessibleJComponent
implements AccessibleSelection, TreeSelectionListener,
TreeModelListener, TreeExpansionListener {
TreePath leadSelectionPath;
Accessible leadSelectionAccessible;
public AccessibleJTree() {
// Add a tree model listener for JTree
TreeModel model = JTree.this.getModel();
if (model != null) {
model.addTreeModelListener(this);
}
JTree.this.addTreeExpansionListener(this);
JTree.this.addTreeSelectionListener(this);
leadSelectionPath = JTree.this.getLeadSelectionPath();
leadSelectionAccessible = (leadSelectionPath != null)
? new AccessibleJTreeNode(JTree.this,
leadSelectionPath,
JTree.this)
: null;
}
/**
* Tree Selection Listener value change method. Used to fire the
* property change
*
* @param e ListSelectionEvent
*
*/
public void valueChanged(TreeSelectionEvent e) {
// Fixes 4546503 - JTree is sending incorrect active
// descendant events
TreePath oldLeadSelectionPath = e.getOldLeadSelectionPath();
leadSelectionPath = e.getNewLeadSelectionPath();
if (oldLeadSelectionPath != leadSelectionPath) {
// Set parent to null so AccessibleJTreeNode computes
// its parent.
Accessible oldLSA = leadSelectionAccessible;
leadSelectionAccessible = (leadSelectionPath != null)
? new AccessibleJTreeNode(JTree.this,
leadSelectionPath,
null) // parent
: null;
firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
oldLSA, leadSelectionAccessible);
}
firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
/**
* Fire a visible data property change notification.
* A 'visible' data property is one that represents
* something about the way the component appears on the
* display, where that appearance isn't bound to any other
* property. It notifies screen readers that the visual
* appearance of the component has changed, so they can
* notify the user.
*/
public void fireVisibleDataPropertyChange() {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
// Fire the visible data changes for the model changes.
/**
* Tree Model Node change notification.
*
* @param e a Tree Model event
*/
public void treeNodesChanged(TreeModelEvent e) {
fireVisibleDataPropertyChange();
}
/**
* Tree Model Node change notification.
*
* @param e a Tree node insertion event
*/
public void treeNodesInserted(TreeModelEvent e) {
fireVisibleDataPropertyChange();
}
/**
* Tree Model Node change notification.
*
* @param e a Tree node(s) removal event
*/
public void treeNodesRemoved(TreeModelEvent e) {
fireVisibleDataPropertyChange();
}
/**
* Tree Model structure change change notification.
*
* @param e a Tree Model event
*/
public void treeStructureChanged(TreeModelEvent e) {
fireVisibleDataPropertyChange();
}
/**
* Tree Collapsed notification.
*
* @param e a TreeExpansionEvent
*/
public void treeCollapsed(TreeExpansionEvent e) {
fireVisibleDataPropertyChange();
TreePath path = e.getPath();
if (path != null) {
// Set parent to null so AccessibleJTreeNode computes
// its parent.
AccessibleJTreeNode node = new AccessibleJTreeNode(JTree.this,
path,
null);
PropertyChangeEvent pce = new PropertyChangeEvent(node,
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.EXPANDED,
AccessibleState.COLLAPSED);
firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, pce);
}
}
/**
* Tree Model Expansion notification.
*
* @param e a Tree node insertion event
*/
public void treeExpanded(TreeExpansionEvent e) {
fireVisibleDataPropertyChange();
TreePath path = e.getPath();
if (path != null) {
// TIGER - 4839971
// Set parent to null so AccessibleJTreeNode computes
// its parent.
AccessibleJTreeNode node = new AccessibleJTreeNode(JTree.this,
path,
null);
PropertyChangeEvent pce = new PropertyChangeEvent(node,
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.COLLAPSED,
AccessibleState.EXPANDED);
firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, pce);
}
}
private AccessibleContext getCurrentAccessibleContext() {
Component c = getCurrentComponent();
if (c instanceof Accessible) {
return c.getAccessibleContext();
} else {
return null;
}
}
private Component getCurrentComponent() {
// is the object visible?
// if so, get row, selected, focus & leaf state,
// and then get the renderer component and return it
TreeModel model = JTree.this.getModel();
if (model == null) {
return null;
}
TreePath path = new TreePath(model.getRoot());
if (JTree.this.isVisible(path)) {
TreeCellRenderer r = JTree.this.getCellRenderer();
TreeUI ui = JTree.this.getUI();
if (ui != null) {
int row = ui.getRowForPath(JTree.this, path);
int lsr = JTree.this.getLeadSelectionRow();
boolean hasFocus = JTree.this.isFocusOwner()
&& (lsr == row);
boolean selected = JTree.this.isPathSelected(path);
boolean expanded = JTree.this.isExpanded(path);
return r.getTreeCellRendererComponent(JTree.this,
model.getRoot(), selected, expanded,
model.isLeaf(model.getRoot()), row, hasFocus);
}
}
return null;
}
// Overridden methods from AccessibleJComponent
/**
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.TREE;
}
/**
* Returns the <code>Accessible</code> child, if one exists,
* contained at the local coordinate <code>Point</code>.
* Otherwise returns <code>null</code>.
*
* @param p point in local coordinates of this <code>Accessible</code>
* @return the <code>Accessible</code>, if it exists,
* at the specified location; else <code>null</code>
*/
public Accessible getAccessibleAt(Point p) {
TreePath path = getClosestPathForLocation(p.x, p.y);
if (path != null) {
// JTree.this is NOT the parent; parent will get computed later
return new AccessibleJTreeNode(JTree.this, path, null);
} else {
return null;
}
}
/**
* Returns the number of top-level children nodes of this
* JTree. Each of these nodes may in turn have children nodes.
*
* @return the number of accessible children nodes in the tree.
*/
public int getAccessibleChildrenCount() {
TreeModel model = JTree.this.getModel();
if (model == null) {
return 0;
}
if (isRootVisible()) {
return 1; // the root node
}
// return the root's first set of children count
return model.getChildCount(model.getRoot());
}
/**
* Return the nth Accessible child of the object.
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
TreeModel model = JTree.this.getModel();
if (model == null) {
return null;
}
if (isRootVisible()) {
if (i == 0) { // return the root node Accessible
Object[] objPath = { model.getRoot() };
TreePath path = new TreePath(objPath);
return new AccessibleJTreeNode(JTree.this, path, JTree.this);
} else {
return null;
}
}
// return Accessible for one of root's child nodes
int count = model.getChildCount(model.getRoot());
if (i < 0 || i >= count) {
return null;
}
Object obj = model.getChild(model.getRoot(), i);
Object[] objPath = { model.getRoot(), obj };
TreePath path = new TreePath(objPath);
return new AccessibleJTreeNode(JTree.this, path, JTree.this);
}
/**
* Get the index of this object in its accessible parent.
*
* @return the index of this object in its parent. Since a JTree
* top-level object does not have an accessible parent.
* @see #getAccessibleParent
*/
public int getAccessibleIndexInParent() {
// didn't ever need to override this...
return super.getAccessibleIndexInParent();
}
// AccessibleSelection methods
/**
* Get the AccessibleSelection associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleSelection interface on behalf of itself.
*
* @return this object
*/
public AccessibleSelection getAccessibleSelection() {
return this;
}
/**
* Returns the number of items currently selected.
* If no items are selected, the return value will be 0.
*
* @return the number of items currently selected.
*/
public int getAccessibleSelectionCount() {
Object[] rootPath = new Object[1];
rootPath[0] = treeModel.getRoot();
TreePath childPath = new TreePath(rootPath);
if (JTree.this.isPathSelected(childPath)) {
return 1;
} else {
return 0;
}
}
/**
* Returns an Accessible representing the specified selected item
* in the object. If there isn't a selection, or there are
* fewer items selected than the integer passed in, the return
* value will be null.
*
* @param i the zero-based index of selected items
* @return an Accessible containing the selected item
*/
public Accessible getAccessibleSelection(int i) {
// The JTree can have only one accessible child, the root.
if (i == 0) {
Object[] rootPath = new Object[1];
rootPath[0] = treeModel.getRoot();
TreePath childPath = new TreePath(rootPath);
if (JTree.this.isPathSelected(childPath)) {
return new AccessibleJTreeNode(JTree.this, childPath, JTree.this);
}
}
return null;
}
/**
* Returns true if the current child of this object is selected.
*
* @param i the zero-based index of the child in this Accessible object.
* @see AccessibleContext#getAccessibleChild
*/
public boolean isAccessibleChildSelected(int i) {
// The JTree can have only one accessible child, the root.
if (i == 0) {
Object[] rootPath = new Object[1];
rootPath[0] = treeModel.getRoot();
TreePath childPath = new TreePath(rootPath);
return JTree.this.isPathSelected(childPath);
} else {
return false;
}
}
/**
* Adds the specified selected item in the object to the object's
* selection. If the object supports multiple selections,
* the specified item is added to any existing selection, otherwise
* it replaces any existing selection in the object. If the
* specified item is already selected, this method has no effect.
*
* @param i the zero-based index of selectable items
*/
public void addAccessibleSelection(int i) {
TreeModel model = JTree.this.getModel();
if (model != null) {
if (i == 0) {
Object[] objPath = {model.getRoot()};
TreePath path = new TreePath(objPath);
JTree.this.addSelectionPath(path);
}
}
}
/**
* Removes the specified selected item in the object from the object's
* selection. If the specified item isn't currently selected, this
* method has no effect.
*
* @param i the zero-based index of selectable items
*/
public void removeAccessibleSelection(int i) {
TreeModel model = JTree.this.getModel();
if (model != null) {
if (i == 0) {
Object[] objPath = {model.getRoot()};
TreePath path = new TreePath(objPath);
JTree.this.removeSelectionPath(path);
}
}
}
/**
* Clears the selection in the object, so that nothing in the
* object is selected.
*/
public void clearAccessibleSelection() {
int childCount = getAccessibleChildrenCount();
for (int i = 0; i < childCount; i++) {
removeAccessibleSelection(i);
}
}
/**
* Causes every selected item in the object to be selected
* if the object supports multiple selections.
*/
public void selectAllAccessibleSelection() {
TreeModel model = JTree.this.getModel();
if (model != null) {
Object[] objPath = {model.getRoot()};
TreePath path = new TreePath(objPath);
JTree.this.addSelectionPath(path);
}
}
/**
* This class implements accessibility support for the
* <code>JTree</code> child. It provides an implementation of the
* Java Accessibility API appropriate to tree nodes.
*/
protected class AccessibleJTreeNode extends AccessibleContext
implements Accessible, AccessibleComponent, AccessibleSelection,
AccessibleAction {
private JTree tree = null;
private TreeModel treeModel = null;
private Object obj = null;
private TreePath path = null;
private Accessible accessibleParent = null;
private int index = 0;
private boolean isLeaf = false;
/**
* Constructs an AccessibleJTreeNode
* @since 1.4
*/
public AccessibleJTreeNode(JTree t, TreePath p, Accessible ap) {
tree = t;
path = p;
accessibleParent = ap;
treeModel = t.getModel();
obj = p.getLastPathComponent();
if (treeModel != null) {
isLeaf = treeModel.isLeaf(obj);
}
}
private TreePath getChildTreePath(int i) {
// Tree nodes can't be so complex that they have
// two sets of children -> we're ignoring that case
if (i < 0 || i >= getAccessibleChildrenCount()) {
return null;
} else {
Object childObj = treeModel.getChild(obj, i);
Object[] objPath = path.getPath();
Object[] objChildPath = new Object[objPath.length+1];
java.lang.System.arraycopy(objPath, 0, objChildPath, 0, objPath.length);
objChildPath[objChildPath.length-1] = childObj;
return new TreePath(objChildPath);
}
}
/**
* Get the AccessibleContext associated with this tree node.
* In the implementation of the Java Accessibility API for
* this class, return this object, which is its own
* AccessibleContext.
*
* @return this object
*/
public AccessibleContext getAccessibleContext() {
return this;
}
private AccessibleContext getCurrentAccessibleContext() {
Component c = getCurrentComponent();
if (c instanceof Accessible) {
return c.getAccessibleContext();
} else {
return null;
}
}
private Component getCurrentComponent() {
// is the object visible?
// if so, get row, selected, focus & leaf state,
// and then get the renderer component and return it
if (tree.isVisible(path)) {
TreeCellRenderer r = tree.getCellRenderer();
if (r == null) {
return null;
}
TreeUI ui = tree.getUI();
if (ui != null) {
int row = ui.getRowForPath(JTree.this, path);
boolean selected = tree.isPathSelected(path);
boolean expanded = tree.isExpanded(path);
boolean hasFocus = false; // how to tell?? -PK
return r.getTreeCellRendererComponent(tree, obj,
selected, expanded, isLeaf, row, hasFocus);
}
}
return null;
}
// AccessibleContext methods
/**
* Get the accessible name of this object.
*
* @return the localized name of the object; null if this
* object does not have a name
*/
public String getAccessibleName() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
String name = ac.getAccessibleName();
if ((name != null) && (name != "")) {
return ac.getAccessibleName();
} else {
return null;
}
}
if ((accessibleName != null) && (accessibleName != "")) {
return accessibleName;
} else {
// fall back to the client property
return (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
}
}
/**
* Set the localized accessible name of this object.
*
* @param s the new localized name of the object.
*/
public void setAccessibleName(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleName(s);
} else {
super.setAccessibleName(s);
}
}
//
// *** should check tooltip text for desc. (needs MouseEvent)
//
/**
* Get the accessible description of this object.
*
* @return the localized description of the object; null if
* this object does not have a description
*/
public String getAccessibleDescription() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleDescription();
} else {
return super.getAccessibleDescription();
}
}
/**
* Set the accessible description of this object.
*
* @param s the new localized description of the object
*/
public void setAccessibleDescription(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleDescription(s);
} else {
super.setAccessibleDescription(s);
}
}
/**
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleRole();
} else {
return AccessibleRole.UNKNOWN;
}
}
/**
* Get the state set of this object.
*
* @return an instance of AccessibleStateSet containing the
* current state set of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleContext ac = getCurrentAccessibleContext();
AccessibleStateSet states;
if (ac != null) {
states = ac.getAccessibleStateSet();
} else {
states = new AccessibleStateSet();
}
// need to test here, 'cause the underlying component
// is a cellRenderer, which is never showing...
if (isShowing()) {
states.add(AccessibleState.SHOWING);
} else if (states.contains(AccessibleState.SHOWING)) {
states.remove(AccessibleState.SHOWING);
}
if (isVisible()) {
states.add(AccessibleState.VISIBLE);
} else if (states.contains(AccessibleState.VISIBLE)) {
states.remove(AccessibleState.VISIBLE);
}
if (tree.isPathSelected(path)){
states.add(AccessibleState.SELECTED);
}
if (path == getLeadSelectionPath()) {
states.add(AccessibleState.ACTIVE);
}
if (!isLeaf) {
states.add(AccessibleState.EXPANDABLE);
}
if (tree.isExpanded(path)) {
states.add(AccessibleState.EXPANDED);
} else {
states.add(AccessibleState.COLLAPSED);
}
if (tree.isEditable()) {
states.add(AccessibleState.EDITABLE);
}
return states;
}
/**
* Get the Accessible parent of this object.
*
* @return the Accessible parent of this object; null if this
* object does not have an Accessible parent
*/
public Accessible getAccessibleParent() {
// someone wants to know, so we need to create our parent
// if we don't have one (hey, we're a talented kid!)
if (accessibleParent == null) {
Object[] objPath = path.getPath();
if (objPath.length > 1) {
Object objParent = objPath[objPath.length-2];
if (treeModel != null) {
index = treeModel.getIndexOfChild(objParent, obj);
}
Object[] objParentPath = new Object[objPath.length-1];
java.lang.System.arraycopy(objPath, 0, objParentPath,
0, objPath.length-1);
TreePath parentPath = new TreePath(objParentPath);
accessibleParent = new AccessibleJTreeNode(tree,
parentPath,
null);
this.setAccessibleParent(accessibleParent);
} else if (treeModel != null) {
accessibleParent = tree; // we're the top!
index = 0; // we're an only child!
this.setAccessibleParent(accessibleParent);
}
}
return accessibleParent;
}
/**
* Get the index of this object in its accessible parent.
*
* @return the index of this object in its parent; -1 if this
* object does not have an accessible parent.
* @see #getAccessibleParent
*/
public int getAccessibleIndexInParent() {
// index is invalid 'till we have an accessibleParent...
if (accessibleParent == null) {
getAccessibleParent();
}
Object[] objPath = path.getPath();
if (objPath.length > 1) {
Object objParent = objPath[objPath.length-2];
if (treeModel != null) {
index = treeModel.getIndexOfChild(objParent, obj);
}
}
return index;
}
/**
* Returns the number of accessible children in the object.
*
* @return the number of accessible children in the object.
*/
public int getAccessibleChildrenCount() {
// Tree nodes can't be so complex that they have
// two sets of children -> we're ignoring that case
return treeModel.getChildCount(obj);
}
/**
* Return the specified Accessible child of the object.
*
* @param i zero-based index of child
* @return the Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
// Tree nodes can't be so complex that they have
// two sets of children -> we're ignoring that case
if (i < 0 || i >= getAccessibleChildrenCount()) {
return null;
} else {
Object childObj = treeModel.getChild(obj, i);
Object[] objPath = path.getPath();
Object[] objChildPath = new Object[objPath.length+1];
java.lang.System.arraycopy(objPath, 0, objChildPath, 0, objPath.length);
objChildPath[objChildPath.length-1] = childObj;
TreePath childPath = new TreePath(objChildPath);
return new AccessibleJTreeNode(JTree.this, childPath, this);
}
}
/**
* Gets the locale of the component. If the component does not have
* a locale, then the locale of its parent is returned.
*
* @return This component's locale. If this component does not have
* a locale, the locale of its parent is returned.
* @exception IllegalComponentStateException
* If the Component does not have its own locale and has not yet
* been added to a containment hierarchy such that the locale can be
* determined from the containing parent.
* @see #setLocale
*/
public Locale getLocale() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getLocale();
} else {
return tree.getLocale();
}
}
/**
* Add a PropertyChangeListener to the listener list.
* The listener is registered for all properties.
*
* @param l The PropertyChangeListener to be added
*/
public void addPropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.addPropertyChangeListener(l);
} else {
super.addPropertyChangeListener(l);
}
}
/**
* Remove a PropertyChangeListener from the listener list.
* This removes a PropertyChangeListener that was registered
* for all properties.
*
* @param l The PropertyChangeListener to be removed
*/
public void removePropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.removePropertyChangeListener(l);
} else {
super.removePropertyChangeListener(l);
}
}
/**
* Get the AccessibleAction associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleAction interface on behalf of itself.
*
* @return this object
*/
public AccessibleAction getAccessibleAction() {
return this;
}
/**
* Get the AccessibleComponent associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleComponent interface on behalf of itself.
*
* @return this object
*/
public AccessibleComponent getAccessibleComponent() {
return this; // to override getBounds()
}
/**
* Get the AccessibleSelection associated with this object if one
* exists. Otherwise return null.
*
* @return the AccessibleSelection, or null
*/
public AccessibleSelection getAccessibleSelection() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null && isLeaf) {
return getCurrentAccessibleContext().getAccessibleSelection();
} else {
return this;
}
}
/**
* Get the AccessibleText associated with this object if one
* exists. Otherwise return null.
*
* @return the AccessibleText, or null
*/
public AccessibleText getAccessibleText() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return getCurrentAccessibleContext().getAccessibleText();
} else {
return null;
}
}
/**
* Get the AccessibleValue associated with this object if one
* exists. Otherwise return null.
*
* @return the AccessibleValue, or null
*/
public AccessibleValue getAccessibleValue() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return getCurrentAccessibleContext().getAccessibleValue();
} else {
return null;
}
}
// AccessibleComponent methods
/**
* Get the background color of this object.
*
* @return the background color, if supported, of the object;
* otherwise, null
*/
public Color getBackground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getBackground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getBackground();
} else {
return null;
}
}
}
/**
* Set the background color of this object.
*
* @param c the new Color for the background
*/
public void setBackground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBackground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setBackground(c);
}
}
}
/**
* Get the foreground color of this object.
*
* @return the foreground color, if supported, of the object;
* otherwise, null
*/
public Color getForeground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getForeground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getForeground();
} else {
return null;
}
}
}
public void setForeground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setForeground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setForeground(c);
}
}
}
public Cursor getCursor() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getCursor();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getCursor();
} else {
Accessible ap = getAccessibleParent();
if (ap instanceof AccessibleComponent) {
return ((AccessibleComponent) ap).getCursor();
} else {
return null;
}
}
}
}
public void setCursor(Cursor c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setCursor(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setCursor(c);
}
}
}
public Font getFont() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFont();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFont();
} else {
return null;
}
}
}
public void setFont(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setFont(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setFont(f);
}
}
}
public FontMetrics getFontMetrics(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFontMetrics(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFontMetrics(f);
} else {
return null;
}
}
}
public boolean isEnabled() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isEnabled();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isEnabled();
} else {
return false;
}
}
}
public void setEnabled(boolean b) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setEnabled(b);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setEnabled(b);
}
}
}
public boolean isVisible() {
Rectangle pathBounds = tree.getPathBounds(path);
Rectangle parentBounds = tree.getVisibleRect();
return pathBounds != null && parentBounds != null &&
parentBounds.intersects(pathBounds);
}
public void setVisible(boolean b) {
}
public boolean isShowing() {
return (tree.isShowing() && isVisible());
}
public boolean contains(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
Rectangle r = ((AccessibleComponent) ac).getBounds();
return r.contains(p);
} else {
Component c = getCurrentComponent();
if (c != null) {
Rectangle r = c.getBounds();
return r.contains(p);
} else {
return getBounds().contains(p);
}
}
}
public Point getLocationOnScreen() {
if (tree != null) {
Point treeLocation = tree.getLocationOnScreen();
Rectangle pathBounds = tree.getPathBounds(path);
if (treeLocation != null && pathBounds != null) {
Point nodeLocation = new Point(pathBounds.x,
pathBounds.y);
nodeLocation.translate(treeLocation.x, treeLocation.y);
return nodeLocation;
} else {
return null;
}
} else {
return null;
}
}
protected Point getLocationInJTree() {
Rectangle r = tree.getPathBounds(path);
if (r != null) {
return r.getLocation();
} else {
return null;
}
}
public Point getLocation() {
Rectangle r = getBounds();
if (r != null) {
return r.getLocation();
} else {
return null;
}
}
public void setLocation(Point p) {
}
public Rectangle getBounds() {
Rectangle r = tree.getPathBounds(path);
Accessible parent = getAccessibleParent();
if (parent != null) {
if (parent instanceof AccessibleJTreeNode) {
Point parentLoc = ((AccessibleJTreeNode) parent).getLocationInJTree();
if (parentLoc != null && r != null) {
r.translate(-parentLoc.x, -parentLoc.y);
} else {
return null; // not visible!
}
}
}
return r;
}
public void setBounds(Rectangle r) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBounds(r);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setBounds(r);
}
}
}
public Dimension getSize() {
return getBounds().getSize();
}
public void setSize (Dimension d) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setSize(d);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setSize(d);
}
}
}
/**
* Returns the <code>Accessible</code> child, if one exists,
* contained at the local coordinate <code>Point</code>.
* Otherwise returns <code>null</code>.
*
* @param p point in local coordinates of this
* <code>Accessible</code>
* @return the <code>Accessible</code>, if it exists,
* at the specified location; else <code>null</code>
*/
public Accessible getAccessibleAt(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getAccessibleAt(p);
} else {
return null;
}
}
@SuppressWarnings("deprecation")
public boolean isFocusTraversable() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isFocusTraversable();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isFocusTraversable();
} else {
return false;
}
}
}
public void requestFocus() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).requestFocus();
} else {
Component c = getCurrentComponent();
if (c != null) {
c.requestFocus();
}
}
}
public void addFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).addFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.addFocusListener(l);
}
}
}
public void removeFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).removeFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.removeFocusListener(l);
}
}
}
// AccessibleSelection methods
/**
* Returns the number of items currently selected.
* If no items are selected, the return value will be 0.
*
* @return the number of items currently selected.
*/
public int getAccessibleSelectionCount() {
int count = 0;
int childCount = getAccessibleChildrenCount();
for (int i = 0; i < childCount; i++) {
TreePath childPath = getChildTreePath(i);
if (tree.isPathSelected(childPath)) {
count++;
}
}
return count;
}
/**
* Returns an Accessible representing the specified selected item
* in the object. If there isn't a selection, or there are
* fewer items selected than the integer passed in, the return
* value will be null.
*
* @param i the zero-based index of selected items
* @return an Accessible containing the selected item
*/
public Accessible getAccessibleSelection(int i) {
int childCount = getAccessibleChildrenCount();
if (i < 0 || i >= childCount) {
return null; // out of range
}
int count = 0;
for (int j = 0; j < childCount && i >= count; j++) {
TreePath childPath = getChildTreePath(j);
if (tree.isPathSelected(childPath)) {
if (count == i) {
return new AccessibleJTreeNode(tree, childPath, this);
} else {
count++;
}
}
}
return null;
}
/**
* Returns true if the current child of this object is selected.
*
* @param i the zero-based index of the child in this Accessible
* object.
* @see AccessibleContext#getAccessibleChild
*/
public boolean isAccessibleChildSelected(int i) {
int childCount = getAccessibleChildrenCount();
if (i < 0 || i >= childCount) {
return false; // out of range
} else {
TreePath childPath = getChildTreePath(i);
return tree.isPathSelected(childPath);
}
}
/**
* Adds the specified selected item in the object to the object's
* selection. If the object supports multiple selections,
* the specified item is added to any existing selection, otherwise
* it replaces any existing selection in the object. If the
* specified item is already selected, this method has no effect.
*
* @param i the zero-based index of selectable items
*/
public void addAccessibleSelection(int i) {
TreeModel model = JTree.this.getModel();
if (model != null) {
if (i >= 0 && i < getAccessibleChildrenCount()) {
TreePath path = getChildTreePath(i);
JTree.this.addSelectionPath(path);
}
}
}
/**
* Removes the specified selected item in the object from the
* object's
* selection. If the specified item isn't currently selected, this
* method has no effect.
*
* @param i the zero-based index of selectable items
*/
public void removeAccessibleSelection(int i) {
TreeModel model = JTree.this.getModel();
if (model != null) {
if (i >= 0 && i < getAccessibleChildrenCount()) {
TreePath path = getChildTreePath(i);
JTree.this.removeSelectionPath(path);
}
}
}
/**
* Clears the selection in the object, so that nothing in the
* object is selected.
*/
public void clearAccessibleSelection() {
int childCount = getAccessibleChildrenCount();
for (int i = 0; i < childCount; i++) {
removeAccessibleSelection(i);
}
}
/**
* Causes every selected item in the object to be selected
* if the object supports multiple selections.
*/
public void selectAllAccessibleSelection() {
TreeModel model = JTree.this.getModel();
if (model != null) {
int childCount = getAccessibleChildrenCount();
TreePath path;
for (int i = 0; i < childCount; i++) {
path = getChildTreePath(i);
JTree.this.addSelectionPath(path);
}
}
}
// AccessibleAction methods
/**
* Returns the number of accessible actions available in this
* tree node. If this node is not a leaf, there is at least
* one action (toggle expand), in addition to any available
* on the object behind the TreeCellRenderer.
*
* @return the number of Actions in this object
*/
public int getAccessibleActionCount() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
AccessibleAction aa = ac.getAccessibleAction();
if (aa != null) {
return (aa.getAccessibleActionCount() + (isLeaf ? 0 : 1));
}
}
return isLeaf ? 0 : 1;
}
/**
* Return a description of the specified action of the tree node.
* If this node is not a leaf, there is at least one action
* description (toggle expand), in addition to any available
* on the object behind the TreeCellRenderer.
*
* @param i zero-based index of the actions
* @return a description of the action
*/
public String getAccessibleActionDescription(int i) {
if (i < 0 || i >= getAccessibleActionCount()) {
return null;
}
AccessibleContext ac = getCurrentAccessibleContext();
if (i == 0) {
// TIGER - 4766636
return AccessibleAction.TOGGLE_EXPAND;
} else if (ac != null) {
AccessibleAction aa = ac.getAccessibleAction();
if (aa != null) {
return aa.getAccessibleActionDescription(i - 1);
}
}
return null;
}
/**
* Perform the specified Action on the tree node. If this node
* is not a leaf, there is at least one action which can be
* done (toggle expand), in addition to any available on the
* object behind the TreeCellRenderer.
*
* @param i zero-based index of actions
* @return true if the the action was performed; else false.
*/
public boolean doAccessibleAction(int i) {
if (i < 0 || i >= getAccessibleActionCount()) {
return false;
}
AccessibleContext ac = getCurrentAccessibleContext();
if (i == 0) {
if (JTree.this.isExpanded(path)) {
JTree.this.collapsePath(path);
} else {
JTree.this.expandPath(path);
}
return true;
} else if (ac != null) {
AccessibleAction aa = ac.getAccessibleAction();
if (aa != null) {
return aa.doAccessibleAction(i - 1);
}
}
return false;
}
} // inner class AccessibleJTreeNode
} // inner class AccessibleJTree
} // End of class JTree
| 206,462
|
Java
|
.java
| 5,027
| 30.228964
| 102
| 0.571112
|
keerath/openjdk-8-source
| 39
| 26
| 0
|
GPL-2.0
|
9/4/2024, 7:24:11 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 206,462
|
4,381,631
|
BenchmarkTest01247.java
|
tranmyabs_OWASPBenchmark/src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01247.java
|
/**
* OWASP Benchmark Project v1.2
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The OWASP Benchmark 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.
*
* The OWASP Benchmark 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.
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(value="/hash-01/BenchmarkTest01247")
public class BenchmarkTest01247 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String param = request.getParameter("BenchmarkTest01247");
if (param == null) param = "";
String bar = new Test().doSomething(request, param);
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] input = { (byte)'?' };
Object inputParam = bar;
if (inputParam instanceof String) input = ((String) inputParam).getBytes();
if (inputParam instanceof java.io.InputStream) {
byte[] strInput = new byte[1000];
int i = ((java.io.InputStream) inputParam).read(strInput);
if (i == -1) {
response.getWriter().println(
"This input source requires a POST, not a GET. Incompatible UI for the InputStream source."
);
return;
}
input = java.util.Arrays.copyOf(strInput, i);
}
md.update(input);
byte[] result = md.digest();
java.io.File fileTarget = new java.io.File(
new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir),"passwordFile.txt");
java.io.FileWriter fw = new java.io.FileWriter(fileTarget,true); //the true will append the new data
fw.write("hash_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n");
fw.close();
response.getWriter().println(
"Sensitive value '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input)) + "' hashed and stored<br/>"
);
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing hash - TestCase");
throw new ServletException(e);
}
response.getWriter().println(
"Hash Test java.security.MessageDigest.getInstance(java.lang.String) executed"
);
} // end doPost
private class Test {
public String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {
String bar = param;
if (param != null && param.length() > 1) {
bar = param.substring(0,param.length()-1);
}
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| 3,570
|
Java
|
.java
| 81
| 40.728395
| 116
| 0.748193
|
tranmyabs/OWASPBenchmark
| 2
| 1
| 0
|
GPL-2.0
|
9/5/2024, 12:11:05 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| true
| false
| true
| 3,570
|
265,914
|
SingleSelectionModel.java
|
openjdk-mirror_jdk7u-jdk/src/share/classes/javax/swing/SingleSelectionModel.java
|
/*
* Copyright (c) 1997, 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing;
import javax.swing.event.*;
/**
* A model that supports at most one indexed selection.
*
* @author Dave Moore
*/
public interface SingleSelectionModel {
/**
* Returns the model's selection.
*
* @return the model's selection, or -1 if there is no selection
* @see #setSelectedIndex
*/
public int getSelectedIndex();
/**
* Sets the model's selected index to <I>index</I>.
*
* Notifies any listeners if the model changes
*
* @param index an int specifying the model selection
* @see #getSelectedIndex
* @see #addChangeListener
*/
public void setSelectedIndex(int index);
/**
* Clears the selection (to -1).
*/
public void clearSelection();
/**
* Returns true if the selection model currently has a selected value.
* @return true if a value is currently selected
*/
public boolean isSelected();
/**
* Adds <I>listener</I> as a listener to changes in the model.
* @param listener the ChangeListener to add
*/
void addChangeListener(ChangeListener listener);
/**
* Removes <I>listener</I> as a listener to changes in the model.
* @param listener the ChangeListener to remove
*/
void removeChangeListener(ChangeListener listener);
}
| 2,549
|
Java
|
.java
| 69
| 33
| 79
| 0.712783
|
openjdk-mirror/jdk7u-jdk
| 525
| 429
| 6
|
GPL-2.0
|
9/4/2024, 7:05:59 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 2,549
|
2,798,406
|
JdbcSQLInvalidAuthorizationSpecException.java
|
GreenByMe_GreenByMe_Server/h2/src/main/org/h2/jdbc/JdbcSQLInvalidAuthorizationSpecException.java
|
/*
* Copyright 2004-2019 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (https://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.jdbc;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.sql.SQLInvalidAuthorizationSpecException;
import org.h2.message.DbException;
/**
* Represents a database exception.
*/
public class JdbcSQLInvalidAuthorizationSpecException extends SQLInvalidAuthorizationSpecException
implements JdbcException {
private static final long serialVersionUID = 1L;
private final String originalMessage;
private final String stackTrace;
private String message;
private String sql;
/**
* Creates a SQLInvalidAuthorizationSpecException.
*
* @param message the reason
* @param sql the SQL statement
* @param state the SQL state
* @param errorCode the error code
* @param cause the exception that was the reason for this exception
* @param stackTrace the stack trace
*/
public JdbcSQLInvalidAuthorizationSpecException(String message, String sql, String state,
int errorCode, Throwable cause, String stackTrace) {
super(message, state, errorCode);
this.originalMessage = message;
this.stackTrace = stackTrace;
// setSQL() also generates message
setSQL(sql);
initCause(cause);
}
@Override
public String getMessage() {
return message;
}
@Override
public String getOriginalMessage() {
return originalMessage;
}
@Override
public void printStackTrace(PrintWriter s) {
super.printStackTrace(s);
DbException.printNextExceptions(this, s);
}
@Override
public void printStackTrace(PrintStream s) {
super.printStackTrace(s);
DbException.printNextExceptions(this, s);
}
@Override
public String getSQL() {
return sql;
}
@Override
public void setSQL(String sql) {
this.sql = sql;
message = DbException.buildMessageForException(this);
}
@Override
public String toString() {
if (stackTrace == null) {
return super.toString();
}
return stackTrace;
}
}
| 2,271
|
Java
|
.java
| 74
| 24.864865
| 98
| 0.692625
|
GreenByMe/GreenByMe_Server
| 6
| 0
| 10
|
GPL-3.0
|
9/4/2024, 10:15:44 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 2,271
|
4,173,794
|
IntRules124.java
|
andryr_symja/symja_android_library/matheclipse-core/src/main/java/org/matheclipse/core/integrate/rubi45/IntRules124.java
|
package org.matheclipse.core.integrate.rubi45;
import static org.matheclipse.core.expression.F.*;
import static org.matheclipse.core.integrate.rubi45.UtilityFunctionCtors.*;
import static org.matheclipse.core.integrate.rubi45.UtilityFunctions.*;
import org.matheclipse.core.interfaces.IAST;
/**
* IndefiniteIntegrationRules from the <a href="http://www.apmaths.uwo.ca/~arich/">Rubi -
* rule-based integrator</a>.
*
*/
public class IntRules124 {
public static IAST RULES = List(
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Power(x_,n_DEFAULT))),-1),ArcTanh(Plus(a_,Times(b_DEFAULT,x_)))),x_Symbol),
Condition(Plus(Times(C1D2,Int(Times(Log(Plus(C1,a,Times(b,x))),Power(Plus(c,Times(d,Power(x,n))),-1)),x)),Times(CN1,C1D2,Int(Times(Log(Plus(C1,Negate(a),Times(CN1,b,x))),Power(Plus(c,Times(d,Power(x,n))),-1)),x))),And(FreeQ(List(a,b,c,d),x),RationalQ(n)))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Power(x_,n_DEFAULT))),-1),ArcCoth(Plus(a_,Times(b_DEFAULT,x_)))),x_Symbol),
Condition(Plus(Times(C1D2,Int(Times(Log(Times(Plus(C1,a,Times(b,x)),Power(Plus(a,Times(b,x)),-1))),Power(Plus(c,Times(d,Power(x,n))),-1)),x)),Times(CN1,C1D2,Int(Times(Log(Times(Plus(CN1,a,Times(b,x)),Power(Plus(a,Times(b,x)),-1))),Power(Plus(c,Times(d,Power(x,n))),-1)),x))),And(FreeQ(List(a,b,c,d),x),RationalQ(n)))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Power(x_,n_))),-1),ArcTanh(Plus(a_,Times(b_DEFAULT,x_)))),x_Symbol),
Condition(Integrate(Times(ArcTanh(Plus(a,Times(b,x))),Power(Plus(c,Times(d,Power(x,n))),-1)),x),And(FreeQ(List(a,b,c,d,n),x),Not(RationalQ(n))))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Power(x_,n_))),-1),ArcCoth(Plus(a_,Times(b_DEFAULT,x_)))),x_Symbol),
Condition(Integrate(Times(ArcCoth(Plus(a,Times(b,x))),Power(Plus(c,Times(d,Power(x,n))),-1)),x),And(FreeQ(List(a,b,c,d,n),x),Not(RationalQ(n))))),
ISetDelayed(Int(ArcTanh(Plus(a_,Times(b_DEFAULT,Power(x_,n_)))),x_Symbol),
Condition(Plus(Times(x,ArcTanh(Plus(a,Times(b,Power(x,n))))),Times(CN1,b,n,Int(Times(Power(x,n),Power(Plus(C1,Negate(Sqr(a)),Times(CN1,C2,a,b,Power(x,n)),Times(CN1,Sqr(b),Power(x,Times(C2,n)))),-1)),x))),FreeQ(List(a,b,n),x))),
ISetDelayed(Int(ArcCoth(Plus(a_,Times(b_DEFAULT,Power(x_,n_)))),x_Symbol),
Condition(Plus(Times(x,ArcCoth(Plus(a,Times(b,Power(x,n))))),Times(CN1,b,n,Int(Times(Power(x,n),Power(Plus(C1,Negate(Sqr(a)),Times(CN1,C2,a,b,Power(x,n)),Times(CN1,Sqr(b),Power(x,Times(C2,n)))),-1)),x))),FreeQ(List(a,b,n),x))),
ISetDelayed(Int(Times(Power(x_,-1),ArcTanh(Plus(a_DEFAULT,Times(b_DEFAULT,Power(x_,n_DEFAULT))))),x_Symbol),
Condition(Plus(Times(C1D2,Int(Times(Log(Plus(C1,a,Times(b,Power(x,n)))),Power(x,-1)),x)),Times(CN1,C1D2,Int(Times(Log(Plus(C1,Negate(a),Times(CN1,b,Power(x,n)))),Power(x,-1)),x))),FreeQ(List(a,b,n),x))),
ISetDelayed(Int(Times(Power(x_,-1),ArcCoth(Plus(a_DEFAULT,Times(b_DEFAULT,Power(x_,n_DEFAULT))))),x_Symbol),
Condition(Plus(Times(C1D2,Int(Times(Log(Plus(C1,Power(Plus(a,Times(b,Power(x,n))),-1))),Power(x,-1)),x)),Times(CN1,C1D2,Int(Times(Log(Plus(C1,Negate(Power(Plus(a,Times(b,Power(x,n))),-1)))),Power(x,-1)),x))),FreeQ(List(a,b,n),x))),
ISetDelayed(Int(Times(Power(x_,m_DEFAULT),ArcTanh(Plus(a_,Times(b_DEFAULT,Power(x_,n_))))),x_Symbol),
Condition(Plus(Times(Power(x,Plus(m,C1)),ArcTanh(Plus(a,Times(b,Power(x,n)))),Power(Plus(m,C1),-1)),Times(CN1,b,n,Power(Plus(m,C1),-1),Int(Times(Power(x,Plus(m,n)),Power(Plus(C1,Negate(Sqr(a)),Times(CN1,C2,a,b,Power(x,n)),Times(CN1,Sqr(b),Power(x,Times(C2,n)))),-1)),x))),And(And(And(FreeQ(List(a,b),x),RationalQ(m,n)),Unequal(Plus(m,C1),C0)),Unequal(Plus(m,C1),n)))),
ISetDelayed(Int(Times(Power(x_,m_DEFAULT),ArcCoth(Plus(a_,Times(b_DEFAULT,Power(x_,n_))))),x_Symbol),
Condition(Plus(Times(Power(x,Plus(m,C1)),ArcCoth(Plus(a,Times(b,Power(x,n)))),Power(Plus(m,C1),-1)),Times(CN1,b,n,Power(Plus(m,C1),-1),Int(Times(Power(x,Plus(m,n)),Power(Plus(C1,Negate(Sqr(a)),Times(CN1,C2,a,b,Power(x,n)),Times(CN1,Sqr(b),Power(x,Times(C2,n)))),-1)),x))),And(And(And(FreeQ(List(a,b),x),RationalQ(m,n)),Unequal(Plus(m,C1),C0)),Unequal(Plus(m,C1),n)))),
ISetDelayed(Int(ArcTanh(Plus(a_DEFAULT,Times(b_DEFAULT,Power(f_,Plus(c_DEFAULT,Times(d_DEFAULT,x_)))))),x_Symbol),
Condition(Plus(Times(C1D2,Int(Log(Plus(C1,a,Times(b,Power(f,Plus(c,Times(d,x)))))),x)),Times(CN1,C1D2,Int(Log(Plus(C1,Negate(a),Times(CN1,b,Power(f,Plus(c,Times(d,x)))))),x))),FreeQ(List(a,b,c,d,f),x))),
ISetDelayed(Int(ArcCoth(Plus(a_DEFAULT,Times(b_DEFAULT,Power(f_,Plus(c_DEFAULT,Times(d_DEFAULT,x_)))))),x_Symbol),
Condition(Plus(Times(C1D2,Int(Log(Plus(C1,Power(Plus(a,Times(b,Power(f,Plus(c,Times(d,x))))),-1))),x)),Times(CN1,C1D2,Int(Log(Plus(C1,Negate(Power(Plus(a,Times(b,Power(f,Plus(c,Times(d,x))))),-1)))),x))),FreeQ(List(a,b,c,d,f),x))),
ISetDelayed(Int(Times(Power(x_,m_DEFAULT),ArcTanh(Plus(a_DEFAULT,Times(b_DEFAULT,Power(f_,Plus(c_DEFAULT,Times(d_DEFAULT,x_))))))),x_Symbol),
Condition(Plus(Times(C1D2,Int(Times(Power(x,m),Log(Plus(C1,a,Times(b,Power(f,Plus(c,Times(d,x))))))),x)),Times(CN1,C1D2,Int(Times(Power(x,m),Log(Plus(C1,Negate(a),Times(CN1,b,Power(f,Plus(c,Times(d,x))))))),x))),And(And(FreeQ(List(a,b,c,d,f),x),IntegerQ(m)),Greater(m,C0)))),
ISetDelayed(Int(Times(Power(x_,m_DEFAULT),ArcCoth(Plus(a_DEFAULT,Times(b_DEFAULT,Power(f_,Plus(c_DEFAULT,Times(d_DEFAULT,x_))))))),x_Symbol),
Condition(Plus(Times(C1D2,Int(Times(Power(x,m),Log(Plus(C1,Power(Plus(a,Times(b,Power(f,Plus(c,Times(d,x))))),-1)))),x)),Times(CN1,C1D2,Int(Times(Power(x,m),Log(Plus(C1,Negate(Power(Plus(a,Times(b,Power(f,Plus(c,Times(d,x))))),-1))))),x))),And(And(FreeQ(List(a,b,c,d,f),x),IntegerQ(m)),Greater(m,C0)))),
ISetDelayed(Int(Times(u_DEFAULT,Power(ArcTanh(Times(c_DEFAULT,Power(Plus(a_DEFAULT,Times(b_DEFAULT,Power(x_,n_DEFAULT))),-1))),m_DEFAULT)),x_Symbol),
Condition(Int(Times(u,Power(ArcCoth(Plus(Times(a,Power(c,-1)),Times(b,Power(x,n),Power(c,-1)))),m)),x),FreeQ(List(a,b,c,n,m),x))),
ISetDelayed(Int(Times(u_DEFAULT,Power(ArcCoth(Times(c_DEFAULT,Power(Plus(a_DEFAULT,Times(b_DEFAULT,Power(x_,n_DEFAULT))),-1))),m_DEFAULT)),x_Symbol),
Condition(Int(Times(u,Power(ArcTanh(Plus(Times(a,Power(c,-1)),Times(b,Power(x,n),Power(c,-1)))),m)),x),FreeQ(List(a,b,c,n,m),x))),
ISetDelayed(Int(Power(Times(Sqrt(Plus(a_DEFAULT,Times(b_DEFAULT,Sqr(x_)))),ArcTanh(Times(c_DEFAULT,x_,Power(Plus(a_DEFAULT,Times(b_DEFAULT,Sqr(x_))),CN1D2)))),-1),x_Symbol),
Condition(Times(Power(c,-1),Log(ArcTanh(Times(c,x,Power(Plus(a,Times(b,Sqr(x))),CN1D2))))),And(FreeQ(List(a,b,c),x),ZeroQ(Plus(b,Negate(Sqr(c))))))),
ISetDelayed(Int(Power(Times(Sqrt(Plus(a_DEFAULT,Times(b_DEFAULT,Sqr(x_)))),ArcCoth(Times(c_DEFAULT,x_,Power(Plus(a_DEFAULT,Times(b_DEFAULT,Sqr(x_))),CN1D2)))),-1),x_Symbol),
Condition(Times(CN1,Power(c,-1),Log(ArcCoth(Times(c,x,Power(Plus(a,Times(b,Sqr(x))),CN1D2))))),And(FreeQ(List(a,b,c),x),ZeroQ(Plus(b,Negate(Sqr(c))))))),
ISetDelayed(Int(Times(Power(Plus(a_DEFAULT,Times(b_DEFAULT,Sqr(x_))),CN1D2),Power(ArcTanh(Times(c_DEFAULT,x_,Power(Plus(a_DEFAULT,Times(b_DEFAULT,Sqr(x_))),CN1D2))),m_DEFAULT)),x_Symbol),
Condition(Times(Power(ArcTanh(Times(c,x,Power(Plus(a,Times(b,Sqr(x))),CN1D2))),Plus(m,C1)),Power(Times(c,Plus(m,C1)),-1)),And(And(FreeQ(List(a,b,c,m),x),ZeroQ(Plus(b,Negate(Sqr(c))))),NonzeroQ(Plus(m,C1))))),
ISetDelayed(Int(Times(Power(Plus(a_DEFAULT,Times(b_DEFAULT,Sqr(x_))),CN1D2),Power(ArcCoth(Times(c_DEFAULT,x_,Power(Plus(a_DEFAULT,Times(b_DEFAULT,Sqr(x_))),CN1D2))),m_DEFAULT)),x_Symbol),
Condition(Times(CN1,Power(ArcCoth(Times(c,x,Power(Plus(a,Times(b,Sqr(x))),CN1D2))),Plus(m,C1)),Power(Times(c,Plus(m,C1)),-1)),And(And(FreeQ(List(a,b,c,m),x),ZeroQ(Plus(b,Negate(Sqr(c))))),NonzeroQ(Plus(m,C1))))),
ISetDelayed(Int(Times(Power(Plus(d_DEFAULT,Times(e_DEFAULT,Sqr(x_))),CN1D2),Power(ArcTanh(Times(c_DEFAULT,x_,Power(Plus(a_DEFAULT,Times(b_DEFAULT,Sqr(x_))),CN1D2))),m_DEFAULT)),x_Symbol),
Condition(Times(Sqrt(Plus(a,Times(b,Sqr(x)))),Power(Plus(d,Times(e,Sqr(x))),CN1D2),Int(Times(Power(ArcTanh(Times(c,x,Power(Plus(a,Times(b,Sqr(x))),CN1D2))),m),Power(Plus(a,Times(b,Sqr(x))),CN1D2)),x)),And(And(FreeQ(List(a,b,c,d,e,m),x),ZeroQ(Plus(b,Negate(Sqr(c))))),ZeroQ(Plus(Times(b,d),Times(CN1,a,e)))))),
ISetDelayed(Int(Times(Power(Plus(d_DEFAULT,Times(e_DEFAULT,Sqr(x_))),CN1D2),Power(ArcCoth(Times(c_DEFAULT,x_,Power(Plus(a_DEFAULT,Times(b_DEFAULT,Sqr(x_))),CN1D2))),m_DEFAULT)),x_Symbol),
Condition(Times(Sqrt(Plus(a,Times(b,Sqr(x)))),Power(Plus(d,Times(e,Sqr(x))),CN1D2),Int(Times(Power(ArcCoth(Times(c,x,Power(Plus(a,Times(b,Sqr(x))),CN1D2))),m),Power(Plus(a,Times(b,Sqr(x))),CN1D2)),x)),And(And(FreeQ(List(a,b,c,d,e,m),x),ZeroQ(Plus(b,Negate(Sqr(c))))),ZeroQ(Plus(Times(b,d),Times(CN1,a,e)))))),
ISetDelayed(Int(Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_)))),x_Symbol),
Condition(Int(Times(Power(Plus(C1,Times(a,x)),Times(C1D2,Plus(n,C1))),Power(Times(Power(Plus(C1,Times(CN1,a,x)),Times(C1D2,Plus(n,Negate(C1)))),Sqrt(Plus(C1,Times(CN1,Sqr(a),Sqr(x))))),-1)),x),And(FreeQ(a,x),OddQ(n)))),
ISetDelayed(Int(Times(Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_)))),Power(x_,m_DEFAULT)),x_Symbol),
Condition(Int(Times(Power(x,m),Power(Plus(C1,Times(a,x)),Times(C1D2,Plus(n,C1))),Power(Times(Power(Plus(C1,Times(CN1,a,x)),Times(C1D2,Plus(n,Negate(C1)))),Sqrt(Plus(C1,Times(CN1,Sqr(a),Sqr(x))))),-1)),x),And(FreeQ(List(a,m),x),OddQ(n)))),
ISetDelayed(Int(Power(E,Times(n_,ArcTanh(Times(a_DEFAULT,x_)))),x_Symbol),
Condition(Int(Times(Power(Plus(C1,Times(a,x)),Times(C1D2,n)),Power(Power(Plus(C1,Times(CN1,a,x)),Times(C1D2,n)),-1)),x),And(FreeQ(List(a,n),x),Not(OddQ(n))))),
ISetDelayed(Int(Times(Power(E,Times(n_,ArcTanh(Times(a_DEFAULT,x_)))),Power(x_,m_DEFAULT)),x_Symbol),
Condition(Int(Times(Power(x,m),Power(Plus(C1,Times(a,x)),Times(C1D2,n)),Power(Power(Plus(C1,Times(CN1,a,x)),Times(C1D2,n)),-1)),x),And(FreeQ(List(a,m,n),x),Not(OddQ(n))))),
ISetDelayed(Int(Times(u_DEFAULT,Power(Plus(c_,Times(d_DEFAULT,x_)),p_DEFAULT),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,p),Int(Times(u,Power(Plus(C1,Times(d,x,Power(c,-1))),p),Power(Plus(C1,Times(a,x)),Times(C1D2,n)),Power(Power(Plus(C1,Times(CN1,a,x)),Times(C1D2,n)),-1)),x)),And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),Sqr(c)),Negate(Sqr(d))))),Or(IntegerQ(p),PositiveQ(c))))),
ISetDelayed(Int(Times(u_DEFAULT,Power(Plus(c_,Times(d_DEFAULT,x_)),p_DEFAULT),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Int(Times(u,Power(Plus(c,Times(d,x)),p),Power(Plus(C1,Times(a,x)),Times(C1D2,n)),Power(Power(Plus(C1,Times(CN1,a,x)),Times(C1D2,n)),-1)),x),And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),Sqr(c)),Negate(Sqr(d))))),Not(Or(IntegerQ(p),PositiveQ(c)))))),
ISetDelayed(Int(Times(u_DEFAULT,Power(Plus(c_,Times(d_DEFAULT,Power(x_,-1))),p_DEFAULT),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(d,p),Int(Times(u,Power(Plus(C1,Times(c,x,Power(d,-1))),p),Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Power(x,p),-1)),x)),And(And(FreeQ(List(a,c,d,n),x),ZeroQ(Plus(Sqr(c),Times(CN1,Sqr(a),Sqr(d))))),IntegerQ(p)))),
ISetDelayed(Int(Times(u_DEFAULT,Power(Plus(c_,Times(d_DEFAULT,Power(x_,-1))),p_),Power(E,Times(n_,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(CN1,Times(C1D2,n)),Power(c,p),Int(Times(u,Power(Plus(C1,Times(d,Power(Times(c,x),-1))),p),Power(Plus(C1,Power(Times(a,x),-1)),Times(C1D2,n)),Power(Power(Plus(C1,Negate(Power(Times(a,x),-1))),Times(C1D2,n)),-1)),x)),And(And(And(And(FreeQ(List(a,c,d,p),x),ZeroQ(Plus(Sqr(c),Times(CN1,Sqr(a),Sqr(d))))),Not(IntegerQ(p))),IntegerQ(Times(C1D2,n))),PositiveQ(c)))),
ISetDelayed(Int(Times(u_DEFAULT,Power(Plus(c_,Times(d_DEFAULT,Power(x_,-1))),p_),Power(E,Times(n_,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Int(Times(u,Power(Plus(c,Times(d,Power(x,-1))),p),Power(Plus(C1,Times(a,x)),Times(C1D2,n)),Power(Power(Plus(C1,Times(CN1,a,x)),Times(C1D2,n)),-1)),x),And(And(And(And(FreeQ(List(a,c,d,p),x),ZeroQ(Plus(Sqr(c),Times(CN1,Sqr(a),Sqr(d))))),Not(IntegerQ(p))),IntegerQ(Times(C1D2,n))),Not(PositiveQ(c))))),
ISetDelayed(Int(Times(u_DEFAULT,Power(Plus(c_,Times(d_DEFAULT,Power(x_,-1))),p_),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(x,p),Power(Plus(c,Times(d,Power(x,-1))),p),Power(Power(Plus(C1,Times(c,x,Power(d,-1))),p),-1),Int(Times(u,Power(Plus(C1,Times(c,x,Power(d,-1))),p),Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Power(x,p),-1)),x)),And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Sqr(c),Times(CN1,Sqr(a),Sqr(d))))),Not(IntegerQ(p))))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),-1),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Times(a,c,n),-1)),And(And(FreeQ(List(a,c,d,n),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Not(IntegerQ(Times(C1D2,n)))))),
ISetDelayed(Int(Times(Power(Plus(C1,Times(d_DEFAULT,Sqr(x_))),CN1D2),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Int(Power(Plus(C1,Times(CN1,a,n,x)),-1),x),And(And(FreeQ(List(a,d,n),x),ZeroQ(Plus(d,Sqr(a)))),ZeroQ(Plus(Sqr(n),Negate(C1)))))),
ISetDelayed(Int(Times(Power(Plus(c_DEFAULT,Times(d_DEFAULT,Sqr(x_))),CN1D2),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Sqrt(Plus(C1,Times(CN1,Sqr(a),Sqr(x)))),Power(Plus(c,Times(d,Sqr(x))),CN1D2),Int(Times(Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Plus(C1,Times(CN1,Sqr(a),Sqr(x))),CN1D2)),x)),And(And(And(FreeQ(List(a,c,d,n),x),ZeroQ(Plus(Times(Sqr(a),c),d))),ZeroQ(Plus(Sqr(n),Negate(C1)))),NonzeroQ(Plus(c,Negate(C1)))))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_DEFAULT),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Plus(n,Times(C2,a,p,x)),Power(Plus(c,Times(d,Sqr(x))),p),Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Times(C2,a,p,Plus(Times(C2,p),C1)),-1)),And(And(And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),ZeroQ(Plus(Sqr(n),Times(CN1,C4,Sqr(p))))),NonzeroQ(Plus(p,C1D2))),Not(IntegerQ(n))))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),QQ(-3L,2L)),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,QQ(-3L,2L)),Int(Power(Times(Plus(C1,Times(a,n,x)),Sqr(Plus(C1,Times(CN1,a,n,x)))),-1),x)),And(And(And(FreeQ(List(a,c,d),x),ZeroQ(Plus(Times(Sqr(a),c),d))),ZeroQ(Plus(Sqr(n),Negate(C1)))),PositiveQ(c)))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),QQ(-3L,2L)),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Sqrt(Plus(C1,Times(CN1,Sqr(a),Sqr(x)))),Power(Times(c,Sqrt(Plus(c,Times(d,Sqr(x))))),-1),Int(Times(Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Plus(C1,Times(CN1,Sqr(a),Sqr(x))),QQ(-3L,2L))),x)),And(And(And(FreeQ(List(a,c,d),x),ZeroQ(Plus(Times(Sqr(a),c),d))),ZeroQ(Plus(Sqr(n),Negate(C1)))),Not(PositiveQ(c))))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),QQ(-3L,2L)),Power(E,Times(n_,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Plus(n,Times(CN1,a,x)),Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Times(a,c,Plus(Sqr(n),Negate(C1)),Sqrt(Plus(c,Times(d,Sqr(x))))),-1)),And(And(And(FreeQ(List(a,c,d,n),x),ZeroQ(Plus(Times(Sqr(a),c),d))),NonzeroQ(Plus(Sqr(n),Negate(C9)))),NonzeroQ(Plus(Sqr(n),Negate(C1)))))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_),Power(E,Times(n_,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Plus(Times(Plus(n,Times(C2,a,Plus(p,C1),x)),Power(Plus(c,Times(d,Sqr(x))),Plus(p,C1)),Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Times(a,c,Plus(Sqr(n),Times(CN1,C4,Sqr(Plus(p,C1))))),-1)),Times(CN1,C2,Plus(p,C1),Plus(Times(C2,p),C3),Power(Times(c,Plus(Sqr(n),Times(CN1,C4,Sqr(Plus(p,C1))))),-1),Int(Times(Power(Plus(c,Times(d,Sqr(x))),Plus(p,C1)),Power(E,Times(n,ArcTanh(Times(a,x))))),x))),And(And(And(And(And(And(And(FreeQ(List(a,c,d,n),x),ZeroQ(Plus(Times(Sqr(a),c),d))),NonzeroQ(Plus(Sqr(n),Times(CN1,C4,Sqr(p))))),RationalQ(p)),Less(p,CN1)),Unequal(p,QQ(-3L,2L))),NonzeroQ(Plus(Sqr(n),Times(CN1,C4,Sqr(Plus(p,C1)))))),Not(IntegerQ(n))))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_DEFAULT),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,p),Int(Times(Power(Plus(C1,Times(CN1,Sqr(a),Sqr(x))),Plus(p,Times(CN1,C1D2,n))),Power(Plus(C1,Times(a,x)),n)),x)),And(And(And(FreeQ(List(a,c,d,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Or(IntegerQ(p),PositiveQ(c))),OddQ(n)))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_DEFAULT),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,p),Int(Times(Power(Plus(C1,Times(CN1,a,x)),Plus(p,Times(CN1,C1D2,n))),Power(Plus(C1,Times(a,x)),Plus(p,Times(C1D2,n)))),x)),And(And(And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Or(IntegerQ(p),PositiveQ(c))),Not(OddQ(n))),Or(Or(RationalQ(n,p),PositiveIntegerQ(Plus(p,Times(CN1,C1D2,n)))),PositiveIntegerQ(Plus(p,Times(C1D2,n))))))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_),Power(E,Times(n_,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,Times(C1D2,n)),Int(Times(Power(Plus(c,Times(d,Sqr(x))),Plus(p,Times(CN1,C1D2,n))),Power(Plus(C1,Times(a,x)),n)),x)),And(And(And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Not(Or(IntegerQ(p),PositiveQ(c)))),EvenQ(n)),RationalQ(p)))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,Plus(p,Negate(C1D2))),Sqrt(Plus(c,Times(d,Sqr(x)))),Power(Plus(C1,Times(CN1,Sqr(a),Sqr(x))),CN1D2),Int(Times(Power(Plus(C1,Times(CN1,Sqr(a),Sqr(x))),p),Power(E,Times(n,ArcTanh(Times(a,x))))),x)),And(And(And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Not(PositiveQ(c))),PositiveIntegerQ(Plus(p,C1D2))),RationalQ(n)))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,Plus(p,C1D2)),Sqrt(Plus(C1,Times(CN1,Sqr(a),Sqr(x)))),Power(Plus(c,Times(d,Sqr(x))),CN1D2),Int(Times(Power(Plus(C1,Times(CN1,Sqr(a),Sqr(x))),p),Power(E,Times(n,ArcTanh(Times(a,x))))),x)),And(And(And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Not(PositiveQ(c))),NegativeIntegerQ(Plus(p,Negate(C1D2)))),RationalQ(n)))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(Plus(c,Times(d,Sqr(x))),p),Power(Power(Plus(C1,Times(CN1,Sqr(a),Sqr(x))),p),-1),Int(Times(Power(Plus(C1,Times(CN1,Sqr(a),Sqr(x))),p),Power(E,Times(n,ArcTanh(Times(a,x))))),x)),And(And(And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Not(Or(IntegerQ(p),PositiveQ(c)))),Not(IntegerQ(Plus(p,C1D2)))),Or(Or(RationalQ(n,p),PositiveIntegerQ(Plus(p,Times(CN1,C1D2,n)))),PositiveIntegerQ(Plus(p,Times(C1D2,n))))))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_DEFAULT),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(Plus(c,Times(d,Sqr(x))),Plus(p,C1)),Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Times(C2,a,c,n),-1),Power(Plus(C1,Power(E,Times(n,Power(Plus(p,C1),-1),ArcTanh(Times(a,x))))),Times(C2,Plus(p,C1))),Hypergeometric2F1(Times(C2,Plus(p,C1)),Times(C2,Plus(p,C1)),Plus(Times(C2,p),C3),Negate(Power(E,Times(n,Power(Plus(p,C1),-1),ArcTanh(Times(a,x))))))),And(And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),ZeroQ(Plus(Sqr(n),Times(CN1,C4,Sqr(Plus(p,C1)))))),Not(IntegerQ(Times(C2,p)))))),
ISetDelayed(Int(Times(Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_DEFAULT),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(C4,Plus(p,C1)),Power(Plus(c,Times(d,Sqr(x))),Plus(p,C1)),Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Times(a,c,Plus(n,Times(CN1,C2,Plus(p,C1)))),-1),Power(Power(Plus(C1,Times(a,x)),-1),Times(C2,Plus(p,C1))),Hypergeometric2F1(Plus(p,Times(CN1,C1D2,n),C1),Times(C2,Plus(p,C1)),Plus(p,Times(CN1,C1D2,n),C2),Negate(Power(E,Times(CN2,ArcTanh(Times(a,x))))))),And(And(And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),NonzeroQ(Plus(Sqr(n),Times(CN1,C4,Sqr(Plus(p,C1)))))),Not(NegativeIntegerQ(Plus(Times(C2,p),C1)))),Not(IntegerQ(Plus(p,Times(CN1,C1D2,n))))))),
ISetDelayed(Int(Times(x_,Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),QQ(-3L,2L)),Power(E,Times(n_,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(CN1,Plus(C1,Times(CN1,a,n,x)),Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Times(Sqr(a),c,Plus(Sqr(n),Negate(C1)),Sqrt(Plus(c,Times(d,Sqr(x))))),-1)),And(And(FreeQ(List(a,c,d,n),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Not(IntegerQ(n))))),
ISetDelayed(Int(Times(x_,Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Plus(Times(Plus(Times(C2,Plus(p,C1)),Times(a,n,x)),Power(Plus(c,Times(d,Sqr(x))),Plus(p,C1)),Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Times(Sqr(a),c,Plus(Sqr(n),Times(CN1,C4,Sqr(Plus(p,C1))))),-1)),Times(CN1,n,Plus(Times(C2,p),C3),Power(Times(a,c,Plus(Sqr(n),Times(CN1,C4,Sqr(Plus(p,C1))))),-1),Int(Times(Power(Plus(c,Times(d,Sqr(x))),Plus(p,C1)),Power(E,Times(n,ArcTanh(Times(a,x))))),x))),And(And(And(And(And(And(FreeQ(List(a,c,d,n),x),ZeroQ(Plus(Times(Sqr(a),c),d))),RationalQ(p)),LessEqual(p,CN1)),Unequal(p,QQ(-3L,2L))),NonzeroQ(Plus(Sqr(n),Times(CN1,C4,Sqr(Plus(p,C1)))))),Not(IntegerQ(n))))),
ISetDelayed(Int(Times(Sqr(x_),Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_DEFAULT),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(CN1,Plus(n,Times(C2,Plus(p,C1),a,x)),Power(Plus(c,Times(d,Sqr(x))),Plus(p,C1)),Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Times(Power(a,3),c,Sqr(n),Plus(Sqr(n),Negate(C1))),-1)),And(And(And(FreeQ(List(a,c,d,n),x),ZeroQ(Plus(Times(Sqr(a),c),d))),ZeroQ(Plus(Sqr(n),Times(C2,Plus(p,C1))))),Not(IntegerQ(n))))),
ISetDelayed(Int(Times(Sqr(x_),Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Plus(Times(Plus(n,Times(C2,Plus(p,C1),a,x)),Power(Plus(c,Times(d,Sqr(x))),Plus(p,C1)),Power(E,Times(n,ArcTanh(Times(a,x)))),Power(Times(Power(a,3),c,Plus(Sqr(n),Times(CN1,C4,Sqr(Plus(p,C1))))),-1)),Times(CN1,Plus(Sqr(n),Times(C2,Plus(p,C1))),Power(Times(Sqr(a),c,Plus(Sqr(n),Times(CN1,C4,Sqr(Plus(p,C1))))),-1),Int(Times(Power(Plus(c,Times(d,Sqr(x))),Plus(p,C1)),Power(E,Times(n,ArcTanh(Times(a,x))))),x))),And(And(And(And(And(And(FreeQ(List(a,c,d,n),x),ZeroQ(Plus(Times(Sqr(a),c),d))),RationalQ(p)),LessEqual(p,CN1)),NonzeroQ(Plus(Sqr(n),Times(C2,Plus(p,C1))))),NonzeroQ(Plus(Sqr(n),Times(CN1,C4,Sqr(Plus(p,C1)))))),Not(IntegerQ(n))))),
ISetDelayed(Int(Times(Power(x_,m_DEFAULT),Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,p),Power(Power(a,Plus(m,C1)),-1),Subst(Int(Times(Power(E,Times(n,x)),Power(Tanh(x),Plus(m,Times(C2,Plus(p,C1)))),Power(Power(Sinh(x),Times(C2,Plus(p,C1))),-1)),x),x,ArcTanh(Times(a,x)))),And(And(And(And(And(And(FreeQ(List(a,c,d,n),x),ZeroQ(Plus(Times(Sqr(a),c),d))),IntegerQ(m)),RationalQ(p)),LessEqual(LessEqual(C3,m),Times(CN2,Plus(p,C1)))),IntegerQ(p)),Not(IntegerQ(n))))),
ISetDelayed(Int(Times(Power(x_,m_DEFAULT),Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_DEFAULT),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,p),Int(Times(Power(x,m),Power(Plus(C1,Times(CN1,a,x)),Plus(p,Times(CN1,C1D2,n))),Power(Plus(C1,Times(a,x)),Plus(p,Times(C1D2,n)))),x)),And(And(And(And(And(FreeQ(List(a,c,d,m,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Or(IntegerQ(p),PositiveQ(c))),ZeroQ(Plus(Sqr(n),Negate(C1)))),Or(Not(RationalQ(m)),Not(RationalQ(p)))),Not(IntegerQ(Plus(p,Times(CN1,C1D2,n))))))),
ISetDelayed(Int(Times(Power(x_,m_DEFAULT),Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_DEFAULT),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,p),Int(Times(Power(x,m),Power(Plus(C1,Times(CN1,Sqr(a),Sqr(x))),Plus(p,Times(CN1,C1D2,n))),Power(Plus(C1,Times(a,x)),n)),x)),And(And(And(And(And(FreeQ(List(a,c,d,m,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Or(IntegerQ(p),PositiveQ(c))),OddQ(n)),Or(Or(Not(RationalQ(m)),Not(RationalQ(p))),And(ZeroQ(Plus(n,Negate(C1))),NonzeroQ(Plus(p,C1))))),Not(IntegerQ(Plus(p,Times(CN1,C1D2,n))))))),
ISetDelayed(Int(Times(Power(x_,m_DEFAULT),Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_),Power(E,Times(n_,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,Times(C1D2,n)),Int(Times(Power(x,m),Power(Plus(c,Times(d,Sqr(x))),Plus(p,Times(CN1,C1D2,n))),Power(Plus(C1,Times(a,x)),n)),x)),And(And(And(And(FreeQ(List(a,c,d,m,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Not(Or(IntegerQ(p),PositiveQ(c)))),IntegerQ(Times(C1D2,n))),Or(ZeroQ(Plus(m,Negate(C1))),Not(IntegerQ(Plus(p,C1D2))))))),
ISetDelayed(Int(Times(u_,Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_DEFAULT),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,p),Int(Times(u,Power(Plus(C1,Times(CN1,a,x)),Plus(p,Times(CN1,C1D2,n))),Power(Plus(C1,Times(a,x)),Plus(p,Times(C1D2,n)))),x)),And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Or(IntegerQ(p),PositiveQ(c))))),
ISetDelayed(Int(Times(u_,Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_),Power(E,Times(n_,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,Plus(p,Negate(C1D2))),Sqrt(Plus(c,Times(d,Sqr(x)))),Power(Times(Sqrt(Plus(C1,Times(CN1,a,x))),Sqrt(Plus(C1,Times(a,x)))),-1),Int(Times(u,Power(Plus(C1,Times(CN1,a,x)),Plus(p,Times(CN1,C1D2,n))),Power(Plus(C1,Times(a,x)),Plus(p,Times(C1D2,n)))),x)),And(And(And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Not(PositiveQ(c))),IntegerQ(Times(C1D2,n))),PositiveIntegerQ(Plus(p,C1D2))))),
ISetDelayed(Int(Times(u_,Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_),Power(E,Times(n_,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,Plus(p,C1D2)),Sqrt(Plus(C1,Times(CN1,a,x))),Sqrt(Plus(C1,Times(a,x))),Power(Plus(c,Times(d,Sqr(x))),CN1D2),Int(Times(u,Power(Plus(C1,Times(CN1,a,x)),Plus(p,Times(CN1,C1D2,n))),Power(Plus(C1,Times(a,x)),Plus(p,Times(C1D2,n)))),x)),And(And(And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Not(PositiveQ(c))),IntegerQ(Times(C1D2,n))),NegativeIntegerQ(Plus(p,Negate(C1D2)))))),
ISetDelayed(Int(Times(u_,Power(Plus(c_,Times(d_DEFAULT,Sqr(x_))),p_),Power(E,Times(n_DEFAULT,ArcTanh(Times(a_DEFAULT,x_))))),x_Symbol),
Condition(Times(Power(c,Plus(p,Negate(C1D2))),Sqrt(Plus(c,Times(d,Sqr(x)))),Power(Plus(C1,Times(CN1,Sqr(a),Sqr(x))),CN1D2),Int(Times(u,Power(Plus(C1,Times(CN1,Sqr(a),Sqr(x))),p),Power(E,Times(n,ArcTanh(Times(a,x))))),x)),And(And(And(And(FreeQ(List(a,c,d,n,p),x),ZeroQ(Plus(Times(Sqr(a),c),d))),Not(PositiveQ(c))),Not(IntegerQ(Times(C1D2,n)))),PositiveIntegerQ(Plus(p,C1D2)))))
);
}
| 27,089
|
Java
|
.java
| 134
| 199.246269
| 658
| 0.678206
|
andryr/symja
| 2
| 2
| 0
|
LGPL-3.0
|
9/5/2024, 12:05:04 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 27,089
|
1,391,491
|
TagsFilter.java
|
europeana_REPOX/gui/src/main/java/harvesterUI/client/panels/browse/TagsFilter.java
|
package harvesterUI.client.panels.browse;
import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style;
import com.extjs.gxt.ui.client.event.CheckChangedEvent;
import com.extjs.gxt.ui.client.event.CheckChangedListener;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.menu.Menu;
import com.extjs.gxt.ui.client.widget.menu.SeparatorMenuItem;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.google.gwt.user.client.rpc.AsyncCallback;
import harvesterUI.client.HarvesterUI;
import harvesterUI.client.core.AppEvents;
import harvesterUI.client.models.FilterButton;
import harvesterUI.client.servlets.dataManagement.FilterServiceAsync;
import harvesterUI.client.util.ServerExceptionDialog;
import harvesterUI.shared.filters.FilterAttribute;
import harvesterUI.shared.filters.FilterQuery;
import harvesterUI.shared.filters.FilterType;
import java.util.ArrayList;
import java.util.List;
/**
* Created to REPOX.
* User: Edmundo
* Date: 09-03-2011
* Time: 11:50
*/
public class TagsFilter extends FilterButton {
private TreePanel<FilterAttribute> tagsList;
private TreePanel<FilterAttribute> checkedTagsList;
private boolean canCheck;
public TagsFilter(BrowseFilterPanel browseFilterPanel) {
super(browseFilterPanel);
setText("Tags");
Menu rangeMenu = new Menu();
rangeMenu.add(createCheckedTagsList());
rangeMenu.add(new SeparatorMenuItem());
rangeMenu.add(createTagsList());
setMenu(rangeMenu);
}
private TreePanel createTagsList(){
TreeStore<FilterAttribute> countryListStore = new TreeStore<FilterAttribute>();
tagsList = new TreePanel<FilterAttribute>(countryListStore);
tagsList.setCheckable(true);
tagsList.setDisplayProperty("name");
countryListStore.sort("name", Style.SortDir.ASC);
tagsList.addCheckListener(new CheckChangedListener<FilterAttribute>() {
@Override
public void checkChanged(CheckChangedEvent<FilterAttribute> event) {
FilterAttribute firstCheck = tagsList.getCheckedSelection().get(0);
tagsList.getStore().remove(firstCheck);
checkedTagsList.getStore().add(firstCheck, false);
canCheck = false;
checkedTagsList.setChecked(firstCheck, true);
updateAttributeInfo(checkedTagsList.getCheckedSelection());
((BrowseFilterPanel)Registry.get("browseFilterPanel")).autoSelectFilter(getFilterButton());
// Grid isn't filtered according to filters, so enable the filter button
((Button) Registry.get("startFilterButton")).enable();
}
});
return tagsList;
}
private TreePanel createCheckedTagsList(){
TreeStore<FilterAttribute> checkedTagsListStore = new TreeStore<FilterAttribute>();
checkedTagsList = new TreePanel<FilterAttribute>(checkedTagsListStore);
checkedTagsList.setCheckable(true);
checkedTagsList.setDisplayProperty("name");
checkedTagsListStore.sort("name", Style.SortDir.ASC);
checkedTagsList.addCheckListener(new CheckChangedListener<FilterAttribute>() {
@Override
public void checkChanged(CheckChangedEvent<FilterAttribute> event) {
// variable to control the immediate check listener effect done when an item is added to this list
if (canCheck) {
removeNonCheckedItems();
updateAttributeInfo(checkedTagsList.getCheckedSelection());
}
canCheck = true;
// Grid isn't filtered according to filters, so enable the filter button
((Button) Registry.get("startFilterButton")).enable();
}
});
return checkedTagsList;
}
public void updateFilterData(){
final TreeStore<FilterAttribute> saveChecked = new TreeStore<FilterAttribute>();
saveChecked.add(checkedTagsList.getStore().getModels(),false);
AsyncCallback<List<FilterAttribute>> callback = new AsyncCallback<List<FilterAttribute>>() {
public void onFailure(Throwable caught) {
new ServerExceptionDialog("Failed to get response from server",caught.getMessage()).show();
}
public void onSuccess(List<FilterAttribute> result) {
Menu rangeMenu = new Menu();
rangeMenu.add(createCheckedTagsList());
rangeMenu.add(new SeparatorMenuItem());
rangeMenu.add(createTagsList());
setMenu(rangeMenu);
tagsList.getStore().add(result,false);
for(FilterAttribute filterAttribute : tagsList.getStore().getModels()) {
for(FilterAttribute savedAttribute : saveChecked.getModels()) {
if(filterAttribute.getValue().equals(savedAttribute.getValue())) {
tagsList.getStore().remove(filterAttribute);
checkedTagsList.getStore().add(filterAttribute,false);
checkedTagsList.setChecked(filterAttribute, true);
}
}
}
updateAttributeInfo(checkedTagsList.getCheckedSelection());
}
};
List<FilterQuery> filterQueries = browseFilterPanel.getAllQueries();
((FilterServiceAsync)Registry.get(HarvesterUI.FILTER_SERVICE)).getTags(filterQueries,HarvesterUI.UTIL_MANAGER.getLoggedUserName(),callback);
}
private void removeNonCheckedItems(){
List<FilterAttribute> valuesToRemove = new ArrayList<FilterAttribute>();
for(FilterAttribute item : checkedTagsList.getStore().getModels()){
boolean result = false;
if(checkedTagsList.getCheckedSelection().size() <= 0){
tagsList.getStore().add(item,false);
valuesToRemove.add(item);
}else{
for(FilterAttribute checkedItem : checkedTagsList.getCheckedSelection()){
if(checkedItem.getValue().equals(item.getValue()))
result = true;
}
if(!result){
tagsList.getStore().add(item,false);
valuesToRemove.add(item);
}
}
}
for(FilterAttribute item : valuesToRemove){
checkedTagsList.getStore().remove(item);
}
}
private void updateAttributeInfo(List<FilterAttribute> selection){
dataFilter.setRangeInfo(createInfoString(selection));
if(selection.size() == 0 && browseFilterPanel.getAttributesSelected().contains(dataFilter)){
browseFilterPanel.deselectFilter(dataFilter);
Dispatcher.forwardEvent(AppEvents.LoadMainData);
return;
}
// Update the attribute info value written on the store
if(browseFilterPanel.getAttributesListStore().contains(dataFilter))
browseFilterPanel.getAttributesListStore().update(dataFilter);
else if(browseFilterPanel.getAttributesSelected().contains(dataFilter)){
browseFilterPanel.getAttributesListStore().update(dataFilter);
if(dataFilter.getChecked() == 1)
Dispatcher.get().dispatch(AppEvents.LoadMainData);
}
}
private String createInfoString(List<FilterAttribute> selection){
String result = "";
if(selection.size() > 0){
if(selection.size() > 1)
result = selection.size() + " selected";
else{
for(FilterAttribute country : selection){
result += country.getValue() + ";";
}
}
}
return result;
}
public FilterQuery getFilterQuery(){
List<String> values = new ArrayList<String>();
for(FilterAttribute filterAttribute : checkedTagsList.getCheckedSelection()){
values.add(filterAttribute.getValue());
}
return new FilterQuery(FilterType.TAG,values);
}
}
| 8,297
|
Java
|
.java
| 172
| 37.459302
| 148
| 0.660529
|
europeana/REPOX
| 20
| 12
| 2
|
EUPL-1.2
|
9/4/2024, 7:48:09 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 8,297
|
2,589,219
|
VN_Double02.java
|
JPortal-system_system/jdk12-06222165c35f/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.jtt/src/org/graalvm/compiler/jtt/optimize/VN_Double02.java
|
/*
* Copyright (c) 2009, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.jtt.optimize;
import org.junit.Test;
import org.graalvm.compiler.jtt.JTTTest;
/*
* Tests optimization of float operations.
*/
public class VN_Double02 extends JTTTest {
private static boolean cond = true;
public static double test(double arg) {
if (arg == 0) {
return add(arg + 10);
}
if (arg == 1) {
return sub(arg + 10);
}
if (arg == 2) {
return mul(arg + 10);
}
if (arg == 3) {
return div(arg + 10);
}
return 0;
}
public static double add(double x) {
double c = 1.0d;
double t = x + c;
if (cond) {
double u = x + c;
return t + u;
}
return 1;
}
public static double sub(double x) {
double c = 1.0d;
double t = x - c;
if (cond) {
double u = x - c;
return t - u;
}
return 1;
}
public static double mul(double x) {
double c = 1.0d;
double t = x * c;
if (cond) {
double u = x * c;
return t * u;
}
return 1.0d;
}
public static double div(double x) {
double c = 1.0d;
double t = x / c;
if (cond) {
double u = x / c;
return t / u;
}
return 1.0d;
}
@Test
public void run0() throws Throwable {
runTest("test", 0d);
}
@Test
public void run1() throws Throwable {
runTest("test", 1d);
}
@Test
public void run2() throws Throwable {
runTest("test", 2d);
}
@Test
public void run3() throws Throwable {
runTest("test", 3d);
}
}
| 2,817
|
Java
|
.java
| 98
| 22.244898
| 79
| 0.588235
|
JPortal-system/system
| 7
| 2
| 1
|
GPL-3.0
|
9/4/2024, 9:49:36 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 2,817
|
3,457,466
|
PLA_ListView.java
|
pengqinping_project_android/WaterfallStream/PinterestLikeAdapterView-master/src/com/huewu/pla/lib/internal/PLA_ListView.java
|
/*
* Copyright (C) 2006 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.huewu.pla.lib.internal;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.widget.ListAdapter;
import android.widget.WrapperListAdapter;
import com.huewu.pla.smaple.R;
/*
* Implementation Notes:
*
* Some terminology:
*
* index - index of the items that are currently visible
* position - index of the items in the cursor
*/
/**
* A view that shows items in a vertically scrolling list. The items
* come from the {@link ListAdapter} associated with this view.
*
* <p>See the <a href="{@docRoot}resources/tutorials/views/hello-listview.html">List View
* tutorial</a>.</p>
*
* @attr ref android.R.styleable#ListView_entries
* @attr ref android.R.styleable#ListView_divider
* @attr ref android.R.styleable#ListView_dividerHeight
* @attr ref android.R.styleable#ListView_choiceMode
* @attr ref android.R.styleable#ListView_headerDividersEnabled
* @attr ref android.R.styleable#ListView_footerDividersEnabled
*/
public class PLA_ListView extends PLA_AbsListView {
//TODO Not Supproted Features
//Entry from XML.
//Choice Mode & Item Selection.
//Filter
//Handle Key Event & Arrow Scrolling..
//Can't find Footer & Header findBy methods...
/**
* Used to indicate a no preference for a position type.
*/
static final int NO_POSITION = -1;
/**
* When arrow scrolling, ListView will never scroll more than this factor
* times the height of the list.
*/
private static final float MAX_SCROLL_FACTOR = 0.33f;
/**
* A class that represents a fixed view in a list, for example a header at the top
* or a footer at the bottom.
*/
public class FixedViewInfo {
/** The view to add to the list */
public View view;
/** The data backing the view. This is returned from {@link ListAdapter#getItem(int)}. */
public Object data;
/** <code>true</code> if the fixed view should be selectable in the list */
public boolean isSelectable;
}
private ArrayList<FixedViewInfo> mHeaderViewInfos = new ArrayList<PLA_ListView.FixedViewInfo>();
private ArrayList<FixedViewInfo> mFooterViewInfos = new ArrayList<PLA_ListView.FixedViewInfo>();
Drawable mDivider;
int mDividerHeight;
Drawable mOverScrollHeader;
Drawable mOverScrollFooter;
private boolean mIsCacheColorOpaque;
private boolean mDividerIsOpaque;
private boolean mClipDivider;
private boolean mHeaderDividersEnabled;
private boolean mFooterDividersEnabled;
private boolean mAreAllItemsSelectable = true;
private boolean mItemsCanFocus = false;
// used for temporary calculations.
private final Rect mTempRect = new Rect();
private Paint mDividerPaint;
public PLA_ListView(Context context) {
this(context, null);
}
public PLA_ListView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.listViewStyle);
}
public PLA_ListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.ListView, defStyle, 0);
// final Drawable d = a.getDrawable(android.R.drawable.divider_horizontal_bright);
// if (d != null) {
// // If a divider is specified use its intrinsic height for divider height
// setDivider(d);
// }
final Drawable osHeader = a.getDrawable(
R.styleable.ListView_overScrollHeader);
if (osHeader != null) {
setOverscrollHeader(osHeader);
}
final Drawable osFooter = a.getDrawable(
R.styleable.ListView_overScrollFooter);
if (osFooter != null) {
setOverscrollFooter(osFooter);
}
// Use the height specified, zero being the default
final int dividerHeight = a.getDimensionPixelSize(
R.styleable.ListView_dividerHeight, 0);
if (dividerHeight != 0) {
setDividerHeight(dividerHeight);
}
mHeaderDividersEnabled = a.getBoolean(R.styleable.ListView_headerDividersEnabled, true);
mFooterDividersEnabled = a.getBoolean(R.styleable.ListView_footerDividersEnabled, true);
a.recycle();
}
/**
* @return The maximum amount a list view will scroll in response to
* an arrow event.
*/
public int getMaxScrollAmount() {
// return (int) (MAX_SCROLL_FACTOR * (mBottom - mTop));
return (int) (MAX_SCROLL_FACTOR * (getBottom() - getTop()));
}
/**
* Make sure views are touching the top or bottom edge, as appropriate for
* our gravity
*/
private void adjustViewsUpOrDown() {
final int childCount = getChildCount();
int delta;
if (childCount > 0) {
//View child;
if (!mStackFromBottom) {
// Uh-oh -- we came up short. Slide all views up to make them
// align with the top
final int firstTop = getScrollChildTop();
//child = getChildAt(0);
//delta = child.getTop() - mListPadding.top;
delta = firstTop - mListPadding.top;
if (mFirstPosition != 0) {
// It's OK to have some space above the first item if it is
// part of the vertical spacing
delta -= mDividerHeight;
}
if (delta < 0) {
// We only are looking to see if we are too low, not too high
delta = 0;
}
} else {
// we are too high, slide all views down to align with bottom
//child = getChildAt(childCount - 1);
//delta = child.getBottom() - (getHeight() - mListPadding.bottom);
final int lastBottom = getScrollChildBottom();
delta = lastBottom - (getHeight() - mListPadding.bottom);
if (mFirstPosition + childCount < mItemCount) {
// It's OK to have some space below the last item if it is
// part of the vertical spacing
delta += mDividerHeight;
}
if (delta > 0) {
delta = 0;
}
}
if (delta != 0) {
//offsetChildrenTopAndBottom(-delta);
tryOffsetChildrenTopAndBottom(-delta);
}
}
}
/**
* Add a fixed view to appear at the top of the list. If addHeaderView is
* called more than once, the views will appear in the order they were
* added. Views added using this call can take focus if they want.
* <p>
* NOTE: Call this before calling setAdapter. This is so ListView can wrap
* the supplied cursor with one that will also account for header and footer
* views.
*
* @param v The view to add.
* @param data Data to associate with this view
* @param isSelectable whether the item is selectable
*/
public void addHeaderView(View v, Object data, boolean isSelectable) {
if (mAdapter != null) {
throw new IllegalStateException(
"Cannot add header view to list -- setAdapter has already been called.");
}
FixedViewInfo info = new FixedViewInfo();
info.view = v;
info.data = data;
info.isSelectable = isSelectable;
mHeaderViewInfos.add(info);
}
/**
* Add a fixed view to appear at the top of the list. If addHeaderView is
* called more than once, the views will appear in the order they were
* added. Views added using this call can take focus if they want.
* <p>
* NOTE: Call this before calling setAdapter. This is so ListView can wrap
* the supplied cursor with one that will also account for header and footer
* views.
*
* @param v The view to add.
*/
public void addHeaderView(View v) {
addHeaderView(v, null, true);
}
@Override
public int getHeaderViewsCount() {
return mHeaderViewInfos.size();
}
/**
* check this view is fixed view(ex>Header & Footer) or not.
* @param v
* @return true if this is fixed view.
*/
public boolean isFixedView( View v ) {
{
//check header view.
ArrayList<FixedViewInfo> where = mHeaderViewInfos;
int len = where.size();
for (int i = 0; i < len; ++i) {
FixedViewInfo info = where.get(i);
if (info.view == v) {
return true;
}
}
}
{
//check footer view.
ArrayList<FixedViewInfo> where = mFooterViewInfos;
int len = where.size();
for (int i = 0; i < len; ++i) {
FixedViewInfo info = where.get(i);
if (info.view == v) {
return true;
}
}
}
return false;
}
/**
* Removes a previously-added header view.
*
* @param v The view to remove
* @return true if the view was removed, false if the view was not a header
* view
*/
public boolean removeHeaderView(View v) {
if (mHeaderViewInfos.size() > 0) {
boolean result = false;
if (((PLA_HeaderViewListAdapter) mAdapter).removeHeader(v)) {
mDataSetObserver.onChanged();
result = true;
}
removeFixedViewInfo(v, mHeaderViewInfos);
return result;
}
return false;
}
private void removeFixedViewInfo(View v, ArrayList<FixedViewInfo> where) {
int len = where.size();
for (int i = 0; i < len; ++i) {
FixedViewInfo info = where.get(i);
if (info.view == v) {
where.remove(i);
break;
}
}
}
/**
* Add a fixed view to appear at the bottom of the list. If addFooterView is
* called more than once, the views will appear in the order they were
* added. Views added using this call can take focus if they want.
* <p>
* NOTE: Call this before calling setAdapter. This is so ListView can wrap
* the supplied cursor with one that will also account for header and footer
* views.
*
* @param v The view to add.
* @param data Data to associate with this view
* @param isSelectable true if the footer view can be selected
*/
public void addFooterView(View v, Object data, boolean isSelectable) {
FixedViewInfo info = new FixedViewInfo();
info.view = v;
info.data = data;
info.isSelectable = isSelectable;
mFooterViewInfos.add(info);
// in the case of re-adding a footer view, or adding one later on,
// we need to notify the observer
if (mDataSetObserver != null) {
mDataSetObserver.onChanged();
}
}
/**
* Add a fixed view to appear at the bottom of the list. If addFooterView is called more
* than once, the views will appear in the order they were added. Views added using
* this call can take focus if they want.
* <p>NOTE: Call this before calling setAdapter. This is so ListView can wrap the supplied
* cursor with one that will also account for header and footer views.
*
*
* @param v The view to add.
*/
public void addFooterView(View v) {
addFooterView(v, null, true);
}
@Override
public int getFooterViewsCount() {
return mFooterViewInfos.size();
}
/**
* Removes a previously-added footer view.
*
* @param v The view to remove
* @return
* true if the view was removed, false if the view was not a footer view
*/
public boolean removeFooterView(View v) {
if (mFooterViewInfos.size() > 0) {
boolean result = false;
if (((PLA_HeaderViewListAdapter) mAdapter).removeFooter(v)) {
mDataSetObserver.onChanged();
result = true;
}
removeFixedViewInfo(v, mFooterViewInfos);
return result;
}
return false;
}
/**
* Returns the adapter currently in use in this ListView. The returned adapter
* might not be the same adapter passed to {@link #setAdapter(ListAdapter)} but
* might be a {@link WrapperListAdapter}.
*
* @return The adapter currently used to display data in this ListView.
*
* @see #setAdapter(ListAdapter)
*/
@Override
public ListAdapter getAdapter() {
return mAdapter;
}
/**
* Sets the data behind this ListView.
*
* The adapter passed to this method may be wrapped by a {@link WrapperListAdapter},
* depending on the ListView features currently in use. For instance, adding
* headers and/or footers will cause the adapter to be wrapped.
*
* @param adapter The ListAdapter which is responsible for maintaining the
* data backing this list and for producing a view to represent an
* item in that data set.
*
* @see #getAdapter()
*/
@Override
public void setAdapter(ListAdapter adapter) {
if (null != mAdapter) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
}
resetList();
mRecycler.clear();
if (mHeaderViewInfos.size() > 0|| mFooterViewInfos.size() > 0) {
mAdapter = new PLA_HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, adapter);
} else {
mAdapter = adapter;
}
mOldSelectedPosition = INVALID_POSITION;
mOldSelectedRowId = INVALID_ROW_ID;
if (mAdapter != null) {
mAreAllItemsSelectable = mAdapter.areAllItemsEnabled();
mOldItemCount = mItemCount;
mItemCount = mAdapter.getCount();
checkFocus();
mDataSetObserver = new AdapterDataSetObserver();
mAdapter.registerDataSetObserver(mDataSetObserver);
mRecycler.setViewTypeCount(mAdapter.getViewTypeCount());
} else {
mAreAllItemsSelectable = true;
checkFocus();
// Nothing selected
}
requestLayout();
}
@Override
public int getFirstVisiblePosition() {
return Math.max( 0, mFirstPosition - getHeaderViewsCount());
}
@Override
public int getLastVisiblePosition() {
return Math.min( mFirstPosition + getChildCount() - 1, mAdapter.getCount() - 1);
}
/**
* The list is empty. Clear everything out.
*/
@Override
void resetList() {
// The parent's resetList() will remove all views from the layout so we need to
// cleanup the state of our footers and headers
clearRecycledState(mHeaderViewInfos);
clearRecycledState(mFooterViewInfos);
super.resetList();
mLayoutMode = LAYOUT_NORMAL;
}
private void clearRecycledState(ArrayList<FixedViewInfo> infos) {
if (infos != null) {
final int count = infos.size();
for (int i = 0; i < count; i++) {
final View child = infos.get(i).view;
final LayoutParams p = (LayoutParams) child.getLayoutParams();
if (p != null) {
p.recycledHeaderFooter = false;
}
}
}
}
/**
* @return Whether the list needs to show the top fading edge
*/
private boolean showingTopFadingEdge() {
// final int listTop = mScrollY + mListPadding.top;
final int listTop = getScrollY() + mListPadding.top;
return (mFirstPosition > 0) || (getChildAt(0).getTop() > listTop);
}
/**
* @return Whether the list needs to show the bottom fading edge
*/
private boolean showingBottomFadingEdge() {
final int childCount = getChildCount();
final int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
final int lastVisiblePosition = mFirstPosition + childCount - 1;
// final int listBottom = mScrollY + getHeight() - mListPadding.bottom;
final int listBottom = getScrollY() + getHeight() - mListPadding.bottom;
return (lastVisiblePosition < mItemCount - 1)
|| (bottomOfBottomChild < listBottom);
}
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
int rectTopWithinChild = rect.top;
// offset so rect is in coordinates of the this view
rect.offset(child.getLeft(), child.getTop());
rect.offset(-child.getScrollX(), -child.getScrollY());
final int height = getHeight();
int listUnfadedTop = getScrollY();
int listUnfadedBottom = listUnfadedTop + height;
final int fadingEdge = getVerticalFadingEdgeLength();
if (showingTopFadingEdge()) {
// leave room for top fading edge as long as rect isn't at very top
if (rectTopWithinChild > fadingEdge) {
listUnfadedTop += fadingEdge;
}
}
int childCount = getChildCount();
int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
if (showingBottomFadingEdge()) {
// leave room for bottom fading edge as long as rect isn't at very bottom
if (rect.bottom < (bottomOfBottomChild - fadingEdge)) {
listUnfadedBottom -= fadingEdge;
}
}
int scrollYDelta = 0;
if (rect.bottom > listUnfadedBottom && rect.top > listUnfadedTop) {
// need to MOVE DOWN to get it in view: move down just enough so
// that the entire rectangle is in view (or at least the first
// screen size chunk).
if (rect.height() > height) {
// just enough to get screen size chunk on
scrollYDelta += (rect.top - listUnfadedTop);
} else {
// get entire rect at bottom of screen
scrollYDelta += (rect.bottom - listUnfadedBottom);
}
// make sure we aren't scrolling beyond the end of our children
int distanceToBottom = bottomOfBottomChild - listUnfadedBottom;
scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
} else if (rect.top < listUnfadedTop && rect.bottom < listUnfadedBottom) {
// need to MOVE UP to get it in view: move up just enough so that
// entire rectangle is in view (or at least the first screen
// size chunk of it).
if (rect.height() > height) {
// screen size chunk
scrollYDelta -= (listUnfadedBottom - rect.bottom);
} else {
// entire rect at top
scrollYDelta -= (listUnfadedTop - rect.top);
}
// make sure we aren't scrolling any further than the top our children
int top = getChildAt(0).getTop();
int deltaToTop = top - listUnfadedTop;
scrollYDelta = Math.max(scrollYDelta, deltaToTop);
}
final boolean scroll = scrollYDelta != 0;
if (scroll) {
scrollListItemsBy(-scrollYDelta);
positionSelector(child);
mSelectedTop = child.getTop();
invalidate();
}
return scroll;
}
/**
* override this method to manipulate the position of each item in list view.
* return item left position.
* @param pos
* @return pos's item left position.
*/
protected int getItemLeft(int pos) {
return mListPadding.left;
}
/**
* override this method to manipulate the position of each item in list view.
* return item's top position. (item will be added in down direction)
* @param pos
* @return value of pos's item top.
*/
protected int getItemTop(int pos) {
//just return the last itme's bottom position..
int count = getChildCount();
return count > 0 ? getChildAt(count - 1).getBottom() + mDividerHeight : getListPaddingTop();
}
/**
* override this method to manipulate the position of each item in list view.
* return item's bottom position. (item will be added in up direction)
* @param pos
* @return value of pos's item bottom.
*/
protected int getItemBottom(int pos) {
int count = getChildCount();
return count > 0 ? getChildAt(0).getTop() - mDividerHeight : getHeight() - getListPaddingBottom();
}
/**
* {@inheritDoc}
*/
@Override
protected void fillGap(boolean down) {
final int count = getChildCount();
if (down) {
fillDown(mFirstPosition + count, getItemTop(mFirstPosition + count));
onAdjustChildViews( down );
} else {
fillUp(mFirstPosition - 1, getItemBottom(mFirstPosition - 1));
onAdjustChildViews( down );
}
}
/**
* Fills the list from pos down to the end of the list view.
*
* @param pos The first position to put in the list
*
* @param nextTop The location where the top of the item associated with pos
* should be drawn
*
* @return The view that is currently selected, if it happens to be in the
* range that we draw.
*/
private View fillDown(int pos, int top) {
//int end = (mBottom - mTop) - mListPadding.bottom;
int end = (getBottom() - getTop()) - mListPadding.bottom;
int childTop = getFillChildBottom() + mDividerHeight;
while (childTop < end && pos < mItemCount) {
// is this the selected item?
makeAndAddView(pos, getItemTop(pos), true, false);
pos++;
childTop = getFillChildBottom() + mDividerHeight;
}
return null;
}
/**
* Fills the list from pos up to the top of the list view.
*
* @param pos The first position to put in the list
*
* @param nextBottom The location where the bottom of the item associated
* with pos should be drawn
*
* @return The view that is currently selected
*/
private View fillUp(int pos, int bottom) {
int end = mListPadding.top;
int childBottom = getFillChildTop();
while (childBottom > end && pos >= 0) {
// is this the selected item?
makeAndAddView(pos, getItemBottom(pos), false, false);
// nextBottom = child.getTop() - mDividerHeight;
pos--;
childBottom = getItemBottom(pos);
}
mFirstPosition = pos + 1;
return null;
}
/**
* Fills the list from top to bottom, starting with mFirstPosition
*
* @param nextTop The location where the top of the first item should be
* drawn
*
* @return The view that is currently selected
*/
private View fillFromTop(int nextTop) {
mFirstPosition = Math.min(mFirstPosition, -1);
mFirstPosition = Math.min(mFirstPosition, mItemCount - 1);
if (mFirstPosition < 0) {
mFirstPosition = 0;
}
return fillDown(mFirstPosition, nextTop);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Sets up mListPadding
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int childWidth = 0;
int childHeight = 0;
mItemCount = mAdapter == null ? 0 : mAdapter.getCount();
if (mItemCount > 0 && (widthMode == MeasureSpec.UNSPECIFIED ||
heightMode == MeasureSpec.UNSPECIFIED)) {
final View child = obtainView(0, mIsScrap);
measureScrapChild(child, 0, widthMeasureSpec);
childWidth = child.getMeasuredWidth();
childHeight = child.getMeasuredHeight();
if (recycleOnMeasure() && mRecycler.shouldRecycleViewType(
((LayoutParams) child.getLayoutParams()).viewType)) {
mRecycler.addScrapView(child);
}
}
if (widthMode == MeasureSpec.UNSPECIFIED) {
widthSize = mListPadding.left + mListPadding.right + childWidth +
getVerticalScrollbarWidth();
}
if (heightMode == MeasureSpec.UNSPECIFIED) {
heightSize = mListPadding.top + mListPadding.bottom + childHeight +
getVerticalFadingEdgeLength() * 2;
}
if (heightMode == MeasureSpec.AT_MOST) {
// TODO: after first layout we should maybe start at the first visible position, not 0
heightSize = measureHeightOfChildren(widthMeasureSpec, 0, NO_POSITION, heightSize, -1);
}
setMeasuredDimension(widthSize, heightSize);
mWidthMeasureSpec = widthMeasureSpec;
}
private void measureScrapChild(View child, int position, int widthMeasureSpec) {
LayoutParams p = (LayoutParams) child.getLayoutParams();
if (p == null) {
p = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 0);
child.setLayoutParams(p);
}
p.viewType = mAdapter.getItemViewType(position);
p.forceAdd = true;
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec,
mListPadding.left + mListPadding.right, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
/**
* @return True to recycle the views used to measure this ListView in
* UNSPECIFIED/AT_MOST modes, false otherwise.
* @hide
*/
@ViewDebug.ExportedProperty(category = "list")
protected boolean recycleOnMeasure() {
return true;
}
/**
* Measures the height of the given range of children (inclusive) and
* returns the height with this ListView's padding and divider heights
* included. If maxHeight is provided, the measuring will stop when the
* current height reaches maxHeight.
*
* @param widthMeasureSpec The width measure spec to be given to a child's
* {@link View#measure(int, int)}.
* @param startPosition The position of the first child to be shown.
* @param endPosition The (inclusive) position of the last child to be
* shown. Specify {@link #NO_POSITION} if the last child should be
* the last available child from the adapter.
* @param maxHeight The maximum height that will be returned (if all the
* children don't fit in this value, this value will be
* returned).
* @param disallowPartialChildPosition In general, whether the returned
* height should only contain entire children. This is more
* powerful--it is the first inclusive position at which partial
* children will not be allowed. Example: it looks nice to have
* at least 3 completely visible children, and in portrait this
* will most likely fit; but in landscape there could be times
* when even 2 children can not be completely shown, so a value
* of 2 (remember, inclusive) would be good (assuming
* startPosition is 0).
* @return The height of this ListView with the given children.
*/
final int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition,
final int maxHeight, int disallowPartialChildPosition) {
final ListAdapter adapter = mAdapter;
if (adapter == null) {
return mListPadding.top + mListPadding.bottom;
}
// Include the padding of the list
int returnedHeight = mListPadding.top + mListPadding.bottom;
final int dividerHeight = ((mDividerHeight > 0) && mDivider != null) ? mDividerHeight : 0;
// The previous height value that was less than maxHeight and contained
// no partial children
int prevHeightWithoutPartialChild = 0;
int i;
View child;
// mItemCount - 1 since endPosition parameter is inclusive
endPosition = (endPosition == NO_POSITION) ? adapter.getCount() - 1 : endPosition;
final PLA_AbsListView.RecycleBin recycleBin = mRecycler;
final boolean recyle = recycleOnMeasure();
final boolean[] isScrap = mIsScrap;
for (i = startPosition; i <= endPosition; ++i) {
child = obtainView(i, isScrap);
measureScrapChild(child, i, widthMeasureSpec);
if (i > 0) {
// Count the divider for all but one child
returnedHeight += dividerHeight;
}
// Recycle the view before we possibly return from the method
if (recyle && recycleBin.shouldRecycleViewType(
((LayoutParams) child.getLayoutParams()).viewType)) {
recycleBin.addScrapView(child);
}
returnedHeight += child.getMeasuredHeight();
if (returnedHeight >= maxHeight) {
// We went over, figure out which height to return. If returnedHeight > maxHeight,
// then the i'th position did not fit completely.
return (disallowPartialChildPosition >= 0) // Disallowing is enabled (> -1)
&& (i > disallowPartialChildPosition) // We've past the min pos
&& (prevHeightWithoutPartialChild > 0) // We have a prev height
&& (returnedHeight != maxHeight) // i'th child did not fit completely
? prevHeightWithoutPartialChild
: maxHeight;
}
if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) {
prevHeightWithoutPartialChild = returnedHeight;
}
}
// At this point, we went through the range of children, and they each
// completely fit, so return the returnedHeight
return returnedHeight;
}
@Override
int findMotionRow(int y) {
int childCount = getChildCount();
if (childCount > 0) {
if (!mStackFromBottom) {
for (int i = 0; i < childCount; i++) {
View v = getChildAt(i);
if (y <= v.getBottom()) {
return mFirstPosition + i;
}
}
} else {
for (int i = childCount - 1; i >= 0; i--) {
View v = getChildAt(i);
if (y >= v.getTop()) {
return mFirstPosition + i;
}
}
}
}
return INVALID_POSITION;
}
/**
* Put a specific item at a specific location on the screen and then build
* up and down from there.
*
* @param position The reference view to use as the starting point
* @param top Pixel offset from the top of this view to the top of the
* reference view.
*
* @return The selected view, or null if the selected view is outside the
* visible area.
*/
private View fillSpecific(int position, int top) {
if(DEBUG) Log.d("PLA_ListView", "FillSpecific: " + position + ":" + top);
View temp = makeAndAddView(position, top, true, false);
// Possibly changed again in fillUp if we add rows above this one.
mFirstPosition = position;
final int dividerHeight = mDividerHeight;
if (!mStackFromBottom) {
fillUp(position - 1, temp.getTop() - dividerHeight);
// This will correct for the top of the first view not touching the top of the list
adjustViewsUpOrDown();
fillDown(position + 1, temp.getBottom() + dividerHeight);
int childCount = getChildCount();
if (childCount > 0) {
correctTooHigh(childCount);
}
} else {
fillDown(position + 1, temp.getBottom() + dividerHeight);
// This will correct for the bottom of the last view not touching the bottom of the list
adjustViewsUpOrDown();
fillUp(position - 1, temp.getTop() - dividerHeight);
int childCount = getChildCount();
if (childCount > 0) {
correctTooLow(childCount);
}
}
return null;
}
/**
* Check if we have dragged the bottom of the list too high (we have pushed the
* top element off the top of the screen when we did not need to). Correct by sliding
* everything back down.
*
* @param childCount Number of children
*/
private void correctTooHigh(int childCount) {
// First see if the last item is visible. If it is not, it is OK for the
// top of the list to be pushed up.
int lastPosition = mFirstPosition + childCount - 1;
if (lastPosition == mItemCount - 1 && childCount > 0) {
// Get the last child ...
//final View lastChild = getChildAt(childCount - 1);
// ... and its bottom edge
//final int lastBottom = lastChild.getBottom();
final int lastBottom = getScrollChildBottom();
// This is bottom of our drawable area
// final int end = (mBottom - mTop) - mListPadding.bottom;
final int end = (getBottom() - getTop()) - mListPadding.bottom;
// This is how far the bottom edge of the last view is from the bottom of the drawable area
int bottomOffset = end - lastBottom;
//View firstChild = getChildAt(0);
//final int firstTop = firstChild.getTop();
final int firstTop = getScrollChildTop();
// Make sure we are 1) Too high, and 2) Either there are more rows above the
// first row or the first row is scrolled off the top of the drawable area
if (bottomOffset > 0 && (mFirstPosition > 0 || firstTop < mListPadding.top)) {
if (mFirstPosition == 0) {
// Don't pull the top too far down
bottomOffset = Math.min(bottomOffset, mListPadding.top - firstTop);
}
// Move everything down
// offsetChildrenTopAndBottom(bottomOffset);
tryOffsetChildrenTopAndBottom(bottomOffset);
if (mFirstPosition > 0) {
// Fill the gap that was opened above mFirstPosition with more rows, if
// possible
int newFirstTop = getScrollChildTop();
fillUp(mFirstPosition - 1, newFirstTop - mDividerHeight);
// Close up the remaining gap
adjustViewsUpOrDown();
}
}
}
}
/**
* Check if we have dragged the bottom of the list too low (we have pushed the
* bottom element off the bottom of the screen when we did not need to). Correct by sliding
* everything back up.
*
* @param childCount Number of children
*/
private void correctTooLow(int childCount) {
// First see if the first item is visible. If it is not, it is OK for the
// bottom of the list to be pushed down.
if (mFirstPosition == 0 && childCount > 0) {
// Get the first child and its top edge
final int firstTop = getScrollChildTop();
// This is top of our drawable area
final int start = mListPadding.top;
// This is bottom of our drawable area
final int end = (getBottom() -getTop()) - mListPadding.bottom;
// This is how far the top edge of the first view is from the top of the drawable area
int topOffset = firstTop - start;
final int lastBottom = getScrollChildBottom();
int lastPosition = mFirstPosition + childCount - 1;
// Make sure we are 1) Too low, and 2) Either there are more rows below the
// last row or the last row is scrolled off the bottom of the drawable area
if (topOffset > 0) {
if (lastPosition < mItemCount - 1 || lastBottom > end) {
if (lastPosition == mItemCount - 1) {
// Don't pull the bottom too far up
topOffset = Math.min(topOffset, lastBottom - end);
}
// Move everything up
tryOffsetChildrenTopAndBottom(-topOffset);
if (lastPosition < mItemCount - 1) {
// Fill the gap that was opened below the last position with more rows, if
// possible
fillDown(lastPosition + 1, getFillChildTop() + mDividerHeight);
// Close up the remaining gap
adjustViewsUpOrDown();
}
} else if (lastPosition == mItemCount - 1) {
adjustViewsUpOrDown();
}
}
}
}
@SuppressWarnings("deprecation")
@Override
protected void layoutChildren() {
final boolean blockLayoutRequests = mBlockLayoutRequests;
if (!blockLayoutRequests) {
mBlockLayoutRequests = true;
} else {
return;
}
try {
super.layoutChildren();
invalidate();
if (mAdapter == null) {
resetList();
invokeOnItemScrollListener();
return;
}
int childrenTop = mListPadding.top;
//int childrenBottom = mBottom - mTop - mListPadding.bottom;
int childrenBottom = getBottom() - getTop() - mListPadding.bottom;
int childCount = getChildCount();
int index = 0;
View oldFirst = null;
View focusLayoutRestoreView = null;
// Remember stuff we will need down below
switch (mLayoutMode) {
case LAYOUT_FORCE_TOP:
case LAYOUT_FORCE_BOTTOM:
case LAYOUT_SPECIFIC:
case LAYOUT_SYNC:
break;
default:
// Remember the previous first child
oldFirst = getChildAt(0);
}
boolean dataChanged = mDataChanged;
if (dataChanged) {
handleDataChanged();
}
// Handle the empty set by removing all views that are visible
// and calling it a day
if (mItemCount == 0) {
resetList();
invokeOnItemScrollListener();
return;
} else if (mItemCount != mAdapter.getCount()) {
throw new IllegalStateException("The content of the adapter has changed but "
+ "ListView did not receive a notification. Make sure the content of "
+ "your adapter is not modified from a background thread, but only "
+ "from the UI thread. [in ListView(" + getId() + ", " + getClass()
+ ") with Adapter(" + mAdapter.getClass() + ")]");
}
// Pull all children into the RecycleBin.
// These views will be reused if possible
final int firstPosition = mFirstPosition;
final RecycleBin recycleBin = mRecycler;
// reset the focus restoration
// Don't put header or footer views into the Recycler. Those are
// already cached in mHeaderViews;
if (dataChanged) {
for (int i = 0; i < childCount; i++) {
recycleBin.addScrapView(getChildAt(i));
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(getChildAt(i),
ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP, index, i);
}
}
} else {
recycleBin.fillActiveViews(childCount, firstPosition);
}
// take focus back to us temporarily to avoid the eventual
// call to clear focus when removing the focused child below
// from messing things up when ViewRoot assigns focus back
// to someone else
final View focusedChild = getFocusedChild();
if (focusedChild != null) {
// TODO: in some cases focusedChild.getParent() == null
// we can remember the focused view to restore after relayout if the
// data hasn't changed, or if the focused position is a header or footer
if (!dataChanged || isDirectChildHeaderOrFooter(focusedChild)) {
// remember the specific view that had focus
focusLayoutRestoreView = findFocus();
if (focusLayoutRestoreView != null) {
// tell it we are going to mess with it
focusLayoutRestoreView.onStartTemporaryDetach();
}
}
requestFocus();
}
switch (mLayoutMode) {
case LAYOUT_SYNC:
onLayoutSync(mSyncPosition);
// Clear out old views
detachAllViewsFromParent();
fillSpecific(mSyncPosition, mSpecificTop);
onLayoutSyncFinished(mSyncPosition);
break;
case LAYOUT_FORCE_BOTTOM:
detachAllViewsFromParent();
fillUp(mItemCount - 1, childrenBottom);
adjustViewsUpOrDown();
break;
case LAYOUT_FORCE_TOP:
detachAllViewsFromParent();
mFirstPosition = 0;
fillFromTop(childrenTop);
adjustViewsUpOrDown();
break;
default:
if (childCount == 0) {
detachAllViewsFromParent();
if (!mStackFromBottom) {
fillFromTop(childrenTop);
} else {
fillUp(mItemCount - 1, childrenBottom);
}
} else {
if (mFirstPosition < mItemCount) {
onLayoutSync(mFirstPosition);
detachAllViewsFromParent();
fillSpecific(mFirstPosition, oldFirst == null ? childrenTop : oldFirst.getTop());
onLayoutSyncFinished(mFirstPosition);
} else {
onLayoutSync(0);
detachAllViewsFromParent();
fillSpecific(0, childrenTop);
onLayoutSyncFinished(0);
}
}
break;
}
// Flush any cached views that did not get reused above
recycleBin.scrapActiveViews();
if (mTouchMode > TOUCH_MODE_DOWN && mTouchMode < TOUCH_MODE_SCROLL) {
View child = getChildAt(mMotionPosition - mFirstPosition);
if (child != null) positionSelector(child);
} else {
mSelectedTop = 0;
mSelectorRect.setEmpty();
}
// even if there is not selected position, we may need to restore
// focus (i.e. something focusable in touch mode)
if (hasFocus() && focusLayoutRestoreView != null) {
focusLayoutRestoreView.requestFocus();
}
// tell focus view we are done mucking with it, if it is still in
// our view hierarchy.
if (focusLayoutRestoreView != null
&& focusLayoutRestoreView.getWindowToken() != null) {
focusLayoutRestoreView.onFinishTemporaryDetach();
}
mLayoutMode = LAYOUT_NORMAL;
mDataChanged = false;
mNeedSync = false;
invokeOnItemScrollListener();
} finally {
if (!blockLayoutRequests) {
mBlockLayoutRequests = false;
}
}
}
/**
* @param child a direct child of this list.
* @return Whether child is a header or footer view.
*/
private boolean isDirectChildHeaderOrFooter(View child) {
final ArrayList<FixedViewInfo> headers = mHeaderViewInfos;
final int numHeaders = headers.size();
for (int i = 0; i < numHeaders; i++) {
if (child == headers.get(i).view) {
return true;
}
}
final ArrayList<FixedViewInfo> footers = mFooterViewInfos;
final int numFooters = footers.size();
for (int i = 0; i < numFooters; i++) {
if (child == footers.get(i).view) {
return true;
}
}
return false;
}
/**
* Obtain the view and add it to our list of children. The view can be made
* fresh, converted from an unused view, or used as is if it was in the
* recycle bin.
*
* @param position Logical position in the list
* @param childrenBottomOrTop Top or bottom edge of the view to add
* @param flow If flow is true, align top edge to y. If false, align bottom
* edge to y.
* @param childrenLeft Left edge where children should be positioned
* @param selected Is this position selected?
* @return View that was added
*/
@SuppressWarnings("deprecation")
private View makeAndAddView(int position, int childrenBottomOrTop, boolean flow,
boolean selected) {
View child;
int childrenLeft;
if (!mDataChanged) {
// Try to use an exsiting view for this position
child = mRecycler.getActiveView(position);
if (child != null) {
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(child, ViewDebug.RecyclerTraceType.RECYCLE_FROM_ACTIVE_HEAP,
position, getChildCount());
}
// Found it -- we're using an existing child
// This just needs to be positioned
childrenLeft = getItemLeft(position);
setupChild(child, position, childrenBottomOrTop, flow, childrenLeft, selected, true);
return child;
}
}
//Notify new item is added to view.
onItemAddedToList( position, flow );
childrenLeft = getItemLeft( position );
// Make a new view for this position, or convert an unused view if possible
child = obtainView(position, mIsScrap);
// This needs to be positioned and measured
setupChild(child, position, childrenBottomOrTop, flow, childrenLeft, selected, mIsScrap[0]);
return child;
}
/**
* @param position position of newly adde ditem.
* @param flow If flow is true, align top edge to y. If false, align bottom edge to y.
*/
protected void onItemAddedToList(int position, boolean flow) {
}
/**
* Add a view as a child and make sure it is measured (if necessary) and
* positioned properly.
*
* @param child The view to add
* @param position The position of this child
* @param y The y position relative to which this view will be positioned
* @param flowDown If true, align top edge to y. If false, align bottom
* edge to y.
* @param childrenLeft Left edge where children should be positioned
* @param selected Is this position selected?
* @param recycled Has this view been pulled from the recycle bin? If so it
* does not need to be remeasured.
*/
private void setupChild(View child, int position, int y, boolean flowDown, int childrenLeft,
boolean selected, boolean recycled) {
final boolean isSelected = selected && shouldShowSelector();
final boolean updateChildSelected = isSelected != child.isSelected();
final int mode = mTouchMode;
final boolean isPressed = mode > TOUCH_MODE_DOWN && mode < TOUCH_MODE_SCROLL &&
mMotionPosition == position;
final boolean updateChildPressed = isPressed != child.isPressed();
final boolean needToMeasure = !recycled || updateChildSelected || child.isLayoutRequested();
// Respect layout params that are already in the view. Otherwise make some up...
// noinspection unchecked
PLA_AbsListView.LayoutParams p = (PLA_AbsListView.LayoutParams) child.getLayoutParams();
if (p == null) {
p = new PLA_AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 0);
}
p.viewType = mAdapter.getItemViewType(position);
if ((recycled && !p.forceAdd) || (p.recycledHeaderFooter &&
p.viewType == PLA_AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER)) {
attachViewToParent(child, flowDown ? -1 : 0, p);
} else {
p.forceAdd = false;
if (p.viewType == PLA_AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
p.recycledHeaderFooter = true;
}
addViewInLayout(child, flowDown ? -1 : 0, p, true);
}
if (updateChildSelected) {
child.setSelected(isSelected);
}
if (updateChildPressed) {
child.setPressed(isPressed);
}
if (needToMeasure) {
int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
mListPadding.left + mListPadding.right, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
onMeasureChild( child, position, childWidthSpec, childHeightSpec );
//child.measure(childWidthSpec, childHeightSpec);
} else {
cleanupLayoutState(child);
}
final int w = child.getMeasuredWidth();
final int h = child.getMeasuredHeight();
final int childTop = flowDown ? y : y - h;
if (needToMeasure) {
final int childRight = childrenLeft + w;
final int childBottom = childTop + h;
//child.layout(childrenLeft, childTop, childRight, childBottom);
onLayoutChild(child, position, childrenLeft, childTop, childRight, childBottom);
} else {
final int offsetLeft = childrenLeft - child.getLeft();
final int offsetTop = childTop - child.getTop();
onOffsetChild(child, position, offsetLeft, offsetTop);
}
if (mCachingStarted && !child.isDrawingCacheEnabled()) {
child.setDrawingCacheEnabled(true);
}
}
protected void onOffsetChild(View child, int position, int offsetLeft, int offsetTop) {
child.offsetLeftAndRight(offsetLeft);
child.offsetTopAndBottom(offsetTop);
}
protected void onLayoutChild(View child, int position, int l, int t, int r, int b) {
child.layout(l, t, r, b);
}
/**
* this method is called every time a new child is mesaure.
* @param child
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
protected void onMeasureChild(View child, int position, int widthMeasureSpec, int heightMeasureSpec) {
child.measure(widthMeasureSpec, heightMeasureSpec);
}
/**
* this method is called to adjust child view's up & down.
* @param down
*/
protected void onAdjustChildViews( boolean down ) {
if( down )
correctTooHigh(getChildCount());
else
correctTooLow(getChildCount());
}
@Override
protected boolean canAnimate() {
return super.canAnimate() && mItemCount > 0;
}
/**
* Sets the currently selected item. If in touch mode, the item will not be selected
* but it will still be positioned appropriately. If the specified selection position
* is less than 0, then the item at position 0 will be selected.
*
* @param position Index (starting at 0) of the data item to be selected.
*/
@Override
public void setSelection(int position) {
}
/**
* Find a position that can be selected (i.e., is not a separator).
*
* @param position The starting position to look at.
* @param lookDown Whether to look down for other positions.
* @return The next selectable position starting at position and then searching either up or
* down. Returns {@link #INVALID_POSITION} if nothing can be found.
*/
@Override
int lookForSelectablePosition(int position, boolean lookDown) {
final ListAdapter adapter = mAdapter;
if (adapter == null || isInTouchMode()) {
return INVALID_POSITION;
}
final int count = adapter.getCount();
if (!mAreAllItemsSelectable) {
if (lookDown) {
position = Math.max(0, position);
while (position < count && !adapter.isEnabled(position)) {
position++;
}
} else {
position = Math.min(position, count - 1);
while (position >= 0 && !adapter.isEnabled(position)) {
position--;
}
}
if (position < 0 || position >= count) {
return INVALID_POSITION;
}
return position;
} else {
if (position < 0 || position >= count) {
return INVALID_POSITION;
}
return position;
}
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
boolean populated = super.dispatchPopulateAccessibilityEvent(event);
// If the item count is less than 15 then subtract disabled items from the count and
// position. Otherwise ignore disabled items.
if (!populated) {
int itemCount = 0;
int currentItemIndex = getSelectedItemPosition();
ListAdapter adapter = getAdapter();
if (adapter != null) {
final int count = adapter.getCount();
if (count < 15) {
for (int i = 0; i < count; i++) {
if (adapter.isEnabled(i)) {
itemCount++;
} else if (i <= currentItemIndex) {
currentItemIndex--;
}
}
} else {
itemCount = count;
}
}
event.setItemCount(itemCount);
event.setCurrentItemIndex(currentItemIndex);
}
return populated;
}
/**
* Go to the last or first item if possible (not worrying about panning across or navigating
* within the internal focus of the currently selected item.)
*
* @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
*
* @return whether selection was moved
*/
public boolean fullScroll(int direction) {
boolean moved = false;
if (direction == FOCUS_UP) {
int position = lookForSelectablePosition(0, true);
if (position >= 0) {
mLayoutMode = LAYOUT_FORCE_TOP;
invokeOnItemScrollListener();
moved = true;
}
} else if (direction == FOCUS_DOWN) {
int position = lookForSelectablePosition(mItemCount - 1, true);
if (position >= 0) {
mLayoutMode = LAYOUT_FORCE_BOTTOM;
invokeOnItemScrollListener();
}
moved = true;
}
if (moved && !awakenScrollBars()) {
awakenScrollBars();
invalidate();
}
return moved;
}
/**
* Scroll the children by amount, adding a view at the end and removing
* views that fall off as necessary.
*
* @param amount The amount (positive or negative) to scroll.
*/
private void scrollListItemsBy(int amount) {
// offsetChildrenTopAndBottom(amount);
tryOffsetChildrenTopAndBottom(amount);
final int listBottom = getHeight() - mListPadding.bottom;
final int listTop = mListPadding.top;
final PLA_AbsListView.RecycleBin recycleBin = mRecycler;
if (amount < 0) {
// shifted items up
// may need to pan views into the bottom space
View last = getLastChild();
int numChildren = getChildCount();
// View last = getChildAt(numChildren - 1);
while (last.getBottom() < listBottom) {
final int lastVisiblePosition = mFirstPosition + numChildren - 1;
if (lastVisiblePosition < mItemCount - 1) {
addViewBelow(last, lastVisiblePosition);
last = getLastChild();
numChildren++;
} else {
break;
}
}
// may have brought in the last child of the list that is skinnier
// than the fading edge, thereby leaving space at the end. need
// to shift back
if (last.getBottom() < listBottom) {
// offsetChildrenTopAndBottom(listBottom - last.getBottom());
tryOffsetChildrenTopAndBottom(listBottom - last.getBottom());
}
// top views may be panned off screen
View first = getChildAt(0);
while (first.getBottom() < listTop) {
PLA_AbsListView.LayoutParams layoutParams = (LayoutParams) first.getLayoutParams();
if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
detachViewFromParent(first);
recycleBin.addScrapView(first);
} else {
removeViewInLayout(first);
}
first = getChildAt(0);
mFirstPosition++;
}
} else {
// shifted items down
View first = getChildAt(0);
// may need to pan views into top
while ((first.getTop() > listTop) && (mFirstPosition > 0)) {
first = addViewAbove(first, mFirstPosition);
mFirstPosition--;
}
// may have brought the very first child of the list in too far and
// need to shift it back
if (first.getTop() > listTop) {
// offsetChildrenTopAndBottom(listTop - first.getTop());
tryOffsetChildrenTopAndBottom(listTop - first.getTop());
}
int lastIndex = getChildCount() - 1;
View last = getChildAt(lastIndex);
// bottom view may be panned off screen
while (last.getTop() > listBottom) {
PLA_AbsListView.LayoutParams layoutParams = (LayoutParams) last.getLayoutParams();
if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
detachViewFromParent(last);
recycleBin.addScrapView(last);
} else {
removeViewInLayout(last);
}
last = getChildAt(--lastIndex);
}
}
}
protected View getLastChild() {
int numChildren = getChildCount();
return getChildAt(numChildren - 1);
}
private View addViewAbove(View theView, int position) {
int abovePosition = position - 1;
View view = obtainView(abovePosition, mIsScrap);
int edgeOfNewChild = theView.getTop() - mDividerHeight;
setupChild(view, abovePosition, edgeOfNewChild, false, mListPadding.left,
false, mIsScrap[0]);
return view;
}
private View addViewBelow(View theView, int position) {
int belowPosition = position + 1;
View view = obtainView(belowPosition, mIsScrap);
int edgeOfNewChild = theView.getBottom() + mDividerHeight;
setupChild(view, belowPosition, edgeOfNewChild, true, mListPadding.left,
false, mIsScrap[0]);
return view;
}
/**
* Indicates that the views created by the ListAdapter can contain focusable
* items.
*
* @param itemsCanFocus true if items can get focus, false otherwise
*/
public void setItemsCanFocus(boolean itemsCanFocus) {
mItemsCanFocus = itemsCanFocus;
if (!itemsCanFocus) {
setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
}
}
/**
* @return Whether the views created by the ListAdapter can contain focusable
* items.
*/
public boolean getItemsCanFocus() {
return mItemsCanFocus;
}
/**
* @hide Pending API council approval.
*/
@Override
public boolean isOpaque() {
// return (mCachingStarted && mIsCacheColorOpaque && mDividerIsOpaque &&
// hasOpaqueScrollbars()) || super.isOpaque();
//we can ignore scrollbar...
return (mCachingStarted && mIsCacheColorOpaque && mDividerIsOpaque) || super.isOpaque();
}
@Override
public void setCacheColorHint(int color) {
final boolean opaque = (color >>> 24) == 0xFF;
mIsCacheColorOpaque = opaque;
if (opaque) {
if (mDividerPaint == null) {
mDividerPaint = new Paint();
}
mDividerPaint.setColor(color);
}
super.setCacheColorHint(color);
}
void drawOverscrollHeader(Canvas canvas, Drawable drawable, Rect bounds) {
final int height = drawable.getMinimumHeight();
canvas.save();
canvas.clipRect(bounds);
final int span = bounds.bottom - bounds.top;
if (span < height) {
bounds.top = bounds.bottom - height;
}
drawable.setBounds(bounds);
drawable.draw(canvas);
canvas.restore();
}
void drawOverscrollFooter(Canvas canvas, Drawable drawable, Rect bounds) {
final int height = drawable.getMinimumHeight();
canvas.save();
canvas.clipRect(bounds);
final int span = bounds.bottom - bounds.top;
if (span < height) {
bounds.bottom = bounds.top + height;
}
drawable.setBounds(bounds);
drawable.draw(canvas);
canvas.restore();
}
@Override
protected void dispatchDraw(Canvas canvas) {
// Draw the dividers
final int dividerHeight = mDividerHeight;
final Drawable overscrollHeader = mOverScrollHeader;
final Drawable overscrollFooter = mOverScrollFooter;
final boolean drawOverscrollHeader = overscrollHeader != null;
final boolean drawOverscrollFooter = overscrollFooter != null;
final boolean drawDividers = dividerHeight > 0 && mDivider != null;
if (drawDividers || drawOverscrollHeader || drawOverscrollFooter) {
// Only modify the top and bottom in the loop, we set the left and right here
final Rect bounds = mTempRect;
// bounds.left = mPaddingLeft;
// bounds.right = mRight - mLeft - mPaddingRight;
bounds.left = getPaddingLeft();
bounds.right = getRight() - getLeft() - getPaddingRight();
final int count = getChildCount();
final int headerCount = mHeaderViewInfos.size();
final int itemCount = mItemCount;
final int footerLimit = itemCount - mFooterViewInfos.size() - 1;
final boolean headerDividers = mHeaderDividersEnabled;
final boolean footerDividers = mFooterDividersEnabled;
final int first = mFirstPosition;
final boolean areAllItemsSelectable = mAreAllItemsSelectable;
final ListAdapter adapter = mAdapter;
// If the list is opaque *and* the background is not, we want to
// fill a rect where the dividers would be for non-selectable items
// If the list is opaque and the background is also opaque, we don't
// need to draw anything since the background will do it for us
final boolean fillForMissingDividers = drawDividers && isOpaque() && !super.isOpaque();
if (fillForMissingDividers && mDividerPaint == null && mIsCacheColorOpaque) {
mDividerPaint = new Paint();
mDividerPaint.setColor(getCacheColorHint());
}
final Paint paint = mDividerPaint;
// final int listBottom = mBottom - mTop - mListPadding.bottom + mScrollY;
final int listBottom = getBottom() - getTop() - mListPadding.bottom + getScrollY();
if (!mStackFromBottom) {
int bottom = 0;
// Draw top divider or header for overscroll
// final int scrollY = mScrollY;
final int scrollY = getScrollY();
if (count > 0 && scrollY < 0) {
if (drawOverscrollHeader) {
bounds.bottom = 0;
bounds.top = scrollY;
drawOverscrollHeader(canvas, overscrollHeader, bounds);
} else if (drawDividers) {
bounds.bottom = 0;
bounds.top = -dividerHeight;
drawDivider(canvas, bounds, -1);
}
}
for (int i = 0; i < count; i++) {
if ((headerDividers || first + i >= headerCount) &&
(footerDividers || first + i < footerLimit)) {
View child = getChildAt(i);
bottom = child.getBottom();
// Don't draw dividers next to items that are not enabled
if (drawDividers &&
(bottom < listBottom && !(drawOverscrollFooter && i == count - 1))) {
if ((areAllItemsSelectable ||
(adapter.isEnabled(first + i) && (i == count - 1 ||
adapter.isEnabled(first + i + 1))))) {
bounds.top = bottom;
bounds.bottom = bottom + dividerHeight;
drawDivider(canvas, bounds, i);
} else if (fillForMissingDividers) {
bounds.top = bottom;
bounds.bottom = bottom + dividerHeight;
canvas.drawRect(bounds, paint);
}
}
}
}
// final int overFooterBottom = mBottom + mScrollY;
final int overFooterBottom = getBottom() + getScrollY();
if (drawOverscrollFooter && first + count == itemCount &&
overFooterBottom > bottom) {
bounds.top = bottom;
bounds.bottom = overFooterBottom;
drawOverscrollFooter(canvas, overscrollFooter, bounds);
}
} else {
int top;
int listTop = mListPadding.top;
// final int scrollY = mScrollY;
final int scrollY = getScrollY();
if (count > 0 && drawOverscrollHeader) {
bounds.top = scrollY;
bounds.bottom = getChildAt(0).getTop();
drawOverscrollHeader(canvas, overscrollHeader, bounds);
}
final int start = drawOverscrollHeader ? 1 : 0;
for (int i = start; i < count; i++) {
if ((headerDividers || first + i >= headerCount) &&
(footerDividers || first + i < footerLimit)) {
View child = getChildAt(i);
top = child.getTop();
// Don't draw dividers next to items that are not enabled
if (drawDividers && top > listTop) {
if ((areAllItemsSelectable ||
(adapter.isEnabled(first + i) && (i == count - 1 ||
adapter.isEnabled(first + i + 1))))) {
bounds.top = top - dividerHeight;
bounds.bottom = top;
// Give the method the child ABOVE the divider, so we
// subtract one from our child
// position. Give -1 when there is no child above the
// divider.
drawDivider(canvas, bounds, i - 1);
} else if (fillForMissingDividers) {
bounds.top = top - dividerHeight;
bounds.bottom = top;
canvas.drawRect(bounds, paint);
}
}
}
}
if (count > 0 && scrollY > 0) {
if (drawOverscrollFooter) {
// final int absListBottom = mBottom;
final int absListBottom = getBottom();
bounds.top = absListBottom;
bounds.bottom = absListBottom + scrollY;
drawOverscrollFooter(canvas, overscrollFooter, bounds);
} else if (drawDividers) {
bounds.top = listBottom;
bounds.bottom = listBottom + dividerHeight;
drawDivider(canvas, bounds, -1);
}
}
}
}
// Draw the indicators (these should be drawn above the dividers) and children
super.dispatchDraw(canvas);
}
/**
* Draws a divider for the given child in the given bounds.
*
* @param canvas The canvas to draw to.
* @param bounds The bounds of the divider.
* @param childIndex The index of child (of the View) above the divider.
* This will be -1 if there is no child above the divider to be
* drawn.
*/
void drawDivider(Canvas canvas, Rect bounds, int childIndex) {
// This widget draws the same divider for all children
final Drawable divider = mDivider;
final boolean clipDivider = mClipDivider;
if (!clipDivider) {
divider.setBounds(bounds);
} else {
canvas.save();
canvas.clipRect(bounds);
}
divider.draw(canvas);
if (clipDivider) {
canvas.restore();
}
}
/**
* Returns the drawable that will be drawn between each item in the list.
*
* @return the current drawable drawn between list elements
*/
public Drawable getDivider() {
return mDivider;
}
/**
* Sets the drawable that will be drawn between each item in the list. If the drawable does
* not have an intrinsic height, you should also call {@link #setDividerHeight(int)}
*
* @param divider The drawable to use.
*/
public void setDivider(Drawable divider) {
if (divider != null) {
mDividerHeight = divider.getIntrinsicHeight();
mClipDivider = divider instanceof ColorDrawable;
} else {
mDividerHeight = 0;
mClipDivider = false;
}
mDivider = divider;
mDividerIsOpaque = divider == null || divider.getOpacity() == PixelFormat.OPAQUE;
requestLayoutIfNecessary();
}
/**
* @return Returns the height of the divider that will be drawn between each item in the list.
*/
public int getDividerHeight() {
return mDividerHeight;
}
/**
* Sets the height of the divider that will be drawn between each item in the list. Calling
* this will override the intrinsic height as set by {@link #setDivider(Drawable)}
*
* @param height The new height of the divider in pixels.
*/
public void setDividerHeight(int height) {
mDividerHeight = height;
requestLayoutIfNecessary();
}
/**
* Enables or disables the drawing of the divider for header views.
*
* @param headerDividersEnabled True to draw the headers, false otherwise.
*
* @see #setFooterDividersEnabled(boolean)
* @see #addHeaderView(android.view.View)
*/
public void setHeaderDividersEnabled(boolean headerDividersEnabled) {
mHeaderDividersEnabled = headerDividersEnabled;
invalidate();
}
/**
* Enables or disables the drawing of the divider for footer views.
*
* @param footerDividersEnabled True to draw the footers, false otherwise.
*
* @see #setHeaderDividersEnabled(boolean)
* @see #addFooterView(android.view.View)
*/
public void setFooterDividersEnabled(boolean footerDividersEnabled) {
mFooterDividersEnabled = footerDividersEnabled;
invalidate();
}
/**
* Sets the drawable that will be drawn above all other list content.
* This area can become visible when the user overscrolls the list.
*
* @param header The drawable to use
*/
public void setOverscrollHeader(Drawable header) {
mOverScrollHeader = header;
// if (mScrollY < 0) {
// invalidate();
// }
if (getScrollY() < 0) {
invalidate();
}
}
/**
* @return The drawable that will be drawn above all other list content
*/
public Drawable getOverscrollHeader() {
return mOverScrollHeader;
}
/**
* Sets the drawable that will be drawn below all other list content.
* This area can become visible when the user overscrolls the list,
* or when the list's content does not fully fill the container area.
*
* @param footer The drawable to use
*/
public void setOverscrollFooter(Drawable footer) {
mOverScrollFooter = footer;
invalidate();
}
/**
* @return The drawable that will be drawn below all other list content
*/
public Drawable getOverscrollFooter() {
return mOverScrollFooter;
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
if(DEBUG)
Log.v("PLA_ListView", "onFocusChanged");
int closetChildIndex = -1;
if (gainFocus && previouslyFocusedRect != null) {
//previouslyFocusedRect.offset(mScrollX, mScrollY);
previouslyFocusedRect.offset(getScrollX(), getScrollY());
final ListAdapter adapter = mAdapter;
// Don't cache the result of getChildCount or mFirstPosition here,
// it could change in layoutChildren.
if (adapter.getCount() < getChildCount() + mFirstPosition) {
mLayoutMode = LAYOUT_NORMAL;
layoutChildren();
}
// figure out which item should be selected based on previously
// focused rect
Rect otherRect = mTempRect;
int minDistance = Integer.MAX_VALUE;
final int childCount = getChildCount();
final int firstPosition = mFirstPosition;
for (int i = 0; i < childCount; i++) {
// only consider selectable views
if (!adapter.isEnabled(firstPosition + i)) {
continue;
}
View other = getChildAt(i);
other.getDrawingRect(otherRect);
offsetDescendantRectToMyCoords(other, otherRect);
int distance = getDistance(previouslyFocusedRect, otherRect, direction);
if (distance < minDistance) {
minDistance = distance;
closetChildIndex = i;
}
}
}
if (closetChildIndex >= 0) {
setSelection(closetChildIndex + mFirstPosition);
} else {
requestLayout();
}
}
/*
* (non-Javadoc)
*
* Children specified in XML are assumed to be header views. After we have
* parsed them move them out of the children list and into mHeaderViews.
*/
@Override
protected void onFinishInflate() {
super.onFinishInflate();
int count = getChildCount();
if (count > 0) {
for (int i = 0; i < count; ++i) {
addHeaderView(getChildAt(i));
}
removeAllViews();
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mItemsCanFocus && ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
// Don't handle edge touches immediately -- they may actually belong to one of our
// descendants.
return false;
}
return super.onTouchEvent(ev);
}
@Override
public boolean performItemClick(View view, int position, long id) {
boolean handled = false;
handled |= super.performItemClick(view, position, id);
return handled;
}
/**
* Sets the checked state of the specified position. The is only valid if
* the choice mode has been set to {@link #CHOICE_MODE_SINGLE} or
* {@link #CHOICE_MODE_MULTIPLE}.
*
* @param position The item whose checked state is to be checked
* @param value The new checked state for the item
*/
public void setItemChecked(int position, boolean value) {
}
/**
* Returns the checked state of the specified position. The result is only
* valid if the choice mode has been set to {@link #CHOICE_MODE_SINGLE}
* or {@link #CHOICE_MODE_MULTIPLE}.
*
* @param position The item whose checked state to return
* @return The item's checked state or <code>false</code> if choice mode
* is invalid
*
* @see #setChoiceMode(int)
*/
public boolean isItemChecked(int position) {
return false;
}
/**
* Returns the currently checked item. The result is only valid if the choice
* mode has been set to {@link #CHOICE_MODE_SINGLE}.
*
* @return The position of the currently checked item or
* {@link #INVALID_POSITION} if nothing is selected
*
* @see #setChoiceMode(int)
*/
public int getCheckedItemPosition() {
return INVALID_POSITION;
}
/**
* Returns the set of checked items in the list. The result is only valid if
* the choice mode has not been set to {@link #CHOICE_MODE_NONE}.
*
* @return A SparseBooleanArray which will return true for each call to
* get(int position) where position is a position in the list,
* or <code>null</code> if the choice mode is set to
* {@link #CHOICE_MODE_NONE}.
*/
public SparseBooleanArray getCheckedItemPositions() {
return null;
}
/**
* Returns the set of checked items ids. The result is only valid if the
* choice mode has not been set to {@link #CHOICE_MODE_NONE}.
*
* @return A new array which contains the id of each checked item in the
* list.
*
* @deprecated Use {@link #getCheckedItemIds()} instead.
*/
@Deprecated
public long[] getCheckItemIds() {
// Use new behavior that correctly handles stable ID mapping.
if (mAdapter != null && mAdapter.hasStableIds()) {
return getCheckedItemIds();
}
return new long[0];
}
/**
* Returns the set of checked items ids. The result is only valid if the
* choice mode has not been set to {@link #CHOICE_MODE_NONE} and the adapter
* has stable IDs. ({@link ListAdapter#hasStableIds()} == {@code true})
*
* @return A new array which contains the id of each checked item in the
* list.
*/
public long[] getCheckedItemIds() {
return new long[0];
}
/**
* Clear any choices previously set
*/
public void clearChoices() {
}
}//end of class
| 69,310
|
Java
|
.java
| 1,952
| 31.728996
| 103
| 0.706752
|
pengqinping/project_android
| 3
| 0
| 0
|
GPL-3.0
|
9/4/2024, 11:29:00 PM (Europe/Amsterdam)
| false
| true
| true
| true
| false
| true
| true
| true
| 69,310
|
4,256,723
|
CacheableService.java
|
rockleeprc_sourcecode/spring-framework/spring-context/src/test/java/org/springframework/cache/config/CacheableService.java
|
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cache.config;
/**
* Basic service interface for caching tests.
*
* @author Costin Leau
* @author Phillip Webb
* @author Stephane Nicoll
*/
public interface CacheableService<T> {
T cache(Object arg1);
T cacheNull(Object arg1);
T cacheSync(Object arg1);
T cacheSyncNull(Object arg1);
void invalidate(Object arg1);
void evictEarly(Object arg1);
void evictAll(Object arg1);
void evictWithException(Object arg1);
void evict(Object arg1, Object arg2);
void invalidateEarly(Object arg1, Object arg2);
T conditional(int field);
T conditionalSync(int field);
T unless(int arg);
T key(Object arg1, Object arg2);
T varArgsKey(Object... args);
T name(Object arg1);
T nullValue(Object arg1);
T update(Object arg1);
T conditionalUpdate(Object arg2);
Number nullInvocations();
T rootVars(Object arg1);
T customKeyGenerator(Object arg1);
T unknownCustomKeyGenerator(Object arg1);
T customCacheManager(Object arg1);
T unknownCustomCacheManager(Object arg1);
T throwChecked(Object arg1) throws Exception;
T throwUnchecked(Object arg1);
T throwCheckedSync(Object arg1) throws Exception;
T throwUncheckedSync(Object arg1);
T multiCache(Object arg1);
T multiEvict(Object arg1);
T multiCacheAndEvict(Object arg1);
T multiConditionalCacheAndEvict(Object arg1);
T multiUpdate(Object arg1);
TestEntity putRefersToResult(TestEntity arg1);
}
| 2,043
|
Java
|
.java
| 60
| 31.5
| 75
| 0.784576
|
rockleeprc/sourcecode
| 2
| 2
| 0
|
GPL-3.0
|
9/5/2024, 12:07:03 AM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 2,043
|
3,417,247
|
FingerTapStateMethods.java
|
steffe_MT4J_KTSI/extensions/org/mt4jx/input/inputProcessors/componentProcessors/Group3DProcessorNew/FingerTapGrouping/FingerTapStateMethods.java
|
package org.mt4jx.input.inputProcessors.componentProcessors.Group3DProcessorNew.FingerTapGrouping;
public interface FingerTapStateMethods {
public void stateEntry(FingerTapSelection sel);
public void stateExit(FingerTapSelection sel);
}
| 251
|
Java
|
.java
| 5
| 46.4
| 99
| 0.866109
|
steffe/MT4J_KTSI
| 3
| 0
| 1
|
GPL-2.0
|
9/4/2024, 11:24:37 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 251
|
3,029,112
|
TiatCamera.java
|
Hl4p3x_L2Scripts_H5_2268/dist/gameserver/data/scripts/ai/seedofdestruction/TiatCamera.java
|
package ai.seedofdestruction;
import java.util.ArrayList;
import java.util.List;
import l2s.gameserver.ai.DefaultAI;
import l2s.gameserver.model.Player;
import l2s.gameserver.model.World;
import l2s.gameserver.model.instances.NpcInstance;
import l2s.gameserver.network.l2.s2c.ExStartScenePlayer;
/**
* @author pchayka
*/
public class TiatCamera extends DefaultAI
{
private List<Player> _players = new ArrayList<Player>();
public TiatCamera(NpcInstance actor)
{
super(actor);
actor.startImmobilized();
actor.startDamageBlocked();
}
@Override
protected boolean thinkActive()
{
NpcInstance actor = getActor();
for(Player p : World.getAroundPlayers(actor, 300, 300))
if(!_players.contains(p))
{
p.showQuestMovie(ExStartScenePlayer.SCENE_TIAT_OPENING);
_players.add(p);
}
return true;
}
}
| 827
|
Java
|
.java
| 33
| 22.757576
| 60
| 0.779747
|
Hl4p3x/L2Scripts_H5_2268
| 5
| 6
| 0
|
GPL-3.0
|
9/4/2024, 10:43:16 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| true
| true
| true
| 827
|
4,789,144
|
ProviderException.java
|
mateor_PDroidHistory/libcore/luni/src/main/java/java/security/ProviderException.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.security;
/**
* {@code ProviderException} is a general exception, thrown by security {@code
* Providers}.
*
* @see Provider
*/
public class ProviderException extends RuntimeException {
private static final long serialVersionUID = 5256023526693665674L;
/**
* Constructs a new instance of {@code ProviderException} with the given
* message.
*
* @param msg
* the detail message for this exception.
*/
public ProviderException(String msg) {
super(msg);
}
/**
* Constructs a new instance of {@code ProviderException}.
*/
public ProviderException() {
}
/**
* Constructs a new instance of {@code ProviderException} with the given
* message and the cause.
*
* @param message
* the detail message for this exception.
* @param cause
* the exception which is the cause for this exception.
*/
public ProviderException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new instance of {@code ProviderException} with the cause.
*
* @param cause
* the exception which is the cause for this exception.
*/
public ProviderException(Throwable cause) {
super(cause);
}
}
| 2,143
|
Java
|
.java
| 62
| 30.209677
| 78
| 0.686114
|
mateor/PDroidHistory
| 1
| 2
| 0
|
GPL-3.0
|
9/5/2024, 12:31:53 AM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 2,143
|
2,220,215
|
MainApplication.java
|
AcornPublishing_spring-boot-jpa/spring-boot-persistence-main/chapter16/JsonToMySQL/src/main/java/com/bookstore/MainApplication.java
|
package com.bookstore;
import com.bookstore.service.BookstoreService;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class MainApplication {
private final BookstoreService bookstoreService;
public MainApplication(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
System.out.println("\n\nPersist a new author:");
bookstoreService.newAuthor();
System.out.println("\n\nFind author by name:");
bookstoreService.byName();
System.out.println("\n\nFind author by the isbn of his book:");
bookstoreService.byNameIsbn();
System.out.println("\n\nFind author by the isbn of his book via a native query:");
bookstoreService.byBookIsbnNativeQuery();
};
}
}
| 1,201
|
Java
|
.java
| 29
| 34.62069
| 94
| 0.719931
|
AcornPublishing/spring-boot-jpa
| 15
| 1
| 0
|
GPL-3.0
|
9/4/2024, 8:33:37 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 1,201
|
1,127,680
|
FileDialog.java
|
nikita36078_phoneME-android/cdc/src/share/personal/classes/awt/peer_based/java/awt/FileDialog.java
|
/*
* @(#)FileDialog.java 1.21 06/10/10
*
* Copyright 1990-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* 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 version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*
*/
package java.awt;
import sun.awt.peer.FileDialogPeer;
import sun.awt.PeerBasedToolkit;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* The <code>FileDialog</code> class displays a dialog window
* from which the user can select a file.
* <p>
* Since it is a modal dialog, when the application calls
* its <code>show</code> method to display the dialog,
* it blocks the rest of the application until the user has
* chosen a file.
*
* @see Window#show
*
* @version 1.16, 08/19/02
* @author Sami Shaio
* @author Arthur van Hoff
* @since JDK1.0
*/
public class FileDialog extends Dialog {
/**
* This constant value indicates that the purpose of the file
* dialog window is to locate a file from which to read.
*/
public static final int LOAD = 0;
/**
* This constant value indicates that the purpose of the file
* dialog window is to locate a file to which to write.
*/
public static final int SAVE = 1;
/**
* There are 2 FileDialog Modes : <code>LOAD<code> and
* <code>SAVE<code>.
* This integer will represent one or the other.
* If the mode is not specified it will default to LOAD.
*
* @serial
* @see getMode()
* @see setMode()
* @see java.awt.FileDialog#LOAD
* @see java.awt.FileDialog#SAVE
*/
int mode;
/**
* The string specifying the directory to display
* in the file dialog.
* This variable may be null.
*
* @serial
* @see getDirectory()
* @see setDirectory()
*/
String dir;
/**
* The string specifying the initial value of the
* filename text field in the file dialog.
* This variable may be null.
*
* @serial
* @see getFile()
* @see setFile()
*/
String file;
/**
* The filter used as the file dialog's filename filter.
* The file dialog will only be displaying files whose
* names are accepted by this filter.
* This variable may be null.
*
* @serial
* @see getFilenameFIlter()
* @see setFilenameFilter()
* @see FileNameFilter
*/
FilenameFilter filter;
private static final String base = "filedlg";
private static int nameCounter = 0;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = 5035145889651310422L;
/**
* Creates a file dialog for loading a file. The title of the
* file dialog is initially empty.
* @param parent the owner of the dialog
* @since JDK1.1
*/
public FileDialog(Frame parent) {
this(parent, "", LOAD);
}
/**
* Creates a file dialog window with the specified title for loading
* a file. The files shown are those in the current directory.
* @param parent the owner of the dialog.
* @param title the title of the dialog.
*/
public FileDialog(Frame parent, String title) {
this(parent, title, LOAD);
}
/**
* Creates a file dialog window with the specified title for loading
* or saving a file.
* <p>
* If the value of <code>mode</code> is <code>LOAD</code>, then the
* file dialog is finding a file to read. If the value of
* <code>mode</code> is <code>SAVE</code>, the file dialog is finding
* a place to write a file.
* @param parent the owner of the dialog.
* @param title the title of the dialog.
* @param mode the mode of the dialog.
* @see java.awt.FileDialog#LOAD
* @see java.awt.FileDialog#SAVE
*/
public FileDialog(Frame parent, String title, int mode) {
super(parent, title, true);
this.setMode(mode);
setLayout(null);
}
/**
* Construct a name for this component. Called by getName() when the
* name is null.
*/
String constructComponentName() {
synchronized (getClass()) {
return base + nameCounter++;
}
}
/**
* Creates the file dialog's peer. The peer allows us to change the look
* of the file dialog without changing its functionality.
*/
public void addNotify() {
synchronized (getTreeLock()) {
if (parent != null && parent.peer == null) {
parent.addNotify();
}
if (peer == null)
peer = ((PeerBasedToolkit) getToolkit()).createFileDialog(this);
super.addNotify();
}
}
/**
* Indicates whether this file dialog box is for loading from a file
* or for saving to a file.
* @return the mode of this file dialog window, either
* <code>FileDialog.LOAD</code> or
* <code>FileDialog.SAVE</code>.
* @see java.awt.FileDialog#LOAD
* @see java.awt.FileDialog#SAVE
* @see java.awt.FileDialog#setMode
*/
public int getMode() {
return mode;
}
/**
* Sets the mode of the file dialog.
* @param mode the mode for this file dialog, either
* <code>FileDialog.LOAD</code> or
* <code>FileDialog.SAVE</code>.
* @see java.awt.FileDialog#LOAD
* @see java.awt.FileDialog#SAVE
* @see java.awt.FileDialog#getMode
* @exception IllegalArgumentException if an illegal file
* dialog mode is used.
* @since JDK1.1
*/
public void setMode(int mode) {
switch (mode) {
case LOAD:
case SAVE:
this.mode = mode;
break;
default:
throw new IllegalArgumentException("illegal file dialog mode");
}
}
/**
* Gets the directory of this file dialog.
* @return the (potentially null or invalid) directory of this
* FileDialog.
* @see java.awt.FileDialog#setDirectory
*/
public String getDirectory() {
return dir;
}
/**
* Sets the directory of this file dialog window to be the
* specified directory. Specifying a <code>null</code> or an
* invalid directory implies an implementation-defined default.
* This default will not be realized, however, until the user
* has selected a file. Until this point, <code>getDirectory()</code>
* will return the value passed into this method.<p>
* Specifying "" as the directory is exactly equivalent to
* specifying <code>null</code> as the directory.
* @param dir the specific directory.
* @see java.awt.FileDialog#getDirectory
*/
public void setDirectory(String dir) {
this.dir = (dir != null && dir.equals("")) ? null : dir;
FileDialogPeer peer = (FileDialogPeer) this.peer;
if (peer != null) {
peer.setDirectory(this.dir);
}
}
/**
* Gets the selected file of this file dialog.
* @return the currently selected file of this file dialog window,
* or <code>null</code> if none is selected.
* @see java.awt.FileDialog#setFile
*/
public String getFile() {
return file;
}
/**
* Sets the selected file for this file dialog window to be the
* specified file. This file becomes the default file if it is set
* before the file dialog window is first shown.<p> Specifying "" as
* the file is exactly equivalent to specifying <code>null</code>
* as the file.
* @param file the file being set.
* @see java.awt.FileDialog#getFile
*/
public void setFile(String file) {
this.file = (file != null && file.equals("")) ? null : file;
FileDialogPeer peer = (FileDialogPeer) this.peer;
if (peer != null) {
peer.setFile(this.file);
}
}
/**
* Determines this file dialog's filename filter. A filename filter
* allows the user to specify which files appear in the file dialog
* window. Filename filters do not function in Sun's reference
* implementation for Windows 95, 98, or NT 4.0.
* @return this file dialog's filename filter.
* @see java.io.FilenameFilter
* @see java.awt.FileDialog#setFilenameFilter
*/
public FilenameFilter getFilenameFilter() {
return filter;
}
/**
* Sets the filename filter for this file dialog window to the
* specified filter.
* Filename filters do not function in Sun's reference
* implementation for Windows 95, 98, or NT 4.0.
* @param filter the specified filter.
* @see java.io.FilenameFilter
* @see java.awt.FileDialog#getFilenameFilter
*/
public synchronized void setFilenameFilter(FilenameFilter filter) {
this.filter = filter;
FileDialogPeer peer = (FileDialogPeer) this.peer;
if (peer != null) {
peer.setFilenameFilter(filter);
}
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException {
s.defaultReadObject();
// 1.1 Compatibility: "" is not converted to null in 1.1
if (dir != null && dir.equals("")) {
dir = null;
}
if (file != null && file.equals("")) {
file = null;
}
}
/**
* Returns the parameter string representing the state of this file
* dialog window. This string is useful for debugging.
* @return the parameter string of this file dialog window.
*/
protected String paramString() {
String str = super.paramString();
str += ",dir= " + dir;
str += ",file= " + file;
return str + ((mode == LOAD) ? ",load" : ",save");
}
boolean postsOldMouseEvents() {
return false;
}
}
| 10,919
|
Java
|
.java
| 312
| 29.016026
| 80
| 0.626086
|
nikita36078/phoneME-android
| 40
| 16
| 1
|
GPL-2.0
|
9/4/2024, 7:11:02 PM (Europe/Amsterdam)
| false
| true
| false
| true
| false
| true
| true
| true
| 10,919
|
4,313,463
|
AsynchronousChannelGroupImpl.java
|
hzio_OpenJDK10/src/java.base/share/classes/sun/nio/ch/AsynchronousChannelGroupImpl.java
|
/*
* Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.nio.ch;
import java.nio.channels.Channel;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.spi.AsynchronousChannelProvider;
import java.io.IOException;
import java.io.FileDescriptor;
import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicBoolean;
import java.security.PrivilegedAction;
import java.security.AccessController;
import java.security.AccessControlContext;
import sun.security.action.GetIntegerAction;
/**
* Base implementation of AsynchronousChannelGroup
*/
abstract class AsynchronousChannelGroupImpl
extends AsynchronousChannelGroup implements Executor
{
// number of internal threads handling I/O events when using an unbounded
// thread pool. Internal threads do not dispatch to completion handlers.
private static final int internalThreadCount = AccessController.doPrivileged(
new GetIntegerAction("sun.nio.ch.internalThreadPoolSize", 1));
// associated thread pool
private final ThreadPool pool;
// number of tasks running (including internal)
private final AtomicInteger threadCount = new AtomicInteger();
// associated Executor for timeouts
private ScheduledThreadPoolExecutor timeoutExecutor;
// task queue for when using a fixed thread pool. In that case, thread
// waiting on I/O events must be awokon to poll tasks from this queue.
private final Queue<Runnable> taskQueue;
// group shutdown
private final AtomicBoolean shutdown = new AtomicBoolean();
private final Object shutdownNowLock = new Object();
private volatile boolean terminateInitiated;
AsynchronousChannelGroupImpl(AsynchronousChannelProvider provider,
ThreadPool pool)
{
super(provider);
this.pool = pool;
if (pool.isFixedThreadPool()) {
taskQueue = new ConcurrentLinkedQueue<>();
} else {
taskQueue = null; // not used
}
// use default thread factory as thread should not be visible to
// application (it doesn't execute completion handlers).
this.timeoutExecutor = (ScheduledThreadPoolExecutor)
Executors.newScheduledThreadPool(1, ThreadPool.defaultThreadFactory());
this.timeoutExecutor.setRemoveOnCancelPolicy(true);
}
final ExecutorService executor() {
return pool.executor();
}
final boolean isFixedThreadPool() {
return pool.isFixedThreadPool();
}
final int fixedThreadCount() {
if (isFixedThreadPool()) {
return pool.poolSize();
} else {
return pool.poolSize() + internalThreadCount;
}
}
private Runnable bindToGroup(final Runnable task) {
final AsynchronousChannelGroupImpl thisGroup = this;
return new Runnable() {
public void run() {
Invoker.bindToGroup(thisGroup);
task.run();
}
};
}
private void startInternalThread(final Runnable task) {
AccessController.doPrivileged(new PrivilegedAction<>() {
@Override
public Void run() {
// internal threads should not be visible to application so
// cannot use user-supplied thread factory
ThreadPool.defaultThreadFactory().newThread(task).start();
return null;
}
});
}
protected final void startThreads(Runnable task) {
if (!isFixedThreadPool()) {
for (int i=0; i<internalThreadCount; i++) {
startInternalThread(task);
threadCount.incrementAndGet();
}
}
if (pool.poolSize() > 0) {
task = bindToGroup(task);
try {
for (int i=0; i<pool.poolSize(); i++) {
pool.executor().execute(task);
threadCount.incrementAndGet();
}
} catch (RejectedExecutionException x) {
// nothing we can do
}
}
}
final int threadCount() {
return threadCount.get();
}
/**
* Invoked by tasks as they terminate
*/
final int threadExit(Runnable task, boolean replaceMe) {
if (replaceMe) {
try {
if (Invoker.isBoundToAnyGroup()) {
// submit new task to replace this thread
pool.executor().execute(bindToGroup(task));
} else {
// replace internal thread
startInternalThread(task);
}
return threadCount.get();
} catch (RejectedExecutionException x) {
// unable to replace
}
}
return threadCount.decrementAndGet();
}
/**
* Wakes up a thread waiting for I/O events to execute the given task.
*/
abstract void executeOnHandlerTask(Runnable task);
/**
* For a fixed thread pool the task is queued to a thread waiting on I/O
* events. For other thread pools we simply submit the task to the thread
* pool.
*/
final void executeOnPooledThread(Runnable task) {
if (isFixedThreadPool()) {
executeOnHandlerTask(task);
} else {
pool.executor().execute(bindToGroup(task));
}
}
final void offerTask(Runnable task) {
taskQueue.offer(task);
}
final Runnable pollTask() {
return (taskQueue == null) ? null : taskQueue.poll();
}
final Future<?> schedule(Runnable task, long timeout, TimeUnit unit) {
try {
return timeoutExecutor.schedule(task, timeout, unit);
} catch (RejectedExecutionException rej) {
if (terminateInitiated) {
// no timeout scheduled as group is terminating
return null;
}
throw new AssertionError(rej);
}
}
@Override
public final boolean isShutdown() {
return shutdown.get();
}
@Override
public final boolean isTerminated() {
return pool.executor().isTerminated();
}
/**
* Returns true if there are no channels in the group
*/
abstract boolean isEmpty();
/**
* Attaches a foreign channel to this group.
*/
abstract Object attachForeignChannel(Channel channel, FileDescriptor fdo)
throws IOException;
/**
* Detaches a foreign channel from this group.
*/
abstract void detachForeignChannel(Object key);
/**
* Closes all channels in the group
*/
abstract void closeAllChannels() throws IOException;
/**
* Shutdown all tasks waiting for I/O events.
*/
abstract void shutdownHandlerTasks();
private void shutdownExecutors() {
AccessController.doPrivileged(
new PrivilegedAction<>() {
public Void run() {
pool.executor().shutdown();
timeoutExecutor.shutdown();
return null;
}
},
null,
new RuntimePermission("modifyThread"));
}
@Override
public final void shutdown() {
if (shutdown.getAndSet(true)) {
// already shutdown
return;
}
// if there are channels in the group then shutdown will continue
// when the last channel is closed
if (!isEmpty()) {
return;
}
// initiate termination (acquire shutdownNowLock to ensure that other
// threads invoking shutdownNow will block).
synchronized (shutdownNowLock) {
if (!terminateInitiated) {
terminateInitiated = true;
shutdownHandlerTasks();
shutdownExecutors();
}
}
}
@Override
public final void shutdownNow() throws IOException {
shutdown.set(true);
synchronized (shutdownNowLock) {
if (!terminateInitiated) {
terminateInitiated = true;
closeAllChannels();
shutdownHandlerTasks();
shutdownExecutors();
}
}
}
/**
* For use by AsynchronousFileChannel to release resources without shutting
* down the thread pool.
*/
final void detachFromThreadPool() {
if (shutdown.getAndSet(true))
throw new AssertionError("Already shutdown");
if (!isEmpty())
throw new AssertionError("Group not empty");
shutdownHandlerTasks();
}
@Override
public final boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException
{
return pool.executor().awaitTermination(timeout, unit);
}
/**
* Executes the given command on one of the channel group's pooled threads.
*/
@Override
public final void execute(Runnable task) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// when a security manager is installed then the user's task
// must be run with the current calling context
final AccessControlContext acc = AccessController.getContext();
final Runnable delegate = task;
task = new Runnable() {
@Override
public void run() {
AccessController.doPrivileged(new PrivilegedAction<>() {
@Override
public Void run() {
delegate.run();
return null;
}
}, acc);
}
};
}
executeOnPooledThread(task);
}
}
| 11,076
|
Java
|
.java
| 303
| 27.646865
| 83
| 0.623754
|
hzio/OpenJDK10
| 2
| 4
| 0
|
GPL-2.0
|
9/5/2024, 12:08:58 AM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 11,076
|
4,299,774
|
ChangeListenerApp.java
|
CISC3120SP18_SamplePrograms/GUI/JavaFXOracleSamples/Ensemble8/src/samples/java/ensemble/samples/language/changelistener/ChangeListenerApp.java
|
/*
* Copyright (c) 2008, 2014, Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* - Neither the name of Oracle Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ensemble.samples.language.changelistener;
import javafx.application.Application;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.effect.Lighting;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
/**
* A sample that demonstrates how to add or remove a change listener on a node
* (for example, a Rectangle node) for some property (for example,
* Rectangle.hover). Once you add a listener, the text field shows the hover
* property change.
*
* @sampleName ChangeListener
* @preview preview.png
* @see javafx.beans.value.ChangeListener
* @see javafx.beans.InvalidationListener
* @see javafx.beans.value.ObservableValue
* @embedded
*/
public class ChangeListenerApp extends Application {
// Simple filled rectangle
Rectangle rect1 = new Rectangle(25, 25, 40, 40);
// Stroked rectangle
Rectangle rect2 = new Rectangle(135, 25, 40, 40);
public Parent createContent() {
HBox outerHbox = new HBox();
outerHbox.setAlignment(Pos.CENTER);
VBox vbox = new VBox(10);
vbox.setPrefWidth(200);
// create rectangle
final Rectangle rect = new Rectangle(150, 0, 60, 60);
rect.setFill(Color.DODGERBLUE);
rect.setEffect(new Lighting());
//create text field for showing actual message
final Text text = new Text(0, 0, "Add a hover listener");
text.setStyle("-fx-font-size: 22;");
text.setTextOrigin(VPos.TOP);
text.setTextAlignment(TextAlignment.CENTER);
// create listener
final InvalidationListener hoverListener = (Observable ov) -> {
if (rect.isHover()) {
text.setText("hovered");
} else {
text.setText("not hovered");
}
};
//create button for adding listener
Button buttonAdd = new Button("Add listener");
buttonAdd.setPrefSize(140, 18);
buttonAdd.setOnAction((ActionEvent t) -> {
//add the listener on property hover
rect.hoverProperty().addListener(hoverListener);
text.setText("listener added");
});
//create a button for removing the listener
Button buttonRemove = new Button("Remove listener");
buttonRemove.setPrefSize(140, 18);
buttonRemove.setOnAction((ActionEvent t) -> {
//remove the listener
rect.hoverProperty().removeListener(hoverListener);
text.setText("listener removed");
});
// show all nodes
vbox.getChildren().addAll(text, buttonAdd, buttonRemove);
outerHbox.getChildren().addAll(vbox, rect);
outerHbox.setPadding(new Insets(5,5,5,5));
return outerHbox;
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(createContent()));
primaryStage.show();
}
/**
* Java main for when running without JavaFX launcher
* @param args command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
| 5,240
|
Java
|
.java
| 126
| 36.436508
| 78
| 0.716719
|
CISC3120SP18/SamplePrograms
| 2
| 7
| 0
|
GPL-3.0
|
9/5/2024, 12:08:25 AM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 5,240
|
4,256,821
|
AbstractRefreshableConfigApplicationContext.java
|
rockleeprc_sourcecode/spring-framework/spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java
|
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* {@link AbstractRefreshableApplicationContext} subclass that adds common handling
* of specified config locations. Serves as base class for XML-based application
* context implementations such as {@link ClassPathXmlApplicationContext} and
* {@link FileSystemXmlApplicationContext}, as well as
* {@link org.springframework.web.context.support.XmlWebApplicationContext}.
*
* @author Juergen Hoeller
* @since 2.5.2
* @see #setConfigLocation
* @see #setConfigLocations
* @see #getDefaultConfigLocations
*/
public abstract class AbstractRefreshableConfigApplicationContext extends AbstractRefreshableApplicationContext
implements BeanNameAware, InitializingBean {
@Nullable
private String[] configLocations;
private boolean setIdCalled = false;
/**
* Create a new AbstractRefreshableConfigApplicationContext with no parent.
*/
public AbstractRefreshableConfigApplicationContext() {
}
/**
* Create a new AbstractRefreshableConfigApplicationContext with the given parent context.
* @param parent the parent context
*/
public AbstractRefreshableConfigApplicationContext(@Nullable ApplicationContext parent) {
super(parent);
}
/**
* Set the config locations for this application context in init-param style,
* i.e. with distinct locations separated by commas, semicolons or whitespace.
* <p>If not set, the implementation may use a default as appropriate.
*/
public void setConfigLocation(String location) {
setConfigLocations(StringUtils.tokenizeToStringArray(location, CONFIG_LOCATION_DELIMITERS));
}
/**
* Set the config locations for this application context.
* <p>If not set, the implementation may use a default as appropriate.
*/
public void setConfigLocations(@Nullable String... locations) {
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
this.configLocations = new String[locations.length];
for (int i = 0; i < locations.length; i++) {
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
/**
* Return an array of resource locations, referring to the XML bean definition
* files that this context should be built with. Can also include location
* patterns, which will get resolved via a ResourcePatternResolver.
* <p>The default implementation returns {@code null}. Subclasses can override
* this to provide a set of resource locations to load bean definitions from.
* @return an array of resource locations, or {@code null} if none
* @see #getResources
* @see #getResourcePatternResolver
*/
@Nullable
protected String[] getConfigLocations() {
return (this.configLocations != null ? this.configLocations : getDefaultConfigLocations());
}
/**
* Return the default config locations to use, for the case where no
* explicit config locations have been specified.
* <p>The default implementation returns {@code null},
* requiring explicit config locations.
* @return an array of default config locations, if any
* @see #setConfigLocations
*/
@Nullable
protected String[] getDefaultConfigLocations() {
return null;
}
/**
* Resolve the given path, replacing placeholders with corresponding
* environment property values if necessary. Applied to config locations.
* @param path the original file path
* @return the resolved file path
* @see org.springframework.core.env.Environment#resolveRequiredPlaceholders(String)
*/
protected String resolvePath(String path) {
return getEnvironment().resolveRequiredPlaceholders(path);
}
@Override
public void setId(String id) {
super.setId(id);
this.setIdCalled = true;
}
/**
* Sets the id of this context to the bean name by default,
* for cases where the context instance is itself defined as a bean.
*/
@Override
public void setBeanName(String name) {
if (!this.setIdCalled) {
super.setId(name);
setDisplayName("ApplicationContext '" + name + "'");
}
}
/**
* Triggers {@link #refresh()} if not refreshed in the concrete context's
* constructor already.
*/
@Override
public void afterPropertiesSet() {
if (!isActive()) {
refresh();
}
}
}
| 5,148
|
Java
|
.java
| 139
| 34.438849
| 111
| 0.772545
|
rockleeprc/sourcecode
| 2
| 2
| 0
|
GPL-3.0
|
9/5/2024, 12:07:03 AM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 5,148
|
2,875,802
|
ChartData3Test.java
|
svn2github_dynamicreports-jasper/dynamicreports-core/src/test/java/net/sf/dynamicreports/test/jasper/chart/ChartData3Test.java
|
/**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2015 Ricardo Mariaca
* http://www.dynamicreports.org
*
* This file is part of DynamicReports.
*
* DynamicReports 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.
*
* DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.test.jasper.chart;
import static net.sf.dynamicreports.report.builder.DynamicReports.*;
import java.io.Serializable;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.column.TextColumnBuilder;
import net.sf.dynamicreports.report.datasource.DRDataSource;
import net.sf.dynamicreports.test.jasper.AbstractJasperChartTest;
import net.sf.jasperreports.engine.JRDataSource;
/**
* @author Ricardo Mariaca (r.mariaca@dynamicreports.org)
*/
public class ChartData3Test extends AbstractJasperChartTest implements Serializable {
private static final long serialVersionUID = 1L;
@Override
protected void configureReport(JasperReportBuilder rb) {
TextColumnBuilder<String> column1;
TextColumnBuilder<Integer> column2;
TextColumnBuilder<Integer> column3;
rb.columns(
column1 = col.column("Column1", "field1", String.class),
column2 = col.column("Column2", "field2", Integer.class),
column3 = col.column("Column3", "field3", Integer.class))
.summary(
cht.lineChart()
.setCategory(column1)
.series(
cht.serie(column2),
cht.serie(column3)));
}
@Override
public void test() {
super.test();
numberOfPagesTest(1);
String[] categories = new String[]{"value1", "value2", "value3"};
String[] series = new String[]{"Column2", "Column3"};
Number[][] values = new Number[][]{{1d, 2d}, {null, 3d}, {3d, 4d}, {4d, null}};
chartCountTest("summary.chart1", 1);
chartCategoryCountTest("summary.chart1", 0, 4);
chartSeriesCountTest("summary.chart1", 0, 2);
chartDataTest("summary.chart1", 0, categories, series, values);
}
@Override
protected JRDataSource createDataSource() {
DRDataSource dataSource = new DRDataSource("field1", "field2", "field3");
dataSource.add("value1", 1, 2);
dataSource.add("value2", null, 1);
dataSource.add("value2", null, null);
dataSource.add("value2", null, 2);
dataSource.add("value3", null, 4);
dataSource.add("value3", 3, null);
dataSource.add("value4", 4, null);
return dataSource;
}
}
| 3,069
|
Java
|
.java
| 75
| 36.946667
| 86
| 0.73266
|
svn2github/dynamicreports-jasper
| 5
| 8
| 2
|
LGPL-3.0
|
9/4/2024, 10:31:19 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 3,069
|
3,434,745
|
ConstructorDecl.java
|
Sable_polyglot/src/polyglot/ast/ConstructorDecl.java
|
package polyglot.ast;
import polyglot.types.ConstructorInstance;
import java.util.List;
import polyglot.types.Flags;
/**
* A <code>ConstructorDecl</code> is an immutable representation of a
* constructor declaration as part of a class body.
*/
public interface ConstructorDecl extends ProcedureDecl
{
/** The constructor's flags. */
Flags flags();
/** Set the constructor's flags. */
ConstructorDecl flags(Flags flags);
/**
* The constructor's name. This should be the short name of the
* containing class.
*/
String name();
/** Set the constructor's name. */
ConstructorDecl name(String name);
/** The constructor's formal parameters.
* @return A list of {@link polyglot.ast.Formal Formal}.
*/
List formals();
/** Set the constructor's formal parameters.
* @param formals A list of {@link polyglot.ast.Formal Formal}.
*/
ConstructorDecl formals(List formals);
/** The constructor's exception throw types.
* @return A list of {@link polyglot.ast.TypeNode TypeNode}.
*/
List throwTypes();
/** Set the constructor's exception throw types.
* @param throwTypes A list of {@link polyglot.ast.TypeNode TypeNode}.
*/
ConstructorDecl throwTypes(List throwTypes);
/**
* The constructor type object. This field may not be valid until
* after signature disambiguation.
*/
ConstructorInstance constructorInstance();
/** Set the constructor's type object. */
ConstructorDecl constructorInstance(ConstructorInstance ci);
}
| 1,577
|
Java
|
.java
| 45
| 30.355556
| 74
| 0.700197
|
Sable/polyglot
| 3
| 3
| 0
|
LGPL-2.1
|
9/4/2024, 11:26:54 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 1,577
|
1,380,526
|
CmsSiteFlowDao.java
|
caipiao_Lottery/src/com/jeecms/cms/dao/assist/CmsSiteFlowDao.java
|
package com.jeecms.cms.dao.assist;
import com.jeecms.cms.entity.assist.CmsSiteFlow;
public interface CmsSiteFlowDao {
public CmsSiteFlow save(CmsSiteFlow cmsSiteFlow);
public CmsSiteFlow findUniqueByProperties(Integer siteId, String accessDate,
String sessionId, String page);
}
| 297
|
Java
|
.java
| 7
| 38.857143
| 78
| 0.823944
|
caipiao/Lottery
| 24
| 17
| 0
|
GPL-2.0
|
9/4/2024, 7:47:27 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 297
|
4,190,782
|
DashChunkSourceTest.java
|
AgnitumuS_TV-App/ExoPlayer-dev-1.5.0-rc/library/src/androidTest/java/com/google/android/exoplayer/dash/DashChunkSourceTest.java
|
/*
* Copyright (C) 2014 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.google.android.exoplayer.dash;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.android.exoplayer.TimeRange;
import com.google.android.exoplayer.chunk.ChunkOperationHolder;
import com.google.android.exoplayer.chunk.Format;
import com.google.android.exoplayer.chunk.InitializationChunk;
import com.google.android.exoplayer.chunk.MediaChunk;
import com.google.android.exoplayer.dash.mpd.AdaptationSet;
import com.google.android.exoplayer.dash.mpd.MediaPresentationDescription;
import com.google.android.exoplayer.dash.mpd.Period;
import com.google.android.exoplayer.dash.mpd.RangedUri;
import com.google.android.exoplayer.dash.mpd.Representation;
import com.google.android.exoplayer.dash.mpd.SegmentBase.MultiSegmentBase;
import com.google.android.exoplayer.dash.mpd.SegmentBase.SegmentList;
import com.google.android.exoplayer.dash.mpd.SegmentBase.SegmentTemplate;
import com.google.android.exoplayer.dash.mpd.SegmentBase.SegmentTimelineElement;
import com.google.android.exoplayer.dash.mpd.SegmentBase.SingleSegmentBase;
import com.google.android.exoplayer.dash.mpd.UrlTemplate;
import com.google.android.exoplayer.testutil.TestUtil;
import com.google.android.exoplayer.upstream.DataSource;
import com.google.android.exoplayer.util.FakeClock;
import com.google.android.exoplayer.util.ManifestFetcher;
import com.google.android.exoplayer.util.Util;
import android.test.InstrumentationTestCase;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Tests {@link DashChunkSource}.
*/
public class DashChunkSourceTest extends InstrumentationTestCase {
private static final long VOD_DURATION_MS = 30000;
private static final long LIVE_SEGMENT_COUNT = 5;
private static final long LIVE_SEGMENT_DURATION_MS = 1000;
private static final long LIVE_DURATION_MS = LIVE_SEGMENT_COUNT * LIVE_SEGMENT_DURATION_MS;
private static final long LIVE_TIMESHIFT_BUFFER_DEPTH_MS = LIVE_DURATION_MS;
private static final int MULTI_PERIOD_COUNT = 2;
private static final long MULTI_PERIOD_VOD_DURATION_MS = VOD_DURATION_MS * MULTI_PERIOD_COUNT;
private static final long MULTI_PERIOD_LIVE_DURATION_MS = LIVE_DURATION_MS * MULTI_PERIOD_COUNT;
private static final long AVAILABILITY_START_TIME_MS = 60000;
private static final long ELAPSED_REALTIME_OFFSET_MS = 1000;
private static final int TALL_HEIGHT = 200;
private static final int WIDE_WIDTH = 400;
private static final Format REGULAR_VIDEO =
new Format("1", "video/mp4", 480, 240, -1, -1, -1, 1000);
private static final Format TALL_VIDEO =
new Format("2", "video/mp4", 100, TALL_HEIGHT, -1, -1, -1, 1000);
private static final Format WIDE_VIDEO =
new Format("3", "video/mp4", WIDE_WIDTH, 50, -1, -1, -1, 1000);
@Override
public void setUp() throws Exception {
TestUtil.setUpMockito(this);
}
public void testGetAvailableRangeOnVod() {
DashChunkSource chunkSource = new DashChunkSource(buildVodMpd(),
DefaultDashTrackSelector.newVideoInstance(null, false, false), null, null);
chunkSource.prepare();
chunkSource.enable(0);
TimeRange availableRange = chunkSource.getAvailableRange();
checkAvailableRange(availableRange, 0, VOD_DURATION_MS * 1000);
long[] seekRangeValuesMs = availableRange.getCurrentBoundsMs(null);
assertEquals(0, seekRangeValuesMs[0]);
assertEquals(VOD_DURATION_MS, seekRangeValuesMs[1]);
}
public void testGetAvailableRangeOnLiveWithTimeline() {
MediaPresentationDescription mpd = buildLiveMpdWithTimeline(LIVE_DURATION_MS, 0);
DashChunkSource chunkSource = buildDashChunkSource(mpd);
TimeRange availableRange = chunkSource.getAvailableRange();
checkAvailableRange(availableRange, 0, LIVE_DURATION_MS * 1000);
}
public void testGetAvailableRangeOnMultiPeriodVod() {
DashChunkSource chunkSource = new DashChunkSource(buildMultiPeriodVodMpd(),
DefaultDashTrackSelector.newVideoInstance(null, false, false), null, null);
chunkSource.prepare();
chunkSource.enable(0);
TimeRange availableRange = chunkSource.getAvailableRange();
checkAvailableRange(availableRange, 0, MULTI_PERIOD_VOD_DURATION_MS * 1000);
}
public void testGetSeekRangeOnMultiPeriodLiveWithTimeline() {
MediaPresentationDescription mpd = buildMultiPeriodLiveMpdWithTimeline();
DashChunkSource chunkSource = buildDashChunkSource(mpd);
TimeRange availableRange = chunkSource.getAvailableRange();
checkAvailableRange(availableRange, 0, MULTI_PERIOD_LIVE_DURATION_MS * 1000);
}
public void testSegmentIndexInitializationOnVod() {
DashChunkSource chunkSource = new DashChunkSource(buildVodMpd(),
DefaultDashTrackSelector.newVideoInstance(null, false, false), mock(DataSource.class),
null);
chunkSource.prepare();
chunkSource.enable(0);
List<MediaChunk> queue = new ArrayList<>();
ChunkOperationHolder out = new ChunkOperationHolder();
// request first chunk; should get back initialization chunk
chunkSource.getChunkOperation(queue, 0, 0, out);
assertNotNull(out.chunk);
assertNotNull(((InitializationChunk) out.chunk).dataSpec);
}
public void testSegmentRequestSequenceOnMultiPeriodLiveWithTimeline() {
MediaPresentationDescription mpd = buildMultiPeriodLiveMpdWithTimeline();
DashChunkSource chunkSource = buildDashChunkSource(mpd);
checkSegmentRequestSequenceOnMultiPeriodLive(chunkSource);
}
public void testSegmentRequestSequenceOnMultiPeriodLiveWithTemplate() {
MediaPresentationDescription mpd = buildMultiPeriodLiveMpdWithTemplate();
DashChunkSource chunkSource = buildDashChunkSource(mpd);
checkSegmentRequestSequenceOnMultiPeriodLive(chunkSource);
}
public void testLiveEdgeLatency() {
long availableRangeStartMs = 0;
long availableRangeEndMs = LIVE_DURATION_MS;
long seekPositionMs = LIVE_DURATION_MS;
long chunkStartTimeMs = 4000;
long chunkEndTimeMs = 5000;
// Test with 1-1000ms latency.
long liveEdgeLatency = 1;
checkLiveEdgeConsistency(LIVE_DURATION_MS, 0, liveEdgeLatency, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
liveEdgeLatency = 1000;
checkLiveEdgeConsistency(LIVE_DURATION_MS, 0, liveEdgeLatency, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
chunkStartTimeMs = 3000;
chunkEndTimeMs = 4000;
// Test with 1001-2000ms latency.
liveEdgeLatency = 1001;
checkLiveEdgeConsistency(LIVE_DURATION_MS, 0, liveEdgeLatency, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
liveEdgeLatency = 2000;
checkLiveEdgeConsistency(LIVE_DURATION_MS, 0, liveEdgeLatency, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
chunkStartTimeMs = 0;
chunkEndTimeMs = 1000;
// Test with 9001-10000 latency.
liveEdgeLatency = 9001;
checkLiveEdgeConsistency(LIVE_DURATION_MS, 0, liveEdgeLatency, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
liveEdgeLatency = 10000;
checkLiveEdgeConsistency(LIVE_DURATION_MS, 0, liveEdgeLatency, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
// Test with 10001 latency. Seek position will be bounded to the first chunk.
liveEdgeLatency = 10001;
checkLiveEdgeConsistency(LIVE_DURATION_MS, 0, liveEdgeLatency, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
}
// Private methods.
private static Representation buildVodRepresentation(Format format) {
RangedUri rangedUri = new RangedUri("https://example.com/1.mp4", null, 0, 100);
SingleSegmentBase segmentBase = new SingleSegmentBase(rangedUri, 1, 0,
"https://example.com/1.mp4", 0, -1);
return Representation.newInstance(null, 0, format, segmentBase);
}
private static Representation buildSegmentTimelineRepresentation(long timelineDurationMs,
long timelineStartTimeMs) {
List<SegmentTimelineElement> segmentTimeline = new ArrayList<>();
List<RangedUri> mediaSegments = new ArrayList<>();
long segmentStartTimeMs = timelineStartTimeMs;
long byteStart = 0;
// Create all but the last segment with LIVE_SEGMENT_DURATION_MS.
int segmentCount = (int) Util.ceilDivide(timelineDurationMs, LIVE_SEGMENT_DURATION_MS);
for (int i = 0; i < segmentCount - 1; i++) {
segmentTimeline.add(new SegmentTimelineElement(segmentStartTimeMs, LIVE_SEGMENT_DURATION_MS));
mediaSegments.add(new RangedUri("", "", byteStart, 500L));
segmentStartTimeMs += LIVE_SEGMENT_DURATION_MS;
byteStart += 500;
}
// The final segment duration is calculated so that the total duration is timelineDurationMs.
long finalSegmentDurationMs = (timelineStartTimeMs + timelineDurationMs) - segmentStartTimeMs;
segmentTimeline.add(new SegmentTimelineElement(segmentStartTimeMs, finalSegmentDurationMs));
mediaSegments.add(new RangedUri("", "", byteStart, 500L));
segmentStartTimeMs += finalSegmentDurationMs;
byteStart += 500;
// Construct the list.
MultiSegmentBase segmentBase = new SegmentList(null, 1000, 0, 0, 0, segmentTimeline,
mediaSegments);
return Representation.newInstance(null, 0, REGULAR_VIDEO, segmentBase);
}
private static Representation buildSegmentTemplateRepresentation() {
UrlTemplate initializationTemplate = null;
UrlTemplate mediaTemplate = UrlTemplate.compile("$RepresentationID$/$Number$");
MultiSegmentBase segmentBase = new SegmentTemplate(null, 1000, 0, 0, LIVE_SEGMENT_DURATION_MS,
null, initializationTemplate, mediaTemplate, "http://www.youtube.com");
return Representation.newInstance(null, 0, REGULAR_VIDEO, segmentBase);
}
private static MediaPresentationDescription buildMpd(long durationMs,
List<Representation> representations, boolean live, boolean limitTimeshiftBuffer) {
AdaptationSet adaptationSet = new AdaptationSet(0, AdaptationSet.TYPE_VIDEO, representations);
Period period = new Period(null, 0, Collections.singletonList(adaptationSet));
return new MediaPresentationDescription(AVAILABILITY_START_TIME_MS, durationMs, -1, live, -1,
(limitTimeshiftBuffer) ? LIVE_TIMESHIFT_BUFFER_DEPTH_MS : -1, null, null,
Collections.singletonList(period));
}
private static MediaPresentationDescription buildMultiPeriodMpd(long durationMs,
List<Period> periods, boolean live, boolean limitTimeshiftBuffer) {
return new MediaPresentationDescription(AVAILABILITY_START_TIME_MS, durationMs, -1, live, -1,
(limitTimeshiftBuffer) ? LIVE_TIMESHIFT_BUFFER_DEPTH_MS : -1,
null, null, periods);
}
private static MediaPresentationDescription buildVodMpd() {
List<Representation> representations = new ArrayList<>();
representations.add(buildVodRepresentation(TALL_VIDEO));
representations.add(buildVodRepresentation(WIDE_VIDEO));
return buildMpd(VOD_DURATION_MS, representations, false, false);
}
private static MediaPresentationDescription buildMultiPeriodVodMpd() {
List<Period> periods = new ArrayList<>();
long timeMs = 0;
long periodDurationMs = VOD_DURATION_MS;
for (int i = 0; i < 2; i++) {
Representation representation = buildVodRepresentation(REGULAR_VIDEO);
AdaptationSet adaptationSet = new AdaptationSet(0, AdaptationSet.TYPE_VIDEO,
Collections.singletonList(representation));
Period period = new Period(null, timeMs, Collections.singletonList(adaptationSet));
periods.add(period);
timeMs += periodDurationMs;
}
return buildMultiPeriodMpd(timeMs, periods, false, false);
}
private static MediaPresentationDescription buildLiveMpdWithTimeline(long durationMs,
long timelineStartTimeMs) {
Representation representation = buildSegmentTimelineRepresentation(
durationMs - timelineStartTimeMs, timelineStartTimeMs);
return buildMpd(durationMs, Collections.singletonList(representation), true, false);
}
private static MediaPresentationDescription buildLiveMpdWithTemplate(long durationMs,
boolean limitTimeshiftBuffer) {
Representation representation = buildSegmentTemplateRepresentation();
return buildMpd(durationMs, Collections.singletonList(representation), true,
limitTimeshiftBuffer);
}
private static MediaPresentationDescription buildMultiPeriodLiveMpdWithTimeline() {
List<Period> periods = new ArrayList<>();
long periodStartTimeMs = 0;
long periodDurationMs = LIVE_DURATION_MS;
for (int i = 0; i < MULTI_PERIOD_COUNT; i++) {
Representation representation = buildSegmentTimelineRepresentation(LIVE_DURATION_MS, 0);
AdaptationSet adaptationSet = new AdaptationSet(0, AdaptationSet.TYPE_VIDEO,
Collections.singletonList(representation));
Period period = new Period(null, periodStartTimeMs, Collections.singletonList(adaptationSet));
periods.add(period);
periodStartTimeMs += periodDurationMs;
}
return buildMultiPeriodMpd(periodDurationMs, periods, true, false);
}
private static MediaPresentationDescription buildMultiPeriodLiveMpdWithTemplate() {
List<Period> periods = new ArrayList<>();
long periodStartTimeMs = 0;
long periodDurationMs = LIVE_DURATION_MS;
for (int i = 0; i < MULTI_PERIOD_COUNT; i++) {
Representation representation = buildSegmentTemplateRepresentation();
AdaptationSet adaptationSet = new AdaptationSet(0, AdaptationSet.TYPE_VIDEO,
Collections.singletonList(representation));
Period period = new Period(null, periodStartTimeMs, Collections.singletonList(adaptationSet));
periods.add(period);
periodStartTimeMs += periodDurationMs;
}
return buildMultiPeriodMpd(MULTI_PERIOD_LIVE_DURATION_MS, periods, true, false);
}
private static DashChunkSource buildDashChunkSource(MediaPresentationDescription mpd) {
return buildDashChunkSource(mpd, false, 0);
}
private static DashChunkSource buildDashChunkSource(MediaPresentationDescription mpd,
boolean startAtLiveEdge, long liveEdgeLatencyMs) {
@SuppressWarnings("unchecked")
ManifestFetcher<MediaPresentationDescription> manifestFetcher = mock(ManifestFetcher.class);
when(manifestFetcher.getManifest()).thenReturn(mpd);
DashChunkSource chunkSource = new DashChunkSource(manifestFetcher, mpd,
DefaultDashTrackSelector.newVideoInstance(null, false, false), mock(DataSource.class), null,
new FakeClock(mpd.availabilityStartTime + mpd.duration - ELAPSED_REALTIME_OFFSET_MS),
liveEdgeLatencyMs * 1000, ELAPSED_REALTIME_OFFSET_MS * 1000, startAtLiveEdge, null, null);
chunkSource.prepare();
chunkSource.enable(0);
return chunkSource;
}
private static void checkAvailableRange(TimeRange seekRange, long startTimeUs, long endTimeUs) {
long[] seekRangeValuesUs = seekRange.getCurrentBoundsUs(null);
assertEquals(startTimeUs, seekRangeValuesUs[0]);
assertEquals(endTimeUs, seekRangeValuesUs[1]);
}
private static void checkLiveEdgeConsistency(long durationMs, long timelineStartMs,
long liveEdgeLatencyMs, long seekPositionMs, long availableRangeStartMs,
long availableRangeEndMs, long chunkStartTimeMs, long chunkEndTimeMs) {
checkLiveEdgeConsistencyWithTimeline(durationMs, timelineStartMs, liveEdgeLatencyMs,
seekPositionMs, availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs,
chunkEndTimeMs);
checkLiveEdgeConsistencyWithTemplateAndUnlimitedTimeshift(durationMs, liveEdgeLatencyMs,
seekPositionMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
checkLiveEdgeConsistencyWithTemplateAndLimitedTimeshift(durationMs, liveEdgeLatencyMs,
seekPositionMs, availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs,
chunkEndTimeMs);
}
private static void checkLiveEdgeConsistencyWithTimeline(long durationMs, long timelineStartMs,
long liveEdgeLatencyMs, long seekPositionMs, long availableRangeStartMs,
long availableRangeEndMs, long chunkStartTimeMs, long chunkEndTimeMs) {
MediaPresentationDescription mpd = buildLiveMpdWithTimeline(durationMs, timelineStartMs);
checkLiveEdgeConsistency(mpd, liveEdgeLatencyMs, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
}
private static void checkLiveEdgeConsistencyWithTemplateAndUnlimitedTimeshift(long durationMs,
long liveEdgeLatencyMs, long availablePositionMs, long availableRangeEndMs,
long chunkStartTimeMs, long chunkEndTimeMs) {
MediaPresentationDescription mpd = buildLiveMpdWithTemplate(durationMs, false);
checkLiveEdgeConsistency(mpd, liveEdgeLatencyMs, availablePositionMs, 0,
availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
}
private static void checkLiveEdgeConsistencyWithTemplateAndLimitedTimeshift(long durationMs,
long liveEdgeLatencyMs, long seekPositionMs, long availableRangeStartMs,
long availableRangeEndMs, long chunkStartTimeMs, long chunkEndTimeMs) {
MediaPresentationDescription mpd = buildLiveMpdWithTemplate(durationMs, true);
checkLiveEdgeConsistency(mpd, liveEdgeLatencyMs, seekPositionMs, availableRangeStartMs,
availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
}
private static void checkLiveEdgeConsistency(MediaPresentationDescription mpd,
long liveEdgeLatencyMs, long seekPositionMs, long availableRangeStartMs,
long availableRangeEndMs, long chunkStartTimeMs, long chunkEndTimeMs) {
DashChunkSource chunkSource = buildDashChunkSource(mpd, true, liveEdgeLatencyMs);
List<MediaChunk> queue = new ArrayList<>();
ChunkOperationHolder out = new ChunkOperationHolder();
checkLiveEdgeConsistency(chunkSource, queue, out, seekPositionMs, availableRangeStartMs,
availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
}
private static void checkLiveEdgeConsistency(DashChunkSource chunkSource, List<MediaChunk> queue,
ChunkOperationHolder out, long seekPositionMs, long availableRangeStartMs,
long availableRangeEndMs, long chunkStartTimeMs, long chunkEndTimeMs) {
chunkSource.getChunkOperation(queue, seekPositionMs * 1000, 0, out);
TimeRange availableRange = chunkSource.getAvailableRange();
checkAvailableRange(availableRange, availableRangeStartMs * 1000, availableRangeEndMs * 1000);
if (chunkStartTimeMs < availableRangeEndMs) {
assertNotNull(out.chunk);
assertEquals(chunkStartTimeMs * 1000, ((MediaChunk) out.chunk).startTimeUs);
assertEquals(chunkEndTimeMs * 1000, ((MediaChunk) out.chunk).endTimeUs);
} else {
assertNull(out.chunk);
}
}
private static void checkSegmentRequestSequenceOnMultiPeriodLive(DashChunkSource chunkSource) {
List<MediaChunk> queue = new ArrayList<>();
ChunkOperationHolder out = new ChunkOperationHolder();
long seekPositionMs = 0;
long availableRangeStartMs = 0;
long availableRangeEndMs = MULTI_PERIOD_LIVE_DURATION_MS;
long chunkStartTimeMs = 0;
long chunkEndTimeMs = 1000;
// request first chunk
checkLiveEdgeConsistency(chunkSource, queue, out, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
queue.add((MediaChunk) out.chunk);
// request second chunk
chunkStartTimeMs += 1000;
chunkEndTimeMs += 1000;
out.chunk = null;
checkLiveEdgeConsistency(chunkSource, queue, out, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
queue.add((MediaChunk) out.chunk);
// request third chunk
chunkStartTimeMs += 1000;
chunkEndTimeMs += 1000;
out.chunk = null;
checkLiveEdgeConsistency(chunkSource, queue, out, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
queue.add((MediaChunk) out.chunk);
// request fourth chunk
chunkStartTimeMs += 1000;
chunkEndTimeMs += 1000;
out.chunk = null;
checkLiveEdgeConsistency(chunkSource, queue, out, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
queue.add((MediaChunk) out.chunk);
// request fifth chunk
chunkStartTimeMs += 1000;
chunkEndTimeMs += 1000;
out.chunk = null;
checkLiveEdgeConsistency(chunkSource, queue, out, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
queue.add((MediaChunk) out.chunk);
// request sixth chunk; this is the first chunk in the 2nd period
chunkStartTimeMs += 1000;
chunkEndTimeMs += 1000;
out.chunk = null;
checkLiveEdgeConsistency(chunkSource, queue, out, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
queue.add((MediaChunk) out.chunk);
// request seventh chunk;
chunkStartTimeMs += 1000;
chunkEndTimeMs += 1000;
out.chunk = null;
checkLiveEdgeConsistency(chunkSource, queue, out, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
queue.add((MediaChunk) out.chunk);
// request eigth chunk
chunkStartTimeMs += 1000;
chunkEndTimeMs += 1000;
out.chunk = null;
checkLiveEdgeConsistency(chunkSource, queue, out, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
queue.add((MediaChunk) out.chunk);
// request ninth chunk
chunkStartTimeMs += 1000;
chunkEndTimeMs += 1000;
out.chunk = null;
checkLiveEdgeConsistency(chunkSource, queue, out, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
queue.add((MediaChunk) out.chunk);
// request tenth chunk
chunkStartTimeMs += 1000;
chunkEndTimeMs += 1000;
out.chunk = null;
checkLiveEdgeConsistency(chunkSource, queue, out, seekPositionMs,
availableRangeStartMs, availableRangeEndMs, chunkStartTimeMs, chunkEndTimeMs);
queue.add((MediaChunk) out.chunk);
// request "eleventh" chunk; this chunk isn't available yet, so we should get null
out.chunk = null;
chunkSource.getChunkOperation(queue, seekPositionMs * 1000, 0, out);
assertNull(out.chunk);
}
}
| 23,146
|
Java
|
.java
| 430
| 48.809302
| 100
| 0.780284
|
AgnitumuS/TV-App
| 2
| 1
| 0
|
GPL-2.0
|
9/5/2024, 12:05:36 AM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 23,146
|
3,208,442
|
JAMWikiListener.java
|
node_jamwiki/jamwiki-web/src/main/java/org/jamwiki/servlets/JAMWikiListener.java
|
/**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License as published by the Free Software Foundation;
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.servlets;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.jamwiki.db.WikiDatabase;
import org.jamwiki.utils.WikiCache;
import org.jamwiki.utils.WikiUtil;
/**
* A ServletContextListener that will do necessary initialization
* and cleanup when the Servlet Context is initialized and destroyed.
*/
public class JAMWikiListener implements ServletContextListener {
/**
* Initialize the database connection pool and disk cache.
*
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent arg0) {
if (!WikiUtil.isFirstUse()) {
WikiDatabase.initialize();
WikiCache.initialize();
}
}
/**
* Clean up the database connection pool and disk cache.
*
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent arg0) {
WikiDatabase.shutdown();
WikiCache.shutdown();
}
}
| 1,851
|
Java
|
.java
| 48
| 36.333333
| 99
| 0.789327
|
node/jamwiki
| 4
| 5
| 0
|
LGPL-3.0
|
9/4/2024, 11:05:15 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 1,851
|
2,672,848
|
BlockSeaLantern.java
|
bergerkiller_SpigotSource/src/main/java/net/minecraft/server/BlockSeaLantern.java
|
package net.minecraft.server;
import java.util.Random;
public class BlockSeaLantern extends Block {
public BlockSeaLantern(Material material) {
super(material);
this.a(CreativeModeTab.b);
}
public int a(Random random) {
return 2 + random.nextInt(2);
}
public int getDropCount(int i, Random random) {
return MathHelper.clamp(this.a(random) + random.nextInt(i + 1), 1, 5);
}
public Item getDropType(IBlockData iblockdata, Random random, int i) {
return Items.PRISMARINE_CRYSTALS;
}
public MaterialMapColor r(IBlockData iblockdata) {
return MaterialMapColor.p;
}
protected boolean o() {
return true;
}
}
| 713
|
Java
|
.java
| 23
| 25.130435
| 78
| 0.677419
|
bergerkiller/SpigotSource
| 6
| 4
| 0
|
GPL-3.0
|
9/4/2024, 10:04:08 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 713
|
661,198
|
package-info.java
|
LoveMyOrange_ding-flowable-vue2-enhance/YuDao/Camunda/ruoyi-vue-pro/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/convert/package-info.java
|
/**
* 提供 POJO 类的实体转换
*
* 目前使用 MapStruct 框架
*/
package cn.iocoder.yudao.module.bpm.convert;
| 123
|
Java
|
.java
| 6
| 14.166667
| 44
| 0.719101
|
LoveMyOrange/ding-flowable-vue2-enhance
| 114
| 11
| 1
|
GPL-3.0
|
9/4/2024, 7:08:18 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 95
|
4,924,139
|
HFR4droidException.java
|
Draluy_HFRFirefoxOS/resources/hfr4droid-read-only/hfr4droidCommon/src/info/toyonos/hfr4droid/common/HFR4droidException.java
|
package info.toyonos.hfr4droid.common;
public class HFR4droidException extends Exception
{
private static final long serialVersionUID = 6776619174712533182L;
public HFR4droidException()
{
super();
}
public HFR4droidException(String detailMessage)
{
super(detailMessage);
}
public HFR4droidException(String detailMessage, Throwable throwable)
{
super(detailMessage, throwable);
}
public HFR4droidException(Throwable throwable)
{
super(throwable);
}
}
| 500
|
Java
|
.java
| 21
| 20.428571
| 70
| 0.787234
|
Draluy/HFRFirefoxOS
| 1
| 0
| 0
|
GPL-2.0
|
9/5/2024, 12:36:02 AM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 500
|
4,701,532
|
SelfAuthenticationApiResource.java
|
openMF_selfservice-plugin/src/main/java/org/apache/fineract/portfolio/self/security/api/SelfAuthenticationApiResource.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.portfolio.self.security.api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import lombok.RequiredArgsConstructor;
import org.apache.fineract.infrastructure.security.api.AuthenticationApiResource;
import org.apache.fineract.infrastructure.security.api.AuthenticationApiResourceSwagger;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
@Component
@ConditionalOnProperty("fineract.security.basicauth.enabled")
@Path("/v1/self/authentication")
@Tag(name = "Self Authentication", description = "Authenticates the credentials provided and returns the set roles and permissions allowed")
@RequiredArgsConstructor
public class SelfAuthenticationApiResource {
private final AuthenticationApiResource authenticationApiResource;
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@Operation(summary = "Verify authentication", description = "Authenticates the credentials provided and returns the set roles and permissions allowed.\n\n"
+ "Please visit this link for more info - https://fineract.apache.org/legacy-docs/apiLive.htm#selfbasicauth")
@RequestBody(required = true, content = @Content(schema = @Schema(implementation = AuthenticationApiResourceSwagger.PostAuthenticationRequest.class)))
@ApiResponses({
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = SelfAuthenticationApiResourceSwagger.PostSelfAuthenticationResponse.class))) })
public String authenticate(final String apiRequestBodyAsJson) {
return this.authenticationApiResource.authenticate(apiRequestBodyAsJson, true);
}
}
| 3,046
|
Java
|
.java
| 55
| 52.763636
| 199
| 0.807834
|
openMF/selfservice-plugin
| 2
| 4
| 11
|
MPL-2.0
|
9/5/2024, 12:21:59 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| true
| true
| 3,046
|
1,135,922
|
FNEG.java
|
kilograham_jpsx/external/bcel-5.1/src/java/org/apache/bcel/generic/FNEG.java
|
package org.apache.bcel.generic;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache BCEL" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* "Apache BCEL", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* FNEG - Negate float
* <PRE>Stack: ..., value -> ..., result</PRE>
*
* @version $Id: FNEG.java,v 1.1.1.1 2001/10/29 20:00:12 jvanzyl Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
*/
public class FNEG extends ArithmeticInstruction {
public FNEG() {
super(org.apache.bcel.Constants.FNEG);
}
/**
* Call corresponding visitor method(s). The order is:
* Call visitor methods of implemented interfaces first, then
* call methods according to the class hierarchy in descending order,
* i.e., the most specific visitXXX() call comes last.
*
* @param v Visitor object
*/
public void accept(Visitor v) {
v.visitTypedInstruction(this);
v.visitStackProducer(this);
v.visitStackConsumer(this);
v.visitArithmeticInstruction(this);
v.visitFNEG(this);
}
}
| 3,535
|
Java
|
.java
| 81
| 41.185185
| 73
| 0.715652
|
kilograham/jpsx
| 35
| 6
| 3
|
GPL-3.0
|
9/4/2024, 7:15:37 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 3,535
|
2,961,651
|
ShardMapping.java
|
JuanJoseFJ_ProyectoPacientes/mysql-connector-java-5.1.43/src/com/mysql/fabric/ShardMapping.java
|
/*
Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/J is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.
There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
this software, see the FOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
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.
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 St, Fifth
Floor, Boston, MA 02110-1301 USA
*/
package com.mysql.fabric;
import java.util.Collections;
import java.util.Set;
/**
* A shard mapping representing this set of sharded data.
*/
public abstract class ShardMapping {
private int mappingId;
private ShardingType shardingType;
private String globalGroupName;
protected Set<ShardTable> shardTables;
protected Set<ShardIndex> shardIndices;
public ShardMapping(int mappingId, ShardingType shardingType, String globalGroupName, Set<ShardTable> shardTables, Set<ShardIndex> shardIndices) {
this.mappingId = mappingId;
this.shardingType = shardingType;
this.globalGroupName = globalGroupName;
this.shardTables = shardTables;
this.shardIndices = shardIndices;
}
/**
* Lookup the server group that stores the given key.
*/
public String getGroupNameForKey(String key) {
return getShardIndexForKey(key).getGroupName();
}
/**
* Decide which shard index stores the given key.
*/
protected abstract ShardIndex getShardIndexForKey(String key);
/**
* The ID of this mapping.
*/
public int getMappingId() {
return this.mappingId;
}
/**
* The {@link ShardingType} of this mapping.
*/
public ShardingType getShardingType() {
return this.shardingType;
}
/**
* The name of the global group for this shard map.
*/
public String getGlobalGroupName() {
return this.globalGroupName;
}
/**
* Return the set of tables sharded in this mapping.
*/
public Set<ShardTable> getShardTables() {
return Collections.unmodifiableSet(this.shardTables);
}
/**
* Return the set of shards in this mapping.
*/
public Set<ShardIndex> getShardIndices() {
return Collections.unmodifiableSet(this.shardIndices);
}
}
| 2,957
|
Java
|
.java
| 77
| 33.311688
| 150
| 0.723464
|
JuanJoseFJ/ProyectoPacientes
| 5
| 1
| 0
|
GPL-3.0
|
9/4/2024, 10:38:53 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 2,957
|
110,127
|
Encryption.java
|
guang19_framework-learning/tomcat9.0-source/java/org/apache/tomcat/util/net/openssl/ciphers/Encryption.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.util.net.openssl.ciphers;
enum Encryption {
AES128,
AES128CCM,
AES128CCM8,
AES128GCM,
AES256,
AES256CCM,
AES256CCM8,
AES256GCM,
ARIA128GCM,
ARIA256GCM,
CAMELLIA256,
CAMELLIA128,
CHACHA20POLY1305,
TRIPLE_DES,
DES,
IDEA,
eGOST2814789CNT,
SEED,
FZA,
RC4,
RC2,
eNULL
}
| 1,195
|
Java
|
.java
| 41
| 25.585366
| 76
| 0.728299
|
guang19/framework-learning
| 1,174
| 238
| 8
|
GPL-3.0
|
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| true
| true
| true
| 1,195
|
1,203,485
|
JvmRTClassPathEntryImpl.java
|
keerath_openjdk-8-source/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmRTClassPathEntryImpl.java
|
/*
* Copyright (c) 2004, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.management.snmp.jvminstr;
// java imports
//
import java.io.Serializable;
// jmx imports
//
import com.sun.jmx.snmp.SnmpStatusException;
// jdmk imports
//
import com.sun.jmx.snmp.agent.SnmpMib;
import sun.management.snmp.jvmmib.JvmRTClassPathEntryMBean;
/**
* The class is used for implementing the "JvmRTClassPathEntry" group.
*/
public class JvmRTClassPathEntryImpl implements JvmRTClassPathEntryMBean,
Serializable {
static final long serialVersionUID = 8524792845083365742L;
private final String item;
private final int index;
/**
* Constructor for the "JvmRTClassPathEntry" group.
*/
public JvmRTClassPathEntryImpl(String item, int index) {
this.item = validPathElementTC(item);
this.index = index;
}
private String validPathElementTC(String str) {
return JVM_MANAGEMENT_MIB_IMPL.validPathElementTC(str);
}
/**
* Getter for the "JvmRTClassPathItem" variable.
*/
public String getJvmRTClassPathItem() throws SnmpStatusException {
return item;
}
/**
* Getter for the "JvmRTClassPathIndex" variable.
*/
public Integer getJvmRTClassPathIndex() throws SnmpStatusException {
return new Integer(index);
}
}
| 2,518
|
Java
|
.java
| 66
| 33.969697
| 79
| 0.736583
|
keerath/openjdk-8-source
| 39
| 26
| 0
|
GPL-2.0
|
9/4/2024, 7:24:11 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 2,518
|
2,360,720
|
NameSection.java
|
OpenSoftwareSolutions_PDFReporter-Studio/com.jaspersoft.studio.components/src/com/jaspersoft/studio/components/section/name/NameSection.java
|
/*******************************************************************************
* Copyright (C) 2005 - 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 and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package com.jaspersoft.studio.components.section.name;
import java.util.HashMap;
import net.sf.jasperreports.components.headertoolbar.HeaderToolbarElement;
import net.sf.jasperreports.engine.JRPropertiesMap;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import com.jaspersoft.studio.components.crosstab.model.MCrosstab;
import com.jaspersoft.studio.components.list.model.MList;
import com.jaspersoft.studio.components.table.model.MTable;
import com.jaspersoft.studio.model.ANode;
import com.jaspersoft.studio.model.APropertyNode;
import com.jaspersoft.studio.model.MGraphicElement;
import com.jaspersoft.studio.properties.view.TabbedPropertySheetPage;
import com.jaspersoft.studio.property.descriptors.JSSTextPropertyDescriptor;
import com.jaspersoft.studio.property.section.AbstractSection;
import com.jaspersoft.studio.property.section.widgets.SPText;
public class NameSection extends AbstractSection {
private JSSTextPropertyDescriptor pd;
private static HashMap<Class<?>, String> namePropertyMap;
static{
namePropertyMap = new HashMap<Class<?>, String>();
namePropertyMap.put(MTable.class, HeaderToolbarElement.PROPERTY_TABLE_NAME);
namePropertyMap.put(MList.class, HeaderToolbarElement.PROPERTY_TABLE_NAME);
namePropertyMap.put(MCrosstab.class, HeaderToolbarElement.PROPERTY_TABLE_NAME);
}
public NameSection() {
super();
pd = new JSSTextPropertyDescriptor(MGraphicElement.PROPERTY_MAP, "Name");
pd.setDescription("Name");
}
@Override
protected void initializeProvidedProperties() {
super.initializeProvidedProperties();
addProvidedProperties(MGraphicElement.PROPERTY_MAP, "Name");
}
protected String getPropertyId(){
ANode node = getSelectedElement();
if (node != null){
return namePropertyMap.get(node.getClass());
}
return null;
}
public static String getNamePropertyId(ANode node){
if (node != null){
return namePropertyMap.get(node.getClass());
}
return null;
}
@Override
public void createControls(Composite parent, TabbedPropertySheetPage aTabbedPropertySheetPage) {
super.createControls(parent, aTabbedPropertySheetPage);
parent = getWidgetFactory().createComposite(parent);
parent.setLayout(new GridLayout(2,false));
parent.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
getWidgetFactory().createCLabel(parent, "Name", SWT.RIGHT);
widgets.put(pd.getId(), new SPText(parent, this, pd) {
@Override
protected String getCurrentValue() {
JRPropertiesMap pmap = (JRPropertiesMap) section.getElement().getPropertyValue(pDescriptor.getId());
String propertyName = getPropertyId();
return (String) pmap.getProperty(propertyName);
}
protected void handleTextChanged(final AbstractSection section, final Object property, String text) {
String propertyName = getPropertyId();
if (propertyName != null){
JRPropertiesMap pmap = (JRPropertiesMap) pnode.getPropertyValue(MGraphicElement.PROPERTY_MAP);
pmap = (JRPropertiesMap) pmap.clone();
pmap.setProperty(propertyName, text);
section.changeProperty(MGraphicElement.PROPERTY_MAP, pmap);
}
}
@Override
public void setData(APropertyNode pnode, Object b) {
if (b instanceof JRPropertiesMap) {
JRPropertiesMap map = (JRPropertiesMap) b;
String propertyName = getPropertyId();
String name = map.getProperty(propertyName);
super.setData(pnode, name);
}
}
});
}
}
| 4,122
|
Java
|
.java
| 97
| 39.412371
| 104
| 0.76175
|
OpenSoftwareSolutions/PDFReporter-Studio
| 8
| 8
| 0
|
LGPL-3.0
|
9/4/2024, 9:12:18 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 4,122
|
2,832,654
|
TimeModel.java
|
umerov1999_ProjectF/material/java/com/google/android/material/timepicker/TimeModel.java
|
/*
* Copyright (C) 2020 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.google.android.material.timepicker;
import com.google.android.material.R;
import static com.google.android.material.timepicker.TimeFormat.CLOCK_12H;
import static com.google.android.material.timepicker.TimeFormat.CLOCK_24H;
import static java.util.Calendar.AM;
import static java.util.Calendar.HOUR;
import static java.util.Calendar.PM;
import android.content.res.Resources;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.IntRange;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import com.google.android.material.timepicker.TimePickerControls.ActiveSelection;
import com.google.android.material.timepicker.TimePickerControls.ClockPeriod;
import java.util.Arrays;
/** The representation of the TimeModel used by TimePicker views. */
class TimeModel implements Parcelable {
public static final String ZERO_LEADING_NUMBER_FORMAT = "%02d";
public static final String NUMBER_FORMAT = "%d";
private final MaxInputValidator minuteInputValidator;
private final MaxInputValidator hourInputValidator;
@TimeFormat final int format;
int hour;
int minute;
@ActiveSelection int selection;
@ClockPeriod int period;
public TimeModel() {
this(CLOCK_12H);
}
public TimeModel(@TimeFormat int format) {
this(0, 0, HOUR, format);
}
public TimeModel(int hour, int minute, @ActiveSelection int selection, @TimeFormat int format) {
this.hour = hour;
this.minute = minute;
this.selection = selection;
this.format = format;
period = getPeriod(hour);
minuteInputValidator = new MaxInputValidator(59);
hourInputValidator = new MaxInputValidator(format == CLOCK_24H ? 23 : 12);
}
protected TimeModel(Parcel in) {
this(in.readInt(), in.readInt(), in.readInt(), in.readInt());
}
/** Set hour respecting the current clock period */
public void setHourOfDay(int hour) {
period = getPeriod(hour);
this.hour = hour;
}
@ClockPeriod
private static int getPeriod(int hourOfDay) {
return hourOfDay >= 12 ? PM : AM;
}
/** Set hour respecting the current clock period */
public void setHour(int hour) {
if (format == CLOCK_24H) {
this.hour = hour;
return;
}
this.hour = hour % 12 + (period == PM ? 12 : 0);
}
public void setMinute(@IntRange(from = 0, to = 59) int minute) {
this.minute = minute % 60;
}
public int getHourForDisplay() {
if (format == CLOCK_24H) {
return hour % 24;
}
if (hour % 12 == 0) {
return 12;
}
if (period == PM) {
return hour - 12;
}
return hour;
}
@StringRes
public int getHourContentDescriptionResId() {
return format == CLOCK_24H ? R.string.material_hour_24h_suffix : R.string.material_hour_suffix;
}
public MaxInputValidator getMinuteInputValidator() {
return minuteInputValidator;
}
public MaxInputValidator getHourInputValidator() {
return hourInputValidator;
}
@Override
public int hashCode() {
Object[] hashedFields = {format, hour, minute, selection};
return Arrays.hashCode(hashedFields);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TimeModel)) {
return false;
}
TimeModel that = (TimeModel) o;
return hour == that.hour
&& minute == that.minute
&& format == that.format
&& selection == that.selection;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(hour);
dest.writeInt(minute);
dest.writeInt(selection);
dest.writeInt(format);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<TimeModel> CREATOR = new Parcelable.Creator<TimeModel>() {
@Override
public TimeModel createFromParcel(Parcel in) {
return new TimeModel(in);
}
@Override
public TimeModel[] newArray(int size) {
return new TimeModel[size];
}
};
public void setPeriod(@ClockPeriod int period) {
if (period != this.period) {
this.period = period;
if (hour < 12 && period == PM) {
hour += 12;
} else if (hour >= 12 && period == AM) {
hour -= 12;
}
}
}
@Nullable
public static String formatText(Resources resources, CharSequence text) {
return formatText(resources, text, ZERO_LEADING_NUMBER_FORMAT);
}
@Nullable
public static String formatText(Resources resources, CharSequence text, String format) {
try {
return String.format(
resources.getConfiguration().locale, format, Integer.parseInt(String.valueOf(text)));
} catch (NumberFormatException e) {
return null;
}
}
}
| 5,379
|
Java
|
.java
| 167
| 28.101796
| 99
| 0.710918
|
umerov1999/ProjectF
| 6
| 0
| 0
|
GPL-3.0
|
9/4/2024, 10:19:49 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| true
| true
| true
| 5,379
|
1,078,212
|
SplitTest.java
|
CyanogenMod_android_libcore/luni/src/test/java/org/apache/harmony/regex/tests/java/util/regex/SplitTest.java
|
package org.apache.harmony.regex.tests.java.util.regex;
import junit.framework.TestCase;
import java.util.regex.*;
/**
* TODO Type description
*
*/
public class SplitTest extends TestCase {
public void testSimple() {
Pattern p = Pattern.compile("/");
String[] results = p.split("have/you/done/it/right");
String[] expected = new String[] { "have", "you", "done", "it", "right" };
assertArraysEqual(expected, results);
}
public void testEmptySplits() {
// Trailing empty matches are removed.
assertArraysEqual(new String[0], "hello".split("."));
assertArraysEqual(new String[] { "1", "2" }, "1:2:".split(":"));
// ...including when that results in an empty result.
assertArraysEqual(new String[0], ":".split(":"));
// ...but not when limit < 0.
assertArraysEqual(new String[] { "1", "2", "" }, "1:2:".split(":", -1));
// Leading empty matches are retained.
assertArraysEqual(new String[] { "", "", "o" }, "hello".split(".."));
// A separator that doesn't occur in the input gets you the input.
assertArraysEqual(new String[] { "hello" }, "hello".split("not-present-in-test"));
// ...including when the input is the empty string.
// (Perl returns an empty list instead.)
assertArraysEqual(new String[] { "" }, "".split("not-present-in-test"));
assertArraysEqual(new String[] { "" }, "".split("A?"));
// The limit argument controls the size of the result.
// If l == 0, the result is as long as needed, except trailing empty matches are dropped.
// If l < 0, the result is as long as needed, and trailing empty matches are retained.
// If l > 0, the result contains the first l matches, plus one string containing the remaining input.
// Examples without a trailing separator (and hence without a trailing empty match):
assertArraysEqual(new String[] { "a", "b", "c" }, "a,b,c".split(",", 0));
assertArraysEqual(new String[] { "a,b,c" }, "a,b,c".split(",", 1));
assertArraysEqual(new String[] { "a", "b,c" }, "a,b,c".split(",", 2));
assertArraysEqual(new String[] { "a", "b", "c" }, "a,b,c".split(",", 3));
assertArraysEqual(new String[] { "a", "b", "c" }, "a,b,c".split(",", Integer.MAX_VALUE));
// Examples with a trailing separator (and hence possibly with a trailing empty match):
assertArraysEqual(new String[] { "a", "b", "c" }, "a,b,c,".split(",", 0));
assertArraysEqual(new String[] { "a,b,c," }, "a,b,c,".split(",", 1));
assertArraysEqual(new String[] { "a", "b,c," }, "a,b,c,".split(",", 2));
assertArraysEqual(new String[] { "a", "b", "c," }, "a,b,c,".split(",", 3));
assertArraysEqual(new String[] { "a", "b", "c", "" }, "a,b,c,".split(",", Integer.MAX_VALUE));
assertArraysEqual(new String[] { "a", "b", "c", "" }, "a,b,c,".split(",", -1));
}
private void assertArraysEqual(String[] expected, String[] actual) {
assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
assertEquals(Integer.toString(i), expected[i], actual[i]);
}
}
public void testSplit1() throws PatternSyntaxException {
Pattern p = Pattern.compile(" ");
String input = "poodle zoo";
String tokens[];
tokens = p.split(input, 1);
assertEquals(1, tokens.length);
assertTrue(tokens[0].equals(input));
tokens = p.split(input, 2);
assertEquals(2, tokens.length);
assertEquals("poodle", tokens[0]);
assertEquals("zoo", tokens[1]);
tokens = p.split(input, 5);
assertEquals(2, tokens.length);
assertEquals("poodle", tokens[0]);
assertEquals("zoo", tokens[1]);
tokens = p.split(input, -2);
assertEquals(2, tokens.length);
assertEquals("poodle", tokens[0]);
assertEquals("zoo", tokens[1]);
tokens = p.split(input, 0);
assertEquals(2, tokens.length);
assertEquals("poodle", tokens[0]);
assertEquals("zoo", tokens[1]);
tokens = p.split(input);
assertEquals(2, tokens.length);
assertEquals("poodle", tokens[0]);
assertEquals("zoo", tokens[1]);
p = Pattern.compile("d");
tokens = p.split(input, 1);
assertEquals(1, tokens.length);
assertTrue(tokens[0].equals(input));
tokens = p.split(input, 2);
assertEquals(2, tokens.length);
assertEquals("poo", tokens[0]);
assertEquals("le zoo", tokens[1]);
tokens = p.split(input, 5);
assertEquals(2, tokens.length);
assertEquals("poo", tokens[0]);
assertEquals("le zoo", tokens[1]);
tokens = p.split(input, -2);
assertEquals(2, tokens.length);
assertEquals("poo", tokens[0]);
assertEquals("le zoo", tokens[1]);
tokens = p.split(input, 0);
assertEquals(2, tokens.length);
assertEquals("poo", tokens[0]);
assertEquals("le zoo", tokens[1]);
tokens = p.split(input);
assertEquals(2, tokens.length);
assertEquals("poo", tokens[0]);
assertEquals("le zoo", tokens[1]);
p = Pattern.compile("o");
tokens = p.split(input, 1);
assertEquals(1, tokens.length);
assertTrue(tokens[0].equals(input));
tokens = p.split(input, 2);
assertEquals(2, tokens.length);
assertEquals("p", tokens[0]);
assertEquals("odle zoo", tokens[1]);
tokens = p.split(input, 5);
assertEquals(5, tokens.length);
assertEquals("p", tokens[0]);
assertTrue(tokens[1].equals(""));
assertEquals("dle z", tokens[2]);
assertTrue(tokens[3].equals(""));
assertTrue(tokens[4].equals(""));
tokens = p.split(input, -2);
assertEquals(5, tokens.length);
assertEquals("p", tokens[0]);
assertTrue(tokens[1].equals(""));
assertEquals("dle z", tokens[2]);
assertTrue(tokens[3].equals(""));
assertTrue(tokens[4].equals(""));
tokens = p.split(input, 0);
assertEquals(3, tokens.length);
assertEquals("p", tokens[0]);
assertTrue(tokens[1].equals(""));
assertEquals("dle z", tokens[2]);
tokens = p.split(input);
assertEquals(3, tokens.length);
assertEquals("p", tokens[0]);
assertTrue(tokens[1].equals(""));
assertEquals("dle z", tokens[2]);
}
public void testSplit2() {
Pattern p = Pattern.compile("");
String s[];
s = p.split("a", -1);
assertEquals(3, s.length);
assertEquals("", s[0]);
assertEquals("a", s[1]);
assertEquals("", s[2]);
s = p.split("", -1);
assertEquals(1, s.length);
assertEquals("", s[0]);
s = p.split("abcd", -1);
assertEquals(6, s.length);
assertEquals("", s[0]);
assertEquals("a", s[1]);
assertEquals("b", s[2]);
assertEquals("c", s[3]);
assertEquals("d", s[4]);
assertEquals("", s[5]);
// Regression test for Android
assertEquals("GOOG,23,500".split("|").length, 12);
}
public void testSplitSupplementaryWithEmptyString() {
/*
* See http://www.unicode.org/reports/tr18/#Supplementary_Characters
* We have to treat text as code points not code units.
*/
Pattern p = Pattern.compile("");
String s[];
s = p.split("a\ud869\uded6b", -1);
assertEquals(5, s.length);
assertEquals("", s[0]);
assertEquals("a", s[1]);
assertEquals("\ud869\uded6", s[2]);
assertEquals("b", s[3]);
assertEquals("", s[4]);
}
}
| 7,813
|
Java
|
.java
| 176
| 35.897727
| 109
| 0.570772
|
CyanogenMod/android_libcore
| 44
| 172
| 0
|
GPL-2.0
|
9/4/2024, 7:11:02 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 7,813
|
2,059,380
|
JsonMappingGen.java
|
timscriptov_ZGNB-Manager-2/jadx-1.2.0/src/main/java/jadx/core/codegen/json/JsonMappingGen.java
|
package jadx.core.codegen.json;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import jadx.api.JadxArgs;
import jadx.core.codegen.json.mapping.JsonClsMapping;
import jadx.core.codegen.json.mapping.JsonFieldMapping;
import jadx.core.codegen.json.mapping.JsonMapping;
import jadx.core.codegen.json.mapping.JsonMthMapping;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.core.utils.files.FileUtils;
public class JsonMappingGen {
private static final Logger LOG = LoggerFactory.getLogger(JsonMappingGen.class);
private static final Gson GSON = new GsonBuilder()
.setPrettyPrinting()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES)
.disableHtmlEscaping()
.create();
public static void dump(RootNode root) {
JsonMapping mapping = new JsonMapping();
fillMapping(mapping, root);
JadxArgs args = root.getArgs();
File outDirSrc = args.getOutDirSrc().getAbsoluteFile();
File mappingFile = new File(outDirSrc, "mapping.json");
FileUtils.makeDirsForFile(mappingFile);
try (Writer writer = new FileWriter(mappingFile)) {
GSON.toJson(mapping, writer);
LOG.info("Save mappings to {}", mappingFile.getAbsolutePath());
} catch (Exception e) {
throw new JadxRuntimeException("Failed to save mapping json", e);
}
}
private static void fillMapping(JsonMapping mapping, RootNode root) {
List<ClassNode> classes = root.getClasses(true);
mapping.setClasses(new ArrayList<>(classes.size()));
for (ClassNode cls : classes) {
ClassInfo classInfo = cls.getClassInfo();
JsonClsMapping jsonCls = new JsonClsMapping();
jsonCls.setName(classInfo.getRawName());
jsonCls.setAlias(classInfo.getAliasFullName());
jsonCls.setInner(classInfo.isInner());
jsonCls.setJson(cls.getTopParentClass().getClassInfo().getAliasFullPath() + ".json");
if (classInfo.isInner()) {
jsonCls.setTopClass(cls.getTopParentClass().getClassInfo().getFullName());
}
addFields(cls, jsonCls);
addMethods(cls, jsonCls);
mapping.getClasses().add(jsonCls);
}
}
private static void addMethods(ClassNode cls, JsonClsMapping jsonCls) {
List<MethodNode> methods = cls.getMethods();
if (methods.isEmpty()) {
return;
}
jsonCls.setMethods(new ArrayList<>(methods.size()));
for (MethodNode method : methods) {
JsonMthMapping jsonMethod = new JsonMthMapping();
MethodInfo methodInfo = method.getMethodInfo();
jsonMethod.setSignature(methodInfo.getShortId());
jsonMethod.setName(methodInfo.getName());
jsonMethod.setAlias(methodInfo.getAlias());
jsonMethod.setOffset("0x" + Long.toHexString(method.getMethodCodeOffset()));
jsonCls.getMethods().add(jsonMethod);
}
}
private static void addFields(ClassNode cls, JsonClsMapping jsonCls) {
List<FieldNode> fields = cls.getFields();
if (fields.isEmpty()) {
return;
}
jsonCls.setFields(new ArrayList<>(fields.size()));
for (FieldNode field : fields) {
JsonFieldMapping jsonField = new JsonFieldMapping();
jsonField.setName(field.getName());
jsonField.setAlias(field.getAlias());
jsonCls.getFields().add(jsonField);
}
}
private JsonMappingGen() {
}
}
| 3,592
|
Java
|
.java
| 95
| 35.010526
| 88
| 0.774462
|
timscriptov/ZGNB-Manager-2
| 10
| 11
| 0
|
GPL-3.0
|
9/4/2024, 8:28:04 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 3,592
|
338,094
|
ParameterizedTypeTest.java
|
google_desugar_jdk_libs/jdk11/src/libcore/harmony-tests/src/test/java/org/apache/harmony/tests/java/lang/reflect/ParameterizedTypeTest.java
|
/*
* Copyright (C) 2008 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 org.apache.harmony.tests.java.lang.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Tests parameterized types and their properties.
*/
public class ParameterizedTypeTest extends GenericReflectionTestsBase {
static class A<T>{}
static class B extends A<String>{}
public void testStringParameterizedSuperClass() {
Class<? extends B> clazz = B.class;
Type genericSuperclass = clazz.getGenericSuperclass();
assertInstanceOf(ParameterizedType.class, genericSuperclass);
String aName = A.class.getName();
assertEquals(aName + "<java.lang.String>", genericSuperclass.toString());
assertEquals(aName + "<java.lang.String>", genericSuperclass.getTypeName());
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
assertEquals(A.class, parameterizedType.getRawType());
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
assertLenghtOne(actualTypeArguments);
assertEquals(String.class, actualTypeArguments[0]);
}
static class C<T>{}
static class D<T> extends C<T>{}
public void testTypeParameterizedSuperClass() {
Class<? extends D> clazz = D.class;
Type genericSuperclass = clazz.getGenericSuperclass();
assertInstanceOf(ParameterizedType.class, genericSuperclass);
String cName = C.class.getName();
assertEquals(cName + "<T>", genericSuperclass.toString());
assertEquals(cName + "<T>", genericSuperclass.getTypeName());
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
assertEquals(C.class, parameterizedType.getRawType());
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
assertLenghtOne(actualTypeArguments);
assertEquals(getTypeParameter(D.class), actualTypeArguments[0]);
}
static class E<T>{}
static class F<T>{
E<T> e;
}
public void testParameterizedMemeber() throws Exception{
Class<? extends F> clazz = F.class;
Field field = clazz.getDeclaredField("e");
assertInstanceOf(ParameterizedType.class, field.getGenericType());
ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
assertEquals(E.class, parameterizedType.getRawType());
String eName = E.class.getName();
assertEquals(eName + "<T>", parameterizedType.toString());
assertEquals(eName + "<T>", parameterizedType.getTypeName());
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
assertLenghtOne(actualTypeArguments);
assertEquals(getTypeParameter(clazz), actualTypeArguments[0]);
}
}
| 3,687
|
Java
|
.java
| 74
| 43.675676
| 89
| 0.733871
|
google/desugar_jdk_libs
| 347
| 25
| 0
|
GPL-2.0
|
9/4/2024, 7:06:38 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 3,687
|
3,135,727
|
RowRecord.java
|
loginus_jexcelapi/src/jxl/write/biff/RowRecord.java
|
/*********************************************************************
*
* Copyright (C) 2002 Andrew Khan
*
* 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
***************************************************************************/
package jxl.write.biff;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import jxl.common.Logger;
import jxl.CellType;
import jxl.SheetSettings;
import jxl.WorkbookSettings;
import jxl.biff.CellReferenceHelper;
import jxl.biff.IndexMapping;
import jxl.biff.IntegerHelper;
import jxl.biff.Type;
import jxl.biff.WritableRecordData;
import jxl.biff.XFRecord;
import jxl.write.Number;
import jxl.write.WritableCellFeatures;
import jxl.write.WritableSheet;
/**
* Contains all the cells for a given row in a sheet
*/
class RowRecord extends WritableRecordData
{
/**
* The logger
*/
private static final Logger logger = Logger.getLogger(RowRecord.class);
/**
* The binary data
*/
private byte[] data;
/**
* The cells which comprise this row
*/
private CellValue[] cells;
/**
* The height of this row in 1/20ths of a point
*/
private int rowHeight;
/**
* Flag to indicate whether this row is outline collapsed or not
*/
private boolean collapsed;
/**
* The number of this row within the worksheet
*/
private int rowNumber;
/**
* The number of columns in this row. This is the largest column value + 1
*/
private int numColumns;
/**
* The xfIndex for this row
*/
private int xfIndex;
/**
* The style for this row
*/
private XFRecord style;
/**
* Flag indicating that this row record has an default format
*/
private boolean defaultFormat;
/**
* Flag indicating whether this row matches the default font height
*/
private boolean matchesDefFontHeight;
/**
* The amount to grow the cells array by
*/
private static final int growSize = 10;
/**
* The maximum integer value that can be squeezed into 30 bits
*/
private static final int maxRKValue = 0x1fffffff;
/**
* The minimum integer value that can be squeezed into 30 bits
*/
private static final int minRKValue = -0x20000000;
/**
* Indicates that the row is default height
*/
private static int defaultHeightIndicator = 0xff;
/**
* The maximum number of columns
*/
private static int maxColumns = 256;
/**
* The outline level of the row
*/
private int outlineLevel;
/**
* Is this the icon indicator row of a group?
*/
private boolean groupStart;
/**
* A handle back to the sheet
*/
private WritableSheet sheet;
/**
* Constructs an empty row which has the specified row number
*
* @param rn the row number of this row
*/
public RowRecord(int rn, WritableSheet ws)
{
super(Type.ROW);
rowNumber = rn;
cells = new CellValue[0];
numColumns = 0;
rowHeight = defaultHeightIndicator;
collapsed = false;
matchesDefFontHeight = true;
sheet = ws;
}
/**
* Sets the height of this row
*
* @param h the row height
*/
public void setRowHeight(int h)
{
if (h == 0)
{
setCollapsed(true);
matchesDefFontHeight = false;
}
else
{
rowHeight = h;
matchesDefFontHeight = false;
}
}
/**
* Sets the row details based upon the readable row record passed in
* Called when copying spreadsheets
*
* @param height the height of the row record in 1/20ths of a point
* @param mdfh matches the default font height
* @param col the collapsed status of the row
* @param ol the outline level
* @param gs the group start
* @param xf the xfrecord for the row (NULL if no default is set)
*/
void setRowDetails(int height,
boolean mdfh,
boolean col,
int ol,
boolean gs,
XFRecord xfr)
{
rowHeight = height;
collapsed = col;
matchesDefFontHeight = mdfh;
outlineLevel = ol;
groupStart = gs;
if (xfr != null)
{
defaultFormat = true;
style = xfr;
xfIndex = style.getXFIndex();
}
}
/**
* Sets the collapsed status of this row
*
* @param c the collapsed flag
*/
public void setCollapsed(boolean c)
{
collapsed = c;
}
/**
* Gets the row number of this row
*
* @return the row number
*/
public int getRowNumber()
{
return rowNumber;
}
/**
* Adds a cell to this row, growing the array of cells as required
*
* @param cv the cell to add
*/
public void addCell(CellValue cv)
{
int col = cv.getColumn();
if (col >= maxColumns)
{
logger.warn("Could not add cell at " +
CellReferenceHelper.getCellReference(cv.getRow(),
cv.getColumn()) +
" because it exceeds the maximum column limit");
return;
}
// Grow the array if needs be
if (col >= cells.length)
{
CellValue[] oldCells = cells;
cells = new CellValue[Math.max(oldCells.length + growSize, col+1)];
System.arraycopy(oldCells, 0, cells, 0, oldCells.length);
oldCells = null;
}
// Remove any cell features from the cell being replaced
if (cells[col] != null)
{
WritableCellFeatures wcf = cells[col].getWritableCellFeatures();
if (wcf != null)
{
wcf.removeComment();
// if the cell is part of a shared data validation,then don't remove
// the validation
if (wcf.getDVParser() != null &&
!wcf.getDVParser().extendedCellsValidation())
{
wcf.removeDataValidation();
}
}
}
cells[col] = cv;
numColumns = Math.max(col+1, numColumns);
}
/**
* Removes a cell from this row
*
* @param col the column at which to remove the cell
*/
public void removeCell(int col)
{
// Grow the array if needs be
if (col >= numColumns)
{
return;
}
cells[col] = null;
}
/**
* Writes out the row information data (but not the individual cells)
*
* @exception IOException
* @param outputFile the output file
*/
public void write(File outputFile) throws IOException
{
outputFile.write(this);
}
/**
* Writes out all the cells in this row. If more than three integer
* values occur consecutively, then a MulRK record is used to group the
* numbers
*
* @exception IOException
* @param outputFile the output file
*/
public void writeCells(File outputFile)
throws IOException
{
// This is the list for integer values
ArrayList integerValues = new ArrayList();
boolean integerValue = false;
// Write out all the records
for (int i = 0; i < numColumns; i++)
{
integerValue = false;
if (cells[i] != null)
{
// See if this cell is a 30-bit integer value (without additional
// cell features)
if (cells[i].getType() == CellType.NUMBER)
{
Number nc = (Number) cells[i];
if (nc.getValue() == (int) nc.getValue() &&
nc.getValue() < maxRKValue &&
nc.getValue() > minRKValue &&
nc.getCellFeatures() == null)
{
integerValue = true;
}
}
if (integerValue)
{
// This cell is an integer, add it to the list
integerValues.add(cells[i]);
}
else
{
// This cell is not an integer. Write out whatever integers we
// have, and then write out this cell
writeIntegerValues(integerValues, outputFile);
outputFile.write(cells[i]);
// If the cell is a string formula, write out the string record
// immediately afterwards
if (cells[i].getType() == CellType.STRING_FORMULA)
{
StringRecord sr = new StringRecord(cells[i].getContents());
outputFile.write(sr);
}
}
}
else
{
// Cell does not exist. Write out the list of integers that
// we have
writeIntegerValues(integerValues, outputFile);
}
}
// All done. Write out any remaining integer values
writeIntegerValues(integerValues, outputFile);
}
/**
* Writes out the list of integer values. If there are more than three,
* a MulRK record is used, otherwise a sequence of Numbers is used
*
* @exception IOException
* @param outputFile the output file
* @param integerValues the array of integer values
*/
private void writeIntegerValues(ArrayList integerValues, File outputFile)
throws IOException
{
if (integerValues.size() == 0)
{
return;
}
if (integerValues.size() >= 3 )
{
// Write out as a MulRK record
MulRKRecord mulrk = new MulRKRecord(integerValues);
outputFile.write(mulrk);
}
else
{
// Write out as number records
Iterator i = integerValues.iterator();
while (i.hasNext())
{
outputFile.write((CellValue) i.next());
}
}
// Clear out the list of integerValues
integerValues.clear();
}
/**
* Gets the row data to output to file
*
* @return the binary data
*/
public byte[] getData()
{
// Write out the row record
byte[] data = new byte[16];
// If the default row height has been changed in the sheet settings,
// then we need to set the rowHeight on this row explicitly, as
// specifying the "match default" flag doesn't work
int rh = rowHeight;
if (sheet.getSettings().getDefaultRowHeight() !=
SheetSettings.DEFAULT_DEFAULT_ROW_HEIGHT)
{
// the default row height has been changed. If this row does not
// have a specific row height set on it, then set it to the default
if (rh == defaultHeightIndicator)
{
rh = sheet.getSettings().getDefaultRowHeight();
}
}
IntegerHelper.getTwoBytes(rowNumber, data, 0);
IntegerHelper.getTwoBytes(numColumns, data, 4);
IntegerHelper.getTwoBytes(rh, data, 6);
int options = 0x100 + outlineLevel;
if (groupStart)
{
options |= 0x10;
}
if (collapsed)
{
options |= 0x20;
}
if (!matchesDefFontHeight)
{
options |= 0x40;
}
if (defaultFormat)
{
options |= 0x80;
options |= (xfIndex << 16);
}
IntegerHelper.getFourBytes(options, data, 12);
return data;
}
/**
* Gets the maximum column value which occurs in this row
*
* @return the maximum column value
*/
public int getMaxColumn()
{
return numColumns;
}
/**
* Gets the cell which occurs at the specified column value
*
* @param col the colun for which to return the cell
* @return the cell value at the specified position, or null if the column
* is invalid
*/
public CellValue getCell(int col)
{
return (col >= 0 && col < numColumns) ? cells[col] : null;
}
/**
* Increments the row of this cell by one. Invoked by the sheet when
* inserting rows
*/
void incrementRow()
{
rowNumber++;
for (int i = 0; i < cells.length; i++)
{
if (cells[i] != null)
{
cells[i].incrementRow();
}
}
}
/**
* Decrements the row of this cell by one. Invoked by the sheet when
* removing rows
*/
void decrementRow()
{
rowNumber--;
for (int i = 0; i < cells.length; i++)
{
if (cells[i] != null)
{
cells[i].decrementRow();
}
}
}
/**
* Inserts a new column at the position specified. If the max column length
* is already reached, then the last column simply gets dropped
*
* @param col the column to insert
*/
void insertColumn(int col)
{
// Don't bother doing anything unless there are cells after the
// column to be inserted
if (col >= numColumns)
{
return;
}
// Create a new array to hold the new column. Grow it if need be
CellValue[] oldCells = cells;
if (numColumns >= cells.length - 1)
{
cells = new CellValue[oldCells.length + growSize];
}
else
{
cells = new CellValue[oldCells.length];
}
// Copy in everything up to the new column
System.arraycopy(oldCells, 0, cells, 0, col);
// Copy in the remaining cells
System.arraycopy(oldCells, col, cells, col+1, numColumns - col);
// Increment all the internal column numbers by one
for (int i = col+1; i <= numColumns; i++)
{
if (cells[i] != null)
{
cells[i].incrementColumn();
}
}
// Adjust the maximum column record
numColumns = Math.min(numColumns+1, maxColumns);
}
/**
* Remove the new column at the position specified
*
* @param col the column to remove
*/
void removeColumn(int col)
{
// Don't bother doing anything unless there are cells after the
// column to be inserted
if (col >= numColumns)
{
return;
}
// Create a new array to hold the new columns
CellValue[] oldCells = cells;
cells = new CellValue[oldCells.length];
// Copy in everything up to the column
System.arraycopy(oldCells, 0, cells, 0, col);
// Copy in the remaining cells after the column
System.arraycopy(oldCells, col + 1, cells, col, numColumns - (col+1));
// Decrement all the internal column numbers by one
for (int i = col; i < numColumns; i++)
{
if (cells[i] != null)
{
cells[i].decrementColumn();
}
}
// Adjust the maximum column record
numColumns--;
}
/**
* Interrogates whether this row is of default height
*
* @return TRUE if this is set to the default height, FALSE otherwise
*/
public boolean isDefaultHeight()
{
return rowHeight == defaultHeightIndicator;
}
/**
* Gets the height of the row
*
* @return the row height
*/
public int getRowHeight()
{
return rowHeight;
}
/**
* Queries whether the row is collapsed
*
* @return the collapsed indicator
*/
public boolean isCollapsed()
{
return collapsed;
}
/**
* Rationalizes the sheets xf index mapping
* @param xfmapping the index mapping
*/
void rationalize(IndexMapping xfmapping)
{
if (defaultFormat)
{
xfIndex = xfmapping.getNewIndex(xfIndex);
}
}
/**
* Accessor for the style. The returned value is only non-null if the
* default style is overridden
*
* @return the style
*/
XFRecord getStyle()
{
return style;
}
/**
* Accessor for the default format flag
*
* @return TRUE if this row has its own default format
*/
boolean hasDefaultFormat()
{
return defaultFormat;
}
/**
* Accessor for the matches default font height flag
*
* @return TRUE if this row matches the default font height
*/
boolean matchesDefaultFontHeight()
{
return matchesDefFontHeight;
}
/**
* Accessor for the column's outline level
*
* @return the column's outline level
*/
public int getOutlineLevel()
{
return outlineLevel;
}
/**
* Accessor for row's groupStart state
*
* @return the row's groupStart state
*/
public boolean getGroupStart()
{
return groupStart;
}
/**
* Increments the row's outline level. This is how groups are made as well
*/
public void incrementOutlineLevel()
{
outlineLevel++;
}
/**
* Decrements the row's outline level. This removes it from a grouping
* level. If
* all outline levels are gone the uncollapse the row.
*/
public void decrementOutlineLevel()
{
if (0 < outlineLevel)
{
outlineLevel--;
}
if (0==outlineLevel)
{
collapsed = false;
}
}
/**
* Sets the row's outline level
*
* @param level the row's outline level
*/
public void setOutlineLevel(int level)
{
outlineLevel = level;
}
/**
* Sets the row's group start state
*
* @param value the group start state
*/
public void setGroupStart(boolean value)
{
groupStart = value;
}
}
| 16,967
|
Java
|
.java
| 654
| 20.847095
| 78
| 0.632138
|
loginus/jexcelapi
| 4
| 4
| 1
|
GPL-2.0
|
9/4/2024, 10:59:44 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 16,967
|
2,589,475
|
LoopNewInstance.java
|
JPortal-system_system/jdk12-06222165c35f/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.jtt/src/org/graalvm/compiler/jtt/loop/LoopNewInstance.java
|
/*
* Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.jtt.loop;
import jdk.vm.ci.meta.ResolvedJavaMethod;
import org.junit.Test;
import org.graalvm.compiler.jtt.JTTTest;
/*
*/
public class LoopNewInstance extends JTTTest {
public static Blop initBlop = new Blop();
@SuppressWarnings("unused")
public static int test(int arg) {
for (int i = 0; i < arg; i++) {
new Blop();
}
return count;
}
private static int count;
private static class Blop {
private boolean exists;
Blop() {
if (!exists) {
count++;
}
exists = true;
}
}
@Override
protected void before(ResolvedJavaMethod m) {
count = 0;
}
@Test
public void run0() throws Throwable {
count = 0;
runTest("test", 0);
}
@Test
public void run1() throws Throwable {
count = 0;
runTest("test", 5);
}
}
| 2,011
|
Java
|
.java
| 62
| 27.33871
| 79
| 0.674082
|
JPortal-system/system
| 7
| 2
| 1
|
GPL-3.0
|
9/4/2024, 9:49:36 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 2,011
|
3,934,788
|
PdfCreator.java
|
tumi8_nasty/src/de/japes/text/PdfCreator.java
|
/**************************************************************************/
/* NASTY - Network Analysis and STatistics Yielding */
/* */
/* Copyright (C) 2006 History Project, http://www.history-project.net */
/* History (HIgh-Speed neTwork mOniToring and analYsis) is a research */
/* project by the Universities of Tuebingen and Erlangen-Nuremberg, */
/* Germany */
/* */
/* Authors of NASTY are: */
/* Christian Japes, University of Erlangen-Nuremberg */
/* Thomas Schurtz, University of Tuebingen */
/* David Halsband, University of Tuebingen */
/* Gerhard Muenz <muenz@informatik.uni-tuebingen.de>, */
/* University of Tuebingen */
/* Falko Dressler <dressler@informatik.uni-erlangen.de>, */
/* University of Erlangen-Nuremberg */
/* */
/* 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 St, Fifth Floor, Boston, MA 02110-1301 USA */
/**************************************************************************/
/*
* Created on 29.09.2004
*/
package de.japes.text;
/**
* @author unrza88
*
* partly taken from http://www.lowagie.com/iText/examples/Chap0101.java
*/
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Calendar;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;
public class PdfCreator {
public String exportToPdf(byte[] imgArray) {
String filename;
Document document = new Document();
Image img = null;
Calendar cal = Calendar.getInstance();
filename = "chart_" + cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH) +
cal.get(Calendar.DAY_OF_MONTH) + "_" + cal.get(Calendar.HOUR_OF_DAY) +
cal.get(Calendar.MINUTE) + ".pdf";
try {
img = Image.getInstance(imgArray);
} catch(MalformedURLException e) {
return e.getMessage();
} catch(IOException e) {
return e.getMessage();
} catch(BadElementException e) {
return e.getMessage();
}
img.setAlignment(Image.ALIGN_CENTER);
try {
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.getInstance(document, new FileOutputStream(filename));
// step 3: we open the document
document.open();
// step 4: we add a paragraph to the document
document.add(img);
}
catch(DocumentException de) {
return de.getMessage();
}
catch(IOException ioe) {
return ioe.getMessage();
}
// step 5: we close the document
document.close();
return filename;
}
}
| 4,158
|
Java
|
.java
| 86
| 43.290698
| 82
| 0.519192
|
tumi8/nasty
| 2
| 0
| 0
|
GPL-2.0
|
9/4/2024, 11:54:52 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 4,158
|
2,061,621
|
DataExceptPattern.java
|
openjdk_jdk6/jaxws/drop_included/jaxws_src/src/com/sun/xml/internal/rngom/binary/DataExceptPattern.java
|
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.rngom.binary;
import com.sun.xml.internal.rngom.binary.visitor.PatternFunction;
import com.sun.xml.internal.rngom.binary.visitor.PatternVisitor;
import org.relaxng.datatype.Datatype;
import org.xml.sax.Locator;
public class DataExceptPattern extends DataPattern {
private Pattern except;
private Locator loc;
DataExceptPattern(Datatype dt, Pattern except, Locator loc) {
super(dt);
this.except = except;
this.loc = loc;
}
boolean samePattern(Pattern other) {
if (!super.samePattern(other))
return false;
return except.samePattern(((DataExceptPattern)other).except);
}
public void accept(PatternVisitor visitor) {
visitor.visitDataExcept(getDatatype(), except);
}
public Object apply(PatternFunction f) {
return f.caseDataExcept(this);
}
void checkRestrictions(int context, DuplicateAttributeDetector dad, Alphabet alpha)
throws RestrictionViolationException {
super.checkRestrictions(context, dad, alpha);
try {
except.checkRestrictions(DATA_EXCEPT_CONTEXT, null, null);
}
catch (RestrictionViolationException e) {
e.maybeSetLocator(loc);
throw e;
}
}
Pattern getExcept() {
return except;
}
}
| 2,451
|
Java
|
.java
| 63
| 35.698413
| 85
| 0.761765
|
openjdk/jdk6
| 19
| 18
| 0
|
GPL-2.0
|
9/4/2024, 8:28:13 PM (Europe/Amsterdam)
| false
| true
| true
| true
| false
| true
| true
| true
| 2,451
|
2,687,619
|
VendorCatalogItemFilter.java
|
kaltura_KalturaGeneratedAPIClientsJava/src/main/java/com/kaltura/client/types/VendorCatalogItemFilter.java
|
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2023 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.types;
import com.google.gson.JsonObject;
import com.kaltura.client.Params;
import com.kaltura.client.utils.GsonParser;
import com.kaltura.client.utils.request.MultiRequestBuilder;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
@MultiRequestBuilder.Tokenizer(VendorCatalogItemFilter.Tokenizer.class)
public class VendorCatalogItemFilter extends VendorCatalogItemBaseFilter {
public interface Tokenizer extends VendorCatalogItemBaseFilter.Tokenizer {
String partnerIdEqual();
}
private Integer partnerIdEqual;
// partnerIdEqual:
public Integer getPartnerIdEqual(){
return this.partnerIdEqual;
}
public void setPartnerIdEqual(Integer partnerIdEqual){
this.partnerIdEqual = partnerIdEqual;
}
public void partnerIdEqual(String multirequestToken){
setToken("partnerIdEqual", multirequestToken);
}
public VendorCatalogItemFilter() {
super();
}
public VendorCatalogItemFilter(JsonObject jsonObject) throws APIException {
super(jsonObject);
if(jsonObject == null) return;
// set members values:
partnerIdEqual = GsonParser.parseInt(jsonObject.get("partnerIdEqual"));
}
public Params toParams() {
Params kparams = super.toParams();
kparams.add("objectType", "KalturaVendorCatalogItemFilter");
kparams.add("partnerIdEqual", this.partnerIdEqual);
return kparams;
}
}
| 2,814
|
Java
|
.java
| 71
| 37.71831
| 102
| 0.670213
|
kaltura/KalturaGeneratedAPIClientsJava
| 6
| 11
| 1
|
AGPL-3.0
|
9/4/2024, 10:06:24 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 2,814
|
3,436,827
|
BaseWindow.java
|
JPII_NavalBattle/src/com/jpii/navalbattle/gui/BaseWindow.java
|
package com.jpii.navalbattle.gui;
import com.jpii.navalbattle.data.Constants;
import com.jpii.navalbattle.gui.listeners.Focus;
import com.jpii.navalbattle.renderer.Helper;
public class BaseWindow extends com.jpii.gamekit.gui.BaseWindow{
private static final long serialVersionUID = 1L;
public BaseWindow() {
super();
}
public BaseWindow(int arg0, int arg1) {
super(arg0, arg1);
}
public void setDefaults() {
this.setIconImage(Helper.GUI_WINDOW_ICON);
setTitle("NavalBattle");
addWindowListener(Constants.closer);
addKeyListener(Constants.keys);
addFocusListener(new Focus(this));
super.setDefaults();
}
}
| 638
|
Java
|
.java
| 21
| 27.809524
| 64
| 0.792422
|
JPII/NavalBattle
| 3
| 3
| 20
|
GPL-3.0
|
9/4/2024, 11:27:11 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 638
|
265,389
|
Subject.java
|
openjdk-mirror_jdk7u-jdk/src/share/classes/javax/security/auth/Subject.java
|
/*
* Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.security.auth;
import java.util.*;
import java.io.*;
import java.lang.reflect.*;
import java.text.MessageFormat;
import java.security.AccessController;
import java.security.AccessControlContext;
import java.security.DomainCombiner;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
import java.security.ProtectionDomain;
import sun.security.util.ResourcesMgr;
/**
* <p> A <code>Subject</code> represents a grouping of related information
* for a single entity, such as a person.
* Such information includes the Subject's identities as well as
* its security-related attributes
* (passwords and cryptographic keys, for example).
*
* <p> Subjects may potentially have multiple identities.
* Each identity is represented as a <code>Principal</code>
* within the <code>Subject</code>. Principals simply bind names to a
* <code>Subject</code>. For example, a <code>Subject</code> that happens
* to be a person, Alice, might have two Principals:
* one which binds "Alice Bar", the name on her driver license,
* to the <code>Subject</code>, and another which binds,
* "999-99-9999", the number on her student identification card,
* to the <code>Subject</code>. Both Principals refer to the same
* <code>Subject</code> even though each has a different name.
*
* <p> A <code>Subject</code> may also own security-related attributes,
* which are referred to as credentials.
* Sensitive credentials that require special protection, such as
* private cryptographic keys, are stored within a private credential
* <code>Set</code>. Credentials intended to be shared, such as
* public key certificates or Kerberos server tickets are stored
* within a public credential <code>Set</code>. Different permissions
* are required to access and modify the different credential Sets.
*
* <p> To retrieve all the Principals associated with a <code>Subject</code>,
* invoke the <code>getPrincipals</code> method. To retrieve
* all the public or private credentials belonging to a <code>Subject</code>,
* invoke the <code>getPublicCredentials</code> method or
* <code>getPrivateCredentials</code> method, respectively.
* To modify the returned <code>Set</code> of Principals and credentials,
* use the methods defined in the <code>Set</code> class.
* For example:
* <pre>
* Subject subject;
* Principal principal;
* Object credential;
*
* // add a Principal and credential to the Subject
* subject.getPrincipals().add(principal);
* subject.getPublicCredentials().add(credential);
* </pre>
*
* <p> This <code>Subject</code> class implements <code>Serializable</code>.
* While the Principals associated with the <code>Subject</code> are serialized,
* the credentials associated with the <code>Subject</code> are not.
* Note that the <code>java.security.Principal</code> class
* does not implement <code>Serializable</code>. Therefore all concrete
* <code>Principal</code> implementations associated with Subjects
* must implement <code>Serializable</code>.
*
* @see java.security.Principal
* @see java.security.DomainCombiner
*/
public final class Subject implements java.io.Serializable {
private static final long serialVersionUID = -8308522755600156056L;
/**
* A <code>Set</code> that provides a view of all of this
* Subject's Principals
*
* <p>
*
* @serial Each element in this set is a
* <code>java.security.Principal</code>.
* The set is a <code>Subject.SecureSet</code>.
*/
Set<Principal> principals;
/**
* Sets that provide a view of all of this
* Subject's Credentials
*/
transient Set<Object> pubCredentials;
transient Set<Object> privCredentials;
/**
* Whether this Subject is read-only
*
* @serial
*/
private volatile boolean readOnly = false;
private static final int PRINCIPAL_SET = 1;
private static final int PUB_CREDENTIAL_SET = 2;
private static final int PRIV_CREDENTIAL_SET = 3;
private static final ProtectionDomain[] NULL_PD_ARRAY
= new ProtectionDomain[0];
/**
* Create an instance of a <code>Subject</code>
* with an empty <code>Set</code> of Principals and empty
* Sets of public and private credentials.
*
* <p> The newly constructed Sets check whether this <code>Subject</code>
* has been set read-only before permitting subsequent modifications.
* The newly created Sets also prevent illegal modifications
* by ensuring that callers have sufficient permissions.
*
* <p> To modify the Principals Set, the caller must have
* <code>AuthPermission("modifyPrincipals")</code>.
* To modify the public credential Set, the caller must have
* <code>AuthPermission("modifyPublicCredentials")</code>.
* To modify the private credential Set, the caller must have
* <code>AuthPermission("modifyPrivateCredentials")</code>.
*/
public Subject() {
this.principals = Collections.synchronizedSet
(new SecureSet<Principal>(this, PRINCIPAL_SET));
this.pubCredentials = Collections.synchronizedSet
(new SecureSet<Object>(this, PUB_CREDENTIAL_SET));
this.privCredentials = Collections.synchronizedSet
(new SecureSet<Object>(this, PRIV_CREDENTIAL_SET));
}
/**
* Create an instance of a <code>Subject</code> with
* Principals and credentials.
*
* <p> The Principals and credentials from the specified Sets
* are copied into newly constructed Sets.
* These newly created Sets check whether this <code>Subject</code>
* has been set read-only before permitting subsequent modifications.
* The newly created Sets also prevent illegal modifications
* by ensuring that callers have sufficient permissions.
*
* <p> To modify the Principals Set, the caller must have
* <code>AuthPermission("modifyPrincipals")</code>.
* To modify the public credential Set, the caller must have
* <code>AuthPermission("modifyPublicCredentials")</code>.
* To modify the private credential Set, the caller must have
* <code>AuthPermission("modifyPrivateCredentials")</code>.
* <p>
*
* @param readOnly true if the <code>Subject</code> is to be read-only,
* and false otherwise. <p>
*
* @param principals the <code>Set</code> of Principals
* to be associated with this <code>Subject</code>. <p>
*
* @param pubCredentials the <code>Set</code> of public credentials
* to be associated with this <code>Subject</code>. <p>
*
* @param privCredentials the <code>Set</code> of private credentials
* to be associated with this <code>Subject</code>.
*
* @exception NullPointerException if the specified
* <code>principals</code>, <code>pubCredentials</code>,
* or <code>privCredentials</code> are <code>null</code>.
*/
public Subject(boolean readOnly, Set<? extends Principal> principals,
Set<?> pubCredentials, Set<?> privCredentials)
{
if (principals == null ||
pubCredentials == null ||
privCredentials == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid.null.input.s."));
this.principals = Collections.synchronizedSet(new SecureSet<Principal>
(this, PRINCIPAL_SET, principals));
this.pubCredentials = Collections.synchronizedSet(new SecureSet<Object>
(this, PUB_CREDENTIAL_SET, pubCredentials));
this.privCredentials = Collections.synchronizedSet(new SecureSet<Object>
(this, PRIV_CREDENTIAL_SET, privCredentials));
this.readOnly = readOnly;
}
/**
* Set this <code>Subject</code> to be read-only.
*
* <p> Modifications (additions and removals) to this Subject's
* <code>Principal</code> <code>Set</code> and
* credential Sets will be disallowed.
* The <code>destroy</code> operation on this Subject's credentials will
* still be permitted.
*
* <p> Subsequent attempts to modify the Subject's <code>Principal</code>
* and credential Sets will result in an
* <code>IllegalStateException</code> being thrown.
* Also, once a <code>Subject</code> is read-only,
* it can not be reset to being writable again.
*
* <p>
*
* @exception SecurityException if the caller does not have permission
* to set this <code>Subject</code> to be read-only.
*/
public void setReadOnly() {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(AuthPermissionHolder.SET_READ_ONLY_PERMISSION);
}
this.readOnly = true;
}
/**
* Query whether this <code>Subject</code> is read-only.
*
* <p>
*
* @return true if this <code>Subject</code> is read-only, false otherwise.
*/
public boolean isReadOnly() {
return this.readOnly;
}
/**
* Get the <code>Subject</code> associated with the provided
* <code>AccessControlContext</code>.
*
* <p> The <code>AccessControlContext</code> may contain many
* Subjects (from nested <code>doAs</code> calls).
* In this situation, the most recent <code>Subject</code> associated
* with the <code>AccessControlContext</code> is returned.
*
* <p>
*
* @param acc the <code>AccessControlContext</code> from which to retrieve
* the <code>Subject</code>.
*
* @return the <code>Subject</code> associated with the provided
* <code>AccessControlContext</code>, or <code>null</code>
* if no <code>Subject</code> is associated
* with the provided <code>AccessControlContext</code>.
*
* @exception SecurityException if the caller does not have permission
* to get the <code>Subject</code>. <p>
*
* @exception NullPointerException if the provided
* <code>AccessControlContext</code> is <code>null</code>.
*/
public static Subject getSubject(final AccessControlContext acc) {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(AuthPermissionHolder.GET_SUBJECT_PERMISSION);
}
if (acc == null) {
throw new NullPointerException(ResourcesMgr.getString
("invalid.null.AccessControlContext.provided"));
}
// return the Subject from the DomainCombiner of the provided context
return AccessController.doPrivileged
(new java.security.PrivilegedAction<Subject>() {
public Subject run() {
DomainCombiner dc = acc.getDomainCombiner();
if (!(dc instanceof SubjectDomainCombiner))
return null;
SubjectDomainCombiner sdc = (SubjectDomainCombiner)dc;
return sdc.getSubject();
}
});
}
/**
* Perform work as a particular <code>Subject</code>.
*
* <p> This method first retrieves the current Thread's
* <code>AccessControlContext</code> via
* <code>AccessController.getContext</code>,
* and then instantiates a new <code>AccessControlContext</code>
* using the retrieved context along with a new
* <code>SubjectDomainCombiner</code> (constructed using
* the provided <code>Subject</code>).
* Finally, this method invokes <code>AccessController.doPrivileged</code>,
* passing it the provided <code>PrivilegedAction</code>,
* as well as the newly constructed <code>AccessControlContext</code>.
*
* <p>
*
* @param subject the <code>Subject</code> that the specified
* <code>action</code> will run as. This parameter
* may be <code>null</code>. <p>
*
* @param action the code to be run as the specified
* <code>Subject</code>. <p>
*
* @return the value returned by the PrivilegedAction's
* <code>run</code> method.
*
* @exception NullPointerException if the <code>PrivilegedAction</code>
* is <code>null</code>. <p>
*
* @exception SecurityException if the caller does not have permission
* to invoke this method.
*/
public static <T> T doAs(final Subject subject,
final java.security.PrivilegedAction<T> action) {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(AuthPermissionHolder.DO_AS_PERMISSION);
}
if (action == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid.null.action.provided"));
// set up the new Subject-based AccessControlContext
// for doPrivileged
final AccessControlContext currentAcc = AccessController.getContext();
// call doPrivileged and push this new context on the stack
return java.security.AccessController.doPrivileged
(action,
createContext(subject, currentAcc));
}
/**
* Perform work as a particular <code>Subject</code>.
*
* <p> This method first retrieves the current Thread's
* <code>AccessControlContext</code> via
* <code>AccessController.getContext</code>,
* and then instantiates a new <code>AccessControlContext</code>
* using the retrieved context along with a new
* <code>SubjectDomainCombiner</code> (constructed using
* the provided <code>Subject</code>).
* Finally, this method invokes <code>AccessController.doPrivileged</code>,
* passing it the provided <code>PrivilegedExceptionAction</code>,
* as well as the newly constructed <code>AccessControlContext</code>.
*
* <p>
*
* @param subject the <code>Subject</code> that the specified
* <code>action</code> will run as. This parameter
* may be <code>null</code>. <p>
*
* @param action the code to be run as the specified
* <code>Subject</code>. <p>
*
* @return the value returned by the
* PrivilegedExceptionAction's <code>run</code> method.
*
* @exception PrivilegedActionException if the
* <code>PrivilegedExceptionAction.run</code>
* method throws a checked exception. <p>
*
* @exception NullPointerException if the specified
* <code>PrivilegedExceptionAction</code> is
* <code>null</code>. <p>
*
* @exception SecurityException if the caller does not have permission
* to invoke this method.
*/
public static <T> T doAs(final Subject subject,
final java.security.PrivilegedExceptionAction<T> action)
throws java.security.PrivilegedActionException {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(AuthPermissionHolder.DO_AS_PERMISSION);
}
if (action == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid.null.action.provided"));
// set up the new Subject-based AccessControlContext for doPrivileged
final AccessControlContext currentAcc = AccessController.getContext();
// call doPrivileged and push this new context on the stack
return java.security.AccessController.doPrivileged
(action,
createContext(subject, currentAcc));
}
/**
* Perform privileged work as a particular <code>Subject</code>.
*
* <p> This method behaves exactly as <code>Subject.doAs</code>,
* except that instead of retrieving the current Thread's
* <code>AccessControlContext</code>, it uses the provided
* <code>AccessControlContext</code>. If the provided
* <code>AccessControlContext</code> is <code>null</code>,
* this method instantiates a new <code>AccessControlContext</code>
* with an empty collection of ProtectionDomains.
*
* <p>
*
* @param subject the <code>Subject</code> that the specified
* <code>action</code> will run as. This parameter
* may be <code>null</code>. <p>
*
* @param action the code to be run as the specified
* <code>Subject</code>. <p>
*
* @param acc the <code>AccessControlContext</code> to be tied to the
* specified <i>subject</i> and <i>action</i>. <p>
*
* @return the value returned by the PrivilegedAction's
* <code>run</code> method.
*
* @exception NullPointerException if the <code>PrivilegedAction</code>
* is <code>null</code>. <p>
*
* @exception SecurityException if the caller does not have permission
* to invoke this method.
*/
public static <T> T doAsPrivileged(final Subject subject,
final java.security.PrivilegedAction<T> action,
final java.security.AccessControlContext acc) {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(AuthPermissionHolder.DO_AS_PRIVILEGED_PERMISSION);
}
if (action == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid.null.action.provided"));
// set up the new Subject-based AccessControlContext
// for doPrivileged
final AccessControlContext callerAcc =
(acc == null ?
new AccessControlContext(NULL_PD_ARRAY) :
acc);
// call doPrivileged and push this new context on the stack
return java.security.AccessController.doPrivileged
(action,
createContext(subject, callerAcc));
}
/**
* Perform privileged work as a particular <code>Subject</code>.
*
* <p> This method behaves exactly as <code>Subject.doAs</code>,
* except that instead of retrieving the current Thread's
* <code>AccessControlContext</code>, it uses the provided
* <code>AccessControlContext</code>. If the provided
* <code>AccessControlContext</code> is <code>null</code>,
* this method instantiates a new <code>AccessControlContext</code>
* with an empty collection of ProtectionDomains.
*
* <p>
*
* @param subject the <code>Subject</code> that the specified
* <code>action</code> will run as. This parameter
* may be <code>null</code>. <p>
*
* @param action the code to be run as the specified
* <code>Subject</code>. <p>
*
* @param acc the <code>AccessControlContext</code> to be tied to the
* specified <i>subject</i> and <i>action</i>. <p>
*
* @return the value returned by the
* PrivilegedExceptionAction's <code>run</code> method.
*
* @exception PrivilegedActionException if the
* <code>PrivilegedExceptionAction.run</code>
* method throws a checked exception. <p>
*
* @exception NullPointerException if the specified
* <code>PrivilegedExceptionAction</code> is
* <code>null</code>. <p>
*
* @exception SecurityException if the caller does not have permission
* to invoke this method.
*/
public static <T> T doAsPrivileged(final Subject subject,
final java.security.PrivilegedExceptionAction<T> action,
final java.security.AccessControlContext acc)
throws java.security.PrivilegedActionException {
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(AuthPermissionHolder.DO_AS_PRIVILEGED_PERMISSION);
}
if (action == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid.null.action.provided"));
// set up the new Subject-based AccessControlContext for doPrivileged
final AccessControlContext callerAcc =
(acc == null ?
new AccessControlContext(NULL_PD_ARRAY) :
acc);
// call doPrivileged and push this new context on the stack
return java.security.AccessController.doPrivileged
(action,
createContext(subject, callerAcc));
}
private static AccessControlContext createContext(final Subject subject,
final AccessControlContext acc) {
return java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<AccessControlContext>() {
public AccessControlContext run() {
if (subject == null)
return new AccessControlContext(acc, null);
else
return new AccessControlContext
(acc,
new SubjectDomainCombiner(subject));
}
});
}
/**
* Return the <code>Set</code> of Principals associated with this
* <code>Subject</code>. Each <code>Principal</code> represents
* an identity for this <code>Subject</code>.
*
* <p> The returned <code>Set</code> is backed by this Subject's
* internal <code>Principal</code> <code>Set</code>. Any modification
* to the returned <code>Set</code> affects the internal
* <code>Principal</code> <code>Set</code> as well.
*
* <p>
*
* @return The <code>Set</code> of Principals associated with this
* <code>Subject</code>.
*/
public Set<Principal> getPrincipals() {
// always return an empty Set instead of null
// so LoginModules can add to the Set if necessary
return principals;
}
/**
* Return a <code>Set</code> of Principals associated with this
* <code>Subject</code> that are instances or subclasses of the specified
* <code>Class</code>.
*
* <p> The returned <code>Set</code> is not backed by this Subject's
* internal <code>Principal</code> <code>Set</code>. A new
* <code>Set</code> is created and returned for each method invocation.
* Modifications to the returned <code>Set</code>
* will not affect the internal <code>Principal</code> <code>Set</code>.
*
* <p>
*
* @param c the returned <code>Set</code> of Principals will all be
* instances of this class.
*
* @return a <code>Set</code> of Principals that are instances of the
* specified <code>Class</code>.
*
* @exception NullPointerException if the specified <code>Class</code>
* is <code>null</code>.
*/
public <T extends Principal> Set<T> getPrincipals(Class<T> c) {
if (c == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid.null.Class.provided"));
// always return an empty Set instead of null
// so LoginModules can add to the Set if necessary
return new ClassSet<T>(PRINCIPAL_SET, c);
}
/**
* Return the <code>Set</code> of public credentials held by this
* <code>Subject</code>.
*
* <p> The returned <code>Set</code> is backed by this Subject's
* internal public Credential <code>Set</code>. Any modification
* to the returned <code>Set</code> affects the internal public
* Credential <code>Set</code> as well.
*
* <p>
*
* @return A <code>Set</code> of public credentials held by this
* <code>Subject</code>.
*/
public Set<Object> getPublicCredentials() {
// always return an empty Set instead of null
// so LoginModules can add to the Set if necessary
return pubCredentials;
}
/**
* Return the <code>Set</code> of private credentials held by this
* <code>Subject</code>.
*
* <p> The returned <code>Set</code> is backed by this Subject's
* internal private Credential <code>Set</code>. Any modification
* to the returned <code>Set</code> affects the internal private
* Credential <code>Set</code> as well.
*
* <p> A caller requires permissions to access the Credentials
* in the returned <code>Set</code>, or to modify the
* <code>Set</code> itself. A <code>SecurityException</code>
* is thrown if the caller does not have the proper permissions.
*
* <p> While iterating through the <code>Set</code>,
* a <code>SecurityException</code> is thrown
* if the caller does not have permission to access a
* particular Credential. The <code>Iterator</code>
* is nevertheless advanced to next element in the <code>Set</code>.
*
* <p>
*
* @return A <code>Set</code> of private credentials held by this
* <code>Subject</code>.
*/
public Set<Object> getPrivateCredentials() {
// XXX
// we do not need a security check for
// AuthPermission(getPrivateCredentials)
// because we already restrict access to private credentials
// via the PrivateCredentialPermission. all the extra AuthPermission
// would do is protect the set operations themselves
// (like size()), which don't seem security-sensitive.
// always return an empty Set instead of null
// so LoginModules can add to the Set if necessary
return privCredentials;
}
/**
* Return a <code>Set</code> of public credentials associated with this
* <code>Subject</code> that are instances or subclasses of the specified
* <code>Class</code>.
*
* <p> The returned <code>Set</code> is not backed by this Subject's
* internal public Credential <code>Set</code>. A new
* <code>Set</code> is created and returned for each method invocation.
* Modifications to the returned <code>Set</code>
* will not affect the internal public Credential <code>Set</code>.
*
* <p>
*
* @param c the returned <code>Set</code> of public credentials will all be
* instances of this class.
*
* @return a <code>Set</code> of public credentials that are instances
* of the specified <code>Class</code>.
*
* @exception NullPointerException if the specified <code>Class</code>
* is <code>null</code>.
*/
public <T> Set<T> getPublicCredentials(Class<T> c) {
if (c == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid.null.Class.provided"));
// always return an empty Set instead of null
// so LoginModules can add to the Set if necessary
return new ClassSet<T>(PUB_CREDENTIAL_SET, c);
}
/**
* Return a <code>Set</code> of private credentials associated with this
* <code>Subject</code> that are instances or subclasses of the specified
* <code>Class</code>.
*
* <p> The caller must have permission to access all of the
* requested Credentials, or a <code>SecurityException</code>
* will be thrown.
*
* <p> The returned <code>Set</code> is not backed by this Subject's
* internal private Credential <code>Set</code>. A new
* <code>Set</code> is created and returned for each method invocation.
* Modifications to the returned <code>Set</code>
* will not affect the internal private Credential <code>Set</code>.
*
* <p>
*
* @param c the returned <code>Set</code> of private credentials will all be
* instances of this class.
*
* @return a <code>Set</code> of private credentials that are instances
* of the specified <code>Class</code>.
*
* @exception NullPointerException if the specified <code>Class</code>
* is <code>null</code>.
*/
public <T> Set<T> getPrivateCredentials(Class<T> c) {
// XXX
// we do not need a security check for
// AuthPermission(getPrivateCredentials)
// because we already restrict access to private credentials
// via the PrivateCredentialPermission. all the extra AuthPermission
// would do is protect the set operations themselves
// (like size()), which don't seem security-sensitive.
if (c == null)
throw new NullPointerException
(ResourcesMgr.getString("invalid.null.Class.provided"));
// always return an empty Set instead of null
// so LoginModules can add to the Set if necessary
return new ClassSet<T>(PRIV_CREDENTIAL_SET, c);
}
/**
* Compares the specified Object with this <code>Subject</code>
* for equality. Returns true if the given object is also a Subject
* and the two <code>Subject</code> instances are equivalent.
* More formally, two <code>Subject</code> instances are
* equal if their <code>Principal</code> and <code>Credential</code>
* Sets are equal.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>Subject</code>.
*
* @return true if the specified Object is equal to this
* <code>Subject</code>.
*
* @exception SecurityException if the caller does not have permission
* to access the private credentials for this <code>Subject</code>,
* or if the caller does not have permission to access the
* private credentials for the provided <code>Subject</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (o instanceof Subject) {
final Subject that = (Subject)o;
// check the principal and credential sets
Set<Principal> thatPrincipals;
synchronized(that.principals) {
// avoid deadlock from dual locks
thatPrincipals = new HashSet<Principal>(that.principals);
}
if (!principals.equals(thatPrincipals)) {
return false;
}
Set<Object> thatPubCredentials;
synchronized(that.pubCredentials) {
// avoid deadlock from dual locks
thatPubCredentials = new HashSet<Object>(that.pubCredentials);
}
if (!pubCredentials.equals(thatPubCredentials)) {
return false;
}
Set<Object> thatPrivCredentials;
synchronized(that.privCredentials) {
// avoid deadlock from dual locks
thatPrivCredentials = new HashSet<Object>(that.privCredentials);
}
if (!privCredentials.equals(thatPrivCredentials)) {
return false;
}
return true;
}
return false;
}
/**
* Return the String representation of this <code>Subject</code>.
*
* <p>
*
* @return the String representation of this <code>Subject</code>.
*/
public String toString() {
return toString(true);
}
/**
* package private convenience method to print out the Subject
* without firing off a security check when trying to access
* the Private Credentials
*/
String toString(boolean includePrivateCredentials) {
String s = ResourcesMgr.getString("Subject.");
String suffix = "";
synchronized(principals) {
Iterator<Principal> pI = principals.iterator();
while (pI.hasNext()) {
Principal p = pI.next();
suffix = suffix + ResourcesMgr.getString(".Principal.") +
p.toString() + ResourcesMgr.getString("NEWLINE");
}
}
synchronized(pubCredentials) {
Iterator<Object> pI = pubCredentials.iterator();
while (pI.hasNext()) {
Object o = pI.next();
suffix = suffix +
ResourcesMgr.getString(".Public.Credential.") +
o.toString() + ResourcesMgr.getString("NEWLINE");
}
}
if (includePrivateCredentials) {
synchronized(privCredentials) {
Iterator<Object> pI = privCredentials.iterator();
while (pI.hasNext()) {
try {
Object o = pI.next();
suffix += ResourcesMgr.getString
(".Private.Credential.") +
o.toString() +
ResourcesMgr.getString("NEWLINE");
} catch (SecurityException se) {
suffix += ResourcesMgr.getString
(".Private.Credential.inaccessible.");
break;
}
}
}
}
return s + suffix;
}
/**
* Returns a hashcode for this <code>Subject</code>.
*
* <p>
*
* @return a hashcode for this <code>Subject</code>.
*
* @exception SecurityException if the caller does not have permission
* to access this Subject's private credentials.
*/
public int hashCode() {
/**
* The hashcode is derived exclusive or-ing the
* hashcodes of this Subject's Principals and credentials.
*
* If a particular credential was destroyed
* (<code>credential.hashCode()</code> throws an
* <code>IllegalStateException</code>),
* the hashcode for that credential is derived via:
* <code>credential.getClass().toString().hashCode()</code>.
*/
int hashCode = 0;
synchronized(principals) {
Iterator<Principal> pIterator = principals.iterator();
while (pIterator.hasNext()) {
Principal p = pIterator.next();
hashCode ^= p.hashCode();
}
}
synchronized(pubCredentials) {
Iterator<Object> pubCIterator = pubCredentials.iterator();
while (pubCIterator.hasNext()) {
hashCode ^= getCredHashCode(pubCIterator.next());
}
}
return hashCode;
}
/**
* get a credential's hashcode
*/
private int getCredHashCode(Object o) {
try {
return o.hashCode();
} catch (IllegalStateException ise) {
return o.getClass().toString().hashCode();
}
}
/**
* Writes this object out to a stream (i.e., serializes it).
*/
private void writeObject(java.io.ObjectOutputStream oos)
throws java.io.IOException {
synchronized(principals) {
oos.defaultWriteObject();
}
}
/**
* Reads this object from a stream (i.e., deserializes it)
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
// The Credential <code>Set</code> is not serialized, but we do not
// want the default deserialization routine to set it to null.
this.pubCredentials = Collections.synchronizedSet
(new SecureSet<Object>(this, PUB_CREDENTIAL_SET));
this.privCredentials = Collections.synchronizedSet
(new SecureSet<Object>(this, PRIV_CREDENTIAL_SET));
}
/**
* Prevent modifications unless caller has permission.
*
* @serial include
*/
private static class SecureSet<E>
extends AbstractSet<E>
implements java.io.Serializable {
private static final long serialVersionUID = 7911754171111800359L;
/**
* @serialField this$0 Subject The outer Subject instance.
* @serialField elements LinkedList The elements in this set.
*/
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("this$0", Subject.class),
new ObjectStreamField("elements", LinkedList.class),
new ObjectStreamField("which", int.class)
};
Subject subject;
LinkedList<E> elements;
/**
* @serial An integer identifying the type of objects contained
* in this set. If <code>which == 1</code>,
* this is a Principal set and all the elements are
* of type <code>java.security.Principal</code>.
* If <code>which == 2</code>, this is a public credential
* set and all the elements are of type <code>Object</code>.
* If <code>which == 3</code>, this is a private credential
* set and all the elements are of type <code>Object</code>.
*/
private int which;
SecureSet(Subject subject, int which) {
this.subject = subject;
this.which = which;
this.elements = new LinkedList<E>();
}
SecureSet(Subject subject, int which, Set<? extends E> set) {
this.subject = subject;
this.which = which;
this.elements = new LinkedList<E>(set);
}
public int size() {
return elements.size();
}
public Iterator<E> iterator() {
final LinkedList<E> list = elements;
return new Iterator<E>() {
ListIterator<E> i = list.listIterator(0);
public boolean hasNext() {return i.hasNext();}
public E next() {
if (which != Subject.PRIV_CREDENTIAL_SET) {
return i.next();
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
sm.checkPermission(new PrivateCredentialPermission
(list.get(i.nextIndex()).getClass().getName(),
subject.getPrincipals()));
} catch (SecurityException se) {
i.next();
throw (se);
}
}
return i.next();
}
public void remove() {
if (subject.isReadOnly()) {
throw new IllegalStateException(ResourcesMgr.getString
("Subject.is.read.only"));
}
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
switch (which) {
case Subject.PRINCIPAL_SET:
sm.checkPermission(AuthPermissionHolder.MODIFY_PRINCIPALS_PERMISSION);
break;
case Subject.PUB_CREDENTIAL_SET:
sm.checkPermission(AuthPermissionHolder.MODIFY_PUBLIC_CREDENTIALS_PERMISSION);
break;
default:
sm.checkPermission(AuthPermissionHolder.MODIFY_PRIVATE_CREDENTIALS_PERMISSION);
break;
}
}
i.remove();
}
};
}
public boolean add(E o) {
if (subject.isReadOnly()) {
throw new IllegalStateException
(ResourcesMgr.getString("Subject.is.read.only"));
}
java.lang.SecurityManager sm = System.getSecurityManager();
if (sm != null) {
switch (which) {
case Subject.PRINCIPAL_SET:
sm.checkPermission(AuthPermissionHolder.MODIFY_PRINCIPALS_PERMISSION);
break;
case Subject.PUB_CREDENTIAL_SET:
sm.checkPermission(AuthPermissionHolder.MODIFY_PUBLIC_CREDENTIALS_PERMISSION);
break;
default:
sm.checkPermission(AuthPermissionHolder.MODIFY_PRIVATE_CREDENTIALS_PERMISSION);
break;
}
}
switch (which) {
case Subject.PRINCIPAL_SET:
if (!(o instanceof Principal)) {
throw new SecurityException(ResourcesMgr.getString
("attempting.to.add.an.object.which.is.not.an.instance.of.java.security.Principal.to.a.Subject.s.Principal.Set"));
}
break;
default:
// ok to add Objects of any kind to credential sets
break;
}
// check for duplicates
if (!elements.contains(o))
return elements.add(o);
else
return false;
}
public boolean remove(Object o) {
final Iterator<E> e = iterator();
while (e.hasNext()) {
E next;
if (which != Subject.PRIV_CREDENTIAL_SET) {
next = e.next();
} else {
next = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<E>() {
public E run() {
return e.next();
}
});
}
if (next == null) {
if (o == null) {
e.remove();
return true;
}
} else if (next.equals(o)) {
e.remove();
return true;
}
}
return false;
}
public boolean contains(Object o) {
final Iterator<E> e = iterator();
while (e.hasNext()) {
E next;
if (which != Subject.PRIV_CREDENTIAL_SET) {
next = e.next();
} else {
// For private credentials:
// If the caller does not have read permission for
// for o.getClass(), we throw a SecurityException.
// Otherwise we check the private cred set to see whether
// it contains the Object
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new PrivateCredentialPermission
(o.getClass().getName(),
subject.getPrincipals()));
}
next = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<E>() {
public E run() {
return e.next();
}
});
}
if (next == null) {
if (o == null) {
return true;
}
} else if (next.equals(o)) {
return true;
}
}
return false;
}
public boolean removeAll(Collection<?> c) {
boolean modified = false;
final Iterator<E> e = iterator();
while (e.hasNext()) {
E next;
if (which != Subject.PRIV_CREDENTIAL_SET) {
next = e.next();
} else {
next = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<E>() {
public E run() {
return e.next();
}
});
}
Iterator<?> ce = c.iterator();
while (ce.hasNext()) {
Object o = ce.next();
if (next == null) {
if (o == null) {
e.remove();
modified = true;
break;
}
} else if (next.equals(o)) {
e.remove();
modified = true;
break;
}
}
}
return modified;
}
public boolean retainAll(Collection<?> c) {
boolean modified = false;
boolean retain = false;
final Iterator<E> e = iterator();
while (e.hasNext()) {
retain = false;
E next;
if (which != Subject.PRIV_CREDENTIAL_SET) {
next = e.next();
} else {
next = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<E>() {
public E run() {
return e.next();
}
});
}
Iterator<?> ce = c.iterator();
while (ce.hasNext()) {
Object o = ce.next();
if (next == null) {
if (o == null) {
retain = true;
break;
}
} else if (next.equals(o)) {
retain = true;
break;
}
}
if (!retain) {
e.remove();
retain = false;
modified = true;
}
}
return modified;
}
public void clear() {
final Iterator<E> e = iterator();
while (e.hasNext()) {
E next;
if (which != Subject.PRIV_CREDENTIAL_SET) {
next = e.next();
} else {
next = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<E>() {
public E run() {
return e.next();
}
});
}
e.remove();
}
}
/**
* Writes this object out to a stream (i.e., serializes it).
*
* <p>
*
* @serialData If this is a private credential set,
* a security check is performed to ensure that
* the caller has permission to access each credential
* in the set. If the security check passes,
* the set is serialized.
*/
private void writeObject(java.io.ObjectOutputStream oos)
throws java.io.IOException {
if (which == Subject.PRIV_CREDENTIAL_SET) {
// check permissions before serializing
Iterator<E> i = iterator();
while (i.hasNext()) {
i.next();
}
}
ObjectOutputStream.PutField fields = oos.putFields();
fields.put("this$0", subject);
fields.put("elements", elements);
fields.put("which", which);
oos.writeFields();
}
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException
{
ObjectInputStream.GetField fields = ois.readFields();
subject = (Subject) fields.get("this$0", null);
elements = (LinkedList<E>) fields.get("elements", null);
which = fields.get("which", 0);
}
}
/**
* This class implements a <code>Set</code> which returns only
* members that are an instance of a specified Class.
*/
private class ClassSet<T> extends AbstractSet<T> {
private int which;
private Class<T> c;
private Set<T> set;
ClassSet(int which, Class<T> c) {
this.which = which;
this.c = c;
set = new HashSet<T>();
switch (which) {
case Subject.PRINCIPAL_SET:
synchronized(principals) { populateSet(); }
break;
case Subject.PUB_CREDENTIAL_SET:
synchronized(pubCredentials) { populateSet(); }
break;
default:
synchronized(privCredentials) { populateSet(); }
break;
}
}
private void populateSet() {
final Iterator<?> iterator;
switch(which) {
case Subject.PRINCIPAL_SET:
iterator = Subject.this.principals.iterator();
break;
case Subject.PUB_CREDENTIAL_SET:
iterator = Subject.this.pubCredentials.iterator();
break;
default:
iterator = Subject.this.privCredentials.iterator();
break;
}
// Check whether the caller has permisson to get
// credentials of Class c
while (iterator.hasNext()) {
Object next;
if (which == Subject.PRIV_CREDENTIAL_SET) {
next = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<Object>() {
public Object run() {
return iterator.next();
}
});
} else {
next = iterator.next();
}
if (c.isAssignableFrom(next.getClass())) {
if (which != Subject.PRIV_CREDENTIAL_SET) {
set.add((T)next);
} else {
// Check permission for private creds
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new PrivateCredentialPermission
(next.getClass().getName(),
Subject.this.getPrincipals()));
}
set.add((T)next);
}
}
}
}
public int size() {
return set.size();
}
public Iterator<T> iterator() {
return set.iterator();
}
public boolean add(T o) {
if (!o.getClass().isAssignableFrom(c)) {
MessageFormat form = new MessageFormat(ResourcesMgr.getString
("attempting.to.add.an.object.which.is.not.an.instance.of.class"));
Object[] source = {c.toString()};
throw new SecurityException(form.format(source));
}
return set.add(o);
}
}
static class AuthPermissionHolder {
static final AuthPermission DO_AS_PERMISSION =
new AuthPermission("doAs");
static final AuthPermission DO_AS_PRIVILEGED_PERMISSION =
new AuthPermission("doAsPrivileged");
static final AuthPermission SET_READ_ONLY_PERMISSION =
new AuthPermission("setReadOnly");
static final AuthPermission GET_SUBJECT_PERMISSION =
new AuthPermission("getSubject");
static final AuthPermission MODIFY_PRINCIPALS_PERMISSION =
new AuthPermission("modifyPrincipals");
static final AuthPermission MODIFY_PUBLIC_CREDENTIALS_PERMISSION =
new AuthPermission("modifyPublicCredentials");
static final AuthPermission MODIFY_PRIVATE_CREDENTIALS_PERMISSION =
new AuthPermission("modifyPrivateCredentials");
}
}
| 54,546
|
Java
|
.java
| 1,280
| 31.554688
| 138
| 0.573515
|
openjdk-mirror/jdk7u-jdk
| 525
| 429
| 6
|
GPL-2.0
|
9/4/2024, 7:05:59 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 54,546
|
2,582,904
|
Stopwatch.java
|
JPortal-system_system/jdk12-06222165c35f/test/failure_handler/src/share/classes/jdk/test/failurehandler/Stopwatch.java
|
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.test.failurehandler;
public final class Stopwatch {
protected boolean isResultAvailable;
protected boolean isRunning;
private long startTimeNs;
private long stopTimeNs;
public Stopwatch() {
isResultAvailable = false;
}
/**
* Starts measuring time.
*/
public void start() {
startTimeNs = System.nanoTime();
isRunning = true;
}
/**
* Stops measuring time.
*/
public void stop() {
if (!isRunning) {
throw new IllegalStateException(" hasn't been started");
}
stopTimeNs = System.nanoTime();
isRunning = false;
isResultAvailable = true;
}
/**
* @return time in nanoseconds measured between
* calls of {@link #start()} and {@link #stop()} methods.
*
* @throws IllegalStateException if called without preceding
* {@link #start()} {@link #stop()} method
*/
public long getElapsedTimeNs() {
if (isRunning) {
throw new IllegalStateException("hasn't been stopped");
}
if (!isResultAvailable) {
throw new IllegalStateException("was not run");
}
return stopTimeNs - startTimeNs;
}
}
| 2,290
|
Java
|
.java
| 66
| 29.484848
| 76
| 0.68065
|
JPortal-system/system
| 7
| 2
| 1
|
GPL-3.0
|
9/4/2024, 9:49:36 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 2,290
|
3,292,922
|
OfToSalVlanPcpCase.java
|
ermin-sakic_sdn-automated-bootstrapping/odl-dependencies/openflowplugin-release-boron-sr2/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/convertor/match/cases/OfToSalVlanPcpCase.java
|
/*
* Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.match.cases;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.common.ConvertorCase;
import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.match.data.MatchResponseConvertorData;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.VlanMatchBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.VlanPcpCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.vlan.pcp._case.VlanPcp;
public class OfToSalVlanPcpCase extends ConvertorCase<VlanPcpCase, MatchBuilder, MatchResponseConvertorData> {
public OfToSalVlanPcpCase() {
super(VlanPcpCase.class, true, OFConstants.OFP_VERSION_1_0, OFConstants.OFP_VERSION_1_3);
}
@Override
public Optional<MatchBuilder> process(@Nonnull VlanPcpCase source, MatchResponseConvertorData data, ConvertorExecutor convertorExecutor) {
final MatchBuilder matchBuilder = data.getMatchBuilder();
final VlanMatchBuilder vlanMatchBuilder = data.getVlanMatchBuilder();
final VlanPcp vlanPcp = source.getVlanPcp();
if (vlanPcp != null) {
vlanMatchBuilder
.setVlanPcp(new org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanPcp(
vlanPcp.getVlanPcp()));
matchBuilder.setVlanMatch(vlanMatchBuilder.build());
}
return Optional.of(matchBuilder);
}
}
| 2,232
|
Java
|
.java
| 36
| 56.527778
| 144
| 0.784833
|
ermin-sakic/sdn-automated-bootstrapping
| 4
| 3
| 5
|
EPL-2.0
|
9/4/2024, 11:11:00 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 2,232
|
2,885,740
|
StringWriter.java
|
wordpress-mobile_WordPress-BlackBerry-Legacy/src/org/json/me/StringWriter.java
|
//#preprocess
//#ifndef BlackBerrySDK6.0.0 | BlackBerrySDK7.0.0
/*
* Copyright 2006 Sun Microsystems, Inc.
*/
package org.json.me;
import java.io.IOException;
import java.io.Writer;
/**
* A simple StringBuffer-based implementation of StringWriter
*/
public class StringWriter extends Writer {
final private StringBuffer buf;
public StringWriter() {
super();
buf = new StringBuffer();
}
public StringWriter(int initialSize) {
super();
buf = new StringBuffer(initialSize);
}
public void write(char[] cbuf, int off, int len) throws IOException {
buf.append(cbuf, off, len);
}
public void write(String str) throws IOException {
buf.append(str);
}
public void write(String str, int off, int len) throws IOException {
buf.append(str.substring(off, len));
}
public void flush() throws IOException {
}
public void close() throws IOException {
}
}
//#endif
| 997
|
Java
|
.java
| 36
| 22.555556
| 73
| 0.677039
|
wordpress-mobile/WordPress-BlackBerry-Legacy
| 5
| 4
| 0
|
GPL-2.0
|
9/4/2024, 10:32:34 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 997
|
4,296,116
|
Fci.java
|
vineet1992_tetrad-vineet/tetrad-lib/src/main/java/edu/cmu/tetrad/search/Fci.java
|
///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// //
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetrad.search;
import edu.cmu.tetrad.data.ICovarianceMatrix;
import edu.cmu.tetrad.data.IKnowledge;
import edu.cmu.tetrad.data.Knowledge2;
import edu.cmu.tetrad.data.KnowledgeEdge;
import edu.cmu.tetrad.graph.Edge;
import edu.cmu.tetrad.graph.Endpoint;
import edu.cmu.tetrad.graph.Graph;
import edu.cmu.tetrad.graph.Node;
import edu.cmu.tetrad.util.TetradLogger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Extends Erin Korber's implementation of the Fast Causal Inference algorithm (found in FCI.java) with Jiji Zhang's
* Augmented FCI rules (found in sec. 4.1 of Zhang's 2006 PhD dissertation, "Causal Inference and Reasoning in Causally
* Insufficient Systems").
* <p>
* This class is based off a copy of FCI.java taken from the repository on 2008/12/16, revision 7306. The extension is
* done by extending doFinalOrientation() with methods for Zhang's rules R5-R10 which implements the augmented search.
* (By a remark of Zhang's, the rule applications can be staged in this way.)
*
* @author Erin Korber, June 2004
* @author Alex Smith, December 2008
* @author Joseph Ramsey
* @author Choh-Man Teng
*/
public final class Fci implements GraphSearch {
/**
* The PAG being constructed.
*/
private Graph graph;
/**
* The SepsetMap being constructed.
*/
private SepsetMap sepsets;
/**
* The background knowledge.
*/
private IKnowledge knowledge = new Knowledge2();
/**
* The variables to search over (optional)
*/
private List<Node> variables = new ArrayList<Node>();
private IndependenceTest independenceTest;
/**
* flag for complete rule set, true if should use complete rule set, false otherwise.
*/
private boolean completeRuleSetUsed = false;
/**
* True iff the possible dsep search is done.
*/
private boolean possibleDsepSearchDone = true;
/**
* The maximum length for any discriminating path. -1 if unlimited; otherwise, a positive integer.
*/
private int maxPathLength = -1;
/**
* The depth for the fast adjacency search.
*/
private int depth = -1;
/**
* Elapsed time of last search.
*/
private long elapsedTime;
/**
* The logger to use.
*/
private TetradLogger logger = TetradLogger.getInstance();
/**
* True iff verbose output should be printed.
*/
public ConcurrentHashMap<String,String> whyOrient;
/*
Maps from "<Node>,<Node>" to integer, where integer describes which rule oriented node -> node as an arrowhead
Useful for determining the relative efficacy of each rule in finding latent confounders
*/
private boolean verbose = false;
private Graph truePag;
private ConcurrentMap<Node, Integer> hashIndices;
private ICovarianceMatrix covarianceMatrix;
private double penaltyDiscount = 2;
private SepsetMap possibleDsepSepsets = new SepsetMap();
private Graph initialGraph;
private int possibleDsepDepth = -1;
//============================CONSTRUCTORS============================//
/**
* Constructs a new FCI search for the given independence test and background knowledge.
*/
public Fci(IndependenceTest independenceTest) {
if (independenceTest == null || knowledge == null) {
throw new NullPointerException();
}
this.independenceTest = independenceTest;
this.variables.addAll(independenceTest.getVariables());
buildIndexing(independenceTest.getVariables());
}
/**
* Constructs a new FCI search for the given independence test and background knowledge and a list of variables to
* search over.
*/
public Fci(IndependenceTest independenceTest, List<Node> searchVars) {
if (independenceTest == null || knowledge == null) {
throw new NullPointerException();
}
this.independenceTest = independenceTest;
this.variables.addAll(independenceTest.getVariables());
Set<Node> remVars = new HashSet<Node>();
for (Node node1 : this.variables) {
boolean search = false;
for (Node node2 : searchVars) {
if (node1.getName().equals(node2.getName())) {
search = true;
}
}
if (!search) {
remVars.add(node1);
}
}
this.variables.removeAll(remVars);
}
//========================PUBLIC METHODS==========================//
public int getDepth() {
return depth;
}
public void setDepth(int depth) {
if (depth < -1) {
throw new IllegalArgumentException(
"Depth must be -1 (unlimited) or >= 0: " + depth);
}
this.depth = depth;
}
public long getElapsedTime() {
return this.elapsedTime;
}
public Graph search() {
return search(new FasStableConcurrent(initialGraph, getIndependenceTest()));
}
public void setInitialGraph(Graph initialGraph) {
this.initialGraph = initialGraph;
}
public Graph search(IFas fas) {
whyOrient = new ConcurrentHashMap<String,String>();
logger.log("info", "Starting FCI algorithm.");
logger.log("info", "Independence test = " + getIndependenceTest() + ".");
fas.setKnowledge(getKnowledge());
fas.setDepth(depth);
fas.setVerbose(verbose);
this.graph = fas.search();
this.sepsets = fas.getSepsets();
graph.reorientAllWith(Endpoint.CIRCLE);
SepsetProducer sp = new SepsetsPossibleDsep(graph, independenceTest, knowledge, depth, maxPathLength);
sp.setVerbose(verbose);
// The original FCI, with or without JiJi Zhang's orientation rules
// // Optional step: Possible Dsep. (Needed for correctness but very time consuming.)
if (isPossibleDsepSearchDone()) {
// long time1 = System.currentTimeMillis();
new FciOrient(new SepsetsSet(this.sepsets, independenceTest)).ruleR0(graph);
for (Edge edge : new ArrayList<>(graph.getEdges())) {
Node x = edge.getNode1();
Node y = edge.getNode2();
List<Node> sepset = sp.getSepset(x, y);
if (sepset != null) {
graph.removeEdge(x, y);
sepsets.set(x, y, sepset);
if (verbose) {
System.out.println("Possible DSEP Removed " + x + "--- " + y + " sepset = " + sepset);
}
}
}
// long time2 = System.currentTimeMillis();
// logger.log("info", "Step C: " + (time2 - time1) / 1000. + "s");
//
// // Step FCI D.
// long time3 = System.currentTimeMillis();
//
// System.out.println("Starting possible dsep search");
// PossibleDsepFci possibleDSep = new PossibleDsepFci(graph, independenceTest);
// possibleDSep.setMaxIndegree(getPossibleDsepDepth());
// possibleDSep.setKnowledge(getKnowledge());
// possibleDSep.setMaxPathLength(maxPathLength);
// this.sepsets.addAll(possibleDSep.search());
// long time4 = System.currentTimeMillis();
// logger.log("info", "Step D: " + (time4 - time3) / 1000. + "s");
// System.out.println("Starting possible dsep search");
// Reorient all edges as o-o.
graph.reorientAllWith(Endpoint.CIRCLE);
}
// Step CI C (Zhang's step F3.)
long time5 = System.currentTimeMillis();
//fciOrientbk(getKnowledge(), graph, independenceTest.getVariables()); - Robert Tillman 2008
// fciOrientbk(getKnowledge(), graph, variables);
// new FciOrient(graph, new Sepsets(this.sepsets)).ruleR0(new Sepsets(this.sepsets));
long time6 = System.currentTimeMillis();
logger.log("info", "Step CI C: " + (time6 - time5) / 1000. + "s");
final FciOrient fciOrient = new FciOrient(new SepsetsSet(this.sepsets, independenceTest),whyOrient);
fciOrient.setCompleteRuleSetUsed(completeRuleSetUsed);
fciOrient.setMaxPathLength(maxPathLength);
fciOrient.setKnowledge(knowledge);
fciOrient.ruleR0(graph);
fciOrient.doFinalOrientation(graph);
return graph;
}
public SepsetMap getSepsets() {
return this.sepsets;
}
public IKnowledge getKnowledge() {
return knowledge;
}
public void setKnowledge(IKnowledge knowledge) {
if (knowledge == null) {
throw new NullPointerException();
}
this.knowledge = knowledge;
}
/**
* @return true if Zhang's complete rule set should be used, false if only R1-R4 (the rule set of the original FCI)
* should be used. False by default.
*/
public boolean isCompleteRuleSetUsed() {
return completeRuleSetUsed;
}
/**
* @param completeRuleSetUsed set to true if Zhang's complete rule set should be used, false if only R1-R4 (the rule
* set of the original FCI) should be used. False by default.
*/
public void setCompleteRuleSetUsed(boolean completeRuleSetUsed) {
this.completeRuleSetUsed = completeRuleSetUsed;
}
public boolean isPossibleDsepSearchDone() {
return possibleDsepSearchDone;
}
public void setPossibleDsepSearchDone(boolean possibleDsepSearchDone) {
this.possibleDsepSearchDone = possibleDsepSearchDone;
}
/**
* @return the maximum length of any discriminating path, or -1 of unlimited.
*/
public int getMaxPathLength() {
return maxPathLength == Integer.MAX_VALUE ? -1 : maxPathLength;
}
/**
* @param maxPathLength the maximum length of any discriminating path, or -1 if unlimited.
*/
public void setMaxPathLength(int maxPathLength) {
if (maxPathLength < -1) {
throw new IllegalArgumentException("Max path length must be -1 (unlimited) or >= 0: " + maxPathLength);
}
this.maxPathLength = maxPathLength;
}
/**
* True iff verbose output should be printed.
*/
public boolean isVerbose() {
return verbose;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
/**
* The independence test.
*/
public IndependenceTest getIndependenceTest() {
return independenceTest;
}
public void setTruePag(Graph truePag) {
this.truePag = truePag;
}
public double getPenaltyDiscount() {
return penaltyDiscount;
}
public void setPenaltyDiscount(double penaltyDiscount) {
this.penaltyDiscount = penaltyDiscount;
}
//===========================PRIVATE METHODS=========================//
private void buildIndexing(List<Node> nodes) {
this.hashIndices = new ConcurrentHashMap<Node, Integer>();
for (Node node : nodes) {
this.hashIndices.put(node, variables.indexOf(node));
}
}
/**
* Orients according to background knowledge
*/
private void fciOrientbk(IKnowledge bk, Graph graph, List<Node> variables) {
logger.log("info", "Starting BK Orientation.");
for (Iterator<KnowledgeEdge> it =
bk.forbiddenEdgesIterator(); it.hasNext(); ) {
KnowledgeEdge edge = it.next();
//match strings to variables in the graph.
Node from = SearchGraphUtils.translate(edge.getFrom(), variables);
Node to = SearchGraphUtils.translate(edge.getTo(), variables);
if (from == null || to == null) {
continue;
}
if (graph.getEdge(from, to) == null) {
continue;
}
// Orient to*->from
graph.setEndpoint(to, from, Endpoint.ARROW);
graph.setEndpoint(from, to, Endpoint.CIRCLE);
logger.log("knowledgeOrientation", SearchLogUtils.edgeOrientedMsg("Knowledge", graph.getEdge(from, to)));
}
for (Iterator<KnowledgeEdge> it =
bk.requiredEdgesIterator(); it.hasNext(); ) {
KnowledgeEdge edge = it.next();
//match strings to variables in this graph
Node from = SearchGraphUtils.translate(edge.getFrom(), variables);
Node to = SearchGraphUtils.translate(edge.getTo(), variables);
if (from == null || to == null) {
continue;
}
if (graph.getEdge(from, to) == null) {
continue;
}
graph.setEndpoint(to, from, Endpoint.TAIL);
graph.setEndpoint(from, to, Endpoint.ARROW);
logger.log("knowledgeOrientation", SearchLogUtils.edgeOrientedMsg("Knowledge", graph.getEdge(from, to)));
}
logger.log("info", "Finishing BK Orientation.");
}
public int getPossibleDsepDepth() {
return possibleDsepDepth;
}
public void setPossibleDsepDepth(int possibleDsepDepth) {
this.possibleDsepDepth = possibleDsepDepth;
}
}
| 14,882
|
Java
|
.java
| 348
| 35.520115
| 120
| 0.610327
|
vineet1992/tetrad-vineet
| 2
| 1
| 4
|
GPL-2.0
|
9/5/2024, 12:08:25 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| true
| false
| true
| 14,882
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.