repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
anandswarupv/DataCleaner | monitor/services/src/test/java/org/datacleaner/monitor/jobwizard/common/SelectTableWizardPageTest.java | 4135 | /**
* DataCleaner (community edition)
* Copyright (C) 2014 Neopost - Customer Information Management
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions 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 distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.datacleaner.monitor.jobwizard.common;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.easymock.EasyMock;
import org.datacleaner.connection.Datastore;
import org.datacleaner.connection.PojoDatastore;
import org.datacleaner.monitor.wizard.WizardPageController;
import org.datacleaner.monitor.wizard.common.SelectTableWizardPage;
import org.datacleaner.monitor.wizard.job.JobWizardContext;
import org.apache.metamodel.pojo.ArrayTableDataProvider;
import org.apache.metamodel.pojo.TableDataProvider;
import org.apache.metamodel.schema.Table;
import org.apache.metamodel.util.SimpleTableDef;
public class SelectTableWizardPageTest extends TestCase {
public void testGetFormInnerHtml() throws Exception {
final List<TableDataProvider<?>> tableDataProviders = new ArrayList<TableDataProvider<?>>();
final SimpleTableDef tableDef1 = new SimpleTableDef("tab", new String[] { "col1", "col2", "col3" });
final SimpleTableDef tableDef2 = new SimpleTableDef("le", new String[] { "col1", "col2", "col3" });
tableDataProviders.add(new ArrayTableDataProvider(tableDef1, new ArrayList<Object[]>()));
tableDataProviders.add(new ArrayTableDataProvider(tableDef2, new ArrayList<Object[]>()));
final Datastore datastore = new PojoDatastore("my_pojo_ds", tableDataProviders);
final JobWizardContext context = EasyMock.createMock(JobWizardContext.class);
EasyMock.expect(context.getSourceDatastore()).andReturn(datastore);
EasyMock.replay(context);
final Integer pageIndex = 1;
final SelectTableWizardPage page = new SelectTableWizardPage(context, pageIndex) {
@Override
protected WizardPageController nextPageController(Table selectedTable) {
throw new IllegalStateException("Should not happen in this test");
}
};
final String formInnerHtml1 = page.getFormInnerHtml();
assertEquals("<div>\n" +
" <p>Please select the source table of the job:</p>\n" +
" <select name=\"tableName\">\n" +
" <optgroup label=\"my_pojo_ds\">\n" +
" <option value=\"my_pojo_ds.le\">le</option>\n" +
" <option value=\"my_pojo_ds.tab\">tab</option>\n" +
" </optgroup>\n" +
" </select>\n" +
"</div>", formInnerHtml1.replaceAll("\t", " ").replaceAll("\r\n", "\n"));
page.setSelectedTableName("my_pojo_ds.tab");
final String formInnerHtml2 = page.getFormInnerHtml();
assertEquals("<div>\n" +
" <p>Please select the source table of the job:</p>\n" +
" <select name=\"tableName\">\n" +
" <optgroup label=\"my_pojo_ds\">\n" +
" <option value=\"my_pojo_ds.le\">le</option>\n" +
" <option value=\"my_pojo_ds.tab\" selected=\"selected\">tab</option>\n" +
" </optgroup>\n" +
" </select>\n" +
"</div>", formInnerHtml2.replaceAll("\t", " ").replaceAll("\r\n", "\n"));
EasyMock.verify(context);
}
}
| lgpl-3.0 |
anandswarupv/DataCleaner | engine/core/src/main/java/org/datacleaner/metadata/DatastoreMetadataImpl.java | 2027 | /**
* DataCleaner (community edition)
* Copyright (C) 2014 Neopost - Customer Information Management
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions 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 distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.datacleaner.metadata;
import java.util.Collection;
import java.util.List;
import org.apache.metamodel.schema.Schema;
import com.google.common.collect.ImmutableList;
/**
* Default (immutable) implementation of {@link DatastoreMetadata}.
*/
public final class DatastoreMetadataImpl extends AbstractHasMetadataAnnotations implements DatastoreMetadata {
private final ImmutableList<SchemaMetadata> _schemaMetadata;
public DatastoreMetadataImpl(Collection<? extends SchemaMetadata> schemaMetadata,
Collection<? extends MetadataAnnotation> annotations) {
super(annotations);
_schemaMetadata = ImmutableList.copyOf(schemaMetadata);
}
@Override
public SchemaMetadata getSchemaMetadataByName(String schemaName) {
return getByName(schemaName, _schemaMetadata);
}
@Override
public SchemaMetadata getSchemaMetadata(Schema schema) {
if (schema == null) {
return null;
}
final String schemaName = schema.getName();
return getSchemaMetadataByName(schemaName);
}
@Override
public List<SchemaMetadata> getSchemaMetadata() {
return _schemaMetadata;
}
}
| lgpl-3.0 |
jblievremont/sonarqube | server/sonar-server/src/main/java/org/sonar/server/component/db/ComponentDao.java | 8754 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.component.db;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.ibatis.session.RowBounds;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
import org.sonar.api.server.ServerSide;
import org.sonar.core.component.ComponentDto;
import org.sonar.core.component.FilePathWithHashDto;
import org.sonar.core.component.UuidWithProjectUuidDto;
import org.sonar.core.component.db.ComponentMapper;
import org.sonar.core.persistence.DaoComponent;
import org.sonar.core.persistence.DaoUtils;
import org.sonar.core.persistence.DbSession;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.exceptions.NotFoundException;
import static com.google.common.collect.Maps.newHashMapWithExpectedSize;
/**
* @since 4.3
*/
@ServerSide
public class ComponentDao implements DaoComponent {
public ComponentDto selectById(Long id, DbSession session) {
ComponentDto componentDto = selectNullableById(id, session);
if (componentDto == null) {
throw new NotFoundException(String.format("Project with id '%s' not found", id));
}
return componentDto;
}
@CheckForNull
public ComponentDto selectNullableById(Long id, DbSession session) {
return mapper(session).selectById(id);
}
@CheckForNull
public ComponentDto selectNullableByUuid(DbSession session, String uuid) {
return mapper(session).selectByUuid(uuid);
}
public ComponentDto selectByUuid(DbSession session, String uuid) {
ComponentDto componentDto = selectNullableByUuid(session, uuid);
if (componentDto == null) {
throw new NotFoundException(String.format("Component with uuid '%s' not found", uuid));
}
return componentDto;
}
public boolean existsById(Long id, DbSession session) {
return mapper(session).countById(id) > 0;
}
public List<ComponentDto> selectSubProjectsByComponentUuids(DbSession session, Collection<String> keys) {
if (keys.isEmpty()) {
return Collections.emptyList();
}
return mapper(session).selectSubProjectsByComponentUuids(keys);
}
public List<ComponentDto> selectDescendantModules(DbSession session, String rootComponentUuid) {
return mapper(session).selectDescendantModules(rootComponentUuid, Scopes.PROJECT, false);
}
public List<ComponentDto> selectEnabledDescendantModules(DbSession session, String rootComponentUuid) {
return mapper(session).selectDescendantModules(rootComponentUuid, Scopes.PROJECT, true);
}
public List<FilePathWithHashDto> selectEnabledDescendantFiles(DbSession session, String rootComponentUuid) {
return mapper(session).selectDescendantFiles(rootComponentUuid, Scopes.FILE, true);
}
public List<FilePathWithHashDto> selectEnabledFilesFromProject(DbSession session, String rootComponentUuid) {
return mapper(session).selectEnabledFilesFromProject(rootComponentUuid);
}
public List<ComponentDto> selectByIds(final DbSession session, Collection<Long> ids) {
return DaoUtils.executeLargeInputs(ids, new Function<List<Long>, List<ComponentDto>>() {
@Override
public List<ComponentDto> apply(List<Long> partition) {
return mapper(session).selectByIds(partition);
}
});
}
public List<ComponentDto> selectByUuids(final DbSession session, Collection<String> uuids) {
return DaoUtils.executeLargeInputs(uuids, new Function<List<String>, List<ComponentDto>>() {
@Override
public List<ComponentDto> apply(List<String> partition) {
return mapper(session).selectByUuids(partition);
}
});
}
public List<String> selectExistingUuids(final DbSession session, Collection<String> uuids) {
return DaoUtils.executeLargeInputs(uuids, new Function<List<String>, List<String>>() {
@Override
public List<String> apply(List<String> partition) {
return mapper(session).selectExistingUuids(partition);
}
});
}
public List<ComponentDto> selectComponentsFromProjectKey(DbSession session, String projectKey) {
return mapper(session).selectComponentsFromProjectKeyAndScope(projectKey, null);
}
public List<ComponentDto> selectModulesFromProjectKey(DbSession session, String projectKey) {
return mapper(session).selectComponentsFromProjectKeyAndScope(projectKey, Scopes.PROJECT);
}
public List<ComponentDto> selectByKeys(DbSession session, Collection<String> keys) {
return mapper(session).selectByKeys(keys);
}
public ComponentDto selectByKey(DbSession session, String key) {
ComponentDto value = selectNullableByKey(session, key);
if (value == null) {
throw new NotFoundException(String.format("Component key '%s' not found", key));
}
return mapper(session).selectByKey(key);
}
@CheckForNull
public ComponentDto selectNullableByKey(DbSession session, String key) {
return mapper(session).selectByKey(key);
}
public List<UuidWithProjectUuidDto> selectAllViewsAndSubViews(DbSession session) {
return mapper(session).selectUuidsForQualifiers(Qualifiers.VIEW, Qualifiers.SUBVIEW);
}
public List<String> selectProjectsFromView(DbSession session, String viewUuid, String projectViewUuid) {
return mapper(session).selectProjectsFromView("%." + viewUuid + ".%", projectViewUuid);
}
public List<ComponentDto> selectProvisionedProjects(DbSession session, SearchOptions searchOptions, @Nullable String query) {
Map<String, String> parameters = newHashMapWithExpectedSize(2);
addProjectQualifier(parameters);
addPartialQueryParameterIfNotNull(parameters, query);
return mapper(session).selectProvisionedProjects(parameters, new RowBounds(searchOptions.getOffset(), searchOptions.getLimit()));
}
public int countProvisionedProjects(DbSession session, @Nullable String query) {
Map<String, String> parameters = newHashMapWithExpectedSize(2);
addProjectQualifier(parameters);
addPartialQueryParameterIfNotNull(parameters, query);
return mapper(session).countProvisionedProjects(parameters);
}
public List<ComponentDto> selectGhostProjects(DbSession session, @Nullable String query, SearchOptions options) {
Map<String, String> parameters = newHashMapWithExpectedSize(2);
addProjectQualifier(parameters);
addPartialQueryParameterIfNotNull(parameters, query);
return mapper(session).selectGhostProjects(parameters, new RowBounds(options.getOffset(), options.getLimit()));
}
public long countGhostProjects(DbSession session, @Nullable String query) {
Map<String, String> parameters = newHashMapWithExpectedSize(2);
addProjectQualifier(parameters);
addPartialQueryParameterIfNotNull(parameters, query);
return mapper(session).countGhostProjects(parameters);
}
private static void addPartialQueryParameterIfNotNull(Map<String, String> parameters, @Nullable String query) {
if (query != null) {
parameters.put("query", "%" + query.toUpperCase() + "%");
}
}
private static void addProjectQualifier(Map<String, String> parameters) {
parameters.put("qualifier", Qualifiers.PROJECT);
}
public void insert(DbSession session, ComponentDto item) {
mapper(session).insert(item);
}
public void insert(DbSession session, Collection<ComponentDto> items) {
for (ComponentDto item : items) {
insert(session, item);
}
}
public void insert(DbSession session, ComponentDto item, ComponentDto... others) {
insert(session, Lists.asList(item, others));
}
public void update(DbSession session, ComponentDto item) {
mapper(session).update(item);
}
private ComponentMapper mapper(DbSession session) {
return session.getMapper(ComponentMapper.class);
}
}
| lgpl-3.0 |
vanZeben/NPCCreatures | src/main/java/ch/spacebase/npccreatures/npcs/nms/NPCZombie.java | 1523 | package ch.spacebase.npccreatures.npcs.nms;
import java.util.ConcurrentModificationException;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.entity.Player;
import net.minecraft.server.DamageSource;
import net.minecraft.server.Entity;
import net.minecraft.server.EntityZombie;
import net.minecraft.server.Packet34EntityTeleport;
import net.minecraft.server.World;
public class NPCZombie extends EntityZombie {
public NPCZombie(World world) {
super(world);
this.damage = 0;
}
public void setBukkitEntity(org.bukkit.entity.Entity entity) {
this.bukkitEntity = entity;
}
@Override
public void move(double arg0, double arg1, double arg2) {
}
@Override
public boolean damageEntity(DamageSource source, int damage) {
return false;
}
@Override
public void die() {
}
@Override
protected Entity findTarget() {
return null;
}
// PathFinding
@Override
protected void d_() {
}
// Stroll
@Override
public void G() {
}
// Movement?
@Override
public void e() {
try {
final Location loc = this.getBukkitEntity().getLocation();
final List<Player> players = this.world.getWorld().getPlayers();
final Packet34EntityTeleport packet = new Packet34EntityTeleport(this);
for (Player player : players) {
if (player.getLocation().distanceSquared(loc) < 4096) {
((CraftPlayer) player).getHandle().netServerHandler.sendPacket(packet);
}
}
} catch (ConcurrentModificationException ex) {
}
}
}
| lgpl-3.0 |
AtomicBlom/SteamNSteel | src/main/java/mod/steamnsteel/block/SteamNSteelMachineBlock.java | 4873 | /*
* Copyright (c) 2014 Rosie Alexander and Scott Killen.
*
* 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 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 mod.steamnsteel.block;
import com.google.common.base.Objects;
import mod.steamnsteel.utility.position.WorldBlockCoord;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import java.util.Random;
public abstract class SteamNSteelMachineBlock extends SteamNSteelDirectionalBlock
{
private static final Material MATERIAL = Material.piston;
private static final SoundType SOUND = Block.soundTypePiston;
private static final float HARDNESS = 0.5f;
@SuppressWarnings("UnsecureRandomNumberGeneration")
private final Random rng = new Random();
protected SteamNSteelMachineBlock()
{
super(MATERIAL);
setStepSound(SOUND);
setHardness(HARDNESS);
}
@Override
public boolean renderAsNormalBlock()
{
return false;
}
@Override
public int getRenderType()
{
// Disable normal block rendering.
return -1;
}
@Override
public boolean isOpaqueCube()
{
return false;
}
@Override
public boolean onBlockEventReceived(World world, int x, int y, int z, int eventId, int eventParameter)
{
super.onBlockEventReceived(world, x, y, z, eventId, eventParameter);
final TileEntity te = world.getTileEntity(x, y, z);
return te != null && te.receiveClientEvent(eventId, eventParameter);
}
@Override
public int getMobilityFlag()
{
// total immobility and stop pistons
return 2;
}
@SuppressWarnings("NoopMethodInAbstractClass")
@Override
public void registerBlockIcons(IIconRegister iconRegister)
{
// no op
}
protected void dropInventory(World world, WorldBlockCoord coord, IInventory inventory)
{
for (int slotIndex = 0; slotIndex < inventory.getSizeInventory(); slotIndex++)
{
dropSlotContents(world, coord, inventory, slotIndex);
}
}
void dropSlotContents(World world, WorldBlockCoord coord, IInventory inventory, int slotIndex)
{
final ItemStack itemstack = inventory.getStackInSlot(slotIndex);
if (itemstack != null)
{
final float xOffset = rng.nextFloat() * 0.8F + 0.1F;
final float yOffset = rng.nextFloat() * 0.8F + 0.1F;
final float zOffset = rng.nextFloat() * 0.8F + 0.1F;
while (itemstack.stackSize > 0)
{
int j1 = rng.nextInt(21) + 10;
if (j1 > itemstack.stackSize)
{
j1 = itemstack.stackSize;
}
itemstack.stackSize -= j1;
//noinspection ObjectAllocationInLoop
final EntityItem entityitem = new EntityItem(world,
coord.getX() + xOffset, coord.getY() + yOffset, coord.getZ() + zOffset,
new ItemStack(itemstack.getItem(), j1, itemstack.getItemDamage()));
final float motionMax = 0.05F;
//noinspection NumericCastThatLosesPrecision
entityitem.motionX = (float) rng.nextGaussian() * motionMax;
//noinspection NumericCastThatLosesPrecision
entityitem.motionY = (float) rng.nextGaussian() * motionMax + 0.2F;
//noinspection NumericCastThatLosesPrecision
entityitem.motionZ = (float) rng.nextGaussian() * motionMax;
if (itemstack.hasTagCompound())
{
entityitem.getEntityItem().setTagCompound((NBTTagCompound) itemstack.getTagCompound().copy());
}
world.spawnEntityInWorld(entityitem);
}
}
}
@Override
public String toString()
{
return Objects.toStringHelper(this)
.add("rng", rng)
.toString();
}
}
| lgpl-3.0 |
Glydar/Glydar.next | glydar-core/src/main/java/org/glydar/core/protocol/packet/Packet09Shoot.java | 4822 | package org.glydar.core.protocol.packet;
import io.netty.buffer.ByteBuf;
import org.glydar.api.model.geom.FloatVector3;
import org.glydar.api.model.geom.IntVector2;
import org.glydar.api.model.geom.LongVector3;
import org.glydar.core.protocol.Packet;
import org.glydar.core.protocol.PacketType;
import org.glydar.core.protocol.ProtocolHandler;
import org.glydar.core.protocol.Remote;
import org.glydar.core.protocol.RemoteType;
import org.glydar.core.protocol.codec.GeomCodec;
/* Structures and data discovered by cuwo (http://github.com/matpow2) */
public class Packet09Shoot implements Packet {
private final long entityId; // Unsigned!
private final IntVector2 chunkPosition;
private final long something5; // Unsigned Int!
private final LongVector3 position;
private final long something13; // uint
private final long something14; // uint
private final long something15; // uint
private final FloatVector3 velocity;
private final float something19; // rand() ??
private final float something20;
private final float something21;
private final float something22; // ?????
private final long something23; // uint
private final byte something24;
private final long something25; // uint
private final byte something26;
private final long something27; // uint
private final long something28; // uint
public Packet09Shoot(ByteBuf buf) {
this.entityId = buf.readLong(); // Unsigned long actually!
this.chunkPosition = GeomCodec.readIntVector2(buf);
this.something5 = buf.readUnsignedInt();
buf.skipBytes(4);
this.position = GeomCodec.readLongVector3(buf);
this.something13 = buf.readUnsignedInt();
this.something14 = buf.readUnsignedInt();
this.something15 = buf.readUnsignedInt();
this.velocity = GeomCodec.readFloatVector3(buf);
this.something19 = buf.readFloat();
this.something20 = buf.readFloat();
this.something21 = buf.readFloat();
this.something22 = buf.readFloat();
this.something23 = buf.readUnsignedInt();
this.something24 = buf.readByte();
buf.skipBytes(3);
this.something25 = buf.readUnsignedInt();
this.something26 = buf.readByte();
buf.skipBytes(3);
this.something27 = buf.readUnsignedInt();
this.something28 = buf.readUnsignedInt();
}
@Override
public PacketType getPacketType() {
return PacketType.SHOOT;
}
@Override
public void writeTo(RemoteType receiver, ByteBuf buf) {
buf.writeLong(entityId);
GeomCodec.writeIntVector2(buf, chunkPosition);
buf.writeInt((int) something5);
buf.writeZero(4);
GeomCodec.writeLongVector3(buf, position);
buf.writeInt((int) something13);
buf.writeInt((int) something14);
buf.writeInt((int) something15);
GeomCodec.writeFloatVector3(buf, velocity);
buf.writeFloat(something19);
buf.writeFloat(something20);
buf.writeFloat(something21);
buf.writeFloat(something22);
buf.writeInt((int) something23);
buf.writeByte(something24);
buf.writeZero(3);
buf.writeInt((int) something25);
buf.writeByte(something26);
buf.writeZero(3);
buf.writeInt((int) something27);
buf.writeInt((int) something28);
}
@Override
public <T extends Remote> void dispatchTo(ProtocolHandler<T> handler, T remote) {
handler.handle(remote, this);
}
public long getEntityId() {
return entityId;
}
public IntVector2 getChunkPosition() {
return chunkPosition;
}
public long getSomething5() {
return something5;
}
public LongVector3 getPosition() {
return position;
}
public long getSomething13() {
return something13;
}
public long getSomething14() {
return something14;
}
public long getSomething15() {
return something15;
}
public FloatVector3 getVelocity() {
return velocity;
}
public float getSomething19() {
return something19;
}
public float getSomething20() {
return something20;
}
public float getSomething21() {
return something21;
}
public float getSomething22() {
return something22;
}
public float getSomething23() {
return something23;
}
public float getSomething24() {
return something24;
}
public float getSomething25() {
return something25;
}
public float getSomething26() {
return something26;
}
public float getSomething27() {
return something27;
}
public float getSomething28() {
return something28;
}
}
| lgpl-3.0 |
jjm223/MyPet | modules/v1_9_R2/src/main/java/de/Keyle/MyPet/compat/v1_9_R2/skill/skills/ranged/nms/MyPetSmallFireball.java | 3093 | /*
* This file is part of MyPet
*
* Copyright © 2011-2016 Keyle
* MyPet is licensed under the GNU Lesser General Public License.
*
* MyPet 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.
*
* MyPet 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 de.Keyle.MyPet.compat.v1_9_R2.skill.skills.ranged.nms;
import de.Keyle.MyPet.api.skill.skills.ranged.EntityMyPetProjectile;
import de.Keyle.MyPet.api.util.Compat;
import de.Keyle.MyPet.compat.v1_9_R2.entity.EntityMyPet;
import de.Keyle.MyPet.compat.v1_9_R2.skill.skills.ranged.bukkit.CraftMyPetSmallFireball;
import net.minecraft.server.v1_9_R2.*;
import org.bukkit.craftbukkit.v1_9_R2.entity.CraftEntity;
@Compat("v1_9_R2")
public class MyPetSmallFireball extends EntitySmallFireball implements EntityMyPetProjectile {
protected float damage = 0;
protected int deathCounter = 100;
public MyPetSmallFireball(World world, EntityMyPet entityliving, double d0, double d1, double d2) {
super(world, entityliving, d0, d1, d2);
}
@Override
public EntityMyPet getShooter() {
return (EntityMyPet) this.shooter;
}
public void setDamage(float damage) {
this.damage = damage;
}
@Override
public void setDirection(double d0, double d1, double d2) {
d0 += this.random.nextGaussian() * 0.2D;
d1 += this.random.nextGaussian() * 0.2D;
d2 += this.random.nextGaussian() * 0.2D;
double d3 = MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2);
this.dirX = (d0 / d3 * 0.1D);
this.dirY = (d1 / d3 * 0.1D);
this.dirZ = (d2 / d3 * 0.1D);
}
@Override
public CraftEntity getBukkitEntity() {
if (this.bukkitEntity == null) {
this.bukkitEntity = new CraftMyPetSmallFireball(this.world.getServer(), this);
}
return this.bukkitEntity;
}
@Override
public void a(NBTTagCompound nbtTagCompound) {
}
@Override
public void b(NBTTagCompound nbtTagCompound) {
}
@Override
protected void a(MovingObjectPosition movingobjectposition) {
if (movingobjectposition.entity != null) {
movingobjectposition.entity.damageEntity(DamageSource.fireball(this, this.shooter), damage);
}
die();
}
public void m() {
try {
super.m();
if (deathCounter-- <= 0) {
die();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean damageEntity(DamageSource damagesource, float f) {
return false;
}
} | lgpl-3.0 |
demoiselle/vaadin | impl/src/main/java/br/gov/frameworkdemoiselle/vaadin/template/CrudView.java | 2437 | /*
* Demoiselle Framework
* Copyright (C) 2010 SERPRO
* ----------------------------------------------------------------------------
* This file is part of Demoiselle Framework.
*
* Demoiselle Framework is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License version 3
* 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 for more details.
*
* You should have received a copy of the GNU Lesser General Public License version 3
* along with this program; if not, see <http://www.gnu.org/licenses/>
* or write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301, USA.
* ----------------------------------------------------------------------------
* Este arquivo é parte do Framework Demoiselle.
*
* O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou
* modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação
* do Software Livre (FSF).
*
* Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA
* GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou
* APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português
* para maiores detalhes.
*
* Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título
* "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/>
* ou escreva para a Fundação do Software Livre (FSF) Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA.
*/
package br.gov.frameworkdemoiselle.vaadin.template;
import java.util.List;
/**
* Extends View interface adding behavior related to CRUD operations.
*
* @author Marlon
*/
public interface CrudView<Bean> extends View {
/**
* Get the bean which will receive CRUD operations.
*
* @return Bean.
*/
Bean getBean();
/**
* Set the bean which will receive CRUD operations.
*
* @param bean
* Bean.
*/
void setBean(Bean bean);
/**
* Clear the bean.
*/
void clear();
/**
* Set the list of beans.
*
* @param list
* List.
*/
void setList(List<Bean> list);
}
| lgpl-3.0 |
jmeppley/strainer | src/amd/strainer/display/LettersDisplayGeometry.java | 1914 | package amd.strainer.display;
import java.awt.Graphics2D;
import java.util.HashSet;
import amd.strainer.display.util.DiffLetterInfo;
import amd.strainer.objects.SequenceFragment;
public class LettersDisplayGeometry extends DisplayGeometry {
private HashSet<DiffLetterInfo> mLetters = new HashSet<DiffLetterInfo>();
public HashSet<DiffLetterInfo> getLetters() {
return mLetters;
}
public void setLetters(HashSet<DiffLetterInfo> pLetters) {
mLetters = pLetters;
}
/**
* Creates the LettersDisplayGeometry object for the given fragment
*
* @param pParent
* Fragment (usually this will be a Gene the length of the entire
* reference)
*/
public LettersDisplayGeometry(SequenceFragment pParent) {
mParent = pParent;
}
@Override
public void draw(Graphics2D pG2d, DisplayData pData) {
if (pData.drawDiffLetters) {
// draw letters over ticks
pG2d
.setColor(DisplaySettings
.getDisplaySettings()
.getLetterColor());
pG2d.setFont(pData.getLetterFont());
for (DiffLetterInfo letter : getLetters()) {
pG2d.drawString(
String.valueOf(letter.getLetter()),
(float) letter.getX(),
(float) letter.getY());
}
}
}
@Override
public boolean update(DisplayData pData) {
if (pData.drawDiffLetters) {
HashSet<DiffLetterInfo> letters = getLetters();
letters.clear();
double width = pData.tickWidth;
double x;
int y = pData.refSeqAreaHeight + pData.rowHeight;
for (int pos = pData.getStart(); pos <= pData.getEnd(); pos++) {
x = getX(pos, pData);
double letterX = width > pData.diffLetterCutoff ? x
+ (width - pData.diffLetterCutoff) / 2 : x;
char letter = mParent.getSequence().getBase(pos);
letters.add(new DiffLetterInfo(
Character.toUpperCase(letter),
letterX,
y));
}
setLetters(letters);
return true;
} else {
return false;
}
}
}
| lgpl-3.0 |
HATB0T/RuneCraftery | forge/mcp/temp/src/minecraft/net/minecraft/block/BlockHalfSlab.java | 4843 | package net.minecraft.block;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.List;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.Facing;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public abstract class BlockHalfSlab extends Block {
protected final boolean field_72242_a;
public BlockHalfSlab(int p_i2208_1_, boolean p_i2208_2_, Material p_i2208_3_) {
super(p_i2208_1_, p_i2208_3_);
this.field_72242_a = p_i2208_2_;
if(p_i2208_2_) {
field_71970_n[p_i2208_1_] = true;
} else {
this.func_71905_a(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F);
}
this.func_71868_h(255);
}
public void func_71902_a(IBlockAccess p_71902_1_, int p_71902_2_, int p_71902_3_, int p_71902_4_) {
if(this.field_72242_a) {
this.func_71905_a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
} else {
boolean var5 = (p_71902_1_.func_72805_g(p_71902_2_, p_71902_3_, p_71902_4_) & 8) != 0;
if(var5) {
this.func_71905_a(0.0F, 0.5F, 0.0F, 1.0F, 1.0F, 1.0F);
} else {
this.func_71905_a(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F);
}
}
}
public void func_71919_f() {
if(this.field_72242_a) {
this.func_71905_a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
} else {
this.func_71905_a(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F);
}
}
public void func_71871_a(World p_71871_1_, int p_71871_2_, int p_71871_3_, int p_71871_4_, AxisAlignedBB p_71871_5_, List p_71871_6_, Entity p_71871_7_) {
this.func_71902_a(p_71871_1_, p_71871_2_, p_71871_3_, p_71871_4_);
super.func_71871_a(p_71871_1_, p_71871_2_, p_71871_3_, p_71871_4_, p_71871_5_, p_71871_6_, p_71871_7_);
}
public boolean func_71926_d() {
return this.field_72242_a;
}
public int func_85104_a(World p_85104_1_, int p_85104_2_, int p_85104_3_, int p_85104_4_, int p_85104_5_, float p_85104_6_, float p_85104_7_, float p_85104_8_, int p_85104_9_) {
return this.field_72242_a?p_85104_9_:(p_85104_5_ != 0 && (p_85104_5_ == 1 || (double)p_85104_7_ <= 0.5D)?p_85104_9_:p_85104_9_ | 8);
}
public int func_71925_a(Random p_71925_1_) {
return this.field_72242_a?2:1;
}
public int func_71899_b(int p_71899_1_) {
return p_71899_1_ & 7;
}
public boolean func_71886_c() {
return this.field_72242_a;
}
@SideOnly(Side.CLIENT)
public boolean func_71877_c(IBlockAccess p_71877_1_, int p_71877_2_, int p_71877_3_, int p_71877_4_, int p_71877_5_) {
if(this.field_72242_a) {
return super.func_71877_c(p_71877_1_, p_71877_2_, p_71877_3_, p_71877_4_, p_71877_5_);
} else if(p_71877_5_ != 1 && p_71877_5_ != 0 && !super.func_71877_c(p_71877_1_, p_71877_2_, p_71877_3_, p_71877_4_, p_71877_5_)) {
return false;
} else {
int var6 = p_71877_2_ + Facing.field_71586_b[Facing.field_71588_a[p_71877_5_]];
int var7 = p_71877_3_ + Facing.field_71587_c[Facing.field_71588_a[p_71877_5_]];
int var8 = p_71877_4_ + Facing.field_71585_d[Facing.field_71588_a[p_71877_5_]];
boolean var9 = (p_71877_1_.func_72805_g(var6, var7, var8) & 8) != 0;
return var9?(p_71877_5_ == 0?true:(p_71877_5_ == 1 && super.func_71877_c(p_71877_1_, p_71877_2_, p_71877_3_, p_71877_4_, p_71877_5_)?true:!func_72241_e(p_71877_1_.func_72798_a(p_71877_2_, p_71877_3_, p_71877_4_)) || (p_71877_1_.func_72805_g(p_71877_2_, p_71877_3_, p_71877_4_) & 8) == 0)):(p_71877_5_ == 1?true:(p_71877_5_ == 0 && super.func_71877_c(p_71877_1_, p_71877_2_, p_71877_3_, p_71877_4_, p_71877_5_)?true:!func_72241_e(p_71877_1_.func_72798_a(p_71877_2_, p_71877_3_, p_71877_4_)) || (p_71877_1_.func_72805_g(p_71877_2_, p_71877_3_, p_71877_4_) & 8) != 0));
}
}
@SideOnly(Side.CLIENT)
private static boolean func_72241_e(int p_72241_0_) {
return p_72241_0_ == Block.field_72079_ak.field_71990_ca || p_72241_0_ == Block.field_72092_bO.field_71990_ca;
}
public abstract String func_72240_d(int var1);
public int func_71873_h(World p_71873_1_, int p_71873_2_, int p_71873_3_, int p_71873_4_) {
return super.func_71873_h(p_71873_1_, p_71873_2_, p_71873_3_, p_71873_4_) & 7;
}
@SideOnly(Side.CLIENT)
public int func_71922_a(World p_71922_1_, int p_71922_2_, int p_71922_3_, int p_71922_4_) {
return func_72241_e(this.field_71990_ca)?this.field_71990_ca:(this.field_71990_ca == Block.field_72085_aj.field_71990_ca?Block.field_72079_ak.field_71990_ca:(this.field_71990_ca == Block.field_72090_bN.field_71990_ca?Block.field_72092_bO.field_71990_ca:Block.field_72079_ak.field_71990_ca));
}
}
| lgpl-3.0 |
Zenoton/Tunnel | Tunnel/src/com/zenoton/TunnelLWJGL/java/Inventory/Tools/Tools.java | 1386 | package com.zenoton.TunnelLWJGL.java.Inventory.Tools;
import com.zenoton.TunnelLWJGL.java.helpers.InputMouse;
import com.zenoton.TunnelLWJGL.java.helpers.Resources;
import com.zenoton.TunnelLWJGL.java.helpers.Texture;
import org.lwjgl.opengl.GL11;
import static org.lwjgl.opengl.GL11.*;
/**
* Created by CAMPBELL MILLAR on 15/09/2015. READ ATTACHED LICENCE (GNU LESSER PUBLIC LICENCE).
*/
public abstract class Tools {
public int inventorySlot;
public String tool;
public Texture toolImage = null;
public static int selectedSlot=0;
public Tools(int inventorySlot){
this.inventorySlot = inventorySlot;
init();
}
public abstract void init();
public void render(){
glPushMatrix();
GL11.glScalef(1,1,0);
glTranslatef(0,0,0);
Resources.getImage("slot").draw(32*inventorySlot+600,10);
glPopMatrix();
if (inventorySlot == selectedSlot){
Resources.getImage("slector").draw(32*inventorySlot+600,10);
}
if (toolImage != null){
toolImage.draw((32*inventorySlot+600)+8,18);
}
glPopMatrix();
}
public void clicked(int x,int y){
if(x>32*inventorySlot+600 && x<32*inventorySlot+600+32 && y>10 && y<10+32 && InputMouse.leftButton()){
selectedSlot = inventorySlot;
}
}
public abstract void update();
}
| lgpl-3.0 |
dean2015/gs-simple | gsimple/gsimple-common/src/main/java/org/gsimple/common/tuple/Quintet.java | 1533 | /*
* Copyright © gaosong
*
* This program and the accompanying materials are licensed under
* the terms of the GNU Lesser General Public License version 3.0
* as published by the Free Software Foundation.
*/
package org.gsimple.common.tuple;
/**
* Quintet tuple
*
* @param <A>
* First value of Quintet
* @param <B>
* Second value of Quintet
* @param <C>
* Third value of Quintet
* @param <D>
* Forth value of Quintet
* @param <E>
* Fifth value of Quintet
*
* @author gaosong
*
*/
public class Quintet<A, B, C, D, E> extends Quartet<A, B, C, D> {
private static final long serialVersionUID = 7659362806794841460L;
protected E value4;
public Quintet(A val0, B val1, C val2, D val3, E val4) {
super(val0, val1, val2, val3);
value4 = val4;
}
public E getValue4() {
return value4;
}
public void setValue4(E value4) {
this.value4 = value4;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((value4 == null) ? 0 : value4.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Quintet<?, ?, ?, ?, ?> other = (Quintet<?, ?, ?, ?, ?>) obj;
if (value4 == null) {
if (other.value4 != null)
return false;
} else if (!value4.equals(other.value4))
return false;
return super.equals(obj);
}
}
| lgpl-3.0 |
BlueVia/Official-Library-Java | src/main/java/com/bluevia/commons/connector/http/oauth/RequestToken.java | 1401 | package com.bluevia.commons.connector.http.oauth;
/**
* This object extends the OAuthToken class to include the URL to verify the Request OAuthToken.
*
*/
public class RequestToken extends OAuthToken {
private String mVerificationUrl;
/**
* Instantiates the OAuthToken with its parameters
*
* @param oauthToken the oauth_token identifier
* @param oauthTokenSecret the oauth shared-secret
* @param url verification url
*/
public RequestToken(String oauthToken, String oauthTokenSecret, String url) {
super(oauthToken, oauthTokenSecret);
mVerificationUrl = url;
}
/**
* Instantiates the OAuthToken with it parameter
*
* @param token
* @param url verification url
*/
public RequestToken(OAuthToken token, String url){
this(token.getToken(), token.getSecret(), url);
}
/**
* Gets the verification url
*
* @return The verification url
*/
public String getVerificationUrl(){
return mVerificationUrl;
}
/**
* Sets the verification url
*
* @param url the verification url
*/
public void setVerificationUrl(String url){
mVerificationUrl = url;
}
/**
* Checks that the token is valid.
* @return true if the OAuthToken seems to be valid, false otherwise
*/
@Override
public boolean isValid(){
return super.isValid(); //VerificationUrl can be null
}
}
| lgpl-3.0 |
Godin/sonar | server/sonar-server/src/main/java/org/sonar/server/platform/monitoring/WebSystemInfoModule.java | 3228 | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.monitoring;
import org.sonar.api.config.Configuration;
import org.sonar.core.platform.Module;
import org.sonar.process.systeminfo.JvmPropertiesSection;
import org.sonar.process.systeminfo.JvmStateSection;
import org.sonar.server.platform.WebServer;
import org.sonar.server.platform.monitoring.cluster.AppNodesInfoLoaderImpl;
import org.sonar.server.platform.monitoring.cluster.CeQueueGlobalSection;
import org.sonar.server.platform.monitoring.cluster.EsClusterStateSection;
import org.sonar.server.platform.monitoring.cluster.GlobalInfoLoader;
import org.sonar.server.platform.monitoring.cluster.GlobalSystemSection;
import org.sonar.server.platform.monitoring.cluster.NodeSystemSection;
import org.sonar.server.platform.monitoring.cluster.ProcessInfoProvider;
import org.sonar.server.platform.monitoring.cluster.SearchNodesInfoLoaderImpl;
import org.sonar.server.platform.ws.ClusterSystemInfoWriter;
import org.sonar.server.platform.ws.InfoAction;
import org.sonar.server.platform.ws.StandaloneSystemInfoWriter;
public class WebSystemInfoModule extends Module {
private final Configuration configuration;
private final WebServer webServer;
public WebSystemInfoModule(Configuration configuration, WebServer webServer) {
this.configuration = configuration;
this.webServer = webServer;
}
@Override
protected void configureModule() {
boolean sonarcloud = configuration.getBoolean("sonar.sonarcloud.enabled").orElse(false);
boolean standalone = webServer.isStandalone();
add(
new JvmPropertiesSection("Web JVM Properties"),
new JvmStateSection("Web JVM State"),
DbSection.class,
DbConnectionSection.class,
EsIndexesSection.class,
LoggingSection.class,
PluginsSection.class,
SettingsSection.class,
InfoAction.class
);
if (standalone || sonarcloud) {
add(
EsStateSection.class,
StandaloneSystemSection.class,
StandaloneSystemInfoWriter.class
);
} else {
add(
CeQueueGlobalSection.class,
EsClusterStateSection.class,
GlobalSystemSection.class,
NodeSystemSection.class,
ProcessInfoProvider.class,
GlobalInfoLoader.class,
AppNodesInfoLoaderImpl.class,
SearchNodesInfoLoaderImpl.class,
ClusterSystemInfoWriter.class
);
}
}
}
| lgpl-3.0 |
Tillerino/log4j-http-appender | src/main/java/fr/bettinger/log4j/HttpLayout.java | 4148 | /*
* This file is part of Log4jHttpAppender.
*
* Log4jHttpAppender is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Log4jHttpAppender 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
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the Lesser GNU General Public License
* along with Log4jHttpAppender. If not, see <http://www.gnu.org/licenses/>.
*
* The original code was written by Sebastien Bettinger <sebastien.bettinger@gmail.com>
*
*/
package fr.bettinger.log4j;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.EnhancedPatternLayout;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;
/**
* HttpLayout
* @author S. Bettinger
*
*/
public class HttpLayout extends Layout {
private final class URLEncodingPatternLayout extends EnhancedPatternLayout {
private URLEncodingPatternLayout(String pattern) {
super(pattern);
}
@Override
public String format(LoggingEvent event) {
String value = super.format(event);
if (urlEncode) {
try {
value = URLEncoder.encode(value, encoding);
} catch (UnsupportedEncodingException e) {
LogLog.warn(e.toString());
}
}
return value;
}
}
public static class URLParameterNameLayout extends Layout {
private final String type;
private final String value;
public URLParameterNameLayout(String type, String value) {
super();
this.type = type;
this.value = value;
}
public String getValue() {
return value;
}
@Override
public void activateOptions() {
}
@Override
public boolean ignoresThrowable() {
return true;
}
@Override
public String format(LoggingEvent event) {
return type + value + "=";
}
}
public static final Pattern URL_PARAMETER_PATTERN = Pattern.compile("(\\?|&)(\\w+)=");
List<Layout> subLayouts = new ArrayList<Layout>();
public HttpLayout() {
}
public HttpLayout(String pattern) throws MalformedURLException {
setConversionPattern(pattern);
}
public void setConversionPattern(String conversionPattern) throws MalformedURLException {
Matcher m = URL_PARAMETER_PATTERN.matcher(conversionPattern);
if(!m.find() || m.start() != 0 || !m.group(1).equals("?")) {
throw new MalformedURLException("You need to provide a proper query string starting with ?");
}
for(;;) {
subLayouts.add(new URLParameterNameLayout(m.group(1), m.group(2)));
int end = m.end();
if(!m.find()) {
subLayouts.add(new URLEncodingPatternLayout(conversionPattern.substring(end)));
return;
}
subLayouts.add(new URLEncodingPatternLayout(conversionPattern.substring(end, m.start())));
}
}
public String encoding = "UTF-8";
public void setEncoding(String encoding) throws UnsupportedEncodingException {
if(encoding == null || !Charset.isSupported(encoding)) {
throw new UnsupportedEncodingException(encoding);
}
this.encoding = encoding.trim();
}
public boolean urlEncode = true;
public void setUrlEncode(boolean urlEncode) {
this.urlEncode = urlEncode;
}
@Override
public void activateOptions() { }
@Override
public String format(LoggingEvent paramLoggingEvent) {
StringBuilder builder = new StringBuilder();
for (Layout layout : subLayouts) {
builder.append(layout.format(paramLoggingEvent));
}
return builder.toString();
}
@Override
public boolean ignoresThrowable() {
for (Layout layout : subLayouts) {
if(!layout.ignoresThrowable()) {
return false;
}
}
return true;
}
}
| lgpl-3.0 |
racodond/sonar-gherkin-plugin | its/plugin/tests/src/test/java/org/sonar/gherkin/its/IssuesTest.java | 2393 | /*
* SonarQube Cucumber Gherkin Analyzer
* Copyright (C) 2016-2017 David RACODON
* david.racodon@gmail.com
*
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.gherkin.its;
import com.sonar.orchestrator.Orchestrator;
import com.sonar.orchestrator.build.SonarScanner;
import org.junit.Test;
import org.sonar.wsclient.issue.Issue;
import org.sonar.wsclient.issue.IssueQuery;
import java.io.File;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
public class IssuesTest {
@org.junit.ClassRule
public static Orchestrator orchestrator = Tests.ORCHESTRATOR;
private static final String PROJECT_KEY = "issues";
@org.junit.BeforeClass
public static void init() {
orchestrator.resetData();
SonarScanner build = Tests.createSonarScannerBuild()
.setProjectDir(new File("../projects/issues/"))
.setProjectKey(PROJECT_KEY)
.setProjectName(PROJECT_KEY);
orchestrator.getServer().provisionProject(PROJECT_KEY, PROJECT_KEY);
Tests.setProfile("allowed-tags-only-profile", PROJECT_KEY);
orchestrator.executeBuild(build);
}
@Test
public void issue_for_rule_allowed_tags() {
List<Issue> issues = orchestrator.getServer().wsClient().issueClient().find(IssueQuery.create()).list();
assertThat(issues).hasSize(2);
assertThat(issues.get(0).ruleKey()).isEqualTo("gherkin:allowed-tags");
assertThat(issues.get(0).severity()).isEqualTo("MAJOR");
assertThat(issues.get(0).line()).isEqualTo(1);
assertThat(issues.get(1).ruleKey()).isEqualTo("gherkin:allowed-tags");
assertThat(issues.get(1).severity()).isEqualTo("MAJOR");
assertThat(issues.get(1).line()).isEqualTo(1);
}
}
| lgpl-3.0 |
medsec/simonspeck | tool/tests/de/mslab/branches/Simon64BranchesTest.java | 1179 | package de.mslab.branches;
import org.junit.Test;
import de.mslab.ciphers.Simon64;
public class Simon64BranchesTest extends SimonBranchesTest {
private static final long[] KEY = { 0x1b1a1918L, 0x13121110L, 0x0b0a0908L, 0x03020100L };
private static final long[][] EXPECTED_DIFFERENCES = {
{ 0x4000_0000, 0x1101_0001 },
{ 0x1101_0000, 0x2000_0000 },
{ 0x0404_0000, 0x1101_0000 },
{ 0x0111_0000, 0x0404_0000 },
{ 0x0040_0000, 0x0111_0000 },
{ 0x0011_0000, 0x0040_0000 },
{ 0x0004_0000, 0x0011_0000 },
{ 0x0001_0000, 0x0004_0000 },
{ 0, 0x0001_0000 },
{ 0x0001_0000, 0 },
{ 0x0004_0000, 0x0001_0000 },
{ 0x0011_0000, 0x0004_0000 },
{ 0x0040_0000, 0x0011_0000 },
{ 0x0111_0000, 0x0040_0000 },
{ 0x0404_0000, 0x0111_0000 },
{ 0x1101_0000, 0x0404_0000 },
{ 0x4000_0000, 0x1101_0000 },
{ 0x1101_0001, 0x4000_0000 }
};
public Simon64BranchesTest() {
super(new Simon64(), KEY, EXPECTED_DIFFERENCES);
}
@Test
public void findBranches() {
final long numPairs = 1L << 23;
// investigateRounds(numPairs, 1, 5);
investigateRounds(numPairs, 4, 10);
investigateRounds(numPairs, 8, 13);
investigateRounds(numPairs, 12, 17);
}
}
| lgpl-3.0 |
plorenz/sarasvati | sarasvati-core/src/test/java/com/googlecode/sarasvati/env/Base64Test.java | 859 | package com.googlecode.sarasvati.env;
import java.security.SecureRandom;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
public class Base64Test
{
@Test
public void test()
{
SecureRandom rand = new SecureRandom();
for (int i = 1; i < 1024; i++)
{
byte[] array = new byte[i];
rand.nextBytes(array);
final String encoded = Base64.encode(array);
byte[] decoded = Base64.decode(encoded);
Assert.assertTrue(Arrays.equals(array, decoded));
}
for (int i = 1024; i < 100 * 1024; i += rand.nextInt(1024))
{
byte[] array = new byte[i];
rand.nextBytes(array);
final String encoded = Base64.encode(array);
byte[] decoded = Base64.decode(encoded);
Assert.assertTrue(Arrays.equals(array, decoded));
}
}
}
| lgpl-3.0 |
MarkyVasconcelos/Towel | src/com/towel/cfg/ProgressiveString.java | 3407 | package com.towel.cfg;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ProgressiveString {
private List<CharInterval> charsIntervals;
private int charIntervalIndex;
private int minChar;
private int maxChar;
private char[] string;
public ProgressiveString(CharInterval... charIntervals) {
this("", charIntervals);
}
public ProgressiveString(String original, CharInterval... charIntervals) {
if (charIntervals.length == 0)
throw new RuntimeException("CharIntervals can't be null!");
string = original.toCharArray();
charsIntervals = Arrays.asList(charIntervals);
Collections.sort(charsIntervals);
charIntervalIndex = 0;
minChar = (int) charsIntervals.get(0).first;
maxChar = (int) charsIntervals.get(charsIntervals.size() - 1).last;
}
private char[] copyChars(int start, char[] old) {
char[] str = new char[start + old.length];
for (int i = 0; i < old.length; i++)
str[start + i] = old[i];
return str;
}
public void increase() {
char[] str = string.clone();
for (int i = str.length - 1; i >= 0; i--) {
IncreaseResult result = tryIncrease(str[i]);
str[i] = result.newChar;
if (result.result == IncreaseResult.INCREASED)
break;
if (result.result == IncreaseResult.DECREASED) {
if (i - 1 == -1) {
str = copyChars(1, str);
str[0] = (char) minChar;
break;
}
}
}
string = str.clone();
}
private IncreaseResult tryIncrease(char c) {
if (((int) c) == maxChar) {
charIntervalIndex = 0;
return new IncreaseResult((char) minChar, IncreaseResult.DECREASED);
} else
return new IncreaseResult(nextChar(c), IncreaseResult.INCREASED);
}
private char nextChar(char c) {
int i = (int) c;
if (i == charsIntervals.get(charIntervalIndex).last) {
charIntervalIndex++;
return (char) charsIntervals.get(charIntervalIndex).first;
}
return (char) (((int) c) + 1);
}
@Override
public String toString() {
return new String(string);
}
public static void main(String[] args) {
ProgressiveString str = new ProgressiveString(
String.valueOf((char) 33), new CharInterval('a', 'm'), new CharInterval('n', 'z'));
// JFrame frame = new JFrame("MutableString");
// JLabel label = new JLabel(" ");
// frame.add(label);
// frame.pack();
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setLocationRelativeTo(null);
// frame.setVisible(true);
int loops = 2500000;
for (int i = 0; i < loops; i++, str.increase(), System.out.println(str))
;
}
public static class CharInterval implements Comparable<CharInterval> {
protected int first;
protected int last;
public CharInterval(int first, int last) {
this.first = first;
this.last = last;
}
public boolean canIncrease(char character) {
int i = (int) character;
return i >= first && i <= last;
}
@Override
public int compareTo(CharInterval arg0) {
if (first < arg0.first)
return -1;
if (first > arg0.first)
return 1;
return 0;
}
}
private class IncreaseResult {
protected char newChar;
protected int result;
public IncreaseResult(char newC, int result) {
newChar = newC;
this.result = result;
}
protected static final int INCREASED = 0;
protected static final int DECREASED = 1;
}
}
| lgpl-3.0 |
lburgazzoli/Chronicle-Map | src/main/java/net/openhft/chronicle/hash/serialization/impl/AbstractCharSequenceUtf8DataAccess.java | 2427 | /*
* Copyright (C) 2015 higherfrequencytrading.com
*
* 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.
*
* 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 net.openhft.chronicle.hash.serialization.impl;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.BytesUtil;
import net.openhft.chronicle.bytes.RandomDataInput;
import net.openhft.chronicle.hash.AbstractData;
import net.openhft.chronicle.hash.Data;
import net.openhft.chronicle.hash.serialization.DataAccess;
import net.openhft.chronicle.wire.WireIn;
import net.openhft.chronicle.wire.WireOut;
import org.jetbrains.annotations.NotNull;
abstract class AbstractCharSequenceUtf8DataAccess<T extends CharSequence> extends AbstractData<T>
implements DataAccess<T>, Data<T> {
/** Cache field */
private transient Bytes bytes;
/** State field */
transient T cs;
AbstractCharSequenceUtf8DataAccess() {
initTransients();
}
private void initTransients() {
bytes = Bytes.allocateElasticDirect(1);
}
@Override
public Data<T> getData(@NotNull T cs) {
this.cs = cs;
bytes.clear();
BytesUtil.appendUtf8(bytes, cs);
return this;
}
@Override
public void uninit() {
cs = null;
}
@Override
public void readMarshallable(@NotNull WireIn wireIn) {
// no config fields to read
initTransients();
}
@Override
public void writeMarshallable(@NotNull WireOut wireOut) {
// no config fields to write
}
@Override
public RandomDataInput bytes() {
return bytes.bytesStore();
}
@Override
public long offset() {
return 0;
}
@Override
public long size() {
return bytes.readRemaining();
}
@Override
public T get() {
return cs;
}
}
| lgpl-3.0 |
lunarray-org/model-descriptor | src/main/java/org/lunarray/model/descriptor/builder/annotation/base/listener/operation/result/SetRelationListener.java | 3067 | /*
* Model Tools.
* Copyright (C) 2013 Pal Hargitai (pal@lunarray.org)
*
* 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.lunarray.model.descriptor.builder.annotation.base.listener.operation.result;
import org.apache.commons.lang.Validate;
import org.lunarray.common.event.EventException;
import org.lunarray.model.descriptor.accessor.entity.DescribedEntity;
import org.lunarray.model.descriptor.accessor.operation.DescribedOperation;
import org.lunarray.model.descriptor.builder.annotation.base.build.context.AnnotationBuilderContext;
import org.lunarray.model.descriptor.builder.annotation.base.build.operation.AnnotationOperationDescriptorBuilder;
import org.lunarray.model.descriptor.builder.annotation.base.build.operation.AnnotationResultDescriptorBuilder;
import org.lunarray.model.descriptor.builder.annotation.base.listener.events.UpdatedOperationReferenceEvent;
import org.lunarray.model.descriptor.builder.annotation.base.listener.operation.AbstractOperationListener;
import org.lunarray.model.descriptor.builder.annotation.util.ResultTypeBuilderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Updates the relation.
*
* @author Pal Hargitai (pal@lunarray.org)
* @param <R>
* The result type.
* @param <E>
* The entity type.
* @param <B>
* The builder type.
*/
public final class SetRelationListener<R, E, B extends AnnotationBuilderContext>
extends AbstractOperationListener<E, B> {
/** The logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(SetRelationListener.class);
/** Default constructor. */
public SetRelationListener() {
super();
}
/** {@inheritDoc} */
@Override
public void handleEvent(final UpdatedOperationReferenceEvent<E, B> event) throws EventException {
SetRelationListener.LOGGER.debug("Handling event {}", event);
Validate.notNull(event, "Event may not be null.");
final AnnotationOperationDescriptorBuilder<E, B> operationBuilder = event.getBuilder();
final AnnotationResultDescriptorBuilder<R, E, B> builder = operationBuilder.getResultBuilder();
final DescribedOperation operation = operationBuilder.getOperation();
@SuppressWarnings("unchecked")
final DescribedEntity<R> entity = (DescribedEntity<R>) builder.getBuilderContext().getEntityResolverStrategy()
.resolveEntity(operation.getResultType());
ResultTypeBuilderUtil.updateRelation(builder, entity, operation);
}
}
| lgpl-3.0 |
andreoid/testing | brjs-core/src/main/java/org/bladerunnerjs/utility/UserCommandRunner.java | 3624 | package org.bladerunnerjs.utility;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.bladerunnerjs.logging.Logger;
import org.bladerunnerjs.memoization.MemoizedFile;
import org.bladerunnerjs.model.App;
import org.bladerunnerjs.model.BRJS;
import org.bladerunnerjs.model.LogLevelAccessor;
import org.bladerunnerjs.model.exception.command.CommandArgumentsException;
import org.bladerunnerjs.model.exception.command.CommandOperationException;
import org.bladerunnerjs.model.exception.command.NoSuchCommandException;
import org.bladerunnerjs.plugin.plugins.commands.core.HelpCommand;
import org.bladerunnerjs.plugin.utility.command.CommandList;
public class UserCommandRunner {
public class Messages {
public static final String OUTDATED_JAR_MESSAGE = "The app '%s' is either missing BRJS jar(s), contains BRJS jar(s) it shouldn't or the BRJS jar(s) are outdated."+
" You should delete all jars prefixed with '%s' in the WEB-INF/lib directory and copy in all jars contained in %s.";
}
public static int run(BRJS brjs, CommandList commandList, LogLevelAccessor logLevelAccessor, String args[]) throws CommandOperationException {
return doRunCommand(brjs, args);
}
private static int doRunCommand(BRJS brjs, String[] args) throws CommandOperationException
{
Logger logger = brjs.logger(UserCommandRunner.class);
try {
checkApplicationLibVersions(brjs, logger);
return brjs.runCommand(args);
}
catch (NoSuchCommandException e) {
if (e.getCommandName().length() > 0)
{
logger.println(e.getMessage());
logger.println("--------");
logger.println("");
}
return doRunCommand(brjs, new String[] {new HelpCommand().getCommandName() });
}
catch (CommandArgumentsException e) {
logger.println("Problem:");
logger.println(" " + e.getMessage());
logger.println("");
logger.println("Usage:");
logger.println(" brjs " + e.getCommand().getCommandName() + " " + e.getCommand().getCommandUsage());
}
catch (CommandOperationException e) {
logger.println("Error:");
logger.println(" " + e.getMessage());
if (e.getCause() != null) {
logger.println("");
logger.println("Caused By:");
logger.println(" " + e.getCause().getMessage());
}
logger.println("");
logger.println("Stack Trace:");
StringWriter stackTrace = new StringWriter();
e.printStackTrace(new PrintWriter(stackTrace));
logger.println(stackTrace.toString());
throw e;
}
return -1;
}
private static void checkApplicationLibVersions(BRJS brjs, Logger logger)
{
for (App app : brjs.userApps()) {
checkApplicationLibVersions(app, logger);
}
}
private static void checkApplicationLibVersions(App app, Logger logger)
{
File webinfLib = app.file("WEB-INF/lib");
MemoizedFile appJarsDir = app.root().appJars().dir();
if (!webinfLib.exists() || !appJarsDir.exists()) {
return;
}
boolean containsInvalidJars = false;
for (File appJar : FileUtils.listFiles(webinfLib, new PrefixFileFilter("brjs-"), null)) {
File sdkJar = app.root().appJars().file(appJar.getName());
if (!sdkJar.exists()) {
containsInvalidJars = true;
}
}
for (File sdkJar : FileUtils.listFiles(appJarsDir, new PrefixFileFilter("brjs-"), null)) {
File appJar = new File(webinfLib, sdkJar.getName());
if (!appJar.exists()) {
containsInvalidJars = true;
}
}
if (containsInvalidJars) {
logger.warn( Messages.OUTDATED_JAR_MESSAGE, app.getName(), "brjs-", app.root().dir().getRelativePath(appJarsDir) );
}
}
} | lgpl-3.0 |
kwakeroni/workshops | java9/solution/src/test/java/be/kwakeroni/workshop/java9/solution/language/Var.java | 3850 | package be.kwakeroni.workshop.java9.solution.language;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
// Examples
// V1 - Replace type declarations with var
// V2 - Inference of generic parameters (to Object)
// V3 - Inference of intersection types
// V4 - var in loops
// V5 - var as variable name
// V6 - var not as class name
// V7 - var not without type inference
// Style guidelines http://openjdk.java.net/projects/amber/LVTIstyle.html
// Principles
// 1. Reading code is more important than writing code.
// 2. Code should be clear from local reasoning.
// 3. Code readability shouldn't depend on IDEs.
// 4. Explicit types are a tradeoff.
// @since 10
public class Var {
public String var;
public void test() {
var var = "var";
List<String> diamond = new ArrayList<>();
var stringList = new ArrayList<String>();
ArrayList<String> sl = stringList;
var varList = new ArrayList<>();
ArrayList<Object> ao = varList;
// Serializable & Comparable<?> x = getSomeX();
doSomeY(this::getSomeX);
doSomeX(getSomeX());
var runnableComparable = getSomeX();
doSomeY(() -> runnableComparable);
for (var i=0; i<10; i++){
// in old loops
}
for (var element : varList){
// or new loops
}
var myRunnable = new Runnable() {
@Override
public void run() {
throw new UnsupportedOperationException();
}
public void setTimeout(long millis) {
}
};
myRunnable.run();
myRunnable.setTimeout(1000);
List<? extends Number> numList = null;
var num = numList.get(0);
Number number = num;
var c = this.getClass();
var t = getT();
// 1. Choose variable names that provide useful information.
// In a var declaration, information about the meaning and use of the variable can be conveyed using the variable's name.
// Instead of the exact type, it's sometimes better for a variable's name to express the role or the nature of the variable
// 2. Minimize the scope of local variables.
// 3. Consider var when the initializer provides sufficient information to the reader.
// 4. Use var to break up chained or nested expressions with local variables.
// Using var allows us to express the the code more naturally without paying the high price of explicitly declaring the types of the intermediate variables
// As with many other situations, the correct use of var might involve both taking something out (explicit types) and adding something back (better variable names, better structuring of code.)
// 6. Take care when using var with diamond or generic methods.
// 7. Take care when using var with literals.
}
private <T> T getT() {
return null;
}
private <X extends Runnable & Comparable<?>> X getSomeX() {
return null;
}
private <X extends Runnable & Comparable<?>> void doSomeX(X x) {
}
private <Y extends Runnable & Comparable<?>> void doSomeY(Supplier<Y> runnableComparable){
var y = runnableComparable.get();
}
// Cannot be used as a class name
// public static final class var {
//
// private var noFields;
//
// private var noMethods(var norArguments){
// try {
// var norWithoutInitializer;
// var nil = null;
// var notWhenTargetTypeIsNeeded = () -> 42;
// String[] s1 = {"A", "B"};
// var notForArrayInitializers = {"A", "B"};
// } catch (var orWithCaughtExceptions){
//
// }
// }
// }
}
| lgpl-3.0 |
FenixEdu/fenixedu-academic | src/main/java/org/fenixedu/academic/domain/EmptyDegree.java | 10705 | /**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic 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.
*
* FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.domain;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.fenixedu.academic.domain.degree.DegreeType;
import org.fenixedu.academic.domain.degree.degreeCurricularPlan.DegreeCurricularPlanState;
import org.fenixedu.academic.domain.exceptions.DomainException;
import org.fenixedu.academic.domain.time.calendarStructure.AcademicPeriod;
import org.fenixedu.academic.util.Bundle;
import org.fenixedu.commons.i18n.LocalizedString;
import org.fenixedu.bennu.core.domain.Bennu;
import org.fenixedu.bennu.core.i18n.BundleUtil;
public class EmptyDegree extends EmptyDegree_Base {
private static volatile EmptyDegree instance = null;
private EmptyDegree() {
super();
setRootDomainObject(Bennu.getInstance());
super.setDegreeType(DegreeType.matching(DegreeType::isEmpty).orElseGet(
() -> {
DegreeType type =
new DegreeType(BundleUtil.getLocalizedString("resources.EnumerationResources", "DegreeType.EMPTY"));
type.setEmpty(true);
return type;
}));
super.setGradeScale(GradeScale.TYPE20);
}
@Override
public boolean isEmpty() {
return true;
}
public static EmptyDegree getInstance() {
if (instance == null) {
synchronized (EmptyDegree.class) {
if (instance == null) {
for (final Degree degree : Bennu.getInstance().getDegreesSet()) {
if (degree.isEmpty()) {
instance = (EmptyDegree) degree;
}
}
}
}
}
return instance;
}
public static void init() {
synchronized (EmptyDegree.class) {
final EmptyDegree existing = getInstance();
if (existing == null) {
final EmptyDegree newinstance = new EmptyDegree();
newinstance.setNomeOnSuper("Curso de Unidades Isoladas");
instance = newinstance;
}
}
}
private void setNomeOnSuper(final String nome) {
super.setNome(nome);
}
@Override
public void edit(LocalizedString name, String acronym, LocalizedString associatedInstitutions, DegreeType degreeType, Double ectsCredits,
GradeScale gradeScale, String prevailingScientificArea, ExecutionYear executionYear) {
throw new DomainException("EmptyDegree.not.available");
}
@Override
public void edit(LocalizedString name, String code, LocalizedString associatedInstitutions, DegreeType degreeType,
GradeScale gradeScale,
ExecutionYear executionYear) {
throw new DomainException("EmptyDegree.not.available");
}
@Override
protected void checkForDeletionBlockers(Collection<String> blockers) {
super.checkForDeletionBlockers(blockers);
blockers.add(BundleUtil.getString(Bundle.APPLICATION, "EmptyDegree.not.available"));
}
@Override
public DegreeCurricularPlan createDegreeCurricularPlan(String name, GradeScale gradeScale, Person creator,
AcademicPeriod duration) {
throw new DomainException("EmptyDegree.not.available");
}
@Override
public void setNome(final String nome) {
throw new DomainException("EmptyDegree.not.available");
}
@Override
public void setNameEn(String nameEn) {
throw new DomainException("EmptyDegree.not.available");
}
@Override
public void setSigla(final String sigla) {
throw new DomainException("EmptyDegree.not.available");
}
@Override
public String getSigla() {
return StringUtils.EMPTY;
}
@Override
public Double getEctsCredits() {
return null;
}
@Override
public void setEctsCredits(Double ectsCredits) {
throw new DomainException("EmptyDegree.not.available");
}
@Override
public boolean hasEctsCredits() {
return false;
}
@Override
public void setGradeScale(GradeScale gradeScale) {
throw new DomainException("EmptyDegree.not.available");
}
@Override
public void setPrevailingScientificArea(String prevailingScientificArea) {
throw new DomainException("EmptyDegree.not.available");
}
@Override
public void setDegreeType(final DegreeType degreeType) {
throw new DomainException("EmptyDegree.not.available");
}
@Override
public boolean isBolonhaDegree() {
return true;
}
@Override
public boolean isDegreeOrBolonhaDegreeOrBolonhaIntegratedMasterDegree() {
return false;
}
@Override
public List<DegreeCurricularPlan> findDegreeCurricularPlansByState(DegreeCurricularPlanState state) {
if (state == DegreeCurricularPlanState.ACTIVE) {
return getActiveDegreeCurricularPlans();
}
return Collections.emptyList();
}
@Override
public List<DegreeCurricularPlan> getActiveDegreeCurricularPlans() {
return Collections.singletonList(getMostRecentDegreeCurricularPlan());
}
@Override
public List<DegreeCurricularPlan> getPastDegreeCurricularPlans() {
return Collections.emptyList();
}
@Override
public List<CurricularCourse> getExecutedCurricularCoursesByExecutionYear(final ExecutionYear executionYear) {
return Collections.emptyList();
}
@Override
public List<CurricularCourse> getExecutedCurricularCoursesByExecutionYearAndYear(final ExecutionYear ey, final Integer cy) {
return Collections.emptyList();
}
@Override
public List<ExecutionCourse> getExecutionCourses(String curricularCourseAcronym, ExecutionSemester executionSemester) {
return Collections.emptyList();
}
@Override
@Deprecated
final public String getName() {
return getPresentationName();
}
@Override
public String getNameEn() {
return getPresentationName();
}
@Override
final public String getPresentationName(ExecutionYear executionYear) {
return getNameFor((ExecutionYear) null).getContent(org.fenixedu.academic.util.LocaleUtils.PT);
}
@Override
final public String getFilteredName(final ExecutionYear executionYear, final Locale locale) {
return getNameFor(executionYear).getContent(locale);
}
@Override
public DegreeCurricularPlan getMostRecentDegreeCurricularPlan() {
return getDegreeCurricularPlansSet().iterator().next();
}
@Override
public DegreeCurricularPlan getLastActiveDegreeCurricularPlan() {
return getMostRecentDegreeCurricularPlan();
}
@Override
public LocalizedString getQualificationLevel(final ExecutionYear executionYear) {
return new LocalizedString();
}
@Override
public LocalizedString getProfessionalExits(final ExecutionYear executionYear) {
return new LocalizedString();
}
@Override
public DegreeInfo getMostRecentDegreeInfo() {
return null;
}
@Override
public DegreeInfo getDegreeInfoFor(ExecutionYear executionYear) {
return getMostRecentDegreeInfo();
}
@Override
public DegreeInfo getMostRecentDegreeInfo(ExecutionYear executionYear) {
return getMostRecentDegreeInfo();
}
@Override
public DegreeInfo createCurrentDegreeInfo() {
throw new DomainException("EmptyDegree.not.available");
}
@Override
public List<Integer> buildFullCurricularYearList() {
return Collections.emptyList();
}
@Override
final public boolean isCoordinator(final Person person, final ExecutionYear executionYear) {
return false;
}
@Override
final public Collection<Coordinator> getResponsibleCoordinators(final ExecutionYear executionYear) {
return Collections.emptySet();
}
@Override
final public Collection<Coordinator> getCurrentCoordinators() {
return Collections.emptySet();
}
@Override
final public Collection<Coordinator> getCurrentResponsibleCoordinators() {
return Collections.emptySet();
}
@Override
final public Collection<Teacher> getResponsibleCoordinatorsTeachers(final ExecutionYear executionYear) {
return Collections.emptySet();
}
@Override
final public Collection<Teacher> getCurrentResponsibleCoordinatorsTeachers() {
return Collections.emptySet();
}
@Override
public String constructSchoolClassPrefix(final Integer curricularYear) {
return StringUtils.EMPTY;
}
@Override
public boolean isFirstCycle() {
return false;
}
@Override
public boolean isSecondCycle() {
return false;
}
@Override
public boolean isAnyPublishedThesisAvailable() {
return false;
}
@Override
public boolean isAnyThesisAvailable() {
return false;
}
@Override
public Set<CurricularCourse> getAllCurricularCourses(ExecutionYear executionYear) {
return Collections.emptySet();
}
@Override
public Set<CurricularCourse> getCurricularCoursesFromGivenCurricularYear(int curricularYear, ExecutionYear executionYear) {
return Collections.emptySet();
}
@Override
public Set<CurricularCourse> getFirstCycleCurricularCourses(ExecutionYear executionYear) {
return Collections.emptySet();
}
@Override
public Set<CurricularCourse> getSecondCycleCurricularCourses(ExecutionYear executionYear) {
return Collections.emptySet();
}
@Override
public boolean canCreateGratuityEvent() {
return false;
}
}
| lgpl-3.0 |
WarpOrganization/warp | graphics/src/main/java/net/warpgame/engine/graphics/rendering/RenderTask.java | 6415 | package net.warpgame.engine.graphics.rendering;
import net.warpgame.engine.core.context.service.Profile;
import net.warpgame.engine.core.context.service.Service;
import net.warpgame.engine.core.context.task.RegisterTask;
import net.warpgame.engine.core.execution.task.EngineTask;
import net.warpgame.engine.graphics.camera.CameraHolder;
import net.warpgame.engine.graphics.camera.CameraProperty;
import net.warpgame.engine.graphics.command.Fence;
import net.warpgame.engine.graphics.command.Semaphore;
import net.warpgame.engine.graphics.command.queue.PresentationQueue;
import net.warpgame.engine.graphics.command.queue.Queue;
import net.warpgame.engine.graphics.command.queue.QueueManager;
import net.warpgame.engine.graphics.core.Device;
import net.warpgame.engine.graphics.utility.VulkanAssertionError;
import net.warpgame.engine.graphics.window.SwapChain;
import org.joml.Matrix4fc;
import org.lwjgl.BufferUtils;
import org.lwjgl.vulkan.VkPresentInfoKHR;
import org.lwjgl.vulkan.VkSubmitInfo;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import static net.warpgame.engine.graphics.GraphicsConfig.MAX_FRAMES_IN_FLIGHT;
import static org.lwjgl.vulkan.KHRSwapchain.*;
import static org.lwjgl.vulkan.VK10.*;
/**
* @author MarconZet
* Created 30.10.2019
*/
@Service
@Profile("graphics")
@RegisterTask(thread = "render")
public class RenderTask extends EngineTask {
private int currentFrame = 0;
private long frameNumber = 0;
private Semaphore[] imageAvailableSemaphore;
private Semaphore[] renderFinishedSemaphore;
private Fence[] inFlightFences;
private Queue graphicsQueue;
private PresentationQueue presentationQueue;
private RecordingTask recordingTask;
private CameraHolder cameraHolder;
private SwapChain swapChain;
private QueueManager queueManager;
private Device device;
public RenderTask(RecordingTask recordingTask, CameraHolder cameraHolder, SwapChain swapChain, QueueManager queueManager, Device device) {
this.recordingTask = recordingTask;
this.cameraHolder = cameraHolder;
this.swapChain = swapChain;
this.queueManager = queueManager;
this.device = device;
}
@Override
protected void onInit() {
try {
synchronized (swapChain) {
if (!swapChain.isCreated())
swapChain.wait();
}
} catch (InterruptedException e) {
if (!swapChain.isCreated())
throw new RuntimeException("Required resources are not ready", e);
}
graphicsQueue = queueManager.getGraphicsQueue();
presentationQueue = queueManager.getPresentationQueue();
recordingTask.setRenderTask(this);
imageAvailableSemaphore = new Semaphore[MAX_FRAMES_IN_FLIGHT];
renderFinishedSemaphore = new Semaphore[MAX_FRAMES_IN_FLIGHT];
inFlightFences = new Fence[MAX_FRAMES_IN_FLIGHT];
for (int i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
imageAvailableSemaphore[i] = new Semaphore(device);
renderFinishedSemaphore[i] = new Semaphore(device);
inFlightFences[i] = new Fence(device, VK_FENCE_CREATE_SIGNALED_BIT);
}
}
@Override
public void update(int delta) {
if(cameraHolder.getCameraProperty() == null || recordingTask.getLatestDrawCommand(currentFrame) == null) return;
drawFrame();
currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
frameNumber++;
}
@Override
protected void onClose() {
vkDeviceWaitIdle(device.get());
for (int i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
imageAvailableSemaphore[i].destroy();
renderFinishedSemaphore[i].destroy();
inFlightFences[i].destroy();
}
}
private void drawFrame() {
inFlightFences[currentFrame].block().reset();
IntBuffer pointer = BufferUtils.createIntBuffer(1);
int err = vkAcquireNextImageKHR(device.get(), swapChain.get(), Long.MAX_VALUE, imageAvailableSemaphore[currentFrame].get(), VK_NULL_HANDLE, pointer);
if(err != VK_SUCCESS && err != VK_SUBOPTIMAL_KHR){
throw new VulkanAssertionError("Failed to acquire next image from KHR", err);
}
int imageIndex = pointer.get(0);
CameraProperty camera = cameraHolder.getCameraProperty();
camera.update();
Matrix4fc viewMatrix = camera.getCameraMatrix();
Matrix4fc projectionMatrix = camera.getProjectionMatrix();
recordingTask.getVulkanRenders().forEach(x -> x.updateUniformBuffer(viewMatrix, projectionMatrix, imageIndex));
LongBuffer waitSemaphores = BufferUtils.createLongBuffer(1).put(0, imageAvailableSemaphore[currentFrame].get());
LongBuffer signalSemaphores = BufferUtils.createLongBuffer(1).put(0, renderFinishedSemaphore[currentFrame].get());
IntBuffer waitStages = BufferUtils.createIntBuffer(1).put(0, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);
VkSubmitInfo submitInfo = VkSubmitInfo.create()
.sType(VK_STRUCTURE_TYPE_SUBMIT_INFO)
.waitSemaphoreCount(1)
.pWaitSemaphores(waitSemaphores)
.pWaitDstStageMask(waitStages)
.pCommandBuffers(BufferUtils.createPointerBuffer(1).put(0, recordingTask.getLatestDrawCommand(imageIndex)))
.pSignalSemaphores(signalSemaphores);
err = graphicsQueue.submit(submitInfo, inFlightFences[currentFrame]);
if (err != VK_SUCCESS) {
throw new VulkanAssertionError("Failed to submit draw command buffer", err);
}
VkPresentInfoKHR presentInfo = VkPresentInfoKHR.create()
.sType(VK_STRUCTURE_TYPE_PRESENT_INFO_KHR)
.pWaitSemaphores(signalSemaphores)
.swapchainCount(1)
.pSwapchains(BufferUtils.createLongBuffer(1).put(0, swapChain.get()))
.pImageIndices(pointer);
err = presentationQueue.presentKHR(presentInfo);
if (err != VK_SUCCESS && err != VK_SUBOPTIMAL_KHR) {
throw new VulkanAssertionError("Failed to present swap chain image", err);
}
}
@Override
public int getPriority() {
return 20;
}
public long getFrameNumber() {
return frameNumber;
}
public Queue getGraphicsQueue() {
return graphicsQueue;
}
}
| lgpl-3.0 |
dma-ais/AisAbnormal | ais-ab-analyzer/src/test/java/dk/dma/ais/abnormal/analyzer/services/SafetyZoneServiceTest.java | 7500 | package dk.dma.ais.abnormal.analyzer.services;
import dk.dma.enav.model.geometry.Ellipse;
import dk.dma.enav.model.geometry.Position;
import org.apache.commons.configuration.Configuration;
import org.jmock.Expectations;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static dk.dma.ais.abnormal.analyzer.config.Configuration.CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_BEHIND;
import static dk.dma.ais.abnormal.analyzer.config.Configuration.CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_BREADTH;
import static dk.dma.ais.abnormal.analyzer.config.Configuration.CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_LENGTH;
import static java.lang.Math.abs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class SafetyZoneServiceTest {
private final Position position = Position.create(56, 12);
SafetyZoneService sut;
@Before
public void setup() {
JUnit4Mockery context = new JUnit4Mockery();
Configuration configurationMock = context.mock(Configuration.class);
context.checking(new Expectations() {{
oneOf(configurationMock).getDouble(with(CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_LENGTH));
will(returnValue(2.0));
oneOf(configurationMock).getDouble(with(CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_BREADTH));
will(returnValue(3.0));
oneOf(configurationMock).getDouble(with(CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_BEHIND));
will(returnValue(0.25));
}});
sut = new SafetyZoneService(configurationMock);
}
@Test
public void safetyZoneXYAreTranslatedForwardX() {
Ellipse ellipse = sut.safetyZone(position, position, 90.0f, 0.0f, 100.0f, 15.0f, 33, 6);
assertEquals(42.0, ellipse.getX(), 1e-6);
assertEquals(-1.5, ellipse.getY(), 1e-6);
}
@Test
public void safetyZoneXYAreTranslatedForwardY() {
Ellipse ellipse = sut.safetyZone(position, position, 0.0f, 0.0f, 100.0f, 15.0f, 33, 6);
assertEquals(1.5, ellipse.getX(), 1e-6); // Small number
assertEquals(42.0, ellipse.getY(), 1e-6); // Large number
}
@Test @Ignore
public void safetyZoneAtSpeedZeroIsSameSizeAsShip() {
// TODO Make safety zone depend on sog
}
@Test @Ignore
public void safetyZoneAtPositiveSpeedIsBiggerThanSizeAsShip() {
// TODO Make safety zone depend on sog
}
@Test
public void safetyZoneXYAreBigForDistantPositions() {
Ellipse ellipse1 = sut.safetyZone(Position.create(57, 12), Position.create(56, 12), 90.0f, 0.0f, 100.0f, 15.0f, 65.0f, 5.5f);
assertTrue(abs(ellipse1.getX()) < 1000);
assertTrue(abs(ellipse1.getY()) > 10000);
Ellipse ellipse2 = sut.safetyZone(Position.create(56, 13), Position.create(56, 12), 90.0f, 0.0f, 100.0f, 15.0f, 65.0f, 5.5f);
assertTrue(abs(ellipse2.getX()) > 10000);
assertTrue(abs(ellipse2.getY()) < 1000);
}
@Test
public void testComputeSafetyZoneCog45() {
Ellipse safetyEllipse = sut.safetyZone(position, position, 45.0f, 0.0f, 100.0f, 15.0f, 65.0f, 5.5f);
assertEquals(8.485281374238571, safetyEllipse.getX(), 1e-6);
assertEquals(5.65685424949238, safetyEllipse.getY(), 1e-6);
assertEquals(22.5, safetyEllipse.getBeta(), 1e-6);
assertEquals(100.0, safetyEllipse.getAlpha(), 1e-6);
assertEquals(45.0, safetyEllipse.getThetaDeg(), 1e-6);
}
@Test
public void testComputeSafetyZoneCog90() {
Ellipse safetyEllipse = sut.safetyZone(position, position, 90.0f, 0.0f, 100.0f, 15.0f, 65.0f, 5.5f);
assertEquals(10.0, safetyEllipse.getX(), 1e-6);
assertEquals(-2.0, safetyEllipse.getY(), 1e-6);
assertEquals(22.5, safetyEllipse.getBeta(), 1e-6);
assertEquals(100.0, safetyEllipse.getAlpha(), 1e-6);
assertEquals(0.0, safetyEllipse.getThetaDeg(), 1e-6);
}
@Test
public void testComputeSafetyZoneWithAlternativeConfigurationParameterEllipseLength() {
JUnit4Mockery context = new JUnit4Mockery();
Configuration configurationMock = context.mock(Configuration.class);
context.checking(new Expectations() {{
oneOf(configurationMock).getDouble(with(CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_LENGTH));
will(returnValue(1.0));
oneOf(configurationMock).getDouble(with(CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_BREADTH));
will(returnValue(3.0));
oneOf(configurationMock).getDouble(with(CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_BEHIND));
will(returnValue(0.25));
}});
SafetyZoneService sut = new SafetyZoneService(configurationMock);
Ellipse safetyEllipse = sut.safetyZone(position, position, 90.0f, 0.0f, 100.0f, 15.0f, 65.0f, 5.5f);
assertEquals(-15.0, safetyEllipse.getX(), 1e-6);
assertEquals(-2.0, safetyEllipse.getY(), 1e-6);
assertEquals(22.5, safetyEllipse.getBeta(), 1e-6);
assertEquals(75.0, safetyEllipse.getAlpha(), 1e-6);
assertEquals(0.0, safetyEllipse.getThetaDeg(), 1e-6);
}
@Test
public void testComputeSafetyZoneWithAlternativeConfigurationParameterEllipseBreadth() {
JUnit4Mockery context = new JUnit4Mockery();
Configuration configurationMock = context.mock(Configuration.class);
context.checking(new Expectations() {{
oneOf(configurationMock).getDouble(with(CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_LENGTH));
will(returnValue(2.0));
oneOf(configurationMock).getDouble(with(CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_BREADTH));
will(returnValue(5.0));
oneOf(configurationMock).getDouble(with(CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_BEHIND));
will(returnValue(0.25));
}});
SafetyZoneService sut = new SafetyZoneService(configurationMock);
Ellipse safetyEllipse = sut.safetyZone(position, position, 90.0f, 0.0f, 100.0f, 15.0f, 65.0f, 5.5f);
assertEquals(10.0, safetyEllipse.getX(), 1e-6);
assertEquals(-2.0, safetyEllipse.getY(), 1e-6);
assertEquals(37.5, safetyEllipse.getBeta(), 1e-6);
assertEquals(100.0, safetyEllipse.getAlpha(), 1e-6);
assertEquals(0.0, safetyEllipse.getThetaDeg(), 1e-6);
}
@Test
public void testComputeSafetyZoneWithAlternativeConfigurationParameterEllipseBehind() {
JUnit4Mockery context = new JUnit4Mockery();
Configuration configurationMock = context.mock(Configuration.class);
context.checking(new Expectations() {{
oneOf(configurationMock).getDouble(with(CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_LENGTH));
will(returnValue(2.0));
oneOf(configurationMock).getDouble(with(CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_BREADTH));
will(returnValue(3.0));
oneOf(configurationMock).getDouble(with(CONFKEY_SAFETYZONES_SAFETY_ELLIPSE_BEHIND));
will(returnValue(0.75));
}});
SafetyZoneService sut = new SafetyZoneService(configurationMock);
Ellipse safetyEllipse = sut.safetyZone(position, position, 90.0f, 0.0f, 100.0f, 15.0f, 65.0f, 5.5f);
assertEquals(-15.0, safetyEllipse.getX(), 1e-6);
assertEquals(-2.0, safetyEllipse.getY(), 1e-6);
assertEquals(22.5, safetyEllipse.getBeta(), 1e-6);
assertEquals(125.0, safetyEllipse.getAlpha(), 1e-6);
assertEquals(0.0, safetyEllipse.getThetaDeg(), 1e-6);
}
}
| lgpl-3.0 |
berisd/VirtualFile | src/main/java/at/beris/virtualfile/client/http/HttpClient.java | 2155 | /*
* This file is part of VirtualFile.
*
* Copyright 2016 by Bernd Riedl <bernd.riedl@gmail.com>
*
* Licensed under GNU Lesser General Public License 3.0 or later.
* Some rights reserved. See COPYING, AUTHORS.
*/
package at.beris.virtualfile.client.http;
import at.beris.virtualfile.attribute.FileAttribute;
import at.beris.virtualfile.client.Client;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.GroupPrincipal;
import java.nio.file.attribute.UserPrincipal;
import java.util.List;
import java.util.Set;
public class HttpClient implements Client<HttpFile, HttpClientConfiguration> {
public HttpClient(HttpClientConfiguration configuration) {
}
@Override
public void connect() {
}
@Override
public void disconnect() {
}
@Override
public void deleteFile(String path) {
}
@Override
public void createFile(String path) {
}
@Override
public boolean exists(String path) {
return false;
}
@Override
public void createDirectory(String path) {
}
@Override
public void deleteDirectory(String path) {
}
@Override
public InputStream getInputStream(String path) {
return null;
}
@Override
public OutputStream getOutputStream(String path) {
return null;
}
@Override
public HttpFile getFileInfo(String path) {
return null;
}
@Override
public List<HttpFile> list(String path) {
return null;
}
@Override
public void setLastModifiedTime(String path, FileTime time) {
}
@Override
public void setAttributes(String path, Set<FileAttribute> attributes) {
}
@Override
public void setOwner(String path, UserPrincipal owner) {
}
@Override
public void setGroup(String path, GroupPrincipal group) {
}
@Override
public void dispose() {
}
@Override
public HttpClientConfiguration getConfiguration() {
return null;
}
@Override
public String getCurrentDirectory() {
return "/";
}
}
| lgpl-3.0 |
pzhangleo/android-base | base/src/main/java/com/zhp/base/ui/widget/ptr/lib/header/StoreHouseBarItem.java | 2111 | package com.zhp.base.ui.widget.ptr.lib.header;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import java.util.Random;
/**
* Created by srain on 11/6/14.
*/
public class StoreHouseBarItem extends Animation {
public PointF midPoint;
public float translationX;
public int index;
private final Paint mPaint = new Paint();
private float mFromAlpha = 1.0f;
private float mToAlpha = 0.4f;
private PointF mCStartPoint;
private PointF mCEndPoint;
public StoreHouseBarItem(int index, PointF start, PointF end, int color, int lineWidth) {
this.index = index;
midPoint = new PointF((start.x + end.x) / 2, (start.y + end.y) / 2);
mCStartPoint = new PointF(start.x - midPoint.x, start.y - midPoint.y);
mCEndPoint = new PointF(end.x - midPoint.x, end.y - midPoint.y);
setColor(color);
setLineWidth(lineWidth);
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
}
public void setLineWidth(int width) {
mPaint.setStrokeWidth(width);
}
public void setColor(int color) {
mPaint.setColor(color);
}
public void resetPosition(int horizontalRandomness) {
Random random = new Random();
int randomNumber = -random.nextInt(horizontalRandomness) + horizontalRandomness;
translationX = randomNumber;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float alpha = mFromAlpha;
alpha = alpha + ((mToAlpha - alpha) * interpolatedTime);
setAlpha(alpha);
}
public void start(float fromAlpha, float toAlpha) {
mFromAlpha = fromAlpha;
mToAlpha = toAlpha;
super.start();
}
public void setAlpha(float alpha) {
mPaint.setAlpha((int) (alpha * 255));
}
public void draw(Canvas canvas) {
canvas.drawLine(mCStartPoint.x, mCStartPoint.y, mCEndPoint.x, mCEndPoint.y, mPaint);
}
} | lgpl-3.0 |
TKiura/GenericBroker2 | GenericBroker2/src/net/agmodel/resources/GeographicalResources_ko.java | 801 | package net.agmodel.resources;
import java.util.ListResourceBundle;
/**
* Default resources for MetBroker
*
* version 1.1 by T.Kiura
*
* Note: Don't use!!
*
*/
public class GeographicalResources_ko extends ListResourceBundle {
/**
*
* @uml.property name="contents"
*/
public Object[][] getContents() {
return contents;
}
public static final Object[][] contents = { { "location", "지역명" },
{ "area", "면적" }, { "zoomIn", "확대" }, { "zoomOut", "축소" },
{ "pan", "이동" }, { "unZoom", "확대취소" }, { "draw", "그리기" },
{ "polygon", "다각형" }, { "point", "점" }, { "polyLine", "다중선" },
{ "circle", "원" }, { "rectangle", "사각형" },
{ "aerialPhoto", "항공사진" }, { "roadMap", "도로망" }, { "dummy", "임시" } };
}
| lgpl-3.0 |
pazfernando/switchyard-bean-wssecurity-example | src/main/java/com/example/switchyard/switchyard_example/KeystorePasswordCallback.java | 2263 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.example.switchyard.switchyard_example;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.ws.security.WSPasswordCallback;
public class KeystorePasswordCallback implements CallbackHandler {
private Map<String, String> passwords = new HashMap<String, String>();
public KeystorePasswordCallback() {
passwords.put("alice", "welcome1");
passwords.put("bob", "welcome1");
passwords.put("swevolutivo", "welcome2");
}
/**
* It attempts to get the password from the private alias/passwords map.
*/
public void handle(Callback[] callbacks) throws IOException,
UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
String pass = passwords.get(pc.getIdentifier());
if (pass != null) {
pc.setPassword(pass);
return;
}
}
}
/**
* Add an alias/password pair to the callback mechanism.
*/
public void setAliasPassword(String alias, String password) {
passwords.put(alias, password);
}
}
| lgpl-3.0 |
Alfresco/alfresco-repository | src/main/java/org/alfresco/opencmis/search/CMISQueryServiceImpl.java | 8952 | /*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco 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.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.opencmis.search;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.alfresco.opencmis.dictionary.CMISDictionaryService;
import org.alfresco.opencmis.search.CMISQueryOptions.CMISQueryMode;
import org.alfresco.repo.search.impl.lucene.PagingLuceneResultSet;
import org.alfresco.repo.search.impl.querymodel.Query;
import org.alfresco.repo.search.impl.querymodel.QueryEngine;
import org.alfresco.repo.search.impl.querymodel.QueryEngineResults;
import org.alfresco.repo.search.impl.querymodel.QueryModelException;
import org.alfresco.repo.security.permissions.impl.acegi.FilteringResultSet;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.LimitBy;
import org.alfresco.service.cmr.search.QueryConsistency;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.util.Pair;
import org.apache.chemistry.opencmis.commons.enums.BaseTypeId;
import org.apache.chemistry.opencmis.commons.enums.CapabilityJoin;
import org.apache.chemistry.opencmis.commons.enums.CapabilityQuery;
/**
* @author andyh
*/
public class CMISQueryServiceImpl implements CMISQueryService
{
private CMISDictionaryService cmisDictionaryService;
private QueryEngine luceneQueryEngine;
private QueryEngine dbQueryEngine;
private NodeService nodeService;
private DictionaryService alfrescoDictionaryService;
public void setOpenCMISDictionaryService(CMISDictionaryService cmisDictionaryService)
{
this.cmisDictionaryService = cmisDictionaryService;
}
/**
* @param queryEngine
* the luceneQueryEngine to set
*/
public void setLuceneQueryEngine(QueryEngine queryEngine)
{
this.luceneQueryEngine = queryEngine;
}
/**
* @param queryEngine
* the dbQueryEngine to set
*/
public void setDbQueryEngine(QueryEngine queryEngine)
{
this.dbQueryEngine = queryEngine;
}
/**
* @param nodeService
* the nodeService to set
*/
public void setNodeService(NodeService nodeService)
{
this.nodeService = nodeService;
}
/**
* @param alfrescoDictionaryService
* the Alfresco Dictionary Service to set
*/
public void setAlfrescoDictionaryService(DictionaryService alfrescoDictionaryService)
{
this.alfrescoDictionaryService = alfrescoDictionaryService;
}
public CMISResultSet query(CMISQueryOptions options)
{
Pair<Query, QueryEngineResults> resultPair = executeQuerySwitchingImpl(options);
Query query = resultPair.getFirst();
QueryEngineResults results = resultPair.getSecond();
Map<String, ResultSet> wrapped = new HashMap<String, ResultSet>();
Map<Set<String>, ResultSet> map = results.getResults();
for (Set<String> group : map.keySet())
{
ResultSet current = map.get(group);
for (String selector : group)
{
wrapped.put(selector, filterNotExistingNodes(current));
}
}
LimitBy limitBy = null;
if ((null != results.getResults()) && !results.getResults().isEmpty()
&& (null != results.getResults().values()) && !results.getResults().values().isEmpty())
{
limitBy = results.getResults().values().iterator().next().getResultSetMetaData().getLimitedBy();
}
CMISResultSet cmis = new CMISResultSet(wrapped, options, limitBy, nodeService, query, cmisDictionaryService,
alfrescoDictionaryService);
return cmis;
}
private Pair<Query, QueryEngineResults> executeQuerySwitchingImpl(CMISQueryOptions options)
{
switch (options.getQueryConsistency())
{
case TRANSACTIONAL_IF_POSSIBLE :
{
try
{
return executeQueryUsingEngine(dbQueryEngine, options);
}
catch(QueryModelException qme)
{
return executeQueryUsingEngine(luceneQueryEngine, options);
}
}
case TRANSACTIONAL :
{
return executeQueryUsingEngine(dbQueryEngine, options);
}
case EVENTUAL :
case DEFAULT :
default :
{
return executeQueryUsingEngine(luceneQueryEngine, options);
}
}
}
private Pair<Query, QueryEngineResults> executeQueryUsingEngine(QueryEngine queryEngine, CMISQueryOptions options)
{
CapabilityJoin joinSupport = getJoinSupport();
if (options.getQueryMode() == CMISQueryOptions.CMISQueryMode.CMS_WITH_ALFRESCO_EXTENSIONS)
{
joinSupport = CapabilityJoin.INNERANDOUTER;
}
// TODO: Refactor to avoid duplication of valid scopes here and in
// CMISQueryParser
BaseTypeId[] validScopes = (options.getQueryMode() == CMISQueryMode.CMS_STRICT) ? CmisFunctionEvaluationContext.STRICT_SCOPES
: CmisFunctionEvaluationContext.ALFRESCO_SCOPES;
CmisFunctionEvaluationContext functionContext = new CmisFunctionEvaluationContext();
functionContext.setCmisDictionaryService(cmisDictionaryService);
functionContext.setNodeService(nodeService);
functionContext.setValidScopes(validScopes);
CMISQueryParser parser = new CMISQueryParser(options, cmisDictionaryService, joinSupport);
QueryConsistency queryConsistency = options.getQueryConsistency();
if (queryConsistency == QueryConsistency.DEFAULT)
{
options.setQueryConsistency(QueryConsistency.EVENTUAL);
}
Query query = parser.parse(queryEngine.getQueryModelFactory(), functionContext);
QueryEngineResults queryEngineResults = queryEngine.executeQuery(query, options, functionContext);
return new Pair<Query, QueryEngineResults>(query, queryEngineResults);
}
/* MNT-8804 filter ResultSet for nodes with corrupted indexes */
private ResultSet filterNotExistingNodes(ResultSet resultSet)
{
if (resultSet instanceof PagingLuceneResultSet)
{
ResultSet wrapped = ((PagingLuceneResultSet)resultSet).getWrapped();
if (wrapped instanceof FilteringResultSet)
{
FilteringResultSet filteringResultSet = (FilteringResultSet)wrapped;
for (int i = 0; i < filteringResultSet.length(); i++)
{
NodeRef nodeRef = filteringResultSet.getNodeRef(i);
/* filter node if it does not exist */
if (!nodeService.exists(nodeRef))
{
filteringResultSet.setIncluded(i, false);
}
}
}
}
return resultSet;
}
public CMISResultSet query(String query, StoreRef storeRef)
{
CMISQueryOptions options = new CMISQueryOptions(query, storeRef);
return query(options);
}
public boolean getPwcSearchable()
{
return true;
}
public boolean getAllVersionsSearchable()
{
return false;
}
public CapabilityQuery getQuerySupport()
{
return CapabilityQuery.BOTHCOMBINED;
}
public CapabilityJoin getJoinSupport()
{
return CapabilityJoin.NONE;
}
}
| lgpl-3.0 |
premium-minds/billy | billy-spain/src/main/java/com/premiumminds/billy/spain/persistence/dao/DAOESCreditReceipt.java | 1261 | /*
* Copyright (C) 2017 Premium Minds.
*
* This file is part of billy spain (ES Pack).
*
* billy spain (ES Pack) 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.
*
* billy spain (ES Pack) 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 billy spain (ES Pack). If not, see <http://www.gnu.org/licenses/>.
*/
package com.premiumminds.billy.spain.persistence.dao;
import java.util.List;
import com.premiumminds.billy.core.services.UID;
import com.premiumminds.billy.spain.persistence.entities.ESCreditReceiptEntity;
import com.premiumminds.billy.spain.services.entities.ESCreditReceipt;
public interface DAOESCreditReceipt extends AbstractDAOESGenericInvoice<ESCreditReceiptEntity> {
public List<ESCreditReceipt> findByReferencedDocument(UID uidCompany, UID uidInvoice);
}
| lgpl-3.0 |
ozacas/bioee | msconvertee/src/au/edu/unimelb/plantcell/servers/msconvertee/impl/MSConvertJobProcessor.java | 3069 | package au.edu.unimelb.plantcell.servers.msconvertee.impl;
import java.io.IOException;
import java.io.StringReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.TextMessage;
import javax.xml.bind.JAXBException;
import au.edu.unimelb.plantcell.servers.core.SendMessage;
/**
* Responsible for managing the job queue and processing jobs.
*
*
*
* @author http://www.plantcell.unimelb.edu.au/bioinformatics
*
*/
@MessageDriven
public class MSConvertJobProcessor implements MessageListener {
private final static Logger logger = Logger.getLogger("MSConvert Job Processor");
/*
* TomEE will load the MascotConfig instance for us
*/
@EJB private MSConvertConfig msconvert_config;
/*
* We also need the completion queue once a job has been done
* so that the web service can identify the results to report to a caller.
* Completion queue entries expire: currently 48 hours and at this time
* another MDB will cleanup the input data files (but not the .dat file computed by mascot)
*/
@Resource(name="MSConvertRunQueue")
private Queue runQueue; // waiting to run or currently running
@Resource(name="MSConvertDoneQueue")
private Queue doneQueue;
@Resource
private ConnectionFactory connectionFactory;
/**
* given that each msconvert job needs quite a bit of state to run, we must be careful which ExecutorService we
* use so that parallel access to state is carefully managed. For now we avoid this problem by using a single thread executor
*/
private static final ExecutorService mes = Executors.newSingleThreadExecutor();
public MSConvertJobProcessor() {
}
/*
* Note we start a separate thread since we must return from this function quickly to acknowledge delivery of the message.
* If we dont, we could incur a transaction timeout and cause mayhem...
*/
@Override
public void onMessage(final Message message) {
try {
if (message instanceof TextMessage) {
MSConvertJob job = MSConvertJob.unmarshal(new StringReader(((TextMessage)message).getText()));
logger.info("Adding "+job.getJobID()+" to msconvert run q");
/*
* must put the message in the runQueue BEFORE we return from this or the web service wont know about the job.
* Message does not expire after a set period in the runQueue (0)
*/
new SendMessage(logger, connectionFactory, runQueue, 0).send(job);
mes.execute(new ConversionJobThread(logger, job, msconvert_config, doneQueue, connectionFactory));
} else {
logger.warning("Got unknown message: "+message);
}
} catch (JMSException|IOException|JAXBException ex) {
ex.printStackTrace();
}
}
}
| lgpl-3.0 |
UniTime/cpsolver | src/org/cpsolver/studentsct/model/Section.java | 38061 | package org.cpsolver.studentsct.model;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.cpsolver.coursett.model.Placement;
import org.cpsolver.coursett.model.RoomLocation;
import org.cpsolver.coursett.model.TimeLocation;
import org.cpsolver.ifs.assignment.Assignment;
import org.cpsolver.ifs.assignment.AssignmentComparable;
import org.cpsolver.ifs.assignment.context.AbstractClassWithContext;
import org.cpsolver.ifs.assignment.context.AssignmentConstraintContext;
import org.cpsolver.ifs.assignment.context.CanInheritContext;
import org.cpsolver.ifs.model.Model;
import org.cpsolver.studentsct.reservation.Reservation;
/**
* Representation of a class. Each section contains id, name, scheduling
* subpart, time/room placement, and a limit. Optionally, parent-child relation
* between sections can be defined. <br>
* <br>
* Each student requesting a course needs to be enrolled in a class of each
* subpart of a selected configuration. In the case of parent-child relation
* between classes, if a student is enrolled in a section that has a parent
* section defined, he/she has to be enrolled in the parent section as well. If
* there is a parent-child relation between two sections, the same relation is
* defined on their subparts as well, i.e., if section A is a parent section B,
* subpart of section A isa parent of subpart of section B. <br>
* <br>
*
* @version StudentSct 1.3 (Student Sectioning)<br>
* Copyright (C) 2007 - 2014 Tomas Muller<br>
* <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
* <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
* <br>
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version. <br>
* <br>
* 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. <br>
* <br>
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not see
* <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>.
*/
public class Section extends AbstractClassWithContext<Request, Enrollment, Section.SectionContext> implements SctAssignment, AssignmentComparable<Section, Request, Enrollment>, CanInheritContext<Request, Enrollment, Section.SectionContext>{
private static DecimalFormat sDF = new DecimalFormat("0.000");
private long iId = -1;
private String iName = null;
private Map<Long, String> iNameByCourse = null;
private Subpart iSubpart = null;
private Section iParent = null;
private Placement iPlacement = null;
private int iLimit = 0;
private List<Instructor> iInstructors = null;
private double iPenalty = 0.0;
private double iSpaceExpected = 0.0;
private double iSpaceHeld = 0.0;
private String iNote = null;
private Set<Long> iIgnoreConflictsWith = null;
private boolean iCancelled = false, iEnabled = true, iOnline = false, iPast = false;
private List<Unavailability> iUnavailabilities = new ArrayList<Unavailability>();
/**
* Constructor
*
* @param id
* section unique id
* @param limit
* section limit, i.e., the maximal number of students that can
* be enrolled in this section at the same time
* @param name
* section name
* @param subpart
* subpart of this section
* @param placement
* time/room placement
* @param instructors
* assigned instructor(s)
* @param parent
* parent section -- if there is a parent section defined, a
* student that is enrolled in this section has to be enrolled in
* the parent section as well. Also, the same relation needs to
* be defined between subpart of this section and the subpart of
* the parent section
*/
public Section(long id, int limit, String name, Subpart subpart, Placement placement, List<Instructor> instructors, Section parent) {
iId = id;
iLimit = limit;
iName = name;
iSubpart = subpart;
if (iSubpart != null)
iSubpart.getSections().add(this);
iPlacement = placement;
iParent = parent;
iInstructors = instructors;
}
/**
* Constructor
*
* @param id
* section unique id
* @param limit
* section limit, i.e., the maximal number of students that can
* be enrolled in this section at the same time
* @param name
* section name
* @param subpart
* subpart of this section
* @param placement
* time/room placement
* @param instructors
* assigned instructor(s)
* @param parent
* parent section -- if there is a parent section defined, a
* student that is enrolled in this section has to be enrolled in
* the parent section as well. Also, the same relation needs to
* be defined between subpart of this section and the subpart of
* the parent section
*/
public Section(long id, int limit, String name, Subpart subpart, Placement placement, Section parent, Instructor... instructors) {
this(id, limit, name, subpart, placement, Arrays.asList(instructors), parent);
}
@Deprecated
public Section(long id, int limit, String name, Subpart subpart, Placement placement, String instructorIds, String instructorNames, Section parent) {
this(id, limit, name, subpart, placement, Instructor.toInstructors(instructorIds, instructorNames), parent);
}
/** Section id */
@Override
public long getId() {
return iId;
}
/**
* Section limit. This is defines the maximal number of students that can be
* enrolled into this section at the same time. It is -1 in the case of an
* unlimited section
* @return class limit
*/
public int getLimit() {
return iLimit;
}
/** Set section limit
* @param limit class limit
**/
public void setLimit(int limit) {
iLimit = limit;
}
/** Section name
* @return class name
**/
public String getName() {
return iName;
}
/** Set section name
* @param name class name
**/
public void setName(String name) {
iName = name;
}
/** Scheduling subpart to which this section belongs
* @return scheduling subpart
**/
public Subpart getSubpart() {
return iSubpart;
}
/**
* Parent section of this section (can be null). If there is a parent
* section defined, a student that is enrolled in this section has to be
* enrolled in the parent section as well. Also, the same relation needs to
* be defined between subpart of this section and the subpart of the parent
* section.
* @return parent class
*/
public Section getParent() {
return iParent;
}
/**
* Time/room placement of the section. This can be null, for arranged
* sections.
* @return time and room assignment of this class
*/
public Placement getPlacement() {
return iPlacement;
}
/**
* Set time/room placement of the section. This can be null, for arranged
* sections.
* @param placement time and room assignment of this class
*/
public void setPlacement(Placement placement) {
iPlacement = placement;
}
/** Time placement of the section. */
@Override
public TimeLocation getTime() {
return (iPlacement == null ? null : iPlacement.getTimeLocation());
}
/** Check if the class has a time assignment (is not arranged hours) */
public boolean hasTime() {
return iPlacement != null && iPlacement.getTimeLocation() != null && iPlacement.getTimeLocation().getDayCode() != 0;
}
/** True if the instructional type is the same */
public boolean sameInstructionalType(Section section) {
return getSubpart().getInstructionalType().equals(section.getSubpart().getInstructionalType());
}
/** True if the time assignment is the same */
public boolean sameTime(Section section) {
return getTime() == null ? section.getTime() == null : getTime().equals(section.getTime());
}
/** True if the instructor(s) are the same */
public boolean sameInstructors(Section section) {
if (nrInstructors() != section.nrInstructors()) return false;
return !hasInstructors() || getInstructors().containsAll(section.getInstructors());
}
/** True if the time assignment as well as the instructor(s) are the same */
public boolean sameChoice(Section section) {
return sameInstructionalType(section) && sameTime(section) && sameInstructors(section);
}
/** Number of rooms in which the section meet. */
@Override
public int getNrRooms() {
return (iPlacement == null ? 0 : iPlacement.getNrRooms());
}
/**
* Room placement -- list of
* {@link org.cpsolver.coursett.model.RoomLocation}
*/
@Override
public List<RoomLocation> getRooms() {
if (iPlacement == null)
return null;
if (iPlacement.getRoomLocations() == null && iPlacement.getRoomLocation() != null) {
List<RoomLocation> ret = new ArrayList<RoomLocation>(1);
ret.add(iPlacement.getRoomLocation());
return ret;
}
return iPlacement.getRoomLocations();
}
/**
* True, if this section overlaps with the given assignment in time and
* space
*/
@Override
public boolean isOverlapping(SctAssignment assignment) {
if (isAllowOverlap() || assignment.isAllowOverlap()) return false;
if (getTime() == null || assignment.getTime() == null) return false;
if (assignment instanceof Section && isToIgnoreStudentConflictsWith(assignment.getId())) return false;
return getTime().hasIntersection(assignment.getTime());
}
/**
* True, if this section overlaps with one of the given set of assignments
* in time and space
*/
@Override
public boolean isOverlapping(Set<? extends SctAssignment> assignments) {
if (isAllowOverlap()) return false;
if (getTime() == null || assignments == null)
return false;
for (SctAssignment assignment : assignments) {
if (assignment.isAllowOverlap())
continue;
if (assignment.getTime() == null)
continue;
if (assignment instanceof Section && isToIgnoreStudentConflictsWith(assignment.getId()))
continue;
if (getTime().hasIntersection(assignment.getTime()))
return true;
}
return false;
}
/** Called when an enrollment with this section is assigned to a request */
@Override
public void assigned(Assignment<Request, Enrollment> assignment, Enrollment enrollment) {
getContext(assignment).assigned(assignment, enrollment);
}
/** Called when an enrollment with this section is unassigned from a request */
@Override
public void unassigned(Assignment<Request, Enrollment> assignment, Enrollment enrollment) {
getContext(assignment).unassigned(assignment, enrollment);
}
/** Long name: subpart name + time long name + room names + instructor names
* @param useAmPm use 12-hour format
* @return long name
**/
public String getLongName(boolean useAmPm) {
return getSubpart().getName() + " " + getName() + " " + (getTime() == null ? "" : " " + getTime().getLongName(useAmPm))
+ (getNrRooms() == 0 ? "" : " " + getPlacement().getRoomName(","))
+ (hasInstructors() ? " " + getInstructorNames(",") : "");
}
@Deprecated
public String getLongName() {
return getLongName(true);
}
@Override
public String toString() {
return getSubpart().getConfig().getOffering().getName() + " " + getSubpart().getName() + " " + getName()
+ (getTime() == null ? "" : " " + getTime().getLongName(true))
+ (getNrRooms() == 0 ? "" : " " + getPlacement().getRoomName(","))
+ (hasInstructors() ? " " + getInstructorNames(",") : "") + " (L:"
+ (getLimit() < 0 ? "unlimited" : "" + getLimit())
+ (getPenalty() == 0.0 ? "" : ",P:" + sDF.format(getPenalty())) + ")";
}
/** Instructors assigned to this section
* @return list of instructors
**/
public List<Instructor> getInstructors() {
return iInstructors;
}
/**
* Has any instructors assigned
* @return return true if there is at least one instructor assigned
*/
public boolean hasInstructors() {
return iInstructors != null && !iInstructors.isEmpty();
}
/**
* Return number of instructors of this section
* @return number of assigned instructors
*/
public int nrInstructors() {
return iInstructors == null ? 0 : iInstructors.size();
}
/**
* Instructor names
* @param delim delimiter
* @return instructor names
*/
public String getInstructorNames(String delim) {
if (iInstructors == null || iInstructors.isEmpty()) return "";
StringBuffer sb = new StringBuffer();
for (Iterator<Instructor> i = iInstructors.iterator(); i.hasNext(); ) {
Instructor instructor = i.next();
sb.append(instructor.getName() != null ? instructor.getName() : instructor.getExternalId() != null ? instructor.getExternalId() : "I" + instructor.getId());
if (i.hasNext()) sb.append(delim);
}
return sb.toString();
}
/**
* Return penalty which is added to an enrollment that contains this
* section.
* @return online penalty
*/
public double getPenalty() {
return iPenalty;
}
/** Set penalty which is added to an enrollment that contains this section.
* @param penalty online penalty
**/
public void setPenalty(double penalty) {
iPenalty = penalty;
}
/**
* Compare two sections, prefer sections with lower penalty and more open
* space
*/
@Override
public int compareTo(Assignment<Request, Enrollment> assignment, Section s) {
int cmp = Double.compare(getPenalty(), s.getPenalty());
if (cmp != 0)
return cmp;
cmp = Double.compare(
getLimit() < 0 ? getContext(assignment).getEnrollmentWeight(assignment, null) : getContext(assignment).getEnrollmentWeight(assignment, null) - getLimit(),
s.getLimit() < 0 ? s.getContext(assignment).getEnrollmentWeight(assignment, null) : s.getContext(assignment).getEnrollmentWeight(assignment, null) - s.getLimit());
if (cmp != 0)
return cmp;
return Double.compare(getId(), s.getId());
}
/**
* Compare two sections, prefer sections with lower penalty
*/
@Override
public int compareTo(Section s) {
int cmp = Double.compare(getPenalty(), s.getPenalty());
if (cmp != 0)
return cmp;
return Double.compare(getId(), s.getId());
}
/**
* Return the amount of space of this section that is held for incoming
* students. This attribute is computed during the batch sectioning (it is
* the overall weight of dummy students enrolled in this section) and it is
* being updated with each incomming student during the online sectioning.
* @return space held
*/
public double getSpaceHeld() {
return iSpaceHeld;
}
/**
* Set the amount of space of this section that is held for incoming
* students. See {@link Section#getSpaceHeld()} for more info.
* @param spaceHeld space held
*/
public void setSpaceHeld(double spaceHeld) {
iSpaceHeld = spaceHeld;
}
/**
* Return the amount of space of this section that is expected to be taken
* by incoming students. This attribute is computed during the batch
* sectioning (for each dummy student that can attend this section (without
* any conflict with other enrollments of that student), 1 / x where x is
* the number of such sections of this subpart is added to this value).
* Also, this value is being updated with each incoming student during the
* online sectioning.
* @return space expected
*/
public double getSpaceExpected() {
return iSpaceExpected;
}
/**
* Set the amount of space of this section that is expected to be taken by
* incoming students. See {@link Section#getSpaceExpected()} for more info.
* @param spaceExpected space expected
*/
public void setSpaceExpected(double spaceExpected) {
iSpaceExpected = spaceExpected;
}
/**
* Online sectioning penalty.
* @param assignment current assignment
* @return online sectioning penalty
*/
public double getOnlineSectioningPenalty(Assignment<Request, Enrollment> assignment) {
if (getLimit() <= 0)
return 0.0;
double available = getLimit() - getContext(assignment).getEnrollmentWeight(assignment, null);
double penalty = (getSpaceExpected() - available) / getLimit();
return Math.max(-1.0, Math.min(1.0, penalty));
}
/**
* Return true if overlaps are allowed, but the number of overlapping slots should be minimized.
* This can be changed on the subpart, using {@link Subpart#setAllowOverlap(boolean)}.
**/
@Override
public boolean isAllowOverlap() {
return iSubpart.isAllowOverlap();
}
/** Sections first, then by {@link FreeTimeRequest#getId()} */
@Override
public int compareById(SctAssignment a) {
if (a instanceof Section) {
return Long.valueOf(getId()).compareTo(((Section)a).getId());
} else {
return -1;
}
}
/**
* Available space in the section that is not reserved by any section reservation
* @param assignment current assignment
* @param excludeRequest excluding given request (if not null)
* @return unreserved space in this class
**/
public double getUnreservedSpace(Assignment<Request, Enrollment> assignment, Request excludeRequest) {
// section is unlimited -> there is unreserved space unless there is an unlimited reservation too
// (in which case there is no unreserved space)
if (getLimit() < 0) {
// exclude reservations that are not directly set on this section
for (Reservation r: getSectionReservations()) {
// ignore expired reservations
if (r.isExpired()) continue;
// there is an unlimited reservation -> no unreserved space
if (r.getLimit() < 0) return 0.0;
}
return Double.MAX_VALUE;
}
double available = getLimit() - getContext(assignment).getEnrollmentWeight(assignment, excludeRequest);
// exclude reservations that are not directly set on this section
for (Reservation r: getSectionReservations()) {
// ignore expired reservations
if (r.isExpired()) continue;
// unlimited reservation -> all the space is reserved
if (r.getLimit() < 0.0) return 0.0;
// compute space that can be potentially taken by this reservation
double reserved = r.getContext(assignment).getReservedAvailableSpace(assignment, excludeRequest);
// deduct the space from available space
available -= Math.max(0.0, reserved);
}
return available;
}
/**
* Total space in the section that cannot be used by any section reservation
* @return total unreserved space in this class
**/
public synchronized double getTotalUnreservedSpace() {
if (iTotalUnreservedSpace == null)
iTotalUnreservedSpace = getTotalUnreservedSpaceNoCache();
return iTotalUnreservedSpace;
}
private Double iTotalUnreservedSpace = null;
private double getTotalUnreservedSpaceNoCache() {
// section is unlimited -> there is unreserved space unless there is an unlimited reservation too
// (in which case there is no unreserved space)
if (getLimit() < 0) {
// exclude reservations that are not directly set on this section
for (Reservation r: getSectionReservations()) {
// ignore expired reservations
if (r.isExpired()) continue;
// there is an unlimited reservation -> no unreserved space
if (r.getLimit() < 0) return 0.0;
}
return Double.MAX_VALUE;
}
// we need to check all reservations linked with this section
double available = getLimit(), reserved = 0, exclusive = 0;
Set<Section> sections = new HashSet<Section>();
reservations: for (Reservation r: getSectionReservations()) {
// ignore expired reservations
if (r.isExpired()) continue;
// unlimited reservation -> no unreserved space
if (r.getLimit() < 0) return 0.0;
for (Section s: r.getSections(getSubpart())) {
if (s.equals(this)) continue;
if (s.getLimit() < 0) continue reservations;
if (sections.add(s))
available += s.getLimit();
}
reserved += r.getLimit();
if (r.getSections(getSubpart()).size() == 1)
exclusive += r.getLimit();
}
return Math.min(available - reserved, getLimit() - exclusive);
}
/**
* Get reservations for this section
* @return reservations that can use this class
*/
public synchronized List<Reservation> getReservations() {
if (iReservations == null) {
iReservations = new ArrayList<Reservation>();
for (Reservation r: getSubpart().getConfig().getOffering().getReservations()) {
if (r.getSections(getSubpart()) == null || r.getSections(getSubpart()).contains(this))
iReservations.add(r);
}
}
return iReservations;
}
private List<Reservation> iReservations = null;
/**
* Get reservations that require this section
* @return reservations that must use this class
*/
public synchronized List<Reservation> getSectionReservations() {
if (iSectionReservations == null) {
iSectionReservations = new ArrayList<Reservation>();
for (Reservation r: getSubpart().getSectionReservations()) {
if (r.getSections(getSubpart()).contains(this))
iSectionReservations.add(r);
}
}
return iSectionReservations;
}
private List<Reservation> iSectionReservations = null;
/**
* Clear reservation information that was cached on this section
*/
public synchronized void clearReservationCache() {
iReservations = null;
iSectionReservations = null;
iTotalUnreservedSpace = null;
}
/**
* Return course-dependent section name
* @param courseId course offering unique id
* @return course dependent class name
*/
public String getName(long courseId) {
if (iNameByCourse == null) return getName();
String name = iNameByCourse.get(courseId);
return (name == null ? getName() : name);
}
/**
* Set course-dependent section name
* @param courseId course offering unique id
* @param name course dependent class name
*/
public void setName(long courseId, String name) {
if (iNameByCourse == null) iNameByCourse = new HashMap<Long, String>();
iNameByCourse.put(courseId, name);
}
/**
* Return course-dependent section names
* @return map of course-dependent class names
*/
public Map<Long, String> getNameByCourse() { return iNameByCourse; }
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof Section)) return false;
return getId() == ((Section)o).getId();
}
@Override
public int hashCode() {
return (int) (iId ^ (iId >>> 32));
}
/**
* Section note
* @return scheduling note
*/
public String getNote() { return iNote; }
/**
* Section note
* @param note scheduling note
*/
public void setNote(String note) { iNote = note; }
/**
* Add section id of a section that student conflicts are to be ignored with
* @param sectionId class unique id
*/
public void addIgnoreConflictWith(long sectionId) {
if (iIgnoreConflictsWith == null) iIgnoreConflictsWith = new HashSet<Long>();
iIgnoreConflictsWith.add(sectionId);
}
/**
* Returns true if student conflicts between this section and the given one are to be ignored
* @param sectionId class unique id
* @return true if student conflicts between these two sections are to be ignored
*/
public boolean isToIgnoreStudentConflictsWith(long sectionId) {
return iIgnoreConflictsWith != null && iIgnoreConflictsWith.contains(sectionId);
}
/**
* Returns a set of ids of sections that student conflicts are to be ignored with (between this section and the others)
* @return set of class unique ids of the sections that student conflicts are to be ignored with
*/
public Set<Long> getIgnoreConflictWithSectionIds() {
return iIgnoreConflictsWith;
}
/** Set of assigned enrollments */
@Override
public Set<Enrollment> getEnrollments(Assignment<Request, Enrollment> assignment) {
return getContext(assignment).getEnrollments();
}
/**
* Enrollment weight -- weight of all requests which have an enrollment that
* contains this section, excluding the given one. See
* {@link Request#getWeight()}.
* @param assignment current assignment
* @param excludeRequest course request to ignore, if any
* @return enrollment weight
*/
public double getEnrollmentWeight(Assignment<Request, Enrollment> assignment, Request excludeRequest) {
return getContext(assignment).getEnrollmentWeight(assignment, excludeRequest);
}
/**
* Enrollment weight including over the limit enrollments.
* That is enrollments that have reservation with {@link Reservation#canBatchAssignOverLimit()} set to true.
* @param assignment current assignment
* @param excludeRequest course request to ignore, if any
* @return enrollment weight
*/
public double getEnrollmentTotalWeight(Assignment<Request, Enrollment> assignment, Request excludeRequest) {
return getContext(assignment).getEnrollmentTotalWeight(assignment, excludeRequest);
}
/**
* Maximal weight of a single enrollment in the section
* @param assignment current assignment
* @return maximal enrollment weight
*/
public double getMaxEnrollmentWeight(Assignment<Request, Enrollment> assignment) {
return getContext(assignment).getMaxEnrollmentWeight();
}
/**
* Minimal weight of a single enrollment in the section
* @param assignment current assignment
* @return minimal enrollment weight
*/
public double getMinEnrollmentWeight(Assignment<Request, Enrollment> assignment) {
return getContext(assignment).getMinEnrollmentWeight();
}
/**
* Return cancelled flag of the class.
* @return true if the class is cancelled
*/
public boolean isCancelled() { return iCancelled; }
/**
* Set cancelled flag of the class.
* @param cancelled true if the class is cancelled
*/
public void setCancelled(boolean cancelled) { iCancelled = cancelled; }
/**
* Return past flag of the class.
* @return true if the class is in the past and should be avoided when possible
*/
public boolean isPast() { return iPast; }
/**
* Set past flag of the class.
* @param past true if the class is in the past and should be avoided when possible
*/
public void setPast(boolean past) { iPast = past; }
/**
* Return enabled flag of the class.
* @return true if the class is enabled for student scheduling
*/
public boolean isEnabled() { return iEnabled; }
/**
* Set enabled flag of the class.
* @param enabled true if the class is enabled for student scheduling
*/
public void setEnabled(boolean enabled) { iEnabled = enabled; }
/**
* Return whether the class is online.
* @return true if the class is online
*/
public boolean isOnline() { return iOnline; }
/**
* Set whether the class is online.
* @param online true if the class is online
*/
public void setOnline(boolean online) { iOnline = online; }
@Override
public Model<Request, Enrollment> getModel() {
return getSubpart().getConfig().getOffering().getModel();
}
@Override
public SectionContext createAssignmentContext(Assignment<Request, Enrollment> assignment) {
return new SectionContext(assignment);
}
@Override
public SectionContext inheritAssignmentContext(Assignment<Request, Enrollment> assignment, SectionContext parentContext) {
return new SectionContext(parentContext);
}
public class SectionContext implements AssignmentConstraintContext<Request, Enrollment> {
private Set<Enrollment> iEnrollments = null;
private double iEnrollmentWeight = 0.0;
private double iEnrollmentTotalWeight = 0.0;
private double iMaxEnrollmentWeight = 0.0;
private double iMinEnrollmentWeight = 0.0;
private boolean iReadOnly = false;
public SectionContext(Assignment<Request, Enrollment> assignment) {
iEnrollments = new HashSet<Enrollment>();
for (Course course: getSubpart().getConfig().getOffering().getCourses()) {
for (CourseRequest request: course.getRequests()) {
Enrollment enrollment = assignment.getValue(request);
if (enrollment != null && enrollment.getSections().contains(Section.this))
assigned(assignment, enrollment);
}
}
}
public SectionContext(SectionContext parent) {
iEnrollmentWeight = parent.iEnrollmentWeight;
iEnrollmentTotalWeight = parent.iEnrollmentTotalWeight;
iMaxEnrollmentWeight = parent.iMaxEnrollmentWeight;
iMinEnrollmentWeight = parent.iMinEnrollmentWeight;
iEnrollments = parent.iEnrollments;
iReadOnly = true;
}
/** Called when an enrollment with this section is assigned to a request */
@Override
public void assigned(Assignment<Request, Enrollment> assignment, Enrollment enrollment) {
if (iReadOnly) {
iEnrollments = new HashSet<Enrollment>(iEnrollments);
iReadOnly = false;
}
if (iEnrollments.isEmpty()) {
iMinEnrollmentWeight = iMaxEnrollmentWeight = enrollment.getRequest().getWeight();
} else {
iMaxEnrollmentWeight = Math.max(iMaxEnrollmentWeight, enrollment.getRequest().getWeight());
iMinEnrollmentWeight = Math.min(iMinEnrollmentWeight, enrollment.getRequest().getWeight());
}
if (iEnrollments.add(enrollment)) {
iEnrollmentTotalWeight += enrollment.getRequest().getWeight();
if (enrollment.getReservation() == null || !enrollment.getReservation().canBatchAssignOverLimit())
iEnrollmentWeight += enrollment.getRequest().getWeight();
}
}
/** Called when an enrollment with this section is unassigned from a request */
@Override
public void unassigned(Assignment<Request, Enrollment> assignment, Enrollment enrollment) {
if (iReadOnly) {
iEnrollments = new HashSet<Enrollment>(iEnrollments);
iReadOnly = false;
}
if (iEnrollments.remove(enrollment)) {
iEnrollmentTotalWeight -= enrollment.getRequest().getWeight();
if (enrollment.getReservation() == null || !enrollment.getReservation().canBatchAssignOverLimit())
iEnrollmentWeight -= enrollment.getRequest().getWeight();
}
if (iEnrollments.isEmpty()) {
iMinEnrollmentWeight = iMaxEnrollmentWeight = 0;
} else if (iMinEnrollmentWeight != iMaxEnrollmentWeight) {
if (iMinEnrollmentWeight == enrollment.getRequest().getWeight()) {
double newMinEnrollmentWeight = Double.MAX_VALUE;
for (Enrollment e : iEnrollments) {
if (e.getRequest().getWeight() == iMinEnrollmentWeight) {
newMinEnrollmentWeight = iMinEnrollmentWeight;
break;
} else {
newMinEnrollmentWeight = Math.min(newMinEnrollmentWeight, e.getRequest().getWeight());
}
}
iMinEnrollmentWeight = newMinEnrollmentWeight;
}
if (iMaxEnrollmentWeight == enrollment.getRequest().getWeight()) {
double newMaxEnrollmentWeight = Double.MIN_VALUE;
for (Enrollment e : iEnrollments) {
if (e.getRequest().getWeight() == iMaxEnrollmentWeight) {
newMaxEnrollmentWeight = iMaxEnrollmentWeight;
break;
} else {
newMaxEnrollmentWeight = Math.max(newMaxEnrollmentWeight, e.getRequest().getWeight());
}
}
iMaxEnrollmentWeight = newMaxEnrollmentWeight;
}
}
}
/** Set of assigned enrollments
* @return assigned enrollments of this section
**/
public Set<Enrollment> getEnrollments() {
return iEnrollments;
}
/**
* Enrollment weight -- weight of all requests which have an enrollment that
* contains this section, excluding the given one. See
* {@link Request#getWeight()}.
* @param assignment current assignment
* @param excludeRequest course request to ignore, if any
* @return enrollment weight
*/
public double getEnrollmentWeight(Assignment<Request, Enrollment> assignment, Request excludeRequest) {
double weight = iEnrollmentWeight;
if (excludeRequest != null) {
Enrollment enrollment = assignment.getValue(excludeRequest);
if (enrollment!= null && iEnrollments.contains(enrollment) && (enrollment.getReservation() == null || !enrollment.getReservation().canBatchAssignOverLimit()))
weight -= excludeRequest.getWeight();
}
return weight;
}
/**
* Enrollment weight including over the limit enrollments.
* That is enrollments that have reservation with {@link Reservation#canBatchAssignOverLimit()} set to true.
* @param assignment current assignment
* @param excludeRequest course request to ignore, if any
* @return enrollment weight
*/
public double getEnrollmentTotalWeight(Assignment<Request, Enrollment> assignment, Request excludeRequest) {
double weight = iEnrollmentTotalWeight;
if (excludeRequest != null) {
Enrollment enrollment = assignment.getValue(excludeRequest);
if (enrollment!= null && iEnrollments.contains(enrollment))
weight -= excludeRequest.getWeight();
}
return weight;
}
/**
* Maximal weight of a single enrollment in the section
* @return maximal enrollment weight
*/
public double getMaxEnrollmentWeight() {
return iMaxEnrollmentWeight;
}
/**
* Minimal weight of a single enrollment in the section
* @return minimal enrollment weight
*/
public double getMinEnrollmentWeight() {
return iMinEnrollmentWeight;
}
}
/**
* Choice matching this section
* @return choice matching this section
*/
public Choice getChoice() {
return new Choice(this);
}
/**
* List of student unavailabilities
* @return student unavailabilities
*/
public List<Unavailability> getUnavailabilities() { return iUnavailabilities; }
}
| lgpl-3.0 |
bullda/DroidText | src/bouncycastle/repack/org/bouncycastle/util/test/FixedSecureRandom.java | 3088 | package repack.org.bouncycastle.util.test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.SecureRandom;
public class FixedSecureRandom
extends SecureRandom
{
private byte[] _data;
private int _index;
private int _intPad;
public FixedSecureRandom(byte[] value)
{
this(false, new byte[][] { value });
}
public FixedSecureRandom(
byte[][] values)
{
this(false, values);
}
/**
* Pad the data on integer boundaries. This is necessary for the classpath project's BigInteger
* implementation.
*/
public FixedSecureRandom(
boolean intPad,
byte[] value)
{
this(intPad, new byte[][] { value });
}
/**
* Pad the data on integer boundaries. This is necessary for the classpath project's BigInteger
* implementation.
*/
public FixedSecureRandom(
boolean intPad,
byte[][] values)
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
for (int i = 0; i != values.length; i++)
{
try
{
bOut.write(values[i]);
}
catch (IOException e)
{
throw new IllegalArgumentException("can't save value array.");
}
}
_data = bOut.toByteArray();
if (intPad)
{
_intPad = _data.length % 4;
}
}
public void nextBytes(byte[] bytes)
{
System.arraycopy(_data, _index, bytes, 0, bytes.length);
_index += bytes.length;
}
//
// classpath's implementation of SecureRandom doesn't currently go back to nextBytes
// when next is called. We can't override next as it's a final method.
//
public int nextInt()
{
int val = 0;
val |= nextValue() << 24;
val |= nextValue() << 16;
if (_intPad == 2)
{
_intPad--;
}
else
{
val |= nextValue() << 8;
}
if (_intPad == 1)
{
_intPad--;
}
else
{
val |= nextValue();
}
return val;
}
//
// classpath's implementation of SecureRandom doesn't currently go back to nextBytes
// when next is called. We can't override next as it's a final method.
//
public long nextLong()
{
long val = 0;
val |= (long)nextValue() << 56;
val |= (long)nextValue() << 48;
val |= (long)nextValue() << 40;
val |= (long)nextValue() << 32;
val |= (long)nextValue() << 24;
val |= (long)nextValue() << 16;
val |= (long)nextValue() << 8;
val |= (long)nextValue();
return val;
}
public boolean isExhausted()
{
return _index == _data.length;
}
private int nextValue()
{
return _data[_index++] & 0xff;
}
}
| lgpl-3.0 |
tunguski/matsuo-core | matsuo-model/src/main/java/pl/matsuo/core/model/organization/initializer/CompanyInitializer.java | 337 | package pl.matsuo.core.model.organization.initializer;
import pl.matsuo.core.model.api.Initializer;
import pl.matsuo.core.model.organization.OrganizationUnit;
public class CompanyInitializer implements Initializer<OrganizationUnit> {
@Override
public void init(OrganizationUnit element) {
element.getEmployees().size();
}
}
| lgpl-3.0 |
hea3ven/BuildCraft | common/buildcraft/core/properties/WorldPropertyIsSoft.java | 785 | /**
* Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.core.properties;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
import buildcraft.api.core.BuildCraftAPI;
public class WorldPropertyIsSoft extends WorldProperty {
@Override
public boolean get(IBlockAccess blockAccess, Block block, int meta, int x, int y, int z) {
return block == null
|| block.isAir(blockAccess, x, y, z)
|| BuildCraftAPI.softBlocks.contains(block)
|| block.isReplaceable(blockAccess, x, y, z);
}
}
| lgpl-3.0 |
SirmaITT/conservation-space-1.7.0 | docker/sirma-platform/platform/seip-parent/api-gateway/ui-gateway/src/test/java/com/sirma/itt/sep/properties/unique/UniqueValueRequestBodyReaderTest.java | 3956 | package com.sirma.itt.sep.properties.unique;
import com.sirma.itt.seip.rest.exceptions.BadRequestException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.IOException;
import java.io.InputStream;
/**
* Unit tests for {@link UniqueValueRequestBodyReader ).
*
* @author Boyan Tonchev.
*/
@RunWith(MockitoJUnitRunner.class)
public class UniqueValueRequestBodyReaderTest {
@InjectMocks
private UniqueValueRequestBodyReader reader;
@Test
public void should_ValueBeNull_When_JsonKeyValueIsEmpty() throws IOException {
try (InputStream stream = this.getClass().getResourceAsStream("empty-value.json")) {
UniqueValueRequest uniqueValueRequest = reader.readFrom(null, null, null, null, null, stream);
Assert.assertNull(uniqueValueRequest.getValue());
}
}
@Test
public void should_ValueBeNull_When_JsonKeyValueIsNull() throws IOException {
try (InputStream stream = this.getClass().getResourceAsStream("null-value.json")) {
UniqueValueRequest uniqueValueRequest = reader.readFrom(null, null, null, null, null, stream);
Assert.assertNull(uniqueValueRequest.getValue());
}
}
@Test
public void should_ValueBeNull_When_JsonKeyValueIsMissing() throws IOException {
try (InputStream stream = this.getClass().getResourceAsStream("missing-value.json")) {
UniqueValueRequest uniqueValueRequest = reader.readFrom(null, null, null, null, null, stream);
Assert.assertNull(uniqueValueRequest.getValue());
}
}
@Test
public void should_Extract_AllProperties() throws IOException {
try (InputStream stream = this.getClass().getResourceAsStream("full-request.json")) {
UniqueValueRequest uniqueValueRequest = reader.readFrom(null, null, null, null, null, stream);
Assert.assertEquals("definition-id", uniqueValueRequest.getDefinitionId());
Assert.assertEquals("instance-id", uniqueValueRequest.getInstanceId());
Assert.assertEquals("title", uniqueValueRequest.getPropertyName());
Assert.assertEquals("value", uniqueValueRequest.getValue());
}
}
@Test(expected = BadRequestException.class)
public void should_ThrowException_When_PropertyNameAndDefinitionIdAreMissing() throws IOException {
try (InputStream stream = this.getClass().getResourceAsStream("missing-property-name-and-definition-id.json")) {
reader.readFrom(null, null, null, null, null, stream);
}
}
@Test(expected = BadRequestException.class)
public void should_ThrowException_When_PropertyNameIsMissing() throws IOException {
try (InputStream stream = this.getClass().getResourceAsStream("missing-property-name.json")) {
reader.readFrom(null, null, null, null, null, stream);
}
}
@Test(expected = BadRequestException.class)
public void should_ThrowException_When_DefinitionIdIsMissing() throws IOException {
try (InputStream stream = this.getClass().getResourceAsStream("missing-definition-id.json")) {
reader.readFrom(null, null, null, null, null, stream);
}
}
@Test(expected = BadRequestException.class)
public void should_ThrowException_When_JsonIsEmpty() throws IOException {
try (InputStream stream = this.getClass().getResourceAsStream("empty.json")) {
reader.readFrom(null, null, null, null, null, stream);
}
}
@Test
public void should_NotBeReadable_When_TypeIsNotCorrect() {
Assert.assertFalse(reader.isReadable(UniqueValueRequestBodyReader.class, null, null, null));
}
@Test
public void should_BeReadable_When_TypeIsCorrect() {
Assert.assertTrue(reader.isReadable(UniqueValueRequest.class, null, null, null));
}
} | lgpl-3.0 |
candyninja001/Factions | src/main/java/candy/factions/faction/EnumRank.java | 780 | package candy.factions.faction;
public enum EnumRank {
FOREIGNER, CITIZEN, GUARD, ADVISER, LEADER;
public int toInt() {
switch (this) {
case FOREIGNER:
return 0;
case CITIZEN:
return 1;
case GUARD:
return 2;
case ADVISER:
return 3;
case LEADER:
return 4;
default:
System.out.println("Could not convert EnumRank to int. Assigning FOREIGNER.");
return 0;
}
}
public static EnumRank fromInt(int relation) {
switch (relation) {
case 0:
return FOREIGNER;
case 1:
return CITIZEN;
case 2:
return GUARD;
case 3:
return ADVISER;
case 4:
return LEADER;
default:
System.out.println("Could not convert int to EnumRank. Assigning FOREIGNER.");
return FOREIGNER;
}
}
}
| lgpl-3.0 |
liuhongchao/GATE_Developer_7.0 | src/gate/gui/ontology/OntologyEditor.java | 92742 | /*
* Copyright (c) 1995-2012, The University of Sheffield. See the file
* COPYRIGHT.txt in the software or at http://gate.ac.uk/gate/COPYRIGHT.txt
*
* This file is part of GATE (see http://gate.ac.uk/), and is free
* software, licenced under the GNU Library General Public License,
* Version 2, June 1991 (in the distribution as file licence.html,
* and also available at http://gate.ac.uk/gate/licence.html).
*
* Niraj Aswani, 09/March/07
*
* $Id: OntologyEditor.html,v 1.0 2007/03/09 16:13:01 niraj Exp $
*/
package gate.gui.ontology;
import gate.Resource;
import gate.creole.AbstractVisualResource;
import gate.creole.ResourceInstantiationException;
import gate.creole.ontology.*;
import gate.event.*;
import gate.gui.*;
import gate.swing.XJTable;
import java.awt.*;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragGestureRecognizer;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceContext;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.*;
/**
* The GUI for the Ontology Editor
*
* @author niraj
*
*/
public class OntologyEditor extends AbstractVisualResource
implements
ResizableVisualResource,
OntologyModificationListener {
private static final long serialVersionUID = 3257847701214345265L;
/*
* (non-Javadoc)
*
* @see gate.creole.AbstractVisualResource#setTarget(java.lang.Object)
*/
public void setTarget(Object target) {
this.ontology = (Ontology)target;
selectedNodes = new ArrayList<DefaultMutableTreeNode>();
detailsTableModel.setOntology(ontology);
topClassAction.setOntology(ontology);
subClassAction.setOntology(ontology);
instanceAction.setOntology(ontology);
annotationPropertyAction.setOntology(ontology);
datatypePropertyAction.setOntology(ontology);
objectPropertyAction.setOntology(ontology);
symmetricPropertyAction.setOntology(ontology);
transitivePropertyAction.setOntology(ontology);
deleteOntoResourceAction.setOntology(ontology);
restrictionAction.setOntology(ontology);
ontology.removeOntologyModificationListener(this);
rebuildModel();
ontology.addOntologyModificationListener(this);
}
/**
* Init method, that creates this object and returns this object as a
* resource
*/
public Resource init() throws ResourceInstantiationException {
super.init();
initLocalData();
initGUIComponents();
initListeners();
return this;
}
/**
* Initialize the local data
*/
protected void initLocalData() {
itemComparator = new OntologyItemComparator();
listeners = new ArrayList<TreeNodeSelectionListener>();
}
/**
* Initialize the GUI Components
*/
protected void initGUIComponents() {
this.setLayout(new BorderLayout());
mainSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
this.add(mainSplit, BorderLayout.CENTER);
tabbedPane = new JTabbedPane();
mainSplit.setLeftComponent(tabbedPane);
rootNode = new DefaultMutableTreeNode(null, true);
treeModel = new DefaultTreeModel(rootNode);
tree = new DnDJTree(treeModel);
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
tree.setCellRenderer(new OntoTreeCellRenderer());
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
scroller = new JScrollPane(tree);
// enable tooltips for the tree
ToolTipManager.sharedInstance().registerComponent(tree);
tabbedPane.addTab("Classes & Instances", scroller);
scroller.setBorder(new TitledBorder("Classes and Instances"));
// ----------------------------------------------
propertyRootNode = new DefaultMutableTreeNode(null, true);
propertyTreeModel = new DefaultTreeModel(propertyRootNode);
propertyTree = new DnDJTree(propertyTreeModel);
propertyTree.setRootVisible(false);
propertyTree.setShowsRootHandles(true);
propertyTree.setCellRenderer(new OntoTreeCellRenderer());
propertyTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
propertyScroller = new JScrollPane(propertyTree);
// enable tooltips for the tree
ToolTipManager.sharedInstance().registerComponent(propertyTree);
tabbedPane.addTab("Properties", propertyScroller);
propertyScroller.setBorder(new TitledBorder("Properties"));
// -----------------------------------------------
detailsTableModel = new DetailsTableModel();
// ----------------
propertyDetailsTableModel = new PropertyDetailsTableModel();
// ----------------
detailsTable = new XJTable(detailsTableModel);
((XJTable)detailsTable).setSortable(false);
DetailsTableCellRenderer renderer = new DetailsTableCellRenderer();
detailsTable.getColumnModel().getColumn(DetailsTableModel.EXPANDED_COLUMN)
.setCellRenderer(renderer);
detailsTable.getColumnModel().getColumn(DetailsTableModel.LABEL_COLUMN)
.setCellRenderer(renderer);
detailsTable.getColumnModel().getColumn(DetailsTableModel.VALUE_COLUMN)
.setCellRenderer(renderer);
detailsTable.getColumnModel().getColumn(DetailsTableModel.DELETE_COLUMN)
.setCellRenderer(renderer);
detailsTable.setShowGrid(false);
detailsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
detailsTable.setColumnSelectionAllowed(true);
detailsTable.setRowSelectionAllowed(true);
detailsTable.setTableHeader(null);
detailsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
detailsTableScroller = new JScrollPane(detailsTable);
detailsTableScroller.getViewport().setOpaque(true);
detailsTableScroller.getViewport().setBackground(
detailsTable.getBackground());
mainSplit.setRightComponent(detailsTableScroller);
// -------------------
propertyDetailsTable = new XJTable(propertyDetailsTableModel);
((XJTable)propertyDetailsTable).setSortable(false);
PropertyDetailsTableCellRenderer propertyRenderer = new PropertyDetailsTableCellRenderer(
propertyDetailsTableModel);
propertyDetailsTable.getColumnModel().getColumn(
PropertyDetailsTableModel.EXPANDED_COLUMN).setCellRenderer(
propertyRenderer);
propertyDetailsTable.getColumnModel().getColumn(
PropertyDetailsTableModel.LABEL_COLUMN).setCellRenderer(
propertyRenderer);
propertyDetailsTable.getColumnModel().getColumn(
PropertyDetailsTableModel.VALUE_COLUMN).setCellRenderer(
propertyRenderer);
propertyDetailsTable.getColumnModel().getColumn(
PropertyDetailsTableModel.DELETE_COLUMN).setCellRenderer(
propertyRenderer);
propertyDetailsTable.setShowGrid(false);
propertyDetailsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
propertyDetailsTable.setColumnSelectionAllowed(true);
propertyDetailsTable.setRowSelectionAllowed(true);
propertyDetailsTable.setTableHeader(null);
propertyDetailsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
propertyDetailsTableScroller = new JScrollPane(propertyDetailsTable);
propertyDetailsTableScroller.getViewport().setOpaque(true);
propertyDetailsTableScroller.getViewport().setBackground(
propertyDetailsTable.getBackground());
// --------------------
toolBar = new JToolBar(JToolBar.HORIZONTAL);
searchAction = new SearchAction("", MainFrame.getIcon("ontology-search"),
this);
search = new JButton(searchAction);
search.setToolTipText("Advanced search in the ontology");
topClassAction = new TopClassAction("", MainFrame
.getIcon("ontology-topclass"));
topClass = new JButton(topClassAction);
topClass.setToolTipText("Add New Top Class");
refreshOntologyBtn =
new JButton(MainFrame.getIcon("crystal-clear-action-reload-small"));
refreshOntologyBtn.setToolTipText("Rebuilds the ontology tree");
refreshOntologyBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
rebuildModel();
}
});
subClassAction = new SubClassAction("", MainFrame
.getIcon("ontology-subclass"));
addTreeNodeSelectionListener(subClassAction);
subClass = new JButton(subClassAction);
subClass.setToolTipText("Add New Sub Class");
subClass.setEnabled(false);
instanceAction = new InstanceAction("", MainFrame
.getIcon("ontology-instance"));
addTreeNodeSelectionListener(instanceAction);
instance = new JButton(instanceAction);
instance.setToolTipText("Add New Instance");
instance.setEnabled(false);
annotationPropertyAction = new AnnotationPropertyAction("", MainFrame
.getIcon("ontology-annotation-property"));
annotationProperty = new JButton(annotationPropertyAction);
annotationProperty.setToolTipText("Add New Annotation Property");
annotationProperty.setEnabled(false);
datatypePropertyAction = new DatatypePropertyAction("", MainFrame
.getIcon("ontology-datatype-property"));
addTreeNodeSelectionListener(datatypePropertyAction);
datatypeProperty = new JButton(datatypePropertyAction);
datatypeProperty.setToolTipText("Add New Datatype Property");
datatypeProperty.setEnabled(false);
objectPropertyAction = new ObjectPropertyAction("", MainFrame
.getIcon("ontology-object-property"));
addTreeNodeSelectionListener(objectPropertyAction);
objectProperty = new JButton(objectPropertyAction);
objectProperty.setToolTipText("Add New Object Property");
objectProperty.setEnabled(false);
symmetricPropertyAction = new SymmetricPropertyAction("", MainFrame
.getIcon("ontology-symmetric-property"));
addTreeNodeSelectionListener(symmetricPropertyAction);
symmetricProperty = new JButton(symmetricPropertyAction);
symmetricProperty.setToolTipText("Add New Symmetric Property");
symmetricProperty.setEnabled(false);
transitivePropertyAction = new TransitivePropertyAction("", MainFrame
.getIcon("ontology-transitive-property"));
addTreeNodeSelectionListener(transitivePropertyAction);
transitiveProperty = new JButton(transitivePropertyAction);
transitiveProperty.setToolTipText("Add New Transitive Property");
transitiveProperty.setEnabled(false);
deleteOntoResourceAction = new DeleteOntologyResourceAction("", MainFrame
.getIcon("ontology-delete"));
restrictionAction = new RestrictionAction("", MainFrame
.getIcon("ontology-restriction"));
addTreeNodeSelectionListener(deleteOntoResourceAction);
delete = new JButton(deleteOntoResourceAction);
delete.setToolTipText("Delete the selected nodes");
delete.setEnabled(false);
restriction = new JButton(restrictionAction);
restriction.setToolTipText("Add New Restriction");
restriction.setEnabled(false);
toolBar.setFloatable(false);
toolBar.add(topClass);
toolBar.add(subClass);
toolBar.add(restriction);
toolBar.add(instance);
toolBar.add(annotationProperty);
toolBar.add(datatypeProperty);
toolBar.add(objectProperty);
toolBar.add(symmetricProperty);
toolBar.add(transitiveProperty);
toolBar.add(delete);
toolBar.add(search);
toolBar.add(refreshOntologyBtn);
this.add(toolBar, BorderLayout.NORTH);
}
private void updateSelection(JTree treeToUse, Component componentToUpdate) {
int[] selectedRows = treeToUse.getSelectionRows();
if(selectedRows != null && selectedRows.length > 0) {
selectedNodes.clear();
for(int i = 0; i < selectedRows.length; i++) {
DefaultMutableTreeNode node1 = (DefaultMutableTreeNode)treeToUse
.getPathForRow(selectedRows[i]).getLastPathComponent();
selectedNodes.add(node1);
}
if(treeToUse == tree) {
detailsTableModel
.setItem(((OResourceNode)(selectedNodes
.get(0)).getUserObject()).getResource());
}
else {
propertyDetailsTableModel
.setItem(((OResourceNode)(selectedNodes
.get(0)).getUserObject()).getResource());
}
enableDisableToolBarComponents();
fireTreeNodeSelectionChanged(selectedNodes);
if(treeToUse == tree)
propertyTree.clearSelection();
else tree.clearSelection();
}
mainSplit.setRightComponent(componentToUpdate);
mainSplit.updateUI();
}
/**
* Initializes various listeners
*/
protected void initListeners() {
tree.getSelectionModel().addTreeSelectionListener(
new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
updateSelection(tree, detailsTableScroller);
}
});
propertyTree.getSelectionModel().addTreeSelectionListener(
new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
updateSelection(propertyTree, propertyDetailsTableScroller);
}
});
mainSplit.addComponentListener(new ComponentListener() {
public void componentHidden(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {
}
public void componentResized(ComponentEvent e) {
mainSplit.setDividerLocation(0.4);
}
public void componentShown(ComponentEvent e) {
}
});
tree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
if(SwingUtilities.isRightMouseButton(me)) {
if(selectedNodes == null || selectedNodes.size() != 1) return;
final JPopupMenu menu = new JPopupMenu();
final JMenu addProperty = new JMenu("Properties");
final OResource candidate = ((OResourceNode)(selectedNodes
.get(0)).getUserObject()).getResource();
menu.add(addProperty);
final JMenuItem sameAs = new JMenuItem(candidate instanceof OClass
? "Equivalent Class"
: "Same As Instance");
menu.add(sameAs);
final JMenuItem subClass = new JMenuItem("Add SubClass", MainFrame
.getIcon("ontology-subclass"));
final JMenuItem instance = new JMenuItem("Add Instance", MainFrame
.getIcon("ontology-instance"));
final JMenuItem delete = new JMenuItem("Delete", MainFrame
.getIcon("delete"));
if(candidate instanceof OClass) {
menu.add(subClass);
menu.add(instance);
// invoke new sub class action
subClass.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
subClassAction.actionPerformed(ae);
}
});
// invoke new instance action
instance.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
instanceAction.actionPerformed(ae);
}
});
// invoke same as action
sameAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Set<OClass> oclasses = ontology.getOClasses(false);
ArrayList<OClass> classList = new ArrayList<OClass>();
Iterator<OClass> classIter = oclasses.iterator();
while(classIter.hasNext()) {
OClass aClass = classIter.next();
classList.add(aClass);
}
// the selected class shouldn't appear in the list
classList.remove(candidate);
ValuesSelectionAction vsa = new ValuesSelectionAction();
String[] classArray = new String[classList.size()];
for(int i = 0; i < classArray.length; i++) {
classArray[i] = classList.get(i).getONodeID().toString();
}
vsa.showGUI(candidate.getName() + " is equivalent to :",
classArray, new String[0], false, null);
String[] selectedValues = vsa.getSelectedValues();
for(int i = 0; i < selectedValues.length; i++) {
OClass byName = (OClass)
Utils.getOResourceFromMap(ontology,selectedValues[i]);
if(byName == null) continue;
((OClass)candidate).setEquivalentClassAs(byName);
}
TreePath path = tree.getSelectionPath();
tree.setSelectionRow(0);
tree.setSelectionPath(path);
return;
}
});
}
// same as action for OInstance
if(candidate instanceof OInstance) {
sameAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Set<OInstance> instances = ontology.getOInstances();
ArrayList<OInstance> instancesList = new ArrayList<OInstance>();
Iterator<OInstance> instancesIter = instances.iterator();
while(instancesIter.hasNext()) {
OInstance instance = instancesIter.next();
instancesList.add(instance);
}
instancesList.remove(candidate);
ValuesSelectionAction vsa = new ValuesSelectionAction();
String[] instancesArray = new String[instancesList.size()];
for(int i = 0; i < instancesArray.length; i++) {
instancesArray[i] = instancesList.get(i).getONodeID().toString();
}
vsa.showGUI(candidate.getName() + " is same As :",
instancesArray, new String[0], false, null);
String[] selectedValues = vsa.getSelectedValues();
for(int i = 0; i < selectedValues.length; i++) {
OInstance byName = (OInstance)
Utils.getOResourceFromMap(ontology,selectedValues[i]);
if(byName == null) continue;
((OInstance)candidate).setSameInstanceAs(byName);
}
TreePath path = tree.getSelectionPath();
tree.setSelectionRow(0);
tree.setSelectionPath(path);
return;
}
});
}
// add the delete button here
menu.add(delete);
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
deleteOntoResourceAction.actionPerformed(ae);
}
});
int propertyCounter = 0;
JMenu whereToAdd = addProperty;
// finally add properties
Set<RDFProperty> props = ontology.getPropertyDefinitions();
Iterator<RDFProperty> iter = props.iterator();
while(iter.hasNext()) {
final RDFProperty p = iter.next();
if(propertyCounter > 10) {
JMenu newMenu = new JMenu("More >");
whereToAdd.add(newMenu);
whereToAdd = newMenu;
propertyCounter = 0;
whereToAdd.setEnabled(false);
}
// if property is an annotation property
if(p instanceof AnnotationProperty) {
JMenuItem item = new JMenuItem(new AnnotationPropertyValueAction(
p.getName(), candidate, (AnnotationProperty) p));
whereToAdd.setEnabled(true);
whereToAdd.add(item);
propertyCounter++;
continue;
}
// if it is a datatype property
if(candidate instanceof OInstance
&& p instanceof DatatypeProperty
&& p.isValidDomain(candidate)) {
JMenuItem item = new JMenuItem(new DatatypePropertyValueAction(
p.getName(), candidate, (DatatypeProperty) p));
whereToAdd.add(item);
whereToAdd.setEnabled(true);
propertyCounter++;
continue;
}
// if it is an object property
if(candidate instanceof OInstance
&& p instanceof ObjectProperty
&& p.isValidDomain(candidate)) {
JMenuItem item = new JMenuItem(new ObjectPropertyValueAction(
p.getName(), candidate, (ObjectProperty) p, null));
whereToAdd.add(item);
whereToAdd.setEnabled(true);
propertyCounter++;
continue;
}
}
menu.show(tree, me.getX(), me.getY());
menu.setVisible(true);
}
}
});
propertyTree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
if(SwingUtilities.isRightMouseButton(me)) {
if(selectedNodes == null || selectedNodes.size() != 1) return;
final JPopupMenu menu = new JPopupMenu();
final OResource candidate = ((OResourceNode)((DefaultMutableTreeNode)selectedNodes
.get(0)).getUserObject()).getResource();
final JMenuItem sameAs = new JMenuItem("Equivalent Property");
final JMenuItem delete = new JMenuItem("Delete", MainFrame
.getIcon("delete"));
final JCheckBoxMenuItem functional = new JCheckBoxMenuItem(
"Functional");
final JCheckBoxMenuItem inverseFunctional = new JCheckBoxMenuItem(
"InverseFunctional");
menu.add(sameAs);
if(candidate instanceof AnnotationProperty) {
return;
}
final Set<RDFProperty> props = new HashSet<RDFProperty>();
if(candidate instanceof ObjectProperty) {
props.addAll(ontology.getObjectProperties());
functional.setSelected(((ObjectProperty)candidate).isFunctional());
inverseFunctional.setSelected(((ObjectProperty)candidate)
.isInverseFunctional());
functional.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
((ObjectProperty)candidate).setFunctional(functional
.isSelected());
}
});
inverseFunctional.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
((ObjectProperty)candidate)
.setInverseFunctional(inverseFunctional.isSelected());
}
});
menu.add(functional);
menu.add(inverseFunctional);
}
else if(candidate instanceof DatatypeProperty) {
props.addAll(ontology.getDatatypeProperties());
}
else {
props.addAll(ontology.getRDFProperties());
}
sameAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
props.remove(candidate);
Iterator<RDFProperty> iter = props.iterator();
ValuesSelectionAction vsa = new ValuesSelectionAction();
String[] propArray = new String[props.size()];
for(int i = 0; i < propArray.length; i++) {
propArray[i] = iter.next().getONodeID().toString();
}
vsa.showGUI(candidate.getName() + " is equivalent to :",
propArray, new String[0], false, null);
String[] selectedValues = vsa.getSelectedValues();
for(int i = 0; i < selectedValues.length; i++) {
RDFProperty byName = (RDFProperty)
Utils.getOResourceFromMap(ontology,selectedValues[i]);
if(byName == null) continue;
((RDFProperty)candidate).setEquivalentPropertyAs(byName);
}
TreePath path = propertyTree.getSelectionPath();
propertyTree.setSelectionRow(0);
propertyTree.setSelectionPath(path);
return;
}
});
menu.add(delete);
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
deleteOntoResourceAction.actionPerformed(ae);
}
});
JMenu addProperty = new JMenu("Properties");
Set<RDFProperty> rdfprops = ontology.getPropertyDefinitions();
Iterator<RDFProperty> iter = rdfprops.iterator();
menu.add(addProperty);
JMenu whereToAdd = addProperty;
int propertyCounter = 0;
while(iter.hasNext()) {
final RDFProperty p = iter.next();
if(propertyCounter > 10) {
JMenu newMenu = new JMenu("More >");
whereToAdd.add(newMenu);
whereToAdd = newMenu;
propertyCounter = 0;
whereToAdd.setEnabled(false);
}
if(p instanceof AnnotationProperty) {
JMenuItem item = new JMenuItem(p.getName(), MainFrame
.getIcon("ontology-annotation-property"));
whereToAdd.add(item);
whereToAdd.setEnabled(true);
propertyCounter++;
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String value = JOptionPane.showInputDialog(
MainFrame.getInstance(),
"Enter Value for property :" + p.getName());
if(value != null) {
candidate.addAnnotationPropertyValue((AnnotationProperty)p,
new Literal(value));
}
TreePath path = propertyTree.getSelectionPath();
propertyTree.setSelectionRow(0);
propertyTree.setSelectionPath(path);
return;
}
});
}
}
menu.show(propertyTree, me.getX(), me.getY());
menu.setVisible(true);
}
}
});
detailsTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
if(SwingUtilities.isLeftMouseButton(me)) {
int row = detailsTable.getSelectedRow();
int column = detailsTable.getSelectedColumn();
if(row == -1 || column == -1) { return; }
Object value = detailsTableModel.getValueAt(
row, DetailsTableModel.LABEL_COLUMN);
OResource resource = detailsTableModel.getItem();
if(value instanceof DetailsGroup) {
if(column == DetailsTableModel.EXPANDED_COLUMN) {
boolean expanded = ((DetailsGroup)value).isExpanded();
((DetailsGroup)value).setExpanded(!expanded);
detailsTable.updateUI();
}
}
else if(column == DetailsTableModel.LABEL_COLUMN
&& me.getClickCount() == 2) {
OResource toSelect = null;
JTree treeToSelectIn = null;
if(value instanceof OClass) {
toSelect = (OResource) value;
treeToSelectIn = tree;
}
else if(value instanceof RDFProperty) {
toSelect = (RDFProperty) value;
treeToSelectIn = propertyTree;
}
else if(value instanceof PropertyValue) {
toSelect = ((PropertyValue) value).getProperty();
treeToSelectIn = propertyTree;
}
if(toSelect != null) {
treeToSelectIn.setSelectionPath(new TreePath(uri2TreeNodesListMap
.get(toSelect.getONodeID().toString()).get(0).getPath()));
treeToSelectIn.scrollPathToVisible(treeToSelectIn
.getSelectionPath());
if(treeToSelectIn == tree) {
tabbedPane.setSelectedComponent(scroller);
}
else {
tabbedPane.setSelectedComponent(propertyScroller);
}
}
}
else if(value instanceof PropertyValue
&& column == DetailsTableModel.VALUE_COLUMN
&& me.getClickCount() == 2) {
PropertyValue pv = (PropertyValue) value;
RDFProperty p = pv.getProperty();
// if it is an object property
if(p instanceof ObjectProperty) {
new ObjectPropertyValueAction("", resource,
(ObjectProperty) p, (OInstance)pv.getValue())
.actionPerformed(null);
}
// for the other types of data edit directly in cell
}
else if(value instanceof RDFProperty
&& column == DetailsTableModel.VALUE_COLUMN
&& me.getClickCount() == 2) {
final RDFProperty property = (RDFProperty) value;
if (property instanceof AnnotationProperty) {
resource.addAnnotationPropertyValue(
(AnnotationProperty) property, new Literal(""));
detailsTableModel.setItem(resource);
SwingUtilities.invokeLater(new Runnable() { public void run() {
for (int rowI = detailsTable.getRowCount()-1; rowI >= 0; rowI--) {
if (detailsTable.getValueAt(rowI,
DetailsTableModel.VALUE_COLUMN).equals("")
&& detailsTable.getValueAt(rowI,
DetailsTableModel.LABEL_COLUMN) instanceof PropertyValue
&& ((PropertyValue)detailsTable.getValueAt(rowI,
DetailsTableModel.LABEL_COLUMN)).getProperty()
.equals(property)) {
detailsTable.editCellAt(rowI, DetailsTableModel.VALUE_COLUMN);
detailsTable.getEditorComponent().requestFocusInWindow();
break;
}
}
}});
}
else if (property instanceof DatatypeProperty
&& resource instanceof OInstance
) {
String type = ((DatatypeProperty)property)
.getDataType().getXmlSchemaURIString();
final String literalValue;
if (type.endsWith("boolean")) {
literalValue = "true";
} else if (type.endsWith("date")) {
literalValue = "01/01/2000";
} else if (type.endsWith("time")) {
literalValue = "12:00";
} else if (type.endsWith("decimal")
|| type.endsWith("double")
|| type.endsWith("float")) {
literalValue = "1.0";
} else if (type.endsWith("byte")
|| type.endsWith("unsignedByte")) {
literalValue = "F";
} else if (type.endsWith("int")
|| type.endsWith("integer")
|| type.endsWith("long")
|| type.endsWith("unsignedInt")
|| type.endsWith("unsignedShort")
|| type.endsWith("unsignedLong")
|| type.endsWith("nonNegativeInteger")
|| type.endsWith("positiveInteger")
|| type.endsWith("short")
|| type.endsWith("duration")) {
literalValue = "1";
} else if (type.endsWith("negativeInteger")
|| type.endsWith("nonPositiveInteger")) {
literalValue = "-1";
} else {
literalValue = "";
}
try {
((OInstance)resource).addDatatypePropertyValue(
(DatatypeProperty) property, new Literal(literalValue,
((DatatypeProperty)property).getDataType()));
} catch(InvalidValueException e) {
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"Incompatible value");
e.printStackTrace();
return;
}
detailsTableModel.setItem(resource);
SwingUtilities.invokeLater(new Runnable() { public void run() {
for (int rowI = detailsTable.getRowCount()-1; rowI >= 0; rowI--) {
if (detailsTable.getValueAt(rowI,
DetailsTableModel.VALUE_COLUMN).equals(literalValue)
&& detailsTable.getValueAt(rowI,
DetailsTableModel.LABEL_COLUMN) instanceof PropertyValue
&& ((PropertyValue)detailsTable.getValueAt(rowI,
DetailsTableModel.LABEL_COLUMN)).getProperty()
.equals(property)) {
detailsTable.editCellAt(rowI, DetailsTableModel.VALUE_COLUMN);
detailsTable.getEditorComponent().requestFocusInWindow();
break;
}
}
}});
}
else if (property instanceof ObjectProperty
&& resource instanceof OInstance) {
new ObjectPropertyValueAction("", resource,
(ObjectProperty) property, null).actionPerformed(null);
}
}
else if(value instanceof PropertyValue
&& column == DetailsTableModel.DELETE_COLUMN
&& me.getClickCount() == 1) {
PropertyValue pv = (PropertyValue) value;
try {
if(resource instanceof OClass) {
if(pv.getProperty() instanceof AnnotationProperty) {
resource.removeAnnotationPropertyValue(
(AnnotationProperty)pv.getProperty(), (Literal)pv
.getValue());
}
}
else {
OInstance instance = (OInstance)resource;
if(pv.getProperty() instanceof AnnotationProperty) {
instance.removeAnnotationPropertyValue((AnnotationProperty)pv
.getProperty(), (Literal)pv.getValue());
}
else if(pv.getProperty() instanceof DatatypeProperty) {
instance.removeDatatypePropertyValue((DatatypeProperty)pv
.getProperty(), (Literal)pv.getValue());
}
else if(pv.getProperty() instanceof ObjectProperty) {
instance.removeObjectPropertyValue((ObjectProperty)pv
.getProperty(), (OInstance)pv.getValue());
}
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TreePath path = tree.getSelectionPath();
tree.setSelectionRow(0);
tree.setSelectionPath(path);
}
});
}
catch(Exception e) {
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"Cannot delete the property value because \n"
+ e.getMessage());
e.printStackTrace();
}
}
}
}
});
propertyDetailsTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
if(SwingUtilities.isLeftMouseButton(me)) {
int[] rows = propertyDetailsTable.getSelectedRows();
int column = propertyDetailsTable.getSelectedColumn();
if(rows == null || rows.length == 0) return;
Object value = propertyDetailsTable.getModel().getValueAt(rows[0], 1);
if(value instanceof DetailsGroup) {
if(column == 0) {
boolean expanded = ((DetailsGroup)value).isExpanded();
((DetailsGroup)value).setExpanded(!expanded);
propertyDetailsTable.updateUI();
}
else {
return;
}
}
if(value instanceof DetailsGroup) return;
final Object finalObj = value;
// find out the selected component in the tree
Object sc = propertyTree.getSelectionPath().getLastPathComponent();
if(sc == null) {
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"No resource selected in the main ontology tree");
return;
}
// find out the treenode for the current selection
final DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)sc;
final OResource resource = ((OResourceNode)dmtn.getUserObject())
.getResource();
if((!(finalObj instanceof PropertyValue) || column == 1)
&& me.getClickCount() == 2) {
OResource toSelect = null;
JTree treeToSelectIn = null;
if(finalObj instanceof OClass) {
toSelect = (OResource)finalObj;
treeToSelectIn = tree;
}
else if(finalObj instanceof RDFProperty) {
toSelect = (RDFProperty)finalObj;
treeToSelectIn = propertyTree;
}
else if(finalObj instanceof PropertyValue) {
toSelect = ((PropertyValue)finalObj).getProperty();
treeToSelectIn = propertyTree;
}
if(toSelect != null) {
treeToSelectIn.setSelectionPath(new TreePath(uri2TreeNodesListMap
.get(toSelect.getONodeID().toString()).get(0).getPath()));
treeToSelectIn.scrollPathToVisible(treeToSelectIn
.getSelectionPath());
if(treeToSelectIn == tree) {
tabbedPane.setSelectedComponent(scroller);
}
else {
tabbedPane.setSelectedComponent(propertyScroller);
}
return;
}
}
if(finalObj instanceof PropertyValue && column == 2
&& me.getClickCount() == 2) {
PropertyValue pv = (PropertyValue)finalObj;
RDFProperty p = pv.getProperty();
// if property is an annotation property
if(p instanceof AnnotationProperty) {
String reply = JOptionPane.showInputDialog(MainFrame
.getInstance(), ((Literal)pv.getValue()).getValue(),
"Value for " + p.getName() + " property",
JOptionPane.QUESTION_MESSAGE);
if(reply != null) {
resource.removeAnnotationPropertyValue((AnnotationProperty)p,
(Literal)pv.getValue());
resource.addAnnotationPropertyValue((AnnotationProperty)p,
new Literal(reply));
}
TreePath path = propertyTree.getSelectionPath();
propertyTree.setSelectionRow(0);
propertyTree.setSelectionPath(path);
return;
}
}
if(finalObj instanceof PropertyValue && column == 3
&& me.getClickCount() == 1) {
PropertyValue pv = (PropertyValue)finalObj;
try {
if(resource instanceof RDFProperty) {
if(pv.getProperty() instanceof AnnotationProperty) {
((RDFProperty)resource).removeAnnotationPropertyValue(
(AnnotationProperty)pv.getProperty(), (Literal)pv
.getValue());
}
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TreePath path = propertyTree.getSelectionPath();
propertyTree.setSelectionRow(0);
propertyTree.setSelectionPath(path);
}
});
}
catch(Exception e) {
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"Cannot delete the property value because \n"
+ e.getMessage());
e.printStackTrace();
}
}
}
}
});
}
protected class AnnotationPropertyValueAction extends AbstractAction {
public AnnotationPropertyValueAction(String name, OResource oResource,
AnnotationProperty property) {
super(name, MainFrame.getIcon("ontology-annotation-property"));
this.oResource = oResource;
this.property = property;
}
public void actionPerformed(ActionEvent e) {
Object inputValue = JOptionPane.showInputDialog(MainFrame.getInstance(),
"<html>Enter a value for the property <b>" +
property.getName() + "</b>",
"New property value", JOptionPane.QUESTION_MESSAGE,
MainFrame.getIcon("ontology-annotation-property"), null, null);
if(inputValue != null) {
// add a new property value
oResource.addAnnotationPropertyValue(
property, new Literal((String) inputValue));
}
// reselect instance in the tree to update the table
TreePath path = tree.getSelectionPath();
tree.setSelectionRow(0);
tree.setSelectionPath(path);
}
private OResource oResource;
private AnnotationProperty property;
}
protected class DatatypePropertyValueAction extends AbstractAction {
public DatatypePropertyValueAction(String name, OResource oResource,
DatatypeProperty property) {
super(name, MainFrame.getIcon("ontology-datatype-property"));
this.oResource = oResource;
this.property = property;
}
public void actionPerformed(ActionEvent ae) {
Object inputValue = JOptionPane.showInputDialog(MainFrame.getInstance(),
"<html>Enter a value for the property <b>" +
property.getName() + "</b>\n" +
"of type " + property.getDataType().getXmlSchemaURIString()
.replaceFirst("http://www.w3.org/2001/XMLSchema#", ""),
"New property value", JOptionPane.QUESTION_MESSAGE,
MainFrame.getIcon("ontology-datatype-property"), null, null);
if(inputValue != null) {
boolean validValue = property.getDataType()
.isValidValue((String) inputValue);
if(!validValue) {
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"Incompatible value: " + inputValue);
return;
}
try {
((OInstance)oResource).addDatatypePropertyValue(property,
new Literal((String) inputValue, property.getDataType()));
}
catch(InvalidValueException e) {
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"Incompatible value.\n" + e.getMessage());
return;
}
}
TreePath path = tree.getSelectionPath();
tree.setSelectionRow(0);
tree.setSelectionPath(path);
}
private OResource oResource;
private DatatypeProperty property;
}
protected class ObjectPropertyValueAction extends AbstractAction {
public ObjectPropertyValueAction(String name, OResource oResource,
ObjectProperty property,
OInstance oldValue) {
super(name, MainFrame.getIcon("ontology-object-property"));
this.oResource = oResource;
this.property = property;
this.oldValue = oldValue;
}
public void actionPerformed(ActionEvent ae) {
Set<OInstance> instances = ontology.getOInstances();
ArrayList<String> validInstances = new ArrayList<String>();
for (OInstance instance : instances) {
if (property.isValidRange(instance)) {
validInstances.add(instance.getONodeID().toString());
}
}
ValuesSelectionAction vsa = new ValuesSelectionAction();
int choice = vsa.showGUI("New property value",
validInstances.toArray(new String[validInstances.size()]),
oldValue != null ?
new String[]{oldValue.getONodeID().toString()} : new String[]{},
false, MainFrame.getIcon("ontology-object-property"));
if (choice != JOptionPane.OK_OPTION) { return; }
if (oldValue != null) {
((OInstance)oResource).removeObjectPropertyValue(property, oldValue);
}
String[] selectedValues = vsa.getSelectedValues();
for(int i = 0; i < selectedValues.length; i++) {
OInstance byName = (OInstance)
Utils.getOResourceFromMap(ontology,selectedValues[i]);
if(byName == null) { continue; }
try {
((OInstance)oResource).addObjectPropertyValue(property, byName);
}
catch(InvalidValueException e) {
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"Incompatible value.\n" + e.getMessage());
return;
}
}
TreePath path = tree.getSelectionPath();
tree.setSelectionRow(0);
tree.setSelectionPath(path);
}
private OResource oResource;
private ObjectProperty property;
private OInstance oldValue;
}
protected void expandNode(JTree tree) {
for(int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
}
/**
* Enable-disable toolBar components
*/
private void enableDisableToolBarComponents() {
boolean allClasses = true;
boolean allProperties = true;
boolean allInstances = true;
for (DefaultMutableTreeNode node : selectedNodes) {
OResource res = ((OResourceNode) node.getUserObject()).getResource();
if (res instanceof OClass) {
allProperties = false;
allInstances = false;
} else if (res instanceof OInstance) {
allClasses = false;
allProperties = false;
} else {
allInstances = false;
allClasses = false;
}
}
if (selectedNodes.isEmpty()) {
topClass.setEnabled(false);
subClass.setEnabled(false);
instance.setEnabled(false);
annotationProperty.setEnabled(false);
datatypeProperty.setEnabled(false);
objectProperty.setEnabled(false);
symmetricProperty.setEnabled(false);
transitiveProperty.setEnabled(false);
delete.setEnabled(false);
restriction.setEnabled(false);
}
else if(allClasses) {
topClass.setEnabled(true);
subClass.setEnabled(true);
instance.setEnabled(true);
annotationProperty.setEnabled(true);
datatypeProperty.setEnabled(true);
objectProperty.setEnabled(true);
symmetricProperty.setEnabled(true);
transitiveProperty.setEnabled(true);
delete.setEnabled(true);
restriction.setEnabled(true);
}
else if(allInstances) {
topClass.setEnabled(true);
subClass.setEnabled(false);
instance.setEnabled(false);
annotationProperty.setEnabled(true);
datatypeProperty.setEnabled(false);
objectProperty.setEnabled(false);
symmetricProperty.setEnabled(false);
transitiveProperty.setEnabled(false);
delete.setEnabled(true);
restriction.setEnabled(false);
}
else if(allProperties) {
topClass.setEnabled(false);
subClass.setEnabled(false);
instance.setEnabled(false);
annotationProperty.setEnabled(true);
datatypeProperty.setEnabled(true);
objectProperty.setEnabled(true);
symmetricProperty.setEnabled(true);
transitiveProperty.setEnabled(true);
delete.setEnabled(true);
restriction.setEnabled(true);
}
else {
topClass.setEnabled(false);
subClass.setEnabled(false);
instance.setEnabled(false);
annotationProperty.setEnabled(true);
datatypeProperty.setEnabled(false);
objectProperty.setEnabled(false);
symmetricProperty.setEnabled(false);
transitiveProperty.setEnabled(false);
delete.setEnabled(true);
restriction.setEnabled(false);
}
}
/**
* Called when the target of this editor has changed
*/
protected void rebuildModel() {
rootNode.removeAllChildren();
propertyRootNode.removeAllChildren();
if(ontologyClassesURIs == null)
ontologyClassesURIs = new ArrayList<String>();
else ontologyClassesURIs.clear();
uri2TreeNodesListMap = new HashMap<String, ArrayList<DefaultMutableTreeNode>>();
reverseMap = new HashMap<DefaultMutableTreeNode, ONodeID>();
List<OResource> rootClasses = new ArrayList<OResource>(ontology
.getOClasses(true));
Collections.sort(rootClasses, itemComparator);
addChidrenRec(rootNode, rootClasses, itemComparator);
List<RDFProperty> props = new ArrayList<RDFProperty>(ontology
.getPropertyDefinitions());
List<RDFProperty> subList = new ArrayList<RDFProperty>();
for(int i = 0; i < props.size(); i++) {
RDFProperty prop = props.get(i);
if(prop instanceof AnnotationProperty) {
subList.add(prop);
continue;
}
Set<RDFProperty> set = prop.getSuperProperties(OConstants.Closure.DIRECT_CLOSURE);
if(set != null && !set.isEmpty()) {
continue;
}
else {
subList.add(prop);
}
}
Collections.sort(subList, itemComparator);
addPropertyChidrenRec(propertyRootNode, subList, itemComparator);
datatypePropertyAction.setOntologyClassesURIs(ontologyClassesURIs);
objectPropertyAction.setOntologyClassesURIs(ontologyClassesURIs);
symmetricPropertyAction.setOntologyClassesURIs(ontologyClassesURIs);
transitivePropertyAction.setOntologyClassesURIs(ontologyClassesURIs);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
treeModel.nodeStructureChanged(rootNode);
tree.setSelectionInterval(0, 0);
// expand the root
tree.expandPath(new TreePath(rootNode));
// expand the entire tree
for(int i = 0; i < tree.getRowCount(); i++)
tree.expandRow(i);
propertyTreeModel.nodeStructureChanged(propertyRootNode);
// expand the root
propertyTree.expandPath(new TreePath(propertyRootNode));
// expand the entire tree
for(int i = 0; i < propertyTree.getRowCount(); i++)
propertyTree.expandRow(i);
// detailsTableModel.fireTableDataChanged();
// propertyDetailsTableModel.fireTableDataChanged();
}
});
}
/**
* Adds the children nodes to a node using values from a list of
* classes and instances.
*
* @param parent the parent node.
* @param children the List<OResource> of children objects.
* @param comparator the Comparator used to sort the children.
*/
protected void addChidrenRec(DefaultMutableTreeNode parent,
List<OResource> children, Comparator<OResource> comparator) {
for(OResource aChild : children) {
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(
new OResourceNode(aChild));
parent.add(childNode);
// we maintain a map of ontology resources and their representing
// tree
// nodes
ArrayList<DefaultMutableTreeNode> list = uri2TreeNodesListMap.get(aChild
.getONodeID().toString());
if(list == null) {
list = new ArrayList<DefaultMutableTreeNode>();
uri2TreeNodesListMap.put(aChild.getONodeID().toString(), list);
}
list.add(childNode);
reverseMap.put(childNode, aChild.getONodeID());
if(aChild instanceof OClass) {
if(!ontologyClassesURIs.contains(aChild.getONodeID().toString()))
ontologyClassesURIs.add(aChild.getONodeID().toString());
childNode.setAllowsChildren(true);
// add all the subclasses
OClass aClass = (OClass)aChild;
List<OResource> childList = new ArrayList<OResource>(aClass
.getSubClasses(OConstants.Closure.DIRECT_CLOSURE));
Collections.sort(childList, comparator);
addChidrenRec(childNode, childList, comparator);
childList = new ArrayList<OResource>(ontology.getOInstances(aClass,
OConstants.Closure.DIRECT_CLOSURE));
Collections.sort(childList, comparator);
addChidrenRec(childNode, childList, comparator);
}
else if(aChild instanceof OInstance) {
childNode.setAllowsChildren(false);
}
tree.expandPath(new TreePath(childNode.getPath()));
}
}
/**
* Adds the children nodes to a node using values from a list of
* classes and instances.
*
* @param parent the parent node.
* @param children the lsit of children objects.
* @param comparator the Comparator used to sort the children.
*/
protected void addPropertyChidrenRec(DefaultMutableTreeNode parent,
List<RDFProperty> children, Comparator<OResource> comparator) {
for(RDFProperty aChild : children) {
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(
new OResourceNode(aChild));
parent.add(childNode);
// we maintain a map of ontology resources and their representing
// tree
// nodes
ArrayList<DefaultMutableTreeNode> list = uri2TreeNodesListMap.get(aChild
.getONodeID().toString());
if(list == null) {
list = new ArrayList<DefaultMutableTreeNode>();
uri2TreeNodesListMap.put(aChild.getONodeID().toString(), list);
}
list.add(childNode);
reverseMap.put(childNode, aChild.getONodeID());
if(aChild instanceof AnnotationProperty) {
childNode.setAllowsChildren(false);
}
else {
childNode.setAllowsChildren(true);
// add all the sub properties
List<RDFProperty> childList = new ArrayList<RDFProperty>(aChild
.getSubProperties(OConstants.Closure.DIRECT_CLOSURE));
Collections.sort(childList, comparator);
addPropertyChidrenRec(childNode, childList, comparator);
}
propertyTree.expandPath(new TreePath(childNode.getPath()));
}
}
public void processGateEvent(GateEvent e) {
// ignore
}
/**
* Update the class tree model. To call when a class is added.
*
* @param aClass class to add
*/
protected void classIsAdded(OClass aClass) {
// we first obtain its superClasses
Set<OClass> superClasses = aClass.getSuperClasses(OConstants.Closure.DIRECT_CLOSURE);
List<OResource> list = new ArrayList<OResource>();
list.add(aClass);
if(superClasses == null || superClasses.isEmpty()) {
// this is a root node
addChidrenRec(rootNode, list, itemComparator);
treeModel.nodeStructureChanged(rootNode);
}
else {
List<OClass> cs = new ArrayList<OClass>(superClasses);
Collections.sort(cs, itemComparator);
for(OClass c : cs) {
ArrayList<DefaultMutableTreeNode> superNodeList = uri2TreeNodesListMap
.get(c.getONodeID().toString());
if(superNodeList == null) {
// this is a result of two classes being created as a result
// of only one addition
// e.g. create a cardinality restriction and it will create a
// fictivenode as well
// so lets first add it
classIsAdded(c);
// no need to go any further, as refreshing the super node
// will automatically refresh the children nodes
continue;
}
for(int i = 0; i < superNodeList.size(); i++) {
DefaultMutableTreeNode node = superNodeList.get(i);
addChidrenRec(node, list, itemComparator);
treeModel.nodeStructureChanged(node);
}
}
}
}
/**
* Update the property tree model. To call when a property is added.
*
* @param p property to add
*/
protected void propertyIsAdded(RDFProperty p) {
// we first obtain its superProperty
if(p instanceof AnnotationProperty) {
List<RDFProperty> list = new ArrayList<RDFProperty>();
list.add(p);
addPropertyChidrenRec(propertyRootNode, list, itemComparator);
propertyTreeModel.nodeStructureChanged(propertyRootNode);
return;
}
Set<RDFProperty> superProperties = p
.getSuperProperties(OConstants.Closure.DIRECT_CLOSURE);
List<RDFProperty> list = new ArrayList<RDFProperty>();
list.add(p);
if(superProperties == null || superProperties.isEmpty()) {
// this is a root node
addPropertyChidrenRec(propertyRootNode, list, itemComparator);
propertyTreeModel.nodeStructureChanged(propertyRootNode);
}
else {
List<RDFProperty> sps = new ArrayList<RDFProperty>(superProperties);
Collections.sort(sps, itemComparator);
for(RDFProperty r : sps) {
ArrayList<DefaultMutableTreeNode> superNodeList = uri2TreeNodesListMap
.get(r.getONodeID().toString());
for(int i = 0; i < superNodeList.size(); i++) {
DefaultMutableTreeNode node = superNodeList.get(i);
addPropertyChidrenRec(node, list, itemComparator);
propertyTreeModel.nodeStructureChanged(node);
}
}
}
}
/**
* Update the class tree model. To call when an instance is added.
*
* @param anInstance instance to add
*/
protected void instanceIsAdded(OInstance anInstance) {
ArrayList<DefaultMutableTreeNode> newList = uri2TreeNodesListMap
.get(anInstance.getONodeID().toString());
if(newList != null) {
for(int i = 0; i < newList.size(); i++) {
DefaultMutableTreeNode node = newList.get(i);
removeFromMap(treeModel, node);
}
}
Set<OClass> superClasses = anInstance
.getOClasses(OConstants.Closure.DIRECT_CLOSURE);
List<OResource> list = new ArrayList<OResource>();
list.add(anInstance);
Iterator<OClass> iter = superClasses.iterator();
while(iter.hasNext()) {
OClass aClass = iter.next();
ArrayList<DefaultMutableTreeNode> superNodeList = uri2TreeNodesListMap
.get(aClass.getONodeID().toString());
for(int i = 0; i < superNodeList.size(); i++) {
DefaultMutableTreeNode node = superNodeList.get(i);
addChidrenRec(node, list, itemComparator);
treeModel.nodeStructureChanged(node);
}
}
}
private void removeFromMap(DefaultTreeModel model, DefaultMutableTreeNode node) {
if(!node.isLeaf()) {
Enumeration enumeration = node.children();
List children = new ArrayList();
while(enumeration.hasMoreElements()) {
children.add(enumeration.nextElement());
}
for(int i = 0; i < children.size(); i++) {
removeFromMap(model, (DefaultMutableTreeNode)children.get(i));
}
}
ONodeID rURI = reverseMap.get(node);
reverseMap.remove(node);
ArrayList<DefaultMutableTreeNode> list = uri2TreeNodesListMap.get(rURI
.toString());
list.remove(node);
if(list.isEmpty()) uri2TreeNodesListMap.remove(rURI.toString());
model.removeNodeFromParent(node);
}
/**
* Update the property tree model. To call when a subproperty is added.
*
* @param p subproperty to add
*/
protected void subPropertyIsAdded(RDFProperty p) {
ArrayList<DefaultMutableTreeNode> nodesList = uri2TreeNodesListMap.get(p
.getONodeID().toString());
// p is a property where the subProperty is added
// the property which is added as a subProperty might not have any
// super RDFProperty before
// so we first remove it from the propertyTree
Set<RDFProperty> props = p.getSubProperties(OConstants.Closure.DIRECT_CLOSURE);
List<RDFProperty> ps = new ArrayList<RDFProperty>(props);
Collections.sort(ps, itemComparator);
for(RDFProperty subP : ps) {
ArrayList<DefaultMutableTreeNode> subNodesList = uri2TreeNodesListMap
.get(subP.getONodeID().toString());
if(subNodesList != null) {
for(int i = 0; i < subNodesList.size(); i++) {
DefaultMutableTreeNode node = subNodesList.get(i);
removeFromMap(propertyTreeModel, node);
propertyTreeModel.nodeStructureChanged(node.getParent());
}
}
if(subNodesList != null && nodesList != null) {
// and each of this node needs to be added again
for(int i = 0; i < nodesList.size(); i++) {
DefaultMutableTreeNode superNode = nodesList.get(i);
List<RDFProperty> list = new ArrayList<RDFProperty>();
list.add(subP);
addPropertyChidrenRec(superNode, list, itemComparator);
propertyTreeModel.nodeStructureChanged(superNode);
}
}
}
}
/**
* Update the property tree model. To call when a subproperty is deleted.
*
* @param p subproperty to delete
*/
protected void subPropertyIsDeleted(RDFProperty p) {
ArrayList<DefaultMutableTreeNode> nodeList = uri2TreeNodesListMap.get(p
.getONodeID().toString());
if(nodeList == null || nodeList.isEmpty()) {
// this is already deleted
return;
}
// p is a property where the subProperty is deleted
// we don't know which property is deleted
// so we remove the property p from the tree and add it again
for(int i = 0; i < nodeList.size(); i++) {
DefaultMutableTreeNode node = nodeList.get(i);
removeFromMap(propertyTreeModel, node);
propertyTreeModel.nodeStructureChanged(node.getParent());
}
// now we need to add it again
Set<RDFProperty> superProperties = p
.getSuperProperties(OConstants.Closure.DIRECT_CLOSURE);
List<RDFProperty> list = new ArrayList<RDFProperty>();
list.add(p);
if(superProperties != null) {
List<RDFProperty> rps = new ArrayList<RDFProperty>(superProperties);
Collections.sort(rps, itemComparator);
for(RDFProperty superP : rps) {
nodeList = uri2TreeNodesListMap.get(superP.getONodeID().toString());
for(int i = 0; i < nodeList.size(); i++) {
DefaultMutableTreeNode superNode = nodeList.get(i);
addPropertyChidrenRec(superNode, list, itemComparator);
propertyTreeModel.nodeStructureChanged(superNode);
}
}
}
else {
addPropertyChidrenRec(propertyRootNode, list, itemComparator);
propertyTreeModel.nodeStructureChanged(propertyRootNode);
}
}
/**
* Update the class tree model. To call when a subclass is added.
*
* @param c subclass to add
*/
protected void subClassIsAdded(OClass c) {
ArrayList<DefaultMutableTreeNode> nodesList = uri2TreeNodesListMap.get(c
.getONodeID().toString());
// c is a class where the subClass is added
// the class which is added as a subClass might not have any
// super Class before
// so we first remove it from the tree
Set<OClass> classes = c.getSubClasses(OClass.Closure.DIRECT_CLOSURE);
List<OClass> cs = new ArrayList<OClass>(classes);
Collections.sort(cs, itemComparator);
for(OClass subC : cs) {
ArrayList<DefaultMutableTreeNode> subNodesList = uri2TreeNodesListMap
.get(subC.getONodeID().toString());
if(subNodesList != null) {
for(int i = 0; i < subNodesList.size(); i++) {
DefaultMutableTreeNode node = subNodesList.get(i);
removeFromMap(treeModel, node);
treeModel.nodeStructureChanged(node.getParent());
}
}
if(subNodesList != null && nodesList != null) {
// and each of this node needs to be added again
List<OResource> list = new ArrayList<OResource>();
list.add(subC);
for(int i = 0; i < nodesList.size(); i++) {
DefaultMutableTreeNode superNode = nodesList.get(i);
addChidrenRec(superNode, list, itemComparator);
treeModel.nodeStructureChanged(superNode);
}
}
}
}
/**
* Update the class tree model. To call when a subclass is deleted.
*
* @param c subclass to delete
*/
protected void subClassIsDeleted(OClass c) {
ArrayList<DefaultMutableTreeNode> nodeList = uri2TreeNodesListMap.get(c
.getONodeID().toString());
if(nodeList == null || nodeList.isEmpty()) {
// this is already deleted
return;
}
List<OResource> toAdd = new ArrayList<OResource>();
// c is a class whose subClass is deleted
// we don't know which class is deleted
// so we remove the class c from the tree and add it again
boolean firstTime = true;
for(int i = 0; i < nodeList.size(); i++) {
DefaultMutableTreeNode node = nodeList.get(i);
if(firstTime) {
OClass parentClass = (OClass)
Utils.getOResourceFromMap(this.ontology,reverseMap.get(node).toString());
firstTime = false;
// find out which class is deleted
Enumeration e = node.children();
if(e != null) {
while(e.hasMoreElements()) {
DefaultMutableTreeNode aNode = (DefaultMutableTreeNode)e
.nextElement();
ONodeID rURI = reverseMap.get(aNode);
// lets check with the ontology if this instance is still
// there
OResource res = Utils.getOResourceFromMap(this.ontology,rURI.toString());
if(res != null) {
// lets check if its parents is the current node
if(res instanceof OClass) {
if(((OClass)res).isSubClassOf(parentClass,
OConstants.Closure.DIRECT_CLOSURE)) {
// continue;
}
else {
// that's it this is the class which should be added
// at the top of tree
toAdd.add((OClass)res);
break;
}
}
}
}
}
}
removeFromMap(treeModel, node);
treeModel.nodeStructureChanged(node.getParent());
}
// now we need to add it again
Set<OClass> superClasses = c.getSuperClasses(OConstants.Closure.DIRECT_CLOSURE);
List<OResource> list = new ArrayList<OResource>();
list.add(c);
if(superClasses != null && !superClasses.isEmpty()) {
List<OClass> cs = new ArrayList<OClass>(superClasses);
Collections.sort(cs, itemComparator);
for(OClass superC : cs) {
nodeList = uri2TreeNodesListMap.get(superC.getONodeID().toString());
for(int i = 0; i < nodeList.size(); i++) {
DefaultMutableTreeNode superNode = nodeList.get(i);
addChidrenRec(superNode, list, itemComparator);
treeModel.nodeStructureChanged(superNode);
}
}
}
else {
addChidrenRec(rootNode, list, itemComparator);
treeModel.nodeStructureChanged(rootNode);
}
if(!toAdd.isEmpty()) {
addChidrenRec(rootNode, toAdd, itemComparator);
treeModel.nodeStructureChanged(rootNode);
}
}
public void resourcesRemoved(final Ontology ontology, final String[] resources) {
if(this.ontology != ontology) {
return;
}
// ok before we refresh our gui, lets find out the resource which
// was deleted originally from the
// gui. Deleting a resource results in deleting other resources as
// well. The last resource in the resources is the one which was
// asked from a user to delete.
String deletedResourceURI = resources[resources.length - 1];
DefaultMutableTreeNode aNode = uri2TreeNodesListMap.get(deletedResourceURI)
.get(0);
DefaultMutableTreeNode probableParentNode = null;
if(aNode.getParent() == null) {
OResource res = ((OResourceNode)aNode.getUserObject()).getResource();
if(res instanceof RDFProperty) {
probableParentNode = propertyRootNode;
}
else {
probableParentNode = rootNode;
}
}
else {
probableParentNode = (DefaultMutableTreeNode)aNode.getParent();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// first hide the tree
scroller.getViewport().setView(new JLabel("PLease wait, updating..."));
propertyScroller.getViewport().setView(
new JLabel("Please wait, updating..."));
// now update the tree
// we can use a normal thread here
Runnable treeUpdater = new Runnable() {
public void run() {
// this is not in the swing thread
// update the tree...
ontologyClassesURIs.removeAll(Arrays.asList(resources));
final HashSet<DefaultMutableTreeNode> nodesToRefresh = new HashSet<DefaultMutableTreeNode>();
for(int i = 0; i < resources.length; i++) {
ArrayList<DefaultMutableTreeNode> nodeList = uri2TreeNodesListMap
.get(resources[i]);
if(nodeList != null) {
for(int j = 0; j < nodeList.size(); j++) {
DefaultMutableTreeNode node = nodeList.get(j);
DefaultTreeModel modelToUse = ((OResourceNode)node
.getUserObject()).getResource() instanceof RDFProperty
? propertyTreeModel
: treeModel;
if(node.getParent() != null) {
nodesToRefresh
.add((DefaultMutableTreeNode)node.getParent());
} else if(modelToUse == treeModel) {
nodesToRefresh.add(rootNode);
} else {
nodesToRefresh.add(propertyRootNode);
}
removeFromMap(modelToUse, node);
modelToUse.nodeStructureChanged(node.getParent());
}
}
}
// now we need to show back the tree
// go back to the swing thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// show the tree again
scroller.getViewport().setView(tree);
propertyScroller.getViewport().setView(propertyTree);
// ask the tree to refresh
tree.invalidate();
propertyTree.invalidate();
for(DefaultMutableTreeNode parentNode : nodesToRefresh) {
if(!reverseMap.containsKey(parentNode) && parentNode != rootNode && parentNode != propertyRootNode) continue;
if(parentNode != rootNode && parentNode != propertyRootNode) {
OResource parentResource = ((OResourceNode)parentNode
.getUserObject()).getResource();
if(parentResource instanceof RDFProperty) {
List<RDFProperty> children = new ArrayList<RDFProperty>(
((RDFProperty)parentResource)
.getSubProperties(OConstants.Closure.DIRECT_CLOSURE));
Enumeration en = parentNode.children();
while(en.hasMoreElements()) {
DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)en
.nextElement();
String toCompare = ((OResourceNode)dmtn.getUserObject())
.getResource().getONodeID().toString();
List<OResource> delete = new ArrayList<OResource>();
for(OResource aRes : children) {
if(toCompare.equals(aRes.getONodeID().toString())) {
delete.add(aRes);
}
}
children.removeAll(delete);
}
addPropertyChidrenRec(parentNode, children,
itemComparator);
propertyTreeModel.nodeStructureChanged(parentNode);
propertyTree.setSelectionPath(new TreePath(parentNode
.getPath()));
}
else {
List<OResource> children = new ArrayList<OResource>(
((OClass)parentResource)
.getSubClasses(OConstants.Closure.DIRECT_CLOSURE));
children.addAll(ontology
.getOInstances((OClass)parentResource,
OConstants.Closure.DIRECT_CLOSURE));
Enumeration en = parentNode.children();
while(en.hasMoreElements()) {
DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)en
.nextElement();
String toCompare = ((OResourceNode)dmtn.getUserObject())
.getResource().getONodeID().toString();
List<OResource> delete = new ArrayList<OResource>();
for(OResource aRes : children) {
if(toCompare.equals(aRes.getONodeID().toString())) {
delete.add(aRes);
}
}
children.removeAll(delete);
}
addChidrenRec(parentNode, children, itemComparator);
treeModel.nodeStructureChanged(parentNode);
tree.setSelectionPath(new TreePath(parentNode.getPath()));
}
}
else if(parentNode == rootNode) {
if(tree.getRowCount() > 0) {
List<OResource> children = new ArrayList<OResource>(
ontology.getOClasses(true));
Enumeration en = parentNode.children();
while(en.hasMoreElements()) {
DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)en
.nextElement();
if(dmtn.getLevel() != 1) continue;
String toCompare = ((OResourceNode)dmtn.getUserObject())
.getResource().getONodeID().toString();
List<OResource> delete = new ArrayList<OResource>();
for(OResource aRes : children) {
if(toCompare.equals(aRes.getONodeID().toString())) {
delete.add(aRes);
}
}
children.removeAll(delete);
}
addChidrenRec(rootNode, children, itemComparator);
treeModel.nodeStructureChanged(rootNode);
tree.setSelectionRow(0);
}
}
else {
if(propertyTree.getRowCount() > 0) {
List<RDFProperty> props = new ArrayList<RDFProperty>(
ontology.getPropertyDefinitions());
List<RDFProperty> subList = new ArrayList<RDFProperty>();
for(int i = 0; i < props.size(); i++) {
RDFProperty prop = props.get(i);
if(prop instanceof AnnotationProperty) {
subList.add(prop);
continue;
}
Set<RDFProperty> set = prop
.getSuperProperties(OConstants.Closure.DIRECT_CLOSURE);
if(set != null && !set.isEmpty()) {
continue;
}
else {
subList.add(prop);
}
}
Collections.sort(subList, itemComparator);
Enumeration en = parentNode.children();
while(en.hasMoreElements()) {
DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)en
.nextElement();
if(dmtn.getLevel() != 1) continue;
String toCompare = ((OResourceNode)dmtn.getUserObject())
.getResource().getONodeID().toString();
List<OResource> delete = new ArrayList<OResource>();
for(OResource aRes : subList) {
if(toCompare.equals(aRes.getONodeID().toString())) {
delete.add(aRes);
}
}
subList.removeAll(delete);
}
addPropertyChidrenRec(propertyRootNode, subList,
itemComparator);
propertyTreeModel.nodeStructureChanged(propertyRootNode);
propertyTree.setSelectionRow(0);
}
}
}
}
});
}
};
treeUpdater.run();
}
});
}
public void resourceAdded(Ontology ontology, OResource resource) {
if(this.ontology != ontology) {
return;
}
boolean isItTree = true;
TreePath path = tree.getSelectionPath();
if(path == null) {
isItTree = false;
path = propertyTree.getSelectionPath();
}
if(resource instanceof OClass) {
classIsAdded((OClass)resource);
expandNode(tree);
}
else if(resource instanceof RDFProperty) {
propertyIsAdded((RDFProperty)resource);
expandNode(propertyTree);
}
else if(resource instanceof OInstance) {
instanceIsAdded((OInstance)resource);
expandNode(tree);
}
datatypePropertyAction.setOntologyClassesURIs(ontologyClassesURIs);
objectPropertyAction.setOntologyClassesURIs(ontologyClassesURIs);
symmetricPropertyAction.setOntologyClassesURIs(ontologyClassesURIs);
transitivePropertyAction.setOntologyClassesURIs(ontologyClassesURIs);
if(isItTree) {
DefaultMutableTreeNode aNode = uri2TreeNodesListMap.get(
resource.getONodeID().toString()).get(0);
tree.setSelectionPath(new TreePath(aNode.getPath()));
}
else {
DefaultMutableTreeNode aNode = uri2TreeNodesListMap.get(
resource.getONodeID().toString()).get(0);
propertyTree.setSelectionPath(new TreePath(aNode.getPath()));
}
return;
}
public void resourceRelationChanged(Ontology ontology, OResource resource1,
OResource resouce2, int eventType) {
this.ontologyModified(ontology, resource1, eventType);
}
public void resourcePropertyValueChanged(Ontology ontology,
OResource resource, RDFProperty property, Object value, int eventType) {
this.ontologyModified(ontology, resource, eventType);
}
/**
* This method is invoked from ontology whenever it is modified
*/
public void ontologyModified(Ontology ontology, OResource resource,
int eventType) {
if(this.ontology != ontology) {
return;
}
boolean isItTree = true;
TreePath path = tree.getSelectionPath();
if(path == null) {
isItTree = false;
path = propertyTree.getSelectionPath();
}
switch(eventType) {
case OConstants.SUB_PROPERTY_ADDED_EVENT:
subPropertyIsAdded((RDFProperty)resource);
break;
case OConstants.SUB_PROPERTY_REMOVED_EVENT:
subPropertyIsDeleted((RDFProperty)resource);
break;
case OConstants.SUB_CLASS_ADDED_EVENT:
subClassIsAdded((OClass)resource);
break;
case OConstants.SUB_CLASS_REMOVED_EVENT:
subClassIsDeleted((OClass)resource);
break;
}
switch(eventType) {
case OConstants.SUB_PROPERTY_ADDED_EVENT:
case OConstants.SUB_PROPERTY_REMOVED_EVENT:
expandNode(propertyTree);
break;
default:
expandNode(tree);
break;
}
datatypePropertyAction.setOntologyClassesURIs(ontologyClassesURIs);
objectPropertyAction.setOntologyClassesURIs(ontologyClassesURIs);
symmetricPropertyAction.setOntologyClassesURIs(ontologyClassesURIs);
transitivePropertyAction.setOntologyClassesURIs(ontologyClassesURIs);
if(isItTree) {
tree.setSelectionPath(path);
DefaultMutableTreeNode aNode = uri2TreeNodesListMap.get(
resource.getONodeID().toString()).get(0);
tree.setSelectionPath(new TreePath(aNode.getPath()));
}
else {
propertyTree.setSelectionPath(path);
DefaultMutableTreeNode aNode = uri2TreeNodesListMap.get(
resource.getONodeID().toString()).get(0);
propertyTree.setSelectionPath(new TreePath(aNode.getPath()));
}
}
/**
* This method is called whenever ontology is reset.
*
* @param ontology
*/
public void ontologyReset(Ontology ontology) {
if(this.ontology != ontology) {
return;
}
rebuildModel();
}
public void addTreeNodeSelectionListener(TreeNodeSelectionListener listener) {
this.listeners.add(listener);
}
public void removeTreeNodeSelectionListener(TreeNodeSelectionListener listener) {
this.listeners.remove(listener);
}
private void fireTreeNodeSelectionChanged(
ArrayList<DefaultMutableTreeNode> nodes) {
for(int i = 0; i < listeners.size(); i++) {
listeners.get(i).selectionChanged(nodes);
}
}
class DnDJTree extends JTree implements DragGestureListener,
DropTargetListener, DragSourceListener {
/** Variables needed for DnD */
private DragSource dragSource = null;
private DragSourceContext dragSourceContext = null;
private DefaultMutableTreeNode selectedNode = null;
private TreePath selectedTreePath = null;
/**
* Constructor
*
* @param model tree model
*/
public DnDJTree(TreeModel model) {
super(model);
dragSource = DragSource.getDefaultDragSource();
DragGestureRecognizer dgr = dragSource
.createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_MOVE, this);
DropTarget dropTarget = new DropTarget(this, this);
}
/** DragGestureListener interface method */
public void dragGestureRecognized(DragGestureEvent e) {
// Get the selected node
if(selectedNodes.isEmpty()) {
selectedNode = null;
selectedTreePath = null;
return;
}
selectedNode = selectedNodes.get(0);
selectedTreePath = new TreePath(selectedNode.getPath());
DefaultMutableTreeNode dragNode = selectedNode;
if(dragNode != null) {
// Get the Transferable Object
Transferable transferable = (Transferable)dragNode.getUserObject();
// Select the appropriate cursor;
Cursor cursor = DragSource.DefaultCopyNoDrop;
int action = e.getDragAction();
if(action == DnDConstants.ACTION_MOVE)
cursor = DragSource.DefaultMoveNoDrop;
// begin the drag
dragSource.startDrag(e, cursor, transferable, this);
}
}
/** DragSourceListener interface method */
public void dragDropEnd(DragSourceDropEvent dsde) {
}
/** DragSourceListener interface method */
public void dragEnter(DragSourceDragEvent dsde) {
}
/** DragSourceListener interface method */
public void dragOver(DragSourceDragEvent dsde) {
}
/** DragSourceListener interface method */
public void dropActionChanged(DragSourceDragEvent dsde) {
}
/** DragSourceListener interface method */
public void dragExit(DragSourceEvent dsde) {
}
/**
* DropTargetListener interface method - What we do when drag is
* released
*/
public void drop(DropTargetDropEvent e) {
/*
* Transferable tr = e.getTransferable();
*
* DefaultMutableTreeNode node =
* (DefaultMutableTreeNode)selectedTreePath
* .getLastPathComponent(); OResource source =
* ((OResourceNode)node.getUserObject()).getResource();
*
* if(source instanceof OInstance) { e.rejectDrop();
* SwingUtilities.invokeLater(new Runnable() { public void run() {
* JOptionPane.showMessageDialog(MainFrame.getInstance(),
* "Instances are not allowed to be moved!", "Error Dialog",
* JOptionPane.ERROR_MESSAGE); } }); return; } // now check if the
* class to be moved under the class is not a // super class of
* the later. // get new parent node Point loc = e.getLocation();
* TreePath destinationPath = getPathForLocation(loc.x, loc.y);
* if(destinationPath == null) { e.rejectDrop(); return; }
*
* OResource target =
* ((OResourceNode)((DefaultMutableTreeNode)destinationPath
* .getLastPathComponent()).getUserObject()).getResource();
*
* if(target instanceof OInstance) { e.rejectDrop();
* SwingUtilities.invokeLater(new Runnable() { public void run() {
* JOptionPane.showMessageDialog(MainFrame.getInstance(), "Invalid
* Operation!", "Error Dialog", JOptionPane.ERROR_MESSAGE); } });
* return; }
*
* if(source instanceof OClass && target instanceof OClass) {
* if(((OClass)target).isSubClassOf((OClass)source,
* OConstants.TRANSITIVE_CLOSURE)) { e.rejectDrop();
* SwingUtilities.invokeLater(new Runnable() { public void run() {
* JOptionPane.showMessageDialog(MainFrame.getInstance(), "A super
* class can not be set as a sub class!", "Error Dialog",
* JOptionPane.ERROR_MESSAGE); } }); return; } }
*
* if(source instanceof RDFProperty && target instanceof
* RDFProperty) {
* if(((RDFProperty)target).isSubPropertyOf((RDFProperty)source,
* OConstants.TRANSITIVE_CLOSURE)) { e.rejectDrop();
* SwingUtilities.invokeLater(new Runnable() { public void run() {
* JOptionPane.showMessageDialog(MainFrame.getInstance(), "A super
* property can not be set as a sub property!", "Error Dialog",
* JOptionPane.ERROR_MESSAGE); } });
*
* return; }
*
* if(source instanceof AnnotationProperty || target instanceof
* AnnotationProperty) { e.rejectDrop();
* SwingUtilities.invokeLater(new Runnable() { public void run() {
* JOptionPane .showMessageDialog( MainFrame.getInstance(),
* "Annotation Properties cannot be set as sub or super
* properties!", "Error Dialog", JOptionPane.ERROR_MESSAGE); } });
* return; } }
*
* if(!source.getClass().getName().equals(target.getClass().getName())) {
* e.rejectDrop(); SwingUtilities.invokeLater(new Runnable() {
* public void run() {
* JOptionPane.showMessageDialog(MainFrame.getInstance(), "Invalid
* Operation!", "Error Dialog", JOptionPane.ERROR_MESSAGE); } });
* return; }
*
* if(source instanceof OClass && target instanceof OClass) { //
* first find out the source's super classes OClass sc =
* (OClass)source; Set<OClass> superClasses = sc
* .getSuperClasses(OConstants.DIRECT_CLOSURE); // lets check if
* the
*
* for(OClass sClass : superClasses) { sClass.removeSubClass(sc); }
*
* ((OClass)target).addSubClass(sc);
*
* return; }
*
* if(source instanceof RDFProperty && target instanceof
* RDFProperty) { // first find out the source's super classes
* RDFProperty sp = (RDFProperty)source; Set<RDFProperty>
* superProps = sp .getSuperProperties(OConstants.DIRECT_CLOSURE);
*
* for(RDFProperty sProp : superProps) {
* sProp.removeSubProperty(sp); }
*
* ((RDFProperty)target).addSubProperty(sp);
*
* return; }
*
*/
int action = e.getDropAction();
e.rejectDrop();
e.getDropTargetContext().dropComplete(false);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane
.showMessageDialog(
MainFrame.getInstance(),
"This feature is being implemented and will be provided soon",
"Coming Soon!", JOptionPane.INFORMATION_MESSAGE);
}
});
} // end of method
/** DropTaregetListener interface method */
public void dragEnter(DropTargetDragEvent e) {
}
/** DropTaregetListener interface method */
public void dragExit(DropTargetEvent e) {
}
/** DropTaregetListener interface method */
public void dragOver(DropTargetDragEvent e) {
}
/** DropTaregetListener interface method */
public void dropActionChanged(DropTargetDragEvent e) {
}
} // end of DnDJTree
public void selectResourceInClassTree(final OResource resource) {
SwingUtilities.invokeLater(new Runnable() { public void run() {
tabbedPane.setSelectedComponent(scroller);
tree.setSelectionPath(new TreePath(uri2TreeNodesListMap.get(
resource.getONodeID().toString()).get(0).getPath()));
tree.scrollPathToVisible(tree.getSelectionPath());
}});
}
/**
* the ontology instance
*/
protected Ontology ontology;
/**
* Ontology Item Comparator
*/
protected OntologyItemComparator itemComparator;
/**
* The tree view.
*/
protected DnDJTree tree;
/**
* The property treeView
*/
protected DnDJTree propertyTree;
/**
* The mode, for the tree.
*/
protected DefaultTreeModel treeModel;
/**
* The property model, for the tree
*/
protected DefaultTreeModel propertyTreeModel;
/**
* The list view used to display item details
*/
protected JTable detailsTable;
protected JTable propertyDetailsTable;
protected DetailsTableModel detailsTableModel;
protected PropertyDetailsTableModel propertyDetailsTableModel;
/**
* The main split
*/
protected JSplitPane mainSplit;
/**
* The root node of the tree.
*/
protected DefaultMutableTreeNode rootNode;
/**
* The property root node of the tree
*/
protected DefaultMutableTreeNode propertyRootNode;
protected JScrollPane detailsTableScroller, propertyDetailsTableScroller;
/**
* ToolBar
*/
protected JToolBar toolBar;
protected JButton queryBtn;
protected JButton refreshOntologyBtn;
protected JButton topClass;
protected JButton subClass;
protected JButton restriction;
protected JButton instance;
protected JButton annotationProperty;
protected JButton datatypeProperty;
protected JButton objectProperty;
protected JButton symmetricProperty;
protected JButton transitiveProperty;
protected JButton delete;
protected JButton search;
protected ArrayList<DefaultMutableTreeNode> selectedNodes;
protected ArrayList<String> ontologyClassesURIs;
protected SearchAction searchAction;
protected TopClassAction topClassAction;
protected SubClassAction subClassAction;
protected InstanceAction instanceAction;
protected AnnotationPropertyAction annotationPropertyAction;
protected DatatypePropertyAction datatypePropertyAction;
protected ObjectPropertyAction objectPropertyAction;
protected SymmetricPropertyAction symmetricPropertyAction;
protected TransitivePropertyAction transitivePropertyAction;
protected DeleteOntologyResourceAction deleteOntoResourceAction;
protected RestrictionAction restrictionAction;
protected ArrayList<TreeNodeSelectionListener> listeners;
protected HashMap<String, ArrayList<DefaultMutableTreeNode>> uri2TreeNodesListMap;
protected HashMap<DefaultMutableTreeNode, ONodeID> reverseMap;
protected JScrollPane propertyScroller, scroller;
protected JTabbedPane tabbedPane;
}
| lgpl-3.0 |
ideaconsult/i5 | iuclid_6_4-io/src/main/java/eu/europa/echa/iuclid6/namespaces/endpoint_study_record_directobservationsclinicalcases/_6/ObjectFactory.java | 24144 |
package eu.europa.echa.iuclid6.namespaces.endpoint_study_record_directobservationsclinicalcases._6;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the eu.europa.echa.iuclid6.namespaces.endpoint_study_record_directobservationsclinicalcases._6 package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _ENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataUsedForMSDS_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/ENDPOINT_STUDY_RECORD-DirectObservationsClinicalCases/6.0", "UsedForMSDS");
private final static QName _ENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataUsedForClassification_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/ENDPOINT_STUDY_RECORD-DirectObservationsClinicalCases/6.0", "UsedForClassification");
private final static QName _ENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataRobustStudy_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/ENDPOINT_STUDY_RECORD-DirectObservationsClinicalCases/6.0", "RobustStudy");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: eu.europa.echa.iuclid6.namespaces.endpoint_study_record_directobservationsclinicalcases._6
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases createENDPOINTSTUDYRECORDDirectObservationsClinicalCases() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.OverallRemarksAttachments }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.OverallRemarksAttachments createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesOverallRemarksAttachments() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.OverallRemarksAttachments();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.OverallRemarksAttachments.AttachedBackgroundMaterial }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.OverallRemarksAttachments.AttachedBackgroundMaterial createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesOverallRemarksAttachmentsAttachedBackgroundMaterial() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.OverallRemarksAttachments.AttachedBackgroundMaterial();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.ResultsAndDiscussion }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.ResultsAndDiscussion createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesResultsAndDiscussion() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.ResultsAndDiscussion();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethods() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsMethod() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsGuidelines() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines.Entry }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines.Entry createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsGuidelinesEntry() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines.Entry();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.DataSource }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.DataSource createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesDataSource() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.DataSource();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeData() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.CrossReference }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.CrossReference createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataCrossReference() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.CrossReference();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.CrossReference.Entry }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.CrossReference.Entry createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataCrossReferenceEntry() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.CrossReference.Entry();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.AttachedJustification }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.AttachedJustification createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataAttachedJustification() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.AttachedJustification();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.AttachedJustification.Entry }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.AttachedJustification.Entry createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataAttachedJustificationEntry() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.AttachedJustification.Entry();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.DataProtection }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.DataProtection createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataDataProtection() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.DataProtection();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.ApplicantSummaryAndConclusion }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.ApplicantSummaryAndConclusion createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesApplicantSummaryAndConclusion() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.ApplicantSummaryAndConclusion();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.OverallRemarksAttachments.AttachedBackgroundMaterial.Entry }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.OverallRemarksAttachments.AttachedBackgroundMaterial.Entry createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesOverallRemarksAttachmentsAttachedBackgroundMaterialEntry() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.OverallRemarksAttachments.AttachedBackgroundMaterial.Entry();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.ResultsAndDiscussion.AnyOtherInformationOnResultsInclTables }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.ResultsAndDiscussion.AnyOtherInformationOnResultsInclTables createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesResultsAndDiscussionAnyOtherInformationOnResultsInclTables() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.ResultsAndDiscussion.AnyOtherInformationOnResultsInclTables();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.StudyType }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.StudyType createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsStudyType() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.StudyType();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.EndpointAddressed }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.EndpointAddressed createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsEndpointAddressed() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.EndpointAddressed();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.GLPComplianceStatement }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.GLPComplianceStatement createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsGLPComplianceStatement() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.GLPComplianceStatement();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.TestMaterials }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.TestMaterials createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsTestMaterials() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.TestMaterials();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.AnyOtherInformationOnMaterialsAndMethodsInclTables }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.AnyOtherInformationOnMaterialsAndMethodsInclTables createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsAnyOtherInformationOnMaterialsAndMethodsInclTables() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.AnyOtherInformationOnMaterialsAndMethodsInclTables();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.TypeOfPopulation }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.TypeOfPopulation createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsMethodTypeOfPopulation() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.TypeOfPopulation();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.EthicalApproval }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.EthicalApproval createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsMethodEthicalApproval() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.EthicalApproval();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.RouteOfExposure }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.RouteOfExposure createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsMethodRouteOfExposure() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.RouteOfExposure();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.ReasonOfExposure }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.ReasonOfExposure createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsMethodReasonOfExposure() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.ReasonOfExposure();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.ExposureAssessment }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.ExposureAssessment createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsMethodExposureAssessment() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Method.ExposureAssessment();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines.Entry.Qualifier }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines.Entry.Qualifier createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsGuidelinesEntryQualifier() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines.Entry.Qualifier();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines.Entry.Guideline }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines.Entry.Guideline createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsGuidelinesEntryGuideline() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines.Entry.Guideline();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines.Entry.Deviation }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines.Entry.Deviation createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesMaterialsAndMethodsGuidelinesEntryDeviation() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.MaterialsAndMethods.Guidelines.Entry.Deviation();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.DataSource.DataAccess }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.DataSource.DataAccess createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesDataSourceDataAccess() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.DataSource.DataAccess();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.DataSource.DataProtectionClaimed }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.DataSource.DataProtectionClaimed createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesDataSourceDataProtectionClaimed() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.DataSource.DataProtectionClaimed();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.Endpoint }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.Endpoint createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataEndpoint() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.Endpoint();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.StudyResultType }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.StudyResultType createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataStudyResultType() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.StudyResultType();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.PurposeFlag }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.PurposeFlag createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataPurposeFlag() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.PurposeFlag();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.Reliability }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.Reliability createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataReliability() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.Reliability();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.RationalReliability }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.RationalReliability createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataRationalReliability() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.RationalReliability();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.DataWaiving }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.DataWaiving createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataDataWaiving() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.DataWaiving();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.DataWaivingJustification }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.DataWaivingJustification createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataDataWaivingJustification() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.DataWaivingJustification();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.CrossReference.Entry.ReasonPurpose }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.CrossReference.Entry.ReasonPurpose createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataCrossReferenceEntryReasonPurpose() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.CrossReference.Entry.ReasonPurpose();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.AttachedJustification.Entry.ReasonPurpose }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.AttachedJustification.Entry.ReasonPurpose createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataAttachedJustificationEntryReasonPurpose() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.AttachedJustification.Entry.ReasonPurpose();
}
/**
* Create an instance of {@link ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.DataProtection.Legislation }
*
*/
public ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.DataProtection.Legislation createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataDataProtectionLegislation() {
return new ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.DataProtection.Legislation();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Boolean }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/ENDPOINT_STUDY_RECORD-DirectObservationsClinicalCases/6.0", name = "UsedForMSDS", scope = ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.class)
public JAXBElement<Boolean> createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataUsedForMSDS(Boolean value) {
return new JAXBElement<Boolean>(_ENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataUsedForMSDS_QNAME, Boolean.class, ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Boolean }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/ENDPOINT_STUDY_RECORD-DirectObservationsClinicalCases/6.0", name = "UsedForClassification", scope = ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.class)
public JAXBElement<Boolean> createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataUsedForClassification(Boolean value) {
return new JAXBElement<Boolean>(_ENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataUsedForClassification_QNAME, Boolean.class, ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Boolean }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/ENDPOINT_STUDY_RECORD-DirectObservationsClinicalCases/6.0", name = "RobustStudy", scope = ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.class)
public JAXBElement<Boolean> createENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataRobustStudy(Boolean value) {
return new JAXBElement<Boolean>(_ENDPOINTSTUDYRECORDDirectObservationsClinicalCasesAdministrativeDataRobustStudy_QNAME, Boolean.class, ENDPOINTSTUDYRECORDDirectObservationsClinicalCases.AdministrativeData.class, value);
}
}
| lgpl-3.0 |
OpenSoftwareSolutions/PDFReporter | pdfreporter-core/src/org/oss/pdfreporter/engine/base/JRBaseBox.java | 6916 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2011 Jaspersoft Corporation. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oss.pdfreporter.engine.base;
import java.io.Serializable;
import org.oss.pdfreporter.engine.JRBox;
import org.oss.pdfreporter.engine.JRConstants;
import org.oss.pdfreporter.engine.JRDefaultStyleProvider;
import org.oss.pdfreporter.engine.JRLineBox;
import org.oss.pdfreporter.engine.JRStyle;
import org.oss.pdfreporter.engine.util.JRPenUtil;
import org.oss.pdfreporter.geometry.IColor;
/**
* This is useful for drawing borders around text elements and images. Boxes can have borders and paddings, which can
* have different width and colour on each side of the element.
* @deprecated Replaced by {@link JRBaseLineBox}
* @author Teodor Danciu (teodord@users.sourceforge.net)
* @version $Id: JRBaseBox.java 5180 2012-03-29 13:23:12Z teodord $
*/
public class JRBaseBox implements JRBox, Serializable
{
/**
*
*/
private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;
protected JRLineBox lineBox;
/**
* @deprecated Replaced by {@link JRBaseLineBox#getDefaultStyleProvider()}
*/
public JRDefaultStyleProvider getDefaultStyleProvider()
{
return lineBox.getDefaultStyleProvider();
}
/**
* @deprecated Replaced by {@link JRBaseLineBox#getStyle()}
*/
public JRStyle getStyle()
{
return lineBox.getStyle();
}
/**
* @deprecated Replaced by {@link JRBaseLineBox#getStyleNameReference()}
*/
public String getStyleNameReference()
{
return lineBox.getStyleNameReference();
}
/**
* @deprecated Replaced by {@link JRLineBox#getPen()}
*/
public Byte getOwnBorder()
{
return JRPenUtil.getOwnPenFromLinePen(lineBox.getPen());
}
/**
* @deprecated Replaced by {@link JRLineBox#getPen()}
*/
public IColor getOwnBorderColor()
{
return lineBox.getPen().getOwnLineColor();
}
/**
* @deprecated Replaced by {@link JRLineBox#getOwnPadding()}
*/
public Integer getOwnPadding()
{
return lineBox.getOwnPadding();
}
/**
* @deprecated Replaced by {@link JRLineBox#getTopPen()}
*/
public Byte getOwnTopBorder()
{
return JRPenUtil.getOwnPenFromLinePen(lineBox.getTopPen());
}
/**
* @deprecated Replaced by {@link JRLineBox#getTopPen()}
*/
public IColor getOwnTopBorderColor()
{
return lineBox.getTopPen().getOwnLineColor();
}
/**
* @deprecated Replaced by {@link JRLineBox#getOwnTopPadding()}
*/
public Integer getOwnTopPadding()
{
return lineBox.getOwnTopPadding();
}
/**
* @deprecated Replaced by {@link JRLineBox#getLeftPen()}
*/
public Byte getOwnLeftBorder()
{
return JRPenUtil.getOwnPenFromLinePen(lineBox.getLeftPen());
}
/**
* @deprecated Replaced by {@link JRLineBox#getLeftPen()}
*/
public IColor getOwnLeftBorderColor()
{
return lineBox.getLeftPen().getOwnLineColor();
}
/**
* @deprecated Replaced by {@link JRLineBox#getOwnLeftPadding()}
*/
public Integer getOwnLeftPadding()
{
return lineBox.getOwnLeftPadding();
}
/**
* @deprecated Replaced by {@link JRLineBox#getBottomPen()}
*/
public Byte getOwnBottomBorder()
{
return JRPenUtil.getOwnPenFromLinePen(lineBox.getBottomPen());
}
/**
* @deprecated Replaced by {@link JRLineBox#getBottomPen()}
*/
public IColor getOwnBottomBorderColor()
{
return lineBox.getBottomPen().getOwnLineColor();
}
/**
* @deprecated Replaced by {@link JRLineBox#getOwnBottomPadding()}
*/
public Integer getOwnBottomPadding()
{
return lineBox.getOwnBottomPadding();
}
/**
* @deprecated Replaced by {@link JRLineBox#getRightPen()}
*/
public Byte getOwnRightBorder()
{
return JRPenUtil.getOwnPenFromLinePen(lineBox.getRightPen());
}
/**
* @deprecated Replaced by {@link JRLineBox#getRightPen()}
*/
public IColor getOwnRightBorderColor()
{
return lineBox.getRightPen().getOwnLineColor();
}
/**
* @deprecated Replaced by {@link JRLineBox#getOwnRightPadding()}
*/
public Integer getOwnRightPadding()
{
return lineBox.getOwnRightPadding();
}
//TODO: Daniel (19.4.2013) - Not needed, removed
// /*
// * These fields are only for serialization backward compatibility.
// */
// /**
// * @deprecated
// */
// private Byte border;
// /**
// * @deprecated
// */
// private Byte topBorder;
// /**
// * @deprecated
// */
// private Byte leftBorder;
// /**
// * @deprecated
// */
// private Byte bottomBorder;
// /**
// * @deprecated
// */
// private Byte rightBorder;
// /**
// * @deprecated
// */
// private IColor borderColor;
// /**
// * @deprecated
// */
// private IColor topBorderColor;
// /**
// * @deprecated
// */
// private IColor leftBorderColor;
// /**
// * @deprecated
// */
// private IColor bottomBorderColor;
// /**
// * @deprecated
// */
// private IColor rightBorderColor;
// /**
// * @deprecated
// */
// private Integer padding;
// /**
// * @deprecated
// */
// private Integer topPadding;
// /**
// * @deprecated
// */
// private Integer leftPadding;
// /**
// * @deprecated
// */
// private Integer bottomPadding;
// /**
// * @deprecated
// */
// private Integer rightPadding;
//
// private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
// {
// in.defaultReadObject();
//
// if (lineBox == null)
// {
// lineBox = new JRBaseLineBox(null);
// JRBoxUtil.setToBox(
// border,
// topBorder,
// leftBorder,
// bottomBorder,
// rightBorder,
// borderColor,
// topBorderColor,
// leftBorderColor,
// bottomBorderColor,
// rightBorderColor,
// padding,
// topPadding,
// leftPadding,
// bottomPadding,
// rightPadding,
// lineBox
// );
// border = null;
// topBorder = null;
// leftBorder = null;
// bottomBorder = null;
// rightBorder = null;
// borderColor = null;
// topBorderColor = null;
// leftBorderColor = null;
// bottomBorderColor = null;
// rightBorderColor = null;
// padding = null;
// topPadding = null;
// leftPadding = null;
// bottomPadding = null;
// rightPadding = null;
// }
// }
}
| lgpl-3.0 |
gmt-europe/gmtdata | gmtdata/src/main/java/nl/gmt/data/schema/SchemaParameter.java | 484 | package nl.gmt.data.schema;
public class SchemaParameter extends SchemaAnnotatableElement {
private String name;
private String value;
SchemaParameter(SchemaParserLocation location) {
super(location);
}
public String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
void setValue(String value) {
this.value = value;
}
}
| lgpl-3.0 |
avstaim/LightDI | src/test/java/com/staim/lightdi/test/TestClass3.java | 365 | package com.staim.lightdi.test;
import com.staim.lightdi.annotations.Inject;
@Inject
public class TestClass3 implements TestInterface3 {
@Inject private TestInterface1 t1;
@Inject private TestInterface2 t2;
@Override
public TestInterface1 t1() {
return t1;
}
@Override
public TestInterface2 t2() {
return t2;
}
}
| lgpl-3.0 |
fuinorg/srcgen4j-commons | src/main/java/org/fuin/srcgen4j/commons/ProjectNameNotDefinedException.java | 1818 | /**
* Copyright (C) 2015 Michael Schnell. All rights reserved.
* http://www.fuin.org/
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option) any
* later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see http://www.gnu.org/licenses/.
*/
package org.fuin.srcgen4j.commons;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* For a given generator/artifact/target was no project found in a generator configuration.
*/
public class ProjectNameNotDefinedException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Constructor with names.
*
* @param generatorName
* Name of the generator with the requested artifact - Should not be <code>null</code>.
* @param artifactName
* Name of the artifact with the request target - Should not be <code>null</code>.
* @param targetPattern
* Target pattern - Should not be <code>null</code>.
*/
public ProjectNameNotDefinedException(@Nullable final String generatorName, @Nullable final String artifactName,
@Nullable final String targetPattern) {
super("No project name is defined for: " + generatorName + " / " + artifactName + " / " + targetPattern);
}
}
| lgpl-3.0 |
Sleaker/Regional | src/com/herocraftonline/regional/flags/RegionFlagSet.java | 2417 | package com.herocraftonline.regional.flags;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.herocraftonline.regional.regions.CubeRegion;
import com.herocraftonline.regional.regions.Region;
import com.herocraftonline.regional.regions.WorldRegion;
/**
* Holds the data for resolving the flags currently at work on a region - this is used for
* determining a flag-value at any given point in-game
*
*/
public class RegionFlagSet implements Iterable<Region> {
final List<Region> regions;
final WorldRegion wRegion;
public RegionFlagSet(List<Region> regions, WorldRegion wRegion) {
this.regions = regions;
Collections.sort(this.regions);
this.wRegion = wRegion;
}
public void addRegion(CubeRegion cRegion) {
regions.add(cRegion);
}
public void removeRegion(CubeRegion cRegion) {
regions.remove(cRegion);
}
@Override
public Iterator<Region> iterator() {
return regions.iterator();
}
private <T> Object getRawFlag(Flag<T> flag) {
Object o = null;
Object def = DefaultFlags.getInstance().get(flag);
if (wRegion.getFlags().containsKey(flag))
def = wRegion.getFlags().get(flag);
Iterator<Region> iter = regions.iterator();
if (flag instanceof BooleanFlag) {
int lastWeight = Integer.MIN_VALUE;
boolean defined = false;
while(iter.hasNext()) {
Region region = iter.next();
if (defined && region.getWeight() < lastWeight)
break;
lastWeight = region.getWeight();
Boolean val = (Boolean) region.getFlag(flag);
if (val == false)
return false;
else if (val == null)
continue;
else
o = true;
}
} else {
while (iter.hasNext()) {
Region region = iter.next();
if (region.hasFlag(flag))
o = region.getFlag(flag);
}
}
return o == null ? def : o;
}
public boolean getFlag(BooleanFlag flag) {
return (Boolean) getRawFlag(flag);
}
public int getFlag(IntegerFlag flag) {
Integer i = (Integer) getRawFlag(flag);
return i != null ? i : -1;
}
public String getFlag(StringFlag flag) {
return (String) getRawFlag(flag);
}
public double getFlag(DoubleFlag flag) {
Double d = (Double) getRawFlag(flag);
return d != null ? d : -1;
}
public boolean getFlag(BuiltinFlag flag) {
return getFlag(new BooleanFlag(flag));
}
}
| lgpl-3.0 |
schuttek/nectar | src/main/java/org/nectarframework/base/service/sql/ResultTable.java | 13769 | package org.nectarframework.base.service.sql;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.nectarframework.base.service.Log;
import org.nectarframework.base.service.cache.CacheableObject;
import org.nectarframework.base.tools.BitMap;
import org.nectarframework.base.tools.ByteArray;
import org.nectarframework.base.tools.StringTools;
public class ResultTable implements CacheableObject, Iterable<ResultRow> {
private JavaTypes[] typesByColumn;
private HashMap<String, Integer> keyMap;
private Object[] table;
private int colCount;
private HashMap<String, HashMap<Long, ArrayList<ResultRow>>> searchMap = null;
/**
* estimated memory usage of this result table.
*/
private long memorySize = 0;
public ResultTable() {
}
protected ResultTable(JavaTypes[] typesByColumn, HashMap<String, Integer> keyMap, Object[] table, int colCount,
long memorySize) {
this.typesByColumn = typesByColumn;
this.keyMap = keyMap;
this.table = table;
this.colCount = colCount;
this.memorySize = memorySize;
}
public int colCount() {
return colCount;
}
public int rowCount() {
return this.table.length / colCount;
}
public String getString(int row, String column) throws SQLException {
return getString(row, lookupColumn(column));
}
public String getString(int row, int column) throws SQLException {
Object obj = table[row * colCount + column];
if (obj == null) {
return null;
}
if (obj instanceof String) {
return (String) obj;
}
throw new SQLException("Type mismatch. Column " + column + " is a " + obj.getClass().getName());
}
public Byte getByte(int row, String column) throws SQLException {
return getByte(row, lookupColumn(column));
}
public Byte getByte(int row, int column) throws SQLException {
Object obj = table[row * colCount + column];
if (obj == null) {
return null;
}
if (obj instanceof Byte) {
return (Byte) obj;
}
throw new SQLException("Type mismatch. Column " + column + " is a " + obj.getClass().getName());
}
public Short getShort(int row, String column) throws SQLException {
return getShort(row, lookupColumn(column));
}
public Short getShort(int row, int column) throws SQLException {
Object obj = table[row * colCount + column];
if (obj == null) {
return null;
}
if (obj instanceof Short) {
return (Short) obj;
}
throw new SQLException("Type mismatch. Column " + column + " is a " + obj.getClass().getName());
}
public Integer getInt(int row, String column) throws SQLException {
return getInt(row, lookupColumn(column));
}
public Integer getInt(int row, int column) throws SQLException {
Object obj = table[row * colCount + column];
if (obj == null) {
return null;
}
if (obj instanceof Integer) {
return (Integer) obj;
}
throw new SQLException("Type mismatch. Column " + column + " is a " + obj.getClass().getName());
}
public BigDecimal getBigDecimal(int row, String column) throws SQLException {
return getBigDecimal(row, lookupColumn(column));
}
public BigDecimal getBigDecimal(int row, int column) throws SQLException {
Object obj = table[row * colCount + column];
if (obj == null) {
return null;
}
if (obj instanceof BigDecimal) {
return (BigDecimal) obj;
}
throw new SQLException("Type mismatch. Column " + column + " is a " + obj.getClass().getName());
}
public Boolean getBoolean(int row, String column) throws SQLException {
return getBoolean(row, lookupColumn(column));
}
public Boolean getBoolean(int row, int column) throws SQLException {
Object obj = table[row * colCount + column];
if (obj == null) {
return null;
}
if (obj instanceof Boolean) {
return (Boolean) obj;
}
throw new SQLException("Type mismatch. Column " + column + " is a " + obj.getClass().getName());
}
public Long getLong(int row, String column) throws SQLException {
return getLong(row, lookupColumn(column));
}
public Long getLong(int row, int column) throws SQLException {
Object obj = table[row * colCount + column];
if (obj == null) {
return null;
}
if (obj instanceof Long) {
return (Long) obj;
}
throw new SQLException("Type mismatch column " + column + " is a " + obj.getClass().getName());
}
public Long getNumberAsLong(int row, int column) throws SQLException {
Object obj = table[row * colCount + column];
if (obj == null) {
return null;
}
if (obj instanceof Long) {
return (Long) obj;
}
if (obj instanceof Integer) {
return ((Integer) obj).longValue();
}
if (obj instanceof Short) {
return ((Short) obj).longValue();
}
if (obj instanceof Byte) {
return ((Byte) obj).longValue();
}
throw new SQLException("Type mismatch column " + column + " is a " + obj.getClass().getName());
}
public Float getFloat(int row, String column) throws SQLException {
return getFloat(row, lookupColumn(column));
}
public Float getFloat(int row, int column) throws SQLException {
Object obj = table[row * colCount + column];
if (obj == null) {
return null;
}
if (obj instanceof Float) {
return (Float) obj;
}
throw new SQLException("Type mismatch. Column " + column + " is a " + obj.getClass().getName());
}
public Double getDouble(int row, String column) throws SQLException {
return getDouble(row, lookupColumn(column));
}
public Double getDouble(int row, int column) throws SQLException {
Object obj = table[row * colCount + column];
if (obj == null) {
return null;
}
if (obj instanceof Double) {
return (Double) obj;
}
throw new SQLException("Type mismatch. Column " + column + " is a " + obj.getClass().getName());
}
public byte[] getBlob(int row, String column) throws SQLException {
return getBlob(row, lookupColumn(column));
}
public byte[] getBlob(int row, int column) throws SQLException {
Object obj = table[row * colCount + column];
if (obj == null) {
return null;
}
if (obj instanceof byte[]) {
return (byte[]) obj;
}
throw new SQLException("Type mismatch. Column " + column + " is a " + obj.getClass().getName());
}
public Object getObject(int row, String column) throws SQLException {
return getObject(row, lookupColumn(column));
}
private Object getObject(int row, int column) {
return table[row * colCount + column];
}
public boolean isNull(int row, String column) throws SQLException {
return isNull(row, lookupColumn(column));
}
public boolean isNull(int row, int column) {
return table[row * colCount + column] == null ? true : false;
}
/**
* Returns the first ResultRow of this table.
*
*/
public ResultRow iterator() {
ResultRow rr = new ResultRow(this);
return rr;
}
private Integer lookupColumn(String column) throws SQLException {
if (!keyMap.containsKey(column)) {
Log.trace("column " + column + " not found in " + StringTools.mapToString(keyMap));
throw new SQLException("Unknown column " + column);
}
return keyMap.get(column);
}
/**
* The names of the columns defined in this result table, in no particular
* order.
*
* @return
*/
public Set<String> getColumNames() {
return keyMap.keySet();
}
/**
* Returns a map indexed by the long values in the given column
*
* @param column
* @return
* @throws SQLException
*/
public HashMap<Long, ResultRow> mapByColumn(String column) throws SQLException {
HashMap<Long, ResultRow> map = new HashMap<Long, ResultRow>();
int colIdx = this.lookupColumn(column);
for (int rowIdx = 0; rowIdx < this.rowCount(); rowIdx++) {
map.put(this.getNumberAsLong(rowIdx, colIdx), new ResultRow(this, rowIdx));
}
return map;
}
/**
* Returns a list of rows where the given column is equal to the given
* match. The first call will build a HashMap in O(n) time, subsequent calls
* are O(1).
*
* Intended for joining the results of 2 queries programmatically.
*
* @param column
* @param match
* @return
* @throws SQLException
*/
public List<ResultRow> subList(String column, Long match) throws SQLException {
if (searchMap == null) {
searchMap = new HashMap<String, HashMap<Long, ArrayList<ResultRow>>>();
}
if (!searchMap.containsKey(column)) {
HashMap<Long, ArrayList<ResultRow>> matchMap = new HashMap<Long, ArrayList<ResultRow>>();
int colIdx = this.lookupColumn(column);
int rowCount = this.rowCount();
for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) {
Long cellValue = getLong(rowIdx, colIdx);
List<ResultRow> list = null;
if (matchMap.containsKey(cellValue)) {
list = matchMap.get(cellValue);
} else {
list = new ArrayList<ResultRow>();
}
list.add(new ResultRow(this, rowIdx));
}
searchMap.put(column, matchMap);
}
ArrayList<ResultRow> subList = searchMap.get(column).get(match);
if (subList == null) {
subList = new ArrayList<ResultRow>();
}
return subList;
}
public long estimateMemorySize() {
return memorySize;
}
public String debugString() throws SQLException {
String s = "";
for (String key : keyMap.keySet()) {
for (ResultRow rr : this) {
s += "> " + key + "=" + rr.getObject(key);
}
}
return s;
}
/**
* Appends the rows of rt2 to rt1, with the columns defined in rt1. rt2 must
* have all the same column names and types as rt1, in no specific order.
*
* @param rt1
* @param rt2
* @return a new ResultTable contains the rows of rt1 and rt2
* @throws SQLException
*/
public static ResultTable append(ResultTable rt1, ResultTable rt2) {
Set<String> rt2colNames = rt2.getColumNames();
for (String key : rt1.getColumNames()) {
if (!rt2colNames.contains(key)) {
throw new IllegalArgumentException("Second ResultTable is missing column " + key);
}
}
int retColCount = rt1.colCount();
Object[] retTable = new Object[retColCount * (rt1.rowCount() + rt2.rowCount())];
int tableIdx;
for (tableIdx = 0; tableIdx < rt1.table.length; tableIdx++) {
retTable[tableIdx] = rt1.table[tableIdx];
}
for (ResultRow rr : rt2) {
for (String key : rt1.getColumNames()) {
try {
retTable[tableIdx] = rr.getObject(key);
} catch (SQLException e) {
// can't happen, we checked at start.
}
tableIdx++;
}
}
ResultTable ret = new ResultTable(rt1.typesByColumn, rt1.keyMap, retTable, retColCount,
rt1.memorySize + rt1.memorySize);
return ret;
}
@Override
public ResultTable fromBytes(ByteArray ba) {
colCount = ba.getInt();
typesByColumn = new JavaTypes[colCount];
for (int t = 0; t < colCount; t++) {
typesByColumn[t] = JavaTypes.lookup(ba.getInt());
}
int keyMapSize = ba.getInt();
this.keyMap = new HashMap<>();
for (int t = 0; t < keyMapSize; t++) {
String k = ba.getString();
int v = ba.getInt();
keyMap.put(k, v);
}
this.table = new Object[ba.getInt()];
BitMap nullBitMap = new BitMap().fromBytes(ba);
for (int t = 0; t < table.length; t++) {
if (nullBitMap.is(t)) {
switch (typesByColumn[t % colCount]) {
case BigDecimal:
table[t] = new BigDecimal(ba.getString());
break;
case Blob:
table[t] = ba.getByteArray();
break;
case Boolean:
table[t] = new Boolean(ba.getByte() > 0 ? true : false);
break;
case Byte:
table[t] = new Byte(ba.getByte());
break;
case Double:
table[t] = new Double(ba.getDouble());
break;
case Float:
table[t] = new Float(ba.getFloat());
break;
case Int:
table[t] = new Integer(ba.getInt());
break;
case Long:
table[t] = new Long(ba.getLong());
break;
case Short:
table[t] = new Short(ba.getShort());
break;
case String:
table[t] = new String(ba.getString());
break;
case Unknown:
table[t] = null;
break;
}
}
}
return this;
}
@Override
public ByteArray toBytes(ByteArray ba) {
ba.add(this.colCount);
for (int t = 0; t < colCount; t++) {
ba.add(typesByColumn[t].getTypeId());
}
ba.add(keyMap.size());
for (String k : keyMap.keySet()) {
ba.add(k);
ba.add(keyMap.get(k));
}
ba.add(table.length);
// null bitmap
BitMap nullBitMap = new BitMap(table.length);
for (int t = 0; t < table.length; t++) {
if (table[t] == null) {
nullBitMap.set(t);
}
}
nullBitMap.toBytes(ba);
for (int t = 0; t < table.length; t++) {
if (table[t] != null) {
switch (typesByColumn[t % colCount]) {
case BigDecimal:
ba.add(((BigDecimal) table[t]).toString());
break;
case Blob:
ba.addByteArray((byte[]) table[t]);
break;
case Boolean:
ba.add((byte) ((Boolean) table[t] ? 1 : 0));
break;
case Byte:
ba.add(((Byte) table[t]).byteValue());
break;
case Double:
ba.add(((Double) table[t]).doubleValue());
break;
case Float:
ba.add(((Float) table[t]).floatValue());
break;
case Int:
ba.add(((Integer) table[t]).intValue());
break;
case Long:
ba.add(((Long) table[t]).longValue());
break;
case Short:
ba.add(((Short) table[t]).shortValue());
break;
case String:
ba.add((String) table[t]);
break;
case Unknown:
break;
}
}
}
return ba;
}
} | lgpl-3.0 |
sarndt/AbusingSwing | src/main/java/net/abusingjava/swing/magix/types/FilterMode.java | 540 | package net.abusingjava.swing.magix.types;
import net.abusingjava.Author;
import net.abusingjava.Since;
import net.abusingjava.Version;
@Author("Julian Fleischer")
@Version("2011-08-25")
@Since(value = "2011-08-25", version = "1.0")
public class FilterMode {
enum Mode {
AND, OR
}
final Mode $mode;
public FilterMode(final String $filter) {
$mode = ("or".equalsIgnoreCase($filter)) ? Mode.OR : Mode.AND;
}
public boolean isAnd() {
return $mode == Mode.AND;
}
public boolean isOr() {
return $mode == Mode.OR;
}
}
| lgpl-3.0 |
MastekLtd/JBEAM | jbeam-core-components/jbeam-core/src/main/java/com/stgmastek/core/dao/DaoFactory.java | 5905 | /*
* Copyright (c) 2014 Mastek Ltd. All rights reserved.
*
* This file is part of JBEAM. JBEAM 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.
*
* JBEAM 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 the specific language governing permissions and
* limitations.
*
* You should have received a copy of the GNU Lesser General Public
* License along with JBEAM. If not, see <http://www.gnu.org/licenses/>.
*/
package com.stgmastek.core.dao;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import com.stgmastek.core.exception.InvalidConfigurationException;
import com.stgmastek.core.util.Constants;
/**
* DaoFactory is responsible to provide the implementation of {@link IBatchDao} and {@link IAppDao}.
*
* Always get the appropriate DAO using one of its methods.
*
* @author Kedar Raybagkar
* @since
*/
public class DaoFactory {
private static final Logger logger = Logger.getLogger(DaoFactory.class);
private static final Lock latch = new ReentrantLock();
private static IAppDao appDao;
private static IBatchDao batchDao;
/**
* Returns the {@link IAppDao} implementation.
* This method uses the system property {@link com.stgmastek.core.util.Constants.SYSTEM_KEY#APP_DAO} to identify
* the implementation class. In case of any error during instantiation return the {@link AppDAO} as the
* default implementation.
*
* Once the class is instantiated then the same class is returned.
*
* @return {@link IAppDao}
*/
public static IAppDao getAppDao() {
if (appDao != null) return appDao;
return instantiateAppDao();
}
/**
* Returns the instance of IAppDao.
* @return IAppDao
*/
private static synchronized IAppDao instantiateAppDao() {
while (appDao == null) {
if (latch.tryLock()) {
try {
if (appDao == null) {
String className = System.getProperty(Constants.SYSTEM_KEY.APP_DAO.getKey(), null);
Object obj;
try {
obj = instantiateClass(className);
} catch (InvalidConfigurationException e) {
logger.fatal("Invalid Configuration", e);
throw e;
}
// if (obj == null) {
// appDao = new AppDAO();
// if (logger.isInfoEnabled()) {
// logger.info(Constants.SYSTEM_KEY.APP_DAO.toString());
// }
// } else {
if (obj instanceof IAppDao) {
appDao = (IAppDao) obj;
if (logger.isInfoEnabled()) {
logger.info("Using the class " + className + " for IAppDao");
}
return appDao;
} else {
logger.fatal(className + " does not implement IAppDao.");
throw new InvalidConfigurationException(className + " does not implement IAppDao.");
}
// }
}
} finally {
latch.unlock();
}
} // if tryLock()
} // While appDao is null
return appDao;
}
/**
* Returns the {@link IBatchDao} implementation.
* This method uses the system property {@link com.stgmastek.core.util.Constants.SYSTEM_KEY#BATCH_DAO} to identify
* the implementation class. In case of any error during instantiation return the {@link IBatchDao} as the
* default implementation.
*
* Once the class is instantiated then the same class is returned.
*
* @return {@link IBatchDao}
*/
public static IBatchDao getBatchDao() {
if (batchDao != null) return batchDao;
return instantiateBatchDao();
}
/**
* Returns the instance of IBatchDao.
* @return IBatchDao
*/
private static IBatchDao instantiateBatchDao() {
while (batchDao == null) {
if (latch.tryLock()) {
try {
if (batchDao == null) {
String className = System.getProperty(Constants.SYSTEM_KEY.BATCH_DAO.getKey(), null);
Object obj;
try {
obj = instantiateClass(className);
} catch (InvalidConfigurationException e) {
logger.fatal("Invalid Configuration", e);
throw e;
}
// if (obj == null) {
// batchDao = new BatchDAO();
// if (logger.isInfoEnabled()) {
// logger.info(Constants.SYSTEM_KEY.BATCH_DAO.toString());
// }
// } else {
if (obj instanceof IBatchDao) {
if (logger.isInfoEnabled()) {
logger.info("Using the class " + className + " for IBatchDao");
}
batchDao = (IBatchDao) obj;
} else {
logger.fatal(className + " does not implement IBatchDao.");
throw new InvalidConfigurationException(className + " does not implement IBatchDao interface");
}
// }
}
} finally {
latch.unlock();
}
}
}
return batchDao;
}
/**
* Protected method to instantiate the given class.
*
* @param className Class to be instantiated.
* @return Object
*/
static Object instantiateClass(String className) throws InvalidConfigurationException {
Object obj = null;
if (className != null) {
try {
Class<?> implClass = Class.forName(className);
obj = implClass.newInstance();
} catch (ClassNotFoundException e) {
throw new InvalidConfigurationException(className + " could not be instantiated. Invalid Configuration", e);
} catch (InstantiationException e) {
throw new InvalidConfigurationException(className + " could not be instantiated. Invalid Configuration", e);
} catch (IllegalAccessException e) {
throw new InvalidConfigurationException(className + " could not be instantiated. Invalid Configuration", e);
}
}
return obj;
}
}
| lgpl-3.0 |
joansmith/sonarqube | sonar-plugin-api/src/main/java/org/sonar/api/component/RubyComponentService.java | 1089 | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.component;
import org.sonar.api.server.ServerSide;
import javax.annotation.CheckForNull;
/**
* @since 3.6
*/
@ServerSide
public interface RubyComponentService {
@CheckForNull
Component findByKey(String key);
}
| lgpl-3.0 |
fustinoni-net/robot | src/net/fustinoni/raspberryPi/robot/robotUtils/MotorsDrivers/CommandLine/CommandLineMotorDriverImpl.java | 2259 | /**
*
* **********************************************************************
* This file is part of the PI2GO java library project.
*
* More information about this project can be found here:
* http://robots.fustinoni.net
* **********************************************************************
*
* Copyright (C) 2015 Enrico Fustinoni
*
* 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 General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
*
**/
package net.fustinoni.raspberryPi.robot.robotUtils.MotorsDrivers.CommandLine;
import net.fustinoni.raspberryPi.robot.robotUtils.MotorsDrivers.MotorsDriver;
/**
*
* @author efustinoni
*/
public class CommandLineMotorDriverImpl implements CommandLineMotorDriver {
final MotorsDriver motors;
public CommandLineMotorDriverImpl(final MotorsDriver motors) {
this.motors = motors;
}
@Override
public void stopMotors() {
motors.stopMotors();
}
@Override
public void moveForward (int speed){
motors.setMotorsSpeeds(speed, speed);
}
@Override
public void moveBackward (int speed){
motors.setMotorsSpeeds(-speed, -speed);
}
@Override
public void spinRight (int speed){
motors.setMotorsSpeeds(speed, -speed);
}
@Override
public void spinLeft (int speed){
motors.setMotorsSpeeds(-speed, speed);
}
@Override
public void moveLeft (int speed, int angle){
motors.setMotorsSpeeds(speed - speed * angle/100, speed);
}
@Override
public void moveRight (int speed, int angle){
motors.setMotorsSpeeds(speed, speed - speed * angle/100);
}
}
| lgpl-3.0 |
enhancedportals/enhancedportals | src/main/java/enhanced/portals/block/BlockDecorBorderedQuartz.java | 1159 | package enhanced.portals.block;
import enhanced.base.block.BlockBase;
import enhanced.base.utilities.ConnectedTexturesDetailed;
import enhanced.portals.EnhancedPortals;
import enhanced.portals.Reference.EPMod;
import enhanced.portals.portal.frame.BlockFrame;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
public class BlockDecorBorderedQuartz extends BlockBase {
ConnectedTexturesDetailed connectedTextures;
public BlockDecorBorderedQuartz(String n) {
super(EPMod.ID, n, Material.rock, EnhancedPortals.instance.creativeTab, 3f);
connectedTextures = new ConnectedTexturesDetailed(BlockFrame.connectedTextures, this, -1);
}
@Override
public IIcon getIcon(IBlockAccess blockAccess, int x, int y, int z, int f) {
return connectedTextures.getIconForSide(blockAccess, x, y, z, f);
}
@Override
public IIcon getIcon(int side, int meta) {
return connectedTextures.getBaseIcon();
}
@Override
public void registerBlockIcons(IIconRegister iir) {
}
}
| lgpl-3.0 |
hea3ven/BuildCraft | common/buildcraft/core/lib/inventory/InventoryMapper.java | 3211 | /**
* Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.core.lib.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
/**
* Wrapper class used to specify part of an existing inventory to be treated as
* a complete inventory. Used primarily to map a side of an ISidedInventory, but
* it is also helpful for complex inventories such as the Tunnel Bore.
*/
public class InventoryMapper implements IInventory {
private final IInventory inv;
private final int start;
private final int size;
private int stackSizeLimit = -1;
private boolean checkItems = true;
/**
* Creates a new InventoryMapper
*
* @param inv The backing inventory
* @param start The starting index
* @param size The size of the new inventory, take care not to exceed the
* end of the backing inventory
*/
public InventoryMapper(IInventory inv, int start, int size) {
this(inv, start, size, true);
}
public InventoryMapper(IInventory inv, int start, int size, boolean checkItems) {
this.inv = inv;
this.start = start;
this.size = size;
this.checkItems = checkItems;
}
public IInventory getBaseInventory() {
return inv;
}
@Override
public int getSizeInventory() {
return size;
}
@Override
public ItemStack getStackInSlot(int slot) {
return inv.getStackInSlot(start + slot);
}
@Override
public ItemStack decrStackSize(int slot, int amount) {
return inv.decrStackSize(start + slot, amount);
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemstack) {
inv.setInventorySlotContents(start + slot, itemstack);
}
@Override
public String getInventoryName() {
return inv.getInventoryName();
}
public void setStackSizeLimit(int limit) {
stackSizeLimit = limit;
}
@Override
public int getInventoryStackLimit() {
return stackSizeLimit > 0 ? stackSizeLimit : inv.getInventoryStackLimit();
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer) {
return inv.isUseableByPlayer(entityplayer);
}
@Override
public void openInventory() {
inv.openInventory();
}
@Override
public void closeInventory() {
inv.closeInventory();
}
@Override
public ItemStack getStackInSlotOnClosing(int slot) {
return inv.getStackInSlotOnClosing(start + slot);
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack stack) {
if (checkItems) {
return inv.isItemValidForSlot(start + slot, stack);
}
return true;
}
@Override
public boolean hasCustomInventoryName() {
return inv.hasCustomInventoryName();
}
@Override
public void markDirty() {
inv.markDirty();
}
}
| lgpl-3.0 |
openbase/jul | pattern/default/src/main/java/org/openbase/jul/pattern/Filter.java | 1512 | package org.openbase.jul.pattern;
/*-
* #%L
* JUL Pattern Default
* %%
* Copyright (C) 2015 - 2022 openbase.org
* %%
* 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 General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
/**
* Filter which decides for a list of objects which to keep and which to filter out.
*
* @param <T> the type of object on which the filter works
* @author <a href="mailto:thuxohl@techfak.uni-bielefeld.de">Tamino Huxohl</a>
*/
public interface Filter<T> {
/**
* Check if the type passes the filter.
*
* @param type the object which is checked.
* @return true if the item passes the filter.
*/
default boolean pass(T type) {
return !match(type);
}
/**
* Check if the type matches the filter.
*
* @param type the object which is checked.
* @return true if this item is filtered.
*/
boolean match(T type);
}
| lgpl-3.0 |
teamrupps/lifecycle_helper | src/main/java/com/alexbat98/lifecyclehelper/utils/PoolObjectFactory.java | 409 | package com.alexbat98.lifecyclehelper.utils;
/**
* Interface that has to be implemented by every class that allows
* the creation of objectes for an object pool through the
* ObjectPool class.
*/
public interface PoolObjectFactory
{
/**
* Creates a new object for the object pool.
*
* @return new object instance for the object pool
*/
public PoolObject createPoolObject();
}
| lgpl-3.0 |
Wehavecookies56/Kingdom-Keys-Re-Coded | src/main/java/uk/co/wehavecookies56/kk/client/model/mobs/ModelWhiteMushroom.java | 3365 | package uk.co.wehavecookies56.kk.client.model.mobs;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
/**
* HeartlessLargeBody - WYND Created using Tabula 7.0.0
*/
public class ModelWhiteMushroom extends ModelBase
{
public ModelRenderer body;
public ModelRenderer cloth1;
public ModelRenderer head;
public ModelRenderer cloth2;
public ModelRenderer leftArm;
public ModelRenderer rightArm;
public ModelRenderer hat;
public ModelRenderer hat2;
public ModelRenderer hat3;
public ModelRenderer hat4;
public ModelRenderer hat5;
public ModelRenderer hat6;
public ModelWhiteMushroom()
{
this.textureWidth = 64;
this.textureHeight = 64;
this.hat5 = new ModelRenderer(this, 30, 1);
this.hat5.setRotationPoint(0.0F, 0.0F, 0.0F);
this.hat5.addBox(-4.0F, -18.5F, -5.0F, 8, 5, 1, 0.0F);
this.body = new ModelRenderer(this, 0, 0);
this.body.setRotationPoint(0.0F, 15.0F, 0.0F);
this.body.addBox(-4.0F, -8.0F, -4.0F, 8, 17, 8, 0.0F);
this.cloth2 = new ModelRenderer(this, 28, 46);
this.cloth2.setRotationPoint(0.0F, 0.0F, 0.0F);
this.cloth2.addBox(-4.5F, -8.0F, -4.5F, 9, 2, 9, 0.0F);
this.rightArm = new ModelRenderer(this, 34, 10);
this.rightArm.setRotationPoint(-4.5F, -7.0F, 0.5F);
this.rightArm.addBox(-1.5F, 0.0F, -1.5F, 2, 9, 3, 0.0F);
this.cloth1 = new ModelRenderer(this, 24, 25);
this.cloth1.setRotationPoint(0.0F, 0.0F, 0.0F);
this.cloth1.addBox(-5.0F, 5.0F, -5.0F, 10, 4, 10, 0.0F);
this.hat4 = new ModelRenderer(this, 4, 55);
this.hat4.setRotationPoint(0.0F, 0.0F, 0.0F);
this.hat4.addBox(-4.0F, -19.5F, -4.0F, 8, 1, 8, 0.0F);
this.hat = new ModelRenderer(this, 0, 48);
this.hat.setRotationPoint(0.0F, 0.0F, 0.0F);
this.hat.addBox(-4.5F, -19.0F, -4.5F, 9, 6, 9, 0.0F);
this.hat6 = new ModelRenderer(this, 17, 57);
this.hat6.setRotationPoint(0.0F, 0.0F, 0.0F);
this.hat6.addBox(-4.0F, -18.5F, 4.0F, 8, 5, 1, 0.0F);
this.hat2 = new ModelRenderer(this, 15, 50);
this.hat2.setRotationPoint(0.0F, 0.0F, 0.0F);
this.hat2.addBox(-5.0F, -18.5F, -4.0F, 1, 5, 8, 0.0F);
this.hat3 = new ModelRenderer(this, 16, 50);
this.hat3.setRotationPoint(0.0F, 0.0F, 0.0F);
this.hat3.addBox(4.0F, -18.5F, -4.0F, 1, 5, 8, 0.0F);
this.leftArm = new ModelRenderer(this, 34, 10);
this.leftArm.setRotationPoint(4.0F, -7.0F, 0.5F);
this.leftArm.addBox(0.0F, 0.0F, -1.5F, 2, 9, 3, 0.0F);
this.head = new ModelRenderer(this, 0, 34);
this.head.setRotationPoint(0.0F, 0.0F, 0.0F);
this.head.addBox(-3.5F, -13.0F, -3.5F, 7, 5, 7, 0.0F);
this.hat.addChild(this.hat5);
this.body.addChild(this.cloth2);
this.body.addChild(this.rightArm);
this.body.addChild(this.cloth1);
this.hat.addChild(this.hat4);
this.head.addChild(this.hat);
this.hat.addChild(this.hat6);
this.hat.addChild(this.hat2);
this.hat.addChild(this.hat3);
this.body.addChild(this.leftArm);
this.body.addChild(this.head);
}
@Override
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5)
{
this.body.render(f5);
}
/**
* This is a helper function from Tabula to set the rotation of model parts
*/
public void setRotateAngle(ModelRenderer modelRenderer, float x, float y, float z)
{
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
}
| lgpl-3.0 |
Godin/sonar | sonar-ws/src/main/java/org/sonarqube/ws/client/usertokens/package-info.java | 1043 | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
@Generated("sonar-ws-generator")
package org.sonarqube.ws.client.usertokens;
import javax.annotation.ParametersAreNonnullByDefault;
import javax.annotation.Generated;
| lgpl-3.0 |
webmotion-framework/webmotion-netbeans | src/org/debux/webmotion/netbeans/javacc/parser/WebMotionParser.java | 40462 | /*
* #%L
* WebMotion plugin netbeans
*
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2012 Debux
* %%
* 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 General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
/* Generated By:JavaCC: Do not edit this line. WebMotionParser.java */
package org.debux.webmotion.netbeans.javacc.parser;
import java.util.*;
public class WebMotionParser implements WebMotionParserConstants {
public static Map<String, String> configurations = new HashMap<String, String>();
public List<ParseException> syntaxErrors = new ArrayList<ParseException>();
void recover(ParseException ex, int ... recoveryPoints) {
syntaxErrors.add(ex);
Token t;
do {
t = getNextToken();
} while(t.kind != EOF && testRecoveryPoint(t.kind, recoveryPoints));
}
boolean testRecoveryPoint(int recoveryPoint, int ... recoveryPoints) {
for (int test : recoveryPoints) {
if (test == recoveryPoint) {
return true;
}
}
return false;
}
final public void Mapping() throws ParseException {
try {
label_1:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case COMMENT:
case SECTION_CONFIG_NAME:
case SECTION_ACTIONS_NAME:
case SECTION_ERRORS_NAME:
case SECTION_FILTERS_NAME:
case SECTION_EXTENSIONS_NAME:
case SECTION_PROPERTIES_NAME:
case SECTION_CONFIG_NEXT_CONFIG:
case SECTION_CONFIG_NEXT_ACTIONS:
case SECTION_CONFIG_NEXT_ERRORS:
case SECTION_CONFIG_NEXT_FILTERS:
case SECTION_CONFIG_NEXT_EXTENSIONS:
case SECTION_CONFIG_NEXT_PROPERTIES:
case SECTION_ACTIONS_NEXT_CONFIG:
case SECTION_ACTIONS_NEXT_ACTIONS:
case SECTION_ACTIONS_NEXT_ERRORS:
case SECTION_ACTIONS_NEXT_FILTERS:
case SECTION_ACTIONS_NEXT_EXTENSIONS:
case SECTION_ACTIONS_NEXT_PROPERTIES:
case SECTION_ERRORS_NEXT_CONFIG:
case SECTION_ERRORS_NEXT_ACTIONS:
case SECTION_ERRORS_NEXT_ERRORS:
case SECTION_ERRORS_NEXT_FILTERS:
case SECTION_ERRORS_NEXT_EXTENSIONS:
case SECTION_ERRORS_NEXT_PROPERTIES:
case SECTION_FILTERS_NEXT_CONFIG:
case SECTION_FILTERS_NEXT_ACTIONS:
case SECTION_FILTERS_NEXT_ERRORS:
case SECTION_FILTERS_NEXT_FILTERS:
case SECTION_FILTERS_NEXT_EXTENSIONS:
case SECTION_FILTERS_NEXT_PROPERTIES:
case SECTION_EXTENSIONS_NEXT_CONFIG:
case SECTION_EXTENSIONS_NEXT_ACTIONS:
case SECTION_EXTENSIONS_NEXT_ERRORS:
case SECTION_EXTENSIONS_NEXT_FILTERS:
case SECTION_EXTENSIONS_NEXT_EXTENSIONS:
case SECTION_EXTENSIONS_NEXT_PROPERTIES:
case SECTION_PROPERTIES_NEXT_CONFIG:
case SECTION_PROPERTIES_NEXT_ACTIONS:
case SECTION_PROPERTIES_NEXT_ERRORS:
case SECTION_PROPERTIES_NEXT_FILTERS:
case SECTION_PROPERTIES_NEXT_EXTENSIONS:
case SECTION_PROPERTIES_NEXT_PROPERTIES:
;
break;
default:
jj_la1[0] = jj_gen;
break label_1;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SECTION_CONFIG_NAME:
case SECTION_CONFIG_NEXT_CONFIG:
case SECTION_ACTIONS_NEXT_CONFIG:
case SECTION_ERRORS_NEXT_CONFIG:
case SECTION_FILTERS_NEXT_CONFIG:
case SECTION_EXTENSIONS_NEXT_CONFIG:
case SECTION_PROPERTIES_NEXT_CONFIG:
SectionConfig();
break;
case SECTION_ACTIONS_NAME:
case SECTION_CONFIG_NEXT_ACTIONS:
case SECTION_ACTIONS_NEXT_ACTIONS:
case SECTION_ERRORS_NEXT_ACTIONS:
case SECTION_FILTERS_NEXT_ACTIONS:
case SECTION_EXTENSIONS_NEXT_ACTIONS:
case SECTION_PROPERTIES_NEXT_ACTIONS:
SectionActions();
break;
case SECTION_ERRORS_NAME:
case SECTION_CONFIG_NEXT_ERRORS:
case SECTION_ACTIONS_NEXT_ERRORS:
case SECTION_ERRORS_NEXT_ERRORS:
case SECTION_FILTERS_NEXT_ERRORS:
case SECTION_EXTENSIONS_NEXT_ERRORS:
case SECTION_PROPERTIES_NEXT_ERRORS:
SectionErrors();
break;
case SECTION_FILTERS_NAME:
case SECTION_CONFIG_NEXT_FILTERS:
case SECTION_ACTIONS_NEXT_FILTERS:
case SECTION_ERRORS_NEXT_FILTERS:
case SECTION_FILTERS_NEXT_FILTERS:
case SECTION_EXTENSIONS_NEXT_FILTERS:
case SECTION_PROPERTIES_NEXT_FILTERS:
SectionFilters();
break;
case SECTION_EXTENSIONS_NAME:
case SECTION_CONFIG_NEXT_EXTENSIONS:
case SECTION_ACTIONS_NEXT_EXTENSIONS:
case SECTION_ERRORS_NEXT_EXTENSIONS:
case SECTION_FILTERS_NEXT_EXTENSIONS:
case SECTION_EXTENSIONS_NEXT_EXTENSIONS:
case SECTION_PROPERTIES_NEXT_EXTENSIONS:
SectionExtensions();
break;
case SECTION_PROPERTIES_NAME:
case SECTION_CONFIG_NEXT_PROPERTIES:
case SECTION_ACTIONS_NEXT_PROPERTIES:
case SECTION_ERRORS_NEXT_PROPERTIES:
case SECTION_FILTERS_NEXT_PROPERTIES:
case SECTION_EXTENSIONS_NEXT_PROPERTIES:
case SECTION_PROPERTIES_NEXT_PROPERTIES:
SectionProperties();
break;
case COMMENT:
jj_consume_token(COMMENT);
break;
default:
jj_la1[1] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
jj_consume_token(0);
} catch (ParseException ex) {
recover(ex, EOF);
}
}
final public void SectionConfig() throws ParseException {
SectionConfigName();
label_2:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case COMMENT_IN_CONFIG:
case CONFIG_KEY:
;
break;
default:
jj_la1[2] = jj_gen;
break label_2;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case CONFIG_KEY:
SectionConfigLine();
break;
case COMMENT_IN_CONFIG:
jj_consume_token(COMMENT_IN_CONFIG);
break;
default:
jj_la1[3] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
}
final public void SectionConfigName() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SECTION_CONFIG_NAME:
jj_consume_token(SECTION_CONFIG_NAME);
break;
case SECTION_CONFIG_NEXT_CONFIG:
jj_consume_token(SECTION_CONFIG_NEXT_CONFIG);
break;
case SECTION_ACTIONS_NEXT_CONFIG:
jj_consume_token(SECTION_ACTIONS_NEXT_CONFIG);
break;
case SECTION_ERRORS_NEXT_CONFIG:
jj_consume_token(SECTION_ERRORS_NEXT_CONFIG);
break;
case SECTION_FILTERS_NEXT_CONFIG:
jj_consume_token(SECTION_FILTERS_NEXT_CONFIG);
break;
case SECTION_EXTENSIONS_NEXT_CONFIG:
jj_consume_token(SECTION_EXTENSIONS_NEXT_CONFIG);
break;
case SECTION_PROPERTIES_NEXT_CONFIG:
jj_consume_token(SECTION_PROPERTIES_NEXT_CONFIG);
break;
default:
jj_la1[4] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
final public void SectionConfigLine() throws ParseException {
Token k = null;
Token v = null;
try {
k = jj_consume_token(CONFIG_KEY);
jj_consume_token(CONFIG_EQUALS);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case CONFIG_VALUE:
v = jj_consume_token(CONFIG_VALUE);
break;
default:
jj_la1[5] = jj_gen;
;
}
jj_consume_token(CONFIG_END);
if (v != null) {
configurations.put(k.image, v.image);
}
} catch (ParseException ex) {
recover(ex, CONFIG_END);
}
}
final public void SectionActions() throws ParseException {
SectionActionsName();
label_3:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case COMMENT_IN_ACTIONS:
case ACTION_METHOD:
;
break;
default:
jj_la1[6] = jj_gen;
break label_3;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_METHOD:
SectionActionsLine();
break;
case COMMENT_IN_ACTIONS:
jj_consume_token(COMMENT_IN_ACTIONS);
break;
default:
jj_la1[7] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
}
final public void SectionActionsName() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SECTION_ACTIONS_NAME:
jj_consume_token(SECTION_ACTIONS_NAME);
break;
case SECTION_CONFIG_NEXT_ACTIONS:
jj_consume_token(SECTION_CONFIG_NEXT_ACTIONS);
break;
case SECTION_ACTIONS_NEXT_ACTIONS:
jj_consume_token(SECTION_ACTIONS_NEXT_ACTIONS);
break;
case SECTION_ERRORS_NEXT_ACTIONS:
jj_consume_token(SECTION_ERRORS_NEXT_ACTIONS);
break;
case SECTION_FILTERS_NEXT_ACTIONS:
jj_consume_token(SECTION_FILTERS_NEXT_ACTIONS);
break;
case SECTION_EXTENSIONS_NEXT_ACTIONS:
jj_consume_token(SECTION_EXTENSIONS_NEXT_ACTIONS);
break;
case SECTION_PROPERTIES_NEXT_ACTIONS:
jj_consume_token(SECTION_PROPERTIES_NEXT_ACTIONS);
break;
default:
jj_la1[8] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
final public void SectionActionsLine() throws ParseException {
try {
jj_consume_token(ACTION_METHOD);
jj_consume_token(ACTION_SEPARATOR);
jj_consume_token(ACTION_PATH);
label_4:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_PATH_VALUE:
case ACTION_PATH_VARIABLE:
;
break;
default:
jj_la1[9] = jj_gen;
break label_4;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_PATH_VALUE:
jj_consume_token(ACTION_PATH_VALUE);
break;
case ACTION_PATH_VARIABLE:
jj_consume_token(ACTION_PATH_VARIABLE);
break;
default:
jj_la1[10] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_PATH:
jj_consume_token(ACTION_PATH);
break;
default:
jj_la1[11] = jj_gen;
;
}
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_PARAMETERS_BEGIN:
jj_consume_token(ACTION_PARAMETERS_BEGIN);
SectionActionsPathParameter();
label_5:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_PATH_PARAMETER_OTHER:
case ACTION_PATH_PARAMETER_VALUE_OTHER:
;
break;
default:
jj_la1[12] = jj_gen;
break label_5;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_PATH_PARAMETER_OTHER:
jj_consume_token(ACTION_PATH_PARAMETER_OTHER);
break;
case ACTION_PATH_PARAMETER_VALUE_OTHER:
jj_consume_token(ACTION_PATH_PARAMETER_VALUE_OTHER);
break;
default:
jj_la1[13] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
SectionActionsPathParameter();
}
break;
default:
jj_la1[14] = jj_gen;
;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_PATH_END:
jj_consume_token(ACTION_PATH_END);
break;
case ACTION_PATH_PARAMETER_SEPARATOR:
jj_consume_token(ACTION_PATH_PARAMETER_SEPARATOR);
break;
case ACTION_PATH_PARAMETER_VALUE_SEPARATOR:
jj_consume_token(ACTION_PATH_PARAMETER_VALUE_SEPARATOR);
break;
default:
jj_la1[15] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_JAVA_BEGIN:
case ACTION_ACTION_VARIABLE:
case ACTION_ACTION_IDENTIFIER:
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_JAVA_BEGIN:
jj_consume_token(ACTION_ACTION_JAVA_BEGIN);
break;
default:
jj_la1[16] = jj_gen;
;
}
label_6:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_VARIABLE:
jj_consume_token(ACTION_ACTION_VARIABLE);
break;
case ACTION_ACTION_IDENTIFIER:
jj_consume_token(ACTION_ACTION_IDENTIFIER);
break;
default:
jj_la1[17] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_VARIABLE:
case ACTION_ACTION_IDENTIFIER:
;
break;
default:
jj_la1[18] = jj_gen;
break label_6;
}
}
label_7:
while (true) {
jj_consume_token(ACTION_ACTION_JAVA_QUALIFIED_IDENTIFIER);
label_8:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_JAVA_VARIABLE:
jj_consume_token(ACTION_ACTION_JAVA_VARIABLE);
break;
case ACTION_ACTION_JAVA_IDENTIFIER:
jj_consume_token(ACTION_ACTION_JAVA_IDENTIFIER);
break;
default:
jj_la1[19] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_JAVA_IDENTIFIER:
case ACTION_ACTION_JAVA_VARIABLE:
;
break;
default:
jj_la1[20] = jj_gen;
break label_8;
}
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_JAVA_QUALIFIED_IDENTIFIER:
;
break;
default:
jj_la1[21] = jj_gen;
break label_7;
}
}
break;
case ACTION_ACTION_VIEW:
jj_consume_token(ACTION_ACTION_VIEW);
label_9:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_VIEW_VALUE:
jj_consume_token(ACTION_ACTION_VIEW_VALUE);
break;
case ACTION_ACTION_VIEW_VARIABLE:
jj_consume_token(ACTION_ACTION_VIEW_VARIABLE);
break;
default:
jj_la1[22] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_VIEW_VALUE:
case ACTION_ACTION_VIEW_VARIABLE:
;
break;
default:
jj_la1[23] = jj_gen;
break label_9;
}
}
break;
case ACTION_ACTION_LINK:
jj_consume_token(ACTION_ACTION_LINK);
label_10:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_LINK_VALUE:
jj_consume_token(ACTION_ACTION_LINK_VALUE);
break;
case ACTION_ACTION_LINK_VARIABLE:
jj_consume_token(ACTION_ACTION_LINK_VARIABLE);
break;
default:
jj_la1[24] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_LINK_VALUE:
case ACTION_ACTION_LINK_VARIABLE:
;
break;
default:
jj_la1[25] = jj_gen;
break label_10;
}
}
break;
default:
jj_la1[26] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_JAVA_SEPARATOR:
case ACTION_ACTION_VIEW_SEPARATOR:
case ACTION_ACTION_LINK_SEPARATOR:
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_JAVA_SEPARATOR:
jj_consume_token(ACTION_ACTION_JAVA_SEPARATOR);
break;
case ACTION_ACTION_VIEW_SEPARATOR:
jj_consume_token(ACTION_ACTION_VIEW_SEPARATOR);
break;
case ACTION_ACTION_LINK_SEPARATOR:
jj_consume_token(ACTION_ACTION_LINK_SEPARATOR);
break;
default:
jj_la1[27] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
SectionActionsParameter();
label_11:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_PARAMETER_SEPARATOR:
case ACTION_PARAMETER_VALUE_SEPARATOR:
;
break;
default:
jj_la1[28] = jj_gen;
break label_11;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_PARAMETER_SEPARATOR:
jj_consume_token(ACTION_PARAMETER_SEPARATOR);
break;
case ACTION_PARAMETER_VALUE_SEPARATOR:
jj_consume_token(ACTION_PARAMETER_VALUE_SEPARATOR);
break;
default:
jj_la1[29] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
SectionActionsParameter();
}
break;
default:
jj_la1[30] = jj_gen;
;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_ACTION_JAVA_END:
jj_consume_token(ACTION_ACTION_JAVA_END);
break;
case ACTION_ACTION_VIEW_END:
jj_consume_token(ACTION_ACTION_VIEW_END);
break;
case ACTION_ACTION_LINK_END:
jj_consume_token(ACTION_ACTION_LINK_END);
break;
case ACTION_PARAMETER_VALUE_END:
jj_consume_token(ACTION_PARAMETER_VALUE_END);
break;
case ACTION_END:
jj_consume_token(ACTION_END);
break;
default:
jj_la1[31] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} catch (ParseException ex) {
recover(ex, ACTION_ACTION_JAVA_END, ACTION_ACTION_VIEW_END, ACTION_ACTION_LINK_END, ACTION_PARAMETER_VALUE_END, ACTION_END);
}
}
final public void SectionActionsPathParameter() throws ParseException {
jj_consume_token(ACTION_PATH_PARAMETER_NAME);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_PATH_PARAMETER_EQUALS:
jj_consume_token(ACTION_PATH_PARAMETER_EQUALS);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_PATH_PARAMETER_VALUE:
case ACTION_PATH_PARAMETER_VALUE_VARIABLE:
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_PATH_PARAMETER_VALUE:
jj_consume_token(ACTION_PATH_PARAMETER_VALUE);
break;
case ACTION_PATH_PARAMETER_VALUE_VARIABLE:
jj_consume_token(ACTION_PATH_PARAMETER_VALUE_VARIABLE);
break;
default:
jj_la1[32] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
break;
default:
jj_la1[33] = jj_gen;
;
}
break;
default:
jj_la1[34] = jj_gen;
;
}
}
final public void SectionActionsParameter() throws ParseException {
jj_consume_token(ACTION_PARAMETER_NAME);
jj_consume_token(ACTION_PARAMETER_EQUALS);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ACTION_PARAMETER_VALUE:
jj_consume_token(ACTION_PARAMETER_VALUE);
break;
default:
jj_la1[35] = jj_gen;
;
}
}
final public void SectionErrors() throws ParseException {
SectionErrorsName();
label_12:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case COMMENT_IN_ERRORS:
case ERROR_CODE:
case ALL:
case EXCEPTION:
;
break;
default:
jj_la1[36] = jj_gen;
break label_12;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ERROR_CODE:
case ALL:
case EXCEPTION:
SectionErrorsLine();
break;
case COMMENT_IN_ERRORS:
jj_consume_token(COMMENT_IN_ERRORS);
break;
default:
jj_la1[37] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
}
final public void SectionErrorsName() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SECTION_ERRORS_NAME:
jj_consume_token(SECTION_ERRORS_NAME);
break;
case SECTION_CONFIG_NEXT_ERRORS:
jj_consume_token(SECTION_CONFIG_NEXT_ERRORS);
break;
case SECTION_ACTIONS_NEXT_ERRORS:
jj_consume_token(SECTION_ACTIONS_NEXT_ERRORS);
break;
case SECTION_ERRORS_NEXT_ERRORS:
jj_consume_token(SECTION_ERRORS_NEXT_ERRORS);
break;
case SECTION_FILTERS_NEXT_ERRORS:
jj_consume_token(SECTION_FILTERS_NEXT_ERRORS);
break;
case SECTION_EXTENSIONS_NEXT_ERRORS:
jj_consume_token(SECTION_EXTENSIONS_NEXT_ERRORS);
break;
case SECTION_PROPERTIES_NEXT_ERRORS:
jj_consume_token(SECTION_PROPERTIES_NEXT_ERRORS);
break;
default:
jj_la1[38] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
final public void SectionErrorsLine() throws ParseException {
try {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ALL:
jj_consume_token(ALL);
break;
case ERROR_CODE:
jj_consume_token(ERROR_CODE);
jj_consume_token(ERROR_CODE_VALUE);
break;
case EXCEPTION:
jj_consume_token(EXCEPTION);
break;
default:
jj_la1[39] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
jj_consume_token(ERROR_SEPARATOR);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ERROR_ACTION_JAVA_BEGIN:
case ERROR_ACTION_JAVA:
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ERROR_ACTION_JAVA_BEGIN:
jj_consume_token(ERROR_ACTION_JAVA_BEGIN);
break;
default:
jj_la1[40] = jj_gen;
;
}
jj_consume_token(ERROR_ACTION_JAVA);
break;
case ERROR_ACTION_VIEW_BEGIN:
jj_consume_token(ERROR_ACTION_VIEW_BEGIN);
jj_consume_token(ERROR_ACTION_VALUE);
break;
case ERROR_ACTION_LINK_BEGIN:
jj_consume_token(ERROR_ACTION_LINK_BEGIN);
jj_consume_token(ERROR_ACTION_VALUE);
break;
default:
jj_la1[41] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ERROR_END:
jj_consume_token(ERROR_END);
break;
case ERROR_VALUE_END:
jj_consume_token(ERROR_VALUE_END);
break;
default:
jj_la1[42] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} catch (ParseException ex) {
recover(ex, ERROR_END);
}
}
final public void SectionFilters() throws ParseException {
SectionFiltersName();
label_13:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case COMMENT_IN_FILTERS:
case FILTER_METHOD:
;
break;
default:
jj_la1[43] = jj_gen;
break label_13;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case FILTER_METHOD:
SectionFiltersLine();
break;
case COMMENT_IN_FILTERS:
jj_consume_token(COMMENT_IN_FILTERS);
break;
default:
jj_la1[44] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
}
final public void SectionFiltersName() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SECTION_FILTERS_NAME:
jj_consume_token(SECTION_FILTERS_NAME);
break;
case SECTION_CONFIG_NEXT_FILTERS:
jj_consume_token(SECTION_CONFIG_NEXT_FILTERS);
break;
case SECTION_ACTIONS_NEXT_FILTERS:
jj_consume_token(SECTION_ACTIONS_NEXT_FILTERS);
break;
case SECTION_ERRORS_NEXT_FILTERS:
jj_consume_token(SECTION_ERRORS_NEXT_FILTERS);
break;
case SECTION_FILTERS_NEXT_FILTERS:
jj_consume_token(SECTION_FILTERS_NEXT_FILTERS);
break;
case SECTION_EXTENSIONS_NEXT_FILTERS:
jj_consume_token(SECTION_EXTENSIONS_NEXT_FILTERS);
break;
case SECTION_PROPERTIES_NEXT_FILTERS:
jj_consume_token(SECTION_PROPERTIES_NEXT_FILTERS);
break;
default:
jj_la1[45] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
final public void SectionFiltersLine() throws ParseException {
try {
jj_consume_token(FILTER_METHOD);
jj_consume_token(FILTER_SEPARATOR);
label_14:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case FILTER_PATH:
jj_consume_token(FILTER_PATH);
break;
case FILTER_PATH_ALL:
jj_consume_token(FILTER_PATH_ALL);
break;
default:
jj_la1[46] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case FILTER_PATH:
case FILTER_PATH_ALL:
;
break;
default:
jj_la1[47] = jj_gen;
break label_14;
}
}
jj_consume_token(FILTER_SEPARATOR);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case FILTER_ACTION_BEGIN:
jj_consume_token(FILTER_ACTION_BEGIN);
break;
default:
jj_la1[48] = jj_gen;
;
}
jj_consume_token(FILTER_ACTION);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case FILTER_PARAMETERS_SEPARATOR:
jj_consume_token(FILTER_PARAMETERS_SEPARATOR);
SectionFiltersParameter();
label_15:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case FILTER_PARAMETER_SEPARATOR:
case FILTER_PARAMETER_VALUE_SEPARATOR:
;
break;
default:
jj_la1[49] = jj_gen;
break label_15;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case FILTER_PARAMETER_SEPARATOR:
jj_consume_token(FILTER_PARAMETER_SEPARATOR);
break;
case FILTER_PARAMETER_VALUE_SEPARATOR:
jj_consume_token(FILTER_PARAMETER_VALUE_SEPARATOR);
break;
default:
jj_la1[50] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
SectionFiltersParameter();
}
break;
default:
jj_la1[51] = jj_gen;
;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case FILTER_END:
jj_consume_token(FILTER_END);
break;
case FILTER_PARAMETER_VALUE_END:
jj_consume_token(FILTER_PARAMETER_VALUE_END);
break;
default:
jj_la1[52] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} catch (ParseException ex) {
recover(ex, FILTER_END, FILTER_PARAMETER_VALUE_END);
}
}
final public void SectionFiltersParameter() throws ParseException {
jj_consume_token(FILTER_PARAMETER_NAME);
jj_consume_token(FILTER_PARAMETER_EQUALS);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case FILTER_PARAMETER_VALUE:
jj_consume_token(FILTER_PARAMETER_VALUE);
break;
default:
jj_la1[53] = jj_gen;
;
}
}
final public void SectionExtensions() throws ParseException {
SectionExtensionsName();
label_16:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case COMMENT_IN_EXTENSIONS:
case EXTENSION_PATH:
;
break;
default:
jj_la1[54] = jj_gen;
break label_16;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case EXTENSION_PATH:
SectionExtensionsLine();
break;
case COMMENT_IN_EXTENSIONS:
jj_consume_token(COMMENT_IN_EXTENSIONS);
break;
default:
jj_la1[55] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
}
final public void SectionExtensionsName() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SECTION_EXTENSIONS_NAME:
jj_consume_token(SECTION_EXTENSIONS_NAME);
break;
case SECTION_CONFIG_NEXT_EXTENSIONS:
jj_consume_token(SECTION_CONFIG_NEXT_EXTENSIONS);
break;
case SECTION_ACTIONS_NEXT_EXTENSIONS:
jj_consume_token(SECTION_ACTIONS_NEXT_EXTENSIONS);
break;
case SECTION_ERRORS_NEXT_EXTENSIONS:
jj_consume_token(SECTION_ERRORS_NEXT_EXTENSIONS);
break;
case SECTION_FILTERS_NEXT_EXTENSIONS:
jj_consume_token(SECTION_FILTERS_NEXT_EXTENSIONS);
break;
case SECTION_EXTENSIONS_NEXT_EXTENSIONS:
jj_consume_token(SECTION_EXTENSIONS_NEXT_EXTENSIONS);
break;
case SECTION_PROPERTIES_NEXT_EXTENSIONS:
jj_consume_token(SECTION_PROPERTIES_NEXT_EXTENSIONS);
break;
default:
jj_la1[56] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
final public void SectionExtensionsLine() throws ParseException {
try {
label_17:
while (true) {
jj_consume_token(EXTENSION_PATH);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case EXTENSION_PATH:
;
break;
default:
jj_la1[57] = jj_gen;
break label_17;
}
}
jj_consume_token(EXTENSION_SEPARATOR);
jj_consume_token(EXTENSION_FILE);
jj_consume_token(EXTENSION_END);
} catch (ParseException ex) {
recover(ex, EXTENSION_END);
}
}
final public void SectionProperties() throws ParseException {
SectionPropertiesName();
label_18:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case COMMENT_IN_PROPERTIES:
case PROPERTIE_NAME:
;
break;
default:
jj_la1[58] = jj_gen;
break label_18;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case PROPERTIE_NAME:
SectionPropertiesLine();
break;
case COMMENT_IN_PROPERTIES:
jj_consume_token(COMMENT_IN_PROPERTIES);
break;
default:
jj_la1[59] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
}
final public void SectionPropertiesName() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case SECTION_PROPERTIES_NAME:
jj_consume_token(SECTION_PROPERTIES_NAME);
break;
case SECTION_CONFIG_NEXT_PROPERTIES:
jj_consume_token(SECTION_CONFIG_NEXT_PROPERTIES);
break;
case SECTION_ACTIONS_NEXT_PROPERTIES:
jj_consume_token(SECTION_ACTIONS_NEXT_PROPERTIES);
break;
case SECTION_ERRORS_NEXT_PROPERTIES:
jj_consume_token(SECTION_ERRORS_NEXT_PROPERTIES);
break;
case SECTION_FILTERS_NEXT_PROPERTIES:
jj_consume_token(SECTION_FILTERS_NEXT_PROPERTIES);
break;
case SECTION_EXTENSIONS_NEXT_PROPERTIES:
jj_consume_token(SECTION_EXTENSIONS_NEXT_PROPERTIES);
break;
case SECTION_PROPERTIES_NEXT_PROPERTIES:
jj_consume_token(SECTION_PROPERTIES_NEXT_PROPERTIES);
break;
default:
jj_la1[60] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
final public void SectionPropertiesLine() throws ParseException {
try {
jj_consume_token(PROPERTIE_NAME);
jj_consume_token(PROPERTIE_EQUALS);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case PROPERTIE_VALUE:
jj_consume_token(PROPERTIE_VALUE);
break;
default:
jj_la1[61] = jj_gen;
;
}
jj_consume_token(PROPERTIE_END);
} catch (ParseException ex) {
recover(ex, PROPERTIE_END);
}
}
/** Generated Token Manager. */
public WebMotionParserTokenManager token_source;
SimpleCharStream jj_input_stream;
/** Current token. */
public Token token;
/** Next token. */
public Token jj_nt;
private int jj_ntk;
private int jj_gen;
final private int[] jj_la1 = new int[62];
static private int[] jj_la1_0;
static private int[] jj_la1_1;
static private int[] jj_la1_2;
static private int[] jj_la1_3;
static private int[] jj_la1_4;
static private int[] jj_la1_5;
static {
jj_la1_init_0();
jj_la1_init_1();
jj_la1_init_2();
jj_la1_init_3();
jj_la1_init_4();
jj_la1_init_5();
}
private static void jj_la1_init_0() {
jj_la1_0 = new int[] {0xf0003f02,0xf0003f02,0x4,0x4,0x10000100,0x0,0x8,0x8,0x20000200,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x10,0x10,0x40000400,0x0,0x0,0x0,0x0,0x20,0x20,0x80000800,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x40,0x40,0x1000,0x0,0x80,0x80,0x2000,0x0,};
}
private static void jj_la1_init_1() {
jj_la1_1 = new int[] {0xfc3,0xfc3,0x4,0x4,0x40,0x10,0x1000,0x1000,0x80,0x300000,0x300000,0x80000,0x44000000,0x44000000,0x400000,0x88800000,0x4000,0x18000,0x18000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7c000,0x0,0x0,0x0,0x0,0x0,0x30000000,0x30000000,0x2000000,0x0,0x0,0x0,0x100,0x0,0x0,0x0,0x0,0x0,0x0,0x200,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x401,0x0,0x0,0x0,0x802,0x0,};
}
private static void jj_la1_init_2() {
jj_la1_2 = new int[] {0x7e00000,0x7e00000,0x0,0x0,0x200000,0x0,0x0,0x0,0x400000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6,0x6,0x1,0x60,0x60,0x600,0x600,0x0,0x888,0x90000,0x90000,0x888,0x121110,0x0,0x0,0x0,0x40000,0x68000000,0x68000000,0x800000,0x68000000,0x0,0x0,0x0,0x0,0x0,0x1000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x2000000,0x0,0x0,0x0,0x4000000,0x0,};
}
private static void jj_la1_init_3() {
jj_la1_3 = new int[] {0xf8001f80,0xf8001f80,0x0,0x0,0x8000080,0x0,0x0,0x0,0x10000100,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20000200,0x0,0x1,0xf,0x50,0x2000,0x2000,0x40000400,0xc000,0xc000,0x20000,0x2400000,0x2400000,0x80000,0x4800000,0x1000000,0x0,0x0,0x80000800,0x0,0x0,0x0,0x1000,0x0,};
}
private static void jj_la1_init_4() {
jj_la1_4 = new int[] {0x7e1,0x7e1,0x0,0x0,0x20,0x0,0x0,0x0,0x40,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x80,0x0,0x0,0x0,0x0,0x0,0x0,0x100,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x2,0x2,0x200,0x2,0x800,0x800,0x401,0x2000,};
}
private static void jj_la1_init_5() {
jj_la1_5 = new int[] {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,};
}
/** Constructor with InputStream. */
public WebMotionParser(java.io.InputStream stream) {
this(stream, null);
}
/** Constructor with InputStream and supplied encoding */
public WebMotionParser(java.io.InputStream stream, String encoding) {
try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source = new WebMotionParserTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 62; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream) {
ReInit(stream, null);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream, String encoding) {
try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 62; i++) jj_la1[i] = -1;
}
/** Constructor. */
public WebMotionParser(java.io.Reader stream) {
jj_input_stream = new SimpleCharStream(stream, 1, 1);
token_source = new WebMotionParserTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 62; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(java.io.Reader stream) {
jj_input_stream.ReInit(stream, 1, 1);
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 62; i++) jj_la1[i] = -1;
}
/** Constructor with generated Token Manager. */
public WebMotionParser(WebMotionParserTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 62; i++) jj_la1[i] = -1;
}
/** Reinitialise. */
public void ReInit(WebMotionParserTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 62; i++) jj_la1[i] = -1;
}
private Token jj_consume_token(int kind) throws ParseException {
Token oldToken;
if ((oldToken = token).next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == kind) {
jj_gen++;
return token;
}
token = oldToken;
jj_kind = kind;
throw generateParseException();
}
/** Get the next Token. */
final public Token getNextToken() {
if (token.next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
jj_gen++;
return token;
}
/** Get the specific Token. */
final public Token getToken(int index) {
Token t = token;
for (int i = 0; i < index; i++) {
if (t.next != null) t = t.next;
else t = t.next = token_source.getNextToken();
}
return t;
}
private int jj_ntk() {
if ((jj_nt=token.next) == null)
return (jj_ntk = (token.next=token_source.getNextToken()).kind);
else
return (jj_ntk = jj_nt.kind);
}
private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>();
private int[] jj_expentry;
private int jj_kind = -1;
/** Generate ParseException. */
public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[165];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 62; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
if ((jj_la1_1[i] & (1<<j)) != 0) {
la1tokens[32+j] = true;
}
if ((jj_la1_2[i] & (1<<j)) != 0) {
la1tokens[64+j] = true;
}
if ((jj_la1_3[i] & (1<<j)) != 0) {
la1tokens[96+j] = true;
}
if ((jj_la1_4[i] & (1<<j)) != 0) {
la1tokens[128+j] = true;
}
if ((jj_la1_5[i] & (1<<j)) != 0) {
la1tokens[160+j] = true;
}
}
}
}
for (int i = 0; i < 165; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
}
/** Enable tracing. */
final public void enable_tracing() {
}
/** Disable tracing. */
final public void disable_tracing() {
}
}
| lgpl-3.0 |
moonsea/maosheji | src/maosheji/core/util/PinYinUtil.java | 2902 | package maosheji.core.util;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
public class PinYinUtil {
/**
* 将字符串中的中文转化为拼音,其他字符不变
*
* @param inputString
* @return
*/
public static String getPingYin(String inputString) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
char[] input = inputString.trim().toCharArray();
String output = "";
try {
for (int i = 0; i < input.length; i++) {
if (java.lang.Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);
output += temp[0];
} else
output += java.lang.Character.toString(input[i]);
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return output;
}
/**
* 获取汉字串拼音首字母,英文字符不变
* @param chinese 汉字串
* @return 汉语拼音首字母
*/
public static String getFirstSpell(String chinese) {
StringBuffer pybf = new StringBuffer();
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 128) {
try {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
if (temp != null) {
pybf.append(temp[0].charAt(0));
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pybf.append(arr[i]);
}
}
return pybf.toString().replaceAll("\\W", "").trim();
}
public static void main(String[] args) {
String chs = "我是中国人! I'm Chinese!";
System.out.println(chs);
System.out.println(getPingYin(chs));
System.out.println(getFirstSpell(chs));
}
}
| lgpl-3.0 |
Alvise88/RabbitSQL | RabbitSQL/src/main/java/org/wildjava/rabbitsql/lib/HashMap.java | 5583 | /* Copyright (c) 2001-2011, The HSQL Development Group
* 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 the HSQL Development Group 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 HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* 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.wildjava.rabbitsql.lib;
import org.wildjava.rabbitsql.map.BaseHashMap;
/**
* This class does not store null keys.
*
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @version 1.9.0
* @since 1.7.2
*/
public class HashMap extends BaseHashMap {
Set keySet;
Collection values;
public HashMap() {
this(8);
}
public HashMap(int initialCapacity) throws IllegalArgumentException {
super(initialCapacity, BaseHashMap.objectKeyOrValue,
BaseHashMap.objectKeyOrValue, false);
}
public Object get(Object key) {
int hash = key.hashCode();
int lookup = getLookup(key, hash);
if (lookup != -1) {
return objectValueTable[lookup];
}
return null;
}
public Object put(Object key, Object value) {
return super.addOrRemove(0, 0, key, value, false);
}
public Object remove(Object key) {
return super.removeObject(key, false);
}
public boolean containsKey(Object key) {
return super.containsKey(key);
}
public boolean containsValue(Object value) {
return super.containsValue(value);
}
public void putAll(HashMap t) {
Iterator it = t.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
put(key, t.get(key));
}
}
public void valuesToArray(Object[] array) {
Iterator it = values().iterator();
int i = 0;
while (it.hasNext()) {
array[i] = it.next();
i++;
}
}
public void keysToArray(Object[] array) {
Iterator it = keySet().iterator();
int i = 0;
while (it.hasNext()) {
array[i] = it.next();
i++;
}
}
public Set keySet() {
if (keySet == null) {
keySet = new KeySet();
}
return keySet;
}
public Collection values() {
if (values == null) {
values = new Values();
}
return values;
}
class KeySet implements Set {
public Iterator iterator() {
return HashMap.this.new BaseHashIterator(true);
}
public int size() {
return HashMap.this.size();
}
public boolean contains(Object o) {
return containsKey(o);
}
public Object get(Object key) {
int lookup = HashMap.this.getLookup(key, key.hashCode());
if (lookup < 0) {
return null;
} else {
return HashMap.this.objectKeyTable[lookup];
}
}
public boolean add(Object value) {
throw new RuntimeException();
}
public boolean addAll(Collection c) {
throw new RuntimeException();
}
public boolean remove(Object o) {
int oldSize = size();
HashMap.this.remove(o);
return size() != oldSize;
}
public boolean isEmpty() {
return size() == 0;
}
public void clear() {
HashMap.this.clear();
}
}
class Values implements Collection {
public Iterator iterator() {
return HashMap.this.new BaseHashIterator(false);
}
public int size() {
return HashMap.this.size();
}
public boolean contains(Object o) {
throw new RuntimeException();
}
public boolean add(Object value) {
throw new RuntimeException();
}
public boolean addAll(Collection c) {
throw new RuntimeException();
}
public boolean remove(Object o) {
throw new RuntimeException();
}
public boolean isEmpty() {
return size() == 0;
}
public void clear() {
HashMap.this.clear();
}
}
}
| lgpl-3.0 |
BITeam/Telegram_Bot | src/bot/translation/SentencesLoader.java | 920 | package bot.translation;
import bot.Setting;
import bot.functions.JsonManager;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.File;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.ResourceBundle;
public class SentencesLoader
{
public static boolean loadSentences()
{
Locale enLocale = new Locale(Setting.readSetting("Language", "Language"), Setting.readSetting("Region", "Language"));
ResourceBundle bundle = ResourceBundle.getBundle("bot.translation.language", enLocale);
Enumeration enumratore = bundle.getKeys();
HashMap<String, String> sentences = Sentences.getSentences();
if(!enumratore.hasMoreElements())
return false;
while (enumratore.hasMoreElements())
{
String key = (String) enumratore.nextElement();
String value = bundle.getString(key);
sentences.put(key,value);
}
return true;
}
}
| lgpl-3.0 |
kralisch/jams | JAMScommon/test/jams/aggregators/CompoundTemporalAggregatorTest.java | 5499 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jams.aggregators;
import jams.data.Attribute;
import jams.data.DefaultDataFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.TreeMap;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author christian
*/
public class CompoundTemporalAggregatorTest {
ArrayList<Attribute.TimeInterval> list = null;
Attribute.Calendar c = null;
public CompoundTemporalAggregatorTest() {
}
@Before
public void setUp() {
list = new ArrayList<Attribute.TimeInterval>();
Attribute.TimeInterval ti1 = DefaultDataFactory.getDataFactory().createTimeInterval();
ti1.getStart().set(2001, 0, 1, 0, 1, 1);
ti1.getEnd().set(2001, 2, 31, 0, 1, 1);
Attribute.TimeInterval ti2 = DefaultDataFactory.getDataFactory().createTimeInterval();
ti2.getStart().set(2001, 4, 1, 0, 1, 1);
ti2.getEnd().set(2001, 6, 31, 0, 1, 1);
Attribute.TimeInterval ti3 = DefaultDataFactory.getDataFactory().createTimeInterval();
ti3.getStart().set(2001, 7, 1, 0, 1, 1);
ti3.getEnd().set(2001, 10, 30, 0, 1, 1);
list.add(ti1);
list.add(ti2);
list.add(ti3);
c = DefaultDataFactory.getDataFactory().createCalendar();
c.set(2001, 0, 1, 0, 1, 1);
}
@AfterClass
public static void tearDownClass() {
}
//@Test
public void CompoundTemporalAggregatorSumTest(){
DoubleArrayAggregator innerAggr = DoubleArrayAggregator.create(Aggregator.AggregationMode.AVERAGE, 2);
DoubleArrayAggregator outerAggr = DoubleArrayAggregator.create(Aggregator.AggregationMode.SUM, 2);
TemporalAggregator<double[]> InnerTempAggr =
new BasicTemporalAggregator(innerAggr, TemporalAggregator.AggregationTimePeriod.DAILY);
CompoundTemporalAggregator<double[]> tempAggr =
new CompoundTemporalAggregator<double[]>(outerAggr, InnerTempAggr, TemporalAggregator.AggregationTimePeriod.YEARLY);
final TreeMap<Attribute.Calendar, double[]> output1 = new TreeMap<Attribute.Calendar, double[]>();
tempAggr.addConsumer(new TemporalAggregator.Consumer<double[]>() {
@Override
public void consume(Attribute.Calendar c, double[] v) {
output1.put(c.getValue(), v.clone());
}
});
c.set(2000, 0, 1, 0, 1, 1);
for (int i=0;i<10000;i++){
if ( i % 2 == 1){
tempAggr.aggregate(c, new double[]{1,Double.NaN});
}else{
tempAggr.aggregate(c, new double[]{1,i});
}
c.add(Attribute.Calendar.DAY_OF_YEAR, 1);
}
tempAggr.finish();
//tempAggr.finish();
assert output1.size() == 28;
Iterator<double[]> iter1 = output1.values().iterator();
assert iter1.next()[0] == 365;
}
@Test
public void CompoundTemporalAggregatorCustomYearlyTest(){
DoubleArrayAggregator innerAggr = DoubleArrayAggregator.create(Aggregator.AggregationMode.AVERAGE, 3);
DoubleArrayAggregator outerAggr = DoubleArrayAggregator.create(Aggregator.AggregationMode.SUM, 3);
TemporalAggregator<double[]> InnerTempAggr =
new BasicTemporalAggregator(innerAggr, TemporalAggregator.AggregationTimePeriod.YEARLY);
CompoundTemporalAggregator<double[]> tempAggr =
new CompoundTemporalAggregator<double[]>(outerAggr, InnerTempAggr, TemporalAggregator.AggregationTimePeriod.CUSTOM, list);
final TreeMap<Attribute.Calendar, double[]> output1 = new TreeMap<Attribute.Calendar, double[]>();
tempAggr.addConsumer(new TemporalAggregator.Consumer<double[]>() {
@Override
public void consume(Attribute.Calendar c, double[] v) {
output1.put(c.getValue(), v.clone());
System.out.println(c + "\t" + Arrays.toString(v));
}
});
c.set(2001, 0, 1, 0, 1, 1);
while(c.get(Attribute.Calendar.YEAR) < 2020){
int dayOfYear = c.get(Attribute.Calendar.DAY_OF_YEAR);
if ( dayOfYear % 2 == 1){
tempAggr.aggregate(c, new double[]{1,dayOfYear,Double.NaN});
}else{
tempAggr.aggregate(c, new double[]{1,dayOfYear,1});
}
c.add(Attribute.Calendar.DAY_OF_YEAR, 1);
}
tempAggr.finish();
//tempAggr.finish();
assert output1.size() == 3;
Iterator<double[]> iter1 = output1.values().iterator();
double first[] = iter1.next();
assert first[0] == 1;
assert first[1] == ((31.+28.+31.)*91./2.)/90.;
double second[] = iter1.next();
assert second[1] == 166.5; //mean from 120 to 211
}
}
| lgpl-3.0 |
Godin/sonar | sonar-core/src/main/java/org/sonar/core/util/logs/DefaultProfiler.java | 8194 | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.core.util.logs;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.LoggerLevel;
class DefaultProfiler extends Profiler {
private static final String CONTEXT_SEPARATOR = " | ";
private static final String NO_MESSAGE_SUFFIX = "";
private final LinkedHashMap<String, Object> context = new LinkedHashMap<>();
private final Logger logger;
private long startTime = 0L;
private String startMessage = null;
private Object[] args = null;
private boolean logTimeLast = false;
public DefaultProfiler(Logger logger) {
this.logger = logger;
}
@Override
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
@Override
public boolean isTraceEnabled() {
return logger.isTraceEnabled();
}
@Override
public Profiler start() {
this.startTime = System2.INSTANCE.now();
this.startMessage = null;
return this;
}
@Override
public Profiler startTrace(String message) {
return doStart(LoggerLevel.TRACE, message);
}
@Override
public Profiler startTrace(String message, Object... args) {
return doStart(LoggerLevel.TRACE, message, args);
}
@Override
public Profiler startDebug(String message) {
return doStart(LoggerLevel.DEBUG, message);
}
@Override
public Profiler startDebug(String message, Object... args) {
return doStart(LoggerLevel.DEBUG, message, args);
}
@Override
public Profiler startInfo(String message) {
return doStart(LoggerLevel.INFO, message);
}
@Override
public Profiler startInfo(String message, Object... args) {
return doStart(LoggerLevel.INFO, message, args);
}
@Override
public long stopTrace() {
return doStopWithoutMessage(LoggerLevel.TRACE);
}
@Override
public long stopDebug() {
return doStopWithoutMessage(LoggerLevel.DEBUG);
}
@Override
public long stopInfo() {
return doStopWithoutMessage(LoggerLevel.INFO);
}
@Override
public long stopTrace(String message) {
return doStop(LoggerLevel.TRACE, message, null, NO_MESSAGE_SUFFIX);
}
@Override
public long stopTrace(String message, Object... args) {
return doStop(LoggerLevel.TRACE, message, args, NO_MESSAGE_SUFFIX);
}
@Override
public long stopDebug(String message) {
return doStop(LoggerLevel.DEBUG, message, null, NO_MESSAGE_SUFFIX);
}
@Override
public long stopDebug(String message, Object... args) {
return doStop(LoggerLevel.DEBUG, message, args, NO_MESSAGE_SUFFIX);
}
@Override
public long stopInfo(String message) {
return doStop(LoggerLevel.INFO, message, null, NO_MESSAGE_SUFFIX);
}
@Override
public long stopInfo(String message, Object... args) {
return doStop(LoggerLevel.INFO, message, args, NO_MESSAGE_SUFFIX);
}
@Override
public long stopError(String message, Object... args) {
return doStop(LoggerLevel.ERROR, message, args, NO_MESSAGE_SUFFIX);
}
private Profiler doStart(LoggerLevel logLevel, String message, Object... args) {
init(message, args);
logStartMessage(logLevel, message, args);
return this;
}
private void init(String message, Object... args) {
this.startTime = System2.INSTANCE.now();
this.startMessage = message;
this.args = args;
}
private void reset() {
this.startTime = 0L;
this.startMessage = null;
this.args = null;
this.context.clear();
}
private void logStartMessage(LoggerLevel loggerLevel, String message, Object... args) {
if (shouldLog(logger, loggerLevel)) {
StringBuilder sb = new StringBuilder();
sb.append(message);
appendContext(sb);
log(loggerLevel, sb.toString(), args);
}
}
private long doStopWithoutMessage(LoggerLevel level) {
if (startMessage == null) {
throw new IllegalStateException("Profiler#stopXXX() can't be called without any message defined in start methods");
}
return doStop(level, startMessage, this.args, " (done)");
}
private long doStop(LoggerLevel level, @Nullable String message, @Nullable Object[] args, String messageSuffix) {
if (startTime == 0L) {
throw new IllegalStateException("Profiler must be started before being stopped");
}
long duration = System2.INSTANCE.now() - startTime;
if (shouldLog(logger, level)) {
StringBuilder sb = new StringBuilder();
if (!StringUtils.isEmpty(message)) {
sb.append(message);
sb.append(messageSuffix);
}
if (logTimeLast) {
appendContext(sb);
appendTime(sb, duration);
} else {
appendTime(sb, duration);
appendContext(sb);
}
log(level, sb.toString(), args);
}
reset();
return duration;
}
private static void appendTime(StringBuilder sb, long duration) {
if (sb.length() > 0) {
sb.append(CONTEXT_SEPARATOR);
}
sb.append("time=").append(duration).append("ms");
}
private void appendContext(StringBuilder sb) {
for (Map.Entry<String, Object> entry : context.entrySet()) {
if (sb.length() > 0) {
sb.append(CONTEXT_SEPARATOR);
}
sb.append(entry.getKey()).append("=").append(Objects.toString(entry.getValue()));
}
}
void log(LoggerLevel level, String msg, @Nullable Object[] args) {
switch (level) {
case TRACE:
logTrace(msg, args);
break;
case DEBUG:
logDebug(msg, args);
break;
case INFO:
logInfo(msg, args);
break;
case WARN:
logWarn(msg, args);
break;
case ERROR:
logError(msg, args);
break;
default:
throw new IllegalArgumentException("Unsupported LoggerLevel value: " + level);
}
}
private void logTrace(String msg, @Nullable Object[] args) {
if (args == null) {
logger.trace(msg);
} else {
logger.trace(msg, args);
}
}
private void logDebug(String msg, @Nullable Object[] args) {
if (args == null) {
logger.debug(msg);
} else {
logger.debug(msg, args);
}
}
private void logInfo(String msg, @Nullable Object[] args) {
if (args == null) {
logger.info(msg);
} else {
logger.info(msg, args);
}
}
private void logWarn(String msg, @Nullable Object[] args) {
if (args == null) {
logger.warn(msg);
} else {
logger.warn(msg, args);
}
}
private void logError(String msg, @Nullable Object[] args) {
if (args == null) {
logger.error(msg);
} else {
logger.error(msg, args);
}
}
private static boolean shouldLog(Logger logger, LoggerLevel level) {
if (level == LoggerLevel.TRACE && !logger.isTraceEnabled()) {
return false;
}
return level != LoggerLevel.DEBUG || logger.isDebugEnabled();
}
@Override
public Profiler addContext(String key, @Nullable Object value) {
if (value == null) {
context.remove(key);
} else {
context.put(key, value);
}
return this;
}
@Override
public boolean hasContext(String key) {
return context.containsKey(key);
}
@Override
public Profiler logTimeLast(boolean flag) {
this.logTimeLast = flag;
return this;
}
}
| lgpl-3.0 |
ATNoG/ODTONE | extensions/sensors/Dummy_Sensor_SAP/src/odtone_java/inc/Common/Types/Address.java | 20910 | //
// Copyright (c) 2009-2013 2013 Universidade Aveiro - Instituto de
// Telecomunicacoes Polo Aveiro
// This file is part of ODTONE - Open Dot Twenty One.
//
// This software is distributed under a license. The full license
// agreement can be found in the file LICENSE in this distribution.
// This software may not be copied, modified, sold or distributed
// other than expressed in the named license agreement.
//
// This software is distributed without any warranty.
//
// Author: Marcelo Lebre <marcelolebre@av.it.pt>
//
package odtone_java.inc.Common.Types;
//~--- non-JDK imports --------------------------------------------------------
import odtone_java.inc.Common.Datatypes.Octet_String;
import odtone_java.inc.Common.Datatypes.UInt16;
import odtone_java.inc.Common.Types.Information.Network_type_addr;
import odtone_java.inc.Common.Types.Ipconfig.IP_Addr;
import odtone_java.inc.Common.Serialization;
//~--- JDK imports ------------------------------------------------------------
import java.util.Vector;
import odtone_java.inc.Common.Datatypes.Octet;
import odtone_java.inc.Common.Datatypes.UInt32;
/**
*
* @author marcelo lebre <marcelolebre@av.it.pt>
*
*/
/**
*
* Class designed to construct a address object
* Nested in this class are several objects that relate to
* address information in the standard
*
*/
public class Address {
/**
*
*/
public IP_Addr ACC_RTR;
/**
*
*/
public IP_Addr DHCP_Serv;
/**
*
*/
public IP_Addr FN_AGNT;
/**
*
*/
public Transport_address mac_address;
/**
*
* Class designed to construct a link address list object
*
*/
public class Link_Addr_List {
byte[] link_addr_list;
Vector link_addr_list_ = new Vector();
public Link_Addr_List(byte[] in) {
link_addr_list = new byte[in.length];
link_addr_list = in;
}
public Link_Addr_List(Vector linkAddrList) {
link_addr_list_ = linkAddrList;
int count = 0, pos = 0;
Serialization srlz = new Serialization();
Vector tmp = new Vector();
for (int i = 0; i < linkAddrList.size(); i++) {
tmp.addElement(((Network_type_addr)linkAddrList.elementAt(i)).get_Network_type_addr());
}
link_addr_list = new byte[srlz.encoding_List(tmp).length];
link_addr_list = srlz.encoding_List(tmp);
}
public byte[] getLinkAddrList() {
return link_addr_list;
}
public Vector getLinkAddrListValues() {
return link_addr_list_;
}
}
/**
*
* Class designed to construct a link address object
*
*/
public class Link_Address {
/**
*
*/
public static final int _3GPP2_ADDR = 5;
/**
*
*/
public static final int _3GPP_2G_CELL_ID = 3;
// Behaviour not implemented
/**
*
*/
public static final int _3GPP_3G_CELL_ID = 2;
/**
*
*/
public static final int _3GPP_ADDR = 4;
/**
*
*/
public static final int _OTHER_L2_ADDR = 6;
/**
*
*/
public static final int mac_add = 1;
//
byte[] link_address;
byte[] link_address_out;
Transport_address macaddr;
ThreeGPP_ADDR tga;
ThreeGPP2_ADDR tg2a;
ThreeGPP_2G_Cell_ID tg2ci;
ThreeGPP_3G_Cell_ID tg3ci;
Other_l2_ADDR ola;
String which_transport = "";
public String get_which_active_transport() {
return which_transport;
}
public Other_l2_ADDR get_Other_L2_Addr() {
return ola;
}
public ThreeGPP_3G_Cell_ID get_3GPP_3G_Cell_ID() {
return tg3ci;
}
public ThreeGPP_2G_Cell_ID get_3GPP_2G_Cell_ID() {
return tg2ci;
}
public ThreeGPP2_ADDR get_3GPP2_Addr() {
return tg2a;
}
public Transport_address get_Transport_address() {
return macaddr;
}
public ThreeGPP_ADDR get_3GPP_Addr() {
return tga;
}
public Link_Address(Transport_address mac_addr) {
macaddr = new Transport_address(mac_addr.get_Value_i(), mac_addr.get_Value_Octet_String());
Serialization srlz = new Serialization();
which_transport = "mac address";
link_address_out = new byte[srlz.choice(mac_addr.get_Transport_address(), 0).length];
link_address_out = srlz.choice(mac_addr.get_Transport_address(), 0);
}
public Link_Address(Link_Address la) {
if (la.get_which_active_transport().equals("mac address")) {
macaddr = new Transport_address(la.get_Transport_address().get_Value_i(), la.get_Transport_address().get_Value_Octet_String());
Serialization srlz = new Serialization();
which_transport = "mac address";
link_address_out = new byte[la.get_link_address().length];
link_address_out = la.get_link_address();
}
if (la.get_which_active_transport().equals("3GPP 3G Cell ID")) {
tg3ci = new ThreeGPP_3G_Cell_ID(la.get_3GPP_3G_Cell_ID().get_PLMN_ID(), la.get_3GPP_3G_Cell_ID().get_CELL_ID());
Serialization srlz = new Serialization();
which_transport = "3GPP 3G Cell ID";
link_address_out = new byte[la.get_link_address().length];
link_address_out = la.get_link_address();
}
if (la.get_which_active_transport().equals("3GPP 2G Cell ID")) {
tg2ci = new ThreeGPP_2G_Cell_ID(la.get_3GPP_2G_Cell_ID().get_PLMN_ID(), la.get_3GPP_2G_Cell_ID().get_LAC(), la.get_3GPP_2G_Cell_ID().get_CI());
Serialization srlz = new Serialization();
which_transport = "3GPP 3G Cell ID";
link_address_out = new byte[la.get_link_address().length];
link_address_out = la.get_link_address();
}
if (la.get_which_active_transport().equals("3GPP Address")) {
tga = new ThreeGPP_ADDR(la.get_3GPP_Addr().get_3GPP_Addr_Value());
Serialization srlz = new Serialization();
which_transport = "3GPP Address";
link_address_out = new byte[la.get_link_address().length];
link_address_out = la.get_link_address();
}
if (la.get_which_active_transport().equals("3GPP2 Address")) {
tg2a = new ThreeGPP2_ADDR(la.get_3GPP2_Addr().get_3GPP2_Addr_Value());
Serialization srlz = new Serialization();
which_transport = "3GPP2 Address";
link_address_out = new byte[la.get_link_address().length];
link_address_out = la.get_link_address();
}
if (la.get_which_active_transport().equals("Other L2 Address")) {
ola = new Other_l2_ADDR(la.get_Other_L2_Addr().get_Other_L2_Addr_Value());
Serialization srlz = new Serialization();
which_transport = "Other L2 Address";
link_address_out = new byte[la.get_link_address().length];
link_address_out = la.get_link_address();
}
}
/**
*
* Constructor
*
*/
public Link_Address(byte[] in) {
int selector = -1;
link_address_out = new byte[in.length];
link_address_out = in;
selector = in[0];
byte[] tmp = new byte[in.length - 1];
for (int i = 0; i < in.length - 1; i++) {
tmp[0] = in[i + 1];
}
if (selector == 0) {
macaddr = new Transport_address(tmp);
Serialization srlz = new Serialization();
which_transport = "mac address";
link_address_out = new byte[in.length];
link_address_out = in;
}
if (selector == 1) {
tg3ci = new ThreeGPP_3G_Cell_ID(tmp);
Serialization srlz = new Serialization();
which_transport = "3GPP 3G Cell ID";
link_address_out = new byte[in.length];
link_address_out = in;
}
if (selector == 2) {
tg2ci = new ThreeGPP_2G_Cell_ID(tmp);
Serialization srlz = new Serialization();
which_transport = "3GPP 3G Cell ID";
link_address_out = new byte[in.length];
link_address_out = in;
}
if (selector == 3) {
tga = new ThreeGPP_ADDR(tmp);
Serialization srlz = new Serialization();
which_transport = "3GPP Address";
link_address_out = new byte[in.length];
link_address_out = in;
}
if (selector == 4) {
tg2a = new ThreeGPP2_ADDR(tmp);
Serialization srlz = new Serialization();
which_transport = "3GPP2 Address";
link_address_out = new byte[in.length];
link_address_out = in;
}
if (selector == 5) {
ola = new Other_l2_ADDR(tmp);
Serialization srlz = new Serialization();
which_transport = "Other L2 Address";
link_address_out = new byte[in.length];
link_address_out = in;
}
}
public Link_Address(ThreeGPP_3G_Cell_ID t3c) {
tg3ci = new ThreeGPP_3G_Cell_ID(null, null);
Serialization srlz = new Serialization();
link_address_out = new byte[srlz.choice(t3c.get_ThreeGPP_3G_Cell_ID(), 1).length];
link_address_out = srlz.choice(t3c.get_ThreeGPP_3G_Cell_ID(), 1);
which_transport = "3GPP 3G Cell ID";
}
/**
*
* Constructor
*
*/
public Link_Address(ThreeGPP_2G_Cell_ID t2c) {
Serialization srlz = new Serialization();
link_address_out = new byte[srlz.choice(t2c.get_ThreeGPP_2G_Cell_ID(), 2).length];
link_address_out = srlz.choice(t2c.get_ThreeGPP_2G_Cell_ID(), 2);
which_transport = "3GPP 2G Cell ID";
}
/**
*
* Constructor
*
*/
public Link_Address(ThreeGPP_ADDR tga) {
Serialization srlz = new Serialization();
link_address_out = new byte[srlz.choice(tga.get_3GPP_ADDR(), 3).length];
link_address_out = srlz.choice(tga.get_3GPP_ADDR(), 3);
which_transport = "3GPP Address";
}
/**
*
* Constructor
*
*/
public Link_Address() {
}
/**
*
* Constructor
*
*/
public Link_Address(ThreeGPP2_ADDR tga) {
Serialization srlz = new Serialization();
link_address_out = new byte[srlz.choice(tga.get_3GPP2_ADDR(), 4).length];
link_address_out = srlz.choice(tga.get_3GPP2_ADDR(), 4);
which_transport = "3GPP2 Address";
}
/**
*
* Constructor
*
*/
public Link_Address(Other_l2_ADDR ola) {
Serialization srlz = new Serialization();
link_address_out = new byte[srlz.choice(ola.get_Other_l2_ADDR(), 4).length];
link_address_out = srlz.choice(ola.get_Other_l2_ADDR(), 4);
which_transport = "Other L2 Address";
}
/**
* Getter - Returns the link address in byte[] form
* @return byte []
*/
public byte[] get_link_address() {
return link_address_out;
}
}
/**
*
* Class designed to construct a transport address object
*
*/
public class Transport_address {
public byte[] transportaddress;
public int value_i;
public Octet_String value_os;
public Transport_address(byte[] in) {
transportaddress = new byte[in.length];
transportaddress = in;
byte[] tmpUint2 = new byte[2];
tmpUint2[0] = in[0];
tmpUint2[1] = in[1];
UInt32 family = new UInt32();
value_i = family.UInt32ToInt(tmpUint2);
byte[] add = new byte[in.length - 2];
for (int i = 0, j = 2; j < in.length; i++) {
add[i] = in[j];
}
value_os = new Octet_String(add);
}
/**
* Constructor
* @param int
* @param Octet_String
*/
public Transport_address(int i, Octet_String os) {
value_i = i;
value_os = new Octet_String(os);
// The maximum value of i according to IANA
// http://www.iana.org/assignments/address-family-numbers/
// Sequencing
Serialization srlz = new Serialization();
transportaddress = new byte[srlz.sequence((new UInt16(i)).getValue(), os.getValue()).length];
transportaddress = srlz.sequence((new UInt16(i)).getValue(), os.getValue());
}
/**
* Getter - returns the transport address value in byte []
* @return byte[]
*/
public byte[] get_Transport_address() {
return transportaddress;
}
public int get_Value_i() {
return value_i;
}
public Octet_String get_Value_Octet_String() {
return value_os;
}
}
/**
*
* Class designed to construct a 3GPP_3G_Cell_ID object
*
*/
public class ThreeGPP_3G_Cell_ID {
byte[] threegpp_3g_cell_id;
PLMN_ID plmn_ID;
CELL_ID cell_ID;
public ThreeGPP_3G_Cell_ID(PLMN_ID plmnID, CELL_ID cellID) {
plmn_ID = new PLMN_ID(plmnID);
cell_ID = new CELL_ID(cellID);
Serialization srlz = new Serialization();
threegpp_3g_cell_id = new byte[srlz.sequence(plmnID.get_PLMN_ID(), cellID.get_CELL_ID()).length];
threegpp_3g_cell_id = srlz.sequence(plmnID.get_PLMN_ID(), cellID.get_CELL_ID());
}
public ThreeGPP_3G_Cell_ID(byte[] in) {
threegpp_3g_cell_id = new byte[in.length];
threegpp_3g_cell_id = in;
byte[] tmp1 = new byte[3];
byte[] tmp2 = new byte[4];
for (int i = 0; i < 3; i++) {
tmp1[i] = in[i];
}
for (int i = 3, j = 0; i < in.length; i++, j++) {
tmp2[j] = in[i];
}
Octet os = new Octet(tmp1);
plmn_ID = new PLMN_ID(os);
UInt32 val = new UInt32();
val.setValue(tmp2);
cell_ID = new CELL_ID(val);
}
public PLMN_ID get_PLMN_ID() {
return plmn_ID;
}
public CELL_ID get_CELL_ID() {
return cell_ID;
}
public byte[] get_ThreeGPP_3G_Cell_ID() {
return threegpp_3g_cell_id;
}
}
public class PLMN_ID {
byte[] plmnID;
Octet value;
public PLMN_ID(Octet os) {
value = new Octet(os);
if (os.getValue().length == 3) {
plmnID = new byte[os.getValue().length];
plmnID = os.getValue();
}
}
public PLMN_ID(PLMN_ID plmnID) {
value = plmnID.get_PLMN_ID_Value();
this.plmnID = new byte[plmnID.get_PLMN_ID().length];
this.plmnID = plmnID.get_PLMN_ID();
}
public byte[] get_PLMN_ID() {
return plmnID;
}
public Octet get_PLMN_ID_Value() {
return value;
}
}
public class CELL_ID {
byte[] cellID;
int value;
public CELL_ID(CELL_ID cellID) {
value = cellID.get_CELL_ID_Value();
this.cellID = new byte[cellID.get_CELL_ID().length];
this.cellID = cellID.get_CELL_ID();
}
public CELL_ID(UInt32 uint) {
value = uint.UInt32ToInt(uint.getValue());
cellID = new byte[uint.getValue().length];
cellID = uint.getValue();
}
public int get_CELL_ID_Value() {
return value;
}
public byte[] get_CELL_ID() {
return cellID;
}
}
public class ThreeGPP_2G_Cell_ID {
byte[] threegpp_2g_cell_id;
PLMN_ID plmnID;
LAC lac;
CI ci;
public ThreeGPP_2G_Cell_ID(byte[] in) {
threegpp_2g_cell_id = new byte[in.length];
threegpp_2g_cell_id = in;
byte[] tmp1 = new byte[3];
byte[] tmp2 = new byte[2];
byte[] tmp3 = new byte[2];
for (int i = 0; i < 3; i++) {
tmp1[i] = in[i];
}
tmp2[0] = in[3];
tmp2[1] = in[4];
tmp3[0] = in[5];
tmp3[1] = in[6];
lac = new LAC(new Octet(tmp2));
ci = new CI(new Octet(tmp3));
}
public PLMN_ID get_PLMN_ID() {
return this.plmnID;
}
public LAC get_LAC() {
return this.lac;
}
public CI get_CI() {
return this.ci;
}
public ThreeGPP_2G_Cell_ID(PLMN_ID plmnID, LAC lac, CI ci) {
Serialization srlz = new Serialization();
this.plmnID = plmnID;
this.lac = lac;
this.ci = ci;
threegpp_2g_cell_id = new byte[srlz.sequence(plmnID.get_PLMN_ID(), lac.get_LAC(), ci.get_CI()).length];
threegpp_2g_cell_id = srlz.sequence(plmnID.get_PLMN_ID(), lac.get_LAC(), ci.get_CI());
}
public byte[] get_ThreeGPP_2G_Cell_ID() {
return threegpp_2g_cell_id;
}
}
public class LAC {
byte[] lac;
Octet os;
public LAC(Octet os) {
this.os = os;
if (os.getValue().length == 2) {
lac = new byte[os.getValue().length];
lac = os.getValue();
}
}
public byte[] get_LAC() {
return lac;
}
public Octet get_LAC_Value() {
return os;
}
}
public class CI {
byte[] ci;
Octet os;
public CI(Octet os) {
this.os = os;
if (os.getValue().length == 2) {
ci = new byte[os.getValue().length];
ci = os.getValue();
}
}
public Octet get_CI_Value() {
return this.os;
}
public byte[] get_CI() {
return ci;
}
}
public class ThreeGPP_ADDR {
byte[] threeGppAddr;
Octet_String os;
public ThreeGPP_ADDR(byte [] in){
threeGppAddr = new byte[in.length];
threeGppAddr = in;
os = new Octet_String(in);
}
public ThreeGPP_ADDR(Octet_String os) {
this.os = new Octet_String(os);
threeGppAddr = new byte[os.getValue().length];
threeGppAddr = os.getValue();
}
public Octet_String get_3GPP_Addr_Value() {
return this.os;
}
public byte[] get_3GPP_ADDR() {
return threeGppAddr;
}
}
public class ThreeGPP2_ADDR {
byte[] threeGpp2Addr;
Octet_String os;
public ThreeGPP2_ADDR(byte [] in){
threeGpp2Addr = new byte[in.length];
threeGpp2Addr = in;
os = new Octet_String(in);
}
public ThreeGPP2_ADDR(Octet_String os) {
this.os = new Octet_String(os);
threeGpp2Addr = new byte[os.getValue().length];
threeGpp2Addr = os.getValue();
}
public byte[] get_3GPP2_ADDR() {
return threeGpp2Addr;
}
public Octet_String get_3GPP2_Addr_Value() {
return this.os;
}
}
public class Other_l2_ADDR {
byte[] other_l2_ADDR;
Octet_String os;
public Other_l2_ADDR(byte [] in){
other_l2_ADDR = new byte[in.length];
other_l2_ADDR = in;
os = new Octet_String(in);
}
public Other_l2_ADDR(Octet_String os) {
this.os = new Octet_String(os);
other_l2_ADDR = new byte[os.getValue().length];
other_l2_ADDR = os.getValue();
}
public Octet_String get_Other_L2_Addr_Value() {
return this.os;
}
public byte[] get_Other_l2_ADDR() {
return other_l2_ADDR;
}
}
}
| lgpl-3.0 |
TeamLapen/Vampirism | src/main/java/de/teamlapen/vampirism/entity/goals/FleeGarlicVampireGoal.java | 925 | package de.teamlapen.vampirism.entity.goals;
import de.teamlapen.vampirism.api.EnumStrength;
import de.teamlapen.vampirism.entity.vampire.VampireBaseEntity;
import de.teamlapen.vampirism.util.Helper;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class FleeGarlicVampireGoal extends FleeGoal {
private final VampireBaseEntity theCreature;
public FleeGarlicVampireGoal(VampireBaseEntity theCreature, double movementSpeed, boolean restrictHome) {
super(theCreature, movementSpeed, restrictHome);
this.theCreature = theCreature;
}
@Override
protected boolean isPositionAcceptable(World world, BlockPos pos) {
return theCreature.doesResistGarlic(Helper.getGarlicStrengthAt(world, pos));
}
@Override
protected boolean shouldFlee() {
return theCreature.isGettingGarlicDamage(theCreature.level) != EnumStrength.NONE;
}
}
| lgpl-3.0 |
beangle/library | security/core/src/main/java/org/beangle/security/core/session/SessionRepo.java | 1160 | /*
* Beangle, Agile Development Scaffold and Toolkits.
*
* Copyright © 2005, The Beangle Software.
*
* 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.beangle.security.core.session;
import java.time.Instant;
public interface SessionRepo {
/**
* 查询对应sessionid的信息
*
* @param sessionid
*/
Session get(String sessionid);
/**
* 更新对应sessionId的最后访问时间
*
* @param sessionid
*/
Session access(String sessionid, Instant accessAt);
void expire(String sid);
}
| lgpl-3.0 |
ujmp/universal-java-matrix-package | ujmp-core/src/main/java/org/ujmp/core/doublematrix/impl/DefaultDenseDoubleMatrix2D.java | 4026 | /*
* Copyright (C) 2008-2015 by Holger Arndt
*
* This file is part of the Universal Java Matrix Package (UJMP).
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* UJMP 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
* of the License, or (at your option) any later version.
*
* UJMP 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 UJMP; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package org.ujmp.core.doublematrix.impl;
import org.ujmp.core.Matrix;
import org.ujmp.core.doublematrix.stub.AbstractDenseDoubleMatrix2D;
import org.ujmp.core.interfaces.HasColumnMajorDoubleArray1D;
import org.ujmp.core.util.MathUtil;
public class DefaultDenseDoubleMatrix2D extends AbstractDenseDoubleMatrix2D implements
HasColumnMajorDoubleArray1D {
private static final long serialVersionUID = -3605416349143850650L;
private final double[] values;
private final int rows;
private final int cols;
public DefaultDenseDoubleMatrix2D(Matrix m) {
super(m.getRowCount(), m.getColumnCount());
this.rows = (int) m.getRowCount();
this.cols = (int) m.getColumnCount();
this.size = new long[] { rows, cols };
if (m instanceof DefaultDenseDoubleMatrix2D) {
double[] v = ((DefaultDenseDoubleMatrix2D) m).values;
this.values = new double[v.length];
System.arraycopy(v, 0, this.values, 0, v.length);
} else {
this.values = new double[rows * cols];
for (long[] c : m.allCoordinates()) {
setDouble(m.getAsDouble(c), c);
}
}
if (m.getMetaData() != null) {
setMetaData(m.getMetaData().clone());
}
}
public DefaultDenseDoubleMatrix2D(int rows, int columns) {
super(rows, columns);
this.rows = rows;
this.cols = columns;
this.size = new long[] { rows, columns };
this.values = new double[MathUtil.longToInt((long) rows * (long) columns)];
}
public DefaultDenseDoubleMatrix2D(double[] v, int rows, int cols) {
super(rows, cols);
this.rows = rows;
this.cols = cols;
this.size = new long[] { rows, cols };
this.values = v;
}
public final long getRowCount() {
return rows;
}
public final long getColumnCount() {
return cols;
}
public final double getDouble(long row, long column) {
return values[(int) (column * rows + row)];
}
public final double getAsDouble(long row, long column) {
return values[(int) (column * rows + row)];
}
public final double getAsDouble(int row, int column) {
return values[(column * rows + row)];
}
public final void setDouble(double value, long row, long column) {
values[(int) (column * rows + row)] = value;
}
public final void setAsDouble(double value, long row, long column) {
values[(int) (column * rows + row)] = value;
}
public final double getDouble(int row, int column) {
return values[column * rows + row];
}
public final void setDouble(double value, int row, int column) {
values[column * rows + row] = value;
}
public final void setAsDouble(double value, int row, int column) {
values[column * rows + row] = value;
}
public final Matrix copy() {
double[] result = new double[values.length];
System.arraycopy(values, 0, result, 0, values.length);
Matrix m = new DefaultDenseDoubleMatrix2D(result, rows, cols);
if (getMetaData() != null) {
m.setMetaData(getMetaData().clone());
}
return m;
}
public final double[] getColumnMajorDoubleArray1D() {
return values;
}
}
| lgpl-3.0 |
facundofarias/iBee | Source/iBeeProject/src/java/ibeeproject/consultarEmpleados.java | 7067 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ibeeproject;
import com.sun.rave.web.ui.appbase.AbstractFragmentBean;
import ibeeproject.model.persona.Empleado;
import ibeeproject.persistencia.GestorEmpleado;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
import javax.faces.component.UIParameter;
/**
*
* @version consultarEmpleados.java
* @version Created on 30-ene-2010, 15:57:59
* @author burni.matias
*/
public class consultarEmpleados extends AbstractFragmentBean {
private String campoBusq;
private ArrayList empleados = new ArrayList();
private GestorEmpleado gestor = new GestorEmpleado();
private UIParameter parametro;
/**
* <p>Automatically managed component initialization. <strong>WARNING:</strong>
* This method is automatically generated, so any user-specified code inserted
* here is subject to being replaced.</p>
*/
private void _init() throws Exception {
}
// </editor-fold>
public consultarEmpleados() {
}
/**
* <p>Callback method that is called whenever a page containing
* this page fragment is navigated to, either directly via a URL,
* or indirectly via page navigation. Override this method to acquire
* resources that will be needed for event handlers and lifecycle methods.</p>
*
* <p>The default implementation does nothing.</p>
*/
@Override
public void init() {
// Perform initializations inherited from our superclass
super.init();
// Perform application initialization that must complete
// *before* managed components are initialized
// TODO - add your own initialiation code here
// <editor-fold defaultstate="collapsed" desc="Visual-Web-managed Component Initialization">
// Initialize automatically managed components
// *Note* - this logic should NOT be modified
try {
_init();
} catch (Exception e) {
log("Page1 Initialization Failure", e);
throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
}
try {
// </editor-fold>
// Perform application initialization that must complete
// *after* managed components are initialized
// TODO - add your own initialization code here
this.updateTable();
} catch (Exception ex) {
Logger.getLogger(consultarEmpleados.class.getName()).log(Level.SEVERE, null, ex);
}
this.setCabecera();
}
/**
* <p>Callback method that is called after rendering is completed for
* this request, if <code>init()</code> was called. Override this
* method to release resources acquired in the <code>init()</code>
* resources that will be needed for event handlers and lifecycle methods.</p>
*
* <p>The default implementation does nothing.</p>
*/
@Override
public void destroy() {
}
/**
* <p>Return a reference to the scoped data bean.</p>
*
* @return reference to the scoped data bean
*/
protected SessionBean1 getSessionBean1() {
return (SessionBean1) getBean("SessionBean1");
}
/**
* <p>Return a reference to the scoped data bean.</p>
*
* @return reference to the scoped data bean
*/
protected ApplicationBean1 getApplicationBean1() {
return (ApplicationBean1) getBean("ApplicationBean1");
}
/**
* <p>Return a reference to the scoped data bean.</p>
*
* @return reference to the scoped data bean
*/
protected RequestBean1 getRequestBean1() {
return (RequestBean1) getBean("RequestBean1");
}
/**
* @return the campoBusq
*/
public String getCampoBusq() {
return campoBusq;
}
/**
* @param campoBusq the campoBusq to set
*/
public void setCampoBusq(String campoBusq) {
this.campoBusq = campoBusq;
}
/**
* @return the empleados
*/
public ArrayList getEmpleados() {
return empleados;
}
/**
* @param empleados the empleados to set
*/
public void setEmpleados(ArrayList empleados) {
this.empleados = empleados;
}
/**
* @return the gestor
*/
public GestorEmpleado getGestor() {
return gestor;
}
/**
* @param gestor the gestor to set
*/
public void setGestor(GestorEmpleado gestor) {
this.gestor = gestor;
}
/**
* @return the parametro
*/
public UIParameter getParametro() {
return parametro;
}
/**
* @param parametro the parametro to set
*/
public void setParametro(UIParameter parametro) {
this.parametro = parametro;
}
public void updateTable() throws Exception {
this.getEmpleados().clear();
setEmpleados(gestor.getTodos());
}
public void setCabecera(String ruta) {
cabecera ca = (cabecera) getBean("cabecera");
ca.setPath(ruta);
}
public void setCabecera() {
cabecera ca = (cabecera) getBean("cabecera");
ca.setPath("Home » Usuarios");
}
public String add_action() {
this.setCabecera("Home » Usuarios » Agregar");
Empleados e = (Empleados) getBean("Empleados");
e.setAgregar(true);
agregarEmpleado agregar = (agregarEmpleado) getBean("agregarEmpleado");
agregar.setEmpleado(new Empleado());
return null;
}
public String modif_action() {
this.setCabecera("Home » Usuarios » Modificar");
Empleados e = (Empleados) getBean("Empleados");
e.setModificar(true);
Empleado empleado = (Empleado) this.parametro.getValue();
modificarEmpleado modificar = (modificarEmpleado) getBean("modificarEmpleado");
modificar.setEmpleado(empleado);
return null;
}
public String delete_action() {
this.setCabecera("Home » Usuarios » Eliminar");
Empleados e = (Empleados) getBean("Empleados");
e.setEliminar(true);
Empleado empleado = (Empleado) this.parametro.getValue();
eliminarEmpleado eliminar = (eliminarEmpleado) getBean("eliminarEmpleado");
eliminar.setEmpleado(empleado);
return null;
}
public String query_action() {
this.setCabecera("Home » Usuarios » Consultar");
Empleados e = (Empleados) getBean("Empleados");
e.setConsultar(true);
Empleado empleado = (Empleado) this.parametro.getValue();
consultarEmpleado consultar = (consultarEmpleado) getBean("consultarEmpleado");
consultar.setEmpleado(empleado);
return null;
}
public String queryAll_action() {
this.setCabecera();
Empleados e = (Empleados) getBean("Empleados");
e.setConsultarAll(true);
return null;
}
}
| unlicense |
nkarasch/ChessGDX | core/src/nkarasch/chessgdx/gui/other/EngineThinkingImage.java | 804 | package nkarasch.chessgdx.gui.other;
import nkarasch.chessgdx.gui.MenuSkin;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.RepeatAction;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
public class EngineThinkingImage extends Image {
/**
* A spinning icon that tells the user the engine is currently processing
* the next move.
*
* @param skin
*/
public EngineThinkingImage(Skin skin) {
super(skin, MenuSkin.IMG_LOADING_ICON);
RepeatAction mSpinAction = new RepeatAction();
mSpinAction.setCount(RepeatAction.FOREVER);
mSpinAction.setAction(Actions.rotateBy(-360.0f, 1.0f));
setOrigin(getWidth() / 2, getHeight() / 2);
addAction(mSpinAction);
setVisible(false);
}
}
| unlicense |
xxing1982/EDU_SYZT | SunReadSource/src/main/java/com/syzton/sunread/controller/bookshelf/BookInShelfController.java | 10977 | package com.syzton.sunread.controller.bookshelf;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javassist.NotFoundException;
import javax.validation.Valid;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.syzton.sunread.dto.bookshelf.BookInShelfDTO;
import com.syzton.sunread.dto.bookshelf.BookshelfStatisticsDTO;
import com.syzton.sunread.dto.bookshelf.BookshelfStatisticsDTO.VerifiedBook;
import com.syzton.sunread.dto.common.PageResource;
import com.syzton.sunread.exception.bookshelf.BookInShelfDuplicateVerifiedException;
import com.syzton.sunread.model.book.Book;
import com.syzton.sunread.model.book.Dictionary;
import com.syzton.sunread.model.book.DictionaryType;
import com.syzton.sunread.model.bookshelf.BookInShelf;
import com.syzton.sunread.model.semester.Semester;
import com.syzton.sunread.service.book.BookService;
import com.syzton.sunread.service.book.DictionaryService;
import com.syzton.sunread.service.bookshelf.BookInShelfService;
import com.syzton.sunread.service.semester.SemesterService;
/**
* @author Morgan-Leon
*/
@Controller
@RequestMapping(value = "/api")
public class BookInShelfController {
private static final Logger LOGGER = LoggerFactory.getLogger(BookshelfController.class);
private BookInShelfService service;
private SemesterService semesterService;
private BookService bookService;
private DictionaryService dictionaryService;
@Autowired
public BookInShelfController(BookInShelfService service){
this.service = service;
}
@Autowired
public void SemesterServiceController(SemesterService semesterService){
this.semesterService = semesterService;
}
@Autowired
public void BookController(BookService bookService){
this.bookService = bookService;
}
@Autowired
public void DictionaryController(DictionaryService dictionaryService){
this.dictionaryService = dictionaryService;
}
//Add a Book to bookshelf
@RequestMapping(value = "/bookshelf/{id}/books/{bookId}/bookinshelf", method = RequestMethod.POST)
@ResponseBody
public BookInShelfDTO add(@Valid @RequestBody BookInShelfDTO dto
,@PathVariable("id")Long id, @PathVariable("bookId")Long bookId ) {
LOGGER.debug("Adding a new book to shelf entry with information: {}", dto);
BookInShelf added = service.add(dto,id, bookId);
return added.createDTO();
}
//Delete a book in shelf
@RequestMapping(value = "/bookinshelf/{id}", method = RequestMethod.DELETE)
@ResponseBody
public BookInShelfDTO deleteById(@PathVariable("id") Long id) throws NotFoundException {
LOGGER.debug("Deleting a book in shelf entry with id: {}", id);
BookInShelf deleted = service.deleteById(id);
LOGGER.debug("Deleted book in shelf entry with information: {}", deleted);
return deleted.createDTO();
}
//Delete a book in shelf
@RequestMapping(value = "/bookshelf/{bookshelfId}/books/{bookId}/bookinshelf", method = RequestMethod.DELETE)
@ResponseBody
public BookInShelfDTO deleteByStudentIdAndBookId(@PathVariable("bookshelfId")Long bookshelfId, @PathVariable("bookId")Long bookId) throws NotFoundException, BookInShelfDuplicateVerifiedException {
LOGGER.debug("Deleting a book in shelf entry with id: {}", bookshelfId);
//Boolean update = service.updateReadState(bookshelfId, bookId);
BookInShelf deleted = service.deleteByBookshelfIdAndBookId(bookshelfId, bookId);
LOGGER.debug("Deleted book in shelf entry with information: {}", deleted);
return deleted.createDTO();
}
//Update a book in shelf
@RequestMapping(value = "/bookinshelf/{id}", method = RequestMethod.PUT)
@ResponseBody
public BookInShelfDTO update(@Valid @RequestBody BookInShelfDTO dto,@PathVariable("id") long id) throws NotFoundException {
LOGGER.debug("Adding a new book to shelf entry with information: {}", dto);
BookInShelf updated = service.update(dto,id);
LOGGER.debug("Added a to-do entry with information: {}", updated);
return updated.createDTO();
}
//Get all books in shelf
@RequestMapping(value = "/bookshelf/{id}/bookinshelf", method = RequestMethod.GET)
@ResponseBody
public PageResource<BookInShelf> findAllBooks(@PathVariable("id") long id,
@RequestParam("page") int page,
@RequestParam("size") int size,
@RequestParam("sortBy") String sortBy) throws NotFoundException {
LOGGER.debug("Finding books in shelf entry with id: {}" );
sortBy = sortBy==null?"id": sortBy;
Pageable pageable = new PageRequest(page,size,new Sort(sortBy));
Page<BookInShelf> pageResult = service.findByBookshelfId(pageable,id);
return new PageResource<>(pageResult,"page","size");
}
//Get a Book in bookshelf
@RequestMapping(value = "/bookinshelf/{id}", method = RequestMethod.GET)
@ResponseBody
public BookInShelfDTO findById(@PathVariable("id") Long id) throws NotFoundException {
LOGGER.debug("Finding a book in shelf entry with id: {}", id);
BookInShelf found = service.findById(id);
LOGGER.debug("Found to-do entry with information: {}", found);
return found.createDTO();
}
//Get a Book in bookshelf
@RequestMapping(value = "/bookshelf/{id}/books/{bookId}/bookinshelf", method = RequestMethod.GET)
@ResponseBody
public BookInShelfDTO findByStudentIdAndBookId(@PathVariable("id") Long id,@PathVariable("bookId") Long bookId) throws NotFoundException {
LOGGER.debug("Finding a book in shelf entry with id: {}", id);
BookInShelf found = service.findByStudentIdAndBookId(id, bookId);
if(found.getDeleted())
throw new com.syzton.sunread.exception.common.NotFoundException("The book with name "+found.getBookName()+"had been deleted.");
return found.createDTO();
}
//Get a Book in bookshelf
@RequestMapping(value = "/student/{studentId}/semester/{semesterId}/bookshelfStatistics", method = RequestMethod.GET)
@ResponseBody
public BookshelfStatisticsDTO findBySemester(@PathVariable("studentId") Long studentId,@PathVariable("semesterId") Long semesterId) throws NotFoundException {
LOGGER.debug("Finding a book in shelf entry with id: {}", semesterId);
Semester semester = semesterService.findOne(semesterId);
DateTime startTime = semester.getStartTime();
DateTime endTime = semester.getEndTime();
ArrayList<BookInShelf> founds = service.findByStudentIdAndSemester(studentId, startTime,endTime);
LOGGER.debug("Found to-do entry with information: {}", founds);
return createBookshelfStatisticsDTO(founds, startTime, endTime);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public BookshelfStatisticsDTO createBookshelfStatisticsDTO(ArrayList<BookInShelf> booksInShelves, DateTime startTime, DateTime endTime) {
// Initlizate the dto entity
BookshelfStatisticsDTO dto = new BookshelfStatisticsDTO();
int startMonth = startTime.getMonthOfYear();
int endMonth = endTime.getMonthOfYear();
int monthCount = endMonth - startMonth + ( startMonth < endMonth ? 0 : 12 ) + 1;
dto.monthlyVerifiedNums = new int[monthCount];
dto.monthlyPoints = new int[monthCount];
dto.semesterVerified = new ArrayList<VerifiedBook>();
dto.semesterReadNum = 0;
// Initlizate monthlyVerifiedNums and monthlyPoints
for ( int i = 0; i < monthCount; i ++ ){
dto.monthlyVerifiedNums[i] = 0;
dto.monthlyPoints[i] = 0;
}
// Initlizate the categoriesMap
List<Dictionary> categories = dictionaryService.findByType(DictionaryType.CATEGORY);
Map categoriesMap = new HashMap<Integer, String>();
for ( Dictionary category : categories ){
categoriesMap.put( category.getValue(), category.getName() );
}
// Calculate the dto
for ( BookInShelf bookInShelf : booksInShelves ) {
// Update semesterReadNum
dto.semesterReadNum ++;
// Check if bookInShelf is verified
if ( bookInShelf.getReadState() == true ) {
// The index in both arrays
int index = bookInShelf.getVerifiedTime().getMonthOfYear() - startMonth;
if ( index < 0 ) { index += 12; }
// Update monthlyVerifiedNums
dto.monthlyVerifiedNums[index] ++;
// Update monthlyPoints
dto.monthlyPoints[index] += bookInShelf.getPoint();
// Update the semesterVerified
VerifiedBook verifiedBook = dto.new VerifiedBook();
Book book = bookService.findById(bookInShelf.getBookId());
verifiedBook.bookName = bookInShelf.getBookName();
verifiedBook.author = book.getAuthor();
verifiedBook.wordCount = book.getWordCount();
verifiedBook.point = bookInShelf.getPoint();
verifiedBook.verifiedTime = bookInShelf.getVerifiedTime();
int categoryId = book.getExtra().getCategory();
verifiedBook.category = (String) categoriesMap.get(categoryId);
dto.semesterVerified.add(verifiedBook);
}
}
return dto;
}
public int bookNumDuration(ArrayList<BookInShelf> booksInShelfs, DateTime fromDate, DateTime toDate){
int count = 0;
for (BookInShelf bookInShelf : booksInShelfs) {
if( bookInShelf.getVerifiedTime() != null && isInDuration(bookInShelf.getVerifiedTime(), fromDate, toDate))
count++;
}
return count;
}
public int bookPointsDuration(ArrayList<BookInShelf> bookInShelfs, DateTime fromDate, DateTime toDate) {
int points = 0;
for (BookInShelf bookInShelf : bookInShelfs) {
if(bookInShelf.getVerifiedTime() != null && isInDuration(bookInShelf.getVerifiedTime(), fromDate, toDate))
points+= bookInShelf.getPoint();
}
return points;
}
public boolean isInDuration(DateTime currentTime,DateTime fromDate, DateTime toDate){
if (currentTime.isAfter(fromDate.getMillis())&¤tTime.isBefore(toDate.getMillis())) {
return true;
}
else {
return false;
}
}
} | unlicense |
ThreaT/blink | front/src/main/java/cool/blink/front/html/attribute/Value.java | 255 | package cool.blink.front.html.attribute;
import cool.blink.front.FrontContent;
import cool.blink.front.html.Attribute;
public class Value extends Attribute {
public Value(final String property) {
super(new FrontContent(property));
}
}
| unlicense |
mr678/spg | core/src/main/java/com/tech11/spg/Main.java | 1442 | package com.tech11.spg;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Locale;
public class Main {
public static void main(String... args) throws IOException {
if (args.length != 3) {
System.err.println("Please use SPG with java -jar spg.jar <TEMPLATE_FOLDER> <TARGET_FOLDER> <MASTERLANGUAGE> <SINGLETARGETLANGUAGE>");
System.exit(1);
}
String templateFolder = convertIntoAbsolutePath(args[0]);
String targetFolder = convertIntoAbsolutePath(args[1]);
Locale locale = new Locale(args[2]);
SystemConfiguration.instance().setTemplateFolder(templateFolder);
SystemConfiguration.instance().setTargetFolder(targetFolder);
SystemConfiguration.instance().setLocale(locale);
// String folderPath =
// "D:\\hero\\workspace-neon\\spg\\src\\test\\resources";
// String outputPath =
// "D:\\hero\\workspace-neon\\spg\\src\\test\\resources\\de";
StaticPageGenerator spg = new StaticPageGenerator()
.setTemplateFolder(templateFolder)
.setTargetFolder(targetFolder)
.setMasterLanguage(locale);
spg.run();
if (System.getProperty("spg.watch") == null)
return;
Path dir = Paths.get(templateFolder);
new WatchDir(dir, true).processEvents(spg);
}
static String convertIntoAbsolutePath(String path) {
if (path.contains(":") || path.startsWith("/"))
return path;
return new File(path).getAbsolutePath();
}
}
| unlicense |
Egga/katas | modules/tic_tac_toe/src/test/java/de/egga/GameTest.java | 702 | package de.egga;
import org.junit.Ignore;
import org.junit.Test;
import static de.egga.Position.CENTER;
import static org.assertj.core.api.Assertions.assertThat;
public class GameTest {
@Test
public void it_should_have_no_winner_before_first_move() {
Game game = new Game();
assertThat(game.getStatus()).isNull();
}
@Test
@Ignore
public void itName2() {
Game game = new Game();
moveSequence(game, CENTER);
assertThat(game.getStatus()).isEqualTo("Player One");
}
private void moveSequence(Game game, Position... positions) {
for (Position position : positions) {
game.move(position);
}
}
}
| unlicense |
mariusj/contests | srm586/src/TeamsSelection.java | 3227 |
public class TeamsSelection
{
public String simulate(int[] preference1, int[] preference2)
{
char[] res = new char[preference1.length];
boolean[] taken = new boolean[preference1.length];
int first = 0;
int second = 0;
for (int i=0; i<preference1.length; i++) {
int p = -1;
while (p==-1 || taken[p]) {
p = i % 2 == 0 ? preference1[first++] : preference2[second++];
p--;
}
res[p] = i % 2 == 0 ? '1' : '2';
taken[p] = true;
}
return new String(res);
}
public static void main(String[] args)
{
long time;
String answer;
boolean errors = false;
String desiredAnswer;
time = System.currentTimeMillis();
answer = new TeamsSelection().simulate(new int[]{1, 2, 3, 4}, new int[]{1, 2, 3, 4});
System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds");
desiredAnswer = "1212";
System.out.println("Your answer:");
System.out.println("\t\"" + answer + "\"");
System.out.println("Desired answer:");
System.out.println("\t\"" + desiredAnswer + "\"");
if (!answer.equals(desiredAnswer))
{
errors = true;
System.out.println("DOESN'T MATCH!!!!");
}
else
System.out.println("Match :-)");
System.out.println();
time = System.currentTimeMillis();
answer = new TeamsSelection().simulate(new int[]{3, 2, 1}, new int[]{1, 3, 2});
System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds");
desiredAnswer = "211";
System.out.println("Your answer:");
System.out.println("\t\"" + answer + "\"");
System.out.println("Desired answer:");
System.out.println("\t\"" + desiredAnswer + "\"");
if (!answer.equals(desiredAnswer))
{
errors = true;
System.out.println("DOESN'T MATCH!!!!");
}
else
System.out.println("Match :-)");
System.out.println();
time = System.currentTimeMillis();
answer = new TeamsSelection().simulate(new int[]{6, 1, 5, 2, 3, 4}, new int[]{1, 6, 3, 4, 5, 2});
System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds");
desiredAnswer = "212211";
System.out.println("Your answer:");
System.out.println("\t\"" + answer + "\"");
System.out.println("Desired answer:");
System.out.println("\t\"" + desiredAnswer + "\"");
if (!answer.equals(desiredAnswer))
{
errors = true;
System.out.println("DOESN'T MATCH!!!!");
}
else
System.out.println("Match :-)");
System.out.println();
time = System.currentTimeMillis();
answer = new TeamsSelection().simulate(new int[]{8, 7, 1, 2, 4, 5, 6, 3, 9}, new int[]{7, 2, 4, 8, 1, 5, 9, 6, 3});
System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds");
desiredAnswer = "121121212";
System.out.println("Your answer:");
System.out.println("\t\"" + answer + "\"");
System.out.println("Desired answer:");
System.out.println("\t\"" + desiredAnswer + "\"");
if (!answer.equals(desiredAnswer))
{
errors = true;
System.out.println("DOESN'T MATCH!!!!");
}
else
System.out.println("Match :-)");
System.out.println();
if (errors)
System.out.println("Some of the test cases had errors :-(");
else
System.out.println("You're a stud (at least on the test data)! :-D ");
}
}
//Powered by [KawigiEdit] 2.0! | unlicense |
fmottard/spanish-quizz-service | src/main/java/com/github/fmottard/spanish/dto/GenericAnswer.java | 394 | package com.github.fmottard.spanish.dto;
import java.time.LocalDateTime;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class GenericAnswer<T> {
private String answer;
private LocalDateTime answerTime;
private T question;
private int score;
public GenericAnswer(T question){
this.question = question;
answerTime = LocalDateTime.now();
}
}
| unlicense |
JorgeVector/OfertaGuiadaVector | src/main/java/com/isb/og/wsdl/ofegui/ComIsbSanoguServiciosdirogEFCbBuscGestoraFISType.java | 3138 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.06.05 at 02:19:47 PM CEST
//
package com.isb.og.wsdl.ofegui;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for com.isb.sanogu.serviciosdirog.e.f.cb.BuscGestoraFI_S_Type complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="com.isb.sanogu.serviciosdirog.e.f.cb.BuscGestoraFI_S_Type">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="listaGestora" type="{http://www.isban.es/webservices/SANOGU/Serviciosdirog_e/F_sanogu_serviciosdirog_e/cbTypes/v1}com.isb.sanogu.serviciosdirog.e.f.cb.ListaGestoraFI_Type" minOccurs="0"/>
* <element name="repos" type="{http://www.isban.es/webservices/SANOGU/Serviciosdirog_e/F_sanogu_serviciosdirog_e/cbTypes/v1}com.isb.sanogu.serviciosdirog.e.f.cb.Pag_S_BuscGestFI_Type" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "com.isb.sanogu.serviciosdirog.e.f.cb.BuscGestoraFI_S_Type", propOrder = {
"listaGestora",
"repos"
})
public class ComIsbSanoguServiciosdirogEFCbBuscGestoraFISType {
protected ComIsbSanoguServiciosdirogEFCbListaGestoraFIType listaGestora;
protected ComIsbSanoguServiciosdirogEFCbPagSBuscGestFIType repos;
/**
* Gets the value of the listaGestora property.
*
* @return
* possible object is
* {@link ComIsbSanoguServiciosdirogEFCbListaGestoraFIType }
*
*/
public ComIsbSanoguServiciosdirogEFCbListaGestoraFIType getListaGestora() {
return listaGestora;
}
/**
* Sets the value of the listaGestora property.
*
* @param value
* allowed object is
* {@link ComIsbSanoguServiciosdirogEFCbListaGestoraFIType }
*
*/
public void setListaGestora(ComIsbSanoguServiciosdirogEFCbListaGestoraFIType value) {
this.listaGestora = value;
}
/**
* Gets the value of the repos property.
*
* @return
* possible object is
* {@link ComIsbSanoguServiciosdirogEFCbPagSBuscGestFIType }
*
*/
public ComIsbSanoguServiciosdirogEFCbPagSBuscGestFIType getRepos() {
return repos;
}
/**
* Sets the value of the repos property.
*
* @param value
* allowed object is
* {@link ComIsbSanoguServiciosdirogEFCbPagSBuscGestFIType }
*
*/
public void setRepos(ComIsbSanoguServiciosdirogEFCbPagSBuscGestFIType value) {
this.repos = value;
}
}
| unlicense |
6tail/nlf | src/nc/liat6/frame/json/wrapper/AbstractJsonWrapper.java | 815 | package nc.liat6.frame.json.wrapper;
import nc.liat6.frame.json.JSON;
public abstract class AbstractJsonWrapper implements IJsonWrapper{
/** 是否极简(不缩进不换行) */
protected boolean tiny;
/** 字符串首尾的引号 */
protected String quote;
/** 数字是否使用引号 */
protected boolean numberQuoted;
protected AbstractJsonWrapper(){
this(JSON.tiny,JSON.quote,JSON.numberQuoted);
}
/**
* 构造包装器
*
* @param tiny 是否极简(不缩进不换行)
* @param quote 字符串首尾的引号
* @param numberQuoted 数字是否使用引号
*/
protected AbstractJsonWrapper(boolean tiny,String quote,boolean numberQuoted){
this.tiny = tiny;
this.quote = quote;
this.numberQuoted = numberQuoted;
}
} | unlicense |
clilystudio/NetBook | allsrc/android/support/v4/view/ScrollingView.java | 583 | package android.support.v4.view;
public abstract interface ScrollingView
{
public abstract int computeHorizontalScrollExtent();
public abstract int computeHorizontalScrollOffset();
public abstract int computeHorizontalScrollRange();
public abstract int computeVerticalScrollExtent();
public abstract int computeVerticalScrollOffset();
public abstract int computeVerticalScrollRange();
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: android.support.v4.view.ScrollingView
* JD-Core Version: 0.6.0
*/ | unlicense |
clilystudio/NetBook | allsrc/com/umeng/update/j.java | 1010 | package com.umeng.update;
import android.content.Context;
final class j
implements Runnable
{
private Context a;
public j(Context paramContext)
{
this.a = paramContext;
}
public final void run()
{
try
{
localUpdateResponse = new n(this.a).a();
if (localUpdateResponse == null)
{
b.a(3, null);
return;
}
if (!localUpdateResponse.hasUpdate)
{
b.a(1, localUpdateResponse);
return;
}
}
catch (Exception localException)
{
UpdateResponse localUpdateResponse;
b.a(1, null);
u.a.b.a("update", "request update error", localException);
return;
b.a(0, localUpdateResponse);
return;
}
catch (Error localError)
{
u.a.b.a("update", "request update error" + localError.getMessage());
}
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.umeng.update.j
* JD-Core Version: 0.6.0
*/ | unlicense |
clilystudio/NetBook | allsrc/com/ushaqi/zhuishushenqi/widget/NicknameEditText.java | 759 | package com.ushaqi.zhuishushenqi.widget;
import android.content.Context;
import android.text.InputFilter;
import android.util.AttributeSet;
import android.widget.EditText;
public class NicknameEditText extends EditText
{
public NicknameEditText(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramContext, paramAttributeSet);
}
protected void onFinishInflate()
{
super.onFinishInflate();
InputFilter[] arrayOfInputFilter = new InputFilter[1];
arrayOfInputFilter[0] = new aj(this, 0);
setFilters(arrayOfInputFilter);
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ushaqi.zhuishushenqi.widget.NicknameEditText
* JD-Core Version: 0.6.0
*/ | unlicense |
delimce/frameworkj6ee | src/java/com/siclhos/controller/ExampleController.java | 591 | package com.siclhos.controller;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.*;
import org.zkoss.zul.*;
public class ExampleController extends SelectorComposer<Component> {
private static final long serialVersionUID = 1L;
@Wire
private Textbox keywordBox;
@Wire
private Listbox carListbox;
@Wire
private Label modelLabel;
@Wire
private Label makeLabel;
@Wire
private Label priceLabel;
@Wire
private Label descriptionLabel;
@Wire
private Image previewImage;
}
| unlicense |
codeApeFromChina/resource | frame_packages/java_libs/hibernate-distribution-3.6.10.Final/project/hibernate-core/src/main/java/org/hibernate/id/enhanced/AccessCallback.java | 1526 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions 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 distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.id.enhanced;
import org.hibernate.id.IntegralDataTypeHolder;
/**
* Contract for providing callback access to a {@link DatabaseStructure},
* typically from the {@link Optimizer}.
*
* @author Steve Ebersole
*/
public interface AccessCallback {
/**
* Retrieve the next value from the underlying source.
*
* @return The next value.
*/
public IntegralDataTypeHolder getNextValue();
}
| unlicense |
baowp/test-sample | src/main/java/com/iteye/baowp/netty/handler/TimeServerHandler.java | 1207 | package com.iteye.baowp.netty.handler;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created with IntelliJ IDEA.
* User: baowp
* Date: 12/30/13
* Time: 11:05 AM
*/
public class TimeServerHandler extends SimpleChannelHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
Channel ch = e.getChannel();
ChannelBuffer time = ChannelBuffers.buffer(4);
int message= ((int) (System.currentTimeMillis() / 1000L));
logger.info("channelConnected,wrote {} as message", message);
time.writeInt(message);
// time.writeShort(message>>16&0xff);
// time.writeShort(message&0xff);
ChannelFuture f = ch.write(time); //will waiting until client received
f.addListener(ChannelFutureListener.CLOSE);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
e.getCause().printStackTrace();
e.getChannel().close();
}
}
| unlicense |
WuSicheng54321/Thinking-in-Java-4th | ThinkingInJava18/src/TestObjectStream.java | 996 | import java.io.*;
public class TestObjectStream {
public static void main(String[] args) {
T t=new T();
t.d=100;
try {
FileOutputStream fos=new FileOutputStream("/home/wusicheng/workspace/the.txt");
ObjectOutputStream ops=new ObjectOutputStream(fos);
ops.writeObject(t);
ops.flush();
ops.close();
FileInputStream fis=new FileInputStream("/home/wusicheng/workspace/the.txt");
ObjectInputStream oos=new ObjectInputStream(fis);
T t1=(T) oos.readObject();
System.out.println(t1.d);
System.out.println(t1.x);
System.out.println(t1.y);
System.out.println(t1.z);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class T implements Serializable{
int x=10;
int y=19;
int z=103;
double d=10.9;
}
| apache-2.0 |
JunGeges/PangCi | app/src/main/java/com/hasee/pangci/activity/MainActivity.java | 20873 | package com.hasee.pangci.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.hasee.pangci.Common.DataCleanManagerUtils;
import com.hasee.pangci.Common.DateFormat;
import com.hasee.pangci.Common.MessageEvent;
import com.hasee.pangci.Common.MessageEvent2;
import com.hasee.pangci.Common.MessageEventNotice;
import com.hasee.pangci.R;
import com.hasee.pangci.adapter.MyFragmentPagerAdapter;
import com.hasee.pangci.bean.Notice;
import com.hasee.pangci.bean.User;
import com.hasee.pangci.fragment.AnimeFragment;
import com.hasee.pangci.fragment.MemberFragment;
import com.hasee.pangci.fragment.MovieFragment;
import com.hasee.pangci.fragment.NetdiskFragment;
import com.hasee.pangci.fragment.RecommendFragment;
import com.hasee.pangci.widget.FadeInTextView;
import com.tencent.bugly.beta.Beta;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.crud.DataSupport;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
@BindView(R.id.main_tab_layout)
TabLayout mTabLayout;
@BindView(R.id.main_tool_bar)
Toolbar mToolbar;
@BindView(R.id.main_view_pager)
ViewPager mViewPager;
@BindView(R.id.main_navigation_view)
NavigationView mNavigationView;
@BindView(R.id.main_drawer_layout)
DrawerLayout mDrawerLayout;
@BindView(R.id.main_fab)
FloatingActionButton mFloatingActionButton;
@BindView(R.id.tv_marquee)
TextView mNoticeTextView;
private MemberFragment memberFragment = new MemberFragment();
private RecommendFragment recommendFragment = new RecommendFragment();
private MovieFragment movieFragment = new MovieFragment();
private AnimeFragment animeFragment = new AnimeFragment();
private NetdiskFragment netdiskFragment = new NetdiskFragment();
private String[] tabTitles = {"推荐", "影视", "腐漫", "网盘", "VIP专区"};
private Fragment[] fragments = {recommendFragment, movieFragment, animeFragment, netdiskFragment, memberFragment};
private ArrayList<Fragment> fragmentArrayList = new ArrayList<>();
private View mNavigationMemberInfoLl;
private TextView mNavigationAccountTv;
private TextView mNavigationMemberLevelTv;
private TextView mNavigationResidueTv;
private CircleImageView mHeadCIV;
private User mUserInfo = new User();//用户信息
private boolean isLogin;//判断用户是否登录
private SharedPreferences mLogin_info;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);//禁止截屏
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
EventBus.getDefault().register(this);
initView();
initData();
checkIsLogin();//判断之前是否登录,如果登录直接进
}
public void initView() {
mNavigationView.setNavigationItemSelectedListener(this);
mFloatingActionButton.setOnClickListener(this);
//初始化公告栏
Notice notice = DataSupport.findLast(Notice.class);
if (notice == null) {
mNoticeTextView.setText(getString(R.string.notice));
} else {
mNoticeTextView.setText(notice.getNotice());
}
}
public void initData() {
mToolbar.setTitle("胖次");
for (int i = 0; i < tabTitles.length; i++) {
fragmentArrayList.add(fragments[i]);
}
//关联彼此
MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentArrayList);
mViewPager.setAdapter(myFragmentPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
//初始化数据
for (int i = 0; i < tabTitles.length; i++) {
mTabLayout.getTabAt(i).setText(tabTitles[i]);
}
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(Gravity.LEFT);
}
});
//初始化导航栏的控件
View headerView = mNavigationView.getHeaderView(0);
mNavigationMemberInfoLl = headerView.findViewById(R.id.navigation_member_info_ll);//会员信息布局
mNavigationAccountTv = (TextView) headerView.findViewById(R.id.navigation_account_tv);
mNavigationAccountTv.setOnClickListener(this);
mNavigationMemberLevelTv = (TextView) headerView.findViewById(R.id.navigation_member_level_tv);//会员等级
//会员剩余天数
mNavigationResidueTv = (TextView) headerView.findViewById(R.id.navigation_residue_tv);
mHeadCIV = (CircleImageView) headerView.findViewById(R.id.navigation_header_icon_civ);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_menu_item_info:
if (mLogin_info != null) {
boolean isLogin = mLogin_info.getBoolean("isLogin", false);
if (isLogin) {
Intent intents = new Intent(MainActivity.this, NotificationActivity.class);
intents.setFlags(0);
startActivity(intents);
} else {
Toast.makeText(this, "您暂未登录!", Toast.LENGTH_SHORT).show();
}
}
break;
case R.id.navigation_menu_item_cache:
try {
DataCleanManagerUtils.clearAllCache(this);
Toast.makeText(MainActivity.this, "缓存清除成功!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.navigation_menu_item_exit:
if (mLogin_info.getBoolean("isLogin", false)) {
//清除账号缓存信息
DataCleanManagerUtils.cleanSharedPreference(this, "LOGIN_INFO");
//清除手势锁的缓存信息
DataCleanManagerUtils.cleanSharedPreference(this, "LOCK_INFO");
mNavigationMemberInfoLl.setVisibility(View.GONE);//隐藏会员信息布局
mNavigationAccountTv.setText("点击登录");
mHeadCIV.setImageResource(R.drawable.normal_login);
isLogin = false;
if (mLogin_info != null) {//注销--》更新登录状态
SharedPreferences.Editor edit = mLogin_info.edit();
edit.putBoolean("isLogin", false);
edit.apply();
}
}
break;
case R.id.navigation_menu_item_flock:
if (!mLogin_info.getBoolean("isLogin", false)) {
Toast.makeText(this, "您暂未登录!", Toast.LENGTH_SHORT).show();
} else if (mLogin_info.getString("memberLevel", "青铜").equals("青铜")) {
Toast.makeText(this, "请先升级会员", Toast.LENGTH_SHORT).show();
} else if (!mLogin_info.getString("memberLevel", "青铜").equals("钻石")) {
Toast.makeText(this, "钻石会员才能加入云群!", Toast.LENGTH_LONG).show();
} else {
//弹窗引导去反馈
showDialog();
}
break;
case R.id.navigation_menu_item_version:
Beta.checkUpgrade();
break;
case R.id.navigation_menu_item_member:
Intent intent = new Intent(MainActivity.this, MemberCenterActivity.class);
if (!isLogin) {
//未登录
intent.setFlags(0);//未登录
Toast.makeText(this, "您暂未登录!", Toast.LENGTH_SHORT).show();
} else {
intent.setFlags(1);//登录
Bundle bundle = new Bundle();
bundle.putSerializable("user", mUserInfo);
intent.putExtras(bundle);
}
startActivity(intent);
break;
case R.id.navigation_menu_item_integral:
//积分
if (mLogin_info != null) {
User user = new User();
boolean isLogin = mLogin_info.getBoolean("isLogin", false);
user.setUserIntegral(mLogin_info.getString("integral", ""));
user.setUserAccount(mLogin_info.getString("account", ""));
user.setUserHeadImg(mLogin_info.getInt("headImg", R.drawable.normal_login));
if (isLogin) {
Intent intents = new Intent(MainActivity.this, IntegralActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("user", user);
intents.putExtras(bundle);
startActivity(intents);
} else {
Toast.makeText(this, "您暂未登录!", Toast.LENGTH_SHORT).show();
}
}
break;
case R.id.navigation_menu_item_lock:
if (mLogin_info != null) {
boolean isLogin = mLogin_info.getBoolean("isLogin", false);
if (isLogin) {
Intent intent1 = new Intent(MainActivity.this, LockActivity.class);
startActivity(intent1);
} else {
Toast.makeText(this, "您暂未登录!", Toast.LENGTH_SHORT).show();
}
}
break;
}
return false;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.navigation_account_tv:
if (mNavigationAccountTv.getText().toString().equals("点击登录")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
mDrawerLayout.closeDrawers();
} else {
Toast.makeText(this, "您已经登录!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.main_fab:
mDrawerLayout.openDrawer(Gravity.LEFT);
break;
}
}
@Subscribe(threadMode = ThreadMode.MAIN)//默认优先级为0
public void handleEvent(MessageEvent event) {
//区分哪里发来的事件
if (!event.getFlag().equals("login")) {
return;
}
User user = event.getUser();
mUserInfo = user;
isLogin = mLogin_info.getBoolean("isLogin", false);
mNavigationMemberInfoLl.setVisibility(View.VISIBLE);
if (user.getMemberLevel().equals("青铜")) {
//普通会员
mHeadCIV.setImageResource(user.getUserHeadImg());
mNavigationAccountTv.setText(user.getUserAccount());
mNavigationMemberLevelTv.setText("会员等级:" + user.getMemberLevel());
mNavigationResidueTv.setVisibility(View.GONE);
} else {
//充值会员
mHeadCIV.setImageResource(user.getUserHeadImg());
mNavigationAccountTv.setText(user.getUserAccount());
mNavigationMemberLevelTv.setText("会员等级:" + user.getMemberLevel());
mNavigationResidueTv.setVisibility(View.VISIBLE);
int residueDays = DateFormat.differentDaysByMillisecond(getCurrentDate(), user.getMemberEndDate().getDate());
if (residueDays <= 0) {
mNavigationResidueTv.setText("您的会员已到期");
SharedPreferences.Editor edit = mLogin_info.edit();
edit.putBoolean("isExpire", true);
edit.apply();
} else {
mNavigationResidueTv.setText("会员剩余天数:" + residueDays + "天");
}
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void handleEvent(MessageEvent2 event2) {
//存到本地数据库
Notice notice = new Notice();
notice.setNotice(event2.getNotice());
notice.save();
mNoticeTextView.setText(event2.getNotice());
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void handleEvent(MessageEventNotice messageEventNotice) {
showPopWindow(messageEventNotice.getContent());
}
private void showPopWindow(String content) {
View view = LayoutInflater.from(this).inflate(R.layout.notice_layout, mDrawerLayout, false);
final PopupWindow popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//设置外部点击消失
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(mDrawerLayout, Gravity.BOTTOM, 0, 0);
FadeInTextView fadeInTextView = (FadeInTextView) view.findViewById(R.id.notice_fade_in_tv);
fadeInTextView.setTextString(content)
.startFadeInAnimation()
.setTextAnimationListener(new FadeInTextView.TextAnimationListener() {
@Override
public void animationFinish() {
Toast.makeText(MainActivity.this, "完毕!", Toast.LENGTH_SHORT).show();
}
});
view.findViewById(R.id.notice_action_tv).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NotificationActivity.class);
startActivity(intent);
popupWindow.dismiss();
}
});
}
private void checkIsLogin() {
mLogin_info = getSharedPreferences("LOGIN_INFO", MODE_PRIVATE);
isLogin = mLogin_info.getBoolean("isLogin", false);
if (!mLogin_info.getString("account", "").equals("")) {
//说明里面有记录
//判断会员等级
mNavigationMemberInfoLl.setVisibility(View.VISIBLE);//显示布局会员信息布局
if (mLogin_info.getString("memberLevel", "青铜").equals("青铜")) {
//普通会员
mHeadCIV.setImageResource(mLogin_info.getInt("headImg", R.drawable.normal_login));
mNavigationAccountTv.setText(mLogin_info.getString("account", ""));
mNavigationMemberLevelTv.setText("会员等级:" + mLogin_info.getString("memberLevel", "青铜"));
mNavigationResidueTv.setVisibility(View.GONE);
mUserInfo.setUserHeadImg(mLogin_info.getInt("headImg", R.drawable.normal_login));
mUserInfo.setMemberLevel(mLogin_info.getString("memberLevel", "青铜"));
mUserInfo.setUserAccount(mLogin_info.getString("account", ""));
} else {
//充值会员
mHeadCIV.setImageResource(mLogin_info.getInt("headImg", R.drawable.normal_login));
mNavigationAccountTv.setText(mLogin_info.getString("account", ""));
mNavigationMemberLevelTv.setText("会员等级:" + mLogin_info.getString("memberLevel", "青铜"));
int residueDays = DateFormat.differentDaysByMillisecond(getCurrentDate(), mLogin_info.getString("memberEndDate", ""));
if (residueDays <= 0) {
mNavigationResidueTv.setText("您的会员已到期");
SharedPreferences.Editor edit = mLogin_info.edit();
edit.putBoolean("isExpire", true);
edit.apply();
} else {
mNavigationResidueTv.setText("会员剩余天数:" + residueDays + "天");
}
mUserInfo.setUserHeadImg(mLogin_info.getInt("headImg", R.drawable.normal_login));
mUserInfo.setMemberLevel(mLogin_info.getString("memberLevel", "青铜"));
mUserInfo.setUserAccount(mLogin_info.getString("account", ""));
}
}
}
private String getCurrentDate() {
//获取当前时间 扣除会员天数
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return simpleDateFormat.format(date);
}
private long tempTime;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//先关闭侧滑
if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
mDrawerLayout.closeDrawers();
return false;
}
if (System.currentTimeMillis() - tempTime > 2000) {
Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
tempTime = System.currentTimeMillis();
return false;
} else {
finish();
System.exit(0);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
super.onDestroy();
//取消注册eventBus
EventBus.getDefault().unregister(this);
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
/**
* 设置内容区域为自定义View
*/
LinearLayout inflate_dialog = (LinearLayout) getLayoutInflater().inflate(R.layout.join_netdisk_dialog, null);
builder.setView(inflate_dialog);
final AlertDialog dialog = builder.create();
dialog.show();
TextView tv_title = (TextView) inflate_dialog.findViewById(R.id.tv_title);
tv_title.setText("加入云群");
TextView tvConfirm = (TextView) inflate_dialog.findViewById(R.id.tv_comfirm);
tvConfirm.setText("去加群");
tvConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NotificationActivity.class);
intent.setFlags(1);
startActivity(intent);
dialog.dismiss();
}
});
}
/* private void showDialogs(String link) {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.ShowDialog);
*//**
* 设置内容区域为自定义View
*//*
View inflate_dialog = getLayoutInflater().inflate(R.layout.action_layout, null);
builder.setView(inflate_dialog);
final AlertDialog dialog = builder.create();
dialog.show();
ImageView actionImageView = (ImageView) inflate_dialog.findViewById(R.id.iv_action);
Glide.with(this).load(link).error(R.drawable.aaa).into(actionImageView);
actionImageView.setImageResource(R.drawable.ic_upper_loading_failed);
ImageView deleteImageView = (ImageView) inflate_dialog.findViewById(R.id.iv_delete);
deleteImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}*/
}
| apache-2.0 |
ibissource/iaf | core/src/test/java/nl/nn/adapterframework/align/TestValidations.java | 1360 | package nl.nn.adapterframework.align;
import static org.junit.Assert.assertEquals;
import java.net.URL;
import org.junit.Test;
import org.w3c.dom.Document;
/**
* @author Gerrit van Brakel
*/
public class TestValidations {
public void validationTest(String namespace, String xsd, String xmlResource, boolean expectValid) throws Exception {
String xmlString = Utils.getTestXml(xmlResource);
URL schemaUrl = Utils.class.getResource(xsd);
assertEquals("valid XML", expectValid, Utils.validate(schemaUrl, xmlString));
Document dom = Utils.string2Dom(xmlString);
assertEquals("valid XML DOM", expectValid, Utils.validate(schemaUrl, dom));
String xml1 = Utils.dom2String1(dom);
assertEquals("valid XML dom2string1", expectValid, Utils.validate(schemaUrl, xml1));
String xml2 = Utils.dom2String2(dom);
assertEquals("valid XML dom2string1", expectValid, Utils.validate(schemaUrl, xml2));
}
@Test
public void testValidToSchema() throws Exception {
// validationTest("http://www.ing.com/testxmlns", "/GetIntermediaryAgreementDetails/xsd/A_correct.xsd","/intermediaryagreementdetails.xml",false,true);
validationTest("urn:test", "/Align/Abc/abc.xsd", "/Align/Abc/abc.xml", true);
}
@Test
public void testNotValidToSchema() throws Exception {
validationTest("urn:test", "/Align/Abc/abc.xsd", "/Align/Abc/acb.xml", false);
}
}
| apache-2.0 |
bluefoot/scripts | utils/src/main/java/info/bluefoot/scripts/threadpool/WorkerPool.java | 4762 | package info.bluefoot.scripts.threadpool;
import java.util.Date;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Thread pool. <br />
* This will create a number of threads that should be given at construction. <br />
* While there's still something to be executed, the threads will work. After that,
* they will not be available anymore (i.e. die). So this is not an "infinite" pool. <br />
* Three steps: <br />
* <ol>
* <li>Instantiate and pass the number of threads in the pool</li>
* <li>{@link WorkerPool#add(Runnable)} how many {@link Runnable} instances you want to be executed</li>
* <li>Start the execution by firing {@link WorkerPool#execute()}</li>
* </ol>
* <em>NOTE: you can't add anymore instances after the {@link WorkerPool#execute()}
* method starts.</em> <br />
* Initially based on <a href="http://www.ibm.com/developerworks/library/j-jtp0730/index.html">this article</a>.
*
*
* @author gewton
*
*/
public class WorkerPool {
private final int nThreads;
private final PoolWorker[] threads;
private final LinkedList<Runnable> queue;
private boolean started = false;
private Runnable finishedCallback;
protected static final Logger logger = LoggerFactory.getLogger(WorkerPool.class);
/**
* Constructs a Worker with a max number of threads. If there's more jobs
* than threads, some waiting will eventually occour.
* @param poolSize the number of threads
*/
public WorkerPool(int poolSize) {
logger.info(String.format("Starting pool with %s threads", poolSize));
this.nThreads = poolSize;
queue = new LinkedList<Runnable>();
threads = new PoolWorker[poolSize];
}
/**
* Adds a job to the execution queue.
* @param r a job to be added
* @throws RuntimeException in case of the execution already begun.
* @see Runnable
*/
public void add(Runnable r) {
if(started) {
throw new RuntimeException("Can't add anymore jobs at this pont. The execution has already started.");
}
synchronized (queue) {
logger.info(String.format("Adding a job to the queue"));
queue.addLast(r);
}
}
/**
* Start the execution of the jobs
*/
public void execute() {
started = true;
final Date initialTime = new Date();
for (int i = 0; i < nThreads; i++) {
threads[i] = new PoolWorker();
logger.info(String.format("Starting thread %s, id:%s", i, threads[i].getId()));
threads[i].start();
}
new Thread(new Runnable() {
@Override
public void run() {
while(stillSomethingAlive()) {}
long time = (System.currentTimeMillis() - initialTime.getTime())/1000;
logger.info(String.format("Finished after %s seconds", String.valueOf(time)));
if(finishedCallback!=null)
new Thread(finishedCallback).run();
}
}).start();
}
/**
* Checks if there is still some active thread
* @return true if there is any thread still alive or false otherwise
* @see Thread#isAlive()
*/
private boolean stillSomethingAlive() {
for (int i = 0; i < nThreads; i++) {
if(threads[i].isAlive()) {
return true;
}
}
return false;
}
public void setFinishedCallback(Runnable r) {
this.finishedCallback=r;
}
private class PoolWorker extends Thread {
public void run() {
Runnable r;
int times = 0;
if(logger.isDebugEnabled()) {
logger.debug(String.format("Thread %s started its execution", this.getId()));
}
while (true) {
synchronized (queue) {
if (queue.isEmpty()) {
if(logger.isDebugEnabled()) {
logger.debug(String.format("Queue is empty, thread %s dismissed after running %s times", this.getId(), times));
}
break;
}
r = queue.removeFirst();
times++;
}
if(logger.isDebugEnabled()) {
logger.debug(String.format("Thread %s will run NOW", this.getId()));
}
try {
r.run();
} catch (RuntimeException e) {
logger.error("Error while executing thread " + this.getId(), e);
}
}
}
}
} | apache-2.0 |
consulo/consulo-python | python-impl/src/main/java/com/jetbrains/python/parsing/StatementParsing.java | 32571 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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.jetbrains.python.parsing;
import java.util.EnumSet;
import java.util.Set;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nullable;
import com.intellij.lang.ITokenTypeRemapper;
import com.intellij.lang.PsiBuilder;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.text.CharArrayUtil;
import com.jetbrains.python.PyElementTypes;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.psi.LanguageLevel;
import com.jetbrains.python.psi.PyElementType;
/**
* @author yole
*/
public class StatementParsing extends Parsing implements ITokenTypeRemapper
{
private static final Logger LOG = Logger.getInstance("#com.jetbrains.python.parsing.StatementParsing");
@NonNls
protected static final String TOK_FUTURE_IMPORT = "__future__";
@NonNls
protected static final String TOK_WITH_STATEMENT = "with_statement";
@NonNls
protected static final String TOK_NESTED_SCOPES = "nested_scopes";
@NonNls
protected static final String TOK_PRINT_FUNCTION = "print_function";
@NonNls
protected static final String TOK_WITH = "with";
@NonNls
protected static final String TOK_AS = "as";
@NonNls
protected static final String TOK_PRINT = "print";
@NonNls
protected static final String TOK_NONE = "None";
@NonNls
protected static final String TOK_TRUE = "True";
@NonNls
protected static final String TOK_DEBUG = "__debug__";
@NonNls
protected static final String TOK_FALSE = "False";
@NonNls
protected static final String TOK_NONLOCAL = "nonlocal";
@NonNls
protected static final String TOK_EXEC = "exec";
@NonNls
protected static final String TOK_ASYNC = "async";
@NonNls
protected static final String TOK_AWAIT = "await";
private static final String EXPRESSION_EXPECTED = "Expression expected";
public static final String IDENTIFIER_EXPECTED = "Identifier expected";
protected enum Phase
{
NONE, FROM, FUTURE, IMPORT
} // 'from __future__ import' phase
private Phase myFutureImportPhase = Phase.NONE;
private boolean myExpectAsKeyword = false;
public enum FUTURE
{
ABSOLUTE_IMPORT, DIVISION, GENERATORS, NESTED_SCOPES, WITH_STATEMENT, PRINT_FUNCTION
}
protected Set<FUTURE> myFutureFlags = EnumSet.noneOf(FUTURE.class);
public static class ImportTypes
{
public final IElementType statement;
public final IElementType element;
public IElementType starElement;
public ImportTypes(IElementType statement, IElementType element, IElementType starElement)
{
this.statement = statement;
this.element = element;
this.starElement = starElement;
}
}
public StatementParsing(ParsingContext context, @Nullable FUTURE futureFlag)
{
super(context);
if(futureFlag != null)
{
myFutureFlags.add(futureFlag);
}
}
private void setExpectAsKeyword(boolean expectAsKeyword)
{
myExpectAsKeyword = expectAsKeyword;
myBuilder.setTokenTypeRemapper(this); // clear cached token type
}
public void parseStatement()
{
while(myBuilder.getTokenType() == PyTokenTypes.STATEMENT_BREAK)
{
myBuilder.advanceLexer();
}
final IElementType firstToken;
firstToken = myBuilder.getTokenType();
if(firstToken == null)
{
return;
}
if(firstToken == PyTokenTypes.WHILE_KEYWORD)
{
parseWhileStatement();
return;
}
if(firstToken == PyTokenTypes.IF_KEYWORD)
{
parseIfStatement(PyTokenTypes.IF_KEYWORD, PyTokenTypes.ELIF_KEYWORD, PyTokenTypes.ELSE_KEYWORD, PyElementTypes.IF_STATEMENT);
return;
}
if(firstToken == PyTokenTypes.FOR_KEYWORD)
{
parseForStatement(myBuilder.mark());
return;
}
if(firstToken == PyTokenTypes.TRY_KEYWORD)
{
parseTryStatement();
return;
}
if(firstToken == PyTokenTypes.DEF_KEYWORD)
{
getFunctionParser().parseFunctionDeclaration(myBuilder.mark(), false);
return;
}
if(firstToken == PyTokenTypes.AT)
{
getFunctionParser().parseDecoratedDeclaration();
return;
}
if(firstToken == PyTokenTypes.CLASS_KEYWORD)
{
parseClassDeclaration();
return;
}
if(firstToken == PyTokenTypes.WITH_KEYWORD)
{
parseWithStatement(myBuilder.mark());
return;
}
if(firstToken == PyTokenTypes.ASYNC_KEYWORD)
{
parseAsyncStatement();
return;
}
parseSimpleStatement();
}
protected void parseSimpleStatement()
{
PsiBuilder builder = myContext.getBuilder();
final IElementType firstToken = builder.getTokenType();
if(firstToken == null)
{
return;
}
if(firstToken == PyTokenTypes.PRINT_KEYWORD && hasPrintStatement())
{
parsePrintStatement(builder);
return;
}
if(firstToken == PyTokenTypes.ASSERT_KEYWORD)
{
parseAssertStatement();
return;
}
if(firstToken == PyTokenTypes.BREAK_KEYWORD)
{
parseKeywordStatement(builder, PyElementTypes.BREAK_STATEMENT);
return;
}
if(firstToken == PyTokenTypes.CONTINUE_KEYWORD)
{
parseKeywordStatement(builder, PyElementTypes.CONTINUE_STATEMENT);
return;
}
if(firstToken == PyTokenTypes.DEL_KEYWORD)
{
parseDelStatement();
return;
}
if(firstToken == PyTokenTypes.EXEC_KEYWORD)
{
parseExecStatement();
return;
}
if(firstToken == PyTokenTypes.GLOBAL_KEYWORD)
{
parseNameDefiningStatement(PyElementTypes.GLOBAL_STATEMENT);
return;
}
if(firstToken == PyTokenTypes.NONLOCAL_KEYWORD)
{
parseNameDefiningStatement(PyElementTypes.NONLOCAL_STATEMENT);
return;
}
if(firstToken == PyTokenTypes.IMPORT_KEYWORD)
{
parseImportStatement(PyElementTypes.IMPORT_STATEMENT, PyElementTypes.IMPORT_ELEMENT);
return;
}
if(firstToken == PyTokenTypes.FROM_KEYWORD)
{
parseFromImportStatement();
return;
}
if(firstToken == PyTokenTypes.PASS_KEYWORD)
{
parseKeywordStatement(builder, PyElementTypes.PASS_STATEMENT);
return;
}
if(firstToken == PyTokenTypes.RETURN_KEYWORD)
{
parseReturnStatement(builder);
return;
}
if(firstToken == PyTokenTypes.RAISE_KEYWORD)
{
parseRaiseStatement();
return;
}
PsiBuilder.Marker exprStatement = builder.mark();
if(builder.getTokenType() == PyTokenTypes.YIELD_KEYWORD)
{
getExpressionParser().parseYieldOrTupleExpression(false);
checkEndOfStatement();
exprStatement.done(PyElementTypes.EXPRESSION_STATEMENT);
return;
}
else if(getExpressionParser().parseExpressionOptional())
{
IElementType statementType = PyElementTypes.EXPRESSION_STATEMENT;
if(PyTokenTypes.AUG_ASSIGN_OPERATIONS.contains(builder.getTokenType()))
{
statementType = PyElementTypes.AUG_ASSIGNMENT_STATEMENT;
builder.advanceLexer();
if(!getExpressionParser().parseYieldOrTupleExpression(false))
{
builder.error(EXPRESSION_EXPECTED);
}
}
else if(atToken(PyTokenTypes.EQ) || (atToken(PyTokenTypes.COLON) && myContext.getLanguageLevel().isPy3K()))
{
exprStatement.rollbackTo();
exprStatement = builder.mark();
getExpressionParser().parseExpression(false, true);
LOG.assertTrue(builder.getTokenType() == PyTokenTypes.EQ || builder.getTokenType() == PyTokenTypes.COLON, builder.getTokenType());
if(builder.getTokenType() == PyTokenTypes.COLON)
{
statementType = PyElementTypes.TYPE_DECLARATION_STATEMENT;
getFunctionParser().parseParameterAnnotation();
}
if(builder.getTokenType() == PyTokenTypes.EQ)
{
statementType = PyElementTypes.ASSIGNMENT_STATEMENT;
builder.advanceLexer();
while(true)
{
PsiBuilder.Marker maybeExprMarker = builder.mark();
final boolean isYieldExpr = builder.getTokenType() == PyTokenTypes.YIELD_KEYWORD;
if(!getExpressionParser().parseYieldOrTupleExpression(false))
{
maybeExprMarker.drop();
builder.error(EXPRESSION_EXPECTED);
break;
}
if(builder.getTokenType() == PyTokenTypes.EQ)
{
if(isYieldExpr)
{
maybeExprMarker.drop();
builder.error("Cannot assign to 'yield' expression");
}
else
{
maybeExprMarker.rollbackTo();
getExpressionParser().parseExpression(false, true);
LOG.assertTrue(builder.getTokenType() == PyTokenTypes.EQ, builder.getTokenType());
}
builder.advanceLexer();
}
else
{
maybeExprMarker.drop();
break;
}
}
}
}
checkEndOfStatement();
exprStatement.done(statementType);
return;
}
else
{
exprStatement.drop();
}
builder.advanceLexer();
reportParseStatementError(builder, firstToken);
}
protected void reportParseStatementError(PsiBuilder builder, IElementType firstToken)
{
if(firstToken == PyTokenTypes.INCONSISTENT_DEDENT)
{
builder.error("Unindent does not match any outer indentation level");
}
else if(firstToken == PyTokenTypes.INDENT)
{
builder.error("Unexpected indent");
}
else
{
builder.error("Statement expected, found " + firstToken.toString());
}
}
private boolean hasPrintStatement()
{
return myContext.getLanguageLevel().hasPrintStatement() && !myFutureFlags.contains(FUTURE.PRINT_FUNCTION);
}
protected void checkEndOfStatement()
{
PsiBuilder builder = myContext.getBuilder();
final ParsingScope scope = getParsingContext().getScope();
if(builder.getTokenType() == PyTokenTypes.STATEMENT_BREAK)
{
builder.advanceLexer();
scope.setAfterSemicolon(false);
}
else if(builder.getTokenType() == PyTokenTypes.SEMICOLON)
{
if(!scope.isSuite())
{
builder.advanceLexer();
scope.setAfterSemicolon(true);
if(builder.getTokenType() == PyTokenTypes.STATEMENT_BREAK)
{
builder.advanceLexer();
scope.setAfterSemicolon(false);
}
}
}
else if(!builder.eof())
{
builder.error("End of statement expected");
}
}
private void parsePrintStatement(final PsiBuilder builder)
{
LOG.assertTrue(builder.getTokenType() == PyTokenTypes.PRINT_KEYWORD);
final PsiBuilder.Marker statement = builder.mark();
builder.advanceLexer();
if(builder.getTokenType() == PyTokenTypes.GTGT)
{
final PsiBuilder.Marker target = builder.mark();
builder.advanceLexer();
getExpressionParser().parseSingleExpression(false);
target.done(PyElementTypes.PRINT_TARGET);
}
else
{
getExpressionParser().parseSingleExpression(false);
}
while(builder.getTokenType() == PyTokenTypes.COMMA)
{
builder.advanceLexer();
if(getEndOfStatementsTokens().contains(builder.getTokenType()))
{
break;
}
getExpressionParser().parseSingleExpression(false);
}
checkEndOfStatement();
statement.done(PyElementTypes.PRINT_STATEMENT);
}
protected void parseKeywordStatement(PsiBuilder builder, IElementType statementType)
{
final PsiBuilder.Marker statement = builder.mark();
builder.advanceLexer();
checkEndOfStatement();
statement.done(statementType);
}
private void parseReturnStatement(PsiBuilder builder)
{
LOG.assertTrue(builder.getTokenType() == PyTokenTypes.RETURN_KEYWORD);
final PsiBuilder.Marker returnStatement = builder.mark();
builder.advanceLexer();
if(builder.getTokenType() != null && !getEndOfStatementsTokens().contains(builder.getTokenType()))
{
getExpressionParser().parseExpression();
}
checkEndOfStatement();
returnStatement.done(PyElementTypes.RETURN_STATEMENT);
}
private void parseDelStatement()
{
assertCurrentToken(PyTokenTypes.DEL_KEYWORD);
final PsiBuilder.Marker delStatement = myBuilder.mark();
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error("Expression expected");
}
while(myBuilder.getTokenType() == PyTokenTypes.COMMA)
{
myBuilder.advanceLexer();
if(!getEndOfStatementsTokens().contains(myBuilder.getTokenType()))
{
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error("Expression expected");
}
}
}
checkEndOfStatement();
delStatement.done(PyElementTypes.DEL_STATEMENT);
}
private void parseRaiseStatement()
{
assertCurrentToken(PyTokenTypes.RAISE_KEYWORD);
final PsiBuilder.Marker raiseStatement = myBuilder.mark();
myBuilder.advanceLexer();
if(!getEndOfStatementsTokens().contains(myBuilder.getTokenType()))
{
getExpressionParser().parseSingleExpression(false);
if(myBuilder.getTokenType() == PyTokenTypes.COMMA)
{
myBuilder.advanceLexer();
getExpressionParser().parseSingleExpression(false);
if(myBuilder.getTokenType() == PyTokenTypes.COMMA)
{
myBuilder.advanceLexer();
getExpressionParser().parseSingleExpression(false);
}
}
else if(myBuilder.getTokenType() == PyTokenTypes.FROM_KEYWORD)
{
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error("Expression expected");
}
}
}
checkEndOfStatement();
raiseStatement.done(PyElementTypes.RAISE_STATEMENT);
}
private void parseAssertStatement()
{
assertCurrentToken(PyTokenTypes.ASSERT_KEYWORD);
final PsiBuilder.Marker assertStatement = myBuilder.mark();
myBuilder.advanceLexer();
if(getExpressionParser().parseSingleExpression(false))
{
if(myBuilder.getTokenType() == PyTokenTypes.COMMA)
{
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(false))
{
myContext.getBuilder().error(EXPRESSION_EXPECTED);
}
}
checkEndOfStatement();
}
else
{
myContext.getBuilder().error(EXPRESSION_EXPECTED);
}
assertStatement.done(PyElementTypes.ASSERT_STATEMENT);
}
protected void parseImportStatement(IElementType statementType, IElementType elementType)
{
final PsiBuilder builder = myContext.getBuilder();
final PsiBuilder.Marker importStatement = builder.mark();
builder.advanceLexer();
parseImportElements(elementType, true, false, false);
checkEndOfStatement();
importStatement.done(statementType);
}
/*
Really parses two forms:
from identifier import id, id... -- may be either relative or absolute
from . import identifier -- only relative
*/
private void parseFromImportStatement()
{
PsiBuilder builder = myContext.getBuilder();
assertCurrentToken(PyTokenTypes.FROM_KEYWORD);
myFutureImportPhase = Phase.FROM;
final PsiBuilder.Marker fromImportStatement = builder.mark();
builder.advanceLexer();
boolean from_future = false;
boolean had_dots = parseRelativeImportDots();
IElementType statementType = PyElementTypes.FROM_IMPORT_STATEMENT;
if(had_dots && parseOptionalDottedName() || parseDottedName())
{
final ImportTypes types = checkFromImportKeyword();
statementType = types.statement;
final IElementType elementType = types.element;
if(myFutureImportPhase == Phase.FUTURE)
{
myFutureImportPhase = Phase.IMPORT;
from_future = true;
}
if(builder.getTokenType() == PyTokenTypes.MULT)
{
final PsiBuilder.Marker star_import_mark = builder.mark();
builder.advanceLexer();
star_import_mark.done(types.starElement);
}
else if(builder.getTokenType() == PyTokenTypes.LPAR)
{
builder.advanceLexer();
parseImportElements(elementType, false, true, from_future);
checkMatches(PyTokenTypes.RPAR, ") expected");
}
else
{
parseImportElements(elementType, false, false, from_future);
}
}
else if(had_dots)
{ // from . import ...
final ImportTypes types = checkFromImportKeyword();
statementType = types.statement;
parseImportElements(types.element, false, false, from_future);
}
checkEndOfStatement();
fromImportStatement.done(statementType);
myFutureImportPhase = Phase.NONE;
}
protected ImportTypes checkFromImportKeyword()
{
checkMatches(PyTokenTypes.IMPORT_KEYWORD, "'import' expected");
return new ImportTypes(PyElementTypes.FROM_IMPORT_STATEMENT, PyElementTypes.IMPORT_ELEMENT, PyElementTypes.STAR_IMPORT_ELEMENT);
}
/**
* Parses option dots before imported name.
*
* @return true iff there were dots.
*/
private boolean parseRelativeImportDots()
{
PsiBuilder builder = myContext.getBuilder();
boolean had_dots = false;
while(builder.getTokenType() == PyTokenTypes.DOT)
{
had_dots = true;
builder.advanceLexer();
}
return had_dots;
}
private void parseImportElements(IElementType elementType, boolean is_module_import, boolean in_parens, final boolean from_future)
{
PsiBuilder builder = myContext.getBuilder();
while(true)
{
final PsiBuilder.Marker asMarker = builder.mark();
if(is_module_import)
{ // import _
if(!parseDottedNameAsAware(true, false))
{
asMarker.drop();
break;
}
}
else
{ // from X import _
String token_text = parseIdentifier(getReferenceType());
if(from_future)
{
// TODO: mark all known future feature names
if(TOK_WITH_STATEMENT.equals(token_text))
{
myFutureFlags.add(FUTURE.WITH_STATEMENT);
}
else if(TOK_NESTED_SCOPES.equals(token_text))
{
myFutureFlags.add(FUTURE.NESTED_SCOPES);
}
else if(TOK_PRINT_FUNCTION.equals(token_text))
{
myFutureFlags.add(FUTURE.PRINT_FUNCTION);
}
}
}
setExpectAsKeyword(true); // possible 'as' comes as an ident; reparse it as keyword if found
if(builder.getTokenType() == PyTokenTypes.AS_KEYWORD)
{
builder.advanceLexer();
setExpectAsKeyword(false);
parseIdentifier(PyElementTypes.TARGET_EXPRESSION);
}
asMarker.done(elementType);
setExpectAsKeyword(false);
if(builder.getTokenType() == PyTokenTypes.COMMA)
{
builder.advanceLexer();
if(in_parens && builder.getTokenType() == PyTokenTypes.RPAR)
{
break;
}
}
else
{
break;
}
}
}
@Nullable
private String parseIdentifier(final IElementType elementType)
{
final PsiBuilder.Marker idMarker = myBuilder.mark();
if(myBuilder.getTokenType() == PyTokenTypes.IDENTIFIER)
{
String id_text = myBuilder.getTokenText();
myBuilder.advanceLexer();
idMarker.done(elementType);
return id_text;
}
else
{
myBuilder.error(IDENTIFIER_EXPECTED);
idMarker.drop();
}
return null;
}
public boolean parseOptionalDottedName()
{
return parseDottedNameAsAware(false, true);
}
public boolean parseDottedName()
{
return parseDottedNameAsAware(false, false);
}
// true if identifier was parsed or skipped as optional, false on error
protected boolean parseDottedNameAsAware(boolean expect_as, boolean optional)
{
if(myBuilder.getTokenType() != PyTokenTypes.IDENTIFIER)
{
if(optional)
{
return true;
}
myBuilder.error(IDENTIFIER_EXPECTED);
return false;
}
PsiBuilder.Marker marker = myBuilder.mark();
myBuilder.advanceLexer();
marker.done(getReferenceType());
boolean old_expect_AS_kwd = myExpectAsKeyword;
setExpectAsKeyword(expect_as);
while(myBuilder.getTokenType() == PyTokenTypes.DOT)
{
marker = marker.precede();
myBuilder.advanceLexer();
checkMatches(PyTokenTypes.IDENTIFIER, IDENTIFIER_EXPECTED);
marker.done(getReferenceType());
}
setExpectAsKeyword(old_expect_AS_kwd);
return true;
}
private void parseNameDefiningStatement(final PyElementType elementType)
{
final PsiBuilder.Marker globalStatement = myBuilder.mark();
myBuilder.advanceLexer();
parseIdentifier(PyElementTypes.TARGET_EXPRESSION);
while(myBuilder.getTokenType() == PyTokenTypes.COMMA)
{
myBuilder.advanceLexer();
parseIdentifier(PyElementTypes.TARGET_EXPRESSION);
}
checkEndOfStatement();
globalStatement.done(elementType);
}
private void parseExecStatement()
{
assertCurrentToken(PyTokenTypes.EXEC_KEYWORD);
final PsiBuilder.Marker execStatement = myBuilder.mark();
myBuilder.advanceLexer();
getExpressionParser().parseExpression(true, false);
if(myBuilder.getTokenType() == PyTokenTypes.IN_KEYWORD)
{
myBuilder.advanceLexer();
getExpressionParser().parseSingleExpression(false);
if(myBuilder.getTokenType() == PyTokenTypes.COMMA)
{
myBuilder.advanceLexer();
getExpressionParser().parseSingleExpression(false);
}
}
checkEndOfStatement();
execStatement.done(PyElementTypes.EXEC_STATEMENT);
}
protected void parseIfStatement(PyElementType ifKeyword, PyElementType elifKeyword, PyElementType elseKeyword, PyElementType elementType)
{
assertCurrentToken(ifKeyword);
final PsiBuilder.Marker ifStatement = myBuilder.mark();
final PsiBuilder.Marker ifPart = myBuilder.mark();
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error("expression expected");
}
parseColonAndSuite();
ifPart.done(PyElementTypes.IF_PART_IF);
PsiBuilder.Marker elifPart = myBuilder.mark();
while(myBuilder.getTokenType() == elifKeyword)
{
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error("expression expected");
}
parseColonAndSuite();
elifPart.done(PyElementTypes.IF_PART_ELIF);
elifPart = myBuilder.mark();
}
elifPart.drop(); // we always kept an open extra elif
final PsiBuilder.Marker elsePart = myBuilder.mark();
if(myBuilder.getTokenType() == elseKeyword)
{
myBuilder.advanceLexer();
parseColonAndSuite();
elsePart.done(PyElementTypes.ELSE_PART);
}
else
{
elsePart.drop();
}
ifStatement.done(elementType);
}
private boolean expectColon()
{
if(myBuilder.getTokenType() == PyTokenTypes.COLON)
{
myBuilder.advanceLexer();
return true;
}
else if(myBuilder.getTokenType() == PyTokenTypes.STATEMENT_BREAK)
{
myBuilder.error("Colon expected");
return true;
}
final PsiBuilder.Marker marker = myBuilder.mark();
while(!atAnyOfTokens(null, PyTokenTypes.DEDENT, PyTokenTypes.STATEMENT_BREAK, PyTokenTypes.COLON))
{
myBuilder.advanceLexer();
}
boolean result = matchToken(PyTokenTypes.COLON);
if(!result && atToken(PyTokenTypes.STATEMENT_BREAK))
{
myBuilder.advanceLexer();
}
marker.error("Colon expected");
return result;
}
private void parseForStatement(PsiBuilder.Marker endMarker)
{
assertCurrentToken(PyTokenTypes.FOR_KEYWORD);
parseForPart();
final PsiBuilder.Marker elsePart = myBuilder.mark();
if(myBuilder.getTokenType() == PyTokenTypes.ELSE_KEYWORD)
{
myBuilder.advanceLexer();
parseColonAndSuite();
elsePart.done(PyElementTypes.ELSE_PART);
}
else
{
elsePart.drop();
}
endMarker.done(PyElementTypes.FOR_STATEMENT);
}
protected void parseForPart()
{
final PsiBuilder.Marker forPart = myBuilder.mark();
myBuilder.advanceLexer();
getExpressionParser().parseExpression(true, true);
checkMatches(PyTokenTypes.IN_KEYWORD, "'in' expected");
getExpressionParser().parseExpression();
parseColonAndSuite();
forPart.done(PyElementTypes.FOR_PART);
}
private void parseWhileStatement()
{
assertCurrentToken(PyTokenTypes.WHILE_KEYWORD);
final PsiBuilder.Marker statement = myBuilder.mark();
final PsiBuilder.Marker whilePart = myBuilder.mark();
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error(EXPRESSION_EXPECTED);
}
parseColonAndSuite();
whilePart.done(PyElementTypes.WHILE_PART);
final PsiBuilder.Marker elsePart = myBuilder.mark();
if(myBuilder.getTokenType() == PyTokenTypes.ELSE_KEYWORD)
{
myBuilder.advanceLexer();
parseColonAndSuite();
elsePart.done(PyElementTypes.ELSE_PART);
}
else
{
elsePart.drop();
}
statement.done(PyElementTypes.WHILE_STATEMENT);
}
private void parseTryStatement()
{
assertCurrentToken(PyTokenTypes.TRY_KEYWORD);
final PsiBuilder.Marker statement = myBuilder.mark();
final PsiBuilder.Marker tryPart = myBuilder.mark();
myBuilder.advanceLexer();
parseColonAndSuite();
tryPart.done(PyElementTypes.TRY_PART);
boolean haveExceptClause = false;
if(myBuilder.getTokenType() == PyTokenTypes.EXCEPT_KEYWORD)
{
haveExceptClause = true;
while(myBuilder.getTokenType() == PyTokenTypes.EXCEPT_KEYWORD)
{
final PsiBuilder.Marker exceptBlock = myBuilder.mark();
myBuilder.advanceLexer();
if(myBuilder.getTokenType() != PyTokenTypes.COLON)
{
if(!getExpressionParser().parseSingleExpression(false))
{
myBuilder.error(EXPRESSION_EXPECTED);
}
setExpectAsKeyword(true);
if(myBuilder.getTokenType() == PyTokenTypes.COMMA || myBuilder.getTokenType() == PyTokenTypes.AS_KEYWORD)
{
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(true))
{
myBuilder.error(EXPRESSION_EXPECTED);
}
}
}
parseColonAndSuite();
exceptBlock.done(PyElementTypes.EXCEPT_PART);
}
final PsiBuilder.Marker elsePart = myBuilder.mark();
if(myBuilder.getTokenType() == PyTokenTypes.ELSE_KEYWORD)
{
myBuilder.advanceLexer();
parseColonAndSuite();
elsePart.done(PyElementTypes.ELSE_PART);
}
else
{
elsePart.drop();
}
}
final PsiBuilder.Marker finallyPart = myBuilder.mark();
if(myBuilder.getTokenType() == PyTokenTypes.FINALLY_KEYWORD)
{
myBuilder.advanceLexer();
parseColonAndSuite();
finallyPart.done(PyElementTypes.FINALLY_PART);
}
else
{
finallyPart.drop();
if(!haveExceptClause)
{
myBuilder.error("'except' or 'finally' expected");
// much better to have a statement of incorrectly determined type
// than "TRY" and "COLON" tokens attached to nothing
}
}
statement.done(PyElementTypes.TRY_EXCEPT_STATEMENT);
}
private void parseColonAndSuite()
{
if(expectColon())
{
parseSuite();
}
else
{
final PsiBuilder.Marker mark = myBuilder.mark();
mark.done(PyElementTypes.STATEMENT_LIST);
}
}
private void parseWithStatement(PsiBuilder.Marker endMarker)
{
assertCurrentToken(PyTokenTypes.WITH_KEYWORD);
myBuilder.advanceLexer();
while(true)
{
PsiBuilder.Marker withItem = myBuilder.mark();
getExpressionParser().parseExpression();
setExpectAsKeyword(true);
if(myBuilder.getTokenType() == PyTokenTypes.AS_KEYWORD)
{
myBuilder.advanceLexer();
if(!getExpressionParser().parseSingleExpression(true))
{
myBuilder.error("Identifier expected");
// 'as' is followed by a target
}
}
withItem.done(PyElementTypes.WITH_ITEM);
if(!matchToken(PyTokenTypes.COMMA))
{
break;
}
}
parseColonAndSuite();
endMarker.done(PyElementTypes.WITH_STATEMENT);
}
private void parseClassDeclaration()
{
final PsiBuilder.Marker classMarker = myBuilder.mark();
parseClassDeclaration(classMarker);
}
public void parseClassDeclaration(PsiBuilder.Marker classMarker)
{
assertCurrentToken(PyTokenTypes.CLASS_KEYWORD);
myBuilder.advanceLexer();
parseIdentifierOrSkip(PyTokenTypes.LPAR, PyTokenTypes.COLON);
if(myBuilder.getTokenType() == PyTokenTypes.LPAR)
{
getExpressionParser().parseArgumentList();
}
else
{
final PsiBuilder.Marker inheritMarker = myBuilder.mark();
inheritMarker.done(PyElementTypes.ARGUMENT_LIST);
}
final ParsingContext context = getParsingContext();
context.pushScope(context.getScope().withClass());
parseColonAndSuite();
context.popScope();
classMarker.done(PyElementTypes.CLASS_DECLARATION);
}
private void parseAsyncStatement()
{
assertCurrentToken(PyTokenTypes.ASYNC_KEYWORD);
final PsiBuilder.Marker marker = myBuilder.mark();
myBuilder.advanceLexer();
final IElementType token = myBuilder.getTokenType();
if(token == PyTokenTypes.DEF_KEYWORD)
{
getFunctionParser().parseFunctionDeclaration(marker, true);
}
else if(token == PyTokenTypes.WITH_KEYWORD)
{
parseWithStatement(marker);
}
else if(token == PyTokenTypes.FOR_KEYWORD)
{
parseForStatement(marker);
}
else
{
marker.drop();
myBuilder.error("'def' or 'with' or 'for' expected");
}
}
public void parseSuite()
{
parseSuite(null, null);
}
public void parseSuite(@Nullable PsiBuilder.Marker endMarker, @Nullable IElementType elType)
{
if(myBuilder.getTokenType() == PyTokenTypes.STATEMENT_BREAK)
{
myBuilder.advanceLexer();
final PsiBuilder.Marker marker = myBuilder.mark();
final boolean indentFound = myBuilder.getTokenType() == PyTokenTypes.INDENT;
if(indentFound)
{
myBuilder.advanceLexer();
if(myBuilder.eof())
{
myBuilder.error("Indented block expected");
}
else
{
while(!myBuilder.eof() && myBuilder.getTokenType() != PyTokenTypes.DEDENT)
{
parseStatement();
}
}
}
else
{
myBuilder.error("Indent expected");
}
marker.done(PyElementTypes.STATEMENT_LIST);
marker.setCustomEdgeTokenBinders(LeadingCommentsBinder.INSTANCE, FollowingCommentBinder.INSTANCE);
if(endMarker != null)
{
endMarker.done(elType);
}
if(indentFound && !myBuilder.eof())
{
checkMatches(PyTokenTypes.DEDENT, "Dedent expected");
}
}
else
{
final PsiBuilder.Marker marker = myBuilder.mark();
if(myBuilder.eof())
{
myBuilder.error("Statement expected");
}
else
{
final ParsingContext context = getParsingContext();
context.pushScope(context.getScope().withSuite());
parseSimpleStatement();
context.popScope();
while(matchToken(PyTokenTypes.SEMICOLON))
{
if(matchToken(PyTokenTypes.STATEMENT_BREAK))
{
break;
}
context.pushScope(context.getScope().withSuite());
parseSimpleStatement();
context.popScope();
}
}
marker.done(PyElementTypes.STATEMENT_LIST);
if(endMarker != null)
{
endMarker.done(elType);
}
}
}
public IElementType filter(final IElementType source, final int start, final int end, final CharSequence text)
{
if((myExpectAsKeyword || myContext.getLanguageLevel().hasWithStatement()) &&
source == PyTokenTypes.IDENTIFIER && isWordAtPosition(text, start, end, TOK_AS))
{
return PyTokenTypes.AS_KEYWORD;
}
else if( // filter
(myFutureImportPhase == Phase.FROM) &&
source == PyTokenTypes.IDENTIFIER &&
isWordAtPosition(text, start, end, TOK_FUTURE_IMPORT))
{
myFutureImportPhase = Phase.FUTURE;
return source;
}
else if(hasWithStatement() &&
source == PyTokenTypes.IDENTIFIER &&
isWordAtPosition(text, start, end, TOK_WITH))
{
return PyTokenTypes.WITH_KEYWORD;
}
else if(hasPrintStatement() && source == PyTokenTypes.IDENTIFIER &&
isWordAtPosition(text, start, end, TOK_PRINT))
{
return PyTokenTypes.PRINT_KEYWORD;
}
else if(myContext.getLanguageLevel().isPy3K() && source == PyTokenTypes.IDENTIFIER)
{
if(isWordAtPosition(text, start, end, TOK_NONE))
{
return PyTokenTypes.NONE_KEYWORD;
}
if(isWordAtPosition(text, start, end, TOK_TRUE))
{
return PyTokenTypes.TRUE_KEYWORD;
}
if(isWordAtPosition(text, start, end, TOK_FALSE))
{
return PyTokenTypes.FALSE_KEYWORD;
}
if(isWordAtPosition(text, start, end, TOK_DEBUG))
{
return PyTokenTypes.DEBUG_KEYWORD;
}
if(isWordAtPosition(text, start, end, TOK_NONLOCAL))
{
return PyTokenTypes.NONLOCAL_KEYWORD;
}
if(myContext.getLanguageLevel().isAtLeast(LanguageLevel.PYTHON35))
{
if(isWordAtPosition(text, start, end, TOK_ASYNC))
{
if(myContext.getScope().isAsync() || myBuilder.lookAhead(1) == PyTokenTypes.DEF_KEYWORD)
{
return PyTokenTypes.ASYNC_KEYWORD;
}
}
if(isWordAtPosition(text, start, end, TOK_AWAIT))
{
if(myContext.getScope().isAsync())
{
return PyTokenTypes.AWAIT_KEYWORD;
}
}
}
}
else if(!myContext.getLanguageLevel().isPy3K() && source == PyTokenTypes.IDENTIFIER)
{
if(isWordAtPosition(text, start, end, TOK_EXEC))
{
return PyTokenTypes.EXEC_KEYWORD;
}
}
return source;
}
protected TokenSet getEndOfStatementsTokens()
{
return PyTokenTypes.END_OF_STATEMENT;
}
private static boolean isWordAtPosition(CharSequence text, int start, int end, final String tokenText)
{
return CharArrayUtil.regionMatches(text, start, end, tokenText) && end - start == tokenText.length();
}
private boolean hasWithStatement()
{
return myContext.getLanguageLevel().hasWithStatement() || myFutureFlags.contains(FUTURE.WITH_STATEMENT);
}
}
| apache-2.0 |
uniqueid001/enunciate | javac-support/src/main/java/com/webcohesion/enunciate/javac/decorations/element/DecoratedAnnotationMirror.java | 2299 | /*
* Copyright 2006 Ryan Heaton
*
* 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.webcohesion.enunciate.javac.decorations.element;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.DeclaredType;
import java.util.Map;
/**
* @author Ryan Heaton
*/
public class DecoratedAnnotationMirror implements AnnotationMirror {
private final AnnotationMirror delegate;
private final ProcessingEnvironment env;
public DecoratedAnnotationMirror(AnnotationMirror delegate, ProcessingEnvironment env) {
if (delegate == null) {
throw new NullPointerException("A delegate must be provided.");
}
if (env == null) {
throw new NullPointerException("A processing environment must be provided.");
}
//unwrap.
while (delegate instanceof DecoratedAnnotationMirror) {
delegate = ((DecoratedAnnotationMirror) delegate).delegate;
}
this.delegate = delegate;
this.env = env;
}
public DeclaredType getAnnotationType() {
return this.delegate.getAnnotationType();
}
public Map<? extends ExecutableElement, ? extends AnnotationValue> getElementValues() {
return this.delegate.getElementValues();
}
public Map<? extends ExecutableElement, ? extends AnnotationValue> getAllElementValues() {
return this.env.getElementUtils().getElementValuesWithDefaults(this.delegate);
}
public boolean equals(Object o) {
if (o instanceof DecoratedAnnotationMirror) {
o = ((DecoratedAnnotationMirror) o).delegate;
}
return this.delegate.equals(o);
}
public AnnotationMirror getDelegate() {
return delegate;
}
}
| apache-2.0 |
fuquanlin/fishbone | account/src/main/java/cn/fql/account/dao/mapper/AcctFlowMapper.java | 182 | package cn.fql.account.dao.mapper;
import cn.fql.account.model.domain.AcctFlow;
import tk.mybatis.mapper.common.Mapper;
public interface AcctFlowMapper extends Mapper<AcctFlow> {
} | apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/compositeeditor/ClearAction.java | 2076 | /* ###
* IP: GHIDRA
*
* 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 ghidra.app.plugin.core.compositeeditor;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.KeyStroke;
import docking.ActionContext;
import docking.action.KeyBindingData;
import ghidra.util.Msg;
import ghidra.util.exception.UsrException;
import resources.ResourceManager;
public class ClearAction extends CompositeEditorTableAction {
public final static String ACTION_NAME = "Clear Components";
private final static String GROUP_NAME = COMPONENT_ACTION_GROUP;
private final static ImageIcon ICON = ResourceManager.loadImage("images/erase16.png");
private final static String[] POPUP_PATH = new String[] { "Clear" };
private final static KeyStroke KEY_STROKE = KeyStroke.getKeyStroke(KeyEvent.VK_C, 0);
public ClearAction(CompositeEditorProvider provider) {
super(provider, EDIT_ACTION_PREFIX + ACTION_NAME, GROUP_NAME, POPUP_PATH, null, ICON);
setDescription("Clear the selected components");
setKeyBindingData(new KeyBindingData(KEY_STROKE));
adjustEnablement();
}
@Override
public void actionPerformed(ActionContext context) {
try {
model.clearSelectedComponents();
}
catch (OutOfMemoryError memExc) {
String errMsg = "Couldn't clear components. Out of memory.";
Msg.showError(this, null, "Out of Memory", errMsg, memExc);
}
catch (UsrException ue) {
model.setStatus(ue.getMessage());
}
requestTableFocus();
}
@Override
public void adjustEnablement() {
setEnabled(model.isClearAllowed());
}
}
| apache-2.0 |
goodwinnk/intellij-community | plugins/IntentionPowerPak/src/com/siyeh/ipp/switchtoif/SwitchPredicate.java | 2111 | /*
* Copyright 2003-2007 Dave Griffith, Bas Leijdekkers
*
* 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.siyeh.ipp.switchtoif;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.siyeh.ipp.base.PsiElementPredicate;
import com.siyeh.ipp.psiutils.ErrorUtil;
import org.jetbrains.annotations.NotNull;
class SwitchPredicate implements PsiElementPredicate {
@Override
public boolean satisfiedBy(PsiElement element) {
if (!(element instanceof PsiJavaToken)) {
return false;
}
final PsiJavaToken token = (PsiJavaToken)element;
final IElementType tokenType = token.getTokenType();
if (!JavaTokenType.SWITCH_KEYWORD.equals(tokenType)) {
return false;
}
final PsiElement parent = element.getParent();
if (!(parent instanceof PsiSwitchStatement)) {
return false;
}
return checkSwitchStatement((PsiSwitchStatement)parent);
}
public static boolean checkSwitchStatement(@NotNull PsiSwitchStatement switchStatement) {
final PsiExpression expression = switchStatement.getExpression();
if (expression == null) {
return false;
}
final PsiCodeBlock body = switchStatement.getBody();
if (body == null) {
return false;
}
if (ErrorUtil.containsError(switchStatement)) {
return false;
}
boolean hasLabel = false;
final PsiStatement[] statements = body.getStatements();
for (PsiStatement statement : statements) {
if (statement instanceof PsiSwitchLabelStatement) {
hasLabel = true;
break;
}
}
return hasLabel;
}
} | apache-2.0 |
ngageoint/geowave-osm | src/test/java/mil/nga/giat/osm/ColumnQualifierTest.java | 826 | package mil.nga.giat.osm;
import com.google.common.io.BaseEncoding;
import mil.nga.giat.osm.accumulo.osmschema.Schema;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class ColumnQualifierTest {
@Test(expected=NullPointerException.class)
public void TAG_QUALIFIER_NULL() throws Exception {
byte[] bytes = Schema.CQ.TAG_QUALIFIER(null);
if (bytes != null){
Assert.fail("returned non null value back; execution path should never be seen");
}
}
@Test
public void TAG_QUALIFIER_TOBYTE() throws Exception {
byte[] bytes = Schema.CQ.TAG_QUALIFIER("フォースを使え ルーク");
byte[] bytes2 = BaseEncoding.base64().decode("44OV44Kp44O844K544KS5L2/44GI44CA44Or44O844Kv");
Assert.assertArrayEquals(bytes, bytes2);
}
} | apache-2.0 |
jottinger/finder | src/main/java/com/redhat/osas/finder/util/SyndUtil.java | 470 | package com.redhat.osas.finder.util;
import java.util.List;
import com.sun.syndication.feed.synd.SyndContent;
public class SyndUtil {
public static String convertToString(SyndContent syndContent) {
return syndContent.getValue();
}
public static String convertToString(List<SyndContent> syndContent) {
StringBuilder sb = new StringBuilder();
for (SyndContent content : syndContent) {
sb.append(convertToString(content));
}
return sb.toString();
}
}
| apache-2.0 |
phoolhbti/AEM | citraining/core/src/main/java/com/citraining/core/sample/impl/ConfigurationFactoryImpl.java | 1515 | package com.citraining.core.sample.impl;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.citraining.core.sample.ConfigurationFactory;
@Component (service = ConfigurationFactory.class,configurationPolicy = ConfigurationPolicy.REQUIRE)
@Designate (ocd = ConfigurationFactoryImpl.Config.class, factory = true)
public class ConfigurationFactoryImpl implements ConfigurationFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationFactoryImpl.class);
@ObjectClassDefinition (name = "Citraining configuration factory")
public @interface Config {
@AttributeDefinition (name = "Content Consumer URL", defaultValue = "http://localhost:8081")
String getContentConsumerUrl();
}
private String contentConsumerUrl;
@Activate
@Modified
protected void activate(final Config config) {
contentConsumerUrl = config.getContentConsumerUrl();
LOGGER.info("Read the content Consumer Url :{} ", contentConsumerUrl);
}
@Override
public String getContentConsumerUrl() {
return contentConsumerUrl;
}
} | apache-2.0 |
dbahat/conventions | Conventions/app/src/main/java/amai/org/conventions/customviews/CenterInToolbarFrameLayout.java | 3688 | package amai.org.conventions.customviews;
import android.content.Context;
import androidx.appcompat.widget.ActionMenuView;
import androidx.appcompat.widget.Toolbar;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageButton;
public class CenterInToolbarFrameLayout extends FrameLayout {
public CenterInToolbarFrameLayout(Context context) {
super(context);
}
public CenterInToolbarFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CenterInToolbarFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// This custom view is used to center the title (in the child view) inside the toolbar.
// The available width of the title changes between screens due to having a different number of menu items,
// and if the number of items to the title's start/end isn't symmetrical, the title won't appear centered
// even if the text view is centered inside it, so we need to add margin to its start to "balance" the space
// taken by the action items.
// There are cases when we can't center the title because there's not enough space for the
// title to be in the center of the toolbar. In this case we do the next best thing and end-align it (with
// no margin).
// To calculate the margin we check how much room the icons on either side of the title take:
// - To the title's start, we'll always have the navigation action as an image button.
// - To the title's end, we'll have a changing amount of action items as an ActionMenuView.
// We take the measured width of each of them and calculate the required margin.
// For example:
// If the menu has no items, we add a negative margin to the title equal to the width of the navigation item.
// If the menu has 2 items, we add a positive margin to the title's start equal to the width of one action item.
// The margin added at the end is half the required margin because the text is centered.
ViewParent parent = getParent();
if (parent instanceof Toolbar && getChildCount() == 1) {
Toolbar toolbar = (Toolbar) parent;
int startWidth = 0;
int endWidth = 0;
for (int childNumber = 0; childNumber < toolbar.getChildCount(); ++childNumber) {
View child = toolbar.getChildAt(childNumber);
if (child == this) {
continue;
}
if (child instanceof ActionMenuView) {
endWidth = child.getMeasuredWidth();
} else if (child instanceof ImageButton) {
startWidth = child.getMeasuredWidth();
}
}
int startMargin = endWidth - startWidth;
View child = getChildAt(0);
LayoutParams childLayoutParams = (LayoutParams) child.getLayoutParams();
childLayoutParams.setMarginStart(0); // Ensure the child width is calculated correctly
child.setLayoutParams(childLayoutParams);
measureChildren(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), heightMeasureSpec);
int childWidth = child.getMeasuredWidth();
int maxWidth = MeasureSpec.getSize(widthMeasureSpec);
if (childWidth + startMargin > maxWidth) {
// Not enough room - end-align child
childLayoutParams.gravity = Gravity.END | Gravity.CENTER_VERTICAL;
childLayoutParams.setMarginStart(0);
} else {
// Center-align child with margin
childLayoutParams.gravity = Gravity.CENTER;
childLayoutParams.setMarginStart(startMargin / 2);
}
child.setLayoutParams(childLayoutParams);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
| apache-2.0 |
daverix/slingerORM | compiler/src/main/java/net/daverix/slingerorm/compiler/TypeElementConverter.java | 815 | /*
* Copyright 2015 David Laurell
*
* 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 net.daverix.slingerorm.compiler;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
interface TypeElementConverter {
TypeElement asTypeElement(TypeMirror typeMirror);
}
| apache-2.0 |
hairlun/customer-visit-web | src/com/jude/controller/InteractiveItemController.java | 5029 | package com.jude.controller;
import com.jude.entity.Customer;
import com.jude.entity.InteractiveItem;
import com.jude.json.JSONArray;
import com.jude.json.JSONObject;
import com.jude.service.InteractiveItemService;
import com.jude.util.ExtJS;
import com.jude.util.HttpUtils;
import com.jude.util.PagingSet;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping({ "/interactiveItem.do" })
public class InteractiveItemController {
public static final Logger log = LoggerFactory.getLogger(InteractiveItemController.class);
@Autowired
private InteractiveItemService interactiveItemService;
@RequestMapping(params = { "action=forwardIndex" })
public String forwardIndex() {
return "interactiveItem/index.jsp";
}
@RequestMapping(params = { "action=queryAll" })
public void queryAll(HttpServletRequest request, HttpServletResponse response) {
try {
Map<String, Object> param = HttpUtils.getRequestParam(request);
int start = NumberUtils.toInt((String) param.get("start"), 0);
int limit = NumberUtils.toInt((String) param.get("limit"), 100);
String sort = (String) param.get("sort");
String dir = (String) param.get("dir");
PagingSet<InteractiveItem> set = this.interactiveItemService.getInteractiveItems(start, limit,
sort, dir);
JSONArray rows = new JSONArray();
JSONObject main = new JSONObject();
List<InteractiveItem> interactiveItemList = set.getList();
JSONObject row;
for (InteractiveItem interactiveItem : interactiveItemList) {
row = new JSONObject();
row.put("id", interactiveItem.getId());
row.put("name", interactiveItem.getName());
rows.put(row);
}
main.put("rows", rows);
main.put("total", set.getTotal());
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.write(main.toString(4));
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
@RequestMapping(params = { "action=addInteractiveItem" })
@ResponseBody
public JSONObject addInteractiveItem(HttpServletRequest request, HttpServletResponse response) {
try {
if (!LoginInfo.isAdmin(request)) {
return ExtJS.fail("非admin用户不能执行此操作!");
}
String name = request.getParameter("name");
if (this.interactiveItemService.nameExist(name)) {
return ExtJS.fail("交互事项已存在,请重新输入!");
}
InteractiveItem interactiveItem = new InteractiveItem();
interactiveItem.setName(name);
this.interactiveItemService.addInteractiveItem(interactiveItem);
return ExtJS.ok("新增交互事项成功!");
} catch (Exception e) {
log.error("add interactiveItem ex", e);
}
return ExtJS.fail("新增交互事项失败,请刷新页面重试!");
}
@RequestMapping(params = { "action=editInteractiveItem" })
@ResponseBody
public JSONObject editInteractiveItem(HttpServletRequest request, HttpServletResponse response) {
try {
if (!LoginInfo.isAdmin(request)) {
return ExtJS.fail("非admin用户不能执行此操作!");
}
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String oname = request.getParameter("oname");
if ((!name.equals(oname))
&& (this.interactiveItemService.nameExist(name))) {
return ExtJS.fail("交互事项已存在,请重新输入!");
}
InteractiveItem interactiveItem = this.interactiveItemService.getInteractiveItem(id);
if (interactiveItem == null) {
return ExtJS.fail("编辑交互事项失败,请刷新页面重试!");
}
interactiveItem.setName(name);
this.interactiveItemService.updateInteractiveItem(interactiveItem);
return ExtJS.ok("修改成功!");
} catch (Exception e) {
}
return ExtJS.fail("编辑交互事项失败,请刷新页面重试!");
}
@RequestMapping(params = { "action=delInteractiveItems" })
@ResponseBody
public JSONObject delInteractiveItems(HttpServletRequest request, HttpServletResponse response) {
try {
if (!LoginInfo.isAdmin(request)) {
return ExtJS.fail("非admin用户不能执行此操作!");
}
String ids = request.getParameter("ids");
ids = ids.substring(1);
this.interactiveItemService.deleteInteractiveItems(ids);
} catch (Exception e) {
return ExtJS.fail("删除交互事项失败,请刷新页面后重试!");
}
return ExtJS.ok("删除交互事项成功!");
}
} | apache-2.0 |
dverstap/wintersleep | wintersleep-spring-util/src/test/java/org/wintersleep/util/spring/tx/FirstService.java | 837 | /*
* Copyright 2008 Davy Verstappen.
*
* 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.wintersleep.util.spring.tx;
public interface FirstService {
void required();
void supports();
void mandatory();
void requiresNew();
void notSupported();
void never();
void nested();
}
| apache-2.0 |
charles-cooper/idylfin | src/de/erichseifert/gral/graphics/Container.java | 3199 | /*
* GRAL: GRAphing Library for Java(R)
*
* (C) Copyright 2009-2012 Erich Seifert <dev[at]erichseifert.de>,
* Michael Seifert <michael[at]erichseifert.de>
*
* This file is part of GRAL.
*
* GRAL 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.
*
* GRAL 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 GRAL. If not, see <http://www.gnu.org/licenses/>.
*/
package de.erichseifert.gral.graphics;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import de.erichseifert.gral.util.Insets2D;
/**
* An interface that provides functions to build a group of multiple components
* of {@link Drawable}. It is also responsible for managing layout of its
* components using a {@link Layout} and layout constraints for each component.
*/
public interface Container extends Iterable<Drawable> {
/**
* Returns the space that this container must preserve at each of its
* edges.
* @return The insets of this DrawableContainer
*/
Insets2D getInsets();
/**
* Sets the space that this container must preserve at each of its
* edges.
* @param insets Insets to be set.
*/
void setInsets(Insets2D insets);
/**
* Returns the bounds of this container.
* @return bounds
*/
Rectangle2D getBounds();
/**
* Sets the bounds of this container.
* @param bounds Bounds
*/
void setBounds(Rectangle2D bounds);
/**
* Returns the layout associated with this container.
* @return Layout manager
*/
Layout getLayout();
/**
* Recalculates this container's layout.
*/
void layout();
/**
* Sets the layout associated with this container.
* @param layout Layout to be set.
*/
void setLayout(Layout layout);
/**
* Adds a new component to this container.
* @param drawable Component
*/
void add(Drawable drawable);
/**
* Adds a new component to this container.
* @param drawable Component
* @param constraints Additional information (e.g. for layout)
*/
void add(Drawable drawable, Object constraints);
/**
* Returns the component at the specified point. If no component could be
* found {@code null} will be returned.
* @param point Two-dimensional point.
* @return Component at the specified point, or {@code null} if no
* component could be found.
*/
Drawable getDrawableAt(Point2D point);
/**
* Return additional information on component
* @param drawable Component
* @return Information object or {@code null}
*/
Object getConstraints(Drawable drawable);
/**
* Removes a component from this container.
* @param drawable Component
*/
void remove(Drawable drawable);
/**
* Returns the number of components that are stored in this container.
* @return total number of components
*/
int size();
}
| apache-2.0 |