repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
cristal-ise/kernel | src/main/java/org/cristalise/kernel/lookup/InvalidPathException.java | 1253 | /**
* This file is part of the CRISTAL-iSE kernel.
* Copyright (c) 2001-2015 The CRISTAL Consortium. All rights reserved.
*
* 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; with out even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* http://www.fsf.org/licensing/licenses/lgpl.html
*/
package org.cristalise.kernel.lookup;
public class InvalidPathException extends Exception {
private static final long serialVersionUID = -1980471517943177915L;
public InvalidPathException() {
super();
}
public InvalidPathException(String msg) {
super(msg);
}
}
| lgpl-3.0 |
kyau/darkmatter | src/main/java/net/kyau/darkmatter/proxy/ClientProxy.java | 2507 | package net.kyau.darkmatter.proxy;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.LogManager;
import net.kyau.darkmatter.client.gui.GuiHUD;
import net.kyau.darkmatter.client.gui.GuiVoidJournal;
import net.kyau.darkmatter.client.renderer.EntityParticleFXQuantum;
import net.kyau.darkmatter.references.ModInfo;
import net.kyau.darkmatter.registry.ModBlocks;
import net.kyau.darkmatter.registry.ModItems;
import net.minecraft.client.Minecraft;
import net.minecraft.client.particle.Particle;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
public class ClientProxy extends CommonProxy {
private static Minecraft minecraft = Minecraft.getMinecraft();
@Override
public ClientProxy getClientProxy() {
return this;
}
@Override
public void registerEventHandlers() {
super.registerEventHandlers();
MinecraftForge.EVENT_BUS.register(new GuiHUD(minecraft));
//LogManager.getLogger(ModInfo.MOD_ID).log(Level.INFO, "ClientProxy: registerEventHandlers() SUCCESS!");
}
@Override
public void registerClientEventHandlers() {
// NOOP
}
@Override
public void registerKeybindings() {
// NOOP
}
@Override
public void initRenderingAndTextures() {
ModItems.registerRenders();
ModBlocks.registerRenders();
}
@Override
public boolean isSinglePlayer() {
return Minecraft.getMinecraft().isSingleplayer();
}
@Override
public void openJournal() {
Minecraft.getMinecraft().displayGuiScreen(new GuiVoidJournal());
}
@Override
public void generateQuantumParticles(World world, BlockPos pos, Random rand) {
float motionX = (float) (rand.nextGaussian() * 0.02F);
float motionY = (float) (rand.nextGaussian() * 0.02F);
float motionZ = (float) (rand.nextGaussian() * 0.02F);
// for (int i = 0; i < 2; i++) {
Particle particleMysterious = new EntityParticleFXQuantum(world, pos.getX() + rand.nextFloat() * 0.7F + 0.2F, pos.getY() + 0.1F, pos.getZ() + rand.nextFloat() * 0.8F + 0.2F, motionX, motionY, motionZ);
Minecraft.getMinecraft().effectRenderer.addEffect(particleMysterious);
// }
}
@Override
public long getVoidPearlLastUse() {
// return lastUseVoidPearl;
return 0;
}
@Override
public void setVoidPearlLastUse(long lastUse) {
// this.lastUseVoidPearl = cooldown;
}
@Override
public void registerTileEntities() {
// TODO Auto-generated method stub
}
}
| lgpl-3.0 |
cismet/verdis-server | src/main/java/de/cismet/verdis/commons/constants/KanalanschlussPropertyConstants.java | 1464 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* Copyright (C) 2011 jruiz
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.cismet.verdis.commons.constants;
/**
* DOCUMENT ME!
*
* @author jruiz
* @version $Revision$, $Date$
*/
public final class KanalanschlussPropertyConstants extends PropertyConstants {
//~ Static fields/initializers ---------------------------------------------
public static final String BEFREIUNGENUNDERLAUBNISSE = "befreiungenunderlaubnisse";
//~ Constructors -----------------------------------------------------------
/**
* Creates a new KanalanschlussPropertyConstants object.
*/
KanalanschlussPropertyConstants() {
}
}
| lgpl-3.0 |
mabe02/lanterna | src/main/java/com/googlecode/lanterna/gui2/BorderLayout.java | 9401 | /*
* This file is part of lanterna (https://github.com/mabe02/lanterna).
*
* lanterna 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/>.
*
* Copyright (C) 2010-2020 Martin Berglund
*/
package com.googlecode.lanterna.gui2;
import com.googlecode.lanterna.TerminalPosition;
import com.googlecode.lanterna.TerminalSize;
import java.util.*;
/**
* BorderLayout imitates the BorderLayout class from AWT, allowing you to add a center component with optional
* components around it in top, bottom, left and right locations. The edge components will be sized at their preferred
* size and the center component will take up whatever remains.
* @author martin
*/
public class BorderLayout implements LayoutManager {
/**
* This type is what you use as the layout data for components added to a panel using {@code BorderLayout} for its
* layout manager. This values specified where inside the panel the component should be added.
*/
public enum Location implements LayoutData {
/**
* The component with this value as its layout data will occupy the center space, whatever is remaining after
* the other components (if any) have allocated their space.
*/
CENTER,
/**
* The component with this value as its layout data will occupy the left side of the container, attempting to
* allocate the preferred width of the component and at least the preferred height, but could be more depending
* on the other components added.
*/
LEFT,
/**
* The component with this value as its layout data will occupy the right side of the container, attempting to
* allocate the preferred width of the component and at least the preferred height, but could be more depending
* on the other components added.
*/
RIGHT,
/**
* The component with this value as its layout data will occupy the top side of the container, attempting to
* allocate the preferred height of the component and at least the preferred width, but could be more depending
* on the other components added.
*/
TOP,
/**
* The component with this value as its layout data will occupy the bottom side of the container, attempting to
* allocate the preferred height of the component and at least the preferred width, but could be more depending
* on the other components added.
*/
BOTTOM,
;
}
//When components don't have a location, we'll assign an available location based on this order
private static final List<Location> AUTO_ASSIGN_ORDER = Collections.unmodifiableList(Arrays.asList(
Location.CENTER,
Location.TOP,
Location.BOTTOM,
Location.LEFT,
Location.RIGHT));
@Override
public TerminalSize getPreferredSize(List<Component> components) {
EnumMap<Location, Component> layout = makeLookupMap(components);
int preferredHeight =
(layout.containsKey(Location.TOP) ? layout.get(Location.TOP).getPreferredSize().getRows() : 0)
+
Math.max(
layout.containsKey(Location.LEFT) ? layout.get(Location.LEFT).getPreferredSize().getRows() : 0,
Math.max(
layout.containsKey(Location.CENTER) ? layout.get(Location.CENTER).getPreferredSize().getRows() : 0,
layout.containsKey(Location.RIGHT) ? layout.get(Location.RIGHT).getPreferredSize().getRows() : 0))
+
(layout.containsKey(Location.BOTTOM) ? layout.get(Location.BOTTOM).getPreferredSize().getRows() : 0);
int preferredWidth =
Math.max(
(layout.containsKey(Location.LEFT) ? layout.get(Location.LEFT).getPreferredSize().getColumns() : 0) +
(layout.containsKey(Location.CENTER) ? layout.get(Location.CENTER).getPreferredSize().getColumns() : 0) +
(layout.containsKey(Location.RIGHT) ? layout.get(Location.RIGHT).getPreferredSize().getColumns() : 0),
Math.max(
layout.containsKey(Location.TOP) ? layout.get(Location.TOP).getPreferredSize().getColumns() : 0,
layout.containsKey(Location.BOTTOM) ? layout.get(Location.BOTTOM).getPreferredSize().getColumns() : 0));
return new TerminalSize(preferredWidth, preferredHeight);
}
@Override
public void doLayout(TerminalSize area, List<Component> components) {
EnumMap<Location, Component> layout = makeLookupMap(components);
int availableHorizontalSpace = area.getColumns();
int availableVerticalSpace = area.getRows();
//We'll need this later on
int topComponentHeight = 0;
int leftComponentWidth = 0;
//First allocate the top
if(layout.containsKey(Location.TOP)) {
Component topComponent = layout.get(Location.TOP);
topComponentHeight = Math.min(topComponent.getPreferredSize().getRows(), availableVerticalSpace);
topComponent.setPosition(TerminalPosition.TOP_LEFT_CORNER);
topComponent.setSize(new TerminalSize(availableHorizontalSpace, topComponentHeight));
availableVerticalSpace -= topComponentHeight;
}
//Next allocate the bottom
if(layout.containsKey(Location.BOTTOM)) {
Component bottomComponent = layout.get(Location.BOTTOM);
int bottomComponentHeight = Math.min(bottomComponent.getPreferredSize().getRows(), availableVerticalSpace);
bottomComponent.setPosition(new TerminalPosition(0, area.getRows() - bottomComponentHeight));
bottomComponent.setSize(new TerminalSize(availableHorizontalSpace, bottomComponentHeight));
availableVerticalSpace -= bottomComponentHeight;
}
//Now divide the remaining space between LEFT, CENTER and RIGHT
if(layout.containsKey(Location.LEFT)) {
Component leftComponent = layout.get(Location.LEFT);
leftComponentWidth = Math.min(leftComponent.getPreferredSize().getColumns(), availableHorizontalSpace);
leftComponent.setPosition(new TerminalPosition(0, topComponentHeight));
leftComponent.setSize(new TerminalSize(leftComponentWidth, availableVerticalSpace));
availableHorizontalSpace -= leftComponentWidth;
}
if(layout.containsKey(Location.RIGHT)) {
Component rightComponent = layout.get(Location.RIGHT);
int rightComponentWidth = Math.min(rightComponent.getPreferredSize().getColumns(), availableHorizontalSpace);
rightComponent.setPosition(new TerminalPosition(area.getColumns() - rightComponentWidth, topComponentHeight));
rightComponent.setSize(new TerminalSize(rightComponentWidth, availableVerticalSpace));
availableHorizontalSpace -= rightComponentWidth;
}
if(layout.containsKey(Location.CENTER)) {
Component centerComponent = layout.get(Location.CENTER);
centerComponent.setPosition(new TerminalPosition(leftComponentWidth, topComponentHeight));
centerComponent.setSize(new TerminalSize(availableHorizontalSpace, availableVerticalSpace));
}
//Set the remaining components to 0x0
for(Component component: components) {
if(component.isVisible() && !layout.containsValue(component)) {
component.setPosition(TerminalPosition.TOP_LEFT_CORNER);
component.setSize(TerminalSize.ZERO);
}
}
}
private EnumMap<Location, Component> makeLookupMap(List<Component> components) {
EnumMap<Location, Component> map = new EnumMap<>(Location.class);
List<Component> unassignedComponents = new ArrayList<>();
for(Component component: components) {
if (!component.isVisible()) {
continue;
}
if(component.getLayoutData() instanceof Location) {
map.put((Location)component.getLayoutData(), component);
}
else {
unassignedComponents.add(component);
}
}
//Try to assign components to available locations
for(Component component: unassignedComponents) {
for(Location location: AUTO_ASSIGN_ORDER) {
if(!map.containsKey(location)) {
map.put(location, component);
break;
}
}
}
return map;
}
@Override
public boolean hasChanged() {
//No internal state
return false;
}
}
| lgpl-3.0 |
leonardoroese/LRWS | lrws/src/br/com/zpi/lrws/conn/DBParVal.java | 220 | package br.com.zpi.lrws.conn;
import java.io.Serializable;
public class DBParVal implements Serializable{
private static final long serialVersionUID = 1L;
public String param = null;
public String value = null;
}
| lgpl-3.0 |
yangjiandong/appjruby | app-plugin-api/src/main/java/org/sonar/api/security/UserRole.java | 1994 | /*
* Sonar, open source software quality management tool.
* Copyright (C) 2009 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.api.security;
import org.sonar.api.database.BaseIdentifiable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* This JPA model maps the table user_roles
*
* @since 1.12
*/
@Entity
@Table(name = "user_roles")
public class UserRole extends BaseIdentifiable {
@Column(name = "user_id")
private Integer userId;
@Column(name = "role")
private String role;
@Column(name = "resource_id")
private Integer resourceId;
public UserRole(Integer userId, String role, Integer resourceId) {
this.userId = userId;
this.role = role;
this.resourceId = resourceId;
}
public UserRole() {
}
public Integer getUserId() {
return userId;
}
public UserRole setUserId(Integer userId) {
this.userId = userId;
return this;
}
public String getRole() {
return role;
}
public UserRole setRole(String role) {
this.role = role;
return this;
}
public Integer getResourceId() {
return resourceId;
}
public UserRole setResourceId(Integer resourceId) {
this.resourceId = resourceId;
return this;
}
}
| lgpl-3.0 |
loftuxab/community-edition-old | projects/sdk/samples/CustomLogin/source/org/alfresco/sample/CustomLoginBean.java | 1790 | /*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.sample;
import java.util.Date;
import org.alfresco.web.bean.LoginBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class CustomLoginBean extends LoginBean
{
private static final Log logger = LogFactory.getLog(CustomLoginBean.class);
@Override
public String login()
{
String outcome = super.login();
// log to the console who logged in and when
String username = this.getUsername();
if (username == null)
{
username = "Guest";
}
logger.info(username + " has logged in at " + new Date());
return outcome;
}
@Override
public String logout()
{
String outcome = super.logout();
// log to the console who logged out and when
String username = this.getUsername();
if (username == null)
{
username = "Guest";
}
logger.info(username + " logged out at " + new Date());
return outcome;
}
}
| lgpl-3.0 |
MinecraftBoomMod/Minecraft-Boom | src/main/java/soupbubbles/minecraftboom/handler/ConfigurationHandler.java | 13226 | package soupbubbles.minecraftboom.handler;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.Level;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntityFurnace;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import soupbubbles.minecraftboom.MinecraftBoom;
import soupbubbles.minecraftboom.lib.Reference;
import soupbubbles.minecraftboom.util.IStairSlab;
import soupbubbles.minecraftboom.util.Utils;
public class ConfigurationHandler
{
public static Configuration configuration;
public static boolean firstLoad = false;
public static final List<String> CATEGORY_LIST = new ArrayList<String>();
public static final String CATEGORY_WORLD_GEN = addCategory("World Generation");
public static final String CATEGORY_TWEAKS = addCategory("Tweaks");
public static final String CATEGORY_COMPAT = addCategory("Compatibility");
public static final String CATEGORY_BLOCKS = addCategory("Blocks");
public static final String CATEGORY_ITEMS = addCategory("Items");
public static final String CATEGORY_MOBS = addCategory("Mobs");
//General
public static boolean minecraftBoomButton;
public static boolean removeBlockChildren;
//Worldgen
public static boolean generateRoses;
public static boolean generatePumpkins;
public static boolean generateFallenTrees;
public static boolean generateFineGravel;
public static boolean generateNetherWells;
public static boolean generateEndPiles;
//Tweaks
public static boolean smeltPumpkin;
public static boolean blazeBonemeal;
public static boolean blazeFuel;
public static int blazeBurnTime;
public static boolean removeSlimeBall;
public static boolean leavesDropSticks;
public static double stickDropRate;
public static boolean spruceDropsPinecones;
public static double pineconeDropRate;
public static boolean replaceLoadingScreen;
public static boolean silverfishDrop;
public static boolean polarBearDrop;
public static boolean witherSkeletonDrop;
public static boolean elderGuardianDrop;
//Compat
public static boolean inspirations;
public static boolean tryGenerateRose;
//Blocks
public static List<Boolean> allowedBlocks = new ArrayList<Boolean>();
public static boolean vanillaBlocks;
public static boolean charcoalBlockFuel;
public static int charcoalBlockBurnTime;
public static boolean blazeBlockFuel;
public static int blazeBlockBurnTime;
public static boolean witherBoneBlockFuel;
public static int witherBoneBlockBurnTime;
//Items
public static List<Boolean> allowedItems = new ArrayList<Boolean>();
public static boolean pineconeFuel;
public static int pineconeBurnTime;
public static boolean witherBoneFuel;
public static int witherBoneBurnTime;
public static boolean telescopeLoot;
public static void initConfiguation(File configFile)
{
if (configuration == null)
{
configuration = new Configuration(configFile, true);
firstLoad = true;
MinecraftBoom.instance.logger.log(Level.INFO, "No configuration file for Minecraft Boom was found, creating new one");
}
//General
minecraftBoomButton = loadCategory("Enable Minecraft Boom Button", Configuration.CATEGORY_GENERAL, "Enabling allows the Minecraft Boom button to appear in the Options menu. The Minecraft Boom configuration can always be reached through Mods -> Minecraft Boom -> Config.", true);
removeBlockChildren = loadCategory("Disable block children if the parent block is disabled", Configuration.CATEGORY_GENERAL, "If this returns true the children blocks (stairs and slabs) will be disabled if their parent block is disabled", true);
//Worldgen
generateRoses = loadPropBool("Generate Roses", CATEGORY_WORLD_GEN, "Enabling allows Roses to naturally spawn in the Overworld.", true);
generatePumpkins = loadPropBool("Generate Pumpkins", CATEGORY_WORLD_GEN, "Enabling allows Faceless Pumpkin Patches to naturally spawn in the Overworld.", true);
generateFallenTrees = loadPropBool("Generate Fallen Trees", CATEGORY_WORLD_GEN, "Enabling allows Fallen Trees to naturally spawn in the Overworld.", true);
generateFineGravel = loadPropBool("Generate Fine Gravel", CATEGORY_WORLD_GEN, "Enabling allows Fine Gravel Patches to naturally spawn in the Overworld.", true);
generateNetherWells = loadPropBool("Generate Nether Wells", CATEGORY_WORLD_GEN, "Enabling allows Nether Wells to spawn in the Nether.", true);
generateEndPiles = loadPropBool("Generate End Piles", CATEGORY_WORLD_GEN, "Enabling allows End Piles to spawn in the End.", true);
//Tweaks
smeltPumpkin = loadPropBool("Pumpking smelts into Orange Dye", CATEGORY_TWEAKS, "Enabling allows Pumpkins (Faceless and Hollowed) to smelt into Orange Dye in a Furnace.", true);
blazeBonemeal = loadPropBool("Use Blaze Powder as Bonemeal", CATEGORY_TWEAKS, "Enabling allows Blaze Powder to be used as a Bonemeal on Nether Wart.", true);
blazeFuel = loadPropBool("Use Blaze Powder as fuel in a Furnace", CATEGORY_TWEAKS, "Enabling allows Blaze Powder to be used as a fuel in a Furnace.", true);
blazeBurnTime = loadPropInt("Blaze Powder Burn Time", CATEGORY_TWEAKS, "", 1200, "Use Blaze Powder as fuel in a Furnace");
removeSlimeBall = loadPropBool("Remove Slime Balls from Sticky Pistons", CATEGORY_TWEAKS, "Enabling allows the Slime Ball being removed from Sticky Pistons by sneaking and right-clicking with a shovel.", true);
leavesDropSticks = loadPropBool("Leaves drop Sticks", CATEGORY_TWEAKS, "Enabling allows a small chance of Sticks dropping when destroying Leaves.", true);
stickDropRate = loadPropDouble("Stick Drop Rate", CATEGORY_TWEAKS, "", 0.2, "Leaves drop Sticks");
spruceDropsPinecones = loadPropBool("Spruce Leaves drop Pinecones", CATEGORY_TWEAKS, "Enabling allows a small chance of Spruce Leaves to drop Pinecones", true);
pineconeDropRate = loadPropDouble("Pinecone Drop Rate", CATEGORY_TWEAKS, "", 0.02, "Spruce Leaves drop Pinecones");
replaceLoadingScreen = loadPropBool("Replace Default Loading Screen", CATEGORY_TWEAKS, "Enabling allows the background in the loading screens to be more appropriate for dimension travel.", true);
silverfishDrop = loadPropBool("Silverfish drop Iron Nuggets", CATEGORY_TWEAKS, "", true);
polarBearDrop = loadPropBool("Polar Bears drop Polar Bear Fur", CATEGORY_TWEAKS, "", true);
witherSkeletonDrop = loadPropBool("Wither Skeletons drop Wither Bones", CATEGORY_TWEAKS, "", true);
elderGuardianDrop = loadPropBool("Elder Guardians drop Elder Guardian Spikes", CATEGORY_TWEAKS, "", true);
//Compat
inspirations = loadPropBool("Inspirations Compatibility", CATEGORY_COMPAT, "Enabling allows compatibility with the mod Inspirations.", true);
tryGenerateRose = loadPropBool("Try Generating Inspiration Roses", CATEGORY_COMPAT, "Enabling will allow Minecraft Boom to generate the Rose from Inspiration since the mod doesn't add worldgen.", false, "Inspirations Compatibility");
//Blocks
vanillaBlocks = loadPropBool("Vanilla Stairs and Slabs", CATEGORY_BLOCKS, "", true);
charcoalBlockFuel = loadPropBool("Use Charcoal Blocks as fuel in a Furnace", CATEGORY_BLOCKS, "", true, "Charcoal Block");
charcoalBlockBurnTime = loadPropInt("Charcoal Block Burn Time", CATEGORY_BLOCKS, "", TileEntityFurnace.getItemBurnTime(new ItemStack(Blocks.COAL_BLOCK)), "Charcoal Block");
blazeBlockFuel = loadPropBool("Use Blaze Powder Blocks as fuel in a Furnace", CATEGORY_BLOCKS, "", true, "Blaze Powder Block");
blazeBlockBurnTime = loadPropInt("Blaze Powder Block Burn Time", CATEGORY_BLOCKS, "", 12000, "Blaze Powder Block");
witherBoneBlockFuel = loadPropBool("Use Charred Bone Blocks as fuel in a Furnace", CATEGORY_BLOCKS, "", true, "Charred Bone Block");
witherBoneBlockBurnTime = loadPropInt("Charred Bone Block Burn Time", CATEGORY_BLOCKS, "", 2000, "Charred Bone Block");
//Items
pineconeFuel = loadPropBool("Use Pinecones as fuel in a Furnace", CATEGORY_ITEMS, "", true, "Pinecone");
pineconeBurnTime = loadPropInt("Pinecone Burn Time", CATEGORY_ITEMS, "", 300, "Pinecone");
witherBoneFuel = loadPropBool("Use Wither Bones as fuel in a Furnace", CATEGORY_ITEMS, "", true, "Wither Bone");
witherBoneBurnTime = loadPropInt("Wither Bone Burn Time", CATEGORY_ITEMS, "", 500, "Wither Bone");
telescopeLoot = loadPropBool("Spawn Telescopes in Dungeon Loot", CATEGORY_ITEMS, "", true, "Telescope");
saveConfiguration();
MinecraftForge.EVENT_BUS.register(configuration);
}
public static void saveConfiguration()
{
if (configuration.hasChanged())
{
configuration.save();
}
}
@SubscribeEvent
public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event)
{
if (event.getModID().equalsIgnoreCase(Reference.MOD_ID))
{
saveConfiguration();
}
}
private static String addCategory(String name)
{
CATEGORY_LIST.add(name);
return name;
}
public static void createItemConfig(Item item)
{
allowedItems.add(loadPropBool(Utils.getConfigName(item), CATEGORY_ITEMS, "", true));
saveConfiguration();
}
public static void createBlockConfig(Block block)
{
allowedBlocks.add(loadPropBool(Utils.getConfigName(block), CATEGORY_BLOCKS, "", true));
if (block instanceof IStairSlab && ((IStairSlab) block).hasStairSlab())
{
loadPropBool(Utils.getStairSlabConfigName(Utils.getConfigName(block), block), CATEGORY_BLOCKS, "", true, Utils.getConfigName(block));
}
saveConfiguration();
}
public static void createVanillaConfig(Block block)
{
loadPropBool(Utils.getStairSlabConfigName(Utils.getConfigName(block), block), CATEGORY_BLOCKS, "", true, "Vanilla Stairs and Slabs");
saveConfiguration();
}
public static int loadPropInt(String name, String category, String comment, int default_)
{
return loadPropInt(name, category, comment, default_, name);
}
public static int loadPropInt(String name, String category, String comment, int default_, String parent)
{
Property prop = configuration.get(category + "." + parent, name, default_);
prop.setComment(comment);
return prop.getInt(default_);
}
public static double loadPropDouble(String name, String category, String comment, double default_)
{
return loadPropDouble(name, category, comment, default_, name);
}
public static double loadPropDouble(String name, String category, String comment, double default_, String parent)
{
Property prop = configuration.get(category + "." + parent, name, default_);
prop.setComment(comment);
return prop.getDouble(default_);
}
public static boolean loadPropBool(String name, String category, String comment, boolean default_)
{
return loadPropBool(name, category, comment, default_, name);
}
public static boolean loadPropBool(String name, String category, String comment, boolean default_, String parent)
{
Property prop = configuration.get(category + "." + parent, name, default_);
prop.setComment(comment);
return prop.getBoolean(default_);
}
public static String loadPropString(String name, String category, String comment, String default_)
{
return loadPropString(name, category, comment, default_, name);
}
public static String loadPropString(String name, String category, String comment, String default_, String parent)
{
Property prop = configuration.get(category + "." + parent, name, default_);
prop.setComment(comment);
return prop.getString();
}
public static String[] loadPropStringList(String name, String category, String comment, String[] default_)
{
return loadPropStringList(name, category, comment, default_, name);
}
public static String[] loadPropStringList(String name, String category, String comment, String[] default_, String parent)
{
Property prop = configuration.get(category, name, default_);
prop.setComment(comment);
return prop.getStringList();
}
public static boolean loadCategory(String name, String category, String comment, boolean default_)
{
Property prop = configuration.get(category, name, default_);
prop.setComment(comment);
return prop.getBoolean(default_);
}
} | lgpl-3.0 |
ptitjes/jlato | src/main/java/org/jlato/internal/td/expr/TDBinaryExpr.java | 4384 | /*
* Copyright (C) 2015-2016 Didier Villevalois.
*
* This file is part of JLaTo.
*
* JLaTo 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.
*
* JLaTo 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 JLaTo. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jlato.internal.td.expr;
import org.jlato.internal.bu.expr.SBinaryExpr;
import org.jlato.internal.bu.expr.SExpr;
import org.jlato.internal.td.TDLocation;
import org.jlato.internal.td.TDTree;
import org.jlato.tree.Kind;
import org.jlato.tree.expr.BinaryExpr;
import org.jlato.tree.expr.BinaryOp;
import org.jlato.tree.expr.Expr;
import org.jlato.util.Mutation;
/**
* A binary expression.
*/
public class TDBinaryExpr extends TDTree<SBinaryExpr, Expr, BinaryExpr> implements BinaryExpr {
/**
* Returns the kind of this binary expression.
*
* @return the kind of this binary expression.
*/
public Kind kind() {
return Kind.BinaryExpr;
}
/**
* Creates a binary expression for the specified tree location.
*
* @param location the tree location.
*/
public TDBinaryExpr(TDLocation<SBinaryExpr> location) {
super(location);
}
/**
* Creates a binary expression with the specified child trees.
*
* @param left the left child tree.
* @param op the op child tree.
* @param right the right child tree.
*/
public TDBinaryExpr(Expr left, BinaryOp op, Expr right) {
super(new TDLocation<SBinaryExpr>(SBinaryExpr.make(TDTree.<SExpr>treeOf(left), op, TDTree.<SExpr>treeOf(right))));
}
/**
* Returns the left of this binary expression.
*
* @return the left of this binary expression.
*/
public Expr left() {
return location.safeTraversal(SBinaryExpr.LEFT);
}
/**
* Replaces the left of this binary expression.
*
* @param left the replacement for the left of this binary expression.
* @return the resulting mutated binary expression.
*/
public BinaryExpr withLeft(Expr left) {
return location.safeTraversalReplace(SBinaryExpr.LEFT, left);
}
/**
* Mutates the left of this binary expression.
*
* @param mutation the mutation to apply to the left of this binary expression.
* @return the resulting mutated binary expression.
*/
public BinaryExpr withLeft(Mutation<Expr> mutation) {
return location.safeTraversalMutate(SBinaryExpr.LEFT, mutation);
}
/**
* Returns the op of this binary expression.
*
* @return the op of this binary expression.
*/
public BinaryOp op() {
return location.safeProperty(SBinaryExpr.OP);
}
/**
* Replaces the op of this binary expression.
*
* @param op the replacement for the op of this binary expression.
* @return the resulting mutated binary expression.
*/
public BinaryExpr withOp(BinaryOp op) {
return location.safePropertyReplace(SBinaryExpr.OP, op);
}
/**
* Mutates the op of this binary expression.
*
* @param mutation the mutation to apply to the op of this binary expression.
* @return the resulting mutated binary expression.
*/
public BinaryExpr withOp(Mutation<BinaryOp> mutation) {
return location.safePropertyMutate(SBinaryExpr.OP, mutation);
}
/**
* Returns the right of this binary expression.
*
* @return the right of this binary expression.
*/
public Expr right() {
return location.safeTraversal(SBinaryExpr.RIGHT);
}
/**
* Replaces the right of this binary expression.
*
* @param right the replacement for the right of this binary expression.
* @return the resulting mutated binary expression.
*/
public BinaryExpr withRight(Expr right) {
return location.safeTraversalReplace(SBinaryExpr.RIGHT, right);
}
/**
* Mutates the right of this binary expression.
*
* @param mutation the mutation to apply to the right of this binary expression.
* @return the resulting mutated binary expression.
*/
public BinaryExpr withRight(Mutation<Expr> mutation) {
return location.safeTraversalMutate(SBinaryExpr.RIGHT, mutation);
}
}
| lgpl-3.0 |
lbndev/sonarqube | server/sonar-server/src/main/java/org/sonar/server/language/ws/ListAction.java | 3630 | /*
* SonarQube
* Copyright (C) 2009-2017 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.language.ws;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Resources;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.RequestHandler;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.text.JsonWriter;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.List;
import java.util.SortedMap;
import java.util.regex.Pattern;
/**
* @since 5.1
*/
public class ListAction implements RequestHandler {
private static final String MATCH_ALL = ".*";
private final Languages languages;
public ListAction(Languages languages) {
this.languages = languages;
}
@Override
public void handle(Request request, Response response) throws Exception {
String query = request.param(Param.TEXT_QUERY);
int pageSize = request.mandatoryParamAsInt("ps");
JsonWriter json = response.newJsonWriter().beginObject().name("languages").beginArray();
for (Language language : listMatchingLanguages(query, pageSize)) {
json.beginObject().prop("key", language.getKey()).prop("name", language.getName()).endObject();
}
json.endArray().endObject().close();
}
void define(WebService.NewController controller) {
NewAction action = controller.createAction("list")
.setDescription("List supported programming languages")
.setSince("5.1")
.setHandler(this)
.setResponseExample(Resources.getResource(getClass(), "example-list.json"));
action.createParam(Param.TEXT_QUERY)
.setDescription("A pattern to match language keys/names against")
.setExampleValue("java");
action.createParam("ps")
.setDescription("The size of the list to return, 0 for all languages")
.setExampleValue("25")
.setDefaultValue("0");
}
private Collection<Language> listMatchingLanguages(@Nullable String query, int pageSize) {
Pattern pattern = Pattern.compile(query == null ? MATCH_ALL : MATCH_ALL + Pattern.quote(query) + MATCH_ALL, Pattern.CASE_INSENSITIVE);
SortedMap<String, Language> languagesByName = Maps.newTreeMap();
for (Language lang : languages.all()) {
if (pattern.matcher(lang.getKey()).matches() || pattern.matcher(lang.getName()).matches()) {
languagesByName.put(lang.getName(), lang);
}
}
List<Language> result = Lists.newArrayList(languagesByName.values());
if (pageSize > 0 && pageSize < result.size()) {
result = result.subList(0, pageSize);
}
return result;
}
}
| lgpl-3.0 |
subes/invesdwin-nowicket | invesdwin-nowicket-examples/invesdwin-nowicket-examples-mvp-bsgcoach/src/main/java/com/bsgcoach/web/ABsgCoachWebPage.java | 4610 | package com.bsgcoach.web;
import javax.annotation.concurrent.NotThreadSafe;
import org.apache.wicket.Page;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.apache.wicket.request.resource.ResourceReference;
import com.bsgcoach.web.footer.FooterPanel;
import com.bsgcoach.web.guide.RedirectToGuidePage;
import de.agilecoders.wicket.core.markup.html.bootstrap.image.GlyphIconType;
import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.Navbar;
import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.NavbarButton;
import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.NavbarComponents;
import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.NavbarExternalLink;
import de.invesdwin.nowicket.application.AWebPage;
import de.invesdwin.nowicket.application.auth.ABaseWebApplication;
import de.invesdwin.nowicket.application.filter.AWebApplication;
import de.invesdwin.nowicket.component.footer.AFooter;
@NotThreadSafe
public abstract class ABsgCoachWebPage extends AWebPage {
private static final boolean INVERTED_HEADER_AND_FOOTER = true;
private static final ResourceReference LOGO = new PackageResourceReference(ABsgCoachWebPage.class, "logo.png");
private static final PackageResourceReference BACKGROUND = new PackageResourceReference(ABsgCoachWebPage.class,
"bg.jpg");
public ABsgCoachWebPage(final IModel<?> model) {
super(model);
}
@Override
protected Navbar newNavbar(final String id) {
final Navbar navbar = super.newNavbar(id);
navbar.setBrandName(null);
navbar.setBrandImage(LOGO, Model.of("bsg-coach"));
navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.LEFT,
new NavbarButton<Void>(RedirectToGuidePage.class, Model.of("Home")).setIconType(GlyphIconType.home)));
navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.LEFT,
new NavbarButton<Void>(ABaseWebApplication.get().getHomePage(), Model.of("Get Feedback"))
.setIconType(GlyphIconType.upload)));
navbar.addComponents(NavbarComponents.transform(Navbar.ComponentPosition.RIGHT,
new NavbarExternalLink(Model.of("mailto:gsubes@gmail.com"))
.setLabel(Model.of("Tell us what you think!")).setIconType(GlyphIconType.envelope)));
navbar.setInverted(INVERTED_HEADER_AND_FOOTER);
return navbar;
}
@Override
protected Class<? extends Page> getNavbarHomePage() {
return RedirectToGuidePage.class;
}
@Override
protected AFooter newFooter(final String id) {
return new FooterPanel(id);
}
@Override
public void renderHead(final IHeaderResponse response) {
super.renderHead(response);
final StringBuilder bgCss = new StringBuilder();
bgCss.append("body {\n");
bgCss.append(" background: url(");
bgCss.append(RequestCycle.get().urlFor(BACKGROUND, null));
bgCss.append(") no-repeat center center fixed;\n");
bgCss.append("}\n");
bgCss.append("nav {\n");
bgCss.append(" opacity: 0.75;\n");
bgCss.append("}\n");
bgCss.append(".footer .panel-footer {\n");
bgCss.append(" background-color: #222;\n");
bgCss.append(" border-color: #080808;\n");
bgCss.append(" opacity: 0.75;\n");
bgCss.append("}\n");
response.render(CssHeaderItem.forCSS(bgCss, "bsgBgCss"));
if (AWebApplication.get().usesDeploymentConfig()) {
//CHECKSTYLE:OFF fdate
response.render(JavaScriptHeaderItem
.forScript("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){" //
+ "(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o)," //
+ "m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)" //
+ "})(window,document,'script','//www.google-analytics.com/analytics.js','ga');" //
+ "ga('create', 'UA-75774568-1', 'auto');" //
+ "ga('send', 'pageview');", "googleAnalytics"));
//CHECKSTYLE:ON
}
}
}
| lgpl-3.0 |
luobuccc/JavaPD | Chapter7/src/Chapter7/ThreadSleep.java | 761 | package Chapter7;
/**
* Created by PuFan on 2016/11/30.
*
* @author PuFan
*/
public class ThreadSleep {
static public void main(String[] args) {
Thread t1 = new Thread(new SleepRunner());
Thread t2 = new Thread(new SleepRunner1());
t1.start();
t2.start();
}
}
class SleepRunner implements Runnable {
public void run() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < 1000; ++i)
System.out.println("Sleep " + i);
}
}
class SleepRunner1 implements Runnable {
public void run() {
for (int i = 0; i < 1000; ++i)
System.out.println("Normal " + i);
}
} | lgpl-3.0 |
SOCR/HTML5_WebSite | SOCR2.8/src/edu/ucla/stat/SOCR/experiments/CrapsExperiment.java | 14111 | /****************************************************
Statistics Online Computational Resource (SOCR)
http://www.StatisticsResource.org
All SOCR programs, materials, tools and resources are developed by and freely disseminated to the entire community.
Users may revise, extend, redistribute, modify under the terms of the Lesser GNU General Public License
as published by the Open Source Initiative http://opensource.org/licenses/. All efforts should be made to develop and distribute
factually correct, useful, portable and extensible resource all available in all digital formats for free over the Internet.
SOCR resources are distributed in the hope that they will be useful, but without
any warranty; without any explicit, implicit or implied warranty for merchantability or
fitness for a particular purpose. See the GNU Lesser General Public License for
more details see http://opensource.org/licenses/lgpl-license.php.
http://www.SOCR.ucla.edu
http://wiki.stat.ucla.edu/socr
It s Online, Therefore, It Exists!
****************************************************/
package edu.ucla.stat.SOCR.experiments;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import edu.ucla.stat.SOCR.core.*;
import edu.ucla.stat.SOCR.distributions.*;
import edu.ucla.stat.SOCR.util.*;
/** The basic casino craps game */
public class CrapsExperiment extends Experiment {
//Constants
public final static int PASS = 0, DONTPASS = 1, FIELD = 2, CRAPS = 3,
CRAPS2 = 4, CRAPS3 = 5, CRAPS12 = 6, SEVEN = 7, ELEVEN = 8, BIG6 = 9,
BIG8 = 10, HARDWAY4 = 11, HARDWAY6 = 12, HARDWAY8 = 13, HARDWAY10 = 14;
//Variables
private int x, y, u, v, point1, point2, win, rolls, betType = PASS;
private double[] prob = new double[] { 251.0 / 495, 0, 244.0 / 495 };
//Objects
private JPanel toolbar = new JPanel();
private DiceBoard diceBoard = new DiceBoard(4);
private JComboBox<String> betJComboBox = new JComboBox<>();
private FiniteDistribution dist = new FiniteDistribution(-1, 1, 1, prob);
private RandomVariable profitRV = new RandomVariable(dist, "W");
private RandomVariableGraph profitGraph = new RandomVariableGraph(profitRV);
private RandomVariableTable profitTable = new RandomVariableTable(profitRV);
/** Initialize the experiment */
public CrapsExperiment() {
setName("Craps Experiment");
//Event listeners
betJComboBox.addItemListener(this);
//Bet choice
betJComboBox.addItem("Pass");
betJComboBox.addItem("Don't Pass");
betJComboBox.addItem("Field");
betJComboBox.addItem("Craps");
betJComboBox.addItem("Craps 2");
betJComboBox.addItem("Craps 3");
betJComboBox.addItem("Craps 12");
betJComboBox.addItem("Seven");
betJComboBox.addItem("Eleven");
betJComboBox.addItem("Big 6");
betJComboBox.addItem("Big 8");
betJComboBox.addItem("Hardway 4");
betJComboBox.addItem("Hardway 6");
betJComboBox.addItem("Hardway 8");
betJComboBox.addItem("Hardway 10");
//toolbars
toolbar.setLayout(new FlowLayout(FlowLayout.CENTER));
toolbar.add(betJComboBox);
addToolbar(toolbar);
//Graphs
addGraph(diceBoard);
addGraph(profitGraph);
//Table
addTable(profitTable);
reset();
}
/**
* Perform the experiment: roll the dice, and depending on the bet,
* determine whether to roll the dice a second time. Finally, deterimine the
* outcome of the bet
*/
public void doExperiment() {
super.doExperiment();
rolls = 1;
x = (int) Math.ceil(6 * Math.random());
y = (int) Math.ceil(6 * Math.random());
point1 = x + y;
point2 = 0;
switch (betType) {
case PASS:
if (point1 == 7 | point1 == 11) win = 1;
else if (point1 == 2 | point1 == 3 | point1 == 12) win = -1;
else {
while (point2 != point1 & point2 != 7) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (point2 == point1) win = 1;
else win = -1;
}
break;
case DONTPASS:
if (point1 == 7 | point1 == 11) win = -1;
else if (point1 == 2 | point1 == 3) win = 1;
else if (point1 == 12) win = 0;
else {
while (point2 != point1 & point2 != 7) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (point2 == point1) win = -1;
else win = 1;
}
break;
case FIELD:
if (point1 == 3 | point1 == 4 | point1 == 9 | point1 == 10
| point1 == 11) win = 1;
else if (point1 == 2 | point1 == 12) win = 2;
else win = -1;
break;
case CRAPS:
if (point1 == 2 | point1 == 3 | point1 == 12) win = 7;
else win = -1;
break;
case CRAPS2:
if (point1 == 2) win = 30;
else win = -1;
break;
case CRAPS3:
if (point1 == 3) win = 15;
else win = -1;
break;
case CRAPS12:
if (point1 == 12) win = 30;
else win = -1;
break;
case SEVEN:
if (point1 == 7) win = 4;
else win = -1;
break;
case ELEVEN:
if (point1 == 11) win = 15;
else win = -1;
break;
case BIG6:
if (point1 == 6) win = 1;
else if (point1 == 7) win = -1;
else {
while (point2 != 6 & point2 != 7) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (point2 == 6) win = 1;
else win = -1;
}
break;
case BIG8:
if (point1 == 8) win = 1;
else if (point1 == 7) win = -1;
else {
while (point2 != 8 & point2 != 7) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (point2 == 8) win = 1;
else win = -1;
}
break;
case HARDWAY4:
if (x == 2 & y == 2) win = 7;
else if (point1 == 7 | point1 == 4) win = -1;
else {
while (point2 != 7 & point2 != 4) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (u == 2 & v == 2) win = 7;
else win = -1;
}
break;
case HARDWAY6:
if (x == 3 & y == 3) win = 9;
else if (point1 == 7 | point1 == 6) win = -1;
else {
while (point2 != 7 & point2 != 6) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (u == 3 & v == 3) win = 9;
else win = -1;
}
break;
case HARDWAY8:
if (x == 4 & y == 4) win = 9;
else if (point1 == 7 | point1 == 8) win = -1;
else {
while (point2 != 7 & point2 != 8) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (u == 4 & v == 4) win = 9;
else win = -1;
}
break;
case HARDWAY10:
if (x == 5 & y == 5) win = 7;
else if (point1 == 7 | point1 == 10) win = -1;
else {
while (point2 != 7 & point2 != 10) {
u = (int) Math.ceil(6 * Math.random());
v = (int) Math.ceil(6 * Math.random());
point2 = u + v;
rolls++;
}
if (u == 5 & v == 5) win = 7;
else win = -1;
}
break;
}
profitRV.setValue(win);
}
/**
* This method runs the the experiment one time, and add sounds depending on
* the outcome of the experiment.
*/
public void step() {
doExperiment();
update();
try {
if (win == -1) play("sounds/0.au");
else play("sounds/1.au");
} catch (Exception e) {
;
}
}
//Reset
public void reset() {
super.reset();
diceBoard.showDice(0);
profitRV.reset();
getRecordTable().append("\t(X,Y)\t(U,V)\tN\tW");
profitGraph.reset();
profitTable.reset();
}
//Update
public void update() {
super.update();
String updateText;
diceBoard.getDie(0).setValue(x);
diceBoard.getDie(1).setValue(y);
if (rolls > 1) {
diceBoard.getDie(2).setValue(u);
diceBoard.getDie(3).setValue(v);
diceBoard.showDice(4);
} else diceBoard.showDice(2);
updateText = "\t(" + x + "," + y + ")";
if (rolls > 1) updateText = updateText + "\t(" + u + "," + v + ")";
else updateText = updateText + "\t(*,*)";
updateText = updateText + "\t" + rolls + "\t" + win;
getRecordTable().append(updateText);
profitGraph.repaint();
profitTable.update();
}
public void itemStateChanged(ItemEvent event) {
if (event.getSource() == betJComboBox) {
betType = betJComboBox.getSelectedIndex();
switch (betType) {
case PASS:
prob = new double[3];
prob[0] = 251.0 / 495;
prob[2] = 244.0 / 495;
dist.setParameters(-1, 1, 1, prob);
break;
case DONTPASS:
prob = new double[3];
prob[0] = 244.0 / 495;
prob[1] = 1.0 / 36;
prob[2] = 949.0 / 1980;
dist.setParameters(-1, 1, 1, prob);
break;
case FIELD:
prob = new double[4];
prob[0] = 5.0 / 9;
prob[2] = 7.0 / 18;
prob[3] = 1.0 / 18;
dist.setParameters(-1, 2, 1, prob);
break;
case CRAPS:
prob = new double[9];
prob[0] = 8.0 / 9;
prob[8] = 1.0 / 9;
dist.setParameters(-1, 7, 1, prob);
break;
case CRAPS2:
prob = new double[32];
prob[0] = 35.0 / 36;
prob[31] = 1.0 / 36;
dist.setParameters(-1, 30, 1, prob);
break;
case CRAPS3:
prob = new double[17];
prob[0] = 17.0 / 18;
prob[16] = 1.0 / 18;
dist.setParameters(-1, 15, 1, prob);
break;
case CRAPS12:
prob = new double[32];
prob[0] = 35.0 / 36;
prob[31] = 1.0 / 36;
dist.setParameters(-1, 30, 1, prob);
break;
case SEVEN:
prob = new double[6];
prob[0] = 5.0 / 6;
prob[5] = 1.0 / 6;
dist.setParameters(-1, 4, 1, prob);
break;
case ELEVEN:
prob = new double[17];
prob[0] = 17.0 / 18;
prob[16] = 1.0 / 18;
dist.setParameters(-1, 15, 1, prob);
break;
case BIG6:
prob = new double[3];
prob[0] = 6.0 / 11;
prob[2] = 5.0 / 11;
dist.setParameters(-1, 1, 1, prob);
break;
case BIG8:
prob = new double[3];
prob[0] = 6.0 / 11;
prob[2] = 5.0 / 11;
dist.setParameters(-1, 1, 1, prob);
break;
case HARDWAY4:
prob = new double[9];
prob[0] = 8.0 / 9;
prob[8] = 1.0 / 9;
dist.setParameters(-1, 7, 1, prob);
break;
case HARDWAY6:
prob = new double[11];
prob[0] = 10. / 11;
prob[10] = 1.0 / 11;
dist.setParameters(-1, 9, 1, prob);
break;
case HARDWAY8:
prob = new double[11];
prob[0] = 10. / 11;
prob[10] = 1.0 / 11;
dist.setParameters(-1, 9, 1, prob);
break;
case HARDWAY10:
prob = new double[9];
prob[0] = 8.0 / 9;
prob[8] = 1.0 / 9;
dist.setParameters(-1, 7, 1, prob);
break;
}
reset();
} else super.itemStateChanged(event);
}
}
| lgpl-3.0 |
SOCR/HTML5_WebSite | SOCR2.8/src/edu/ucla/stat/SOCR/util/NormalCurve.java | 16918 | /****************************************************
Statistics Online Computational Resource (SOCR)
http://www.StatisticsResource.org
All SOCR programs, materials, tools and resources are developed by and freely disseminated to the entire community.
Users may revise, extend, redistribute, modify under the terms of the Lesser GNU General Public License
as published by the Open Source Initiative http://opensource.org/licenses/. All efforts should be made to develop and distribute
factually correct, useful, portable and extensible resource all available in all digital formats for free over the Internet.
SOCR resources are distributed in the hope that they will be useful, but without
any warranty; without any explicit, implicit or implied warranty for merchantability or
fitness for a particular purpose. See the GNU Lesser General Public License for
more details see http://opensource.org/licenses/lgpl-license.php.
http://www.SOCR.ucla.edu
http://wiki.stat.ucla.edu/socr
It s Online, Therefore, It Exists!
****************************************************/
/* created by annie che 20060915. */
package edu.ucla.stat.SOCR.util;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import edu.ucla.stat.SOCR.analyses.result.NormalPowerResult;
import edu.ucla.stat.SOCR.distributions.Domain;
import edu.ucla.stat.SOCR.distributions.IntervalData;
import edu.ucla.stat.SOCR.distributions.NormalDistribution;
import edu.ucla.stat.SOCR.modeler.Modeler;
import edu.ucla.stat.SOCR.modeler.gui.ModelerColor;
/**
* This class models an interactive histogram. The user can click on the horizontal axes to add points to the data set.
*/
public class NormalCurve extends ModelerHistogram {
protected boolean drawData = false;
protected double[] rawData = null;
protected NormalDistribution dataDist = null;
protected int[] freq = null;
protected int sampleSize;
protected Domain domain;
protected IntervalData intervalData;
protected double maxRelFreq = -1;
protected Frequency frequency = null;
protected HashMap map = null;
private double mu0;
private double muA;
private double sigma;
private double sampleSE;
private double ciLeft;
private double ciRight;
private NormalDistribution normal0 = null;
private NormalDistribution normalA = null;
private boolean fillArea = true;
private Color fillColor1 = Color.PINK;
private Color fillColor2 = fillColor1.brighter();
private Color fillColor3 = Color.YELLOW;
private Color fillColor4 = fillColor3.brighter();
private Color ciColor = Color.GREEN;
private double xIntersect;
private double yIntersect;
private boolean useSampleMean = false;
private String hypothesisType = null;
private static byte NORMAL_CURVE_THICKNESS = 1;
public NormalCurve(double a, double b, double w) {
super(a, b, w);
this.modelType = Modeler.CONTINUOUS_DISTRIBUTION_TYPE;
setDrawUserClicks(false);
}
public NormalCurve() {
super();
setDrawUserClicks(false);
}
/**
* @param rawData the rawData to set
* @uml.property name="rawData"
*/
public void setRawData(double[] input) {
sampleSize = input.length;
try {
this.rawData = input;
double dataMax = 0;
try {
dataMax = QSortAlgorithm.max(this.rawData);
} catch (Exception e) {
}
double dataMin = 0;
try {
dataMin = QSortAlgorithm.min(this.rawData);
} catch (Exception e) {
}
domain = new Domain(dataMin, dataMax, 1);
intervalData = new IntervalData(domain, null);
setIntervalData(intervalData);
frequency = new Frequency(rawData);
map = frequency.getMap();
frequency.computeFrequency();
maxRelFreq = frequency.getMaxRelFreq();
} catch (Exception e) {
}
}
public void setRawDataDistribution(NormalDistribution normal) {
this.dataDist = normal;
}
/**
* @return the rawData
* @uml.property name="rawData"
*/
public double[] getRawData() {
return this.rawData;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D G2 = (Graphics2D) g;
G2.setStroke(new BasicStroke(NORMAL_CURVE_THICKNESS)); // how thick the pen it.
float[] HSBVal = new float[3];
double x = 0;
double width = .5;
double d = 1;
try {
if (rawData.length > 0) {
Set keySet = map.keySet();
Iterator iterator = keySet.iterator();
int freqSize = map.size();
int dataCount = -1;
String id = null;
while (iterator.hasNext()) {
id = (String)iterator.next();
dataCount = ((Integer)map.get(id)).intValue();;
x = Double.parseDouble(id);
double dataCountDouble = dataCount;
double sampleSizeDouble = sampleSize;
d = dataCountDouble/sampleSizeDouble;
g.setColor(Color.PINK);
drawBox(g, x - width / 2, 0, x + width / 2, d);
g.setColor(Color.PINK);
fillBox(g, x - width / 2, 0, x + width / 2, d);
}
}
} catch (Exception e) {
}
if (modelX1 != null && modelX1.length > 0 && modelX2 != null && modelX2.length > 0) {
double maxXVal1 = modelX1[0], maxYVal1 = modelY1[0];
int terms1 = modelY1.length; // how many dx.
double maxXVal2 = modelX2[0], maxYVal2 = modelY1[0];
int term2s = modelY2.length; // how many dx.
double xa, ya;
int subLth = 0;
subLth = (int) (modelX1.length / modelCount);
double x1 = 0;
double y1 = 0;
//for (int j = 0; j < modelCount; j++) {
int j = 0;
x1 = (double) modelX1[0 + j * subLth];
y1 = (double) modelY1[0 + j * subLth];
for (int i = 1; i < subLth; i++) {
xa = modelX1[i + j * subLth];
ya = modelY1[i + j * subLth];
x1 = xa;
y1 = ya;
}
G2.setStroke(new BasicStroke(NORMAL_CURVE_THICKNESS));
G2.setColor(this.getOutlineColor2());
x1 = (double) modelX2[0 + j * subLth];
y1 = (double) modelY2[0 + j * subLth];
for (int i = 1; i < subLth; i++) {
xa = modelX2[i + j * subLth];
ya = modelY2[i + j * subLth];
if (fillArea) {
G2.setColor(Color.YELLOW);
G2.setStroke(new BasicStroke(3f));
if (hypothesisType.equalsIgnoreCase(NormalPowerResult.HYPOTHESIS_TYPE_GT) && (x1 > ciRight)) {
//fillBox(G2, x1, normal0.getDensity(xa), xa, normalA.getDensity(xa) && (x1 < ciLeft)) {
fillBox(G2, x1, 0, xa, normalA.getDensity(xa));
} else if (hypothesisType.equalsIgnoreCase(NormalPowerResult.HYPOTHESIS_TYPE_LT)&& (x1 < ciLeft)) {
//fillBox(G2, x1, normal0.getDensity(xa), xa, normalA.getDensity(xa));
fillBox(G2, x1, 0, xa, normalA.getDensity(xa));
} else if (hypothesisType.equalsIgnoreCase(NormalPowerResult.HYPOTHESIS_TYPE_NE)&& (((x1 > ciRight)) || (x1 < ciLeft))) {
//fillBox(G2, x1, normal0.getDensity(xa), xa, normalA.getDensity(xa));
fillBox(G2, x1, 0, xa, normalA.getDensity(xa));
}
}
x1 = xa;
y1 = ya;
}
// model curve
G2.setStroke(new BasicStroke(NORMAL_CURVE_THICKNESS));
G2.setColor(this.getOutlineColor1());
x1 = (double) modelX1[0 + j * subLth];
y1 = (double) modelY1[0 + j * subLth];
////////////////////System.outprintln("NormalCurve mu0 = " + mu0);
for (int i = 1; i < subLth; i++) {
xa = modelX1[i + j * subLth];
ya = modelY1[i + j * subLth];
//if (x1 < mu0 + 5 * sigma || x1 > mu0 - 5 * sigma)
drawLine(G2, x1, y1, xa, ya); // when modelCount == any #
x1 = xa;
y1 = ya;
}
subLth = (int) (modelX2.length / modelCount);
// model curve
G2.setStroke(new BasicStroke(NORMAL_CURVE_THICKNESS));
G2.setColor(this.getOutlineColor2());
x1 = (double) modelX2[0 + j * subLth];
y1 = (double) modelY2[0 + j * subLth];
////////////////////System.outprintln("NormalCurve muA = " + muA);
for (int i = 1; i < subLth; i++) {
xa = modelX2[i + j * subLth];
ya = modelY2[i + j * subLth];
//if (x1 < muA + 5 * sigma || x1 > muA - 5 * sigma)
drawLine(G2, x1, y1, xa, ya); // when modelCount == any #
x1 = xa;
y1 = ya;
}
}
// draw it second time (looks nicer)
G2.setStroke(new BasicStroke(NORMAL_CURVE_THICKNESS));
g.setColor(Color.BLACK);
super.drawAxis(g, -yMax, yMax, 0.1 * yMax, xMin, VERTICAL); // 6 args
super.drawAxis(g, xMin, xMax, (xMax - xMin) / 10, 0, HORIZONTAL, axisType, listOfTicks); // c must be 0.
}
protected void drawAxisWithDomain(Graphics g, Domain domain, double c, int orientation, int type, ArrayList list){
double t;
double currentUpperBound = domain.getUpperBound(); // of the model (distribution)
double currentLowerBound = domain.getLowerBound();
int domainSize = domain.getSize();
if (orientation == HORIZONTAL){
this.drawLine(g, currentLowerBound, c, currentUpperBound, c);
//Draw tick marks, depending on type
for (int i = 0; i < domainSize; i++){
if (type == MIDPOINTS) {
t = domain.getValue(i);
} else {
t = domain.getBound(i);
}
g.setColor(ModelerColor.HISTOGRAM_TICKMARK);
//g.setStroke(new BasicStroke(3.05f));
//drawTick(g, t, c, VERTICAL);
}
if (type == BOUNDS) {
t = domain.getUpperBound();
drawTick(g, t, c, VERTICAL);
}
//Draw labels
if (type == MIDPOINTS) {
t = domain.getLowerValue();
} else {
t = domain.getLowerBound();
}
drawLabel(g, format(t), t, c, BELOW);
if (type == MIDPOINTS) {
t = domain.getUpperValue();
} else {
t = domain.getUpperBound();
}
drawLabel(g, format(t), t, c, BELOW);
//double mu0 = 0;
//double muA = 0;
//double sigma = 0;
//ciLeft = 0;
//ciRight = 0;
//double sampleSE = 0;
//NormalDistribution normal0 = null;
//NormalDistribution normalA = null;
if (list != null) {
//for (int i = 0; i < list.size(); i++) {
try {
mu0 = Double.parseDouble(((String)list.get(0)));
muA = Double.parseDouble(((String)list.get(1)));
sigma = Double.parseDouble(((String)list.get(2)));
////////////System.outprintln("NormalCurve mu0 = " + mu0);
////////////System.outprintln("NormalCurve muA = " + muA);
//sampleSE = Double.parseDouble(((String)list.get(3)));
normal0 = new NormalDistribution(mu0, sigma);
normalA = new NormalDistribution(muA, sigma);
//ciLeft = mu0 - 1.96 * sigma;
//ciRight = mu0 + 1.96 * sigma;
//t = Double.parseDouble(((String)list.get(i)));
drawLabel(g, format(mu0), mu0, c, BELOW);
drawLabel(g, format(muA), muA, c, BELOW);
Color oldColor = g.getColor();
g.setColor(this.getOutlineColor1());
drawLine(g, mu0, 0, mu0, normal0.getMaxDensity());
//drawLine(g, ciLeft, 0, ciLeft, normal0.getDensity(ciLeft));
//drawLine(g, ciRight, 0, ciRight, normal0.getDensity(ciRight));
g.setColor(this.getOutlineColor2());
drawLine(g, muA, 0, muA, normalA.getMaxDensity());
double density = 0;
if (hypothesisType == null)
hypothesisType = (String)list.get(5);
////////System.outprintln("NormalCurve hypothesisType = " + hypothesisType);
if (hypothesisType.equalsIgnoreCase(NormalPowerResult.HYPOTHESIS_TYPE_NE)){
try {
g.setColor(this.getOutlineColor1());
ciLeft = Double.parseDouble(((String)list.get(3)));
//drawLabel(g, format(ciLeft), ciLeft, c, BELOW);
density = Math.max(normal0.getDensity(ciLeft), normalA.getDensity(ciLeft));
g.setColor(ciColor);
drawLine(g, ciLeft, 0, ciLeft, density);
g.setColor(this.getOutlineColor1());
//hypothesisType = (String)list.get(5);
//////////////System.outprintln("NormalCurve ciLeft = " + ciLeft + " density = " + density);
}
catch (Exception e) {
//////////////System.outprintln("NormalCurve e = " + e);
}
try {
g.setColor(this.getOutlineColor1());
ciRight = Double.parseDouble(((String)list.get(4)));
//drawLabel(g, format(ciLeft), ciLeft, c, BELOW);
density = Math.max(normal0.getDensity(ciRight), normalA.getDensity(ciRight));
g.setColor(ciColor);
drawLine(g, ciRight, 0, ciRight, density);
g.setColor(this.getOutlineColor1());
//hypothesisType = (String)list.get(5);
//////////////System.outprintln("NormalCurve ciRight = " + ciRight + " density = " + density);
}
catch (Exception e) {
//////////////System.outprintln("NormalCurve e = " + e);
}
}
else if (muA < mu0) {
hypothesisType = NormalPowerResult.HYPOTHESIS_TYPE_LT;
}
else if (muA > mu0) {
hypothesisType = NormalPowerResult.HYPOTHESIS_TYPE_GT;
}
if (hypothesisType.equalsIgnoreCase(NormalPowerResult.HYPOTHESIS_TYPE_LT)) {
try {
g.setColor(this.getOutlineColor1());
ciLeft = Double.parseDouble(((String)list.get(3)));
//drawLabel(g, format(ciLeft), ciLeft, c, BELOW);
density = Math.max(normal0.getDensity(ciLeft), normalA.getDensity(ciLeft));
g.setColor(ciColor);
drawLine(g, ciLeft, 0, ciLeft, density);
g.setColor(this.getOutlineColor1());
//hypothesisType = (String)list.get(5);
////////System.outprintln("NormalCurve ciLeft = " + ciLeft + " density = " + density);
} catch (Exception e) {
////////System.outprintln("NormalCurve Exception e = " + e);
}
} else if (hypothesisType.equalsIgnoreCase(NormalPowerResult.HYPOTHESIS_TYPE_GT)) {
try {
g.setColor(this.getOutlineColor1());
ciRight = Double.parseDouble(((String)list.get(4)));
//drawLabel(g, format(ciLeft), ciLeft, c, BELOW);
density = Math.max(normal0.getDensity(ciRight), normalA.getDensity(ciRight));
g.setColor(ciColor);
drawLine(g, ciRight, 0, ciRight, density);
g.setColor(this.getOutlineColor1());
//hypothesisType = (String)list.get(5);
////////System.outprintln("NormalCurve ciRight = " + ciRight + " density = " + density);
} catch (Exception e) {
////////System.outprintln("NormalCurve Exception e = " + e);
}
}
////////////System.outprintln("NormalCurve hypothesisType = " + hypothesisType);
double x1 = 0, y1 = 0, xa = 0;
g.setColor(oldColor);
} catch (Exception e) {
//////////////System.outprintln("NormalCurve last e = " + e);
}
//}
}
}
else{
//Draw thte line
drawLine(g, c, domain.getLowerBound(), c, domain.getUpperBound());
//drawLine(g, c, -10, c, 10);
//Draw tick marks, depending on type
for (int i = 0; i < domain.getSize(); i++){
if (type == MIDPOINTS) t = domain.getValue(i); else t = domain.getBound(i);
//drawTick(g, c, t, HORIZONTAL);
}
if (type == BOUNDS) drawTick(g, c, domain.getUpperBound(), HORIZONTAL);
//Draw labels
if (type == MIDPOINTS) t = domain.getLowerValue(); else t = domain.getLowerBound();
g.setColor(ModelerColor.HISTOGRAM_LABEL);
drawLabel(g, format(t), c, t, LEFT);
if (type == MIDPOINTS) t = domain.getUpperValue(); else t = domain.getUpperBound();
drawLabel(g, format(t), c, t, LEFT);
}
int sum = Math.abs(currentXUpperBound) + Math.abs(currentXLowerBound); //
int diff = Math.abs(currentXUpperBound) - Math.abs(currentXLowerBound); //
}
/**
* @return the maxRelFreq
* @uml.property name="maxRelFreq"
*/
public double getMaxRelFreq() {
return this.maxRelFreq;
}
/**
* @param fillArea the fillArea to set
* @uml.property name="fillArea"
*/
public void setFillArea(boolean fillArea) {
this.fillArea = fillArea;
}
/*
private void findIntersection(double[] x1, double[] y1, double[] x2, double[] y2) {
double numberTooSmall = 1E-10;
boolean[] willUse = new boolean[x1.length];
for (int i = 0; i < x1.length; i++) {
if (y1[i] < numberTooSmall || y2[i] < numberTooSmall) {
willUse[i] = false;
}
else {
willUse[i] = true;
}
}
}
*/
public void setSampleMeanOption(boolean input) {
this.useSampleMean = input;
}
public boolean withinSampleMeanCurve(double x, double y) {//, double scale) {
double f = normalA.getDensity(x);
//////////System.outprintln("NormailCurve x = " + x + ", y = " + y + ", f = " + f);
if (f <= y && f >= 0.0001) {
return true;
}
else {
return false;
}
}
public void resetHypotheseType() {
hypothesisType = null;
}
}
| lgpl-3.0 |
ucchyocean/DelayCommand | src/main/java/org/bitbucket/ucchy/delay/DelayCommandPlugin.java | 2383 | /*
* @author ucchy
* @license LGPLv3
* @copyright Copyright ucchy 2014
*/
package org.bitbucket.ucchy.delay;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
/**
* Delay Command Plugin
* @author ucchy
*/
public class DelayCommandPlugin extends JavaPlugin {
/**
* @see org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if ( args.length < 2 ) {
return false;
}
final ArrayList<String> commands = new ArrayList<String>();
boolean isAsync = false;
int ticks = 0;
if ( isDigit(args[0]) ) {
// /delay (ticks) (command...)
for ( int index=1; index<args.length; index++ ) {
commands.add(args[index]);
}
ticks = Integer.parseInt(args[0]);
} else if ( args[0].equalsIgnoreCase("async") && isDigit(args[1]) && args.length >= 3 ) {
// /delay async (ticks) (command...)
isAsync = true;
for ( int index=2; index<args.length; index++ ) {
commands.add(args[index]);
}
ticks = Integer.parseInt(args[1]);
} else {
return false;
}
final CommandSender comSender = sender;
BukkitRunnable runnable = new BukkitRunnable() {
@Override
public void run() {
StringBuilder builder = new StringBuilder();
for ( String com : commands ) {
builder.append(com + " ");
}
Bukkit.dispatchCommand(comSender, builder.toString().trim());
}
};
if ( isAsync ) {
runnable.runTaskLaterAsynchronously(this, ticks);
} else {
runnable.runTaskLater(this, ticks);
}
return true;
}
private boolean isDigit(String value) {
return value.matches("^[0-9]{1,9}$");
}
}
| lgpl-3.0 |
loftuxab/community-edition-old | projects/share-po/src/main/java/org/alfresco/po/share/enums/UserRole.java | 1846 | /*
* Copyright (C) 2005-2013 Alfresco Software Limited.
* This file is part of Alfresco
* 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/>.
*/
package org.alfresco.po.share.enums;
import java.util.NoSuchElementException;
/**
* This enums used to describe the user roles.
*
* @author cbairaajoni
* @since v1.0
*/
public enum UserRole
{
ALL("All"),
MANAGER("Manager"),
EDITOR("Editor"),
CONSUMER("Consumer"),
COLLABORATOR("Collaborator"),
COORDINATOR("Coordinator"),
CONTRIBUTOR("Contributor"),
SITECONSUMER("Site Consumer"),
SITECONTRIBUTOR("Site Contributor"),
SITEMANAGER("Site Manager"),
SITECOLLABORATOR("Site Collaborator");
private String roleName;
private UserRole(String role)
{
roleName = role;
}
public String getRoleName()
{
return roleName;
}
public static UserRole getUserRoleforName(String name)
{
for (UserRole role : UserRole.values())
{
if (role.getRoleName().equalsIgnoreCase(name))
{
return role;
}
}
throw new NoSuchElementException("No Role for value - " + name);
}
} | lgpl-3.0 |
xinghuangxu/xinghuangxu.sonarqube | sonar-ws-client/src/test/java/org/sonar/wsclient/services/TimeMachineQueryTest.java | 2818 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 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.wsclient.services;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.sonar.wsclient.JdkUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import static org.fest.assertions.Assertions.assertThat;
public class TimeMachineQueryTest extends QueryTestCase {
private TimeZone systemTimeZone;
@Before
public void before() {
systemTimeZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
WSUtils.setInstance(new JdkUtils());
}
@After
public void after() {
TimeZone.setDefault(systemTimeZone);
}
@Test
public void should_get_url() {
TimeMachineQuery query = TimeMachineQuery.createForMetrics("12345", "ncloc", "coverage");
assertThat(query.getUrl()).isEqualTo("/api/timemachine?resource=12345&metrics=ncloc,coverage&");
}
@Test
public void should_set_period() throws ParseException {
Date from = new SimpleDateFormat("yyyy-MM-dd").parse("2010-02-18");
Date to = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2010-03-25 14:59");
TimeMachineQuery query = TimeMachineQuery.createForMetrics("12345", "ncloc").setFrom(from).setTo(to);
assertThat(query.getUrl()).isEqualTo(
"/api/timemachine?resource=12345&metrics=ncloc&fromDateTime=2010-02-18T00%3A00%3A00%2B0000&toDateTime=2010-03-25T14%3A59%3A00%2B0000&");
}
@Test
public void should_create_query_from_resource() {
TimeMachineQuery query = TimeMachineQuery.createForMetrics(new Resource().setId(1), "ncloc");
assertThat(query.getUrl()).isEqualTo("/api/timemachine?resource=1&metrics=ncloc&"); }
@Test
public void should_not_create_query_from_resource_without_id() {
try {
TimeMachineQuery.createForMetrics(new Resource());
} catch (Exception e) {
assertThat(e).isInstanceOf(IllegalArgumentException.class);
}
}
}
| lgpl-3.0 |
ijpb/MorphoLibJ | src/main/java/inra/ijpb/binary/distmap/ChamferDistanceTransform2D.java | 495 | /**
*
*/
package inra.ijpb.binary.distmap;
/**
* Specialization of DistanceTransform based on the use of a chamfer mask.
*
* Provides methods for retrieving the mask, and the normalization weight.
*
* @author dlegland
*/
public interface ChamferDistanceTransform2D extends DistanceTransform
{
/**
* Return the chamfer mask used by this distance transform algorithm.
*
* @return the chamfer mask used by this distance transform algorithm.
*/
public ChamferMask2D mask();
}
| lgpl-3.0 |
JpressProjects/jpress | module-product/module-product-web/src/main/java/io/jpress/module/product/directive/ProductDirective.java | 1922 | /**
* Copyright (c) 2016-2020, Michael Yang 杨福海 (fuhai999@gmail.com).
* <p>
* Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl-3.0.txt
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jpress.module.product.directive;
import com.jfinal.aop.Inject;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import io.jboot.utils.StrUtil;
import io.jboot.web.directive.annotation.JFinalDirective;
import io.jboot.web.directive.base.JbootDirectiveBase;
import io.jpress.module.product.model.Product;
import io.jpress.module.product.service.ProductService;
/**
* @author Michael Yang 杨福海 (fuhai999@gmail.com)
* @version V1.0
*/
@JFinalDirective("product")
public class ProductDirective extends JbootDirectiveBase {
@Inject
private ProductService service;
@Override
public void onRender(Env env, Scope scope, Writer writer) {
String idOrSlug = getPara(0, scope);
Product product = getProduct(idOrSlug);
if (product == null) {
return;
}
scope.setLocal("product", product);
renderBody(env, scope, writer);
}
private Product getProduct(String idOrSlug) {
return StrUtil.isNumeric(idOrSlug)
? service.findById(idOrSlug)
: service.findFirstBySlug(idOrSlug);
}
@Override
public boolean hasEnd() {
return true;
}
}
| lgpl-3.0 |
cfscosta/fenix | src/main/java/org/fenixedu/academic/domain/phd/thesis/activities/ConcludePhdProcess.java | 3354 | /**
* 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.phd.thesis.activities;
import java.util.Optional;
import org.fenixedu.academic.domain.caseHandling.PreConditionNotValidException;
import org.fenixedu.academic.domain.phd.PhdIndividualProgramProcess;
import org.fenixedu.academic.domain.phd.PhdIndividualProgramProcessState;
import org.fenixedu.academic.domain.phd.conclusion.PhdConclusionProcess;
import org.fenixedu.academic.domain.phd.conclusion.PhdConclusionProcessBean;
import org.fenixedu.academic.domain.phd.thesis.PhdThesisProcess;
import org.fenixedu.bennu.core.domain.User;
import org.fenixedu.bennu.core.domain.UserLoginPeriod;
public class ConcludePhdProcess extends PhdThesisActivity {
@Override
protected void activityPreConditions(PhdThesisProcess process, User userView) {
if (!process.isAllowedToManageProcess(userView)) {
throw new PreConditionNotValidException();
}
if (!process.isConcluded()) {
throw new PreConditionNotValidException();
}
if (!isStudentCurricularPlanFinishedForPhd(process)) {
throw new PreConditionNotValidException();
}
}
/**
* TODO: phd-refactor
*
* Check if the root group of the phd student curricular plan is concluded is enough
* to be able to conclude the phd process.
*
* This should be changed when the phd process becomes itself a curriculum group.
*
* @param process the student's thesis process
* @return true if the root curriculum group has a conclusion process.
*/
private boolean isStudentCurricularPlanFinishedForPhd(PhdThesisProcess process) {
return Optional.ofNullable(process.getIndividualProgramProcess().getRegistration())
.map(r -> r.getLastStudentCurricularPlan().getRoot().isConclusionProcessed()).orElse(null);
}
@Override
protected PhdThesisProcess executeActivity(PhdThesisProcess process, User userView, Object object) {
PhdConclusionProcessBean bean = (PhdConclusionProcessBean) object;
PhdConclusionProcess.create(bean, userView.getPerson());
PhdIndividualProgramProcess individualProgramProcess = process.getIndividualProgramProcess();
if (!PhdIndividualProgramProcessState.CONCLUDED.equals(individualProgramProcess.getActiveState())) {
individualProgramProcess.createState(PhdIndividualProgramProcessState.CONCLUDED, userView.getPerson(), "");
}
UserLoginPeriod.createOpenPeriod(process.getPerson().getUser());
return process;
}
}
| lgpl-3.0 |
jmecosta/sonar | sonar-plugin-api/src/test/java/org/sonar/api/config/SettingsTest.java | 15285 | /*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2012 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.api.config;
import com.google.common.collect.ImmutableMap;
import org.fest.assertions.Delta;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.Properties;
import org.sonar.api.Property;
import org.sonar.api.PropertyType;
import static org.fest.assertions.Assertions.assertThat;
public class SettingsTest {
private PropertyDefinitions definitions;
@Properties({
@Property(key = "hello", name = "Hello", defaultValue = "world"),
@Property(key = "date", name = "Date", defaultValue = "2010-05-18"),
@Property(key = "datetime", name = "DateTime", defaultValue = "2010-05-18T15:50:45+0100"),
@Property(key = "boolean", name = "Boolean", defaultValue = "true"),
@Property(key = "falseboolean", name = "False Boolean", defaultValue = "false"),
@Property(key = "integer", name = "Integer", defaultValue = "12345"),
@Property(key = "array", name = "Array", defaultValue = "one,two,three"),
@Property(key = "multi_values", name = "Array", defaultValue = "1,2,3", multiValues = true),
@Property(key = "sonar.jira", name = "Jira Server", type = PropertyType.PROPERTY_SET, propertySetKey = "jira"),
@Property(key = "newKey", name = "New key", deprecatedKey = "oldKey"),
@Property(key = "newKeyWithDefaultValue", name = "New key with default value", deprecatedKey = "oldKeyWithDefaultValue", defaultValue = "default_value"),
@Property(key = "new_multi_values", name = "New multi values", defaultValue = "1,2,3", multiValues = true, deprecatedKey = "old_multi_values")
})
static class Init {
}
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void initDefinitions() {
definitions = new PropertyDefinitions();
definitions.addComponent(Init.class);
}
@Test
public void defaultValuesShouldBeLoadedFromDefinitions() {
Settings settings = new Settings(definitions);
assertThat(settings.getDefaultValue("hello")).isEqualTo("world");
}
@Test
public void setProperty_int() {
Settings settings = new Settings();
settings.setProperty("foo", 123);
assertThat(settings.getInt("foo")).isEqualTo(123);
assertThat(settings.getString("foo")).isEqualTo("123");
assertThat(settings.getBoolean("foo")).isFalse();
}
@Test
public void setProperty_boolean() {
Settings settings = new Settings();
settings.setProperty("foo", true);
settings.setProperty("bar", false);
assertThat(settings.getBoolean("foo")).isTrue();
assertThat(settings.getBoolean("bar")).isFalse();
assertThat(settings.getString("foo")).isEqualTo("true");
assertThat(settings.getString("bar")).isEqualTo("false");
}
@Test
public void default_number_values_are_zero() {
Settings settings = new Settings();
assertThat(settings.getInt("foo")).isEqualTo(0);
assertThat(settings.getLong("foo")).isEqualTo(0L);
}
@Test
public void getInt_value_must_be_valid() {
thrown.expect(NumberFormatException.class);
Settings settings = new Settings();
settings.setProperty("foo", "not a number");
settings.getInt("foo");
}
@Test
public void allValuesShouldBeTrimmed_set_property() {
Settings settings = new Settings();
settings.setProperty("foo", " FOO ");
assertThat(settings.getString("foo")).isEqualTo("FOO");
}
@Test
public void allValuesShouldBeTrimmed_set_properties() {
Settings settings = new Settings();
settings.setProperties(ImmutableMap.of("foo", " FOO "));
assertThat(settings.getString("foo")).isEqualTo("FOO");
}
@Test
public void testGetDefaultValue() {
Settings settings = new Settings(definitions);
assertThat(settings.getDefaultValue("unknown")).isNull();
}
@Test
public void testGetString() {
Settings settings = new Settings(definitions);
settings.setProperty("hello", "Russia");
assertThat(settings.getString("hello")).isEqualTo("Russia");
}
@Test
public void testGetDate() {
Settings settings = new Settings(definitions);
assertThat(settings.getDate("unknown")).isNull();
assertThat(settings.getDate("date").getDate()).isEqualTo(18);
assertThat(settings.getDate("date").getMonth()).isEqualTo(4);
}
@Test
public void testGetDateNotFound() {
Settings settings = new Settings(definitions);
assertThat(settings.getDate("unknown")).isNull();
}
@Test
public void testGetDateTime() {
Settings settings = new Settings(definitions);
assertThat(settings.getDateTime("unknown")).isNull();
assertThat(settings.getDateTime("datetime").getDate()).isEqualTo(18);
assertThat(settings.getDateTime("datetime").getMonth()).isEqualTo(4);
assertThat(settings.getDateTime("datetime").getMinutes()).isEqualTo(50);
}
@Test
public void testGetDouble() {
Settings settings = new Settings();
settings.setProperty("from_double", 3.14159);
settings.setProperty("from_string", "3.14159");
assertThat(settings.getDouble("from_double")).isEqualTo(3.14159, Delta.delta(0.00001));
assertThat(settings.getDouble("from_string")).isEqualTo(3.14159, Delta.delta(0.00001));
assertThat(settings.getDouble("unknown")).isNull();
}
@Test
public void testGetFloat() {
Settings settings = new Settings();
settings.setProperty("from_float", 3.14159f);
settings.setProperty("from_string", "3.14159");
assertThat(settings.getDouble("from_float")).isEqualTo(3.14159f, Delta.delta(0.00001));
assertThat(settings.getDouble("from_string")).isEqualTo(3.14159f, Delta.delta(0.00001));
assertThat(settings.getDouble("unknown")).isNull();
}
@Test
public void testGetBadFloat() {
Settings settings = new Settings();
settings.setProperty("foo", "bar");
thrown.expect(IllegalStateException.class);
thrown.expectMessage("The property 'foo' is not a float value");
settings.getFloat("foo");
}
@Test
public void testGetBadDouble() {
Settings settings = new Settings();
settings.setProperty("foo", "bar");
thrown.expect(IllegalStateException.class);
thrown.expectMessage("The property 'foo' is not a double value");
settings.getDouble("foo");
}
@Test
public void testSetNullFloat() {
Settings settings = new Settings();
settings.setProperty("foo", (Float) null);
assertThat(settings.getFloat("foo")).isNull();
}
@Test
public void testSetNullDouble() {
Settings settings = new Settings();
settings.setProperty("foo", (Double) null);
assertThat(settings.getDouble("foo")).isNull();
}
@Test
public void getStringArray() {
Settings settings = new Settings(definitions);
String[] array = settings.getStringArray("array");
assertThat(array).isEqualTo(new String[]{"one", "two", "three"});
}
@Test
public void setStringArray() {
Settings settings = new Settings(definitions);
settings.setProperty("multi_values", new String[]{"A", "B"});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A", "B"});
}
@Test
public void setStringArrayTrimValues() {
Settings settings = new Settings(definitions);
settings.setProperty("multi_values", new String[]{" A ", " B "});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A", "B"});
}
@Test
public void setStringArrayEscapeCommas() {
Settings settings = new Settings(definitions);
settings.setProperty("multi_values", new String[]{"A,B", "C,D"});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A,B", "C,D"});
}
@Test
public void setStringArrayWithEmptyValues() {
Settings settings = new Settings(definitions);
settings.setProperty("multi_values", new String[]{"A,B", "", "C,D"});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A,B", "", "C,D"});
}
@Test
public void setStringArrayWithNullValues() {
Settings settings = new Settings(definitions);
settings.setProperty("multi_values", new String[]{"A,B", null, "C,D"});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A,B", "", "C,D"});
}
@Test(expected = IllegalStateException.class)
public void shouldFailToSetArrayValueOnSingleValueProperty() {
Settings settings = new Settings(definitions);
settings.setProperty("array", new String[]{"A", "B", "C"});
}
@Test
public void getStringArray_no_value() {
Settings settings = new Settings();
String[] array = settings.getStringArray("array");
assertThat(array).isEmpty();
}
@Test
public void shouldTrimArray() {
Settings settings = new Settings();
settings.setProperty("foo", " one, two, three ");
String[] array = settings.getStringArray("foo");
assertThat(array).isEqualTo(new String[]{"one", "two", "three"});
}
@Test
public void shouldKeepEmptyValuesWhenSplitting() {
Settings settings = new Settings();
settings.setProperty("foo", " one, , two");
String[] array = settings.getStringArray("foo");
assertThat(array).isEqualTo(new String[]{"one", "", "two"});
}
@Test
public void testDefaultValueOfGetString() {
Settings settings = new Settings(definitions);
assertThat(settings.getString("hello")).isEqualTo("world");
}
@Test
public void testGetBoolean() {
Settings settings = new Settings(definitions);
assertThat(settings.getBoolean("boolean")).isTrue();
assertThat(settings.getBoolean("falseboolean")).isFalse();
assertThat(settings.getBoolean("unknown")).isFalse();
assertThat(settings.getBoolean("hello")).isFalse();
}
@Test
public void shouldCreateByIntrospectingComponent() {
Settings settings = Settings.createForComponent(MyComponent.class);
// property definition has been loaded, ie for default value
assertThat(settings.getDefaultValue("foo")).isEqualTo("bar");
}
@Property(key = "foo", name = "Foo", defaultValue = "bar")
public static class MyComponent {
}
@Test
public void cloneSettings() {
Settings target = new Settings(definitions).setProperty("foo", "bar");
Settings settings = new Settings(target);
assertThat(settings.getString("foo")).isEqualTo("bar");
assertThat(settings.getDefinitions()).isSameAs(definitions);
// do not propagate changes
settings.setProperty("foo", "changed");
settings.setProperty("new", "value");
assertThat(settings.getString("foo")).isEqualTo("changed");
assertThat(settings.getString("new")).isEqualTo("value");
assertThat(target.getString("foo")).isEqualTo("bar");
assertThat(target.getString("new")).isNull();
}
@Test
public void getStringLines_no_value() {
assertThat(new Settings().getStringLines("foo")).hasSize(0);
}
@Test
public void getStringLines_single_line() {
Settings settings = new Settings();
settings.setProperty("foo", "the line");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"the line"});
}
@Test
public void getStringLines_linux() {
Settings settings = new Settings();
settings.setProperty("foo", "one\ntwo");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two"});
settings.setProperty("foo", "one\ntwo\n");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two"});
}
@Test
public void getStringLines_windows() {
Settings settings = new Settings();
settings.setProperty("foo", "one\r\ntwo");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two"});
settings.setProperty("foo", "one\r\ntwo\r\n");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two"});
}
@Test
public void getStringLines_mix() {
Settings settings = new Settings();
settings.setProperty("foo", "one\r\ntwo\nthree");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two", "three"});
}
@Test
public void getKeysStartingWith() {
Settings settings = new Settings();
settings.setProperty("sonar.jdbc.url", "foo");
settings.setProperty("sonar.jdbc.username", "bar");
settings.setProperty("sonar.security", "admin");
assertThat(settings.getKeysStartingWith("sonar")).containsOnly("sonar.jdbc.url", "sonar.jdbc.username", "sonar.security");
assertThat(settings.getKeysStartingWith("sonar.jdbc")).containsOnly("sonar.jdbc.url", "sonar.jdbc.username");
assertThat(settings.getKeysStartingWith("other")).hasSize(0);
}
@Test
public void should_fallback_deprecated_key_to_default_value_of_new_key() {
Settings settings = new Settings(definitions);
assertThat(settings.getString("newKeyWithDefaultValue")).isEqualTo("default_value");
assertThat(settings.getString("oldKeyWithDefaultValue")).isEqualTo("default_value");
}
@Test
public void should_fallback_deprecated_key_to_new_key() {
Settings settings = new Settings(definitions);
settings.setProperty("newKey", "value of newKey");
assertThat(settings.getString("newKey")).isEqualTo("value of newKey");
assertThat(settings.getString("oldKey")).isEqualTo("value of newKey");
}
@Test
public void should_load_value_of_deprecated_key() {
// it's used for example when deprecated settings are set through command-line
Settings settings = new Settings(definitions);
settings.setProperty("oldKey", "value of oldKey");
assertThat(settings.getString("newKey")).isEqualTo("value of oldKey");
assertThat(settings.getString("oldKey")).isEqualTo("value of oldKey");
}
@Test
public void should_load_values_of_deprecated_key() {
Settings settings = new Settings(definitions);
settings.setProperty("oldKey", "a,b");
assertThat(settings.getStringArray("newKey")).containsOnly("a", "b");
assertThat(settings.getStringArray("oldKey")).containsOnly("a", "b");
}
@Test
public void should_support_deprecated_props_with_multi_values() {
Settings settings = new Settings(definitions);
settings.setProperty("new_multi_values", new String[]{" A ", " B "});
assertThat(settings.getStringArray("new_multi_values")).isEqualTo(new String[]{"A", "B"});
assertThat(settings.getStringArray("old_multi_values")).isEqualTo(new String[]{"A", "B"});
}
}
| lgpl-3.0 |
btrplace/scheduler-UCC-15 | choco/src/test/java/org/btrplace/scheduler/choco/constraint/mttr/CMinMTTRTest.java | 2052 | package org.btrplace.scheduler.choco.constraint.mttr;
import org.btrplace.model.DefaultModel;
import org.btrplace.model.Model;
import org.btrplace.model.Node;
import org.btrplace.model.VM;
import org.btrplace.model.constraint.Preserve;
import org.btrplace.model.constraint.SatConstraint;
import org.btrplace.model.view.ShareableResource;
import org.btrplace.plan.ReconfigurationPlan;
import org.btrplace.scheduler.choco.DefaultChocoScheduler;
import org.testng.Assert;
import java.util.ArrayList;
import java.util.List;
/**
* Created by fhermeni on 17/02/2015.
*/
public class CMinMTTRTest {
/**
* The DC is heavily loaded.
* Provoked a large amount of backtracks when we relied on a random search
* @throws Exception
*/
/*@Test*/
public void testHeavyLoad() throws Exception {
Model mo = new DefaultModel();
ShareableResource cpu = new ShareableResource("core", 7, 1);
ShareableResource mem = new ShareableResource("mem", 20, 2);
for (int i = 0; i < 50; i++) {
Node n = mo.newNode();
mo.getMapping().addOnlineNode(n);
for (int j = 0; j < 4; j++) {
VM v = mo.newVM();
mo.getMapping().addRunningVM(v, n);
if (j % 2 == 0) {
mem.setConsumption(v, 1);
}
}
}
List<SatConstraint> l = new ArrayList<>();
for (Node n : mo.getMapping().getAllNodes()) {
if (n.id() % 3 == 0) {
l.addAll(Preserve.newPreserve(mo.getMapping().getRunningVMs(n), "core", 2));
}
}
mo.attach(cpu);
mo.attach(mem);
DefaultChocoScheduler sched = new DefaultChocoScheduler();
//sched.setVerbosity(2);
ReconfigurationPlan p = sched.solve(mo, l);
Assert.assertNotNull(p);
System.err.println(sched.getStatistics());
//TODO: fragile. Usefull ?
Assert.assertTrue(sched.getStatistics().getNbBacktracks() < 100);
System.err.flush();
}
}
| lgpl-3.0 |
Biobanques/biobanques-etl-app | src/main/java/fr/inserm/ihm/WizardPanelNotFoundException.java | 236 | package fr.inserm.ihm;
public class WizardPanelNotFoundException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -1947507532224487459L;
public WizardPanelNotFoundException() {
super();
}
} | lgpl-3.0 |
alimux/RssFeedReader | app/src/main/java/apps/database/dnr2i/rssfeedreader/model/RSSAdapter.java | 2847 | package apps.database.dnr2i.rssfeedreader.model;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.util.ArrayList;
import apps.database.dnr2i.rssfeedreader.FeedSelectorActivity;
import apps.database.dnr2i.rssfeedreader.R;
/**
* Class Adpater to prepare Display
* Created by Alexandre DUCREUX on 21/01/2017.
*/
public class RSSAdapter extends RecyclerView.Adapter<ArticleViewHolder> implements DocumentConsumer{
private ArrayList<FeedItems> rssFI = new ArrayList<>();
private Document _document;
private Context context;
public RSSAdapter(ArrayList<FeedItems> rssFI, Context context) {
this.rssFI = rssFI;
this.context = context;
}
@Override
public int getItemCount(){
int recordNumber = rssFI.size();
Log.i("AD", "Nombre d'enregistrement en base : "+recordNumber);
return recordNumber;
}
@Override
public ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.rss_selected_feed_details, parent, false);
return new ArticleViewHolder(view);
}
@Override
public void onBindViewHolder(ArticleViewHolder holder, int position){
FeedItems feedItemsList = rssFI.get(position);
holder.getTitle().setText(feedItemsList.getTitle());
holder.getDescription().setText(feedItemsList.getDescription());
holder.getLink().setText(feedItemsList.getLink());
holder.getDate().setText(feedItemsList.getDate());
}
@Override
public void setXMLDocument(Document document, int feedId) {
_document = document;
ItemEntity item = new ItemEntity(this.context);
if (document.getElementsByTagName("item").getLength() > 0)
{
item.emptyItemsById(feedId);
}
for (int i=0; i<document.getElementsByTagName("item").getLength(); i++)
{
Element element = (Element) _document.getElementsByTagName("item").item(i);
String title = element.getElementsByTagName("title").item(0).getTextContent();
String description = element.getElementsByTagName("description").item(0).getTextContent();
String date = element.getElementsByTagName("pubDate").item(0).getTextContent();
String link = element.getElementsByTagName("link").item(0).getTextContent();
item.setItem(title,description,date,link,feedId);
Log.i("valeur de title"," title = " +title);
}
notifyDataSetChanged();
Log.i("FIN","FIN");
}
}
| lgpl-3.0 |
imintel/ddmsence | src/main/java/buri/ddmsence/ddms/summary/tspi/Circle.java | 4720 | /* Copyright 2010 - 2013 by Brian Uri!
This file is part of DDMSence.
This library is free software; you can redistribute it and/or modify
it under the terms of version 3.0 of the GNU Lesser General Public
License as published by the Free Software Foundation.
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 DDMSence. If not, see <http://www.gnu.org/licenses/>.
You can contact the author at ddmsence@urizone.net. The DDMSence
home page is located at http://ddmsence.urizone.net/
*/
package buri.ddmsence.ddms.summary.tspi;
import nu.xom.Element;
import buri.ddmsence.AbstractBaseComponent;
import buri.ddmsence.AbstractTspiShape;
import buri.ddmsence.ddms.IBuilder;
import buri.ddmsence.ddms.InvalidDDMSException;
import buri.ddmsence.util.DDMSVersion;
import buri.ddmsence.util.Util;
/**
* An immutable implementation of tspi:Circle.
* <br /><br />
* {@ddms.versions 00001}
*
* <p>For the initial support of DDMS 5.0 TSPI shapes, the DDMSence component will only return the raw XML of
* a shape. The TSPI specification is incredibly complex and multi-layered, and it is unclear how much
* value full-fledged classes would have. As use cases refine and more organizations adopt DDMS 5.0, the components
* can be revisited to provide more value-add.</p>
*
* {@table.header History}
* None.
* {@table.footer}
* {@table.header Nested Elements}
* None.
* {@table.footer}
* {@table.header Attributes}
* {@child.info gml:id|1|00001}
* {@child.info <<i>srsAttributes</i>>|0..*|00001}
* {@table.footer}
* {@table.header Validation Rules}
* {@ddms.rule Component must not be used before the DDMS version in which it was introduced.|Error|11111}
* {@ddms.rule The qualified name of this element must be correct.|Error|11111}
* {@ddms.rule The srsName must exist.|Error|11111}
* {@ddms.rule The gml:id must exist, and must be a valid NCName.|Error|11111}
* {@ddms.rule If the gml:pos has an srsName, it must match the srsName of this Point.|Error|11111}
* {@ddms.rule Warnings from any SRS attributes are claimed by this component.|Warning|11111}
* <p>No additional validation is done on the TSPI shape at this time.</p>
* {@table.footer}
*
* @author Brian Uri!
* @since 2.2.0
*/
public final class Circle extends AbstractTspiShape {
/**
* Constructor for creating a component from a XOM Element
*
* @param element the XOM element representing this
* @throws InvalidDDMSException if any required information is missing or malformed
*/
public Circle(Element element) throws InvalidDDMSException {
super(element);
}
/**
* @see AbstractBaseComponent#validate()
*/
protected void validate() throws InvalidDDMSException {
Util.requireQName(getXOMElement(), getNamespace(), Circle.getName(getDDMSVersion()));
super.validate();
}
/**
* @see AbstractBaseComponent#getOutput(boolean, String, String)
*/
public String getOutput(boolean isHTML, String prefix, String suffix) {
String localPrefix = buildPrefix(prefix, "", suffix);
StringBuffer text = new StringBuffer();
text.append(buildOutput(isHTML, localPrefix + "shapeType", getName()));
return (text.toString());
}
/**
* Builder for the element name of this component, based on the version of DDMS used
*
* @param version the DDMSVersion
* @return an element name
*/
public static String getName(DDMSVersion version) {
Util.requireValue("version", version);
return ("Circle");
}
/**
* @see Object#equals(Object)
*/
public boolean equals(Object obj) {
if (!super.equals(obj) || !(obj instanceof Circle))
return (false);
return (true);
}
/**
* Builder for this DDMS component.
*
* @see IBuilder
* @author Brian Uri!
* @since 2.2.0
*/
public static class Builder extends AbstractTspiShape.Builder {
private static final long serialVersionUID = 7750664735441105296L;
/**
* Empty constructor
*/
public Builder() {
super();
}
/**
* Constructor which starts from an existing component.
*/
public Builder(Circle address) {
super(address);
}
/**
* @see IBuilder#commit()
*/
public Circle commit() throws InvalidDDMSException {
if (isEmpty())
return (null);
return (new Circle(commitXml()));
}
}
} | lgpl-3.0 |
istvanszoke/softlab4 | src/main/commands/executes/ChangeDirectionExecute.java | 1517 | package commands.executes;
import agents.Agent;
import agents.Robot;
import agents.Speed;
import agents.Vacuum;
import commands.AgentCommand;
import commands.AgentCommandVisitor;
import commands.FieldCommand;
import commands.NoFieldCommandException;
import commands.transmits.ChangeDirectionTransmit;
import field.Direction;
public class ChangeDirectionExecute extends AgentCommand {
private Direction direction;
public ChangeDirectionExecute(ChangeDirectionTransmit parent) {
super(parent);
this.direction = parent.getDirection();
}
public Direction getDirection() {
return direction;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
@Override
public FieldCommand getFieldCommand() throws NoFieldCommandException {
throw new NoFieldCommandException();
}
@Override
public void accept(AgentCommandVisitor modifier) {
modifier.visit(this);
}
@Override
public void visit(Robot element) {
visitCommon(element);
}
@Override
public void visit(Vacuum element) {
visitCommon(element);
}
private void visitCommon(Agent element) {
if (!canExecute) {
result.pushNormal("irvalt 1 " + element);
return;
}
Speed newSpeed = element.getSpeed();
newSpeed.setDirection(direction);
element.setSpeed(newSpeed);
result.pushNormal("irvalt 0 " + element + " " + direction);
}
}
| lgpl-3.0 |
imintel/ddmsence | src/test/java/buri/ddmsence/ddms/summary/tspi/EllipseTest.java | 7170 | /* Copyright 2010 - 2013 by Brian Uri!
This file is part of DDMSence.
This library is free software; you can redistribute it and/or modify
it under the terms of version 3.0 of the GNU Lesser General Public
License as published by the Free Software Foundation.
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 DDMSence. If not, see <http://www.gnu.org/licenses/>.
You can contact the author at ddmsence@urizone.net. The DDMSence
home page is located at http://ddmsence.urizone.net/
*/
package buri.ddmsence.ddms.summary.tspi;
import nu.xom.Element;
import buri.ddmsence.AbstractBaseTestCase;
import buri.ddmsence.ddms.InvalidDDMSException;
import buri.ddmsence.util.DDMSVersion;
import buri.ddmsence.util.Util;
/**
* <p> Tests related to tspi:Ellipse elements </p>
*
* @author Brian Uri!
* @since 2.2.0
*/
public class EllipseTest extends AbstractBaseTestCase {
/**
* Constructor
*/
public EllipseTest() {
super("ellipse.xml");
removeSupportedVersions("2.0 3.0 3.1 4.1");
}
/**
* Returns a fixture object for testing.
*/
public static Ellipse getFixture() {
try {
Ellipse.Builder builder = new Ellipse.Builder();
builder.setXml(getExpectedXMLOutput());
return (builder.commit());
}
catch (InvalidDDMSException e) {
fail("Could not create fixture: " + e.getMessage());
}
return (null);
}
/**
* Attempts to build a component from a XOM element.
* @param element the element to build from
* @param message an expected error message. If empty, the constructor is expected to succeed.
*
* @return a valid object
*/
private Ellipse getInstance(Element element, String message) {
boolean expectFailure = !Util.isEmpty(message);
Ellipse component = null;
try {
component = new Ellipse(element);
checkConstructorSuccess(expectFailure);
}
catch (InvalidDDMSException e) {
checkConstructorFailure(expectFailure, e);
expectMessage(e, message);
}
return (component);
}
/**
* Returns a builder, pre-populated with base data from the XML sample.
*
* This builder can then be modified to test various conditions.
*/
private Ellipse.Builder getBaseBuilder() {
DDMSVersion version = DDMSVersion.getCurrentVersion();
Ellipse component = getInstance(getValidElement(version.getVersion()), SUCCESS);
return (new Ellipse.Builder(component));
}
/**
* Returns the expected HTML or Text output for this unit test
*/
private String getExpectedOutput(boolean isHTML) throws InvalidDDMSException {
StringBuffer text = new StringBuffer();
text.append(buildOutput(isHTML, "shapeType", "Ellipse"));
return (text.toString());
}
/**
* Returns the expected XML output for this unit test
*/
private static String getExpectedXMLOutput() {
StringBuffer xml = new StringBuffer();
xml.append("<tspi:Ellipse ");
xml.append("xmlns:tspi=\"").append(DDMSVersion.getCurrentVersion().getTspiNamespace()).append("\" ");
xml.append("xmlns:tspi-core=\"http://metadata.ces.mil/mdr/ns/GSIP/tspi/2.0/core\" ");
xml.append("xmlns:gml=\"").append(DDMSVersion.getCurrentVersion().getGmlNamespace()).append("\" ");
xml.append("gml:id=\"EllipseMinimalExample\" srsName=\"http://metadata.ces.mil/mdr/ns/GSIP/crs/WGS84E_2D\">");
xml.append("<gml:pos>53.81 -2.10</gml:pos>");
xml.append("<tspi-core:semiMajorLength uom=\"http://metadata.ces.mil/mdr/ns/GSIP/uom/length/kilometre\">7.5</tspi-core:semiMajorLength>");
xml.append("<tspi-core:semiMinorLength uom=\"http://metadata.ces.mil/mdr/ns/GSIP/uom/length/kilometre\">5</tspi-core:semiMinorLength>");
xml.append("<tspi-core:orientation uom=\"http://metadata.ces.mil/mdr/ns/GSIP/uom/planeAngle/arcDegree\">-67.5</tspi-core:orientation>");
xml.append("</tspi:Ellipse>");
return (xml.toString());
}
public void testNameAndNamespace() {
for (String sVersion : getSupportedVersions()) {
DDMSVersion version = DDMSVersion.setCurrentVersion(sVersion);
assertNameAndNamespace(getInstance(getValidElement(sVersion), SUCCESS), DEFAULT_TSPI_PREFIX,
Ellipse.getName(version));
getInstance(getWrongNameElementFixture(), WRONG_NAME_MESSAGE);
}
}
public void testConstructors() {
for (String sVersion : getSupportedVersions()) {
DDMSVersion.setCurrentVersion(sVersion);
// Element-based
getInstance(getValidElement(sVersion), SUCCESS);
// Data-based via Builder
getBaseBuilder();
}
}
public void testConstructorsMinimal() throws InvalidDDMSException {
// No tests.
}
public void testValidationErrors() throws InvalidDDMSException {
// Invalid XML case is implicit in Util.commitXml() test.
}
public void testValidationWarnings() throws InvalidDDMSException {
for (String sVersion : getSupportedVersions()) {
DDMSVersion.setCurrentVersion(sVersion);
// No warnings
Ellipse component = getInstance(getValidElement(sVersion), SUCCESS);
assertEquals(0, component.getValidationWarnings().size());
}
}
public void testEquality() throws InvalidDDMSException {
for (String sVersion : getSupportedVersions()) {
DDMSVersion.setCurrentVersion(sVersion);
// Base equality
Ellipse elementComponent = getInstance(getValidElement(sVersion), SUCCESS);
Ellipse builderComponent = new Ellipse.Builder(elementComponent).commit();
assertEquals(elementComponent, builderComponent);
assertEquals(elementComponent.hashCode(), builderComponent.hashCode());
// Wrong class
assertFalse(elementComponent.equals(Integer.valueOf(1)));
// Different values in each field
Ellipse.Builder builder = getBaseBuilder();
String xml = getExpectedXMLOutput();
xml = xml.replace("MinimalExample", "Example");
builder.setXml(xml);
assertFalse(elementComponent.equals(builder.commit()));
}
}
public void testVersionSpecific() {
// Pre-5.0 test is implicit, since TSPI namespace did not exist.
}
public void testOutput() throws InvalidDDMSException {
for (String sVersion : getSupportedVersions()) {
DDMSVersion.setCurrentVersion(sVersion);
Ellipse elementComponent = getInstance(getValidElement(sVersion), SUCCESS);
assertEquals(getExpectedOutput(true), elementComponent.toHTML());
assertEquals(getExpectedOutput(false), elementComponent.toText());
assertEquals(getExpectedXMLOutput(), elementComponent.toXML());
}
}
public void testBuilderIsEmpty() throws InvalidDDMSException {
for (String sVersion : getSupportedVersions()) {
DDMSVersion.setCurrentVersion(sVersion);
Ellipse.Builder builder = new Ellipse.Builder();
assertNull(builder.commit());
assertTrue(builder.isEmpty());
builder.setXml("<hello />");
assertFalse(builder.isEmpty());
}
}
}
| lgpl-3.0 |
liuhongchao/GATE_Developer_7.0 | src/hepple/postag/rules/Rule_PREVTAG.java | 1057 | /*
* 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).
*
* HepTag was originally written by Mark Hepple, this version contains
* modifications by Valentin Tablan and Niraj Aswani.
*
* $Id: Rule_PREVTAG.java 15333 2012-02-07 13:18:33Z ian_roberts $
*/
package hepple.postag.rules;
import hepple.postag.*;
/**
* Title: HepTag
* Description: Mark Hepple's POS tagger
* Copyright: Copyright (c) 2001
* Company: University of Sheffield
* @author Mark Hepple
* @version 1.0
*/
public class Rule_PREVTAG extends Rule {
public Rule_PREVTAG() {
}
public boolean checkContext(POSTagger tagger) {
return (tagger.lexBuff[2][0].equals(context[0]));
}
} | lgpl-3.0 |
impetus-opensource/jumbune | common/src/main/java/org/jumbune/common/utils/RemoteFileUtil.java | 27308 | package org.jumbune.common.utils;
import static org.jumbune.common.utils.Constants.AT_OP;
import static org.jumbune.common.utils.Constants.COLON;
import static org.jumbune.common.utils.Constants.CPU_DUMP_FILE;
import static org.jumbune.common.utils.Constants.MEM_DUMP_FILE;
import static org.jumbune.common.utils.Constants.SPACE;
import static org.jumbune.common.utils.Constants.UNDERSCORE;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jumbune.common.beans.JumbuneInfo;
import org.jumbune.common.beans.cluster.Cluster;
import org.jumbune.common.beans.cluster.Workers;
import org.jumbune.common.job.JobConfig;
import org.jumbune.common.job.JumbuneRequest;
import org.jumbune.remoting.client.Remoter;
import org.jumbune.remoting.common.CommandType;
import org.jumbune.remoting.common.RemotingMethodConstants;
import org.jumbune.utils.exception.JumbuneException;
import org.jumbune.utils.exception.JumbuneRuntimeException;
/**
* This class provides methods to collect or distribute files from to/from
* master nodes.
*
*/
public class RemoteFileUtil {
/** The Constant LOGGER. */
private static final Logger LOGGER = LogManager
.getLogger(RemoteFileUtil.class);
/** The Constant SCP_R_CMD. */
private static final String SCP_R_CMD = "scp -r";
/** The Constant AGENT_HOME. */
private static final String AGENT_HOME = "AGENT_HOME";
/** The Constant MKDIR_P_CMD. */
private static final String MKDIR_P_CMD = "mkdir -p ";
private static final String RM_CMD = "rm";
/** The Constant TOP_DUMP_FILE. */
private static final String TOP_DUMP_FILE = "top.txt";
/**
* <p>
* Create a new instance of ClusterUtil.
* </p>
*/
public RemoteFileUtil() {
}
/**
* Copy remote log files
* @param masterLocation
* @param slaveDVLocation
*
* @param logCollection
* the log collection
* @throws JumbuneException
* the hTF exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* the interrupted exception
*/
@SuppressWarnings("unchecked")
public void copyRemoteLogFiles(JumbuneRequest jumbuneRequest, String slaveDVLocation, String masterLocation)
throws JumbuneException, IOException, InterruptedException {
String appHome = JumbuneInfo.getHome();
String relativePath = masterLocation.substring(appHome.length() - 1,
masterLocation.length());
Cluster cluster = jumbuneRequest.getCluster();
Remoter remoter = RemotingUtil.getRemoter(cluster);
String remoteMkdir = MKDIR_P_CMD + AGENT_HOME + relativePath;
CommandWritableBuilder builder = new CommandWritableBuilder(cluster);
builder.addCommand(remoteMkdir, false, null, CommandType.FS);
remoter.fireAndForgetCommand(builder.getCommandWritable());
// Creating local directories in Jumbune Working Dir
String mkdirCmd = MKDIR_P_CMD + masterLocation;
execute(mkdirCmd.split(" "), null);
Workers workers = cluster.getWorkers();
LOGGER.debug("Starting to copy remote log files...");
for (String workerHost : workers.getHosts()) {
LOGGER.debug("Copy log files from: " + workerHost + ":" + slaveDVLocation);
String command ;
if(cluster.getAgents().getSshAuthKeysFile() != null && cluster.getAgents().getSshAuthKeysFile().endsWith(".pem")){
command = "scp -i " + cluster.getAgents().getSshAuthKeysFile() + " -r " + jumbuneRequest.getJobConfig().getOperatingUser() + "@" + workerHost + ":"
+ slaveDVLocation + " " + AGENT_HOME + relativePath;}
else{
command = "scp -r " + jumbuneRequest.getJobConfig().getOperatingUser() + "@" + workerHost + ":"
+ slaveDVLocation + " " + AGENT_HOME + relativePath;
}
CommandWritableBuilder copyBuilder = new CommandWritableBuilder(cluster, null);
copyBuilder.addCommand(command, false, null, CommandType.FS).setMethodToBeInvoked(RemotingMethodConstants.RUN_SCP_ACROSS_NODES);
remoter.fireAndForgetCommand(copyBuilder.getCommandWritable());
}
builder.clear();
builder.addCommand(AGENT_HOME + relativePath, false, null,
CommandType.FS).setMethodToBeInvoked(
RemotingMethodConstants.PROCESS_GET_FILES);
List<String> fileList = (List<String>) remoter
.fireCommandAndGetObjectResponse(builder.getCommandWritable());
for (String string : fileList) {
remoter.receiveLogFiles(relativePath, relativePath + "/" + string);
}
remoter.close();
}
/**
* Copy remote log files.
* @param masterLocation
* @param tempDirLocation
*
* @param logCollection
* the log collection
* @throws JumbuneException
* the hTF exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* the interrupted exception
*/
// TODO:
@SuppressWarnings("unchecked")
public void copyRemoteAjLogFiles(JumbuneRequest jumbuneRequest, String tempDirLocation, String masterLocation)
throws JumbuneException, IOException, InterruptedException {
String appHome = JumbuneInfo.getHome();
String relativePath = masterLocation.substring(appHome.length() - 1,
masterLocation.length());
Cluster cluster = jumbuneRequest.getCluster();
Remoter remoter = RemotingUtil.getRemoter(cluster);
String remoteMkdir = MKDIR_P_CMD + AGENT_HOME + relativePath;
CommandWritableBuilder builder = new CommandWritableBuilder(cluster, null);
builder.addCommand(remoteMkdir, false, null, CommandType.FS);
remoter.fireAndForgetCommand(builder.getCommandWritable());
String mkdirCmd = MKDIR_P_CMD + masterLocation;
execute(mkdirCmd.split(" "), null);
Workers workers = cluster.getWorkers();
for (String workerHost : workers.getHosts()) {
ConsoleLogUtil.LOGGER.debug("Copy log file from: [" + workerHost
+ "] to [" + tempDirLocation + "]");
LOGGER.debug("Copy log file from: [" + workerHost + "] to ["
+ tempDirLocation + "]");
StringBuilder lsSb = new StringBuilder()
.append("-")
.append(workerHost)
.append("-")
.append(tempDirLocation.substring(0,
tempDirLocation.indexOf("*.log*"))).append("-")
.append(relativePath);
builder.clear();
builder.addCommand(lsSb.toString(), false, null, CommandType.FS)
.setMethodToBeInvoked(RemotingMethodConstants.PROCESS_DB_OPT_STEPS);
remoter.fireCommandAndGetObjectResponse(builder
.getCommandWritable());
String command ;
if(cluster.getAgents().getSshAuthKeysFile()!=null && cluster.getAgents().getSshAuthKeysFile().endsWith(".pem")){
command = "scp -i " + cluster.getAgents().getSshAuthKeysFile() + " -r " + jumbuneRequest.getJobConfig().getOperatingUser() + "@" + workerHost + ":"
+ tempDirLocation.substring(0,tempDirLocation.indexOf("*.log*")) + " " + AGENT_HOME + relativePath;
}else{
command = "scp -r " + jumbuneRequest.getJobConfig().getOperatingUser() + "@" + workerHost + ":"
+ tempDirLocation.substring(0,tempDirLocation.indexOf("*.log*")) + " " + AGENT_HOME + relativePath;
}
builder.clear();
builder.addCommand(command, false, null, CommandType.FS).setMethodToBeInvoked(RemotingMethodConstants.RUN_SCP_ACROSS_NODES);
remoter.fireAndForgetCommand(builder.getCommandWritable());
}
builder.clear();
builder.addCommand(AGENT_HOME + relativePath, false, null,
CommandType.FS).setMethodToBeInvoked(
RemotingMethodConstants.PROCESS_GET_FILES);
List<String> fileList = (List<String>) remoter
.fireCommandAndGetObjectResponse(builder.getCommandWritable());
for (String string : fileList) {
remoter.receiveLogFiles(relativePath, relativePath + "/" + string);
}
for (String string : fileList) {
if (!string.contains("mrChain")) {
execute(new String[] { "unzip", string }, appHome + relativePath + "/");
execute(new String[] { "rm", string }, appHome + relativePath + "/");
}
}
}
/**
* Copy remote lib files to master.
*
* @param config
* the loader
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* the interrupted exception
*/
public void copyRemoteLibFilesToMaster(
JumbuneRequest jumbuneRequest) throws IOException, InterruptedException {
JobConfig jobConfig = jumbuneRequest.getJobConfig();
String userLibLoc = jobConfig.getUserLibLocationAtMaster();
Cluster cluster = jumbuneRequest.getCluster();
Remoter remoter = RemotingUtil.getRemoter(cluster);
String mkdir = MKDIR_P_CMD + userLibLoc;
CommandWritableBuilder builder = new CommandWritableBuilder(cluster);
builder.addCommand(mkdir, false, null, CommandType.FS);
remoter.fireAndForgetCommand(builder.getCommandWritable());
Workers workers= cluster.getWorkers();
if (workers.getHosts().isEmpty()) {
LOGGER.error("No Worker found in cluster");
return;
}
String workerHost = workers.getHosts().get(0);
List<String> fileList = ConfigurationUtil.getAllClasspathFiles(
jobConfig.getClasspathFolders(ClasspathUtil.USER_SUPPLIED),
jobConfig.getClasspathExcludes(ClasspathUtil.USER_SUPPLIED),
jobConfig.getClasspathFiles(ClasspathUtil.USER_SUPPLIED));
String hadoopFSUser = cluster.getHadoopUsers().getFsUser();
for (String file : fileList) {
String command = "scp " + workers.getUser() + "@" + workerHost + ":" + file
+ " " + hadoopFSUser + "@" + cluster.getNameNode()+ ":"
+ userLibLoc;
LOGGER.debug("Executing the cmd: " + command);
builder.clear();
builder.addCommand(command, false, null, CommandType.FS).populate(cluster, null).setMethodToBeInvoked(RemotingMethodConstants.RUN_SCP_ACROSS_NODES);
remoter.fireAndForgetCommand(builder.getCommandWritable());
}
remoter.close();
}
/**
* Return rack id from IP.
*
* @param ip
* example: 192.168.169.52
* @return the rack id, example: 192.168.169
*/
public static String getRackId(String ip) {
int lastIndex = ip.lastIndexOf('.');
return ip.substring(0, lastIndex);
}
/**
* Return data centre id from IP.
*
* @param ip
* example: 192.168.169.52
* @return the data centre id, example: 192.168
*/
public static String getDataCentreId(String ip) {
String[] octats = ip.split("\\.");
if (octats.length > 0) {
return octats[0] + "." + octats[1];
} else {
return null;
}
}
/**
* Execute the given command.
*
* @param commands
* the commands
* @param directory
* the directory
*/
private void execute(String[] commands, String directory) {
ProcessBuilder processBuilder = new ProcessBuilder(commands);
if (directory != null && !directory.isEmpty()) {
processBuilder.directory(new File(directory));
} else {
processBuilder.directory(new File(JumbuneInfo.getHome()));
}
Process process = null;
InputStream inputStream = null;
BufferedReader bufferReader = null;
try {
process = processBuilder.start();
inputStream = process.getInputStream();
if (inputStream != null) {
bufferReader = new BufferedReader(new InputStreamReader(
inputStream));
String line = bufferReader.readLine();
while (line != null) {
line = bufferReader.readLine();
}
}
} catch (IOException e) {
LOGGER.error(JumbuneRuntimeException.throwUnresponsiveIOException(e.getStackTrace()));
} finally {
try {
if (bufferReader != null) {
bufferReader.close();
}
} catch (IOException e) {
LOGGER.error(JumbuneRuntimeException.throwUnresponsiveIOException(e.getStackTrace()));
}
}
}
/**
* Execute response list.
*
* @param commands
* the commands
* @param directory
* the directory
* @return the list
*/
public static List<String> executeResponseList(String[] commands,
String directory) {
List<String> responseList = new ArrayList<String>();
ProcessBuilder processBuilder = new ProcessBuilder(commands);
if (directory != null && !directory.isEmpty()) {
processBuilder.directory(new File(directory));
} else {
processBuilder.directory(new File(JumbuneInfo.getHome()));
}
Process process = null;
InputStream inputStream = null;
BufferedReader bufferReader = null;
try {
process = processBuilder.start();
inputStream = process.getInputStream();
if (inputStream != null) {
bufferReader = new BufferedReader(new InputStreamReader(
inputStream));
String line = bufferReader.readLine();
while (line != null) {
responseList.add(line);
line = bufferReader.readLine();
}
}
return responseList;
} catch (IOException e) {
LOGGER.error(JumbuneRuntimeException.throwUnresponsiveIOException(e.getStackTrace()));
} finally {
try {
if (bufferReader != null) {
bufferReader.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
LOGGER.error(JumbuneRuntimeException.throwUnresponsiveIOException(e.getStackTrace()));
}
}
return responseList;
}
/**
* Copy System stats files from slaves to Jumbune deploy directory.
*
* @param logCollection
* the log collection
* @throws JumbuneException
* the hTF exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* the interrupted exception
*/
@SuppressWarnings("unchecked")
public void copyRemoteSysStatsFiles(Cluster cluster)
throws JumbuneException, IOException, InterruptedException {
// changing the namenode location to null as this method is not used currently.
String nameNodeLocation = null;
String appHome = JumbuneInfo.getHome();
String relativePath = nameNodeLocation.substring(appHome.length() - 1,
nameNodeLocation.length());
Remoter remoter = RemotingUtil.getRemoter(cluster);
String remoteMkdir = MKDIR_P_CMD + AGENT_HOME + relativePath;
CommandWritableBuilder builder = new CommandWritableBuilder(cluster);
builder.addCommand(remoteMkdir, false, null, CommandType.FS);
remoter.fireAndForgetCommand(builder.getCommandWritable());
String mkdirCmd = MKDIR_P_CMD + nameNodeLocation;
execute(mkdirCmd.split(SPACE), appHome);
Workers workers = cluster.getWorkers();
String workerUser = workers.getUser();
// changing the worker location to null as this method is not used currently.
String workerLocation = null ;
for (String workerHost : workers.getHosts()) {
// copy cpu stats file from slaves
StringBuffer copyCpuFile = new StringBuffer(SCP_R_CMD);
copyCpuFile.append(SPACE).append(workerUser).append(AT_OP)
.append(workerHost).append(COLON).append(workerLocation)
.append(File.separator).append(CPU_DUMP_FILE)
.append(UNDERSCORE).append(workerHost).append(SPACE)
.append(AGENT_HOME).append(relativePath);
// copy memory stats file from slaves
StringBuffer copyMemFile = new StringBuffer(SCP_R_CMD);
copyMemFile.append(SPACE).append(workerUser).append(AT_OP)
.append(workerHost).append(COLON).append(workerLocation)
.append(File.separator).append(MEM_DUMP_FILE)
.append(UNDERSCORE).append(workerHost).append(SPACE)
.append(AGENT_HOME).append(relativePath);
String topDumpFile = workerLocation + File.separator
+ TOP_DUMP_FILE;
StringBuffer rmTopDumpFile = new StringBuffer(RM_CMD);
rmTopDumpFile.append(SPACE).append(topDumpFile);
StringBuffer rmCpuFile = new StringBuffer(RM_CMD);
rmCpuFile.append(SPACE).append(workerLocation)
.append(File.separator).append(CPU_DUMP_FILE)
.append(UNDERSCORE).append(workerHost);
// copy memory stats file from slaves
StringBuffer rmMemFile = new StringBuffer(SCP_R_CMD);
rmMemFile.append(SPACE).append(workerLocation)
.append(File.separator).append(MEM_DUMP_FILE)
.append(UNDERSCORE).append(workerHost);
builder.clear();
builder.addCommand(copyCpuFile.toString(), false, null,
CommandType.FS).setMethodToBeInvoked(RemotingMethodConstants.RUN_SCP_ACROSS_NODES)
.addCommand(copyMemFile.toString(), false, null,
CommandType.FS).setMethodToBeInvoked(RemotingMethodConstants.RUN_SCP_ACROSS_NODES)
.addCommand(rmCpuFile.toString(), false, null,
CommandType.FS)
.addCommand(rmMemFile.toString(), false, null,
CommandType.FS)
.addCommand(rmTopDumpFile.toString(), false, null,
CommandType.FS);
remoter.fireAndForgetCommand(builder.getCommandWritable());
}
builder.clear();
builder.addCommand(AGENT_HOME + relativePath, false, null,
CommandType.FS).setMethodToBeInvoked(
RemotingMethodConstants.PROCESS_GET_FILES);
List<String> fileList = (List<String>) remoter
.fireCommandAndGetObjectResponse(builder.getCommandWritable());
for (String string : fileList) {
remoter.receiveLogFiles(relativePath, relativePath + File.separator
+ string);
}
remoter.close();
}
/**
/**
* <p>
* This method collects all the log files from all the cluster nodes
* </p>
* .
* @param string
* @param slaveDVLocation
*
* @param logCollection
* log collection details
* @throws JumbuneException
* If any error occurred
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws InterruptedException
* the interrupted exception
*/
public void copyLogFilesToMaster(JumbuneRequest jumbuneRequest, String slaveDVLocation, String masterLocation)
throws JumbuneException, IOException, InterruptedException {
copyRemoteLogFiles(jumbuneRequest,slaveDVLocation,masterLocation);
}
/**
* Gets the HDFS paths recursively. The output of this method depends on the output of command {@code hdfs dfs -ls -R }.
* Additionally, this parses and filters the output based on whether {@code includeDirs } flag is true or false, if true,
* this includes directory entries also in the resulting list.
*
* The output is a list of all the files/directories in the following format. </br></br>
*
* -rw-r--r-- 1 impadmin supergroup 2805600 2016-04-29 14:53 /Jumbune/Demo/input/PREPROCESSED/data1
*
* @param cluster the cluster
* @param parentPath the parent path
* @param includeDirs whether to include directory entries in resulting list
* @return the HDFS paths recursively
*/
public List<String> getHDFSPathsRecursively(Cluster cluster, String parentPath, boolean includeDirs) {
List<String> paths = null;
String response = fireLSRCommandOnHDFS(cluster, parentPath);
if (response != null && !response.isEmpty()) {
paths = new ArrayList<>();
String attrib[] = null;
try (BufferedReader br = new BufferedReader(new StringReader(response))) {
for (String line = br.readLine(); line != null; line = br.readLine()) {
attrib = line.split(Constants.SPACE_REGEX);
if (attrib.length == 8) {
if (includeDirs) {
paths.add(line);
} else {
if (!attrib[0].startsWith("d")) {
paths.add(line);
}
}
}
}
} catch (IOException e) {
LOGGER.error("unable to parse response of lsr command fired on HDFS for path " + parentPath);
}
}
return paths;
}
/**
* Fires {@code hdfs dfs -ls -R }command on hdfs on the given path.
*
* @param cluster the cluster
* @param parentPath the parent path
* @return the string
*/
private String fireLSRCommandOnHDFS(Cluster cluster, String parentPath) {
Remoter remoter = RemotingUtil.getRemoter(cluster, null);
StringBuilder command = new StringBuilder().append(Constants.HADOOP_HOME).append(Constants.BIN_HDFS)
.append(Constants.DFS_LSR).append(parentPath);
CommandWritableBuilder commandWritableBuilder = new CommandWritableBuilder(cluster);
commandWritableBuilder.addCommand(command.toString(), false, null, CommandType.HADOOP_FS);
return (String) remoter.fireCommandAndGetObjectResponse(commandWritableBuilder.getCommandWritable());
}
/**
* Copies the validation files to Jumbune home
*
* @param cluster the cluster
* @param jumbuneRequest the jumbune request
*/
public void copyLogFilesToMasterForDV(JumbuneRequest jumbuneRequest) {
JobConfig jobConfig = jumbuneRequest.getJobConfig();
String nameNodeLocation = jobConfig.getMasterConsolidatedDVLocation();
String appHome = JumbuneInfo.getHome();
Cluster cluster = jumbuneRequest.getCluster();
String relativePath = nameNodeLocation.substring(appHome.length() - 1,
nameNodeLocation.length());
Remoter remoter = RemotingUtil.getRemoter(cluster);
String remoteMkdir = MKDIR_P_CMD + AGENT_HOME + relativePath;
CommandWritableBuilder builder = new CommandWritableBuilder(cluster);
builder.addCommand(remoteMkdir, false, null, CommandType.FS);
remoter.fireAndForgetCommand(builder.getCommandWritable());
// Creating local directories in Jumbune Working Dir
//String mkdirCmd = MKDIR_P_CMD + nameNodeLocation;
//execute(mkdirCmd.split(" "), null);
Workers workers = cluster.getWorkers();
String workerLocation = jobConfig.getTempDirectory() + Constants.JOB_JARS_LOC + jobConfig.getFormattedJumbuneJobName()+ Constants.SLAVE_DV_LOC;
LOGGER.debug("Starting to copy remote log files...");
for (String workerHost : workers.getHosts()) {
LOGGER.debug("Copy log files from: " + workerHost + ":" + workerLocation);
String command ;
if(cluster.getAgents().getSshAuthKeysFile() != null && cluster.getAgents().getSshAuthKeysFile().endsWith(".pem")){
command = "scp -i " + cluster.getAgents().getSshAuthKeysFile() + " -r " + jumbuneRequest.getJobConfig().getOperatingUser() + "@" + workerHost + ":"
+ workerLocation + " " + AGENT_HOME + relativePath;
}else{
command = "scp -r " + jumbuneRequest.getJobConfig().getOperatingUser() + "@" + workerHost + ":"
+ workerLocation + " " + AGENT_HOME + relativePath;
}
CommandWritableBuilder copyBuilder = new CommandWritableBuilder(cluster, null);
copyBuilder.addCommand(command, false, null, CommandType.FS).setMethodToBeInvoked(RemotingMethodConstants.RUN_SCP_ACROSS_NODES);
remoter.fireAndForgetCommand(copyBuilder.getCommandWritable());
}
try {
accumulateFileOutput(jumbuneRequest.getJobConfig().getHdfsInputPath(), jumbuneRequest.getJobConfig(), cluster);
} catch (IOException e) {
LOGGER.error(e);
}
builder.clear();
builder.addCommand(AGENT_HOME + relativePath, false, null,
CommandType.FS).setMethodToBeInvoked(
RemotingMethodConstants.PROCESS_GET_FILES);
List<String> fileList = (List<String>) remoter
.fireCommandAndGetObjectResponse(builder.getCommandWritable());
for (String file : fileList) {
remoter.receiveLogFiles(relativePath, relativePath + "/" + file);
}
}
/**
* Accumulate file output into single file with sorted first thousand keys mantained.
*
* @param inputPath the input path
* @param jobConfig the job config
* @param cluster the cluster
* @throws IOException Signals that an I/O exception has occurred.
*/
public void accumulateFileOutput(String inputPath, JobConfig jobConfig, Cluster cluster) throws IOException {
String dataValidationDirPath = null;
StringBuilder stringBuilder = new StringBuilder();
StringBuilder DtPath = new StringBuilder();
List<String> dataViolationTypes = new ArrayList<>();
dataViolationTypes.add(Constants.NUM_OF_FIELDS_CHECK);
dataViolationTypes.add(Constants.USER_DEFINED_NULL_CHECK);
dataViolationTypes.add(Constants.USER_DEFINED_DATA_TYPE);
dataViolationTypes.add(Constants.USER_DEFINED_REGEX_CHECK);
CommandWritableBuilder builder = null;
Remoter remoter = null;
String filePaths = getInputPaths(inputPath, jobConfig, getLsrCommandResponse(inputPath, cluster));
String[] listofFilesFromHDFS = filePaths.split(Constants.COMMA);
for (String fileFromList : listofFilesFromHDFS) {
for (String violationType : dataViolationTypes) {
DtPath.append("AGENT_HOME").append(Constants.JOB_JARS_LOC).append(jobConfig.getFormattedJumbuneJobName()).append("dv/")
.append(violationType).append(Constants.FORWARD_SLASH);
stringBuilder.append("if ! [ `ls ").append(DtPath).append(" | wc -l` == 0 ]; then ").append("cat ").append(DtPath)
.append(fileFromList.replaceFirst("\\.", "").trim()).append("-*").append(" >> ").append(DtPath)
.append("a1 && sort -n -t \"|\" -k 1 ").append(DtPath).append("a1 -o ").
append(DtPath).append("a1 && head -n 1000 ").append(DtPath).append("a1 >> ").append(DtPath).append(fileFromList.replaceFirst("\\.", "").trim()).append("&& rm ")
.append(DtPath).append("a1 ")
.append(DtPath).append(fileFromList.replaceFirst("\\.", "").trim()).append("-*;")
.append(" else echo \"No files found hence exiting\"; fi");
dataValidationDirPath = stringBuilder.toString();
builder = new CommandWritableBuilder(cluster);
builder.addCommand(dataValidationDirPath.trim(), false, null, CommandType.FS).populate(cluster, cluster.getNameNode());
remoter = RemotingUtil.getRemoter(cluster);
remoter.fireAndForgetCommand(builder.getCommandWritable());
DtPath.delete(0, DtPath.length());
stringBuilder.delete(0, stringBuilder.length());
}
}
}
/**
* Gets the lsr command response containing all the files in the given path.
*
* @param hdfsFilePath the hdfs file path
* @param cluster the cluster
* @return the lsr command response
*/
private String getLsrCommandResponse(String hdfsFilePath,
Cluster cluster) {
Remoter remoter = RemotingUtil.getRemoter(cluster, null);
StringBuilder stringBuilder = new StringBuilder().append(Constants.HADOOP_HOME).append(Constants.BIN_HDFS).append(Constants.DFS_LSR).append(hdfsFilePath)
.append(" | sed 's/ */ /g' | cut -d\\ -f 1,8 --output-delimiter=',' | grep ^- | cut -d, -f2 ");
CommandWritableBuilder commandWritableBuilder = new CommandWritableBuilder(cluster, null);
commandWritableBuilder.addCommand(stringBuilder.toString(), false, null, CommandType.HADOOP_FS);
String commmandResponse = (String) remoter.fireCommandAndGetObjectResponse(commandWritableBuilder.getCommandWritable());
return commmandResponse;
}
/**
* Gets the input paths.
*
* @param hdfsFilePath the hdfs file path
* @param jobConfig the job config
* @param commandResponse the command response
* @return the input paths
* @throws IOException Signals that an I/O exception has occurred.
*/
private String getInputPaths(String hdfsFilePath,JobConfig jobConfig, String commandResponse) throws IOException{
List<String> listOfFiles = new ArrayList<String>();
String[] fileResponse = commandResponse.split(Constants.NEW_LINE);
String filePath = null ;
for (int i = 0; i < fileResponse.length; i++) {
String [] eachFileResponse = fileResponse[i].split("\\s+");
filePath = eachFileResponse[eachFileResponse.length-1];
if(filePath.contains(hdfsFilePath)){
filePath = filePath.replaceAll(File.separator, Constants.DOT);
listOfFiles.add(filePath);
}
}
return listOfFiles.toString().substring(1, listOfFiles.toString().length()-1);
}
}
| lgpl-3.0 |
qagwaai/StarMalaccamax | src/com/qagwaai/starmalaccamax/client/service/action/GetAllMarketsResponse.java | 1492 | /**
* GetAllUsersResponse.java
* Created by pgirard at 2:07:29 PM on Aug 19, 2010
* in the com.qagwaai.starmalaccamax.shared.services.action package
* for the StarMalaccamax project
*/
package com.qagwaai.starmalaccamax.client.service.action;
import java.util.ArrayList;
import com.google.gwt.user.client.rpc.IsSerializable;
import com.qagwaai.starmalaccamax.shared.model.MarketDTO;
/**
* @author pgirard
*
*/
public final class GetAllMarketsResponse extends AbstractResponse implements IsSerializable {
/**
*
*/
private ArrayList<MarketDTO> markets;
/**
*
*/
private int totalMarkets;
/**
* @return the users
*/
public ArrayList<MarketDTO> getMarkets() {
return markets;
}
/**
* @return the totalMarkets
*/
public int getTotalMarkets() {
return totalMarkets;
}
/**
* @param markets
* the users to set
*/
public void setMarkets(final ArrayList<MarketDTO> markets) {
this.markets = markets;
}
/**
* @param totalMarkets
* the totalMarkets to set
*/
public void setTotalMarkets(final int totalMarkets) {
this.totalMarkets = totalMarkets;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "GetAllMarketsResponse [markets=" + markets + ", totalMarkets=" + totalMarkets + "]";
}
}
| lgpl-3.0 |
Depter/JRLib | NetbeansProject/jreserve-dummy/substance/src/main/java/org/pushingpixels/substance/internal/ui/SubstanceSpinnerUI.java | 15881 | /*
* Copyright (c) 2005-2010 Substance Kirill Grouchnikov. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of Substance Kirill Grouchnikov nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.pushingpixels.substance.internal.ui;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.EnumSet;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.UIResource;
import javax.swing.plaf.basic.BasicSpinnerUI;
import javax.swing.text.JTextComponent;
import org.pushingpixels.substance.api.*;
import org.pushingpixels.substance.api.SubstanceConstants.Side;
import org.pushingpixels.substance.internal.utils.*;
import org.pushingpixels.substance.internal.utils.SubstanceCoreUtilities.TextComponentAware;
import org.pushingpixels.substance.internal.utils.border.SubstanceTextComponentBorder;
import org.pushingpixels.substance.internal.utils.icon.TransitionAwareIcon;
/**
* UI for spinners in <b>Substance</b> look and feel.
*
* @author Kirill Grouchnikov
*/
public class SubstanceSpinnerUI extends BasicSpinnerUI {
/**
* Tracks changes to editor, removing the border as necessary.
*/
protected PropertyChangeListener substancePropertyChangeListener;
/**
* The next (increment) button.
*/
protected SubstanceSpinnerButton nextButton;
/**
* The previous (decrement) button.
*/
protected SubstanceSpinnerButton prevButton;
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.ComponentUI#createUI(javax.swing.JComponent)
*/
public static ComponentUI createUI(JComponent comp) {
SubstanceCoreUtilities.testComponentCreationThreadingViolation(comp);
return new SubstanceSpinnerUI();
}
@Override
public void installUI(JComponent c) {
super.installUI(c);
c.putClientProperty(SubstanceCoreUtilities.TEXT_COMPONENT_AWARE,
new TextComponentAware<JSpinner>() {
@Override
public JTextComponent getTextComponent(JSpinner t) {
JComponent editor = t.getEditor();
if ((editor != null)
&& (editor instanceof JSpinner.DefaultEditor)) {
return ((JSpinner.DefaultEditor) editor)
.getTextField();
}
return null;
}
});
}
@Override
public void uninstallUI(JComponent c) {
c.putClientProperty(SubstanceCoreUtilities.TEXT_COMPONENT_AWARE, null);
super.uninstallUI(c);
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.basic.BasicSpinnerUI#createNextButton()
*/
@Override
protected Component createNextButton() {
this.nextButton = new SubstanceSpinnerButton(this.spinner,
SwingConstants.NORTH);
this.nextButton.setFont(this.spinner.getFont());
this.nextButton.setName("Spinner.nextButton");
Icon icon = new TransitionAwareIcon(this.nextButton,
new TransitionAwareIcon.Delegate() {
public Icon getColorSchemeIcon(SubstanceColorScheme scheme) {
int fontSize = SubstanceSizeUtils
.getComponentFontSize(nextButton);
return SubstanceImageCreator.getArrowIcon(
SubstanceSizeUtils
.getSpinnerArrowIconWidth(fontSize),
SubstanceSizeUtils
.getSpinnerArrowIconHeight(fontSize),
SubstanceSizeUtils
.getArrowStrokeWidth(fontSize),
SwingConstants.NORTH, scheme);
}
}, "substance.spinner.nextButton");
this.nextButton.setIcon(icon);
int spinnerButtonSize = SubstanceSizeUtils
.getScrollBarWidth(SubstanceSizeUtils
.getComponentFontSize(spinner));
this.nextButton.setPreferredSize(new Dimension(spinnerButtonSize,
spinnerButtonSize));
this.nextButton.setMinimumSize(new Dimension(5, 5));
this.nextButton.putClientProperty(
SubstanceLookAndFeel.BUTTON_OPEN_SIDE_PROPERTY, EnumSet
.of(Side.BOTTOM));
this.nextButton.putClientProperty(
SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, EnumSet
.of(Side.BOTTOM));
this.installNextButtonListeners(this.nextButton);
Color spinnerBg = this.spinner.getBackground();
if (!(spinnerBg instanceof UIResource)) {
this.nextButton.setBackground(spinnerBg);
}
return this.nextButton;
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.basic.BasicSpinnerUI#createPreviousButton()
*/
@Override
protected Component createPreviousButton() {
this.prevButton = new SubstanceSpinnerButton(this.spinner,
SwingConstants.SOUTH);
this.prevButton.setFont(this.spinner.getFont());
this.prevButton.setName("Spinner.previousButton");
Icon icon = new TransitionAwareIcon(this.prevButton,
new TransitionAwareIcon.Delegate() {
public Icon getColorSchemeIcon(SubstanceColorScheme scheme) {
int fontSize = SubstanceSizeUtils
.getComponentFontSize(prevButton);
float spinnerArrowIconHeight = SubstanceSizeUtils
.getSpinnerArrowIconHeight(fontSize);
return SubstanceImageCreator.getArrowIcon(
SubstanceSizeUtils
.getSpinnerArrowIconWidth(fontSize),
spinnerArrowIconHeight, SubstanceSizeUtils
.getArrowStrokeWidth(fontSize),
SwingConstants.SOUTH, scheme);
}
}, "substance.spinner.prevButton");
this.prevButton.setIcon(icon);
int spinnerButtonSize = SubstanceSizeUtils
.getScrollBarWidth(SubstanceSizeUtils
.getComponentFontSize(this.prevButton));
this.prevButton.setPreferredSize(new Dimension(spinnerButtonSize,
spinnerButtonSize));
this.prevButton.setMinimumSize(new Dimension(5, 5));
this.prevButton.putClientProperty(
SubstanceLookAndFeel.BUTTON_OPEN_SIDE_PROPERTY, EnumSet
.of(Side.TOP));
this.prevButton
.putClientProperty(SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY,
EnumSet.of(Side.TOP));
this.installPreviousButtonListeners(this.prevButton);
Color spinnerBg = this.spinner.getBackground();
if (!(spinnerBg instanceof UIResource)) {
this.nextButton.setBackground(spinnerBg);
}
return this.prevButton;
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.basic.BasicSpinnerUI#installDefaults()
*/
@Override
protected void installDefaults() {
super.installDefaults();
JComponent editor = this.spinner.getEditor();
if ((editor != null) && (editor instanceof JSpinner.DefaultEditor)) {
JTextField tf = ((JSpinner.DefaultEditor) editor).getTextField();
if (tf != null) {
int fontSize = SubstanceSizeUtils
.getComponentFontSize(this.spinner);
Insets ins = SubstanceSizeUtils
.getSpinnerTextBorderInsets(fontSize);
tf.setBorder(new EmptyBorder(ins.top, ins.left, ins.bottom,
ins.right));
tf.setFont(spinner.getFont());
tf.setOpaque(false);
}
}
if (editor != null) {
editor.setOpaque(false);
}
Border b = this.spinner.getBorder();
if (b == null || b instanceof UIResource) {
this.spinner.setBorder(new SubstanceTextComponentBorder(
SubstanceSizeUtils
.getSpinnerBorderInsets(SubstanceSizeUtils
.getComponentFontSize(this.spinner))));
}
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.basic.BasicSpinnerUI#installListeners()
*/
@Override
protected void installListeners() {
super.installListeners();
this.substancePropertyChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if ("editor".equals(evt.getPropertyName())) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (spinner == null)
return;
JComponent editor = spinner.getEditor();
if ((editor != null)
&& (editor instanceof JSpinner.DefaultEditor)) {
JTextField tf = ((JSpinner.DefaultEditor) editor)
.getTextField();
if (tf != null) {
Insets ins = SubstanceSizeUtils
.getSpinnerTextBorderInsets(SubstanceSizeUtils
.getComponentFontSize(spinner));
tf.setBorder(new EmptyBorder(ins.top,
ins.left, ins.bottom, ins.right));
tf.revalidate();
}
}
}
});
}
if ("font".equals(evt.getPropertyName())) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (spinner != null) {
spinner.updateUI();
}
}
});
}
if ("background".equals(evt.getPropertyName())) {
JComponent editor = spinner.getEditor();
if ((editor != null)
&& (editor instanceof JSpinner.DefaultEditor)) {
JTextField tf = ((JSpinner.DefaultEditor) editor)
.getTextField();
if (tf != null) {
// Use SubstanceColorResource to distingish between
// color set by application and color set
// (propagated)
// by Substance. In the second case we can replace
// that color (even though it's not a UIResource).
Color tfBackground = tf.getBackground();
boolean canReplace = SubstanceCoreUtilities
.canReplaceChildBackgroundColor(tfBackground);
// fix for issue 387 - if spinner background
// is null, do nothing
if (spinner.getBackground() == null)
canReplace = false;
if (canReplace) {
tf.setBackground(new SubstanceColorResource(
spinner.getBackground()));
}
}
}
nextButton.setBackground(spinner.getBackground());
prevButton.setBackground(spinner.getBackground());
}
}
};
this.spinner
.addPropertyChangeListener(this.substancePropertyChangeListener);
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.basic.BasicSpinnerUI#uninstallListeners()
*/
@Override
protected void uninstallListeners() {
this.spinner
.removePropertyChangeListener(this.substancePropertyChangeListener);
this.substancePropertyChangeListener = null;
super.uninstallListeners();
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.ComponentUI#paint(java.awt.Graphics,
* javax.swing.JComponent)
*/
@Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
Graphics2D graphics = (Graphics2D) g.create();
int width = this.spinner.getWidth();
int height = this.spinner.getHeight();
int componentFontSize = SubstanceSizeUtils
.getComponentFontSize(this.spinner);
int borderDelta = (int) Math.floor(SubstanceSizeUtils
.getBorderStrokeWidth(componentFontSize));
Shape contour = SubstanceOutlineUtilities
.getBaseOutline(
width,
height,
Math.max(
0,
2.0f
* SubstanceSizeUtils
.getClassicButtonCornerRadius(componentFontSize)
- borderDelta), null, borderDelta);
graphics.setColor(SubstanceTextUtilities
.getTextBackgroundFillColor(this.spinner));
graphics.fill(contour);
graphics.dispose();
}
/*
* (non-Javadoc)
*
* @see
* javax.swing.plaf.ComponentUI#getPreferredSize(javax.swing.JComponent)
*/
@Override
public Dimension getPreferredSize(JComponent c) {
Dimension nextD = this.nextButton.getPreferredSize();
Dimension previousD = this.prevButton.getPreferredSize();
Dimension editorD = spinner.getEditor().getPreferredSize();
Dimension size = new Dimension(editorD.width, editorD.height);
size.width += Math.max(nextD.width, previousD.width);
Insets insets = this.spinner.getInsets();
size.width += insets.left + insets.right;
size.height += insets.top + insets.bottom;
return size;
}
/*
* (non-Javadoc)
*
* @see javax.swing.plaf.ComponentUI#update(java.awt.Graphics,
* javax.swing.JComponent)
*/
@Override
public void update(Graphics g, JComponent c) {
SubstanceTextUtilities.paintTextCompBackground(g, c);
this.paint(g, c);
}
@Override
protected LayoutManager createLayout() {
return new SpinnerLayoutManager();
}
/**
* Layout manager for the spinner.
*
* @author Kirill Grouchnikov
*/
protected class SpinnerLayoutManager implements LayoutManager {
public void addLayoutComponent(String name, Component comp) {
}
public void removeLayoutComponent(Component comp) {
}
public Dimension minimumLayoutSize(Container parent) {
return this.preferredLayoutSize(parent);
}
public Dimension preferredLayoutSize(Container parent) {
Dimension nextD = nextButton.getPreferredSize();
Dimension previousD = prevButton.getPreferredSize();
Dimension editorD = spinner.getEditor().getPreferredSize();
/*
* Force the editors height to be a multiple of 2
*/
editorD.height = ((editorD.height + 1) / 2) * 2;
Dimension size = new Dimension(editorD.width, editorD.height);
size.width += Math.max(nextD.width, previousD.width);
Insets insets = parent.getInsets();
size.width += insets.left + insets.right;
size.height += insets.top + insets.bottom;
Insets buttonInsets = SubstanceSizeUtils
.getSpinnerArrowButtonInsets(SubstanceSizeUtils
.getComponentFontSize(spinner));
size.width += (buttonInsets.left + buttonInsets.right);
return size;
}
public void layoutContainer(Container parent) {
int width = parent.getWidth();
int height = parent.getHeight();
Insets insets = parent.getInsets();
Dimension nextD = nextButton.getPreferredSize();
Dimension previousD = prevButton.getPreferredSize();
int buttonsWidth = Math.max(nextD.width, previousD.width);
int editorHeight = height - (insets.top + insets.bottom);
Insets buttonInsets = SubstanceSizeUtils
.getSpinnerArrowButtonInsets(SubstanceSizeUtils
.getComponentFontSize(spinner));
/*
* Deal with the spinner's componentOrientation property.
*/
int editorX, editorWidth, buttonsX;
if (parent.getComponentOrientation().isLeftToRight()) {
editorX = insets.left;
editorWidth = width - insets.left - buttonsWidth;
buttonsX = width - buttonsWidth;// - buttonInsets.right;
} else {
buttonsX = 0;// buttonInsets.left;
editorX = buttonsX + buttonsWidth;
editorWidth = width - editorX - insets.right;
}
int nextY = 0;// buttonInsets.top;
int nextHeight = (height / 2) + (height % 2) - nextY;
int previousY = 0 * buttonInsets.top + nextHeight;
int previousHeight = height - previousY;// - buttonInsets.bottom;
spinner.getEditor().setBounds(editorX, insets.top, editorWidth,
editorHeight);
nextButton.setBounds(buttonsX, nextY, buttonsWidth, nextHeight);
prevButton.setBounds(buttonsX, previousY, buttonsWidth,
previousHeight);
// System.out.println("next : " + nextButton.getBounds());
// System.out.println("prev : " + prevButton.getBounds());
}
}
}
| lgpl-3.0 |
ZalemSoftware/Ymir | ymir.client-android.entity.data-openmobster/src/main/java/br/com/zalem/ymir/client/android/entity/data/openmobster/cursor/AbstractMobileBeanCursor.java | 1776 | package br.com.zalem.ymir.client.android.entity.data.openmobster.cursor;
import android.database.Cursor;
import br.com.zalem.ymir.client.android.entity.data.cursor.IEntityRecordCursor;
/**
* Base para cursores de dados baseados no OpenMobster.<br>
* Apenas engloba um {@link android.database.Cursor} e repassa para ele as funções básicas de um cursor, como mover-se, obter a contagem,
* fechar, etc.
*
* @see android.database.Cursor
*
* @author Thiago Gesser
*/
public abstract class AbstractMobileBeanCursor implements IEntityRecordCursor {
protected final Cursor dbCursor;
public AbstractMobileBeanCursor(Cursor dbCursor) {
this.dbCursor = dbCursor;
}
@Override
public int getCount() {
return dbCursor.getCount();
}
@Override
public int getPosition() {
return dbCursor.getPosition();
}
@Override
public boolean move(int offset) {
return dbCursor.move(offset);
}
@Override
public boolean moveToPosition(int position) {
return dbCursor.moveToPosition(position);
}
@Override
public boolean moveToFirst() {
return dbCursor.moveToFirst();
}
@Override
public boolean moveToLast() {
return dbCursor.moveToLast();
}
@Override
public boolean moveToNext() {
return dbCursor.moveToNext();
}
@Override
public boolean moveToPrevious() {
return dbCursor.moveToPrevious();
}
@Override
public boolean isFirst() {
return dbCursor.isFirst();
}
@Override
public boolean isLast() {
return dbCursor.isLast();
}
@Override
public boolean isBeforeFirst() {
return dbCursor.isBeforeFirst();
}
@Override
public boolean isAfterLast() {
return dbCursor.isAfterLast();
}
@Override
public void close() {
dbCursor.close();
}
@Override
public boolean isClosed() {
return dbCursor.isClosed();
}
}
| lgpl-3.0 |
yuripourre/runaway | src/main/java/TombRunaway.java | 578 |
import br.com.etyllica.EtyllicaFrame;
import br.com.etyllica.core.context.Application;
import br.com.runaway.menu.MainMenu;
public class TombRunaway extends EtyllicaFrame {
private static final long serialVersionUID = 1L;
public TombRunaway() {
super(800, 600);
}
public static void main(String[] args){
TombRunaway map = new TombRunaway();
map.init();
}
public Application startApplication() {
initialSetup("../");
/*JoystickLoader.getInstance().start(1);
new Thread(JoystickLoader.getInstance()).start();*/
return new MainMenu(w, h);
}
}
| lgpl-3.0 |
MingweiSamuel/Zyra | src/main/gen/com/mingweisamuel/zyra/matchV4/ParticipantStats.java | 22002 | package com.mingweisamuel.zyra.matchV4;
import com.google.common.base.Objects;
import java.io.Serializable;
import java.lang.Object;
import java.lang.Override;
/**
* ParticipantStats.<br><br>
*
* This class was automatically generated from the <a href="http://www.mingweisamuel.com/riotapi-schema/openapi-3.0.0.min.json">Riot API reference</a>. */
public class ParticipantStats implements Serializable {
public final int altarsCaptured;
public final int altarsNeutralized;
public final int assists;
public final int champLevel;
public final int combatPlayerScore;
public final long damageDealtToObjectives;
public final long damageDealtToTurrets;
public final long damageSelfMitigated;
public final int deaths;
public final int doubleKills;
public final boolean firstBloodAssist;
public final boolean firstBloodKill;
public final boolean firstInhibitorAssist;
public final boolean firstInhibitorKill;
public final boolean firstTowerAssist;
public final boolean firstTowerKill;
public final int goldEarned;
public final int goldSpent;
public final int inhibitorKills;
public final int item0;
public final int item1;
public final int item2;
public final int item3;
public final int item4;
public final int item5;
public final int item6;
public final int killingSprees;
public final int kills;
public final int largestCriticalStrike;
public final int largestKillingSpree;
public final int largestMultiKill;
public final int longestTimeSpentLiving;
public final long magicDamageDealt;
public final long magicDamageDealtToChampions;
public final long magicalDamageTaken;
public final int neutralMinionsKilled;
public final int neutralMinionsKilledEnemyJungle;
public final int neutralMinionsKilledTeamJungle;
public final int nodeCapture;
public final int nodeCaptureAssist;
public final int nodeNeutralize;
public final int nodeNeutralizeAssist;
public final int objectivePlayerScore;
public final int participantId;
public final int pentaKills;
/**
* Primary path keystone rune. */
public final int perk0;
/**
* Post game rune stats. */
public final int perk0Var1;
/**
* Post game rune stats. */
public final int perk0Var2;
/**
* Post game rune stats. */
public final int perk0Var3;
/**
* Primary path rune. */
public final int perk1;
/**
* Post game rune stats. */
public final int perk1Var1;
/**
* Post game rune stats. */
public final int perk1Var2;
/**
* Post game rune stats. */
public final int perk1Var3;
/**
* Primary path rune. */
public final int perk2;
/**
* Post game rune stats. */
public final int perk2Var1;
/**
* Post game rune stats. */
public final int perk2Var2;
/**
* Post game rune stats. */
public final int perk2Var3;
/**
* Primary path rune. */
public final int perk3;
/**
* Post game rune stats. */
public final int perk3Var1;
/**
* Post game rune stats. */
public final int perk3Var2;
/**
* Post game rune stats. */
public final int perk3Var3;
/**
* Secondary path rune. */
public final int perk4;
/**
* Post game rune stats. */
public final int perk4Var1;
/**
* Post game rune stats. */
public final int perk4Var2;
/**
* Post game rune stats. */
public final int perk4Var3;
/**
* Secondary path rune. */
public final int perk5;
/**
* Post game rune stats. */
public final int perk5Var1;
/**
* Post game rune stats. */
public final int perk5Var2;
/**
* Post game rune stats. */
public final int perk5Var3;
/**
* Primary rune path */
public final int perkPrimaryStyle;
/**
* Secondary rune path */
public final int perkSubStyle;
public final long physicalDamageDealt;
public final long physicalDamageDealtToChampions;
public final long physicalDamageTaken;
public final int playerScore0;
public final int playerScore1;
public final int playerScore2;
public final int playerScore3;
public final int playerScore4;
public final int playerScore5;
public final int playerScore6;
public final int playerScore7;
public final int playerScore8;
public final int playerScore9;
public final int quadraKills;
public final int sightWardsBoughtInGame;
public final int teamObjective;
public final long timeCCingOthers;
public final long totalDamageDealt;
public final long totalDamageDealtToChampions;
public final long totalDamageTaken;
public final long totalHeal;
public final int totalMinionsKilled;
public final int totalPlayerScore;
public final int totalScoreRank;
public final int totalTimeCrowdControlDealt;
public final int totalUnitsHealed;
public final int tripleKills;
public final long trueDamageDealt;
public final long trueDamageDealtToChampions;
public final long trueDamageTaken;
public final int turretKills;
public final int unrealKills;
public final long visionScore;
public final int visionWardsBoughtInGame;
public final int wardsKilled;
public final int wardsPlaced;
public final boolean win;
public ParticipantStats(final int altarsCaptured, final int altarsNeutralized, final int assists,
final int champLevel, final int combatPlayerScore, final long damageDealtToObjectives,
final long damageDealtToTurrets, final long damageSelfMitigated, final int deaths,
final int doubleKills, final boolean firstBloodAssist, final boolean firstBloodKill,
final boolean firstInhibitorAssist, final boolean firstInhibitorKill,
final boolean firstTowerAssist, final boolean firstTowerKill, final int goldEarned,
final int goldSpent, final int inhibitorKills, final int item0, final int item1,
final int item2, final int item3, final int item4, final int item5, final int item6,
final int killingSprees, final int kills, final int largestCriticalStrike,
final int largestKillingSpree, final int largestMultiKill, final int longestTimeSpentLiving,
final long magicDamageDealt, final long magicDamageDealtToChampions,
final long magicalDamageTaken, final int neutralMinionsKilled,
final int neutralMinionsKilledEnemyJungle, final int neutralMinionsKilledTeamJungle,
final int nodeCapture, final int nodeCaptureAssist, final int nodeNeutralize,
final int nodeNeutralizeAssist, final int objectivePlayerScore, final int participantId,
final int pentaKills, final int perk0, final int perk0Var1, final int perk0Var2,
final int perk0Var3, final int perk1, final int perk1Var1, final int perk1Var2,
final int perk1Var3, final int perk2, final int perk2Var1, final int perk2Var2,
final int perk2Var3, final int perk3, final int perk3Var1, final int perk3Var2,
final int perk3Var3, final int perk4, final int perk4Var1, final int perk4Var2,
final int perk4Var3, final int perk5, final int perk5Var1, final int perk5Var2,
final int perk5Var3, final int perkPrimaryStyle, final int perkSubStyle,
final long physicalDamageDealt, final long physicalDamageDealtToChampions,
final long physicalDamageTaken, final int playerScore0, final int playerScore1,
final int playerScore2, final int playerScore3, final int playerScore4,
final int playerScore5, final int playerScore6, final int playerScore7,
final int playerScore8, final int playerScore9, final int quadraKills,
final int sightWardsBoughtInGame, final int teamObjective, final long timeCCingOthers,
final long totalDamageDealt, final long totalDamageDealtToChampions,
final long totalDamageTaken, final long totalHeal, final int totalMinionsKilled,
final int totalPlayerScore, final int totalScoreRank, final int totalTimeCrowdControlDealt,
final int totalUnitsHealed, final int tripleKills, final long trueDamageDealt,
final long trueDamageDealtToChampions, final long trueDamageTaken, final int turretKills,
final int unrealKills, final long visionScore, final int visionWardsBoughtInGame,
final int wardsKilled, final int wardsPlaced, final boolean win) {
this.altarsCaptured = altarsCaptured;
this.altarsNeutralized = altarsNeutralized;
this.assists = assists;
this.champLevel = champLevel;
this.combatPlayerScore = combatPlayerScore;
this.damageDealtToObjectives = damageDealtToObjectives;
this.damageDealtToTurrets = damageDealtToTurrets;
this.damageSelfMitigated = damageSelfMitigated;
this.deaths = deaths;
this.doubleKills = doubleKills;
this.firstBloodAssist = firstBloodAssist;
this.firstBloodKill = firstBloodKill;
this.firstInhibitorAssist = firstInhibitorAssist;
this.firstInhibitorKill = firstInhibitorKill;
this.firstTowerAssist = firstTowerAssist;
this.firstTowerKill = firstTowerKill;
this.goldEarned = goldEarned;
this.goldSpent = goldSpent;
this.inhibitorKills = inhibitorKills;
this.item0 = item0;
this.item1 = item1;
this.item2 = item2;
this.item3 = item3;
this.item4 = item4;
this.item5 = item5;
this.item6 = item6;
this.killingSprees = killingSprees;
this.kills = kills;
this.largestCriticalStrike = largestCriticalStrike;
this.largestKillingSpree = largestKillingSpree;
this.largestMultiKill = largestMultiKill;
this.longestTimeSpentLiving = longestTimeSpentLiving;
this.magicDamageDealt = magicDamageDealt;
this.magicDamageDealtToChampions = magicDamageDealtToChampions;
this.magicalDamageTaken = magicalDamageTaken;
this.neutralMinionsKilled = neutralMinionsKilled;
this.neutralMinionsKilledEnemyJungle = neutralMinionsKilledEnemyJungle;
this.neutralMinionsKilledTeamJungle = neutralMinionsKilledTeamJungle;
this.nodeCapture = nodeCapture;
this.nodeCaptureAssist = nodeCaptureAssist;
this.nodeNeutralize = nodeNeutralize;
this.nodeNeutralizeAssist = nodeNeutralizeAssist;
this.objectivePlayerScore = objectivePlayerScore;
this.participantId = participantId;
this.pentaKills = pentaKills;
this.perk0 = perk0;
this.perk0Var1 = perk0Var1;
this.perk0Var2 = perk0Var2;
this.perk0Var3 = perk0Var3;
this.perk1 = perk1;
this.perk1Var1 = perk1Var1;
this.perk1Var2 = perk1Var2;
this.perk1Var3 = perk1Var3;
this.perk2 = perk2;
this.perk2Var1 = perk2Var1;
this.perk2Var2 = perk2Var2;
this.perk2Var3 = perk2Var3;
this.perk3 = perk3;
this.perk3Var1 = perk3Var1;
this.perk3Var2 = perk3Var2;
this.perk3Var3 = perk3Var3;
this.perk4 = perk4;
this.perk4Var1 = perk4Var1;
this.perk4Var2 = perk4Var2;
this.perk4Var3 = perk4Var3;
this.perk5 = perk5;
this.perk5Var1 = perk5Var1;
this.perk5Var2 = perk5Var2;
this.perk5Var3 = perk5Var3;
this.perkPrimaryStyle = perkPrimaryStyle;
this.perkSubStyle = perkSubStyle;
this.physicalDamageDealt = physicalDamageDealt;
this.physicalDamageDealtToChampions = physicalDamageDealtToChampions;
this.physicalDamageTaken = physicalDamageTaken;
this.playerScore0 = playerScore0;
this.playerScore1 = playerScore1;
this.playerScore2 = playerScore2;
this.playerScore3 = playerScore3;
this.playerScore4 = playerScore4;
this.playerScore5 = playerScore5;
this.playerScore6 = playerScore6;
this.playerScore7 = playerScore7;
this.playerScore8 = playerScore8;
this.playerScore9 = playerScore9;
this.quadraKills = quadraKills;
this.sightWardsBoughtInGame = sightWardsBoughtInGame;
this.teamObjective = teamObjective;
this.timeCCingOthers = timeCCingOthers;
this.totalDamageDealt = totalDamageDealt;
this.totalDamageDealtToChampions = totalDamageDealtToChampions;
this.totalDamageTaken = totalDamageTaken;
this.totalHeal = totalHeal;
this.totalMinionsKilled = totalMinionsKilled;
this.totalPlayerScore = totalPlayerScore;
this.totalScoreRank = totalScoreRank;
this.totalTimeCrowdControlDealt = totalTimeCrowdControlDealt;
this.totalUnitsHealed = totalUnitsHealed;
this.tripleKills = tripleKills;
this.trueDamageDealt = trueDamageDealt;
this.trueDamageDealtToChampions = trueDamageDealtToChampions;
this.trueDamageTaken = trueDamageTaken;
this.turretKills = turretKills;
this.unrealKills = unrealKills;
this.visionScore = visionScore;
this.visionWardsBoughtInGame = visionWardsBoughtInGame;
this.wardsKilled = wardsKilled;
this.wardsPlaced = wardsPlaced;
this.win = win;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) return true;
if (!(obj instanceof ParticipantStats)) return false;
final ParticipantStats other = (ParticipantStats) obj;
return true
&& Objects.equal(altarsCaptured, other.altarsCaptured)
&& Objects.equal(altarsNeutralized, other.altarsNeutralized)
&& Objects.equal(assists, other.assists)
&& Objects.equal(champLevel, other.champLevel)
&& Objects.equal(combatPlayerScore, other.combatPlayerScore)
&& Objects.equal(damageDealtToObjectives, other.damageDealtToObjectives)
&& Objects.equal(damageDealtToTurrets, other.damageDealtToTurrets)
&& Objects.equal(damageSelfMitigated, other.damageSelfMitigated)
&& Objects.equal(deaths, other.deaths)
&& Objects.equal(doubleKills, other.doubleKills)
&& Objects.equal(firstBloodAssist, other.firstBloodAssist)
&& Objects.equal(firstBloodKill, other.firstBloodKill)
&& Objects.equal(firstInhibitorAssist, other.firstInhibitorAssist)
&& Objects.equal(firstInhibitorKill, other.firstInhibitorKill)
&& Objects.equal(firstTowerAssist, other.firstTowerAssist)
&& Objects.equal(firstTowerKill, other.firstTowerKill)
&& Objects.equal(goldEarned, other.goldEarned)
&& Objects.equal(goldSpent, other.goldSpent)
&& Objects.equal(inhibitorKills, other.inhibitorKills)
&& Objects.equal(item0, other.item0)
&& Objects.equal(item1, other.item1)
&& Objects.equal(item2, other.item2)
&& Objects.equal(item3, other.item3)
&& Objects.equal(item4, other.item4)
&& Objects.equal(item5, other.item5)
&& Objects.equal(item6, other.item6)
&& Objects.equal(killingSprees, other.killingSprees)
&& Objects.equal(kills, other.kills)
&& Objects.equal(largestCriticalStrike, other.largestCriticalStrike)
&& Objects.equal(largestKillingSpree, other.largestKillingSpree)
&& Objects.equal(largestMultiKill, other.largestMultiKill)
&& Objects.equal(longestTimeSpentLiving, other.longestTimeSpentLiving)
&& Objects.equal(magicDamageDealt, other.magicDamageDealt)
&& Objects.equal(magicDamageDealtToChampions, other.magicDamageDealtToChampions)
&& Objects.equal(magicalDamageTaken, other.magicalDamageTaken)
&& Objects.equal(neutralMinionsKilled, other.neutralMinionsKilled)
&& Objects.equal(neutralMinionsKilledEnemyJungle, other.neutralMinionsKilledEnemyJungle)
&& Objects.equal(neutralMinionsKilledTeamJungle, other.neutralMinionsKilledTeamJungle)
&& Objects.equal(nodeCapture, other.nodeCapture)
&& Objects.equal(nodeCaptureAssist, other.nodeCaptureAssist)
&& Objects.equal(nodeNeutralize, other.nodeNeutralize)
&& Objects.equal(nodeNeutralizeAssist, other.nodeNeutralizeAssist)
&& Objects.equal(objectivePlayerScore, other.objectivePlayerScore)
&& Objects.equal(participantId, other.participantId)
&& Objects.equal(pentaKills, other.pentaKills)
&& Objects.equal(perk0, other.perk0)
&& Objects.equal(perk0Var1, other.perk0Var1)
&& Objects.equal(perk0Var2, other.perk0Var2)
&& Objects.equal(perk0Var3, other.perk0Var3)
&& Objects.equal(perk1, other.perk1)
&& Objects.equal(perk1Var1, other.perk1Var1)
&& Objects.equal(perk1Var2, other.perk1Var2)
&& Objects.equal(perk1Var3, other.perk1Var3)
&& Objects.equal(perk2, other.perk2)
&& Objects.equal(perk2Var1, other.perk2Var1)
&& Objects.equal(perk2Var2, other.perk2Var2)
&& Objects.equal(perk2Var3, other.perk2Var3)
&& Objects.equal(perk3, other.perk3)
&& Objects.equal(perk3Var1, other.perk3Var1)
&& Objects.equal(perk3Var2, other.perk3Var2)
&& Objects.equal(perk3Var3, other.perk3Var3)
&& Objects.equal(perk4, other.perk4)
&& Objects.equal(perk4Var1, other.perk4Var1)
&& Objects.equal(perk4Var2, other.perk4Var2)
&& Objects.equal(perk4Var3, other.perk4Var3)
&& Objects.equal(perk5, other.perk5)
&& Objects.equal(perk5Var1, other.perk5Var1)
&& Objects.equal(perk5Var2, other.perk5Var2)
&& Objects.equal(perk5Var3, other.perk5Var3)
&& Objects.equal(perkPrimaryStyle, other.perkPrimaryStyle)
&& Objects.equal(perkSubStyle, other.perkSubStyle)
&& Objects.equal(physicalDamageDealt, other.physicalDamageDealt)
&& Objects.equal(physicalDamageDealtToChampions, other.physicalDamageDealtToChampions)
&& Objects.equal(physicalDamageTaken, other.physicalDamageTaken)
&& Objects.equal(playerScore0, other.playerScore0)
&& Objects.equal(playerScore1, other.playerScore1)
&& Objects.equal(playerScore2, other.playerScore2)
&& Objects.equal(playerScore3, other.playerScore3)
&& Objects.equal(playerScore4, other.playerScore4)
&& Objects.equal(playerScore5, other.playerScore5)
&& Objects.equal(playerScore6, other.playerScore6)
&& Objects.equal(playerScore7, other.playerScore7)
&& Objects.equal(playerScore8, other.playerScore8)
&& Objects.equal(playerScore9, other.playerScore9)
&& Objects.equal(quadraKills, other.quadraKills)
&& Objects.equal(sightWardsBoughtInGame, other.sightWardsBoughtInGame)
&& Objects.equal(teamObjective, other.teamObjective)
&& Objects.equal(timeCCingOthers, other.timeCCingOthers)
&& Objects.equal(totalDamageDealt, other.totalDamageDealt)
&& Objects.equal(totalDamageDealtToChampions, other.totalDamageDealtToChampions)
&& Objects.equal(totalDamageTaken, other.totalDamageTaken)
&& Objects.equal(totalHeal, other.totalHeal)
&& Objects.equal(totalMinionsKilled, other.totalMinionsKilled)
&& Objects.equal(totalPlayerScore, other.totalPlayerScore)
&& Objects.equal(totalScoreRank, other.totalScoreRank)
&& Objects.equal(totalTimeCrowdControlDealt, other.totalTimeCrowdControlDealt)
&& Objects.equal(totalUnitsHealed, other.totalUnitsHealed)
&& Objects.equal(tripleKills, other.tripleKills)
&& Objects.equal(trueDamageDealt, other.trueDamageDealt)
&& Objects.equal(trueDamageDealtToChampions, other.trueDamageDealtToChampions)
&& Objects.equal(trueDamageTaken, other.trueDamageTaken)
&& Objects.equal(turretKills, other.turretKills)
&& Objects.equal(unrealKills, other.unrealKills)
&& Objects.equal(visionScore, other.visionScore)
&& Objects.equal(visionWardsBoughtInGame, other.visionWardsBoughtInGame)
&& Objects.equal(wardsKilled, other.wardsKilled)
&& Objects.equal(wardsPlaced, other.wardsPlaced)
&& Objects.equal(win, other.win);}
@Override
public int hashCode() {
return Objects.hashCode(0,
altarsCaptured,
altarsNeutralized,
assists,
champLevel,
combatPlayerScore,
damageDealtToObjectives,
damageDealtToTurrets,
damageSelfMitigated,
deaths,
doubleKills,
firstBloodAssist,
firstBloodKill,
firstInhibitorAssist,
firstInhibitorKill,
firstTowerAssist,
firstTowerKill,
goldEarned,
goldSpent,
inhibitorKills,
item0,
item1,
item2,
item3,
item4,
item5,
item6,
killingSprees,
kills,
largestCriticalStrike,
largestKillingSpree,
largestMultiKill,
longestTimeSpentLiving,
magicDamageDealt,
magicDamageDealtToChampions,
magicalDamageTaken,
neutralMinionsKilled,
neutralMinionsKilledEnemyJungle,
neutralMinionsKilledTeamJungle,
nodeCapture,
nodeCaptureAssist,
nodeNeutralize,
nodeNeutralizeAssist,
objectivePlayerScore,
participantId,
pentaKills,
perk0,
perk0Var1,
perk0Var2,
perk0Var3,
perk1,
perk1Var1,
perk1Var2,
perk1Var3,
perk2,
perk2Var1,
perk2Var2,
perk2Var3,
perk3,
perk3Var1,
perk3Var2,
perk3Var3,
perk4,
perk4Var1,
perk4Var2,
perk4Var3,
perk5,
perk5Var1,
perk5Var2,
perk5Var3,
perkPrimaryStyle,
perkSubStyle,
physicalDamageDealt,
physicalDamageDealtToChampions,
physicalDamageTaken,
playerScore0,
playerScore1,
playerScore2,
playerScore3,
playerScore4,
playerScore5,
playerScore6,
playerScore7,
playerScore8,
playerScore9,
quadraKills,
sightWardsBoughtInGame,
teamObjective,
timeCCingOthers,
totalDamageDealt,
totalDamageDealtToChampions,
totalDamageTaken,
totalHeal,
totalMinionsKilled,
totalPlayerScore,
totalScoreRank,
totalTimeCrowdControlDealt,
totalUnitsHealed,
tripleKills,
trueDamageDealt,
trueDamageDealtToChampions,
trueDamageTaken,
turretKills,
unrealKills,
visionScore,
visionWardsBoughtInGame,
wardsKilled,
wardsPlaced,
win);}
}
| lgpl-3.0 |
DivineCooperation/jul | pattern/controller/src/main/java/org/openbase/jul/pattern/controller/ConfigurableController.java | 1249 | package org.openbase.jul.pattern.controller;
/*
* #%L
* JUL Pattern Controller
* %%
* Copyright (C) 2015 - 2021 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%
*/
import org.openbase.jul.iface.Configurable;
import org.openbase.jul.iface.Manageable;
/**
*
* @author <a href="mailto:divine@openbase.org">Divine Threepwood</a>
* @param <ID> the identifier type
* @param <M> the data type
* @param <CONFIG> the configuration type
*/
public interface ConfigurableController<ID, M, CONFIG> extends IdentifiableController<ID, M>, Manageable<CONFIG>, Configurable<ID, CONFIG> {
}
| lgpl-3.0 |
kwakeroni/workshops | java9/solution/src/main/java/be/kwakeroni/workshop/java9/solution/Main.java | 1540 | package be.kwakeroni.workshop.java9.solution;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
new Main().handleFiles(args);
}
private final StudentParser parser = new StudentParser();
private void handleFiles(String[] args) throws Exception {
if (args.length == 0) {
handleGroups(
parser.parseStudents(Paths.get("group1.csv")),
parser.parseStudents(Paths.get("group2.csv")));
} else {
handleGroups(parse(args));
}
}
@SuppressWarnings("unchecked")
private List<Student>[] parse(String[] paths) {
return Arrays.stream(paths)
.map(Paths::get)
.map(this::parse)
.toArray(List[]::new);
}
private List<Student> parse(Path path) {
try {
return parser.parseStudents(path);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@java.lang.SafeVarargs
private void handleGroups(List<Student>... groups) {
for (int i = 0; i < groups.length; i++) {
System.out.println("- Group #%s".formatted(i));
groups[i].forEach(student -> System.out.println("-- %s %s (aged %s)".formatted(student.lastName(), student.firstName(), student.age())));
}
}
}
| lgpl-3.0 |
waterguo/antsdb | fish-server/src/main/java/com/antsdb/saltedfish/sql/vdm/StringLiteral.java | 1832 | /*-------------------------------------------------------------------------------------------------
_______ __ _ _______ _______ ______ ______
|_____| | \ | | |______ | \ |_____]
| | | \_| | ______| |_____/ |_____]
Copyright (c) 2016, antsdb.com and/or its affiliates. All rights reserved. *-xguo0<@
This program is free software: you can redistribute it and/or modify it under the terms of the
GNU GNU Lesser General Public License, version 3, as published by the Free Software Foundation.
You should have received a copy of the GNU Affero General Public License along with this program.
If not, see <https://www.gnu.org/licenses/lgpl-3.0.en.html>
-------------------------------------------------------------------------------------------------*/
package com.antsdb.saltedfish.sql.vdm;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import com.antsdb.saltedfish.cpp.FishObject;
import com.antsdb.saltedfish.cpp.Heap;
import com.antsdb.saltedfish.sql.DataType;
public class StringLiteral extends Operator {
String value;
public StringLiteral(String value) {
super();
this.value = value;
}
@Override
public long eval(VdmContext ctx, Heap heap, Parameters params, long pRecord) {
long addr = FishObject.allocSet(heap, this.value);
return addr;
}
@Override
public DataType getReturnType() {
return DataType.varchar();
}
@Override
public List<Operator> getChildren() {
return Collections.emptyList();
}
@Override
public void visit(Consumer<Operator> visitor) {
visitor.accept(this);
}
@Override
public String toString() {
return "'" + this.value + "'";
}
public String getValue() {
return this.value;
}
}
| lgpl-3.0 |
korvus81/ari4java | classes/ch/loway/oss/ari4java/generated/ari_1_5_0/models/FormatLangPair_impl_ari_1_5_0.java | 1312 | package ch.loway.oss.ari4java.generated.ari_1_5_0.models;
// ----------------------------------------------------
// THIS CLASS WAS GENERATED AUTOMATICALLY
// PLEASE DO NOT EDIT
// Generated on: Sat Sep 19 08:50:54 CEST 2015
// ----------------------------------------------------
import ch.loway.oss.ari4java.generated.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**********************************************************
* Identifies the format and language of a sound file
*
* Defined in file: sounds.json
* Generated by: Model
*********************************************************/
public class FormatLangPair_impl_ari_1_5_0 implements FormatLangPair, java.io.Serializable {
private static final long serialVersionUID = 1L;
/** */
private String format;
public String getFormat() {
return format;
}
@JsonDeserialize( as=String.class )
public void setFormat(String val ) {
format = val;
}
/** */
private String language;
public String getLanguage() {
return language;
}
@JsonDeserialize( as=String.class )
public void setLanguage(String val ) {
language = val;
}
/** No missing signatures from interface */
}
| lgpl-3.0 |
kocakosm/pitaya | src/org/kocakosm/pitaya/io/TextFiles.java | 15156 | /*----------------------------------------------------------------------------*
* This file is part of Pitaya. *
* Copyright (C) 2012-2016 Osman KOCAK <kocakosm@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, see <http://www.gnu.org/licenses/>. *
*----------------------------------------------------------------------------*/
package org.kocakosm.pitaya.io;
import org.kocakosm.pitaya.charset.Charsets;
import org.kocakosm.pitaya.util.Parameters;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* Text files utilities.
*
* @see XFiles
*
* @author Osman KOCAK
*/
public final class TextFiles
{
/**
* Returns the first (up to 10) lines of the given {@code File} using
* the system's default charset. Named after the Unix command of the
* same name.
*
* @param f the {@code File} to read.
*
* @return the first lines of the given {@code File}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> head(File f) throws IOException
{
return head(f, Charsets.DEFAULT);
}
/**
* Returns the first (up to 10) lines of the given {@code File} using
* the specified charset. Named after the Unix command of the same name.
*
* @param f the {@code File} to read.
* @param charset the charset to use.
*
* @return the first lines of the given {@code File}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> head(File f, Charset charset) throws IOException
{
return head(f, 10, charset);
}
/**
* Returns the first (up to {@code n}) lines of the given {@code File}
* using the system's default charset. Named after the Unix command of
* the same name.
*
* @param f the {@code File} to read.
* @param n the maximum number of lines to read.
*
* @return the first lines of the given {@code File}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IllegalArgumentException if {@code n} is negative.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> head(File f, int n) throws IOException
{
return head(f, n, Charsets.DEFAULT);
}
/**
* Returns the first (up to {@code n}) lines of the given {@code File}
* using the specified charset. Named after the Unix command of the same
* name.
*
* @param f the {@code File} to read.
* @param n the maximum number of lines to read.
* @param charset the charset to use.
*
* @return the first lines of the given {@code File}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IllegalArgumentException if {@code n} is negative.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> head(File f, int n, Charset charset)
throws IOException
{
Parameters.checkCondition(n >= 0);
List<String> lines = new ArrayList<String>();
BufferedReader reader = newReader(f, charset);
try {
String line = reader.readLine();
while (line != null && lines.size() < n) {
lines.add(line);
line = reader.readLine();
}
} finally {
IO.close(reader);
}
return Collections.unmodifiableList(lines);
}
/**
* Returns the last (up to 10) lines of the given {@code File} using the
* system's default charset. Named after the Unix command of the same
* name.
*
* @param f the {@code File} to read.
*
* @return the last lines of the given {@code File}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> tail(File f) throws IOException
{
return tail(f, Charsets.DEFAULT);
}
/**
* Returns the last (up to 10) lines of the given {@code File} using the
* specified charset. Named after the Unix command of the same name.
*
* @param f the {@code File} to read.
* @param charset the charset to use.
*
* @return the last lines of the given {@code File}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> tail(File f, Charset charset) throws IOException
{
return tail(f, 10, charset);
}
/**
* Returns the last (up to n) lines of the given {@code File} using the
* system's default charset. Named after the Unix command of the same
* name.
*
* @param f the {@code File} to read.
* @param n the maximum number of lines to read.
*
* @return the last lines of the given {@code File}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IllegalArgumentException if {@code n} is negative.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> tail(File f, int n) throws IOException
{
return tail(f, n, Charsets.DEFAULT);
}
/**
* Returns the last (up to n) lines of the given {@code File} using the
* specified charset. Named after the Unix command of the same name.
*
* @param f the {@code File} to read.
* @param n the maximum number of lines to read.
* @param charset the charset to use.
*
* @return the last lines of the given {@code File}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IllegalArgumentException if {@code n} is negative.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> tail(File f, int n, Charset charset)
throws IOException
{
Parameters.checkCondition(n >= 0);
if (n == 0) {
return Collections.emptyList();
}
List<String> lines = new LinkedList<String>();
BufferedReader reader = newReader(f, charset);
try {
String line = reader.readLine();
while (line != null) {
lines.add(line);
if (lines.size() > n) {
lines.remove(0);
}
line = reader.readLine();
}
} finally {
IO.close(reader);
}
return Collections.unmodifiableList(lines);
}
/**
* Returns a new {@code BufferedReader} to read the given {@code File}
* using the system's default charset.
*
* @param f the file to read from.
*
* @return a {@code BufferedReader} to read the given {@code File}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws FileNotFoundException if {@code f} doesn't exist, or if it is
* a directory rather than a regular file, or if it can't be opened
* for reading.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static BufferedReader newReader(File f) throws FileNotFoundException
{
return newReader(f, Charsets.DEFAULT);
}
/**
* Returns a new {@code BufferedReader} to read the given {@code File}
* using the specified charset.
*
* @param f the file to read from.
* @param charset the charset to use.
*
* @return a {@code BufferedReader} to read the given {@code File}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws FileNotFoundException if {@code f} doesn't exist, or if it is
* a directory rather than a regular file, or if it can't be opened
* for reading.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static BufferedReader newReader(File f, Charset charset)
throws FileNotFoundException
{
InputStream in = new FileInputStream(f);
return new BufferedReader(new InputStreamReader(in, charset));
}
/**
* Returns a new {@code BufferedWriter} to write to the given
* {@code File} using the system's default charset.
*
* @param f the file to write to.
* @param options the write options.
*
* @return a {@code BufferedWriter} to write to the given {@code File}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IllegalArgumentException if incompatible options are given.
* @throws FileNotFoundException if {@code f} exists but is a directory
* rather than a regular file, or if it does not exist but cannot
* be created, or if it cannot be opened for any other reason.
* @throws IOException if the {@link WriteOption#CREATE} option is given
* and the specified file already exists.
* @throws SecurityException if a security manager exists and denies
* write access to {@code f}.
*/
public static BufferedWriter newWriter(File f, WriteOption... options)
throws IOException
{
return newWriter(f, Charsets.DEFAULT, options);
}
/**
* Returns a new {@code BufferedWriter} to write to the given
* {@code File} using the specified charset.
*
* @param f the file to write to.
* @param charset the charset to use.
* @param options the write options.
*
* @return a {@code BufferedWriter} to write to the given {@code File}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IllegalArgumentException if incompatible options are given.
* @throws FileNotFoundException if {@code f} exists but is a directory
* rather than a regular file, or if it does not exist but cannot
* be created, or if it cannot be opened for any other reason.
* @throws IOException if the {@link WriteOption#CREATE} option is given
* and the specified file already exists.
* @throws SecurityException if a security manager exists and denies
* write access to {@code f}.
*/
public static BufferedWriter newWriter(File f, Charset charset,
WriteOption... options) throws IOException
{
OutputStream out = XFiles.newOutputStream(f, options);
return new BufferedWriter(new OutputStreamWriter(out, charset));
}
/**
* Reads the whole content of the given {@code File} as a {@code String}
* using the system's default charset.
*
* @param f the file to read.
*
* @return the file's content as a {@code String}.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static String read(File f) throws IOException
{
return read(f, Charsets.DEFAULT);
}
/**
* Reads the whole content of the given {@code File} as a {@code String}
* using the specified charset.
*
* @param f the file to read.
* @param charset the charset to use.
*
* @return the file's content as a {@code String}.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static String read(File f, Charset charset) throws IOException
{
BufferedReader in = newReader(f, charset);
try {
return CharStreams.read(in);
} finally {
IO.close(in);
}
}
/**
* Reads all the lines from the given {@code File} using the system's
* default charset. Note that the returned {@code List} is immutable.
*
* @param f the file to read.
*
* @return the file's lines.
*
* @throws NullPointerException if {@code f} is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> readLines(File f) throws IOException
{
return readLines(f, Charsets.DEFAULT);
}
/**
* Reads all the lines from the given {@code File} using the specified
* charset. Note that the returned {@code List} is immutable.
*
* @param f the file to read.
* @param charset the charset to use.
*
* @return the file's lines.
*
* @throws NullPointerException if one of the arguments is {@code null}.
* @throws IOException if {@code f} does not exist, or if it is a
* directory rather than a regular file, or if it can't be read.
* @throws SecurityException if a security manager exists and denies
* read access to {@code f}.
*/
public static List<String> readLines(File f, Charset charset)
throws IOException
{
BufferedReader in = newReader(f, charset);
try {
return CharStreams.readLines(in);
} finally {
IO.close(in);
}
}
private TextFiles()
{
/* ... */
}
}
| lgpl-3.0 |
cswaroop/Catalano-Framework | Catalano.Android.Image/src/Catalano/Imaging/Filters/Threshold.java | 3408 | // Catalano Imaging Library
// The Catalano Framework
//
// Copyright © Diego Catalano, 2015
// diego.catalano at live.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
package Catalano.Imaging.Filters;
import Catalano.Imaging.FastBitmap;
import Catalano.Imaging.IBaseInPlace;
/**
* The filter does image binarization using specified threshold value. All pixels with intensities equal or higher than threshold value are converted to white pixels. All other pixels with intensities below threshold value are converted to black pixels.
*
* Supported types: Grayscale.
* Coordinate System: Independent.
*
* @author Diego Catalano
*/
public class Threshold implements IBaseInPlace{
private int value = 128;
private boolean invert = false;
/**
* Initialize a new instance of the Threshold class.
*/
public Threshold() {}
/**
* Initialize a new instance of the Threshold class.
* @param value Threshold value.
*/
public Threshold(int value){
this.value = value;
}
/**
* Initialize a new instance of the Threshold class.
* @param value Threshold value.
* @param invert All pixels with intensities equal or higher than threshold value are converted to black pixels. All other pixels with intensities below threshold value are converted to white pixels.
*/
public Threshold(int value, boolean invert){
this.value = value;
this.invert = invert;
}
/**
* Threshold value.
* @return Threshold value.
*/
public int getValue() {
return value;
}
/**
* Threshold value.
* @param value Threshold value.
*/
public void setValue(int value) {
this.value = value;
}
@Override
public void applyInPlace(FastBitmap fastBitmap){
if (!fastBitmap.isGrayscale())
throw new IllegalArgumentException("Binarization works only with RGB images.");
int[] pixels = fastBitmap.getData();
for (int i = 0; i < pixels.length; i++) {
int l = pixels[i] & 0xFF;
if(invert == false){
if(l >= value){
pixels[i] = 255 << 24 | 255 << 16 | 255 << 8 | 255;
}
else{
pixels[i] = 0;
}
}
else{
if(l < value){
pixels[i] = 0;
}
else{
pixels[i] = 255 << 24 | 255 << 16 | 255 << 8 | 255;
}
}
}
}
} | lgpl-3.0 |
pingping-jiang6141/Engine-Master | Engine/src/org/zywx/wbpalmstar/engine/EBrowserView.java | 49210 | /*
* Copyright (C) 2014 The AppCan Open Source Project.
*
* 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.zywx.wbpalmstar.engine;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.inputmethod.InputMethodManager;
import android.webkit.DownloadListener;
import android.webkit.WebView;
import android.widget.FrameLayout;
import org.json.JSONObject;
import org.zywx.wbpalmstar.acedes.ACEDes;
import org.zywx.wbpalmstar.acedes.EXWebViewClient;
import org.zywx.wbpalmstar.base.BDebug;
import org.zywx.wbpalmstar.base.vo.KernelInfoVO;
import org.zywx.wbpalmstar.engine.EBrowserHistory.EHistoryEntry;
import org.zywx.wbpalmstar.engine.universalex.EUExCallback;
import org.zywx.wbpalmstar.engine.universalex.EUExManager;
import org.zywx.wbpalmstar.engine.universalex.EUExWindow;
import org.zywx.wbpalmstar.widgetone.dataservice.WWidgetData;
import java.lang.reflect.Method;
import java.util.Map;
public class EBrowserView extends WebView implements View.OnLongClickListener,
DownloadListener {
public static final String CONTENT_MIMETYPE_HTML = "text/html";
public static final String CONTENT_DEFAULT_CODE = "utf-8";
public static final int F_PRINT_TYPE_DOM_TREE = 0;
public static final int F_PRINT_TYPE_DISPLAY_TREE = 1;
public static final int F_PRINT_TYPE_RENDER_TREE = 2;
public static final int F_PRINT_TYPE_DRAW_PAGE = 3;
private int mType;
private String mName;
private String mQuery;
private String mRelativeUrl;
private Context mContext;
private EUExManager mUExMgr;
private EBrowserBaseSetting mBaSetting;
private EBrowserWindow mBroWind;
private boolean mShouldOpenInSystem;
private boolean mOpaque;
private boolean mOAuth;
private boolean mWebApp;
private boolean mSupportZoom;
private int mDateType;
private boolean mDestroyed;
private EBrwViewAnim mViewAnim;
private EXWebViewClient mEXWebViewClient;
private Method mDismissZoomControl;
private int mDownloadCallback = 0; // 0 下载不回调,使用引擎下载; 1 下载回调给主窗口,前端自己下载; 2 下载回调给当前窗口,前端自己下载;
// use for debug
private Method mDumpDisplayTree;
private Method mDumpDomTree;
private Method mDumpRenderTree;
private Method mDrawPage;
private int mMyCountId;
private int mScrollDistance = 10;
private EUExWindow callback;
private boolean mIsNeedScroll = false;
private boolean isMultilPopoverFlippingEnbaled = false;
private boolean isSupportSlideCallback = false;//is need callback,set by API interface.
private boolean disturbLongPressGesture = false;
private int mThreshold = 5;
private OnEBrowserViewChangeListener mBrowserViewChangeListener;
public static boolean sHardwareAccelerate = true;//配置全部WebView是否硬件加速,默认开启,config.xml 配置关闭
public EBrowserView(Context context, int inType, EBrowserWindow inParent) {
super(context);
mMyCountId = EBrowser.assignCountID();
mBroWind = inParent;
mContext = context;
mType = inType;
initPrivateVoid();
setOnLongClickListener(this);
setDownloadListener(this);
setACEHardwareAccelerate();
}
public EUExManager getEUExManager() {
return mUExMgr;
}
public void setScrollCallBackContex(EUExWindow callback) {
this.callback = callback;
}
public float getCustomScale(){
float nowScale = 1.0f;
if (Build.VERSION.SDK_INT <= 18) {
nowScale = getScale();
}
return nowScale;
}
public void init() {
setInitialScale(100);
setVerticalScrollbarOverlay(true);
setHorizontalScrollbarOverlay(true);
setLayoutAnimation(null);
setAnimation(null);
setNetworkAvailable(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (mBroWind!=null){
int debug = mBroWind.getWidget().m_appdebug;
setWebContentsDebuggingEnabled(debug == 1 ? true : false);
}
}
if (Build.VERSION.SDK_INT <= 7) {
if (mBaSetting == null) {
mBaSetting = new EBrowserSetting(this);
mBaSetting.initBaseSetting(mWebApp);
setWebViewClient(mEXWebViewClient = new CBrowserWindow());
setWebChromeClient(new CBrowserMainFrame(mContext));
}
} else {
if (mBaSetting == null) {
mBaSetting = new EBrowserSetting7(this);
mBaSetting.initBaseSetting(mWebApp);
setWebViewClient(mEXWebViewClient = new CBrowserWindow7());
setWebChromeClient(new CBrowserMainFrame7(mContext));
}
}
mUExMgr = new EUExManager(mContext);
mUExMgr.addJavascriptInterface(this);
}
private void setACEHardwareAccelerate() {
if (!sHardwareAccelerate) {
setLayerType(LAYER_TYPE_SOFTWARE, null);
} else {
closeHardwareForSpecificString();
}
}
@Override
protected void onAttachedToWindow() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (!isHardwareAccelerated()) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
BDebug.i("setLayerType","LAYER_TYPE_SOFTWARE");
} else {
closeHardwareForSpecificString();
}
}
super.onAttachedToWindow();
}
private void closeHardwareForSpecificString() {
WWidgetData widgetData = getCurrentWidget();
if (widgetData != null) {
for (String noHardware : widgetData.noHardwareList) {
String str = noHardware.trim();
// 手机型号、Android系统定制商、硬件制造商
if (Build.MODEL.trim().equals(str)
|| Build.BRAND.trim().equals(str)
|| Build.MANUFACTURER.trim().equals(str)) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
BDebug.i("setLayerType", "LAYER_TYPE_SOFTWARE");
break;
}
}
}
}
@Override
public boolean isHardwareAccelerated() {
//confirm view is attached to a window
boolean isHardwareAccelerated = super.isHardwareAccelerated();
BDebug.v("isHardwareAccelerated", isHardwareAccelerated);
return isHardwareAccelerated;
}
@Override
public void loadUrl(String url) {
if (mDestroyed) {
return;
}
BDebug.i("loadUrl url " + url);
try {
if (url.startsWith("javascript:") && Build.VERSION.SDK_INT >= 19) {
evaluateJavascript(url.substring("javascript:".length()), null);
} else {
super.loadUrl(url);
}
} catch (Exception e) {
;
}
}
@SuppressLint("NewApi")
@Override
public void loadUrl(String url, Map<String, String> extraHeaders) {
if (mDestroyed) {
return;
}
try {
super.loadUrl(url, extraHeaders);
} catch (Exception e) {
;
}
}
@Override
public void loadData(String data, String mimeType, String encoding) {
if (mDestroyed) {
return;
}
try {
super.loadData(data, mimeType, encoding);
} catch (Exception e) {
;
}
}
@Override
public void loadDataWithBaseURL(String baseUrl, String data,
String mimeType, String encoding, String historyUrl) {
if (mDestroyed) {
return;
}
try {
super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding,
historyUrl);
} catch (Exception e) {
;
}
}
public boolean checkType(int inType) {
return inType == mType;
}
public int getMyId() {
return mMyCountId;
}
public void setDefaultFontSize(int size) {
if (mDestroyed) {
return;
}
mBaSetting.setDefaultFontSize(size);
}
public void setSupportZoom() {
mSupportZoom = true;
mBaSetting.setSupportZoom();
}
public boolean supportZoom() {
return mSupportZoom;
}
@SuppressLint("NewApi")
private void initPrivateVoid() {
Class[] nullParm = {};
try {
mDismissZoomControl = WebView.class.getDeclaredMethod(
"dismissZoomControl", nullParm);
mDismissZoomControl.setAccessible(true);
} catch (Exception e) {
;
}
try {
mDumpDisplayTree = WebView.class.getDeclaredMethod(
"dumpDisplayTree", nullParm);
mDumpDisplayTree.setAccessible(true);
} catch (Exception e) {
;
}
Class[] booleanParam = {boolean.class};
try {
mDumpDomTree = WebView.class.getDeclaredMethod("dumpDomTree",
booleanParam);
mDumpDomTree.setAccessible(true);
} catch (Exception e) {
;
}
try {
mDumpRenderTree = WebView.class.getDeclaredMethod("dumpRenderTree",
booleanParam);
mDumpRenderTree.setAccessible(true);
} catch (Exception e) {
;
}
try {
Class[] canvasParam = {Canvas.class};
mDrawPage = WebView.class
.getDeclaredMethod("drawPage", canvasParam);
mDrawPage.setAccessible(true);
} catch (Exception e) {
;
}
if (Build.VERSION.SDK_INT >= 9) {
setOverScrollMode(2);
return;
}
try {
Class[] intParam = {int.class};
Method setOverScrollMode = WebView.class.getDeclaredMethod(
"setOverScrollMode", intParam);
setOverScrollMode.invoke(this, 2);
} catch (Exception e) {
;
}
}
public void dumpPageInfo(int type) {
switch (type) {
case F_PRINT_TYPE_DOM_TREE:
myDumpDomTree();
break;
case F_PRINT_TYPE_DISPLAY_TREE:
myDumpDisplayTree();
break;
case F_PRINT_TYPE_RENDER_TREE:
myDumpRenderTree();
break;
case F_PRINT_TYPE_DRAW_PAGE:
break;
}
}
// protected void setLayerTypeForHeighVersion() {
// // if(Build.VERSION.SDK_INT < 11){
// // return;
// // }
// // String MODEL = Build.MODEL;
// // String MANUFACTURER = Build.MANUFACTURER;
// // if(null != MODEL && null != MANUFACTURER){
// // MODEL = MODEL.toLowerCase();
// // MANUFACTURER = MANUFACTURER.toLowerCase();
// // if((MODEL.contains("9508") || MODEL.contains("9500")) &&
// // MANUFACTURER.contains("samsung")){
// // return;
// // }
// // }
// // Paint paint = new Paint();
// // paint.setColor(0x00000000);
// // if(isHardwareAccelerated()){
// // setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// // }
// }
// @SuppressLint("NewApi")
// @Override
// protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// if (Build.VERSION.SDK_INT >= 11) {
// String MODEL = Build.MODEL;
// String MANUFACTURER = Build.MANUFACTURER;
// if (null != MODEL && null != MANUFACTURER) {
// MODEL = MODEL.toLowerCase();
// MANUFACTURER = MANUFACTURER.toLowerCase();
// if ((MODEL.contains("9508") || MODEL.contains("9500"))
// && MANUFACTURER.contains("samsung")) {
// if (isHardwareAccelerated()) {
// setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// }
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// return;
// }
// }
// setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// invalidate();
// }
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// }
@SuppressLint("NewApi")
public void destroyControl() {
if (null != mDismissZoomControl) {
try {
mDismissZoomControl.invoke(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@SuppressLint("NewApi")
private void pauseCore() {
if (Build.VERSION.SDK_INT >= 11) {
super.onPause();
} else {
try {
Class[] nullParm = {};
Method pause = WebView.class.getDeclaredMethod("onPause",
nullParm);
pause.setAccessible(true);
pause.invoke(this);
} catch (Exception e) {
;
}
}
}
@SuppressLint("NewApi")
private void resumeCore() {
if (Build.VERSION.SDK_INT >= 11) {
super.onResume();
} else {
try {
Class[] nullParm = {};
Method resume = WebView.class.getDeclaredMethod("onResume",
nullParm);
resume.setAccessible(true);
resume.invoke(this);
} catch (Exception e) {
;
}
}
}
public void myDumpDisplayTree() {
if (null != mDumpDisplayTree) {
try {
mDumpDisplayTree.invoke(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void myDumpDomTree() {
if (null != mDumpDomTree) {
try {
mDumpDomTree.invoke(this, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void myDumpRenderTree() {
if (null != mDumpRenderTree) {
try {
mDumpRenderTree.invoke(this, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void myDrawPage(Canvas canvas) {
if (null != mDrawPage) {
try {
mDrawPage.invoke(this, canvas);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mDestroyed) {
return false;
}
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
if (!isFocused()) {
strugglefoucs();
}
onScrollChanged(getScrollX(), getScrollY(), getScrollX(), getScrollY());
if (mIsNeedScroll) {
//modify no-response-for-onclick-event
int temp_ScrollY = this.getScrollY();
this.scrollTo(this.getScrollX(), this.getScrollY() + 1);
this.scrollTo(this.getScrollX(), temp_ScrollY);
}
setMultilPopoverFlippingEnbaled();
break;
case MotionEvent.ACTION_MOVE:
setMultilPopoverFlippingEnbaled();
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
break;
}
return super.onTouchEvent(ev);
}
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
return super.onGenericMotionEvent(event); //To change body of overridden methods use File | Settings | File Templates.
}
public void setIsMultilPopoverFlippingEnbaled(boolean isEnabled) {
isMultilPopoverFlippingEnbaled = isEnabled;
setMultilPopoverFlippingEnbaled();
}
private void setMultilPopoverFlippingEnbaled() {
View parentBounceView = (View) this.getParent();
if (parentBounceView != null && parentBounceView instanceof EBounceView) {
ViewParent parentViewPager = parentBounceView.getParent();
if (parentViewPager != null && parentViewPager instanceof ViewPager) {
parentViewPager.requestDisallowInterceptTouchEvent(isMultilPopoverFlippingEnbaled);
}
}
}
private void strugglefoucs() {
requestFocus();
/**
* InputManager.get().hideSoftInput(getWindowToken(), 0, null);
* Log.d("ldx", "-------------- view in: " + mName);
*
* Log.d("ldx", "hasFocus: " + hasFocus()); Log.d("ldx", "isFocused: " +
* isFocused());
*
* try{ Class[] nullParam = {}; Method clearHelpers =
* WebView.class.getDeclaredMethod("clearHelpers", nullParam);
* clearHelpers.setAccessible(true); clearHelpers.invoke(this); }catch
* (Exception e) { e.printStackTrace(); } Log.d("ldx",
* "-------------- --------------");
*
* boolean Ac1 = InputManager.get().isActive(); boolean Ac2 =
* InputManager.get().isActive(this); if(Ac1){
* InputManager.get().hideSoftInput(this.getWindowToken(), 0, null); }
* Log.d("ldx", "imm Ac1: " + Ac1); Log.d("ldx", "imm Ac2: " + Ac2); int
* childCount = getChildCount(); Log.d("ldx", "childCount: " +
* childCount); for(int i = 0; i < childCount; ++i){ View child =
* getChildAt(i); boolean Ac3 = InputManager.get().isActive(child);
* Log.d("ldx", "imm Ac3: " + Ac3); if(Ac3){
* InputManager.get().hideSoftInput(child.getWindowToken(), 0, null); }
* child.clearFocus(); } boolean requestFocusOk = requestFocus();
* removeAllViews();
*
* Log.d("ldx", "requestFocusOk: " + requestFocusOk);
**/
// int childCount1 = getChildCount();
// Log.d("ldx", "childCount1: " + childCount1);
Log.d("ldx", "hasFocus: " + hasFocus());
Log.d("ldx", "isFocused: " + isFocused());
Log.d("ldx", "-------------- view out: " + mName);
}
@Override
public boolean onLongClick(View v) {
return disturbLongPressGesture;
}
public void setDisturbLongPressGesture(boolean disturbLongPress) {
disturbLongPressGesture = disturbLongPress;
}
@SuppressLint("NewApi")
@Override
protected void onVisibilityChanged(View v, int visibility) {
super.onVisibilityChanged(v, visibility);
if ((v == this || v == mBroWind)
&& (visibility == INVISIBLE || visibility == GONE)) {
hideSoftKeyboard();
}
}
private void hideSoftKeyboard() {
try {
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onPageStarted(EBrowserView view, String url) {
if (mDestroyed) {
return;
}
mUExMgr.notifyDocChange();
if (checkType(EBrwViewEntry.VIEW_TYPE_POP) && mOAuth) {
mBroWind.onUrlChange(mName, url);
return;
}
if (!checkType(EBrwViewEntry.VIEW_TYPE_MAIN)) {
return;
}
if (mBroWind!=null) {
mBroWind.onPageStarted(view, url);
}
}
protected void onPageFinished(EBrowserView view, String url) {
if (mDestroyed) {
return;
}
if (mBroWind!=null){
mBroWind.onPageFinished(view, url);
}
if (mBrowserViewChangeListener != null) {
mBrowserViewChangeListener.onPageFinish();
}
}
public boolean isObfuscation() {
if (mDestroyed) {
return false;
}
return mBroWind.isObfuscation();
}
public boolean isOAth() {
if (mDestroyed) {
return false;
}
return mBroWind.isOAuth();
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
@Override
public void goBack() {
if (mDestroyed) {
return;
}
if (isObfuscation()) {
EHistoryEntry enty = mBroWind.getHistory(-1);
if (null != enty) {
String url = enty.mUrl;
if (Build.VERSION.SDK_INT >= 11) {
if (url.startsWith("file")) {
int index = url.indexOf("?");
if (index > 0) {
mQuery = url.substring(index + 1);
url = url.substring(0, index);
}
}
}
if (enty.mIsObfuscation) {
needToEncrypt(this, url, EBrowserHistory.UPDATE_STEP_BACK);
} else {
loadUrl(url);
updateObfuscationHistroy(url,
EBrowserHistory.UPDATE_STEP_BACK, false);
}
}
} else {
super.goBack();
}
}
@Override
public void goForward() {
if (mDestroyed) {
return;
}
if (isObfuscation()) {
EHistoryEntry enty = mBroWind.getHistory(1);
if (null != enty) {
if (enty.mIsObfuscation) {
needToEncrypt(this, enty.mUrl,
EBrowserHistory.UPDATE_STEP_FORWARD);
} else {
loadUrl(enty.mUrl);
updateObfuscationHistroy(enty.mUrl,
EBrowserHistory.UPDATE_STEP_FORWARD, false);
}
}
} else {
super.goForward();
}
}
protected void updateObfuscationHistroy(String inUrl, int step,
boolean isObfuscation) {
if (mDestroyed) {
return;
}
if (!checkType(EBrwViewEntry.VIEW_TYPE_MAIN)) {
return;
}
mBroWind.updateObfuscationHistroy(inUrl, step, isObfuscation);
}
protected void clearObfuscationHistroy() {
if (mDestroyed) {
return;
}
mBroWind.clearObfuscationHistroy();
}
public void addViewToCurrentWindow(View child,
FrameLayout.LayoutParams parms) {
if (mDestroyed) {
return;
}
if (parms != null) {
child.setLayoutParams(parms);
}
mBroWind.addViewToCurrentWindow(child);
}
public void removeViewFromCurrentWindow(View child) {
if (mDestroyed) {
return;
}
mBroWind.removeViewFromCurrentWindow(child);
}
public final void startWidget(WWidgetData inData, EWgtResultInfo inResult) {
if (mDestroyed) {
return;
}
mBroWind.startWidget(inData, inResult);
}
protected void start1(String url) {
if (mDestroyed) {
return;
}
if (null == url || 0 == url.length()) {
return;
}
if (Build.VERSION.SDK_INT >= 11) {
if (url != null) {
int index = url.indexOf("?");
if (index > 0) {
setQuery(url.substring(index + 1));
if (!url.startsWith("http")) {
url = url.substring(0, index);
}
}
}
}
addUriTask(url);
}
private void eClearHistory() {
if (mDestroyed) {
return;
}
if (isObfuscation()) {
clearObfuscationHistroy();
} else {
clearHistory();
}
}
protected void start(String url) {
if (mDestroyed) {
return;
}
if (null == url || 0 == url.length()) {
return;
}
if (isObfuscation()) {
clearObfuscationHistroy();
if (url.startsWith("http")) {
addUriTask(url);
updateObfuscationHistroy(url, EBrowserHistory.UPDATE_STEP_INIT,
false);
} else {
needToEncrypt(this, url, EBrowserHistory.UPDATE_STEP_INIT); // may
// be
// crash
}
} else {
if (Build.VERSION.SDK_INT >= 11) {
if (url != null) {
int index = url.indexOf("?");
if (index > 0) {
setQuery(url.substring(index + 1));
if (!url.startsWith("http")) {
url = url.substring(0, index);
}
}
}
}
addUriTask(url);
clearHistory();
}
}
public void newLoadUrl(String url) {
if (mDestroyed) {
return;
}
if (null == url || 0 == url.length()) {
return;
}
addUriTask(url);
}
public void newLoadData(String inData) {
if (mDestroyed) {
return;
}
loadData(inData, CONTENT_MIMETYPE_HTML, CONTENT_DEFAULT_CODE);
}
protected void receivedError(int errorCode, String description,
String failingUrl) {
if (mDestroyed) {
return;
}
if (checkType(EBrwViewEntry.VIEW_TYPE_ADD)) {
loadUrl("about:bank");
mBroWind.closeAd();
return;
}
String errorPath="file:///android_asset/error/error.html";
if (mBroWind!=null&&!TextUtils.isEmpty(getRootWidget().mErrorPath)){
errorPath="file:///android_asset/widget/"+getRootWidget().mErrorPath;
loadUrl(errorPath);
}else{
loadUrl(errorPath);
}
}
public int getType() {
return mType;
}
public void addUriTask(String uri) {
if (null != mBroWind && !mDestroyed) {
mBroWind.addUriTask(this, uri);
}
}
public void addUriTaskAsyn(String uri) {
if (null != mBroWind && !mDestroyed) {
mBroWind.addUriTaskAsyn(this, uri);
}
}
/**
* 设置是否开启硬件加速
*
* @param flag -1不处理,0关闭,1开启
*/
public void setHWEnable(int flag) {
if (flag == -1) {
return;
}
if (flag == 1) {
setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
protected void needToEncrypt(WebView view, String url, int inFlag) {
if (mDestroyed) {
return;
}
int index = url.indexOf("?");
String turl = url;
if (index > 0) {
setQuery(url.substring(index + 1));
turl = turl.substring(0, index);
}
String data = ACEDes.decrypt(turl, mContext, false, null);
;
if (ACEDes.isSpecifiedEncrypt()) {
// data = SpecifiedEncrypt.parseSpecifiedEncryptHtml(data);
}
// if (SpecifiedEncrypt.isSpecifiedEncrypt()) {
//
// data = SpecifiedEncrypt.parseSpecifiedEncrypt(turl);
//
// } else {
// data = BHtmlDecrypt.decrypt(turl, mContext, false, null);
// }
view.loadDataWithBaseURL(url, data, CONTENT_MIMETYPE_HTML,
CONTENT_DEFAULT_CODE, url);
if (mType == EBrwViewEntry.VIEW_TYPE_MAIN) {
updateObfuscationHistroy(url, inFlag, true);
}
}
public EBrowserWindow getBrowserWindow() {
return mBroWind;
}
public int getWidgetType() {
int type = mBroWind.getWidgetType();
return type;
}
public String getWindowName() {
if (mDestroyed) {
return null;
}
return mBroWind.getName();
}
public void setQuery(String query) {
if (mDestroyed) {
return;
}
mQuery = query;
}
public String getQuery() {
if (mDestroyed) {
return null;
}
return mQuery;
}
public String getRelativeUrl() {
if (mDestroyed) {
return null;
}
return mRelativeUrl;
}
public void setRelativeUrl(String url) {
if (mDestroyed) {
return;
}
mRelativeUrl = url;
}
public String getCurrentUrl() {
if (mDestroyed) {
return "";
}
//修改浮动窗口中不能打开窗口问题
//if (!checkType(EBrwViewEntry.VIEW_TYPE_MAIN)) {
// return mBroWind.location();
//} else {
String url = getUrl();
int index = url.indexOf("?");
if (-1 != index) {
url = url.substring(0, index);
}
int indexS = url.indexOf("#");
if (-1 != indexS) {
url = url.substring(0, indexS);
}
return url;
//}
}
public String getCurrentUrl(String baseUrl) {
if (mDestroyed) {
return "";
}
//修改浮动窗口中不能打开窗口问题
//if (!checkType(EBrwViewEntry.VIEW_TYPE_MAIN)) {
// return mBroWind.location();
//} else {
String url = getUrl();
if (TextUtils.isEmpty(url)) {
url = baseUrl;
}
int index = url.indexOf("?");
if (-1 != index) {
url = url.substring(0, index);
}
int indexS = url.indexOf("#");
if (-1 != indexS) {
url = url.substring(0, indexS);
}
return url;
//}
}
public String getWidgetPath() {
if (mDestroyed) {
return "";
}
String ret = getCurrentWidget().m_widgetPath;
return ret;
}
public WWidgetData getCurrentWidget() {
if (mDestroyed) {
return new WWidgetData();
}
return mBroWind.getWidget();
}
public WWidgetData getRootWidget() {
if (mDestroyed) {
return new WWidgetData();
}
return mBroWind.getRootWidget();
}
public boolean isOAuth() {
return mOAuth;
}
public void setOAuth(boolean flag) {
mOAuth = flag;
}
public boolean shouldOpenInSystem() {
return mShouldOpenInSystem;
}
public void setShouldOpenInSystem(boolean flag) {
mShouldOpenInSystem = flag;
}
public void setOpaque(boolean flag) {
mOpaque = flag;
if (mOpaque) {
setBackgroundColor(0xFFFFFFFF);
} else {
setBackgroundColor(Color.TRANSPARENT);
}
}
/**wanglei del 20151124*/
// public void setBrwViewBackground(boolean flag, String bgColor, String baseUrl) {
// if (flag) {
// if(bgColor.startsWith("#") || bgColor.startsWith("rgb")){
// int color = BUtility.parseColor(bgColor);
// setBackgroundColor(color);
// }else{
// String path = BUtility.makeRealPath(BUtility.makeUrl(getCurrentUrl(baseUrl),bgColor),
// getCurrentWidget().m_widgetPath, getCurrentWidget().m_wgtType);
// Bitmap bitmap = BUtility.getLocalImg(mContext, path);
// Drawable d = null;
// if(bitmap != null){
// d = new BitmapDrawable(mContext.getResources(), bitmap);
// }
// int version = Build.VERSION.SDK_INT;
// if(version < 16){
// setBackgroundDrawable(d);
// setBackgroundColor(Color.argb(0, 0, 0, 0));
// }else{
// setBackground(d);
// setBackgroundColor(Color.argb(0, 0, 0, 0));
// }
// }
// } else {
// setBackgroundColor(Color.TRANSPARENT);
// }
// }
public void setWebApp(boolean flag) {
mWebApp = flag;
}
public boolean isWebApp() {
return mWebApp;
}
public int getDateType() {
return mDateType;
}
public void setDateType(int dateType) {
mDateType = dateType;
}
public void beginAnimition() {
if (mDestroyed) {
return;
}
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null == mViewAnim) {
mViewAnim = new EBrwViewAnim();
}
mViewAnim.beginAnimition(v);
}
});
}
public void setAnimitionDelay(final long del) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionDelay(v, del);
}
}
});
}
public void setAnimitionDuration(final long dur) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionDuration(v, dur);
}
}
});
}
public void setAnimitionCurve(final int cur) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionCurve(v, cur);
}
}
});
}
public void setAnimitionRepeatCount(final int count) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionRepeatCount(v, count);
}
}
});
}
public void setAnimitionAutoReverse(final boolean flag) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionAutoReverse(v, flag);
}
}
});
}
public void makeTranslation(final float tx, final float ty, final float tz) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.makeTranslation(v, tx, ty, tz);
}
}
});
}
public void makeScale(final float tx, final float ty, final float tz) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.makeScale(v, tx, ty, tz);
}
}
});
}
public void makeRotate(final float fd, final float px, final float py,
final float pz) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.makeRotate(v, fd, px, py, pz);
}
}
});
}
public void makeAlpha(final float fc) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.makeAlpha(v, fc);
}
}
});
}
public void commitAnimition() {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.commitAnimition(v);
mBroWind.invalidate();
}
}
});
}
public void cbBounceState(int inData) {
String js = "javascript:if(" + EUExWindow.function_cbBounceState + "){"
+ EUExWindow.function_cbBounceState + "(" + 0 + "," + 2 + ","
+ inData + ")}";
addUriTask(js);
}
public void getBounce() {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.obj = getParent();
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_GET_BOUNCE_VIEW);
}
public void setBounce(int flag) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.obj = getParent();
bounceEntry.flag = flag;
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_SET_BOUNCE_VIEW);
}
public void notifyBounceEvent(int inType, int inStatus) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
bounceEntry.flag = inStatus;
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_NOTIFY_BOUNCE_VIEW);
}
public void showBounceView(int inType, String inColor, int inFlag) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
bounceEntry.color = parseColor(inColor);
bounceEntry.flag = inFlag;
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_SHOW_BOUNCE_VIEW);
}
public void onBounceStateChange(int type, int state) {
String js = "javascript:if(uexWindow.onBounceStateChange){uexWindow.onBounceStateChange("
+ type + "," + state + ");}";
loadUrl(js);
}
public int parseColor(String inColor) {
int reColor = 0;
try {
if (inColor != null && inColor.length() != 0) {
inColor = inColor.replace(" ", "");
if (inColor.charAt(0) == 'r') { // rgba
int start = inColor.indexOf('(') + 1;
int off = inColor.indexOf(')');
inColor = inColor.substring(start, off);
String[] rgba = inColor.split(",");
int r = Integer.parseInt(rgba[0]);
int g = Integer.parseInt(rgba[1]);
int b = Integer.parseInt(rgba[2]);
int a = Integer.parseInt(rgba[3]);
reColor = (a << 24) | (r << 16) | (g << 8) | b;
} else { // #
inColor = inColor.substring(1);
if (3 == inColor.length()) {
char[] t = new char[6];
t[0] = inColor.charAt(0);
t[1] = inColor.charAt(0);
t[2] = inColor.charAt(1);
t[3] = inColor.charAt(1);
t[4] = inColor.charAt(2);
t[5] = inColor.charAt(2);
inColor = String.valueOf(t);
} else if (6 == inColor.length()) {
;
}
long color = Long.parseLong(inColor, 16);
reColor = (int) (color | 0x00000000ff000000);
}
}
} catch (Exception e) {
;
}
return reColor;
}
public void resetBounceView(int inType) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_RESET_BOUNCE_VIEW);
}
public void hiddenBounceView(int inType) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_HIDDEN_BOUNCE_VIEW);
}
public void setBounceParams(int inType, JSONObject json, String guestId) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
bounceEntry.obj1 = json;
bounceEntry.arg1 = guestId;
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_SET_BOUNCE_PARMS);
}
public void topBounceViewRefresh() {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.obj = getParent();
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_TOP_BOUNCE_VIEW_REFRESH);
}
public boolean beDestroy() {
return mDestroyed;
}
protected void reset() {
mDestroyed = false;
View bv = (View) getParent();
if (bv != null && bv instanceof EBounceView) {
((EBounceView) bv).release();
}
clearView();
clearMatches();
mQuery = null;
mName = null;
mRelativeUrl = null;
mShouldOpenInSystem = false;
mOpaque = false;
mOAuth = false;
mWebApp = false;
mSupportZoom = false;
isSupportSlideCallback = false;
disturbLongPressGesture = false;
eClearHistory();
resumeCore();
mUExMgr.notifyReset();
}
@Override
public void stopLoading() {
super.stopLoading();
mUExMgr.notifyStop();
pauseCore();
}
@Override
public void destroy() {
if (mDestroyed) {
return;
}
mDestroyed = true;
mBroWind = null;
mBaSetting = null;
mContext = null;
clearView();
clearHistory();
ViewGroup parent = (ViewGroup) getParent();
if (null != parent) {
parent.removeView(this);
}
mUExMgr.notifyDestroy(this);
mUExMgr = null;
super.destroy();
}
protected void printThreadStackTrace() {
StackTraceElement[] stak = Thread.currentThread().getStackTrace();
String s = "";
int len = stak.length;
for (int i = 0; i < len; ++i) {
StackTraceElement one = stak[i];
String className = one.getClassName();
String methodName = one.getMethodName();
int line = one.getLineNumber();
String x = s + className + "." + methodName + " [" + line + "]";
x.charAt(0);
if (i == 0 || i == 1 || i == 2) {
s += " ";
}
}
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
//if (!EBrowserWindow.isShowDialog) {
int versionA = Build.VERSION.SDK_INT;
boolean isSlideCallback = false;
if (versionA >= 19) {
//system above 4.4, is support callback depend on isSupportSlideCallback which
// set by developer.
// 4.4以上手机系统,是否回调取决于前端接口设置。
isSlideCallback = isSupportSlideCallback;
} else {
//system below 4.4, is support callback depend on isSupportSlideCallback and
//isShowDialog, isShowDialog indicate is pop-up keyboard or whether to switch
// the screen.
// 4.4以下手机系统,是否回调即取决于前端接口设置,也取决于当前键盘是否弹出或者是否变换屏幕。因此在该
// 条件下屏幕旋转之后,上滑下滑的监听不生效。
isSlideCallback = isSupportSlideCallback && !EBrowserWindow.isShowDialog;
}
if (isSlideCallback) {
float contentHeight = getContentHeight() * getCustomScale();
boolean isSlipedDownEdge = t != oldt && t > 0
&& contentHeight <= t + getHeight() + mThreshold;
if (isSlipedDownEdge) {
callback.jsCallback(EUExWindow.function_cbslipedDownEdge, 0,
EUExCallback.F_C_INT, 0);
callback.jsCallback(EUExWindow.function_onSlipedDownEdge, 0,
EUExCallback.F_C_INT, 0);
} else if (getScrollY() == 0) {
callback.jsCallback(EUExWindow.function_cbslipedUpEdge, 0,
EUExCallback.F_C_INT, 0);
callback.jsCallback(EUExWindow.function_onSlipedUpEdge, 0,
EUExCallback.F_C_INT, 0);
} else if (oldt - t > mScrollDistance) {
callback.jsCallback(EUExWindow.function_cbslipedDownward, 0,
EUExCallback.F_C_INT, 0);
callback.jsCallback(EUExWindow.function_onSlipedDownward, 0,
EUExCallback.F_C_INT, 0);
} else if (oldt - t < -mScrollDistance) {
callback.jsCallback(EUExWindow.function_cbslipedUpward, 0,
EUExCallback.F_C_INT, 0);
callback.jsCallback(EUExWindow.function_onSlipedUpward, 0,
EUExCallback.F_C_INT, 0);
}
}
//}
super.onScrollChanged(l, t, oldl, oldt);
}
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
if (mDownloadCallback == 0) {
mEXWebViewClient.onDownloadStart(mContext, url, userAgent,
contentDisposition, mimetype, contentLength);
} else {
mBroWind.executeCbDownloadCallbackJs(this, mDownloadCallback,
url, userAgent, contentDisposition, mimetype, contentLength);
}
}
public void setNeedScroll(boolean b) {
this.mIsNeedScroll = b;
}
public void setIsSupportSlideCallback(boolean isSupport) {
isSupportSlideCallback = isSupport;
}
public void setEBrowserViewChangeListener(OnEBrowserViewChangeListener browserViewChangeListener) {
mBrowserViewChangeListener = browserViewChangeListener;
}
public interface OnEBrowserViewChangeListener {
void onPageFinish();
}
public String getWebViewKernelInfo() {
KernelInfoVO infoVO = new KernelInfoVO();
if (Build.VERSION.SDK_INT > 18) {
infoVO.setKernelType("System(Blink)");
try {
PackageManager pm = this.getContext().getPackageManager();
PackageInfo pinfo = pm.getPackageInfo("com.google.android.webview",
PackageManager.GET_CONFIGURATIONS);
infoVO.setKernelVersion(pinfo.versionName);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
} else {
infoVO.setKernelType("System(Webkit)");
}
String info = DataHelper.gson.toJson(infoVO);
return info;
}
public void setUserAgent(String userAgent) {
mBaSetting.setUserAgent(userAgent);
}
public int getDownloadCallback() {
if (mDestroyed) {
return 0;
}
return mDownloadCallback;
}
public void setDownloadCallback(int downloadCallback) {
if (mDestroyed) {
return;
}
this.mDownloadCallback = downloadCallback;
}
}
| lgpl-3.0 |
ecologylab/ecologylabFundamental | src/ecologylab/serialization/deserializers/parsers/bibtex/entrytypes/BibTeXTechReport.java | 1351 | package ecologylab.serialization.deserializers.parsers.bibtex.entrytypes;
import ecologylab.serialization.annotations.bibtex_tag;
import ecologylab.serialization.annotations.bibtex_type;
import ecologylab.serialization.annotations.simpl_inherit;
import ecologylab.serialization.annotations.simpl_scalar;
import ecologylab.serialization.annotations.simpl_tag;
@simpl_inherit
@simpl_tag("bibtex_techreport")
@bibtex_type("techreport")
public class BibTeXTechReport extends AbstractBibTeXEntry
{
// required fields
@simpl_scalar
@bibtex_tag("institution")
private String institution;
@simpl_scalar
@bibtex_tag("type")
private String type;
@simpl_scalar
@bibtex_tag("number")
private long number;
@simpl_scalar
@bibtex_tag("address")
private String address;
public String getInstitution()
{
return institution;
}
public void setInstitution(String institution)
{
this.institution = institution;
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public long getNumber()
{
return number;
}
public void setNumber(long number)
{
this.number = number;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
}
| lgpl-3.0 |
bigorc/orchestra | src/main/java/org/orchestra/client/ClientAuthHelper.java | 7259 | package org.orchestra.client;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.SignatureException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.orchestra.auth.Constants;
import org.orchestra.rest.ServerAuthHelper;
import org.orchestra.util.CipherUtil;
import org.orchestra.util.HttpUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
public class ClientAuthHelper {
private static Map<String, String> cache = new HashMap<String, String>();
private String username;
private String password;
private String filename;
private String apikeyPath;
public ClientAuthHelper(String username, String password) {
this.username = username;
this.password = password;
this.apikeyPath = Client.getProperty("apikey.dir");
this.filename = new Md5Hash(username) + ".apikey";
}
public String getApikey() {
String apikey = cache.get(username);
if(apikey != null) return apikey;
apikey = loadApikeyFromFile();
if(apikey != null) return apikey;
apikey = getApikeyFromServer();
return apikey;
}
private String getApikeyFromServer() {
HttpCommandBuilder builder = new HttpCommandBuilder(username, password);
HttpCommand command = builder.setScheme("https")
.setNeedAuthHeader(true)
.setHost(Client.getProperty("server"))
.setPort(Integer.valueOf(Client.getProperty("port")))
.setAction("update")
.setTarget("apikey")
.addPathParameter(username)
.addPathParameter(Client.getName())
.build();
HttpResponse response = command.execute();
if(200 != response.getStatusLine().getStatusCode()) {
throw new RuntimeException("Unable to get apikey from server.");
}
String apikey = saveApikeyToFile(response);
return apikey;
}
public void removeApikeyFile() {
File file = new File(apikeyPath + "/" + filename);
if(file.exists()) file.delete();
}
public String saveApikeyToFile(HttpResponse response) {
Reader in = null;
try {
in = new InputStreamReader(response.getEntity().getContent());
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
JSONObject json = (JSONObject) JSONValue.parse(in);
String apikey = null;
if(json != null) {
apikey = (String) json.get("apikey");
String secret = (String) json.get("secret");
cache.put(username, apikey);
cache.put(apikey, secret);
String jsonString = json.toJSONString();
System.out.println(jsonString);
OutputStream out = null;
try {
String apikey_filename = apikeyPath + "/" + filename;
File file = new File(apikey_filename);
if(file.exists()) {
file.delete();
}
out = new FileOutputStream(apikey_filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
CipherUtil.encrypt(jsonString , out , password);
}
return apikey;
}
private String loadApikeyFromFile() {
File file = new File(apikeyPath + "/" + filename);
InputStream in = null;
if(!file.exists()) return null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String jsonString = CipherUtil.decrypt(in, password);
JSONObject json = (JSONObject) JSONValue.parse(jsonString);
if(json == null) return null;
String apikey = (String) json.get("apikey");
String secret = (String) json.get("secret");
if(apikey == null || secret == null) return null;
cache.put(username, apikey);
cache.put(apikey, secret);
return apikey;
}
public String sign(HttpCommandBuilder request) throws SignatureException, UnsupportedEncodingException {
String secret = cache.get(getApikey());
String canonicalRequestHashHex = CipherUtil.toHex(CipherUtil.hash(getCanonicalRequest(request)));
String timestamp = (String) request.getParameter("timestamp");
String nonce = (String) request.getParameter("nonce");
String stringToSign =
Constants.SIGNATURE_ALGORITHM + Constants.NEW_LINE +
timestamp + Constants.NEW_LINE +
canonicalRequestHashHex;
DateTimeFormatter formatter = DateTimeFormat.forPattern(Constants.TIMESTAMP_FORMAT);
DateTime date = formatter.parseDateTime(timestamp);
String dateStamp = date .toString(Constants.DATE_FORMAT);
byte[] kDate = CipherUtil.sign(dateStamp, secret);
byte[] kSigning = CipherUtil.sign(nonce , kDate);
byte[] signature = CipherUtil.sign(stringToSign, kSigning);
String signatureHex = CipherUtil.toHex(signature);
return signatureHex;
}
public static String getCanonicalRequest(HttpCommandBuilder request) throws UnsupportedEncodingException, SignatureException {
String method = request.getMethod();
String canonicalURI = HttpUtil.canonicalURI(request.getPath());
String canonicalQueryString = canonicalizeQueryString(request);
String canonicalHeadersString = canonicalizeHeadersString(request);
String signedHeadersString = getSignedHeadersString(request);
String canonicalRequest =
method + Constants.NEW_LINE +
canonicalURI + Constants.NEW_LINE +
canonicalQueryString + Constants.NEW_LINE +
canonicalHeadersString + Constants.NEW_LINE +
signedHeadersString;
return canonicalRequest;
}
private static String canonicalizeHeadersString(HttpCommandBuilder request) {
Map<String, String> headers = request.getAllHeaders();
StringBuilder buffer = new StringBuilder();
for( Entry<String, String> header : headers.entrySet()) {
if(header.getKey().equalsIgnoreCase(Constants.SIGNED_HEADERS)) continue;
buffer.append(header.getKey().toLowerCase()).append(":");
String values = header.getValue();
buffer.append(values.trim());
buffer.append(Constants.NEW_LINE);
}
return buffer.toString();
}
private static String canonicalizeQueryString(HttpCommandBuilder request) {
String queryString = request.getQueryString();
return HttpUtil.canonicalizeQueryString(queryString);
}
public static String getSignedHeadersString(HttpCommandBuilder request) {
Map<String, String> headers = request.getAllHeaders();
StringBuilder buffer = new StringBuilder();
for(Entry<String, String> header : headers.entrySet()) {
if(header.getKey().equalsIgnoreCase(Constants.SIGNED_HEADERS)) continue;
if (buffer.length() > 0) buffer.append(";");
buffer.append(header.getKey().toLowerCase());
}
return buffer.toString();
}
private static class HeaderComparator implements Comparator<org.apache.http.Header> {
@Override
public int compare(org.apache.http.Header o1,
org.apache.http.Header o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
}
}
| lgpl-3.0 |
lewjeen/framework | unitecore-parent/unitecore/unitecore-tools/src/main/java/com/mocha/util/queue/ConcurrentLinkedQueueExtendsHandler.java | 11926 | package com.mocha.util.queue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* <strong>Title : ConcurrentLinkedQueueExtendsHandler </strong>. <br>
* <strong>Description : 队列管理.</strong> <br>
* <strong>Create on : 2014年8月14日 下午2:31:02 </strong>. <br>
* <p>
* <strong>Copyright (C) Mocha Software Co.,Ltd.</strong> <br>
* </p>
*
* @author 刘军 liujun1@mochasoft.com.cn <br>
* @version <strong>Mocha JavaOA v7.0.0</strong> <br>
* <br>
* <strong>修改历史: .</strong> <br>
* 修改人 修改日期 修改描述<br>
* -------------------------------------------<br>
* <br>
* <br>
*/
public class ConcurrentLinkedQueueExtendsHandler<E> implements QueueHandler<E> {
/**
* 单例对象实例
*/
private static ConcurrentLinkedQueueExtendsHandler instance = null;
// public static ConcurrentLinkedQueueExtendsHandler getInstance() {
// if (instance == null) {
// instance = new ConcurrentLinkedQueueExtendsHandler(); //
// }
// return instance;
// }
private static class ConcurrentLinkedQueueExtendsSingletonHolder {
/**
* 单例对象实例
*/
static final ConcurrentLinkedQueueExtendsHandler INSTANCE = new ConcurrentLinkedQueueExtendsHandler();
}
public static ConcurrentLinkedQueueExtendsHandler getInstance() {
return ConcurrentLinkedQueueExtendsSingletonHolder.INSTANCE;
}
/**
* private的构造函数用于避免外界直接使用new来实例化对象
*/
private ConcurrentLinkedQueueExtendsHandler() {
}
// 队列容器
List<ConcurrentLinkedQueueExtends<E>> queueList = new LinkedList<ConcurrentLinkedQueueExtends<E>>();
// 队列名字容器
List<String> queueNames = new ArrayList<String>();
// =========================对队列的操作
/**
* 根据名称参数动态创建不包含任何元素的空队列
*
* @param name
* 队列的名字
* @return
* @throws Exception
*/
@Override
public ConcurrentLinkedQueueExtends<E> createQueueByName(String name)
throws Exception {
if (null == name || "".equals(name)) {
throw new Exception("队列名称不能为空。");
}
if (queueNames.contains(name)) {
throw new Exception("此名称已被使用,请另起其他名字。");
}
ConcurrentLinkedQueueExtends<E> queue = new ConcurrentLinkedQueueExtends<E>(
name);
// 将队列加到容器中
queueList.add(queue);
// 将本队列名加入容器中
queueNames.add(name);
return queue;
}
/**
* 根据名称参数动态创建不包含任何元素的空队列
*
* @param name
* 队列的名字
* @return
* @throws Exception
*/
@Override
public void createQueueByNames(String[] names) throws Exception {
for (String name : names) {
if (null == name || "".equals(name)) {
throw new Exception("队列名称不能为空。");
}
if (queueNames.contains(name)) {
throw new Exception("此名称已被使用,请另起其他名字。");
}
ConcurrentLinkedQueueExtends<E> queue = new ConcurrentLinkedQueueExtends<E>(
name);
// 将队列加到容器中
queueList.add(queue);
// 将本队列名加入容器中
queueNames.add(name);
}
}
/**
* 根据名称参数动态创建不包含任何元素的空队列, 并设置队列的大小。
*
* @param name
* 队列的名字
* @param length
* 队列元素最大个数
* @return 新的队列对象
* @throws Exception
*/
@Override
public ConcurrentLinkedQueueExtends<E> createQueueByName(String name,
int maxSize) throws Exception {
if (null == name || "".equals(name)) {
throw new Exception("队列名称不能为空。");
}
if (queueNames.contains(name)) {
throw new Exception("此名称已被使用,请另起其他名字。");
}
if (maxSize <= 0) {
throw new Exception("队列大小必须大于零");
}
ConcurrentLinkedQueueExtends<E> queue = new ConcurrentLinkedQueueExtends<E>(
name, maxSize);
// 将队列加到容器中
queueList.add(queue);
// 将本队列名加入容器中
queueNames.add(name);
return queue;
}
public boolean checkqueueName(String name) {
boolean flag = false;
if (queueNames.contains(name)) {
flag = true;
}
return flag;
}
/**
* 根据名称参数动态获得队列。
*
* @param name
* 队列的名字
* @return
* @throws Exception
*/
@Override
public ConcurrentLinkedQueueExtends<E> getQueueByName(String name)
throws Exception {
if (queueNames.contains(name)) {
return queueList.get(queueNames.indexOf(name));
} else
throw new Exception("不存在名称为 " + name + "的队列");
}
/**
* 根据名称参数动态删除队列
*
* @param name
* 队列的名字
*/
@Override
public void removeQueueByName(String name) {
if (queueNames.contains(name)) {
queueList.remove(queueNames.indexOf(name));
queueNames.remove(name);
}
}
// =========================对队列中的元素的操作
// 1.添加
/**
* 根据队列名向队列中添加元素,若添加元素失败,则抛出异常
*
* @param queueName
* 队列名字
* @param e
* 向队列中添加的元素
* @return
* @throws Exception
*/
@Override
public boolean add(String queueName, E e) throws Exception {
ConcurrentLinkedQueueExtends<E> queue = this.getQueueByName(queueName);
if (queue.size() >= queue.getMaxSize()) {
throw new Exception("队列已满,不允许继续添加元素。");
}
return queue.add(e);
}
/**
* 根据队列名向队列中添加元素集合,若添加元素集合失败,则抛出异常
*
* @param queueName
* 队列名称
* @param c
* collection containing elements to be added to this queue
* @return <tt>true</tt> if this queue changed as a result of the call
* @throws Exception
*/
@Override
public boolean addAll(String queueName, Collection<? extends E> c)
throws Exception {
ConcurrentLinkedQueueExtends<E> queue = this.getQueueByName(queueName);
if (queue.size() >= queue.getMaxSize()) {
throw new Exception("队列已满,不允许继续添加元素。");
} else if (queue.size() + c.size() > queue.getMaxSize()) {
throw new Exception("新增的集合中的元素太多,以致超出队列容量上限");
}
return queue.addAll(c);
}
/**
* 根据队列名向队列中添加元素,若添加元素失败,则返回false
*
* @param queueName
* 队列名
* @param e
* 向队列中添加的元素
* @return
* @throws Exception
*/
@Override
public boolean offer(String queueName, E e) throws Exception {
ConcurrentLinkedQueueExtends<E> queue = this.getQueueByName(queueName);
if (queue.size() >= queue.getMaxSize()) {
throw new Exception("队列已满,不允许继续添加元素。");
}
return queue.offer(e);
}
// 2.得到但不删除
/**
* 获取但不移除此队列的头;如果此队列为空,则返回 null。
*
* @param queueName
* 队列名字
* @return 队列的头,如果此队列为空,则返回 null
* @throws Exception
*/
@Override
public E peek(String queueName) throws Exception {
return this.getQueueByName(queueName).peek();
}
/**
* 获取但不移除此队列的头;如果此队列为空,则抛出异常。
*
* @param queueName
* 队列名字
* @return 队列的头,如果此队列为空,则抛出异常
* @throws Exception
*/
@Override
public E element(String queueName) throws Exception {
return this.getQueueByName(queueName).element();
}
// 3.得到并删除
/**
* 获取并移除此队列的头,如果此队列为空,则返回 null。
*
* @param queueName
* 队列名字
* @return 此队列的头;如果此队列为空,则返回 null
* @throws Exception
*/
@Override
public E poll(String queueName) throws Exception {
return this.getQueueByName(queueName).poll();
}
/**
* 获取并移除此队列的头,如果此队列为空,则抛出异常。
*
* @param queueName
* 队列名字
* @return
* @throws Exception
*/
@Override
public E remove(String queueName) throws Exception {
return this.getQueueByName(queueName).remove();
}
/**
* 根据队列名删除某一元素
*
* @param queueName
* 队列名字
* @param o
* 删除的元素
* @return
* @throws Exception
*/
@Override
public boolean remove(String queueName, Object o) throws Exception {
return this.getQueueByName(queueName).remove(o);
}
/**
*
* @param queueName
* 队列名字
* @param c
* 删除的元素
* @return
* @throws Exception
*/
@Override
public boolean removeAll(String queueName, Collection<?> c)
throws Exception {
return this.getQueueByName(queueName).removeAll(c);
}
/**
* 清空队列
*
* @param queueName
* 队列名字
* @throws Exception
*/
@Override
public void clear(String queueName) throws Exception {
this.getQueueByName(queueName).clear();
}
/**
* 判断 名称与参数一致的 队列 中是否有元素
*
* @param queueName
* 队列名
* @return
* @throws Exception
*/
@Override
public boolean isEmpty(String queueName) throws Exception {
return this.getQueueByName(queueName).isEmpty();
}
/**
* 根据 队列名 判断队列中已有元素的歌声
*
* @param queueName
* 队列名
* @return
* @throws Exception
*/
@Override
public int size(String queueName) throws Exception {
return this.getQueueByName(queueName).size();
}
/**
* 根据队列名判断队列中是否包含某一元素
*
* @param queueName
* 队列名
* @param o
* 元素
* @return
* @throws Exception
*/
@Override
public boolean contains(String queueName, Object o) throws Exception {
return this.getQueueByName(queueName).contains(o);
}
/**
* 根据队列名判断队列中是否包含某些元素
*
* @param queueName
* 队列名
* @param c
* 元素集合
* @return
* @throws Exception
*/
@Override
public boolean containsAll(String queueName, Collection<?> c)
throws Exception {
return this.getQueueByName(queueName).containsAll(c);
}
/**
* 根据队列名将某一队列中的元素转换为Object数组形式
*
* @param queueName
* @return
* @throws Exception
*/
@Override
public Object[] toArray(String queueName) throws Exception {
return this.getQueueByName(queueName).toArray();
}
/**
* 根据队列名将某一队列中的元素转换为某一特定类型的数组形式
*
* @param queueName
* 队列名
* @param a
* @return
* @throws Exception
*/
@Override
public <T> T[] toArray(String queueName, T[] a) throws Exception {
return this.getQueueByName(queueName).toArray(a);
}
/**
* 根据队列名遍历队列中所有元素
*
* @param queueName
* 队列名
* @return
* @throws Exception
*/
@Override
public Iterator<E> iterator(String queueName) throws Exception {
return this.getQueueByName(queueName).iterator();
}
@Override
public Iterator<E> iterator(String[] queueName) throws Exception {
// TODO Auto-generated method stub
return null;
}
}
| unlicense |
cc14514/hq6 | hq-util/src/main/java/org/hyperic/util/xmlparser/XmlParser.java | 18165 | /*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU 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 General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.util.xmlparser;
import org.hyperic.util.StringUtil;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.xml.sax.EntityResolver;
/**
* The main entry point && bulk of XmlParser. The parsing routine
* takes an entry-point tag, which provides information about subtags,
* attributes it takes, etc. Tags can implement various interfaces
* to tell the parser to call back when certain conditions are met.
* This class takes the role of both a minimal validator as well as
* a traversal mechanism for building data objects out of XML.
*/
public class XmlParser {
private XmlParser(){}
private static void checkAttributes(Element elem, XmlTagHandler tag,
XmlFilterHandler filter)
throws XmlAttrException
{
boolean handlesAttrs = tag instanceof XmlAttrHandler;
XmlAttr[] attrs;
if(handlesAttrs)
attrs = ((XmlAttrHandler)tag).getAttributes();
else
attrs = new XmlAttr[0];
// Ensure out all the required && optional attributes
for(int i=0; i<attrs.length; i++){
Attribute a = null;
boolean found = false;
for(Iterator j=elem.getAttributes().iterator(); j.hasNext(); ){
a = (Attribute)j.next();
if(a.getName().equalsIgnoreCase(attrs[i].getName())){
found = true;
break;
}
}
if(!found && attrs[i].getType() == XmlAttr.REQUIRED){
throw new XmlRequiredAttrException(elem,
attrs[i].getName());
}
if(found && handlesAttrs){
String val;
val = filter.filterAttrValue(tag, a.getName(), a.getValue());
((XmlAttrHandler)tag).handleAttribute(i, val);
}
}
// Second loop to handle unknown attributes
for(Iterator i=elem.getAttributes().iterator(); i.hasNext(); ){
Attribute a = (Attribute)i.next();
boolean found = false;
for(int j=0; j<attrs.length; j++){
if(a.getName().equalsIgnoreCase(attrs[j].getName())){
found = true;
break;
}
}
if(found)
continue;
if(tag instanceof XmlUnAttrHandler){
XmlUnAttrHandler handler;
String val;
val = filter.filterAttrValue(tag, a.getName(), a.getValue());
handler = (XmlUnAttrHandler)tag;
handler.handleUnknownAttribute(a.getName(), val);
} else {
throw new XmlUnknownAttrException(elem, a.getName());
}
}
if(tag instanceof XmlEndAttrHandler){
((XmlEndAttrHandler)tag).endAttributes();
}
}
private static void checkSubNodes(Element elem, XmlTagHandler tag,
XmlFilterHandler filter)
throws XmlAttrException, XmlTagException
{
XmlTagInfo[] subTags = tag.getSubTags();
Map hash;
hash = new HashMap();
// First, count how many times each sub-tag is referenced
for(Iterator i=elem.getChildren().iterator(); i.hasNext(); ){
Element e = (Element)i.next();
String name;
Integer val;
name = e.getName().toLowerCase();
if((val = (Integer)hash.get(name)) == null){
val = new Integer(0);
}
val = new Integer(val.intValue() + 1);
hash.put(name, val);
}
for(int i=0; i<subTags.length; i++){
String name = subTags[i].getTag().getName().toLowerCase();
Integer iVal = (Integer)hash.get(name);
int threshold = 0, val;
val = iVal == null ? 0 : iVal.intValue();
switch(subTags[i].getType()){
case XmlTagInfo.REQUIRED:
if(val == 0){
throw new XmlMissingTagException(elem, name);
} else if(val != 1){
throw new XmlTooManyTagException(elem, name);
}
break;
case XmlTagInfo.OPTIONAL:
if(val > 1){
throw new XmlTooManyTagException(elem, name);
}
break;
case XmlTagInfo.ONE_OR_MORE:
threshold++;
case XmlTagInfo.ZERO_OR_MORE:
if(val < threshold){
throw new XmlMissingTagException(elem, name);
}
break;
}
hash.remove(name);
}
// Now check for excess sub-tags
if(hash.size() != 0){
Set keys = hash.keySet();
throw new XmlTooManyTagException(elem,
(String)keys.iterator().next());
}
// Recurse to all sub-tags
for(Iterator i=elem.getChildren().iterator(); i.hasNext(); ){
Element child = (Element)i.next();
for(int j=0; j<subTags.length; j++){
XmlTagHandler subTag = subTags[j].getTag();
String subName = subTag.getName();
if(child.getName().equalsIgnoreCase(subName)){
XmlParser.processNode(child, subTag, filter);
break;
}
}
}
}
private static void processNode(Element elem, XmlTagHandler tag,
XmlFilterHandler filter)
throws XmlAttrException, XmlTagException
{
if(tag instanceof XmlTagEntryHandler){
((XmlTagEntryHandler)tag).enter();
}
if(tag instanceof XmlFilterHandler){
filter = (XmlFilterHandler)tag;
}
XmlParser.checkAttributes(elem, tag, filter);
if(tag instanceof XmlTextHandler) {
((XmlTextHandler)tag).handleText(elem.getText());
}
XmlParser.checkSubNodes(elem, tag, filter);
if(tag instanceof XmlTagExitHandler){
((XmlTagExitHandler)tag).exit();
}
}
private static class DummyFilter
implements XmlFilterHandler
{
public String filterAttrValue(XmlTagHandler tag, String attrName,
String attrValue)
{
return attrValue;
}
}
/**
* Parse an input stream, otherwise the same as parsing a file
*/
public static void parse(InputStream is, XmlTagHandler tag)
throws XmlParseException
{
parse(is, tag, null);
}
public static void parse(InputStream is, XmlTagHandler tag,
EntityResolver resolver)
throws XmlParseException
{
SAXBuilder builder;
Document doc;
builder = new SAXBuilder();
if (resolver != null) {
builder.setEntityResolver(resolver);
}
try {
if (resolver != null) {
//WTF? seems relative entity URIs are allowed
//by certain xerces impls. but fully qualified
//file://... URLs trigger a NullPointerException
//in others. setting base here worksaround
doc = builder.build(is, "");
}
else {
doc = builder.build(is);
}
} catch(JDOMException exc){
XmlParseException toThrow = new XmlParseException(exc.getMessage());
toThrow.initCause(exc);
throw toThrow;
} catch (IOException exc) {
XmlParseException toThrow = new XmlParseException(exc.getMessage());
toThrow.initCause(exc);
throw toThrow;
}
generalParse(tag, doc);
}
/**
* Parse a file, which should have a root which is the associated tag.
*
* @param in File to parse
* @param tag Root tag which the parsed file should contain
*/
public static void parse(File in, XmlTagHandler tag)
throws XmlParseException
{
SAXBuilder builder;
Document doc;
builder = new SAXBuilder();
InputStream is = null;
//open the file ourselves. the builder(File)
//method escapes " " -> "%20" and bombs
try {
is = new FileInputStream(in);
doc = builder.build(is);
} catch (IOException exc) {
throw new XmlParseException(exc.getMessage());
} catch (JDOMException exc) {
throw new XmlParseException(exc.getMessage());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {}
}
}
generalParse(tag, doc);
}
/** General parsing used by both parse methods above */
private static void generalParse(XmlTagHandler tag, Document doc)
throws XmlParseException
{
Element root = doc.getRootElement();
if(!root.getName().equalsIgnoreCase(tag.getName())){
throw new XmlParseException("Incorrect root tag. Expected <"+
tag.getName() + "> but got <" +
root.getName() + ">");
}
XmlParser.processNode(root, tag, new DummyFilter());
}
private static void dumpAttrs(XmlAttr[] attrs, String typeName,
int type, PrintStream out, int indent)
{
String printMsg;
boolean printed = false;
int lineBase, lineLen;
if(attrs.length == 0)
return;
lineLen = 0;
printMsg = "- Has " + typeName + " attributes: ";
lineBase = indent + printMsg.length();
// Required attributes
for(int i=0; i<attrs.length; i++){
String toPrint;
if(attrs[i].getType() != type)
continue;
if(!printed){
toPrint = StringUtil.repeatChars(' ', indent) +
"- Has " + typeName + " attributes: ";
out.print(toPrint);
lineLen = toPrint.length();
printed = true;
}
toPrint = attrs[i].getName() + ", ";
lineLen += toPrint.length();
out.print(toPrint);
if(lineLen > 70){
out.println();
out.print(StringUtil.repeatChars(' ', lineBase));
lineLen = lineBase;
}
}
if(printed)
out.println();
}
private static void dumpNode(XmlTagHandler tag, PrintStream out,
int indent)
throws XmlTagException
{
XmlTagInfo[] subTags = tag.getSubTags();
out.println(StringUtil.repeatChars(' ', indent) +
"Tag <" + tag.getName() + ">:");
if(tag instanceof XmlAttrHandler){
XmlAttr[] attrs;
attrs = ((XmlAttrHandler)tag).getAttributes();
if(attrs.length == 0)
out.println(StringUtil.repeatChars(' ', indent) +
"- has no required or optional attributes");
XmlParser.dumpAttrs(attrs, "REQUIRED", XmlAttr.REQUIRED,
out, indent);
XmlParser.dumpAttrs(attrs, "OPTIONAL", XmlAttr.OPTIONAL,
out, indent);
} else {
out.println(StringUtil.repeatChars(' ', indent) +
"- has no required or optional attributes");
}
if(tag instanceof XmlUnAttrHandler)
out.println(StringUtil.repeatChars(' ', indent) +
"- handles arbitrary attributes");
subTags = tag.getSubTags();
if(subTags.length == 0){
out.println(StringUtil.repeatChars(' ', indent) +
"- has no subtags");
} else {
for(int i=0; i<subTags.length; i++){
String name = subTags[i].getTag().getName();
int type = subTags[i].getType();
out.print(StringUtil.repeatChars(' ', indent) +
"- has subtag <" + name + ">, which ");
switch(type){
case XmlTagInfo.REQUIRED:
out.println("is REQUIRED");
break;
case XmlTagInfo.OPTIONAL:
out.println("is OPTIONAL");
break;
case XmlTagInfo.ONE_OR_MORE:
out.println("is REQUIRED at least ONCE");
break;
case XmlTagInfo.ZERO_OR_MORE:
out.println("can be specified any # of times");
break;
}
XmlParser.dumpNode(subTags[i].getTag(), out, indent + 4);
}
}
}
public static void dump(XmlTagHandler root, PrintStream out){
try {
XmlParser.dumpNode(root, out, 0);
} catch(XmlTagException exc){
out.println("Error traversing tags: " + exc.getMessage());
}
}
private static String bold(String text) {
return "<emphasis role=\"bold\">" + text + "</emphasis>";
}
private static String tag(String name) {
return bold("<" + name + ">");
}
private static String listitem(String name, String desc) {
String item =
"<listitem><para>" + name + "</para>";
if (desc != null) {
item += "<para>" + desc + "</para>";
}
return item;
}
private static void dumpAttrsWiki(XmlAttr[] attrs, String typeName,
int type, PrintStream out, int indent)
{
boolean printed = false;
if (attrs.length == 0) {
return;
}
// Required attributes
for (int i=0; i<attrs.length; i++) {
if (attrs[i].getType() != type) {
continue;
}
if (!printed) {
out.println(StringUtil.repeatChars('*', indent) +
" " + typeName + " attributes: ");
printed = true;
}
out.println(StringUtil.repeatChars('*', indent) +
" " + attrs[i].getName());
}
}
private static void dumpNodeWiki(XmlTagHandler tag, PrintStream out,
int indent)
throws XmlTagException
{
XmlTagInfo[] subTags = tag.getSubTags();
if (indent == 1) {
out.println(StringUtil.repeatChars('*', indent) +
" Tag *<" + tag.getName() + ">*: ");
}
if (tag instanceof XmlAttrHandler) {
XmlAttr[] attrs;
attrs = ((XmlAttrHandler)tag).getAttributes();
dumpAttrsWiki(attrs, "*REQUIRED*", XmlAttr.REQUIRED,
out, indent+1);
dumpAttrsWiki(attrs, "*OPTIONAL*", XmlAttr.OPTIONAL,
out, indent+1);
}
subTags = tag.getSubTags();
if (subTags.length != 0) {
for (int i=0; i<subTags.length; i++) {
String name = subTags[i].getTag().getName();
int type = subTags[i].getType();
String desc = "";
switch(type){
case XmlTagInfo.REQUIRED:
desc = "REQUIRED";
break;
case XmlTagInfo.OPTIONAL:
desc = "OPTIONAL";
break;
case XmlTagInfo.ONE_OR_MORE:
desc = "REQUIRED at least ONCE";
break;
case XmlTagInfo.ZERO_OR_MORE:
desc = "can be specified any # of times";
break;
}
out.println(StringUtil.repeatChars('*', indent+1) +
" Sub Tag *<" + name + ">* " + desc);
dumpNodeWiki(subTags[i].getTag(), out, indent+1);
}
}
}
public static void dumpWiki(XmlTagHandler root, PrintStream out){
try {
dumpNodeWiki(root, out, 1);
} catch(XmlTagException exc){
out.println("Error traversing tags: " + exc.getMessage());
}
}
}
| unlicense |
clilystudio/NetBook | allsrc/android/support/v7/app/a(1).java | 1431 | package android.support.v7.app;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.support.v7.b.b;
import android.view.KeyEvent;
import android.view.View;
public abstract class a
{
public android.support.v7.b.a a(b paramb)
{
return null;
}
public abstract View a();
public abstract void a(int paramInt);
public void a(Configuration paramConfiguration)
{
}
public abstract void a(Drawable paramDrawable);
public abstract void a(View paramView);
public abstract void a(CharSequence paramCharSequence);
public abstract void a(boolean paramBoolean);
public boolean a(int paramInt, KeyEvent paramKeyEvent)
{
return false;
}
public abstract int b();
public void b(CharSequence paramCharSequence)
{
}
public abstract void b(boolean paramBoolean);
public Context c()
{
return null;
}
public abstract void c(boolean paramBoolean);
public abstract void d(boolean paramBoolean);
public boolean d()
{
return false;
}
public void e(boolean paramBoolean)
{
}
public boolean e()
{
return false;
}
public void f(boolean paramBoolean)
{
}
public void g(boolean paramBoolean)
{
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: android.support.v7.app.a
* JD-Core Version: 0.6.0
*/ | unlicense |
clilystudio/NetBook | allsrc/com/ximalaya/ting/android/opensdk/datatrasfer/CommonRequest$29$1.java | 465 | package com.ximalaya.ting.android.opensdk.datatrasfer;
import com.google.gson.reflect.TypeToken;
import com.ximalaya.ting.android.opensdk.model.album.HotAggregation;
import java.util.List;
class CommonRequest$29$1 extends TypeToken<List<HotAggregation>>
{
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest.29.1
* JD-Core Version: 0.6.0
*/ | unlicense |
cc14514/hq6 | hq-server/src/main/java/org/hyperic/hq/livedata/server/session/LiveDataCacheKey.java | 2028 | /**
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2009-2010], VMware, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU 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 General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
*/
package org.hyperic.hq.livedata.server.session;
import org.hyperic.hq.livedata.shared.LiveDataCommand;
class LiveDataCacheKey {
private LiveDataCommand[] _commands;
public LiveDataCacheKey(LiveDataCommand[] cmds) {
_commands = cmds;
}
public LiveDataCommand[] getCommands() {
return _commands;
}
public boolean equals(Object o) {
if (!(o instanceof LiveDataCacheKey)) {
return false;
}
LiveDataCommand[] cmds = ((LiveDataCacheKey)o).getCommands();
for (int i = 0; i < cmds.length; i++) {
if (!(cmds[i].equals(_commands[i]))) {
return false;
}
}
return true;
}
public int hashCode() {
int result = 17;
for (int i = 0; i < _commands.length; i++) {
result = result*37 + _commands[i].hashCode();
}
return result;
}
}
| unlicense |
patinyanudklin/git_testing | cpe-2015-projects/DragonCommon/javasrc/com/grs/dragon/ui/ImgHeaderCallback.java | 9258 | /*
* ImgHeaderCallback.java
*
* Copyright 2001-2007 Goldin-Rudahl Associates
*
* Created by Sally Goldin, 5/16/2001
*
* $Id: ImgHeaderCallback.java,v 1.20 2007/01/05 07:41:57 rudahl Exp $
* $Log: ImgHeaderCallback.java,v $
* Revision 1.20 2007/01/05 07:41:57 rudahl
* added Whatis info
*
* Revision 1.19 2006/12/17 11:35:56 goldin
* fix formatting of reals
*
* Revision 1.18 2006/12/10 12:09:58 goldin
* Adding new menus and panels for revised geometry/geography
*
* Revision 1.17 2006/02/11 07:15:31 goldin
* Enable classnames tab even if no classnames yet
*
* Revision 1.16 2005/08/13 08:41:23 goldin
* Migrate fix in 5.6 regarding display type setting based on header
*
* Revision 1.15 2004/12/06 03:41:56 goldin
* Don't change display type for MEA if =M
*
* Revision 1.14 2002/09/11 23:34:20 goldin
* Call new statusmanager method to translate =R etc into a filename
*
* Revision 1.13 2002/07/25 23:06:18 goldin
* Make Source show up in HEA
*
* Revision 1.12 2002/05/29 17:52:24 goldin
* Add processing for calibration fields
*
* Revision 1.11 2002/03/06 17:48:12 goldin
* Enhance and extend use of ImgHeaderCallback to control display type
*
* Revision 1.10 2001/11/30 18:01:21 goldin
* Moved most of the UI basic components to the com.grs.gui package
*
* Revision 1.9 2001/11/16 16:41:07 goldin
* Move some files to common .gui package and adjust imports in dragon.ui pkg
*
* Revision 1.8 2001/11/09 17:52:05 goldin
* Set display type to color for =C or classified file
*
* Revision 1.7 2001/11/05 13:59:15 goldin
* Put UI code in a package
*
* Revision 1.6 2001/10/17 10:29:37 goldin
* Modify to use ApplicationManager to get error display, etc.
*
* Revision 1.5 2001/10/12 11:41:05 goldin
* New callbacks for HEA panel
*
* Revision 1.4 2001/07/31 17:40:38 goldin
* display correct range as part of message for out-of-range errors
*
* Revision 1.3 2001/07/25 11:53:05 goldin
* support nlines/npix in SUB
*
* Revision 1.2 2001/05/29 10:35:28 goldin
* Add tab disabling capability
*
* Revision 1.1 2001/05/16 15:43:16 goldin
* Implemen header-based callback
*
*/
package com.grs.dragon.ui;
import com.grs.gui.*;
import java.util.*;
import javax.swing.*;
import java.text.NumberFormat;
/**
* This class implements the Callback interface. It is used to populate
* fields depending on a panel, based on data in the header of the
* image file specified in the field that invokes the callback.
* @author goldin*/
public class ImgHeaderCallback extends HeaderCallback
{
/** Primary method of a callback class.
* Process sigFile if necessary, and set values in the
* appropriate combo box.
* @param field Field whose value will determine the
* effects of the callback.
*/
public void executeCallback(DragonField field)
{
DImageHeader thisHeader = null;
DragonField dispTypeField = null;
DragonPanel parent = field.getTopLevelPanel();
if (parent == null)
{
return;
}
DragonUI mainApp = DragonUI.currentApplication;
String value = field.getFieldValue();
if ((value == null) || (value.length() == 0))
return;
// determine if there is a current header and if so,
// if that is what the user requested
DImageHeader header = mainApp.getMemoryHeader();
if ((header != null) && (header.isInitialized()) &&
(value.equals("=M")))
{
thisHeader = header;
}
else if (value.equals("=C"))
{
dispTypeField = parent.getField("^DSP");
if (dispTypeField != null)
dispTypeField.setFieldValue("C");
return;
}
else
{
if (value.startsWith("="))
value =
DragonUI.currentApplication.getStatusManager().getMemoryFileEquivalent(value);
thisHeader = new DImageHeader(value);
if (!thisHeader.isInitialized())
{
UiErrorDisplay errDisp = (UiErrorDisplay)
ApplicationManager.getErrorDisplay();
errDisp.sendError(thisHeader.getErrorMessage());
return;
}
}
String parentID = parent.getName();
if (parentID.compareTo("rHEA")== 0)
{
processHeaFields(parent, thisHeader);
}
else if ((parentID.compareTo("rMEA")== 0) ||
(parentID.compareTo("rBUF")== 0))
{
processMeaFields(value, parent, thisHeader);
}
else if (parentID.compareTo("rSUB")== 0)
{
processSubFields(parent, thisHeader);
}
else
{
processDisplayType(parent,thisHeader);
}
}
/**
* Set fields in MEA panel based on header values.
*/
protected void processMeaFields(String value,
DragonPanel parent,
DImageHeader header)
{
NumberFormat nformat = NumberFormat.getInstance();
nformat.setMaximumFractionDigits(2);
DragonField units = parent.getField("^U");
if (units != null)
units.setFieldValue(header.getUnitname());
DragonField xcell = parent.getField("^XF");
if (xcell != null)
xcell.setFieldValue(nformat.format(header.getXcell_size()));
DragonField ycell = parent.getField("^YF");
if (ycell != null)
ycell.setFieldValue(nformat.format(header.getYcell_size()));
// we have already dealt with the display type for memory files
if (!value.startsWith("="))
processDisplayType(parent,header);
}
/** Set fields in HEA panel based on header values. */
protected void processHeaFields(DragonPanel parent,
DImageHeader header)
{
DragonField fld = parent.getField("^FXI");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getImg_x()));
fld = parent.getField("^FYI");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getImg_y()));
fld = parent.getField("^RFX");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getRef_x()));
fld = parent.getField("^RFY");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getRef_y()));
fld = parent.getField("^MU");
if (fld != null)
fld.setFieldValue(header.getUnitname());
fld = parent.getField("^CLX");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getXcell_size()));
fld = parent.getField("^CLY");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getYcell_size()));
fld = parent.getField("^ECUTIL");
if (fld != null)
fld.setFieldValue(header.getComment());
fld = parent.getField("^ESID");
if (fld != null)
fld.setFieldValue(header.getScene());
fld = parent.getField("^ESS");
if (fld != null)
fld.setFieldValue(header.getSubscene());
fld = parent.getField("^ECF");
if (fld != null)
fld.setFieldValue(header.getClf());
fld = parent.getField("^ESRC");
if (fld != null)
fld.setFieldValue(header.getSource());
fld = parent.getField("^EB");
if (fld != null)
fld.setFieldValue(header.getBand());
fld = parent.getField("^ET");
if (fld != null)
fld.setFieldValue(header.getFileType());
fld = parent.getField("^CALUNIT");
if (fld != null)
fld.setFieldValue(header.getZUnit());
fld = parent.getField("^CALMULT");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getZScale()));
fld = parent.getField("^CALOFF");
if (fld != null)
fld.setFieldValue(String.valueOf(header.getZOffset()));
if (header.getFileType().compareTo("I") == 0)
{
parent.enableTab(1,false);
clearClassNames(parent,header);
}
else
{
parent.enableTab(1,true);
processClassNames(parent,header);
}
}
/**
* Set fields in SUB panel based on header values.
*/
protected void processSubFields(DragonPanel parent,
DImageHeader header)
{
boolean bEnable = false;
DragonField nlines = parent.getField("^NLS");
if (nlines != null)
nlines.setFieldValue(String.valueOf(header.getNLines()));
DragonField npix = parent.getField("^NPS");
if (npix != null)
npix.setFieldValue(String.valueOf(header.getNPix()));
if (header.getBitsPerPix() == 8)
{
bEnable = false;
}
else
{
bEnable = true;
}
DragonField fld = parent.getField("^SM");
if (fld != null)
fld.setEnabled(bEnable);
processDisplayType(parent,header);
}
/**
* If the panel has a "display" type option, set it
* to 'C' if the file is classified.
*/
protected void processDisplayType(DragonPanel parent,
DImageHeader header)
{
DragonField dispType = parent.getField("^DSP");
if (dispType == null)
return;
if (header.getFileType().startsWith("I"))
dispType.setFieldValue("G");
else if (header.getFileType().startsWith("C"))
dispType.setFieldValue("C");
else if (header.getFileType().startsWith("L"))
dispType.setFieldValue("C");
}
protected static String cvsInfo = null;
protected static void setCvsInfo()
{
cvsInfo = "\n@(#) $Id: ImgHeaderCallback.java,v 1.20 2007/01/05 07:41:57 rudahl Exp $ \n";
}
}
| unlicense |
facundofarias/iBee | Source/WeatherService/src/model/ManejadorUbicar.java | 1255 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import controller.GestorLocalidad;
import java.util.ArrayList;
import org.w3c.dom.Document;
/**
*
* @author soriagal
*/
public class ManejadorUbicar {
private WebUbicar webUbicar;
private GestorLocalidad gestorLocalidad = new GestorLocalidad();
private ArrayList idLocalidades;
private ArrayList documents; //object: document con el xml
private ArrayList localidades = new ArrayList(); //object: objeto localidad
public void pedirUbicacion () {
idLocalidades = gestorLocalidad.getLocalidades();
webUbicar = new WebUbicar();
documents = webUbicar.getDocuments(idLocalidades);
for (int i=0; i<documents.size(); i++) {
Localidad localidad;
LectorUbicacionXml lector = new LectorUbicacionXml((Document) documents.get(i));
localidad = lector.getLocalidad();
localidades.add(localidad);
}
}
public void guardarUbicacion () {
for (int i=0; i<localidades.size(); i++) {
Localidad localidad = (Localidad) localidades.get(i);
gestorLocalidad.guardarUbicacion(localidad);
}
}
}
| unlicense |
vijayvelpula/MeetAt | src/main/java/com/stech/meetat/service/SchedulerService.java | 74 | package com.stech.meetat.service;
public interface SchedulerService {
}
| unlicense |
will-gilbert/SmartGWT-Mobile | mobile/src/main/java/com/smartgwt/mobile/client/widgets/toolbar/ToolStripButton.java | 2366 | /*
* SmartGWT Mobile
* Copyright 2008 and beyond, Isomorphic Software, Inc.
*
* SmartGWT Mobile 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. SmartGWT Mobile is also
* available under typical commercial license terms - see
* http://smartclient.com/license
*
* 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.
*/
package com.smartgwt.mobile.client.widgets.toolbar;
import com.smartgwt.mobile.client.widgets.BaseButton;
/**
* This class represents a button that is placed on the {@link ToolStrip}.
* It can either be a back / forward button, or an action button.
*
* @see com.smartgwt.mobile.client.widgets.toolbar.ToolStrip#addButton(ToolStripButton)
*/
public class ToolStripButton extends BaseButton {
private ButtonType buttonType = ButtonType.BORDERED;
private boolean inheritTint;
public ToolStripButton() {
internalSetButtonType(buttonType);
}
public ToolStripButton(String title) {
this();
setTitle(title);
}
public ToolStripButton(String title, ButtonType buttonType) {
this(title);
internalSetButtonType(buttonType);
}
public final ButtonType getButtonType() {
return buttonType;
}
private void internalSetButtonType(ButtonType buttonType) {
if (this.buttonType != null) {
getElement().removeClassName(this.buttonType._getClassNames());
}
this.buttonType = buttonType;
if (buttonType != null) {
getElement().addClassName(buttonType._getClassNames());
}
}
public void setButtonType(ButtonType buttonType) {
internalSetButtonType(buttonType);
}
public final boolean isInheritTint() {
return inheritTint;
}
public void setInheritTint(boolean inheritTint) {
this.inheritTint = inheritTint;
if(inheritTint) {
getElement().addClassName(_CSS.customTintedButtonClass());
} else {
getElement().removeClassName(_CSS.customTintedButtonClass());
}
}
}
| unlicense |
mvanbesien/projecteuler | fr.mvanbesien.projecteuler/src/main/java/fr/mvanbesien/projecteuler/from001to020/Problem015.java | 846 | package fr.mvanbesien.projecteuler.from001to020;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
public class Problem015 implements Callable<Long> {
public static void main(String[] args) throws Exception {
long nanotime = System.nanoTime();
System.out.println("Answer is " + new Problem015().call());
System.out.println(String.format("Executed in %d µs", (System.nanoTime() - nanotime) / 1000));
}
@Override
public Long call() throws Exception {
List<Long> list = new ArrayList<>();
list.add(1L);
list.add(1L);
for (int i = 1; i < 40; i++) {
List<Long> list2 = new ArrayList<>();
list2.add(1L);
for (int j = 0; j < list.size() - 1; j++) {
list2.add(list.get(j) + list.get(j + 1));
}
list2.add(1L);
list = list2;
}
return list.get(list.size() / 2);
}
}
| unlicense |
BTS-SIO2-2013/ZombieKiller | src/consolefps/views/IAffichage.java | 280 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package consolefps.views;
import consolefps.models.elements.Elements;
/**
*
* @author krilivye
*/
public interface IAffichage {
public String afficher(Elements element);
}
| unlicense |
robbinmathew/centbunk | java/BunkAccountingApplication/BunkAccountingSwingApp/src/main/java/bronz/accounting/bunk/ui/model/CalendarTableModel.java | 2231 | package bronz.accounting.bunk.ui.model;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.table.AbstractTableModel;
import bronz.accounting.bunk.ui.panel.CalendarPanel;
import bronz.utilities.custom.CustomCalendar;
import bronz.utilities.general.DateUtil;
public class CalendarTableModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
private final CalendarPanel panel;
private final Calendar startDate;
private Object[][] data;
private String[] columnNames = { "", "", "", "", "", "", "" };
public CalendarTableModel( final CalendarPanel panel ,
final Calendar startDate )
{
this.panel = panel;
this.startDate = startDate;
this.data = new Object[ 7 ][ 7 ];
loadDates();
}
private void loadDates()
{
this.data[ 0 ][ 0 ] = "SUN";
this.data[ 0 ][ 1 ] = "MON";
this.data[ 0 ][ 2 ] = "TUE";
this.data[ 0 ][ 3 ] = "WED";
this.data[ 0 ][ 4 ] = "THU";
this.data[ 0 ][ 5 ] = "FRI";
this.data[ 0 ][ 6 ] = "SAT";
int a = DateUtil.getNoOfDayInMonth( (GregorianCalendar) startDate);
startDate.set( Calendar.DATE, 1 );
int day = startDate.get( Calendar.DAY_OF_WEEK );
day--;
int x = 0;
int y = 0;
for ( int i = 0; i < 42; i++)
{
if( i%7 == 0)
{
x++;
y = 0;
}
if( (i >= day) && i < ( a + day ) )
{
this.data[ x ][ y ] = (i - day)+ 1;
}
y++;
}
}
public int getColumnCount()
{
return columnNames.length;
}
public int getRowCount()
{
return data.length;
}
public String getColumnName(int col)
{
return columnNames[ col ];
}
public Object getValueAt(int row, int col)
{
return data[ row ][ col ];
}
public boolean isCellEditable(int row, int col)
{
if ( this.data[ row ][ col ] instanceof Integer )
{
final int selectedDate = (Integer) this.data[ row ][ col ];
final Calendar selectedCalendar = new CustomCalendar();
selectedCalendar.set( Calendar.DATE , selectedDate );
return panel.setSelectedDate( selectedCalendar );
}
else
{
return false;
}
}
public void setValueAt( final Object value, final int row, final int col)
{
}
}
| unlicense |
discord-java/discord.jar | src/main/java/discord/jar/EmbedBuilder.java | 3220 | package discord.jar;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class EmbedBuilder {
private String title;
private String type;
private String description;
private String url;
private Color color;
private Embed.EmbedFooter footer;
private Embed.EmbedImage image;
private Embed.EmbedImage thumbnail;
private Embed.EmbedMedia video;
private Embed.EmbedProvider provider;
private Embed.EmbedAuthor author;
private List<Embed.EmbedField> fields = new ArrayList<>();
public EmbedBuilder withTitle(String title) {
this.title = title;
return this;
}
public EmbedBuilder withType(String type) {
this.type = type;
return this;
}
public EmbedBuilder withDescription(String description) {
this.description = description;
return this;
}
public EmbedBuilder withUrl(String url) {
this.url = url;
return this;
}
public EmbedBuilder withColor(Color color) {
this.color = color;
return this;
}
public EmbedBuilder withFooter(Embed.EmbedFooter footer) {
this.footer = footer;
return this;
}
public EmbedBuilder withFooter(String text, String iconUrl) {
this.footer = new Embed.EmbedFooter(text, iconUrl, null);
return this;
}
public EmbedBuilder withImage(Embed.EmbedImage image) {
this.image = image;
return this;
}
public EmbedBuilder withImage(String url) {
this.image = new Embed.EmbedImage(url, null, -1, -1);
return this;
}
public EmbedBuilder withThumbnail(Embed.EmbedImage thumbnail) {
this.thumbnail = thumbnail;
return this;
}
public EmbedBuilder withThumbnail(String url) {
this.thumbnail = new Embed.EmbedImage(url, null, -1, -1);
return this;
}
public EmbedBuilder withVideo(Embed.EmbedMedia video) {
this.video = video;
return this;
}
public EmbedBuilder withVideo(String url) {
this.video = new Embed.EmbedMedia(url, -1, -1);
return this;
}
public EmbedBuilder withProvider(Embed.EmbedProvider provider) {
this.provider = provider;
return this;
}
public EmbedBuilder withProvider(String name, String url) {
this.provider = new Embed.EmbedProvider(name, url);
return this;
}
public EmbedBuilder withAuthor(Embed.EmbedAuthor author) {
this.author = author;
return this;
}
public EmbedBuilder withAuthor(String name, String url, String iconUrl) {
this.author = new Embed.EmbedAuthor(name, url, iconUrl, null);
return this;
}
public EmbedBuilder appendField(Embed.EmbedField field) {
this.fields.add(field);
return this;
}
public EmbedBuilder appendField(String name, String value, boolean inline) {
this.fields.add(new Embed.EmbedField(name, value, inline));
return this;
}
public Embed build() {
return new Embed(title, type, description, url, color, footer, image, thumbnail, video, provider, author, fields.toArray(new Embed.EmbedField[0]));
}
}
| unlicense |
rsmeral/pv243-jboss | project/project-et-ejb/src/main/java/cz/muni/fi/pv243/et/model/ExpenseReport.java | 4903 | package cz.muni.fi.pv243.et.model;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.IndexedEmbedded;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@Indexed
public class ExpenseReport implements Serializable {
@Id
@GeneratedValue
private Long id;
@NotNull
private String name;
private String description;
private Boolean selected;
public ExpenseReport() {
}
public ExpenseReport(String name, String description, Person submitter, Person verifier, ReportStatus status) {
this.name = name;
this.description = description;
this.submitter = submitter;
this.verifier = verifier;
this.status = status;
}
@NotNull
@ManyToOne
@IndexedEmbedded
private Person submitter;
@ManyToOne(cascade= CascadeType.MERGE)
@IndexedEmbedded
private Person verifier;
@OneToMany(mappedBy = "report", cascade = CascadeType.MERGE)
@LazyCollection(LazyCollectionOption.FALSE)
private List<Payment> payments;
@OneToMany(mappedBy = "report", cascade = CascadeType.MERGE)
@LazyCollection(LazyCollectionOption.FALSE)
private List<MoneyTransfer> moneyTransfers;
@Temporal(TemporalType.TIMESTAMP)
private Date lastSubmittedDate;
@Temporal(TemporalType.TIMESTAMP)
private Date approvedDate;
@Temporal(TemporalType.TIMESTAMP)
private Date lastChangeDate;
@Field
@Enumerated(EnumType.ORDINAL)
@IndexedEmbedded
private ReportStatus status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Person getSubmitter() {
return submitter;
}
public void setSubmitter(Person submitter) {
this.submitter = submitter;
}
public Person getVerifier() {
return verifier;
}
public void setVerifier(Person verifier) {
this.verifier = verifier;
}
public List<Payment> getPayments() {
return payments;
}
public void setPayments(List<Payment> payments) {
this.payments = payments;
}
public List<MoneyTransfer> getMoneyTransfers() {
return moneyTransfers;
}
public void setMoneyTransfers(List<MoneyTransfer> moneyTransfers) {
this.moneyTransfers = moneyTransfers;
}
public Date getLastSubmittedDate() {
return lastSubmittedDate;
}
public void setLastSubmittedDate(Date lastSubmittedDate) {
this.lastSubmittedDate = lastSubmittedDate;
}
public Date getApprovedDate() {
return approvedDate;
}
public void setApprovedDate(Date approvedDate) {
this.approvedDate = approvedDate;
}
public ReportStatus getStatus() {
return status;
}
public void setStatus(ReportStatus status) {
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getLastChangeDate() {
return lastChangeDate;
}
public void setLastChangeDate(Date lastChangeDate) {
this.lastChangeDate = lastChangeDate;
}
public Boolean getSelected() {
return selected;
}
public void setSelected(Boolean selected) {
this.selected = selected;
}
@Override
public final boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ExpenseReport)) return false;
ExpenseReport report = (ExpenseReport) o;
if (getId() != null ? !getId().equals(report.getId()) : report.getId() != null) return false;
return true;
}
@Override
public int hashCode() {
return getId() != null ? getId().hashCode() : 0;
}
@Override
public String toString() {
return "ExpenseReport{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", submitter=" + submitter +
", verifier=" + verifier +
", payments=" + payments +
", moneyTransfers=" + moneyTransfers +
", lastSubmittedDate=" + lastSubmittedDate +
", approvedDate=" + approvedDate +
", lastChangeDate=" + lastChangeDate +
", status=" + status +
", selected=" + selected +
'}';
}
}
| unlicense |
clilystudio/NetBook | allsrc/com/ushaqi/zhuishushenqi/util/l(1).java | 833 | package com.ushaqi.zhuishushenqi.util;
import com.ushaqi.zhuishushenqi.a.e;
import com.ushaqi.zhuishushenqi.api.ApiService;
import com.ushaqi.zhuishushenqi.api.b;
import com.ushaqi.zhuishushenqi.model.ResultStatus;
final class l extends e<String, Void, ResultStatus>
{
private l(k paramk)
{
}
private static ResultStatus a(String[] paramArrayOfString)
{
try
{
b.a();
ResultStatus localResultStatus = b.b().n(paramArrayOfString[0], paramArrayOfString[1], paramArrayOfString[2]);
return localResultStatus;
}
catch (Exception localException)
{
localException.printStackTrace();
}
return null;
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ushaqi.zhuishushenqi.util.l
* JD-Core Version: 0.6.0
*/ | unlicense |
will-gilbert/SmartGWT-Mobile | mobile/src/main/java/com/smartgwt/mobile/client/internal/widgets/events/ValuesSelectedEvent.java | 1137 | package com.smartgwt.mobile.client.internal.widgets.events;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HasHandlers;
public class ValuesSelectedEvent extends GwtEvent<ValuesSelectedHandler> {
private static Type<ValuesSelectedHandler> TYPE = null;
public static Type<ValuesSelectedHandler> getType() {
if (TYPE == null) TYPE = new Type<ValuesSelectedHandler>();
return TYPE;
}
public static <S extends HasValuesSelectedHandlers & HasHandlers> void fire(S source, Object[] values) {
if (TYPE != null) {
final ValuesSelectedEvent event = new ValuesSelectedEvent(values);
source.fireEvent(event);
}
}
private Object[] values;
private ValuesSelectedEvent(Object[] values) {
this.values = values;
}
public final Object[] getValues() {
return values;
}
@Override
public final Type<ValuesSelectedHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(ValuesSelectedHandler handler) {
handler._onValuesSelected(this);
}
}
| unlicense |
cc14514/hq6 | hq-server/src/main/java/org/hyperic/hq/bizapp/shared/EventsBoss.java | 17838 | /**
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2009-2010], VMware, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU 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 General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
*/
package org.hyperic.hq.bizapp.shared;
import java.util.List;
import java.util.Map;
import javax.security.auth.login.LoginException;
import org.hyperic.hq.appdef.shared.AppdefEntityID;
import org.hyperic.hq.appdef.shared.AppdefEntityNotFoundException;
import org.hyperic.hq.appdef.shared.AppdefEntityTypeID;
import org.hyperic.hq.auth.shared.SessionException;
import org.hyperic.hq.auth.shared.SessionNotFoundException;
import org.hyperic.hq.auth.shared.SessionTimeoutException;
import org.hyperic.hq.authz.server.session.AuthzSubject;
import org.hyperic.hq.authz.shared.PermissionException;
import org.hyperic.hq.common.ApplicationException;
import org.hyperic.hq.common.DuplicateObjectException;
import org.hyperic.hq.escalation.server.session.Escalatable;
import org.hyperic.hq.escalation.server.session.Escalation;
import org.hyperic.hq.escalation.server.session.EscalationAlertType;
import org.hyperic.hq.escalation.server.session.EscalationState;
import org.hyperic.hq.events.ActionConfigInterface;
import org.hyperic.hq.events.ActionCreateException;
import org.hyperic.hq.events.ActionExecuteException;
import org.hyperic.hq.events.AlertConditionCreateException;
import org.hyperic.hq.events.AlertDefinitionCreateException;
import org.hyperic.hq.events.AlertNotFoundException;
import org.hyperic.hq.events.MaintenanceEvent;
import org.hyperic.hq.events.TriggerCreateException;
import org.hyperic.hq.events.server.session.Action;
import org.hyperic.hq.events.server.session.Alert;
import org.hyperic.hq.events.shared.ActionValue;
import org.hyperic.hq.events.shared.AlertDefinitionValue;
import org.hyperic.util.ConfigPropertyException;
import org.hyperic.util.config.ConfigResponse;
import org.hyperic.util.config.ConfigSchema;
import org.hyperic.util.config.InvalidOptionException;
import org.hyperic.util.config.InvalidOptionValueException;
import org.hyperic.util.pager.PageControl;
import org.hyperic.util.pager.PageList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.quartz.SchedulerException;
import org.springframework.transaction.annotation.Transactional;
/**
* Local interface for EventsBoss.
*/
public interface EventsBoss {
/**
* Get the number of alerts for the given array of AppdefEntityID's
*/
public int[] getAlertCount(int sessionID, org.hyperic.hq.appdef.shared.AppdefEntityID[] ids)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Get the number of alerts for the given array of AppdefEntityID's, mapping AppdefEntityID to it's alerts count
*
*/
@Transactional(readOnly = true)
public Map<AppdefEntityID, Integer> getAlertCountMapped(int sessionID, AppdefEntityID[] ids)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Create an alert definition
*/
public AlertDefinitionValue createAlertDefinition(int sessionID, AlertDefinitionValue adval)
throws org.hyperic.hq.events.AlertDefinitionCreateException, PermissionException,
InvalidOptionException, InvalidOptionValueException, SessionException;
/**
* Create an alert definition for a resource type
*/
public AlertDefinitionValue createResourceTypeAlertDefinition(int sessionID,
AppdefEntityTypeID aetid,
AlertDefinitionValue adval)
throws org.hyperic.hq.events.AlertDefinitionCreateException, PermissionException,
InvalidOptionException, InvalidOptionValueException, SessionNotFoundException,
SessionTimeoutException;
public Action createAction(int sessionID, Integer adid, String className, ConfigResponse config)
throws SessionNotFoundException, SessionTimeoutException, ActionCreateException,
PermissionException;
/**
* Activate/deactivate a collection of alert definitions
*/
public void activateAlertDefinitions(int sessionID, java.lang.Integer[] ids, boolean activate)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Activate or deactivate alert definitions by AppdefEntityID.
*/
public void activateAlertDefinitions(int sessionID,
org.hyperic.hq.appdef.shared.AppdefEntityID[] eids,
boolean activate) throws SessionNotFoundException,
SessionTimeoutException, AppdefEntityNotFoundException, PermissionException;
/**
* Update just the basics
*/
public void updateAlertDefinitionBasic(int sessionID, Integer alertDefId, String name,
String desc, int priority, boolean activate)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
public void updateAlertDefinition(int sessionID, AlertDefinitionValue adval)
throws TriggerCreateException, InvalidOptionException, InvalidOptionValueException,
AlertConditionCreateException, ActionCreateException, SessionNotFoundException,
SessionTimeoutException;
/**
* Get actions for a given alert.
* @param alertId the alert id
*/
public List<ActionValue> getActionsForAlert(int sessionId, Integer alertId)
throws SessionNotFoundException, SessionTimeoutException;
/**
* Update an action
*/
public void updateAction(int sessionID, ActionValue aval) throws SessionNotFoundException,
SessionTimeoutException;
/**
* Delete a collection of alert definitions
*/
public void deleteAlertDefinitions(int sessionID, java.lang.Integer[] ids)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Delete list of alerts
*/
public void deleteAlerts(int sessionID, java.lang.Integer[] ids)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Delete all alerts for a list of alert definitions
*
*/
public int deleteAlertsForDefinitions(int sessionID, java.lang.Integer[] adids)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Get an alert definition by ID
*/
public AlertDefinitionValue getAlertDefinition(int sessionID, Integer id)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Find an alert by ID
*/
public Alert getAlert(int sessionID, Integer id) throws SessionNotFoundException,
SessionTimeoutException, AlertNotFoundException;
/**
* Get a list of all alert definitions
*/
public PageList<AlertDefinitionValue> findAllAlertDefinitions(int sessionID)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Get a collection of alert definitions for a resource
*/
public PageList<AlertDefinitionValue> findAlertDefinitions(int sessionID, AppdefEntityID id,
PageControl pc)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Get a collection of alert definitions for a resource or resource type
*/
public PageList<AlertDefinitionValue> findAlertDefinitions(int sessionID,
AppdefEntityTypeID id, PageControl pc)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Find all alert definition names for a resource
* @return Map of AlertDefinition names and IDs
*/
public Map<String, Integer> findAlertDefinitionNames(int sessionID, AppdefEntityID id,
Integer parentId)
throws SessionNotFoundException, SessionTimeoutException, AppdefEntityNotFoundException,
PermissionException;
/**
* Find all alerts for an appdef resource
*/
public PageList<Alert> findAlerts(int sessionID, AppdefEntityID id, long begin, long end,
PageControl pc) throws SessionNotFoundException,
SessionTimeoutException, PermissionException;
/**
* Search alerts given a set of criteria
* @param username the username
* @param count the maximum number of alerts to return
* @param priority allowable values: 0 (all), 1, 2, or 3
* @param timeRange the amount of time from current time to include
* @param ids the IDs of resources to include or null for ALL
* @return a list of {@link Escalatable}s
*/
public List<Escalatable> findRecentAlerts(String username, int count, int priority,
long timeRange,
org.hyperic.hq.appdef.shared.AppdefEntityID[] ids)
throws LoginException, ApplicationException, ConfigPropertyException;
/**
* Search recent alerts given a set of criteria
* @param sessionID the session token
* @param count the maximum number of alerts to return
* @param priority allowable values: 0 (all), 1, 2, or 3
* @param timeRange the amount of time from current time to include
* @param ids the IDs of resources to include or null for ALL
* @return a list of {@link Escalatable}s
*/
public List<Escalatable> findRecentAlerts(int sessionID, int count, int priority,
long timeRange,
org.hyperic.hq.appdef.shared.AppdefEntityID[] ids)
throws SessionNotFoundException, SessionTimeoutException, PermissionException;
/**
* Get config schema info for an action class
*/
public ConfigSchema getActionConfigSchema(int sessionID, String actionClass)
throws SessionNotFoundException, SessionTimeoutException,
org.hyperic.util.config.EncodingException;
/**
* Get config schema info for a trigger class
*/
public ConfigSchema getRegisteredTriggerConfigSchema(int sessionID, String triggerClass)
throws SessionNotFoundException, SessionTimeoutException,
org.hyperic.util.config.EncodingException;
public void deleteEscalationByName(int sessionID, String name) throws SessionTimeoutException,
SessionNotFoundException, PermissionException, org.hyperic.hq.common.ApplicationException;
public void deleteEscalationById(int sessionID, Integer id) throws SessionTimeoutException,
SessionNotFoundException, PermissionException, org.hyperic.hq.common.ApplicationException;
/**
* remove escalation by id
*/
public void deleteEscalationById(int sessionID, java.lang.Integer[] ids)
throws SessionTimeoutException, SessionNotFoundException, PermissionException,
org.hyperic.hq.common.ApplicationException;
/**
* retrieve escalation name by alert definition id.
*/
public Integer getEscalationIdByAlertDefId(int sessionID, Integer id,
EscalationAlertType alertType)
throws SessionTimeoutException, SessionNotFoundException, PermissionException;
/**
* set escalation name by alert definition id.
*/
public void setEscalationByAlertDefId(int sessionID, Integer id, Integer escId,
EscalationAlertType alertType)
throws SessionTimeoutException, SessionNotFoundException, PermissionException;
/**
* unset escalation by alert definition id.
*/
public void unsetEscalationByAlertDefId(int sessionID, Integer id, EscalationAlertType alertType)
throws SessionTimeoutException, SessionNotFoundException, PermissionException;
/**
* retrieve escalation JSONObject by alert definition id.
*/
public JSONObject jsonEscalationByAlertDefId(int sessionID, Integer id,
EscalationAlertType alertType)
throws org.hyperic.hq.auth.shared.SessionException, PermissionException, JSONException;
/**
* retrieve escalation object by escalation id.
*/
public Escalation findEscalationById(int sessionID, Integer id) throws SessionTimeoutException,
SessionNotFoundException, PermissionException;
public void addAction(int sessionID, Escalation e, ActionConfigInterface cfg, long waitTime)
throws SessionTimeoutException, SessionNotFoundException, PermissionException;
public void removeAction(int sessionID, Integer escId, Integer actId)
throws SessionTimeoutException, SessionNotFoundException, PermissionException;
/**
* Retrieve a list of {@link EscalationState}s, representing the active
* escalations in the system.
*/
public List<EscalationState> getActiveEscalations(int sessionId, int maxEscalations)
throws org.hyperic.hq.auth.shared.SessionException;
/**
* Gets the escalatable associated with the specified state
*/
public Escalatable getEscalatable(int sessionId, EscalationState state)
throws org.hyperic.hq.auth.shared.SessionException;
/**
* retrieve all escalation policy names as a Array of JSONObject. Escalation
* json finders begin with json* to be consistent with DAO finder convention
*/
public JSONArray listAllEscalationName(int sessionID) throws JSONException,
SessionTimeoutException, SessionNotFoundException, PermissionException;
/**
* Create a new escalation. If alertDefId is non-null, the escalation will
* also be associated with the given alert definition.
*/
public Escalation createEscalation(int sessionID, String name, String desc, boolean allowPause,
long maxWaitTime, boolean notifyAll, boolean repeat,
EscalationAlertType alertType, Integer alertDefId)
throws SessionTimeoutException, SessionNotFoundException, PermissionException,
DuplicateObjectException;
/**
* Update basic escalation properties
*/
public void updateEscalation(int sessionID, Escalation escalation, String name, String desc,
long maxWait, boolean pausable, boolean notifyAll, boolean repeat)
throws SessionTimeoutException, SessionNotFoundException, PermissionException,
DuplicateObjectException;
public boolean acknowledgeAlert(int sessionID, EscalationAlertType alertType, Integer alertID,
long pauseWaitTime, String moreInfo)
throws SessionTimeoutException, SessionNotFoundException, PermissionException,
ActionExecuteException;
/**
* Fix a single alert. Method is "NotSupported" since all the alert fixes
* may take longer than the transaction timeout. No need for a transaction
* in this context.
*/
public void fixAlert(int sessionID, EscalationAlertType alertType, Integer alertID,
String moreInfo) throws SessionTimeoutException, SessionNotFoundException,
PermissionException, ActionExecuteException;
/**
* Fix a batch of alerts. Method is "NotSupported" since all the alert fixes
* may take longer than the transaction timeout. No need for a transaction
* in this context.
*/
public void fixAlert(int sessionID, EscalationAlertType alertType, Integer alertID,
String moreInfo, boolean fixAllPrevious) throws SessionTimeoutException,
SessionNotFoundException, PermissionException, ActionExecuteException;
/**
* Get the last fix if available
*/
public String getLastFix(int sessionID, Integer defId) throws SessionNotFoundException,
SessionTimeoutException, PermissionException;
/**
* Get a maintenance event by group id
*/
public MaintenanceEvent getMaintenanceEvent(int sessionId, Integer groupId)
throws SessionNotFoundException, SessionTimeoutException, PermissionException,
SchedulerException;
/**
* Schedule a maintenance event
*/
public MaintenanceEvent scheduleMaintenanceEvent(int sessionId, MaintenanceEvent event)
throws SessionNotFoundException, SessionTimeoutException, PermissionException,
SchedulerException;
/**
* Schedule a maintenance event
*/
public void unscheduleMaintenanceEvent(int sessionId, MaintenanceEvent event)
throws SessionNotFoundException, SessionTimeoutException, PermissionException,
SchedulerException;
}
| unlicense |
neftalyluis/HRSolutions | src/main/java/mx/neftaly/hackerrank/algorithms/Kangaroo.java | 882 | /*
* 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 mx.neftaly.hackerrank.algorithms;
import java.util.Scanner;
/**
*
* @author samas
*/
public class Kangaroo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
int x1 = in.nextInt();
int v1 = in.nextInt();
int x2 = in.nextInt();
int v2 = in.nextInt();
if (x2 >= x1 && v2 >= v1) {
System.out.println("NO");
} else if ((x1 - x2) % (v2 - v1) == 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| unlicense |
aatxe/pixalia | src/main/java/us/aaronweiss/pixalia/core/Player.java | 240 | package us.aaronweiss.pixalia.core;
import us.aaronweiss.pixalia.tools.Vector;
public class Player extends Pixal {
public Player(String hostname) {
super(hostname);
}
public void setColor(Vector color) {
this.color = color;
}
}
| unlicense |
POKLpokl112/leetcode | leetcode/src/code/one/GroupAnagrams_time.java | 1763 | package code.one;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//Given an array of strings, group anagrams together.
//
//For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
//Return:
//
//[
// ["ate", "eat","tea"],
// ["nat","tan"],
// ["bat"]
//]
public class GroupAnagrams_time {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) {
return new ArrayList<>();
}
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
char[] c = str.toCharArray();
Arrays.sort(c);
String s = new String(c);
if (!map.containsKey(s)) {
map.put(s, new ArrayList<>());
}
map.get(s).add(str);
}
return new ArrayList<>(map.values());
}
public List<List<String>> groupAnagrams1(String[] strs) {
List<List<String>> array = new ArrayList<>();
List<String> list = new ArrayList<>();
List<char[]> list1 = new ArrayList<>();
for (int i = 0; i < strs.length; i++) {
char[] c = strs[i].toCharArray();
Arrays.sort(c);
list1.add(c);
list.add(strs[i]);
}
while (!list.isEmpty()) {
List<String> l = new ArrayList<>();
l.add(list.remove(0));
char[] c = list1.remove(0);
for (int i = 0; i < list.size(); i++) {
if (equal(c, list1.get(i))) {
l.add(list.remove(i));
list1.remove(i);
i--;
}
}
array.add(l);
}
return array;
}
private boolean equal(char[] c, char[] ds) {
if (c.length != ds.length) {
return false;
}
for (int i = 0; i < ds.length; i++) {
if (c[i] != ds[i]) {
return false;
}
}
return true;
}
}
| unlicense |
nfd/KeePassNFC | app/src/main/java/net/lardcave/keepassnfc/nfccomms/KPNdef.java | 3998 | package net.lardcave.keepassnfc.nfccomms;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Parcelable;
import net.lardcave.keepassnfc.Settings;
import java.io.IOException;
import java.util.Arrays;
public class KPNdef {
private static final String nfc_ndef_mime_type = "application/x-keepassnfc-3";
// Stored on the tag:
private static final int KEY_TYPE_RAW = 1; // Password is stored directly on the card (basic NTAG203 memory-only tag)
private static final int KEY_TYPE_APP = 2; // Password is stored in the KeepassNFC applet (JavaCard smartcard).
private static final int key_type_length = 1;
private byte[] secretKey;
private boolean _successfulNdefRead = false;
/** Construct an NDEF message for writing containing a secret key. */
public KPNdef(byte[] secretKey) {
this.secretKey = secretKey;
}
/** Construct an NDEF message for writing without any secret information (for use with applet) */
public KPNdef() {
// TODO this is unused because the applet code bypasses Android's NDEF support (since it
// TODO already has an isodep channel open). harmonise this & applet NDEF code.
this.secretKey = null;
}
public static IntentFilter getIntentFilter() {
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType(nfc_ndef_mime_type);
}
catch (IntentFilter.MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
return ndef;
}
/** Read an NDEF message from an Intent */
public KPNdef(Intent intent) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
NdefMessage [] msgs = new NdefMessage[rawMsgs.length];
for (int j = 0; j < rawMsgs.length; j++) {
msgs[j] = (NdefMessage) rawMsgs[j];
NdefRecord record = msgs[j].getRecords()[0];
if (record.getTnf() == NdefRecord.TNF_MIME_MEDIA)
{
String mimetype = record.toMimeType();
if (mimetype.equals(nfc_ndef_mime_type)) {
_successfulNdefRead = true;
decodePayload(record.getPayload());
}
}
}
}
}
public boolean readWasSuccessful() {
return _successfulNdefRead;
}
public byte[] getSecretKey() {
return secretKey;
}
/** Write NDEF to the tag to wake up KPNFC when it's presented. */
public boolean write(Tag tag) {
if(secretKey == null) {
return writeMessageInternal(tag, createWakeOnlyNdefMessage());
} else {
return writeMessageInternal(tag, createRandomBytesNdefMessage(secretKey));
}
}
private void decodePayload(byte[] payload) {
switch(payload[0]) {
case KEY_TYPE_RAW:
secretKey = Arrays.copyOfRange(payload, 1, payload.length);
break;
case KEY_TYPE_APP:
secretKey = null;
break;
}
}
private static boolean writeMessageInternal(Tag tag, NdefMessage message) {
// Write the payload to the tag.
android.nfc.tech.Ndef ndef = android.nfc.tech.Ndef.get(tag);
try {
ndef.connect();
ndef.writeNdefMessage(message);
ndef.close();
return true;
} catch (IOException | FormatException e) {
e.printStackTrace();
}
return false;
}
private static NdefMessage createRandomBytesNdefMessage(byte[] secretKey)
{
byte[] messageBytes;
messageBytes = new byte[key_type_length + Settings.key_length];
messageBytes[0] = (byte)KEY_TYPE_RAW;
System.arraycopy(secretKey, 0, messageBytes, 1, Settings.key_length);
return ndefFromBytes(messageBytes);
}
static NdefMessage createWakeOnlyNdefMessage()
{
byte[] messageBytes;
messageBytes = new byte[key_type_length];
messageBytes[0] = (byte)KEY_TYPE_APP;
return ndefFromBytes(messageBytes);
}
private static NdefMessage ndefFromBytes(byte[] messageBytes) {
NdefRecord ndef_records = NdefRecord.createMime(nfc_ndef_mime_type, messageBytes);
return new NdefMessage(ndef_records);
}
}
| unlicense |
ofbizfriends/vogue | framework/widget/src/org/ofbiz/widget/tree/ModelTreeCondition.java | 20242 | /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.widget.tree;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Matcher;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.ObjectType;
import org.ofbiz.base.util.PatternFactory;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.UtilXml;
import org.ofbiz.base.util.collections.FlexibleMapAccessor;
import org.ofbiz.base.util.string.FlexibleStringExpander;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entityext.permission.EntityPermissionChecker;
import org.ofbiz.minilang.operation.BaseCompare;
import org.ofbiz.security.Security;
import org.w3c.dom.Element;
/**
* Widget Library - Screen model condition class
*/
public class ModelTreeCondition {
public static final String module = ModelTreeCondition.class.getName();
protected ModelTree modelTree;
protected TreeCondition rootCondition;
public ModelTreeCondition(ModelTree modelTree, Element conditionElement) {
this.modelTree = modelTree;
Element firstChildElement = UtilXml.firstChildElement(conditionElement);
this.rootCondition = readCondition(modelTree, firstChildElement);
}
public boolean eval(Map<String, ? extends Object> context) {
if (rootCondition == null) {
return true;
}
return rootCondition.eval(context);
}
public static abstract class TreeCondition {
protected ModelTree modelTree;
public TreeCondition(ModelTree modelTree, Element conditionElement) {
this.modelTree = modelTree;
}
public abstract boolean eval(Map<String, ? extends Object> context);
}
public static List<TreeCondition> readSubConditions(ModelTree modelTree, Element conditionElement) {
List<TreeCondition> condList = new ArrayList<TreeCondition>();
for (Element subElement: UtilXml.childElementList(conditionElement)) {
condList.add(readCondition(modelTree, subElement));
}
return condList;
}
public static TreeCondition readCondition(ModelTree modelTree, Element conditionElement) {
if (conditionElement == null) {
return null;
}
if ("and".equals(conditionElement.getNodeName())) {
return new And(modelTree, conditionElement);
} else if ("xor".equals(conditionElement.getNodeName())) {
return new Xor(modelTree, conditionElement);
} else if ("or".equals(conditionElement.getNodeName())) {
return new Or(modelTree, conditionElement);
} else if ("not".equals(conditionElement.getNodeName())) {
return new Not(modelTree, conditionElement);
} else if ("if-has-permission".equals(conditionElement.getNodeName())) {
return new IfHasPermission(modelTree, conditionElement);
} else if ("if-validate-method".equals(conditionElement.getNodeName())) {
return new IfValidateMethod(modelTree, conditionElement);
} else if ("if-compare".equals(conditionElement.getNodeName())) {
return new IfCompare(modelTree, conditionElement);
} else if ("if-compare-field".equals(conditionElement.getNodeName())) {
return new IfCompareField(modelTree, conditionElement);
} else if ("if-regexp".equals(conditionElement.getNodeName())) {
return new IfRegexp(modelTree, conditionElement);
} else if ("if-empty".equals(conditionElement.getNodeName())) {
return new IfEmpty(modelTree, conditionElement);
} else if ("if-entity-permission".equals(conditionElement.getNodeName())) {
return new IfEntityPermission(modelTree, conditionElement);
} else {
throw new IllegalArgumentException("Condition element not supported with name: " + conditionElement.getNodeName());
}
}
public static class And extends TreeCondition {
protected List<? extends TreeCondition> subConditions;
public And(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.subConditions = readSubConditions(modelTree, condElement);
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
// return false for the first one in the list that is false, basic and algo
for (TreeCondition subCondition: subConditions) {
if (!subCondition.eval(context)) {
return false;
}
}
return true;
}
}
public static class Xor extends TreeCondition {
protected List<? extends TreeCondition> subConditions;
public Xor(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.subConditions = readSubConditions(modelTree, condElement);
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
// if more than one is true stop immediately and return false; if all are false return false; if only one is true return true
boolean foundOneTrue = false;
for (TreeCondition subCondition: subConditions) {
if (subCondition.eval(context)) {
if (foundOneTrue) {
// now found two true, so return false
return false;
} else {
foundOneTrue = true;
}
}
}
return foundOneTrue;
}
}
public static class Or extends TreeCondition {
protected List<? extends TreeCondition> subConditions;
public Or(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.subConditions = readSubConditions(modelTree, condElement);
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
// return true for the first one in the list that is true, basic or algo
for (TreeCondition subCondition: subConditions) {
if (subCondition.eval(context)) {
return true;
}
}
return false;
}
}
public static class Not extends TreeCondition {
protected TreeCondition subCondition;
public Not(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
Element firstChildElement = UtilXml.firstChildElement(condElement);
this.subCondition = readCondition(modelTree, firstChildElement);
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
return !this.subCondition.eval(context);
}
}
public static class IfHasPermission extends TreeCondition {
protected FlexibleStringExpander permissionExdr;
protected FlexibleStringExpander actionExdr;
public IfHasPermission(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.permissionExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("permission"));
this.actionExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("action"));
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
// if no user is logged in, treat as if the user does not have permission
GenericValue userLogin = (GenericValue) context.get("userLogin");
if (userLogin != null) {
String permission = permissionExdr.expandString(context);
String action = actionExdr.expandString(context);
Security security = (Security) context.get("security");
if (UtilValidate.isNotEmpty(action)) {
// run hasEntityPermission
if (security.hasEntityPermission(permission, action, userLogin)) {
return true;
}
} else {
// run hasPermission
if (security.hasPermission(permission, userLogin)) {
return true;
}
}
}
return false;
}
}
public static class IfValidateMethod extends TreeCondition {
protected FlexibleMapAccessor<Object> fieldAcsr;
protected FlexibleStringExpander methodExdr;
protected FlexibleStringExpander classExdr;
public IfValidateMethod(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field"));
if (this.fieldAcsr.isEmpty()) this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field-name"));
this.methodExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("method"));
this.classExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("class"));
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
String methodName = this.methodExdr.expandString(context);
String className = this.classExdr.expandString(context);
Object fieldVal = this.fieldAcsr.get(context);
String fieldString = null;
if (fieldVal != null) {
try {
fieldString = (String) ObjectType.simpleTypeConvert(fieldVal, "String", null, (TimeZone) context.get("timeZone"), (Locale) context.get("locale"), true);
} catch (GeneralException e) {
Debug.logError(e, "Could not convert object to String, using empty String", module);
}
}
// always use an empty string by default
if (fieldString == null) fieldString = "";
Class<?>[] paramTypes = new Class[] {String.class};
Object[] params = new Object[] {fieldString};
Class<?> valClass;
try {
valClass = ObjectType.loadClass(className);
} catch (ClassNotFoundException cnfe) {
Debug.logError("Could not find validation class: " + className, module);
return false;
}
Method valMethod;
try {
valMethod = valClass.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException cnfe) {
Debug.logError("Could not find validation method: " + methodName + " of class " + className, module);
return false;
}
Boolean resultBool = Boolean.FALSE;
try {
resultBool = (Boolean) valMethod.invoke(null, params);
} catch (Exception e) {
Debug.logError(e, "Error in IfValidationMethod " + methodName + " of class " + className + ", defaulting to false ", module);
}
return resultBool.booleanValue();
}
}
public static class IfCompare extends TreeCondition {
protected FlexibleMapAccessor<Object> fieldAcsr;
protected FlexibleStringExpander valueExdr;
protected String operator;
protected String type;
protected FlexibleStringExpander formatExdr;
public IfCompare(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field"));
if (this.fieldAcsr.isEmpty()) this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field-name"));
this.valueExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("value"));
this.operator = condElement.getAttribute("operator");
this.type = condElement.getAttribute("type");
this.formatExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("format"));
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
String value = this.valueExdr.expandString(context);
String format = this.formatExdr.expandString(context);
Object fieldVal = this.fieldAcsr.get(context);
// always use an empty string by default
if (fieldVal == null) {
fieldVal = "";
}
List<Object> messages = new LinkedList<Object>();
Boolean resultBool = BaseCompare.doRealCompare(fieldVal, value, operator, type, format, messages, null, null, true);
if (messages.size() > 0) {
messages.add(0, "Error with comparison in if-compare between field [" + fieldAcsr.toString() + "] with value [" + fieldVal + "] and value [" + value + "] with operator [" + operator + "] and type [" + type + "]: ");
StringBuilder fullString = new StringBuilder();
for (Object message: messages) {
fullString.append((String) message);
}
Debug.logWarning(fullString.toString(), module);
throw new IllegalArgumentException(fullString.toString());
}
return resultBool.booleanValue();
}
}
public static class IfCompareField extends TreeCondition {
protected FlexibleMapAccessor<Object> fieldAcsr;
protected FlexibleMapAccessor<Object> toFieldAcsr;
protected String operator;
protected String type;
protected FlexibleStringExpander formatExdr;
public IfCompareField(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field"));
if (this.fieldAcsr.isEmpty()) this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field-name"));
this.toFieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("to-field"));
if (this.toFieldAcsr.isEmpty()) this.toFieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("to-field-name"));
this.operator = condElement.getAttribute("operator");
this.type = condElement.getAttribute("type");
this.formatExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("format"));
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
String format = this.formatExdr.expandString(context);
Object fieldVal = this.fieldAcsr.get(context);
Object toFieldVal = this.toFieldAcsr.get(context);
// always use an empty string by default
if (fieldVal == null) {
fieldVal = "";
}
List<Object> messages = new LinkedList<Object>();
Boolean resultBool = BaseCompare.doRealCompare(fieldVal, toFieldVal, operator, type, format, messages, null, null, false);
if (messages.size() > 0) {
messages.add(0, "Error with comparison in if-compare-field between field [" + fieldAcsr.toString() + "] with value [" + fieldVal + "] and to-field [" + toFieldVal.toString() + "] with value [" + toFieldVal + "] with operator [" + operator + "] and type [" + type + "]: ");
StringBuilder fullString = new StringBuilder();
for (Object message: messages) {
fullString.append((String) message);
}
Debug.logWarning(fullString.toString(), module);
throw new IllegalArgumentException(fullString.toString());
}
return resultBool.booleanValue();
}
}
public static class IfRegexp extends TreeCondition {
protected FlexibleMapAccessor<Object> fieldAcsr;
protected FlexibleStringExpander exprExdr;
public IfRegexp(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field"));
if (this.fieldAcsr.isEmpty()) this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field-name"));
this.exprExdr = FlexibleStringExpander.getInstance(condElement.getAttribute("expr"));
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
Object fieldVal = this.fieldAcsr.get(context);
String expr = this.exprExdr.expandString(context);
Pattern pattern = null;
try {
pattern = PatternFactory.createOrGetPerl5CompiledPattern(expr, true);
} catch (MalformedPatternException e) {
String errMsg = "Error in evaluation in if-regexp in screen: " + e.toString();
Debug.logError(e, errMsg, module);
throw new IllegalArgumentException(errMsg);
}
String fieldString = null;
try {
fieldString = (String) ObjectType.simpleTypeConvert(fieldVal, "String", null, (TimeZone) context.get("timeZone"), (Locale) context.get("locale"), true);
} catch (GeneralException e) {
Debug.logError(e, "Could not convert object to String, using empty String", module);
}
// always use an empty string by default
if (fieldString == null) fieldString = "";
PatternMatcher matcher = new Perl5Matcher();
return matcher.matches(fieldString, pattern);
}
}
public static class IfEmpty extends TreeCondition {
protected FlexibleMapAccessor<Object> fieldAcsr;
public IfEmpty(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field"));
if (this.fieldAcsr.isEmpty()) this.fieldAcsr = FlexibleMapAccessor.getInstance(condElement.getAttribute("field-name"));
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
Object fieldVal = this.fieldAcsr.get(context);
return ObjectType.isEmpty(fieldVal);
}
}
public static class IfEntityPermission extends TreeCondition {
protected EntityPermissionChecker permissionChecker;
public IfEntityPermission(ModelTree modelTree, Element condElement) {
super (modelTree, condElement);
this.permissionChecker = new EntityPermissionChecker(condElement);
}
@Override
public boolean eval(Map<String, ? extends Object> context) {
boolean passed = permissionChecker.runPermissionCheck(context);
return passed;
}
}
}
| apache-2.0 |
dump247/aws-sdk-java | aws-java-sdk-elastictranscoder/src/main/java/com/amazonaws/services/elastictranscoder/model/transform/CreateJobPlaylistJsonUnmarshaller.java | 4113 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.elastictranscoder.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import com.amazonaws.services.elastictranscoder.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* CreateJobPlaylist JSON Unmarshaller
*/
public class CreateJobPlaylistJsonUnmarshaller implements
Unmarshaller<CreateJobPlaylist, JsonUnmarshallerContext> {
public CreateJobPlaylist unmarshall(JsonUnmarshallerContext context)
throws Exception {
CreateJobPlaylist createJobPlaylist = new CreateJobPlaylist();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL)
return null;
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Name", targetDepth)) {
context.nextToken();
createJobPlaylist.setName(StringJsonUnmarshaller
.getInstance().unmarshall(context));
}
if (context.testExpression("Format", targetDepth)) {
context.nextToken();
createJobPlaylist.setFormat(StringJsonUnmarshaller
.getInstance().unmarshall(context));
}
if (context.testExpression("OutputKeys", targetDepth)) {
context.nextToken();
createJobPlaylist
.setOutputKeys(new ListUnmarshaller<String>(
StringJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("HlsContentProtection", targetDepth)) {
context.nextToken();
createJobPlaylist
.setHlsContentProtection(HlsContentProtectionJsonUnmarshaller
.getInstance().unmarshall(context));
}
if (context.testExpression("PlayReadyDrm", targetDepth)) {
context.nextToken();
createJobPlaylist
.setPlayReadyDrm(PlayReadyDrmJsonUnmarshaller
.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null
|| context.getLastParsedParentElement().equals(
currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return createJobPlaylist;
}
private static CreateJobPlaylistJsonUnmarshaller instance;
public static CreateJobPlaylistJsonUnmarshaller getInstance() {
if (instance == null)
instance = new CreateJobPlaylistJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
GwtMaterialDesign/gwt-material-addins | src/main/java/gwt/material/design/incubator/client/keyboard/events/ChangeEvent.java | 1811 | /*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 - 2018 GwtMaterialDesign
* %%
* 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.
* #L%
*/
package gwt.material.design.incubator.client.keyboard.events;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HasHandlers;
//@formatter:off
/**
* Executes the callback function on input change. Returns the current input’s string.
*
* @author kevzlou7979
*/
public class ChangeEvent extends GwtEvent<ChangeEvent.ChangeHandler> {
public static final Type<ChangeHandler> TYPE = new Type<>();
private String input;
public ChangeEvent(String input) {
this.input = input;
}
public static Type<ChangeHandler> getType() {
return TYPE;
}
public static void fire(HasHandlers source, String message) {
source.fireEvent(new ChangeEvent(message));
}
@Override
public Type<ChangeHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(ChangeHandler handler) {
handler.onChange(this);
}
public String getInput() {
return input;
}
public interface ChangeHandler extends EventHandler {
void onChange(ChangeEvent event);
}
}
| apache-2.0 |
compomics/pride-asa-pipeline | pride-asa-pipeline-core/src/main/java/com/compomics/pride_asa_pipeline/core/repository/impl/webservice/WSModificationRepository.java | 1930 | package com.compomics.pride_asa_pipeline.core.repository.impl.webservice;
import com.compomics.pride_asa_pipeline.core.model.modification.source.PRIDEModificationFactory;
import com.compomics.pride_asa_pipeline.core.model.modification.impl.AsapModificationAdapter;
import com.compomics.pride_asa_pipeline.core.repository.ModificationRepository;
import com.compomics.pride_asa_pipeline.model.Modification;
import com.compomics.util.pride.PrideWebService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import uk.ac.ebi.pride.archive.web.service.model.assay.AssayDetail;
/**
*
* @author Kenneth Verheggen
*/
public class WSModificationRepository implements ModificationRepository {
private static final Logger LOGGER = Logger.getLogger(WSModificationRepository.class);
@Override
public List<Modification> getModificationsByPeptideId(long peptideId) {
throw new UnsupportedOperationException("Currently not supported through the webservice");
}
@Override
public List<Modification> getModificationsByExperimentId(String experimentId) {
LOGGER.debug("Loading modifications for experimentid " + experimentId);
List<Modification> modifications = new ArrayList<>();
AsapModificationAdapter adapter = new AsapModificationAdapter();
try {
AssayDetail assayDetail = PrideWebService.getAssayDetail(String.valueOf(experimentId));
for (String aPtmName : assayDetail.getPtmNames()) {
PRIDEModificationFactory.getInstance().getModification(adapter, aPtmName);
}
LOGGER.debug("Finished loading modifications for pride experiment with id " + experimentId);
return modifications;
} catch (IOException ex) {
LOGGER.error(ex);
}
return modifications;
}
}
| apache-2.0 |
ibissource/iaf | cmis/src/main/java/nl/nn/adapterframework/extensions/cmis/servlets/AtomPub10.java | 985 | /*
Copyright 2019 Nationale-Nederlanden
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 nl.nn.adapterframework.extensions.cmis.servlets;
import nl.nn.adapterframework.lifecycle.IbisInitializer;
@IbisInitializer
public class AtomPub10 extends AtomPubServletBase {
private static final long serialVersionUID = 1L;
@Override
public String getUrlMapping() {
return "/cmis/atompub10/*";
}
@Override
protected String getCmisVersionStr() {
return "1.0";
}
}
| apache-2.0 |
gigaSproule/platform | src/main/java/com/benjaminsproule/platform/binder/PlatformBinder.java | 315 | package com.benjaminsproule.platform.binder;
import com.benjaminsproule.platform.Properties;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
public class PlatformBinder extends AbstractBinder {
@Override
protected void configure() {
bind(Properties.class).to(Properties.class);
}
}
| apache-2.0 |
PierreLemordant/alien4cloud | alien4cloud-core/src/main/java/alien4cloud/tosca/parser/impl/base/KeyDiscriminatorParser.java | 3172 | package alien4cloud.tosca.parser.impl.base;
import java.util.Map;
import java.util.Set;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import alien4cloud.tosca.parser.INodeParser;
import alien4cloud.tosca.parser.ParsingContextExecution;
import alien4cloud.tosca.parser.ParsingError;
import alien4cloud.tosca.parser.impl.ErrorCode;
import alien4cloud.tosca.parser.mapping.DefaultParser;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* Map using a child parser based on a discriminator key (valid only for MappingNode).
*/
public class KeyDiscriminatorParser<T> extends DefaultParser<T> {
private static final String MAPPING_NODE_FALLBACK_KEY = "__";
private Map<String, INodeParser<T>> parserByExistKey;
private INodeParser<T> fallbackParser;
/**
* Create a new key discriminator parser instance.
*
* @param parserByExistKey A map of existing keys to the parser to use in case the key exists.
* @param fallbackParser The parser to use if none of the key is actually found or if the node type is not a MappingNode.
*/
public KeyDiscriminatorParser(Map<String, INodeParser<T>> parserByExistKey, INodeParser<T> fallbackParser) {
if (parserByExistKey == null) {
this.parserByExistKey = Maps.newLinkedHashMap();
} else {
this.parserByExistKey = parserByExistKey;
}
this.fallbackParser = fallbackParser;
}
@Override
public T parse(Node node, ParsingContextExecution context) {
Set<String> keySet = Sets.newHashSet();
if (node instanceof MappingNode) {
// create a set of available keys
MappingNode mappingNode = (MappingNode) node;
for (NodeTuple tuple : mappingNode.getValue()) {
keySet.add(((ScalarNode) tuple.getKeyNode()).getValue());
}
INodeParser<T> mappingNodeFallbackParser = null;
// check if one of the discriminator key exists and if so use it for parsing.
for (Map.Entry<String, INodeParser<T>> entry : parserByExistKey.entrySet()) {
if (keySet.contains(entry.getKey())) {
return entry.getValue().parse(node, context);
} else if (MAPPING_NODE_FALLBACK_KEY.equals(entry.getKey())) {
mappingNodeFallbackParser = entry.getValue();
}
}
// if not we should use the mapping node fallback parser.
if (mappingNodeFallbackParser != null) {
return mappingNodeFallbackParser.parse(node, context);
}
}
if (fallbackParser != null) {
return fallbackParser.parse(node, context);
} else {
context.getParsingErrors().add(new ParsingError(ErrorCode.UNKNWON_DISCRIMINATOR_KEY, "Invalid scalar value.", node.getStartMark(),
"Tosca type cannot be expressed with the given scalar value.", node.getEndMark(), keySet.toString()));
}
return null;
}
}
| apache-2.0 |
davyjoneswang/UsefulDemSuit | app/src/main/java/com/meituan/davy/myapplication/github/GithubActivity.java | 300 | package com.meituan.davy.myapplication.github;
import android.support.v4.app.Fragment;
import com.meituan.davy.myapplication.ContainerActivity;
public class GithubActivity extends ContainerActivity {
@Override
protected Fragment getFragment() {
return new GithubFragment();
}
} | apache-2.0 |
BUPTAnderson/apache-hive-2.1.1-src | ql/src/java/org/apache/hadoop/hive/ql/exec/spark/status/impl/JobMetricsListener.java | 3467 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.exec.spark.status.impl;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.spark.JavaSparkListener;
import org.apache.spark.executor.TaskMetrics;
import org.apache.spark.scheduler.SparkListenerJobStart;
import org.apache.spark.scheduler.SparkListenerTaskEnd;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class JobMetricsListener extends JavaSparkListener {
private static final Logger LOG = LoggerFactory.getLogger(JobMetricsListener.class);
private final Map<Integer, int[]> jobIdToStageId = Maps.newHashMap();
private final Map<Integer, Integer> stageIdToJobId = Maps.newHashMap();
private final Map<Integer, Map<String, List<TaskMetrics>>> allJobMetrics = Maps.newHashMap();
@Override
public synchronized void onTaskEnd(SparkListenerTaskEnd taskEnd) {
int stageId = taskEnd.stageId();
int stageAttemptId = taskEnd.stageAttemptId();
String stageIdentifier = stageId + "_" + stageAttemptId;
Integer jobId = stageIdToJobId.get(stageId);
if (jobId == null) {
LOG.warn("Can not find job id for stage[" + stageId + "].");
} else {
Map<String, List<TaskMetrics>> jobMetrics = allJobMetrics.get(jobId);
if (jobMetrics == null) {
jobMetrics = Maps.newHashMap();
allJobMetrics.put(jobId, jobMetrics);
}
List<TaskMetrics> stageMetrics = jobMetrics.get(stageIdentifier);
if (stageMetrics == null) {
stageMetrics = Lists.newLinkedList();
jobMetrics.put(stageIdentifier, stageMetrics);
}
stageMetrics.add(taskEnd.taskMetrics());
}
}
@Override
public synchronized void onJobStart(SparkListenerJobStart jobStart) {
int jobId = jobStart.jobId();
int size = jobStart.stageIds().size();
int[] intStageIds = new int[size];
for (int i = 0; i < size; i++) {
Integer stageId = (Integer) jobStart.stageIds().apply(i);
intStageIds[i] = stageId;
stageIdToJobId.put(stageId, jobId);
}
jobIdToStageId.put(jobId, intStageIds);
}
public synchronized Map<String, List<TaskMetrics>> getJobMetric(int jobId) {
return allJobMetrics.get(jobId);
}
public synchronized void cleanup(int jobId) {
allJobMetrics.remove(jobId);
jobIdToStageId.remove(jobId);
Iterator<Map.Entry<Integer, Integer>> iterator = stageIdToJobId.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, Integer> entry = iterator.next();
if (entry.getValue() == jobId) {
iterator.remove();
}
}
}
}
| apache-2.0 |
eddumelendez/spring-security | config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java | 16385 | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestRule;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.request.async.SecurityContextCallableProcessingInterceptor;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.accept.ContentNegotiationStrategy;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
import org.springframework.web.context.request.async.CallableProcessingInterceptor;
import org.springframework.web.context.request.async.WebAsyncManager;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Tests for {@link WebSecurityConfigurerAdapter}.
*
* @author Rob Winch
* @author Joe Grandja
*/
@PrepareForTest({WebAsyncManager.class})
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({ "org.w3c.dom.*", "org.xml.sax.*", "org.apache.xerces.*", "javax.xml.parsers.*", "javax.xml.transform.*" })
public class WebSecurityConfigurerAdapterTests {
@Rule
public final SpringTestRule spring = new SpringTestRule();
@Autowired
private MockMvc mockMvc;
@Test
public void loadConfigWhenRequestSecureThenDefaultSecurityHeadersReturned() throws Exception {
this.spring.register(HeadersArePopulatedByDefaultConfig.class).autowire();
this.mockMvc.perform(get("/").secure(true))
.andExpect(header().string("X-Content-Type-Options", "nosniff"))
.andExpect(header().string("X-Frame-Options", "DENY"))
.andExpect(header().string("Strict-Transport-Security", "max-age=31536000 ; includeSubDomains"))
.andExpect(header().string("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"))
.andExpect(header().string("Pragma", "no-cache"))
.andExpect(header().string("Expires", "0"))
.andExpect(header().string("X-XSS-Protection", "1; mode=block"));
}
@EnableWebSecurity
static class HeadersArePopulatedByDefaultConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
}
}
@Test
public void loadConfigWhenDefaultConfigThenWebAsyncManagerIntegrationFilterAdded() throws Exception {
this.spring.register(WebAsyncPopulatedByDefaultConfig.class).autowire();
WebAsyncManager webAsyncManager = mock(WebAsyncManager.class);
this.mockMvc.perform(get("/").requestAttr(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, webAsyncManager));
ArgumentCaptor<CallableProcessingInterceptor> callableProcessingInterceptorArgCaptor =
ArgumentCaptor.forClass(CallableProcessingInterceptor.class);
verify(webAsyncManager, atLeastOnce()).registerCallableInterceptor(any(), callableProcessingInterceptorArgCaptor.capture());
CallableProcessingInterceptor callableProcessingInterceptor =
callableProcessingInterceptorArgCaptor.getAllValues().stream()
.filter(e -> SecurityContextCallableProcessingInterceptor.class.isAssignableFrom(e.getClass()))
.findFirst()
.orElse(null);
assertThat(callableProcessingInterceptor).isNotNull();
}
@EnableWebSecurity
static class WebAsyncPopulatedByDefaultConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
}
}
@Test
public void loadConfigWhenRequestAuthenticateThenAuthenticationEventPublished() throws Exception {
this.spring.register(InMemoryAuthWithWebSecurityConfigurerAdapter.class).autowire();
this.mockMvc.perform(formLogin())
.andExpect(status().is3xxRedirection());
assertThat(InMemoryAuthWithWebSecurityConfigurerAdapter.EVENTS).isNotEmpty();
assertThat(InMemoryAuthWithWebSecurityConfigurerAdapter.EVENTS).hasSize(1);
}
@EnableWebSecurity
static class InMemoryAuthWithWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter
implements ApplicationListener<AuthenticationSuccessEvent> {
static List<AuthenticationSuccessEvent> EVENTS = new ArrayList<>();
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
}
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
EVENTS.add(event);
}
}
@Test
public void loadConfigWhenInMemoryConfigureProtectedThenPasswordUpgraded() throws Exception {
this.spring.register(InMemoryConfigureProtectedConfig.class).autowire();
this.mockMvc.perform(formLogin())
.andExpect(status().is3xxRedirection());
UserDetailsService uds = this.spring.getContext()
.getBean(UserDetailsService.class);
assertThat(uds.loadUserByUsername("user").getPassword()).startsWith("{bcrypt}");
}
@EnableWebSecurity
static class InMemoryConfigureProtectedConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
}
@Override
@Bean
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
}
@Test
public void loadConfigWhenInMemoryConfigureGlobalThenPasswordUpgraded() throws Exception {
this.spring.register(InMemoryConfigureGlobalConfig.class).autowire();
this.mockMvc.perform(formLogin())
.andExpect(status().is3xxRedirection());
UserDetailsService uds = this.spring.getContext()
.getBean(UserDetailsService.class);
assertThat(uds.loadUserByUsername("user").getPassword()).startsWith("{bcrypt}");
}
@EnableWebSecurity
static class InMemoryConfigureGlobalConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
}
@Override
@Bean
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
}
@Test
public void loadConfigWhenCustomContentNegotiationStrategyBeanThenOverridesDefault() throws Exception {
OverrideContentNegotiationStrategySharedObjectConfig.CONTENT_NEGOTIATION_STRATEGY_BEAN = mock(ContentNegotiationStrategy.class);
this.spring.register(OverrideContentNegotiationStrategySharedObjectConfig.class).autowire();
OverrideContentNegotiationStrategySharedObjectConfig securityConfig =
this.spring.getContext().getBean(OverrideContentNegotiationStrategySharedObjectConfig.class);
assertThat(securityConfig.contentNegotiationStrategySharedObject).isNotNull();
assertThat(securityConfig.contentNegotiationStrategySharedObject)
.isSameAs(OverrideContentNegotiationStrategySharedObjectConfig.CONTENT_NEGOTIATION_STRATEGY_BEAN);
}
@EnableWebSecurity
static class OverrideContentNegotiationStrategySharedObjectConfig extends WebSecurityConfigurerAdapter {
static ContentNegotiationStrategy CONTENT_NEGOTIATION_STRATEGY_BEAN;
private ContentNegotiationStrategy contentNegotiationStrategySharedObject;
@Bean
public ContentNegotiationStrategy contentNegotiationStrategy() {
return CONTENT_NEGOTIATION_STRATEGY_BEAN;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
this.contentNegotiationStrategySharedObject = http.getSharedObject(ContentNegotiationStrategy.class);
super.configure(http);
}
}
@Test
public void loadConfigWhenDefaultContentNegotiationStrategyThenHeaderContentNegotiationStrategy() throws Exception {
this.spring.register(ContentNegotiationStrategyDefaultSharedObjectConfig.class).autowire();
ContentNegotiationStrategyDefaultSharedObjectConfig securityConfig =
this.spring.getContext().getBean(ContentNegotiationStrategyDefaultSharedObjectConfig.class);
assertThat(securityConfig.contentNegotiationStrategySharedObject).isNotNull();
assertThat(securityConfig.contentNegotiationStrategySharedObject).isInstanceOf(HeaderContentNegotiationStrategy.class);
}
@EnableWebSecurity
static class ContentNegotiationStrategyDefaultSharedObjectConfig extends WebSecurityConfigurerAdapter {
private ContentNegotiationStrategy contentNegotiationStrategySharedObject;
@Override
protected void configure(HttpSecurity http) throws Exception {
this.contentNegotiationStrategySharedObject = http.getSharedObject(ContentNegotiationStrategy.class);
super.configure(http);
}
}
@Test
public void loadConfigWhenUserDetailsServiceHasCircularReferenceThenStillLoads() throws Exception {
this.spring.register(RequiresUserDetailsServiceConfig.class, UserDetailsServiceConfig.class).autowire();
MyFilter myFilter = this.spring.getContext().getBean(MyFilter.class);
Throwable thrown = catchThrowable(() -> myFilter.userDetailsService.loadUserByUsername("user") );
assertThat(thrown).isNull();
thrown = catchThrowable(() -> myFilter.userDetailsService.loadUserByUsername("admin") );
assertThat(thrown).isInstanceOf(UsernameNotFoundException.class);
}
@Configuration
static class RequiresUserDetailsServiceConfig {
@Bean
public MyFilter myFilter(UserDetailsService userDetailsService) {
return new MyFilter(userDetailsService);
}
}
@EnableWebSecurity
static class UserDetailsServiceConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyFilter myFilter;
@Bean
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Override
public void configure(HttpSecurity http) {
http.addFilterBefore(this.myFilter, UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
}
}
static class MyFilter extends OncePerRequestFilter {
private UserDetailsService userDetailsService;
MyFilter(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
filterChain.doFilter(request, response);
}
}
// SEC-2274: WebSecurityConfigurer adds ApplicationContext as a shared object
@Test
public void loadConfigWhenSharedObjectsCreatedThenApplicationContextAdded() throws Exception {
this.spring.register(ApplicationContextSharedObjectConfig.class).autowire();
ApplicationContextSharedObjectConfig securityConfig =
this.spring.getContext().getBean(ApplicationContextSharedObjectConfig.class);
assertThat(securityConfig.applicationContextSharedObject).isNotNull();
assertThat(securityConfig.applicationContextSharedObject).isSameAs(this.spring.getContext());
}
@EnableWebSecurity
static class ApplicationContextSharedObjectConfig extends WebSecurityConfigurerAdapter {
private ApplicationContext applicationContextSharedObject;
@Override
protected void configure(HttpSecurity http) throws Exception {
this.applicationContextSharedObject = http.getSharedObject(ApplicationContext.class);
super.configure(http);
}
}
@Test
public void loadConfigWhenCustomAuthenticationTrustResolverBeanThenOverridesDefault() throws Exception {
CustomTrustResolverConfig.AUTHENTICATION_TRUST_RESOLVER_BEAN = mock(AuthenticationTrustResolver.class);
this.spring.register(CustomTrustResolverConfig.class).autowire();
CustomTrustResolverConfig securityConfig =
this.spring.getContext().getBean(CustomTrustResolverConfig.class);
assertThat(securityConfig.authenticationTrustResolverSharedObject).isNotNull();
assertThat(securityConfig.authenticationTrustResolverSharedObject)
.isSameAs(CustomTrustResolverConfig.AUTHENTICATION_TRUST_RESOLVER_BEAN);
}
@EnableWebSecurity
static class CustomTrustResolverConfig extends WebSecurityConfigurerAdapter {
static AuthenticationTrustResolver AUTHENTICATION_TRUST_RESOLVER_BEAN;
private AuthenticationTrustResolver authenticationTrustResolverSharedObject;
@Bean
public AuthenticationTrustResolver authenticationTrustResolver() {
return AUTHENTICATION_TRUST_RESOLVER_BEAN;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
this.authenticationTrustResolverSharedObject = http.getSharedObject(AuthenticationTrustResolver.class);
super.configure(http);
}
}
@Test
public void compareOrderWebSecurityConfigurerAdapterWhenLowestOrderToDefaultOrderThenGreaterThanZero() throws Exception {
AnnotationAwareOrderComparator comparator = new AnnotationAwareOrderComparator();
assertThat(comparator.compare(
new LowestPriorityWebSecurityConfig(),
new DefaultOrderWebSecurityConfig())).isGreaterThan(0);
}
static class DefaultOrderWebSecurityConfig extends WebSecurityConfigurerAdapter {
}
@Order
static class LowestPriorityWebSecurityConfig extends WebSecurityConfigurerAdapter {
}
}
| apache-2.0 |
TesisTarjetasMejorar/TarjetasISIS | dom/src/main/java/servicios/validacion/RegexValidation.java | 1016 |
package servicios.validacion;
public final class RegexValidation {
public static final class ValidaNombres {
private ValidaNombres() {
}
// public static final String INICIALES = "[a-z,A-Z,ñ,Ñ]{2}$+";
public static final String NOMBRE = "[A-Z]+[a-z,ñ]*+[ ]+[A-Z]+[a-z,ñ]*";
}
public static final class ValidaTel {
private ValidaTel() {
}
public static final String NUMEROTEL = "[+]?[0-9]{3}+[-]+[0-9]{7}";
}
public static final class ValidaMail {
private ValidaMail() {
}
public static final String EMAIL = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
}
public static final class ValidaDireccion{
private ValidaDireccion() {
}
public static final String DIRECCION = "^[_A-Za-z-\\+]+(\\ [0-9-]+)$";
}
public static final class ValidaPalabra{
private ValidaPalabra() {
}
public static final String PALABRA = "[a-zA-Z]*$";
public static final String PALABRAINICIALMAYUSCULA = "[A-Z]+[a-z]*$";
}
} | apache-2.0 |
ay65535/hbase-0.94.0 | src/main/java/org/apache/hadoop/hbase/io/hfile/HFileWriterV2.java | 16662 | /*
* Copyright 2011 The Apache Software Foundation
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.io.hfile;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.KeyValue.KeyComparator;
import org.apache.hadoop.hbase.io.hfile.HFile.Writer;
import org.apache.hadoop.hbase.io.hfile.HFileBlock.BlockWritable;
import org.apache.hadoop.hbase.regionserver.metrics.SchemaMetrics;
import org.apache.hadoop.hbase.util.ChecksumType;
import org.apache.hadoop.hbase.util.BloomFilterWriter;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
/**
* Writes HFile format version 2.
*/
public class HFileWriterV2 extends AbstractHFileWriter {
static final Log LOG = LogFactory.getLog(HFileWriterV2.class);
/** Max memstore (mvcc) timestamp in FileInfo */
public static final byte [] MAX_MEMSTORE_TS_KEY =
Bytes.toBytes("MAX_MEMSTORE_TS_KEY");
/** KeyValue version in FileInfo */
public static final byte [] KEY_VALUE_VERSION =
Bytes.toBytes("KEY_VALUE_VERSION");
/** Version for KeyValue which includes memstore timestamp */
public static final int KEY_VALUE_VER_WITH_MEMSTORE = 1;
/** Inline block writers for multi-level block index and compound Blooms. */
private List<InlineBlockWriter> inlineBlockWriters =
new ArrayList<InlineBlockWriter>();
/** Unified version 2 block writer */
private HFileBlock.Writer fsBlockWriter;
private HFileBlockIndex.BlockIndexWriter dataBlockIndexWriter;
private HFileBlockIndex.BlockIndexWriter metaBlockIndexWriter;
/** The offset of the first data block or -1 if the file is empty. */
private long firstDataBlockOffset = -1;
/** The offset of the last data block or 0 if the file is empty. */
private long lastDataBlockOffset;
/** Additional data items to be written to the "load-on-open" section. */
private List<BlockWritable> additionalLoadOnOpenData =
new ArrayList<BlockWritable>();
/** Checksum related settings */
private ChecksumType checksumType = HFile.DEFAULT_CHECKSUM_TYPE;
private int bytesPerChecksum = HFile.DEFAULT_BYTES_PER_CHECKSUM;
private final boolean includeMemstoreTS = true;
private long maxMemstoreTS = 0;
static class WriterFactoryV2 extends HFile.WriterFactory {
WriterFactoryV2(Configuration conf, CacheConfig cacheConf) {
super(conf, cacheConf);
}
@Override
public Writer createWriter(FileSystem fs, Path path,
FSDataOutputStream ostream, int blockSize,
Compression.Algorithm compress, HFileDataBlockEncoder blockEncoder,
final KeyComparator comparator, final ChecksumType checksumType,
final int bytesPerChecksum) throws IOException {
return new HFileWriterV2(conf, cacheConf, fs, path, ostream, blockSize,
compress, blockEncoder, comparator, checksumType, bytesPerChecksum);
}
}
/** Constructor that takes a path, creates and closes the output stream. */
public HFileWriterV2(Configuration conf, CacheConfig cacheConf,
FileSystem fs, Path path, FSDataOutputStream ostream, int blockSize,
Compression.Algorithm compressAlgo, HFileDataBlockEncoder blockEncoder,
final KeyComparator comparator, final ChecksumType checksumType,
final int bytesPerChecksum) throws IOException {
super(cacheConf,
ostream == null ? createOutputStream(conf, fs, path) : ostream,
path, blockSize, compressAlgo, blockEncoder, comparator);
SchemaMetrics.configureGlobally(conf);
this.checksumType = checksumType;
this.bytesPerChecksum = bytesPerChecksum;
finishInit(conf);
}
/** Additional initialization steps */
private void finishInit(final Configuration conf) {
if (fsBlockWriter != null)
throw new IllegalStateException("finishInit called twice");
// HFile filesystem-level (non-caching) block writer
fsBlockWriter = new HFileBlock.Writer(compressAlgo, blockEncoder,
includeMemstoreTS, checksumType, bytesPerChecksum);
// Data block index writer
boolean cacheIndexesOnWrite = cacheConf.shouldCacheIndexesOnWrite();
dataBlockIndexWriter = new HFileBlockIndex.BlockIndexWriter(fsBlockWriter,
cacheIndexesOnWrite ? cacheConf.getBlockCache(): null,
cacheIndexesOnWrite ? name : null);
dataBlockIndexWriter.setMaxChunkSize(
HFileBlockIndex.getMaxChunkSize(conf));
inlineBlockWriters.add(dataBlockIndexWriter);
// Meta data block index writer
metaBlockIndexWriter = new HFileBlockIndex.BlockIndexWriter();
LOG.debug("Initialized with " + cacheConf);
if (isSchemaConfigured()) {
schemaConfigurationChanged();
}
}
@Override
protected void schemaConfigurationChanged() {
passSchemaMetricsTo(dataBlockIndexWriter);
passSchemaMetricsTo(metaBlockIndexWriter);
}
/**
* At a block boundary, write all the inline blocks and opens new block.
*
* @throws IOException
*/
private void checkBlockBoundary() throws IOException {
if (fsBlockWriter.blockSizeWritten() < blockSize)
return;
finishBlock();
writeInlineBlocks(false);
newBlock();
}
/** Clean up the current block */
private void finishBlock() throws IOException {
if (!fsBlockWriter.isWriting() || fsBlockWriter.blockSizeWritten() == 0)
return;
long startTimeNs = System.nanoTime();
// Update the first data block offset for scanning.
if (firstDataBlockOffset == -1) {
firstDataBlockOffset = outputStream.getPos();
}
// Update the last data block offset
lastDataBlockOffset = outputStream.getPos();
fsBlockWriter.writeHeaderAndData(outputStream);
int onDiskSize = fsBlockWriter.getOnDiskSizeWithHeader();
dataBlockIndexWriter.addEntry(firstKeyInBlock, lastDataBlockOffset,
onDiskSize);
totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader();
HFile.offerWriteLatency(System.nanoTime() - startTimeNs);
if (cacheConf.shouldCacheDataOnWrite()) {
doCacheOnWrite(lastDataBlockOffset);
}
}
/** Gives inline block writers an opportunity to contribute blocks. */
private void writeInlineBlocks(boolean closing) throws IOException {
for (InlineBlockWriter ibw : inlineBlockWriters) {
while (ibw.shouldWriteBlock(closing)) {
long offset = outputStream.getPos();
boolean cacheThisBlock = ibw.cacheOnWrite();
ibw.writeInlineBlock(fsBlockWriter.startWriting(
ibw.getInlineBlockType()));
fsBlockWriter.writeHeaderAndData(outputStream);
ibw.blockWritten(offset, fsBlockWriter.getOnDiskSizeWithHeader(),
fsBlockWriter.getUncompressedSizeWithoutHeader());
totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader();
if (cacheThisBlock) {
doCacheOnWrite(offset);
}
}
}
}
/**
* Caches the last written HFile block.
* @param offset the offset of the block we want to cache. Used to determine
* the cache key.
*/
private void doCacheOnWrite(long offset) {
// We don't cache-on-write data blocks on compaction, so assume this is not
// a compaction.
final boolean isCompaction = false;
HFileBlock cacheFormatBlock = blockEncoder.diskToCacheFormat(
fsBlockWriter.getBlockForCaching(), isCompaction);
passSchemaMetricsTo(cacheFormatBlock);
cacheConf.getBlockCache().cacheBlock(
new BlockCacheKey(name, offset, blockEncoder.getEncodingInCache(),
cacheFormatBlock.getBlockType()), cacheFormatBlock);
}
/**
* Ready a new block for writing.
*
* @throws IOException
*/
private void newBlock() throws IOException {
// This is where the next block begins.
fsBlockWriter.startWriting(BlockType.DATA);
firstKeyInBlock = null;
}
/**
* Add a meta block to the end of the file. Call before close(). Metadata
* blocks are expensive. Fill one with a bunch of serialized data rather than
* do a metadata block per metadata instance. If metadata is small, consider
* adding to file info using {@link #appendFileInfo(byte[], byte[])}
*
* @param metaBlockName
* name of the block
* @param content
* will call readFields to get data later (DO NOT REUSE)
*/
@Override
public void appendMetaBlock(String metaBlockName, Writable content) {
byte[] key = Bytes.toBytes(metaBlockName);
int i;
for (i = 0; i < metaNames.size(); ++i) {
// stop when the current key is greater than our own
byte[] cur = metaNames.get(i);
if (Bytes.BYTES_RAWCOMPARATOR.compare(cur, 0, cur.length, key, 0,
key.length) > 0) {
break;
}
}
metaNames.add(i, key);
metaData.add(i, content);
}
/**
* Add key/value to file. Keys must be added in an order that agrees with the
* Comparator passed on construction.
*
* @param kv
* KeyValue to add. Cannot be empty nor null.
* @throws IOException
*/
@Override
public void append(final KeyValue kv) throws IOException {
append(kv.getMemstoreTS(), kv.getBuffer(), kv.getKeyOffset(), kv.getKeyLength(),
kv.getBuffer(), kv.getValueOffset(), kv.getValueLength());
this.maxMemstoreTS = Math.max(this.maxMemstoreTS, kv.getMemstoreTS());
}
/**
* Add key/value to file. Keys must be added in an order that agrees with the
* Comparator passed on construction.
*
* @param key
* Key to add. Cannot be empty nor null.
* @param value
* Value to add. Cannot be empty nor null.
* @throws IOException
*/
@Override
public void append(final byte[] key, final byte[] value) throws IOException {
append(0, key, 0, key.length, value, 0, value.length);
}
/**
* Add key/value to file. Keys must be added in an order that agrees with the
* Comparator passed on construction.
*
* @param key
* @param koffset
* @param klength
* @param value
* @param voffset
* @param vlength
* @throws IOException
*/
private void append(final long memstoreTS, final byte[] key, final int koffset, final int klength,
final byte[] value, final int voffset, final int vlength)
throws IOException {
boolean dupKey = checkKey(key, koffset, klength);
checkValue(value, voffset, vlength);
if (!dupKey) {
checkBlockBoundary();
}
if (!fsBlockWriter.isWriting())
newBlock();
// Write length of key and value and then actual key and value bytes.
// Additionally, we may also write down the memstoreTS.
{
DataOutputStream out = fsBlockWriter.getUserDataStream();
out.writeInt(klength);
totalKeyLength += klength;
out.writeInt(vlength);
totalValueLength += vlength;
out.write(key, koffset, klength);
out.write(value, voffset, vlength);
if (this.includeMemstoreTS) {
WritableUtils.writeVLong(out, memstoreTS);
}
}
// Are we the first key in this block?
if (firstKeyInBlock == null) {
// Copy the key.
firstKeyInBlock = new byte[klength];
System.arraycopy(key, koffset, firstKeyInBlock, 0, klength);
}
lastKeyBuffer = key;
lastKeyOffset = koffset;
lastKeyLength = klength;
entryCount++;
}
@Override
public void close() throws IOException {
if (outputStream == null) {
return;
}
// Write out the end of the data blocks, then write meta data blocks.
// followed by fileinfo, data block index and meta block index.
finishBlock();
writeInlineBlocks(true);
FixedFileTrailer trailer = new FixedFileTrailer(2,
HFileReaderV2.MAX_MINOR_VERSION);
// Write out the metadata blocks if any.
if (!metaNames.isEmpty()) {
for (int i = 0; i < metaNames.size(); ++i) {
// store the beginning offset
long offset = outputStream.getPos();
// write the metadata content
DataOutputStream dos = fsBlockWriter.startWriting(BlockType.META);
metaData.get(i).write(dos);
fsBlockWriter.writeHeaderAndData(outputStream);
totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader();
// Add the new meta block to the meta index.
metaBlockIndexWriter.addEntry(metaNames.get(i), offset,
fsBlockWriter.getOnDiskSizeWithHeader());
}
}
// Load-on-open section.
// Data block index.
//
// In version 2, this section of the file starts with the root level data
// block index. We call a function that writes intermediate-level blocks
// first, then root level, and returns the offset of the root level block
// index.
long rootIndexOffset = dataBlockIndexWriter.writeIndexBlocks(outputStream);
trailer.setLoadOnOpenOffset(rootIndexOffset);
// Meta block index.
metaBlockIndexWriter.writeSingleLevelIndex(fsBlockWriter.startWriting(
BlockType.ROOT_INDEX), "meta");
fsBlockWriter.writeHeaderAndData(outputStream);
totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader();
if (this.includeMemstoreTS) {
appendFileInfo(MAX_MEMSTORE_TS_KEY, Bytes.toBytes(maxMemstoreTS));
appendFileInfo(KEY_VALUE_VERSION, Bytes.toBytes(KEY_VALUE_VER_WITH_MEMSTORE));
}
// File info
writeFileInfo(trailer, fsBlockWriter.startWriting(BlockType.FILE_INFO));
fsBlockWriter.writeHeaderAndData(outputStream);
totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader();
// Load-on-open data supplied by higher levels, e.g. Bloom filters.
for (BlockWritable w : additionalLoadOnOpenData){
fsBlockWriter.writeBlock(w, outputStream);
totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader();
}
// Now finish off the trailer.
trailer.setNumDataIndexLevels(dataBlockIndexWriter.getNumLevels());
trailer.setUncompressedDataIndexSize(
dataBlockIndexWriter.getTotalUncompressedSize());
trailer.setFirstDataBlockOffset(firstDataBlockOffset);
trailer.setLastDataBlockOffset(lastDataBlockOffset);
trailer.setComparatorClass(comparator.getClass());
trailer.setDataIndexCount(dataBlockIndexWriter.getNumRootEntries());
finishClose(trailer);
fsBlockWriter.releaseCompressor();
}
@Override
public void addInlineBlockWriter(InlineBlockWriter ibw) {
inlineBlockWriters.add(ibw);
}
@Override
public void addGeneralBloomFilter(final BloomFilterWriter bfw) {
this.addBloomFilter(bfw, BlockType.GENERAL_BLOOM_META);
}
@Override
public void addDeleteFamilyBloomFilter(final BloomFilterWriter bfw) {
this.addBloomFilter(bfw, BlockType.DELETE_FAMILY_BLOOM_META);
}
private void addBloomFilter(final BloomFilterWriter bfw,
final BlockType blockType) {
if (bfw.getKeyCount() <= 0)
return;
if (blockType != BlockType.GENERAL_BLOOM_META &&
blockType != BlockType.DELETE_FAMILY_BLOOM_META) {
throw new RuntimeException("Block Type: " + blockType.toString() +
"is not supported");
}
additionalLoadOnOpenData.add(new BlockWritable() {
@Override
public BlockType getBlockType() {
return blockType;
}
@Override
public void writeToBlock(DataOutput out) throws IOException {
bfw.getMetaWriter().write(out);
Writable dataWriter = bfw.getDataWriter();
if (dataWriter != null)
dataWriter.write(out);
}
});
}
}
| apache-2.0 |
bshp/midPoint | model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/OperationFilterHelper.java | 1574 | /*
* Copyright (c) 2010-2013 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.notifications.impl.helpers;
import com.evolveum.midpoint.notifications.api.events.Event;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.EventHandlerType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.EventOperationType;
import org.springframework.stereotype.Component;
/**
* @author mederly
*/
@Component
public class OperationFilterHelper extends BaseHelper {
private static final Trace LOGGER = TraceManager.getTrace(OperationFilterHelper.class);
public boolean processEvent(Event event, EventHandlerType eventHandlerType) {
if (eventHandlerType.getOperation().isEmpty()) {
return true;
}
logStart(LOGGER, event, eventHandlerType, eventHandlerType.getOperation());
boolean retval = false;
for (EventOperationType eventOperationType : eventHandlerType.getOperation()) {
if (eventOperationType == null) {
LOGGER.warn("Filtering on null eventOperationType; filter = " + eventHandlerType);
} else if (event.isOperationType(eventOperationType)) {
retval = true;
break;
}
}
logEnd(LOGGER, event, eventHandlerType, retval);
return retval;
}
}
| apache-2.0 |
waans11/incubator-asterixdb | hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterTuplesDataflowHelperFactory.java | 4634 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.hyracks.storage.am.lsm.rtree.dataflow;
import java.util.Map;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import org.apache.hyracks.api.dataflow.value.ILinearizeComparatorFactory;
import org.apache.hyracks.api.dataflow.value.ITypeTraits;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.storage.am.common.api.IPrimitiveValueProviderFactory;
import org.apache.hyracks.storage.am.common.dataflow.IIndexOperatorDescriptor;
import org.apache.hyracks.storage.am.common.dataflow.IndexDataflowHelper;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationCallbackFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationSchedulerProvider;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMMergePolicyFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMOperationTrackerFactory;
import org.apache.hyracks.storage.am.lsm.common.api.IVirtualBufferCacheProvider;
import org.apache.hyracks.storage.am.lsm.common.dataflow.AbstractLSMIndexDataflowHelperFactory;
import org.apache.hyracks.storage.am.rtree.frames.RTreePolicyType;
public class LSMRTreeWithAntiMatterTuplesDataflowHelperFactory extends AbstractLSMIndexDataflowHelperFactory {
private static final long serialVersionUID = 1L;
private final IBinaryComparatorFactory[] btreeComparatorFactories;
private final IPrimitiveValueProviderFactory[] valueProviderFactories;
private final RTreePolicyType rtreePolicyType;
private final ILinearizeComparatorFactory linearizeCmpFactory;
private final int[] rtreeFields;
protected final boolean isPointMBR;
public LSMRTreeWithAntiMatterTuplesDataflowHelperFactory(IPrimitiveValueProviderFactory[] valueProviderFactories,
RTreePolicyType rtreePolicyType, IBinaryComparatorFactory[] btreeComparatorFactories,
IVirtualBufferCacheProvider virtualBufferCacheProvider, ILSMMergePolicyFactory mergePolicyFactory,
Map<String, String> mergePolicyProperties, ILSMOperationTrackerFactory opTrackerFactory,
ILSMIOOperationSchedulerProvider ioSchedulerProvider, ILSMIOOperationCallbackFactory ioOpCallbackFactory,
ILinearizeComparatorFactory linearizeCmpFactory, int[] rtreeFields, ITypeTraits[] filterTypeTraits,
IBinaryComparatorFactory[] filterCmpFactories, int[] filterFields, boolean durable, boolean isPointMBR) {
super(virtualBufferCacheProvider, mergePolicyFactory, mergePolicyProperties, opTrackerFactory,
ioSchedulerProvider, ioOpCallbackFactory, 1.0, filterTypeTraits, filterCmpFactories, filterFields,
durable);
this.btreeComparatorFactories = btreeComparatorFactories;
this.valueProviderFactories = valueProviderFactories;
this.rtreePolicyType = rtreePolicyType;
this.linearizeCmpFactory = linearizeCmpFactory;
this.rtreeFields = rtreeFields;
this.isPointMBR = isPointMBR;
}
@Override
public IndexDataflowHelper createIndexDataflowHelper(IIndexOperatorDescriptor opDesc, IHyracksTaskContext ctx,
int partition) throws HyracksDataException {
return new LSMRTreeWithAntiMatterTuplesDataflowHelper(opDesc, ctx, partition,
virtualBufferCacheProvider.getVirtualBufferCaches(ctx, opDesc.getFileSplitProvider()),
btreeComparatorFactories, valueProviderFactories, rtreePolicyType,
mergePolicyFactory.createMergePolicy(mergePolicyProperties, ctx), opTrackerFactory,
ioSchedulerProvider.getIOScheduler(ctx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields,
filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR);
}
}
| apache-2.0 |
soumitrak/mmap-ds | src/main/java/sk/util/MUHSetLong.java | 3408 | package sk.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sk.mmap.Constants;
import sk.mmap.IUnsafeAllocator;
import java.util.Map;
import java.util.HashMap;
// Memory mapped hash set of Long
public class MUHSetLong {
private static final Logger logger = LoggerFactory.getLogger(MUHSetLong.class);
private final int numBuckets;
private final IUnsafeAllocator allocator;
private final MBUArrayListL buckets;
// TODO: Implement rehashing when table is full to avoid adding lots of elements in list
public MUHSetLong(final IUnsafeAllocator allocator, final int numBuckets) {
this.allocator = allocator;
this.numBuckets = numBuckets;
buckets = new MBUArrayListL(allocator, numBuckets);
// Initialize all buckets with NULL
for (int i = 0; i < numBuckets; i++) {
buckets.add(Constants.NULL);
}
}
public void debug() {
logger.debug("Printing details of Hash table");
final Map<Integer, Integer> elems2buckets = new HashMap<>();
for (int i = 0; i < buckets.size(); i++) {
final long list = buckets.get(i);
int elems = 0;
if (list != Constants.NULL) {
long node = MULinkedListL.getFirst(allocator, list);
// If list is non-NULL, search in the MULinkedListL
while (node != Constants.NULL) {
++elems;
node = MULinkedListL.getNext(allocator, node);
}
/*
if (elems > 1) {
logger.debug("Bucket " + i + " has " + elems + " elements");
}
*/
}
if (elems2buckets.containsKey(elems)) {
elems2buckets.put(elems, elems2buckets.get(elems) + 1);
} else {
elems2buckets.put(elems, 1);
}
}
elems2buckets.forEach((key, val) -> {
logger.debug(val + " buckets have " + key + " elements");
});
logger.debug("End printing details of Hash table");
}
private long getBucket(final long key, final boolean create) {
final long hash = JenkinsHash.hash64(key);
final int index = (int)(hash % numBuckets);
if (create) {
// logger.debug("Key " + key + " : Hash " + hash + " : index " + index);
}
long list = buckets.get(index);
if (create && list == Constants.NULL) {
list = MULinkedListL.create(allocator);
buckets.put(index, list);
}
return list;
}
public void put(final long value) {
long list = getBucket(value, true);
MULinkedListL.add(allocator, list, value);
}
public long get(final long key) {
long value = Constants.NULL;
final long list = getBucket(key, false);
if (list != Constants.NULL) {
long node = MULinkedListL.getFirst(allocator, list);
// If list is non-NULL, search in the MULinkedListL
while (node != Constants.NULL) {
final long tmp = MULinkedListL.getL(allocator, node);
if (tmp == key) {
value = tmp;
break;
}
node = MULinkedListL.getNext(allocator, node);
}
}
return value;
}
}
| apache-2.0 |
olivergierke/sos | 00-monolith/src/main/java/example/sos/monolith/MonolithApplication.java | 1646 | /*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.sos.monolith;
import example.sos.monolith.catalog.Catalog;
import example.sos.monolith.catalog.Product;
import example.sos.monolith.inventory.Inventory;
import example.sos.monolith.orders.OrderManager;
import java.math.BigDecimal;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/**
* @author Oliver Gierke
*/
@SpringBootApplication
public class MonolithApplication {
public static void main(String... args) {
SpringApplication.run(MonolithApplication.class, args);
}
@Bean
CommandLineRunner onStartup(Catalog catalog, Inventory inventory, OrderManager orders) {
return args -> {
Product iPad = catalog.save(new Product("iPad", new BigDecimal(699.99)));
Product iPhone = catalog.save(new Product("iPhone", new BigDecimal(899.99)));
inventory.addItemFor(iPad, 10);
inventory.addItemFor(iPhone, 15);
};
}
}
| apache-2.0 |
meringlab/stringdb-psicquic | src/main/java/org/string_db/psicquic/SearchServer.java | 1651 | /*
* Copyright 2014 University of Zürich, SIB, and others.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.string_db.psicquic;
import org.hupo.psi.calimocho.model.Row;
/**
* @author Milan Simonovic <milan.simonovic@imls.uzh.ch>
*/
public interface SearchServer {
/**
* Add a new interaction to the index; might not be visible for search
* before {@link #commit(boolean)} is called.
*
* @param row
* @throws RuntimeException
*/
void add(Row row) throws RuntimeException;
/**
* Write all previously added interactions to the index.
*
* @param reopenSearcher true to wait to reopen searcher
* @throws RuntimeException
*/
void commit(boolean reopenSearcher) throws RuntimeException;
/**
* @return number of indexed documents
*/
Long countIndexedDocuments();
/**
* remove all documents from the index
*
* @throws RuntimeException
*/
void deleteAll() throws RuntimeException;
}
| apache-2.0 |
bounswe/bounswe2016group7 | TheFirst/app/src/main/java/com/example/denizalp/thefirst/TopicAdapter.java | 2061 | package com.example.denizalp.thefirst;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.bounswe.group7.model.Topics;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by denizalp on 18/12/16.
*/
public class TopicAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<Topics> mTopicList;
private String currentToken;
private Activity activity;
public TopicAdapter(Activity activity, List<Topics> topicList, String currentToken){
this.activity = activity;
mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mTopicList = topicList;
this.currentToken = currentToken;
}
@Override
public int getCount() {
return mTopicList.size();
}
@Override
public Object getItem(int position) {
return mTopicList.get(position);
}
@Override
public long getItemId(int position) {
return mTopicList.get(position).getTopicId();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View singleTopicView = mInflater.inflate(R.layout.activity_single_topic, null);
Topics topic = mTopicList.get(position);
TextView textView = (TextView) singleTopicView.findViewById(R.id.textView8);
Button button = (Button) singleTopicView.findViewById(R.id.button38);
Intent toTopic = new Intent(activity, ShowTopicPage.class);
textView.setText(topic.getHeader());
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toTopic.putExtra("topicId",topic.getTopicId());
activity.startActivity(toTopic);
}
});
return singleTopicView;
}
}
| apache-2.0 |
tetigi/toucan | java/src/utils/UnorderedTree.java | 2232 | package utils;
import java.util.ArrayList;
import java.util.List;
/**
* Utility tree class, where the children are not necessarily ordered in any
* particular way besides their locations.
*
* @author tetigi
*
* @param <T>
* Type of the data node
*/
public class UnorderedTree<T> implements Tree<T> {
private final ArrayList<Tree<T>> children = new ArrayList<Tree<T>>();
private T value;
@SafeVarargs
public UnorderedTree(final T val, final Tree<T>... trees) {
value = val;
for (final Tree<T> t : trees) {
children.add(t);
}
}
public UnorderedTree(final T val) {
value = val;
}
public UnorderedTree() {
value = null;
}
@Override
public void map(final utils.Tree.TreeFunc<T> f) {
for (final Tree<T> t : children) {
t.setValue(f.mapFunction(t.getValue()));
t.map(f);
}
}
@Override
public Tree<T> getChild(final int index) {
return children.get(index);
}
@Override
public void printTree() {
System.out.println(value);
for (final Tree<T> t : children) {
t.printTree();
}
}
@Override
public <U> Tree<U> transform(final utils.Tree.TreeTFunc<T, U> f) {
final UnorderedTree<U> ret = new UnorderedTree<U>();
for (final Tree<T> t : children) {
ret.setValue(f.transform(t.getValue()));
ret.addChild(t.transform(f));
}
return ret;
}
@Override
public void addChild(final Tree<T> t) {
children.add(t);
}
@Override
public T getValue() {
return value;
}
@Override
public void setValue(final T t) {
value = t;
}
@Override
public boolean isLeaf() {
return (children.size() == 0);
}
@Override
public <U> Tree<U> depthFirstTransform(utils.Tree.TreeNodeTFunc<T, U> f) {
return f.transformTree(this);
}
@Override
public List<Tree<T>> getChildren() {
return children;
}
@Override
public void setChildren(List<Tree<T>> children) {
this.children.clear();
this.children.addAll(children);
}
/*
* (non-Javadoc)
*
* @see utils.Tree#setChildren(java.util.List)
*/
@Override
public void addChildren(List<Tree<T>> children) {
this.children.addAll(children);
}
}
| apache-2.0 |
googleapis/java-bigquery | samples/snippets/src/test/java/com/example/bigquery/CreateClusteredTableIT.java | 2864 | /*
* Copyright 2020 Google LLC
*
* 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.example.bigquery;
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.assertNotNull;
import com.google.cloud.bigquery.Field;
import com.google.cloud.bigquery.Schema;
import com.google.cloud.bigquery.StandardSQLTypeName;
import com.google.common.collect.ImmutableList;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class CreateClusteredTableIT {
private final Logger log = Logger.getLogger(this.getClass().getName());
private String tableName;
private ByteArrayOutputStream bout;
private PrintStream out;
private PrintStream originalPrintStream;
private static final String BIGQUERY_DATASET_NAME = System.getenv("BIGQUERY_DATASET_NAME");
private static void requireEnvVar(String varName) {
assertNotNull(
"Environment variable " + varName + " is required to perform these tests.",
System.getenv(varName));
}
@BeforeClass
public static void checkRequirements() {
requireEnvVar("BIGQUERY_DATASET_NAME");
}
@Before
public void setUp() {
tableName = "MY_CLUSTERED_TABLE_TEST" + UUID.randomUUID().toString().substring(0, 8);
bout = new ByteArrayOutputStream();
out = new PrintStream(bout);
originalPrintStream = System.out;
System.setOut(out);
}
@After
public void tearDown() {
// Clean up
DeleteTable.deleteTable(BIGQUERY_DATASET_NAME, tableName);
// restores print statements in the original method
System.out.flush();
System.setOut(originalPrintStream);
log.log(Level.INFO, "\n" + bout.toString());
}
@Test
public void createClusteredTable() {
Schema schema =
Schema.of(
Field.of("name", StandardSQLTypeName.STRING),
Field.of("post_abbr", StandardSQLTypeName.STRING),
Field.of("date", StandardSQLTypeName.DATE));
CreateClusteredTable.createClusteredTable(
BIGQUERY_DATASET_NAME, tableName, schema, ImmutableList.of("name", "post_abbr"));
assertThat(bout.toString()).contains("Clustered table created successfully");
}
}
| apache-2.0 |
googleapis/java-datastream | proto-google-cloud-datastream-v1alpha1/src/main/java/com/google/cloud/datastream/v1alpha1/DeleteConnectionProfileRequest.java | 32578 | /*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/datastream/v1alpha1/datastream.proto
package com.google.cloud.datastream.v1alpha1;
/** Protobuf type {@code google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest} */
public final class DeleteConnectionProfileRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest)
DeleteConnectionProfileRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use DeleteConnectionProfileRequest.newBuilder() to construct.
private DeleteConnectionProfileRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DeleteConnectionProfileRequest() {
name_ = "";
requestId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new DeleteConnectionProfileRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private DeleteConnectionProfileRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
requestId_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datastream.v1alpha1.CloudDatastreamServiceProto
.internal_static_google_cloud_datastream_v1alpha1_DeleteConnectionProfileRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datastream.v1alpha1.CloudDatastreamServiceProto
.internal_static_google_cloud_datastream_v1alpha1_DeleteConnectionProfileRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest.class,
com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
*
*
* <pre>
* Required. The name of the connection profile resource to delete.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The name of the connection profile resource to delete.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int REQUEST_ID_FIELD_NUMBER = 2;
private volatile java.lang.Object requestId_;
/**
*
*
* <pre>
* Optional. A request ID to identify requests. Specify a unique request ID
* so that if you must retry your request, the server will know to ignore
* the request if it has already been completed. The server will guarantee
* that for at least 60 minutes after the first request.
* For example, consider a situation where you make an initial request and the
* request times out. If you make the request again with the same request ID,
* the server can check if original operation with the same request ID was
* received, and if so, will ignore the second request. This prevents clients
* from accidentally creating duplicate commitments.
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The requestId.
*/
@java.lang.Override
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. A request ID to identify requests. Specify a unique request ID
* so that if you must retry your request, the server will know to ignore
* the request if it has already been completed. The server will guarantee
* that for at least 60 minutes after the first request.
* For example, consider a situation where you make an initial request and the
* request times out. If you make the request again with the same request ID,
* the server can check if original operation with the same request ID was
* received, and if so, will ignore the second request. This prevents clients
* from accidentally creating duplicate commitments.
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for requestId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, requestId_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, requestId_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest)) {
return super.equals(obj);
}
com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest other =
(com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest) obj;
if (!getName().equals(other.getName())) return false;
if (!getRequestId().equals(other.getRequestId())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER;
hash = (53 * hash) + getRequestId().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/** Protobuf type {@code google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest} */
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest)
com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datastream.v1alpha1.CloudDatastreamServiceProto
.internal_static_google_cloud_datastream_v1alpha1_DeleteConnectionProfileRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datastream.v1alpha1.CloudDatastreamServiceProto
.internal_static_google_cloud_datastream_v1alpha1_DeleteConnectionProfileRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest.class,
com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest.Builder.class);
}
// Construct using
// com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
name_ = "";
requestId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.datastream.v1alpha1.CloudDatastreamServiceProto
.internal_static_google_cloud_datastream_v1alpha1_DeleteConnectionProfileRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest
getDefaultInstanceForType() {
return com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest build() {
com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest buildPartial() {
com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest result =
new com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest(this);
result.name_ = name_;
result.requestId_ = requestId_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest) {
return mergeFrom(
(com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest other) {
if (other
== com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest
.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
if (!other.getRequestId().isEmpty()) {
requestId_ = other.requestId_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* Required. The name of the connection profile resource to delete.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the connection profile resource to delete.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the connection profile resource to delete.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the connection profile resource to delete.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the connection profile resource to delete.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
private java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* Optional. A request ID to identify requests. Specify a unique request ID
* so that if you must retry your request, the server will know to ignore
* the request if it has already been completed. The server will guarantee
* that for at least 60 minutes after the first request.
* For example, consider a situation where you make an initial request and the
* request times out. If you make the request again with the same request ID,
* the server can check if original operation with the same request ID was
* received, and if so, will ignore the second request. This prevents clients
* from accidentally creating duplicate commitments.
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The requestId.
*/
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. A request ID to identify requests. Specify a unique request ID
* so that if you must retry your request, the server will know to ignore
* the request if it has already been completed. The server will guarantee
* that for at least 60 minutes after the first request.
* For example, consider a situation where you make an initial request and the
* request times out. If you make the request again with the same request ID,
* the server can check if original operation with the same request ID was
* received, and if so, will ignore the second request. This prevents clients
* from accidentally creating duplicate commitments.
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for requestId.
*/
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. A request ID to identify requests. Specify a unique request ID
* so that if you must retry your request, the server will know to ignore
* the request if it has already been completed. The server will guarantee
* that for at least 60 minutes after the first request.
* For example, consider a situation where you make an initial request and the
* request times out. If you make the request again with the same request ID,
* the server can check if original operation with the same request ID was
* received, and if so, will ignore the second request. This prevents clients
* from accidentally creating duplicate commitments.
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
requestId_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A request ID to identify requests. Specify a unique request ID
* so that if you must retry your request, the server will know to ignore
* the request if it has already been completed. The server will guarantee
* that for at least 60 minutes after the first request.
* For example, consider a situation where you make an initial request and the
* request times out. If you make the request again with the same request ID,
* the server can check if original operation with the same request ID was
* received, and if so, will ignore the second request. This prevents clients
* from accidentally creating duplicate commitments.
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearRequestId() {
requestId_ = getDefaultInstance().getRequestId();
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A request ID to identify requests. Specify a unique request ID
* so that if you must retry your request, the server will know to ignore
* the request if it has already been completed. The server will guarantee
* that for at least 60 minutes after the first request.
* For example, consider a situation where you make an initial request and the
* request times out. If you make the request again with the same request ID,
* the server can check if original operation with the same request ID was
* received, and if so, will ignore the second request. This prevents clients
* from accidentally creating duplicate commitments.
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
requestId_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest)
private static final com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest();
}
public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DeleteConnectionProfileRequest> PARSER =
new com.google.protobuf.AbstractParser<DeleteConnectionProfileRequest>() {
@java.lang.Override
public DeleteConnectionProfileRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new DeleteConnectionProfileRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<DeleteConnectionProfileRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DeleteConnectionProfileRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
SENA-CEET/1349397-Trimestre-4 | java/JSF/mavenproject2/src/main/java/co/edu/sena/mavenproject2/model/entities/InstructorFicha.java | 4558 | /*
* 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 co.edu.sena.mavenproject2.model.entities;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Enrique
*/
@Entity
@Table(name = "instructor_ficha")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "InstructorFicha.findAll", query = "SELECT i FROM InstructorFicha i")
, @NamedQuery(name = "InstructorFicha.findByTipoDocumento", query = "SELECT i FROM InstructorFicha i WHERE i.instructorFichaPK.tipoDocumento = :tipoDocumento")
, @NamedQuery(name = "InstructorFicha.findByNumeroDocumento", query = "SELECT i FROM InstructorFicha i WHERE i.instructorFichaPK.numeroDocumento = :numeroDocumento")
, @NamedQuery(name = "InstructorFicha.findByFicha", query = "SELECT i FROM InstructorFicha i WHERE i.instructorFichaPK.ficha = :ficha")})
public class InstructorFicha implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected InstructorFichaPK instructorFichaPK;
@JoinColumns({
@JoinColumn(name = "tipo_documento", referencedColumnName = "tipo_documento", nullable = false, insertable = false, updatable = false)
, @JoinColumn(name = "numero_documento", referencedColumnName = "numero_documento", nullable = false, insertable = false, updatable = false)})
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Cliente cliente;
@JoinColumn(name = "ficha", referencedColumnName = "numero_ficha", nullable = false, insertable = false, updatable = false)
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Ficha ficha1;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "instructorFicha", fetch = FetchType.LAZY)
private Collection<InstructorHasTrimestre> instructorHasTrimestreCollection;
public InstructorFicha() {
}
public InstructorFicha(InstructorFichaPK instructorFichaPK) {
this.instructorFichaPK = instructorFichaPK;
}
public InstructorFicha(String tipoDocumento, String numeroDocumento, String ficha) {
this.instructorFichaPK = new InstructorFichaPK(tipoDocumento, numeroDocumento, ficha);
}
public InstructorFichaPK getInstructorFichaPK() {
return instructorFichaPK;
}
public void setInstructorFichaPK(InstructorFichaPK instructorFichaPK) {
this.instructorFichaPK = instructorFichaPK;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public Ficha getFicha1() {
return ficha1;
}
public void setFicha1(Ficha ficha1) {
this.ficha1 = ficha1;
}
@XmlTransient
public Collection<InstructorHasTrimestre> getInstructorHasTrimestreCollection() {
return instructorHasTrimestreCollection;
}
public void setInstructorHasTrimestreCollection(Collection<InstructorHasTrimestre> instructorHasTrimestreCollection) {
this.instructorHasTrimestreCollection = instructorHasTrimestreCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (instructorFichaPK != null ? instructorFichaPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof InstructorFicha)) {
return false;
}
InstructorFicha other = (InstructorFicha) object;
if ((this.instructorFichaPK == null && other.instructorFichaPK != null) || (this.instructorFichaPK != null && !this.instructorFichaPK.equals(other.instructorFichaPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "co.edu.sena.mavenproject2.model.entities.InstructorFicha[ instructorFichaPK=" + instructorFichaPK + " ]";
}
}
| apache-2.0 |
yahoo/fili | fili-core/src/main/java/com/yahoo/bard/webservice/table/Schema.java | 1788 | // Copyright 2017 Yahoo Inc.
// Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms.
package com.yahoo.bard.webservice.table;
import com.yahoo.bard.webservice.data.time.Granularity;
import com.yahoo.bard.webservice.util.Utils;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
/**
* An interface describing a table or table-like entity composed of sets of columns.
*/
public interface Schema {
/**
* Get all the columns underlying this Schema.
*
* @return The columns of this schema
*/
Set<Column> getColumns();
/**
* Get the time granularity for this Schema.
*
* @return The time granularity of this schema
*/
Granularity getGranularity();
/**
* Getter for set of columns by sub-type.
*
* @param columnClass The class of columns to to search
* @param <T> sub-type of Column to return
*
* @return Set of Columns
*/
default <T extends Column> LinkedHashSet<T> getColumns(Class<T> columnClass) {
return Utils.getSubsetByType(getColumns(), columnClass);
}
/**
* Given a column type and name, return the column of the expected type.
*
* @param name The name on the column
* @param columnClass The class of the column being retrieved
* @param <T> The type of the subclass of the column being retrieved
*
* @return The an optional containing the column of the name and type specified, if any
*/
default <T extends Column> Optional<T> getColumn(String name, Class<T> columnClass) {
return getColumns(columnClass).stream()
.filter(column -> column.getName().equals(name))
.findFirst();
}
}
| apache-2.0 |
csgordon/SJS | sjsc/src/main/java/com/samsung/sjs/backend/asts/ir/Str.java | 1266 | /*
* Copyright 2014-2016 Samsung Research America, Inc.
*
* 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.
*/
/*
* String literal
*
* @author colin.gordon
*/
package com.samsung.sjs.backend.asts.ir;
public class Str extends Expression {
private String s;
public Str(String s) {
super(Tag.Str);
this.s = s;
}
public String getValue() { return s; }
@Override
public String toSource(int x) {
return "\""+s+"\"";
}
@Override
public <R> R accept(IRVisitor<R> v) {
return v.visitStr(this);
}
@Override
public boolean isPure() { return true; }
@Override
public boolean isConst() { return true; }
@Override
public boolean mustSaveIntermediates() { return false; }
}
| apache-2.0 |
cshannon/activemq-artemis | tests/artemis-test-support/src/main/java/org/apache/activemq/transport/amqp/client/transport/NettyWSTransport.java | 6723 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.transport.amqp.client.transport;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
/**
* Transport for communicating over WebSockets
*/
public class NettyWSTransport extends NettyTcpTransport {
private static final Logger LOG = LoggerFactory.getLogger(NettyWSTransport.class);
private static final String AMQP_SUB_PROTOCOL = "amqp";
/**
* Create a new transport instance
*
* @param remoteLocation
* the URI that defines the remote resource to connect to.
* @param options
* the transport options used to configure the socket connection.
*/
public NettyWSTransport(URI remoteLocation, NettyTransportOptions options) {
this(null, remoteLocation, options);
}
/**
* Create a new transport instance
*
* @param listener
* the TransportListener that will receive events from this Transport.
* @param remoteLocation
* the URI that defines the remote resource to connect to.
* @param options
* the transport options used to configure the socket connection.
*/
public NettyWSTransport(NettyTransportListener listener, URI remoteLocation, NettyTransportOptions options) {
super(listener, remoteLocation, options);
}
@Override
public void send(ByteBuf output) throws IOException {
checkConnected();
int length = output.readableBytes();
if (length == 0) {
return;
}
LOG.trace("Attempted write of: {} bytes", length);
channel.writeAndFlush(new BinaryWebSocketFrame(output));
}
@Override
protected ChannelInboundHandlerAdapter createChannelHandler() {
return new NettyWebSocketTransportHandler();
}
@Override
protected void addAdditionalHandlers(ChannelPipeline pipeline) {
pipeline.addLast(new HttpClientCodec());
pipeline.addLast(new HttpObjectAggregator(8192));
}
@Override
protected void handleConnected(Channel channel) throws Exception {
LOG.trace("Channel has become active, awaiting WebSocket handshake! Channel is {}", channel);
}
// ----- Handle connection events -----------------------------------------//
private class NettyWebSocketTransportHandler extends NettyDefaultHandler<Object> {
private final WebSocketClientHandshaker handshaker;
NettyWebSocketTransportHandler() {
handshaker = WebSocketClientHandshakerFactory.newHandshaker(
getRemoteLocation(), WebSocketVersion.V13, AMQP_SUB_PROTOCOL,
true, new DefaultHttpHeaders(), getMaxFrameSize());
}
@Override
public void channelActive(ChannelHandlerContext context) throws Exception {
handshaker.handshake(context.channel());
super.channelActive(context);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object message) throws Exception {
LOG.trace("New data read: incoming: {}", message);
Channel ch = ctx.channel();
if (!handshaker.isHandshakeComplete()) {
handshaker.finishHandshake(ch, (FullHttpResponse) message);
LOG.trace("WebSocket Client connected! {}", ctx.channel());
// Now trigger super processing as we are really connected.
NettyWSTransport.super.handleConnected(ch);
return;
}
// We shouldn't get this since we handle the handshake previously.
if (message instanceof FullHttpResponse) {
FullHttpResponse response = (FullHttpResponse) message;
throw new IllegalStateException(
"Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(StandardCharsets.UTF_8) + ')');
}
WebSocketFrame frame = (WebSocketFrame) message;
if (frame instanceof TextWebSocketFrame) {
TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
LOG.warn("WebSocket Client received message: " + textFrame.text());
ctx.fireExceptionCaught(new IOException("Received invalid frame over WebSocket."));
} else if (frame instanceof BinaryWebSocketFrame) {
BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
LOG.trace("WebSocket Client received data: {} bytes", binaryFrame.content().readableBytes());
listener.onData(binaryFrame.content());
} else if (frame instanceof PingWebSocketFrame) {
LOG.trace("WebSocket Client received ping, response with pong");
ch.write(new PongWebSocketFrame(frame.content()));
} else if (frame instanceof CloseWebSocketFrame) {
LOG.trace("WebSocket Client received closing");
ch.close();
}
}
}
}
| apache-2.0 |
sedesdev/design-patterns | src/br/com/caelum/designpatterns/decorator/imposto/ICMS.java | 358 | package br.com.caelum.designpatterns.decorator.imposto;
import br.com.caelum.designpatterns.modelo.Orcamento;
public class ICMS extends Imposto{
public ICMS(Imposto outroImposto) {
super(outroImposto);
}
public ICMS() {
}
public double calcula(Orcamento orcamento){
return orcamento.getValor() * 0.1 + calculoDoOutroImposto(orcamento);
}
}
| apache-2.0 |
wangqi/gameserver | admin/src/main/java/com/xinqihd/sns/gameserver/admin/i18n/ColumnNames.java | 3924 | package com.xinqihd.sns.gameserver.admin.i18n;
import java.util.HashMap;
public class ColumnNames {
private static HashMap<String, String> map = new HashMap<String, String>();
static {
map.put("profile" , "profile");
map.put("vip" , "vip");
map.put("ability" , "ability");
map.put("login" , "登陆");
map.put("config" , "配置");
map.put("wealth" , "wealth");
map.put("loc" , "位置");
map.put("tools" , "便携道具");
map.put("wears" , "wears");
map.put("count" , "count");
map.put("items" , "items");
map.put("class" , "class");
map.put("name" , "名称");
map.put("type" , "类型");
map.put("reqlv" , "reqlv");
map.put("scrollAreaX" , "scrollAreaX");
map.put("scrollAreaY" , "scrollAreaY");
map.put("scrollAreaWidth" , "scrollAreaWidth");
map.put("scrollAreaHeight" , "scrollAreaHeight");
map.put("layers" , "layers");
map.put("bgm" , "bgm");
map.put("damage" , "damage");
map.put("bosses" , "bosses");
map.put("enemies" , "enemies");
map.put("startPoints" , "startPoints");
map.put("index" , "index");
map.put("quality" , "品质");
map.put("qualityColor" , "品质颜色");
map.put("sName" , "名称");
map.put("equipType" , "装备类型");
map.put("addAttack" , "加攻击");
map.put("addDefend" , "加防御");
map.put("addAgility" , "加敏捷");
map.put("addLuck" , "加幸运");
map.put("addBlood" , "加血量");
map.put("addBloodPercent" , "加血量比例");
map.put("addThew" , "加体力");
map.put("addDamage" , "加伤害");
map.put("addSkin" , "加护甲");
map.put("sex" , "性别");
map.put("unused1" , "unused1");
map.put("unused2" , "unused2");
map.put("unused3" , "unused3");
map.put("indate1" , "indate1");
map.put("indate2" , "indate2");
map.put("indate3" , "indate3");
map.put("sign" , "sign");
map.put("lv" , "lv");
map.put("autoDirection" , "自动定位");
map.put("sAutoDirection" , "大招定位");
map.put("specialAction" , "特殊攻击");
map.put("radius" , "攻击半径");
map.put("sRadius" , "大招攻击半径");
map.put("expBlend" , "混合(不用)");
map.put("expSe" , "音效");
map.put("power" , "战斗力(未使用)");
map.put("autoDestory" , "自动伤害");
map.put("bullet" , "子弹标识");
map.put("icon" , "图标");
map.put("info" , "描述");
map.put("bubble" , "bubble");
map.put("slot" , "卡槽");
map.put("avatar" , "形象");
map.put("propInfoId" , "propInfoId");
map.put("level" , "level");
map.put("moneyType" , "货币类型");
map.put("buyPrices" , "购买价格");
map.put("banded" , "是否绑定");
map.put("discount" , "折扣");
map.put("sell" , "出售");
map.put("limitCount" , "limitCount");
map.put("limitGroup" , "limitGroup");
map.put("shopId" , "shopId");
map.put("isItem" , "isItem");
map.put("catalogs" , "商品目录");
map.put("desc" , "描述");
map.put("taskTarget" , "taskTarget");
map.put("step" , "步骤(step)");
map.put("exp" , "经验");
map.put("gold" , "金币");
map.put("ticket" , "礼券");
map.put("gongxun" , "功勋");
map.put("caifu" , "财富");
map.put("seq" , "顺序(seq)");
map.put("userLevel" , "用户等级");
map.put("script" , "脚本");
map.put("awards" , "奖励");
map.put("rival" , "rival");
map.put("typeId" , "typeId");
map.put("q" , "概率q");
map.put("rewards" , "奖励");
map.put("conditions" , "开启条件");
map.put("dayNum" , "天数");
map.put("price" , "价格");
map.put("currency" , "货币");
map.put("yuanbao" , "元宝");
map.put("isHotSale" , "是否热卖");
map.put("month" , "月");
map.put("yuanbaoPrice" , "元宝价格");
map.put("voucherPrice" , "礼券价格");
map.put("medalPrice" , "勋章价格");
}
public static String translate(String columnName) {
String name = map.get(columnName);
if ( name != null ) {
return name;
}
return columnName;
}
}
| apache-2.0 |
Anteoy/jottings | src/main/java/com/anteoy/coreJava/reflect/BeanUtil.java | 1049 | package com.anteoy.coreJava.reflect;
import java.lang.reflect.Method;
public class BeanUtil {
/**
* ���ݱ�javaBean�������������ȡ������ֵ
*
* @param obj
* @param propertyName
* @return
*/
public static Object getValueByPropertyName(Object obj, String propertyName) {
// 1.�����������ƾͿ��Ի�ȡ��get����
String getMethodName = "get"
+ propertyName.substring(0, 1).toUpperCase()
+ propertyName.substring(1);
//2.��ȡ��������
Class c = obj.getClass();
try {
//get��������public��������
Method m = c.getMethod(getMethodName);
//3 ͨ�������ķ����������
Object value = m.invoke(obj);
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| apache-2.0 |
Adobe-Marketing-Cloud/aem-scf-sample-components-extension | bundles/aem-scf-extensions/src/main/java/com/adobe/aem/scf/extensions/IdeationStatusExtension.java | 2104 | package com.adobe.aem.scf.extensions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.jcr.Session;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceUtil;
import com.adobe.cq.social.forum.client.api.Post;
import com.adobe.cq.social.forum.client.endpoints.ForumOperationExtension;
import com.adobe.cq.social.scf.Operation;
import com.adobe.cq.social.scf.OperationException;
@Component(name = "Ideation Status Extension", immediate = true, metatype = true)
@Service
public class IdeationStatusExtension implements ForumOperationExtension {
@Override
public void afterAction(Operation op, Session sessionUsed, Post post, Map<String, Object> props)
throws OperationException {
// TODO Auto-generated method stub
}
@Override
public void beforeAction(Operation op, Session sessionUsed, Resource requestResource, Map<String, Object> props)
throws OperationException {
if (ResourceUtil.isA(requestResource, "acme/components/ideation/forum")) {
List<String> tags = new ArrayList<String>();
if (props.containsKey("tags")) {
final Object v = props.get("tags");
if (!(v instanceof String[])) {
if (v instanceof String) {
tags.add((String) v);
}
} else {
for (String t : (String[]) v) {
tags.add(t);
}
}
}
tags.add("acmeideas:new");
props.put("tags", tags.toArray(new String[]{}));
}
}
@Override
public String getName() {
return "ideation status";
}
@Override
public int getOrder() {
return 1;
}
@Override
public List<ForumOperation> getOperationsToHookInto() {
return Arrays.asList(ForumOperation.CREATE);
}
}
| apache-2.0 |
trudeau/spanning | src/test/java/org/nnsoft/trudeau/spanning/BoruvkaTestCase.java | 8095 | package org.nnsoft.trudeau.spanning;
/*
* Copyright 2013 The Trudeau Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.nnsoft.trudeau.spanning.SpanningTreeSolver.minimumSpanningTree;
import org.junit.Test;
import org.nnsoft.trudeau.api.Graph;
import org.nnsoft.trudeau.api.SpanningTree;
import org.nnsoft.trudeau.inmemory.MutableSpanningTree;
import org.nnsoft.trudeau.inmemory.UndirectedMutableGraph;
import org.nnsoft.trudeau.inmemory.labeled.BaseLabeledVertex;
import org.nnsoft.trudeau.inmemory.labeled.BaseLabeledWeightedEdge;
import org.nnsoft.trudeau.inmemory.labeled.BaseWeightedEdge;
import org.nnsoft.trudeau.math.monoid.primitive.DoubleWeightBaseOperations;
public final class BoruvkaTestCase
{
@Test( expected = NullPointerException.class )
public void testNullGraph()
{
minimumSpanningTree( (Graph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>) null )
.whereEdgesHaveWeights( new BaseWeightedEdge<Double>() )
.fromArbitrarySource()
.applyingBoruvkaAlgorithm( new DoubleWeightBaseOperations() );
}
@Test( expected = NullPointerException.class )
public void testNullVertex()
{
UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>> input =
new UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>();
minimumSpanningTree( input )
.whereEdgesHaveWeights( new BaseWeightedEdge<Double>() )
.fromSource( null )
.applyingBoruvkaAlgorithm( new DoubleWeightBaseOperations() );
}
@Test( expected = NullPointerException.class )
public void testNullMonoid()
{
UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>> input = null;
BaseLabeledVertex a = null;
try
{
input = new UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>();
a = new BaseLabeledVertex( "A" );
input.addVertex( a );
}
catch ( NullPointerException e )
{
//try..catch need to avoid a possible test success even if a NPE is thorw during graph population
fail( e.getMessage() );
}
minimumSpanningTree( input )
.whereEdgesHaveWeights( new BaseWeightedEdge<Double>() )
.fromSource( a )
.applyingBoruvkaAlgorithm( null );
}
@Test( expected = IllegalStateException.class )
public void testNotExistVertex()
{
UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>> input =
new UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>();
minimumSpanningTree( input )
.whereEdgesHaveWeights( new BaseWeightedEdge<Double>() )
.fromSource( new BaseLabeledVertex( "NOT EXIST" ) );
}
@Test( expected = IllegalStateException.class )
public void testEmptyGraph()
{
UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>> input =
new UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>();
minimumSpanningTree( input )
.whereEdgesHaveWeights( new BaseWeightedEdge<Double>() )
.fromArbitrarySource()
.applyingBoruvkaAlgorithm( new DoubleWeightBaseOperations() );
}
/**
* Test Graph and boruvka's solution can be seen on
*/
@Test
public void verifyWikipediaMinimumSpanningTree()
{
UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>> input =
new UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>();
BaseLabeledVertex a = new BaseLabeledVertex( "A" );
BaseLabeledVertex b = new BaseLabeledVertex( "B" );
BaseLabeledVertex c = new BaseLabeledVertex( "C" );
BaseLabeledVertex d = new BaseLabeledVertex( "D" );
BaseLabeledVertex e = new BaseLabeledVertex( "E" );
BaseLabeledVertex f = new BaseLabeledVertex( "F" );
BaseLabeledVertex g = new BaseLabeledVertex( "G" );
input.addVertex( a );
input.addVertex( b );
input.addVertex( c );
input.addVertex( d );
input.addVertex( e );
input.addVertex( f );
input.addVertex( g );
input.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> b", 7D ), b );
input.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> c", 14D ), c );
input.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> d", 30D ), d );
input.addEdge( b, new BaseLabeledWeightedEdge<Double>( "b <-> c", 21D ), c );
input.addEdge( c, new BaseLabeledWeightedEdge<Double>( "c <-> d", 10D ), d );
input.addEdge( c, new BaseLabeledWeightedEdge<Double>( "c <-> e", 1D ), e );
input.addEdge( e, new BaseLabeledWeightedEdge<Double>( "e <-> f", 6D ), f );
input.addEdge( e, new BaseLabeledWeightedEdge<Double>( "e <-> g", 9D ), g );
input.addEdge( f, new BaseLabeledWeightedEdge<Double>( "f <-> g", 4D ), g );
// expected
MutableSpanningTree<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>, Double> expected =
new MutableSpanningTree<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>, Double>( new DoubleWeightBaseOperations(), new BaseWeightedEdge<Double>() );
for ( BaseLabeledVertex vertex : input.getVertices() )
{
expected.addVertex( vertex );
}
expected.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> b", 7D ), b );
expected.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> c", 14D ), c );
expected.addEdge( c, new BaseLabeledWeightedEdge<Double>( "c <-> d", 10D ), d );
expected.addEdge( c, new BaseLabeledWeightedEdge<Double>( "c <-> e", 1D ), e );
expected.addEdge( e, new BaseLabeledWeightedEdge<Double>( "e <-> f", 6D ), f );
expected.addEdge( f, new BaseLabeledWeightedEdge<Double>( "e <-> g", 9D ), g );
// Actual
SpanningTree<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>, Double> actual =
minimumSpanningTree( input )
.whereEdgesHaveWeights( new BaseWeightedEdge<Double>() )
.fromArbitrarySource()
.applyingBoruvkaAlgorithm( new DoubleWeightBaseOperations() );
// assert!
assertEquals( expected, actual );
}
/**
* Test Boruvka's solution on a not-connected graph.
*/
@Test( expected = IllegalStateException.class )
public void verifySparseGraphMinimumSpanningTree()
{
UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>> input =
new UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>();
input.addVertex( new BaseLabeledVertex( "A" ) );
input.addVertex( new BaseLabeledVertex( "B" ) );
input.addVertex( new BaseLabeledVertex( "C" ) );
input.addVertex( new BaseLabeledVertex( "D" ) );
input.addVertex( new BaseLabeledVertex( "E" ) );
input.addVertex( new BaseLabeledVertex( "F" ) );
input.addVertex( new BaseLabeledVertex( "G" ) );
minimumSpanningTree( input )
.whereEdgesHaveWeights( new BaseWeightedEdge<Double>() )
.fromArbitrarySource()
.applyingBoruvkaAlgorithm( new DoubleWeightBaseOperations() );
}
}
| apache-2.0 |
markus1978/citygml4emf | de.hub.citygml.emf.ecore/src/net/opengis/gml/FeaturePropertyType.java | 14502 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.gml;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.w3._1999.xlink.ActuateType;
import org.w3._1999.xlink.ShowType;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Feature Property Type</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* Container for a feature - follow gml:AssociationType pattern.
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link net.opengis.gml.FeaturePropertyType#getFeatureGroup <em>Feature Group</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getFeature <em>Feature</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getActuate <em>Actuate</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getArcrole <em>Arcrole</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getHref <em>Href</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getRemoteSchema <em>Remote Schema</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getRole <em>Role</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getShow <em>Show</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getTitle <em>Title</em>}</li>
* <li>{@link net.opengis.gml.FeaturePropertyType#getType <em>Type</em>}</li>
* </ul>
* </p>
*
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType()
* @model extendedMetaData="name='FeaturePropertyType' kind='elementOnly'"
* @generated
*/
public interface FeaturePropertyType extends EObject {
/**
* Returns the value of the '<em><b>Feature Group</b></em>' attribute list.
* The list contents are of type {@link org.eclipse.emf.ecore.util.FeatureMap.Entry}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Feature Group</em>' attribute list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Feature Group</em>' attribute list.
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_FeatureGroup()
* @model dataType="org.eclipse.emf.ecore.EFeatureMapEntry" many="false"
* extendedMetaData="kind='group' name='_Feature:group' namespace='##targetNamespace'"
* @generated
*/
FeatureMap getFeatureGroup();
/**
* Returns the value of the '<em><b>Feature</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Feature</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Feature</em>' containment reference.
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Feature()
* @model containment="true" transient="true" changeable="false" volatile="true" derived="true"
* extendedMetaData="kind='element' name='_Feature' namespace='##targetNamespace' group='_Feature:group'"
* @generated
*/
AbstractFeatureType getFeature();
/**
* Returns the value of the '<em><b>Actuate</b></em>' attribute.
* The literals are from the enumeration {@link org.w3._1999.xlink.ActuateType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
*
* The 'actuate' attribute is used to communicate the desired timing
* of traversal from the starting resource to the ending resource;
* it's value should be treated as follows:
* onLoad - traverse to the ending resource immediately on loading
* the starting resource
* onRequest - traverse from the starting resource to the ending
* resource only on a post-loading event triggered for
* this purpose
* other - behavior is unconstrained; examine other markup in link
* for hints
* none - behavior is unconstrained
*
* <!-- end-model-doc -->
* @return the value of the '<em>Actuate</em>' attribute.
* @see org.w3._1999.xlink.ActuateType
* @see #isSetActuate()
* @see #unsetActuate()
* @see #setActuate(ActuateType)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Actuate()
* @model unsettable="true"
* extendedMetaData="kind='attribute' name='actuate' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
ActuateType getActuate();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getActuate <em>Actuate</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Actuate</em>' attribute.
* @see org.w3._1999.xlink.ActuateType
* @see #isSetActuate()
* @see #unsetActuate()
* @see #getActuate()
* @generated
*/
void setActuate(ActuateType value);
/**
* Unsets the value of the '{@link net.opengis.gml.FeaturePropertyType#getActuate <em>Actuate</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetActuate()
* @see #getActuate()
* @see #setActuate(ActuateType)
* @generated
*/
void unsetActuate();
/**
* Returns whether the value of the '{@link net.opengis.gml.FeaturePropertyType#getActuate <em>Actuate</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Actuate</em>' attribute is set.
* @see #unsetActuate()
* @see #getActuate()
* @see #setActuate(ActuateType)
* @generated
*/
boolean isSetActuate();
/**
* Returns the value of the '<em><b>Arcrole</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Arcrole</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Arcrole</em>' attribute.
* @see #setArcrole(String)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Arcrole()
* @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI"
* extendedMetaData="kind='attribute' name='arcrole' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getArcrole();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getArcrole <em>Arcrole</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Arcrole</em>' attribute.
* @see #getArcrole()
* @generated
*/
void setArcrole(String value);
/**
* Returns the value of the '<em><b>Href</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Href</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Href</em>' attribute.
* @see #setHref(String)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Href()
* @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI"
* extendedMetaData="kind='attribute' name='href' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getHref();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getHref <em>Href</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Href</em>' attribute.
* @see #getHref()
* @generated
*/
void setHref(String value);
/**
* Returns the value of the '<em><b>Remote Schema</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Reference to an XML Schema fragment that specifies the content model of the propertys value. This is in conformance with the XML Schema Section 4.14 Referencing Schemas from Elsewhere.
* <!-- end-model-doc -->
* @return the value of the '<em>Remote Schema</em>' attribute.
* @see #setRemoteSchema(String)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_RemoteSchema()
* @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI"
* extendedMetaData="kind='attribute' name='remoteSchema' namespace='##targetNamespace'"
* @generated
*/
String getRemoteSchema();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getRemoteSchema <em>Remote Schema</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Remote Schema</em>' attribute.
* @see #getRemoteSchema()
* @generated
*/
void setRemoteSchema(String value);
/**
* Returns the value of the '<em><b>Role</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Role</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Role</em>' attribute.
* @see #setRole(String)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Role()
* @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI"
* extendedMetaData="kind='attribute' name='role' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getRole();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getRole <em>Role</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Role</em>' attribute.
* @see #getRole()
* @generated
*/
void setRole(String value);
/**
* Returns the value of the '<em><b>Show</b></em>' attribute.
* The literals are from the enumeration {@link org.w3._1999.xlink.ShowType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
*
* The 'show' attribute is used to communicate the desired presentation
* of the ending resource on traversal from the starting resource; it's
* value should be treated as follows:
* new - load ending resource in a new window, frame, pane, or other
* presentation context
* replace - load the resource in the same window, frame, pane, or
* other presentation context
* embed - load ending resource in place of the presentation of the
* starting resource
* other - behavior is unconstrained; examine other markup in the
* link for hints
* none - behavior is unconstrained
*
* <!-- end-model-doc -->
* @return the value of the '<em>Show</em>' attribute.
* @see org.w3._1999.xlink.ShowType
* @see #isSetShow()
* @see #unsetShow()
* @see #setShow(ShowType)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Show()
* @model unsettable="true"
* extendedMetaData="kind='attribute' name='show' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
ShowType getShow();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getShow <em>Show</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Show</em>' attribute.
* @see org.w3._1999.xlink.ShowType
* @see #isSetShow()
* @see #unsetShow()
* @see #getShow()
* @generated
*/
void setShow(ShowType value);
/**
* Unsets the value of the '{@link net.opengis.gml.FeaturePropertyType#getShow <em>Show</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetShow()
* @see #getShow()
* @see #setShow(ShowType)
* @generated
*/
void unsetShow();
/**
* Returns whether the value of the '{@link net.opengis.gml.FeaturePropertyType#getShow <em>Show</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Show</em>' attribute is set.
* @see #unsetShow()
* @see #getShow()
* @see #setShow(ShowType)
* @generated
*/
boolean isSetShow();
/**
* Returns the value of the '<em><b>Title</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Title</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Title</em>' attribute.
* @see #setTitle(String)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Title()
* @model dataType="org.eclipse.emf.ecore.xml.type.String"
* extendedMetaData="kind='attribute' name='title' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getTitle();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getTitle <em>Title</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Title</em>' attribute.
* @see #getTitle()
* @generated
*/
void setTitle(String value);
/**
* Returns the value of the '<em><b>Type</b></em>' attribute.
* The default value is <code>"simple"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Type</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Type</em>' attribute.
* @see #isSetType()
* @see #unsetType()
* @see #setType(String)
* @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Type()
* @model default="simple" unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.String"
* extendedMetaData="kind='attribute' name='type' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getType();
/**
* Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getType <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Type</em>' attribute.
* @see #isSetType()
* @see #unsetType()
* @see #getType()
* @generated
*/
void setType(String value);
/**
* Unsets the value of the '{@link net.opengis.gml.FeaturePropertyType#getType <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetType()
* @see #getType()
* @see #setType(String)
* @generated
*/
void unsetType();
/**
* Returns whether the value of the '{@link net.opengis.gml.FeaturePropertyType#getType <em>Type</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Type</em>' attribute is set.
* @see #unsetType()
* @see #getType()
* @see #setType(String)
* @generated
*/
boolean isSetType();
} // FeaturePropertyType
| apache-2.0 |
Langenoir1878/vet_web | src/main/java/web/hospital/LoginBean.java | 4588 | /*
* 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 edu.iit.sat.itmd4515.yzhan214.fp.web.hospital;
import edu.iit.sat.itmd4515.yzhan214.fp.web.hospital.AbstractJSFBean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.inject.Named;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* @author ln1878
*/
@Named
@RequestScoped
public class LoginBean extends AbstractJSFBean{
private static final Logger LOG = Logger.getLogger(LoginBean.class.getName());
@NotNull(message = "You shall not pass without a username!")
private String username;
@NotNull(message = "You shall not pass without a password!")
@Size(min = 5, message = "Password must be at least 5 characters in length.")
private String password;
/**
*
*/
public LoginBean() {
}
@PostConstruct
private void postConstruct() {
super.postContruct();
}
/**
*
* @return
*/
public boolean isAdmin() {
return facesContext.getExternalContext().isUserInRole("admin");
}
/**
*
* @return
*/
public boolean isDoctor() {
return facesContext.getExternalContext().isUserInRole("doctor");
}
/**
*
* @return
*/
public boolean isAssistant() {
return facesContext.getExternalContext().isUserInRole("vetassistant");
}
/**
*
* @return
*/
public boolean isPetOwner() {
return facesContext.getExternalContext().isUserInRole("petowner");
}
/**
*
* @param path
* @return
*/
public String getPortalPathByRole(String path) {
LOG.info("Inside LoginBean getPortal");
if (isAdmin()) {
return "/admin" + path;
} else if (isDoctor()) {
return "/doctorPortal" + path;
} else if (isAssistant()) {
return "/assistantPortal" + path;
} else if(isPetOwner()) {
return "/petownerPortal" + path;
}
else {
return path ;
}
}
/**
*
* @return
*/
public String doLogin() {
HttpServletRequest req = (HttpServletRequest) facesContext.getExternalContext().getRequest();
try {
req.login(username, password);
} catch (ServletException ex) {
LOG.log(Level.SEVERE, null, ex);
facesContext.addMessage(null, new FacesMessage("Bad Login", "Detail: You made a bad login!"));
return "/login.xhtml";
}
return getPortalPathByRole("/welcome.xhtml");
}
/**
*
* @return
*/
public String doLogout() {
HttpServletRequest req = (HttpServletRequest) facesContext.getExternalContext().getRequest();
try {
req.logout();
} catch (ServletException ex) {
LOG.log(Level.SEVERE,"There has been a problem invoking HttpServletRequest.logout",ex);
facesContext.addMessage(null, new FacesMessage("Bad Logout", "Detail:There was a problem with the logout"));
return "/error.xhtml";
}
return "/index.xhtml";
}
/**
*
* @return
*/
public String getRemoteUser() {
return facesContext.getExternalContext().getRemoteUser();
}
/**
* Get the value of password
*
* @return the value of password
*/
public String getPassword() {
return password;
}
/**
* Set the value of password
*
* @param password new value of password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Get the value of username
*
* @return the value of username
*/
public String getUsername() {
return username;
}
/**
* Set the value of username
*
* @param username new value of username
*/
public void setUsername(String username) {
this.username = username;
}
}
| apache-2.0 |
TwoPillar/jiba | src/com/twopillar/jiba/activity/MainActivity.java | 8696 | package com.twopillar.jiba.activity;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import com.twopillar.jiba.R;
import com.twopillar.jiba.fragment.ActionFragment;
import com.twopillar.jiba.fragment.BBSFragment;
import com.twopillar.jiba.fragment.MeFragment;
import com.twopillar.jiba.fragment.PlanFragment;
public class MainActivity extends BaseActivity{
private FragmentTabHost mTabHost;
private RadioGroup radioGroup;
private RadioButton plan;//计划
private RadioButton action;//动作
private RadioButton bbs;//论坛
private RadioButton me;//我
private long exitTime = 0;
String tabs[] = {"Tab1","Tab2","Tab3","Tab4"};
Class cls[] = {PlanFragment.class,ActionFragment.class,BBSFragment.class,MeFragment.class};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_fragment_tabs);
initView();
}
private void initView() {
plan = (RadioButton)findViewById(R.id.plan);
action = (RadioButton)findViewById(R.id.action);
bbs = (RadioButton)findViewById(R.id.bbs);
me = (RadioButton)findViewById(R.id.me);
mTabHost = (FragmentTabHost)this.findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.getTabWidget().setVisibility(View.GONE);
for(int i=0;i<tabs.length;i++){
mTabHost.addTab(mTabHost.newTabSpec(tabs[i]).setIndicator(tabs[i]),cls[i], null);
}
radioGroup = (RadioGroup) findViewById(R.id.main_radiogroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.plan:
changeSeletedButton(0);
mTabHost.setCurrentTabByTag(tabs[0]);
break;
case R.id.action:
changeSeletedButton(1);
mTabHost.setCurrentTabByTag(tabs[1]);
break;
case R.id.bbs:
changeSeletedButton(2);
mTabHost.setCurrentTabByTag(tabs[2]);
break;
case R.id.me:
changeSeletedButton(3);
mTabHost.setCurrentTabByTag(tabs[3]);
break;
}
}
});
((RadioButton)radioGroup.getChildAt(0)).toggle();
}
private void changeSeletedButton(int type) {
Drawable drawable = null;
switch (type) {
case 0:
drawable = getResources().getDrawable(R.drawable.icon_plan_selected);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
plan.setCompoundDrawables(null, drawable, null, null);
plan.setTextColor(Color.parseColor("#FFDA44"));
drawable = getResources().getDrawable(R.drawable.icon_action);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
action.setCompoundDrawables(null, drawable, null, null);
action.setTextColor(Color.parseColor("#595959"));
drawable = getResources().getDrawable(R.drawable.icon_bbs);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
bbs.setCompoundDrawables(null, drawable, null, null);
bbs.setTextColor(Color.parseColor("#595959"));
drawable = getResources().getDrawable(R.drawable.icon_me);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
me.setCompoundDrawables(null, drawable, null, null);
me.setTextColor(Color.parseColor("#595959"));
break;
case 1:
drawable = getResources().getDrawable(R.drawable.icon_action_selected);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
action.setCompoundDrawables(null, drawable, null, null);
action.setTextColor(Color.parseColor("#FFDA44"));
drawable = getResources().getDrawable(R.drawable.icon_plan);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
plan.setCompoundDrawables(null, drawable, null, null);
plan.setTextColor(Color.parseColor("#595959"));
drawable = getResources().getDrawable(R.drawable.icon_bbs);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
bbs.setCompoundDrawables(null, drawable, null, null);
bbs.setTextColor(Color.parseColor("#595959"));
drawable = getResources().getDrawable(R.drawable.icon_me);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
me.setCompoundDrawables(null, drawable, null, null);
me.setTextColor(Color.parseColor("#595959"));
break;
case 2:
drawable = getResources().getDrawable(R.drawable.icon_bbs_selected);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
bbs.setCompoundDrawables(null, drawable, null, null);
bbs.setTextColor(Color.parseColor("#FFDA44"));
drawable = getResources().getDrawable(R.drawable.icon_plan);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
plan.setCompoundDrawables(null, drawable, null, null);
plan.setTextColor(Color.parseColor("#595959"));
drawable = getResources().getDrawable(R.drawable.icon_action);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
action.setCompoundDrawables(null, drawable, null, null);
action.setTextColor(Color.parseColor("#595959"));
drawable = getResources().getDrawable(R.drawable.icon_me);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
me.setCompoundDrawables(null, drawable, null, null);
me.setTextColor(Color.parseColor("#595959"));
break;
case 3:
drawable = getResources().getDrawable(R.drawable.icon_me_selected);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
me.setCompoundDrawables(null, drawable, null, null);
me.setTextColor(Color.parseColor("#FFDA44"));
drawable = getResources().getDrawable(R.drawable.icon_plan);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
plan.setCompoundDrawables(null, drawable, null, null);
plan.setTextColor(Color.parseColor("#595959"));
drawable = getResources().getDrawable(R.drawable.icon_action);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
action.setCompoundDrawables(null, drawable, null, null);
action.setTextColor(Color.parseColor("#595959"));
drawable = getResources().getDrawable(R.drawable.icon_bbs);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
bbs.setCompoundDrawables(null, drawable, null, null);
bbs.setTextColor(Color.parseColor("#595959"));
break;
default:
break;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
ExitApp();
}
}
return false;
}
// 返回键双击退出APP
public void ExitApp() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
}
}
| apache-2.0 |
SAP/cloud-odata-java | odata-core/src/main/java/com/sap/core/odata/core/uri/expression/OrderExpressionImpl.java | 2356 | /*******************************************************************************
* Copyright 2013 SAP AG
*
* 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.sap.core.odata.core.uri.expression;
import com.sap.core.odata.api.edm.EdmType;
import com.sap.core.odata.api.exception.ODataApplicationException;
import com.sap.core.odata.api.uri.expression.CommonExpression;
import com.sap.core.odata.api.uri.expression.ExceptionVisitExpression;
import com.sap.core.odata.api.uri.expression.ExpressionKind;
import com.sap.core.odata.api.uri.expression.ExpressionVisitor;
import com.sap.core.odata.api.uri.expression.OrderExpression;
import com.sap.core.odata.api.uri.expression.SortOrder;
/**
* @author SAP AG
*/
public class OrderExpressionImpl implements OrderExpression {
SortOrder orderType = SortOrder.asc;
CommonExpression expression;
OrderExpressionImpl(final CommonExpression expression) {
this.expression = expression;
}
@Override
public SortOrder getSortOrder() {
return orderType;
}
@Override
public CommonExpression getExpression() {
return expression;
}
void setSortOrder(final SortOrder orderType) {
this.orderType = orderType;
}
@Override
public ExpressionKind getKind() {
return ExpressionKind.ORDER;
}
@Override
public EdmType getEdmType() {
return null;
}
@Override
public CommonExpression setEdmType(final EdmType edmType) {
return this;
}
@Override
public String getUriLiteral() {
return "";
}
@Override
public Object accept(final ExpressionVisitor visitor) throws ExceptionVisitExpression, ODataApplicationException {
Object obj = expression.accept(visitor);
Object ret = visitor.visitOrder(this, obj, orderType);
return ret;
}
}
| apache-2.0 |
metatron-app/metatron-discovery | discovery-server/src/main/java/app/metatron/discovery/common/geospatial/geojson/PointGeometry.java | 975 | /*
* 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 specic language governing permissions and
* limitations under the License.
*/
package app.metatron.discovery.common.geospatial.geojson;
public class PointGeometry implements GeoJsonGeometry {
private double[] coordinates;
private double[] bbox;
public PointGeometry() {
}
public PointGeometry(double[] coordinates) {
this.coordinates = coordinates;
}
public double[] getCoordinates() {
return coordinates;
}
public double[] getBbox() {
return bbox;
}
}
| apache-2.0 |
e-biz/gatling-liferay | src/main/java/io/gatling/liferay/model/impl/ProcessModelImpl.java | 11680 | /**
* Copyright 2011-2016 GatlingCorp (http://gatling.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gatling.liferay.model.impl;
import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ProxyUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.model.CacheModel;
import com.liferay.portal.model.impl.BaseModelImpl;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portlet.expando.model.ExpandoBridge;
import com.liferay.portlet.expando.util.ExpandoBridgeFactoryUtil;
import io.gatling.liferay.model.Process;
import io.gatling.liferay.model.ProcessModel;
import java.io.Serializable;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
/**
* The base model implementation for the Process service. Represents a row in the "StressTool_Process" database table, with each column mapped to a property of this class.
*
* <p>
* This implementation and its corresponding interface {@link io.gatling.liferay.model.ProcessModel} exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in {@link ProcessImpl}.
* </p>
*
* @author Brian Wing Shun Chan
* @see ProcessImpl
* @see io.gatling.liferay.model.Process
* @see io.gatling.liferay.model.ProcessModel
* @generated
*/
public class ProcessModelImpl extends BaseModelImpl<Process>
implements ProcessModel {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this class directly. All methods that expect a process model instance should use the {@link io.gatling.liferay.model.Process} interface instead.
*/
public static final String TABLE_NAME = "StressTool_Process";
public static final Object[][] TABLE_COLUMNS = {
{ "process_id", Types.BIGINT },
{ "name", Types.VARCHAR },
{ "type_", Types.VARCHAR },
{ "feederId", Types.BIGINT }
};
public static final String TABLE_SQL_CREATE = "create table StressTool_Process (process_id LONG not null primary key,name VARCHAR(75) null,type_ VARCHAR(75) null,feederId LONG)";
public static final String TABLE_SQL_DROP = "drop table StressTool_Process";
public static final String ORDER_BY_JPQL = " ORDER BY process.process_id ASC";
public static final String ORDER_BY_SQL = " ORDER BY StressTool_Process.process_id ASC";
public static final String DATA_SOURCE = "liferayDataSource";
public static final String SESSION_FACTORY = "liferaySessionFactory";
public static final String TX_MANAGER = "liferayTransactionManager";
public static final boolean ENTITY_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
"value.object.entity.cache.enabled.io.gatling.liferay.model.Process"),
true);
public static final boolean FINDER_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
"value.object.finder.cache.enabled.io.gatling.liferay.model.Process"),
true);
public static final boolean COLUMN_BITMASK_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
"value.object.column.bitmask.enabled.io.gatling.liferay.model.Process"),
true);
public static long NAME_COLUMN_BITMASK = 1L;
public static long PROCESS_ID_COLUMN_BITMASK = 2L;
public static final long LOCK_EXPIRATION_TIME = GetterUtil.getLong(com.liferay.util.service.ServiceProps.get(
"lock.expiration.time.io.gatling.liferay.model.Process"));
private static ClassLoader _classLoader = Process.class.getClassLoader();
private static Class<?>[] _escapedModelInterfaces = new Class[] {
Process.class
};
private long _process_id;
private String _name;
private String _originalName;
private String _type;
private Long _feederId;
private long _columnBitmask;
private Process _escapedModel;
public ProcessModelImpl() {
}
@Override
public long getPrimaryKey() {
return _process_id;
}
@Override
public void setPrimaryKey(long primaryKey) {
setProcess_id(primaryKey);
}
@Override
public Serializable getPrimaryKeyObj() {
return _process_id;
}
@Override
public void setPrimaryKeyObj(Serializable primaryKeyObj) {
setPrimaryKey(((Long) primaryKeyObj).longValue());
}
@Override
public Class<?> getModelClass() {
return Process.class;
}
@Override
public String getModelClassName() {
return Process.class.getName();
}
@Override
public Map<String, Object> getModelAttributes() {
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("process_id", getProcess_id());
attributes.put("name", getName());
attributes.put("type", getType());
attributes.put("feederId", getFeederId());
return attributes;
}
@Override
public void setModelAttributes(Map<String, Object> attributes) {
Long process_id = (Long) attributes.get("process_id");
if (process_id != null) {
setProcess_id(process_id);
}
String name = (String) attributes.get("name");
if (name != null) {
setName(name);
}
String type = (String) attributes.get("type");
if (type != null) {
setType(type);
}
Long feederId = (Long) attributes.get("feederId");
if (feederId != null) {
setFeederId(feederId);
}
}
@Override
public long getProcess_id() {
return _process_id;
}
@Override
public void setProcess_id(long process_id) {
_process_id = process_id;
}
@Override
public String getName() {
if (_name == null) {
return StringPool.BLANK;
} else {
return _name;
}
}
@Override
public void setName(String name) {
_columnBitmask |= NAME_COLUMN_BITMASK;
if (_originalName == null) {
_originalName = _name;
}
_name = name;
}
public String getOriginalName() {
return GetterUtil.getString(_originalName);
}
@Override
public String getType() {
if (_type == null) {
return StringPool.BLANK;
} else {
return _type;
}
}
@Override
public void setType(String type) {
_type = type;
}
@Override
public Long getFeederId() {
return _feederId;
}
@Override
public void setFeederId(Long feederId) {
_feederId = feederId;
}
public long getColumnBitmask() {
return _columnBitmask;
}
@Override
public ExpandoBridge getExpandoBridge() {
return ExpandoBridgeFactoryUtil.getExpandoBridge(0,
Process.class.getName(), getPrimaryKey());
}
@Override
public void setExpandoBridgeAttributes(ServiceContext serviceContext) {
ExpandoBridge expandoBridge = getExpandoBridge();
expandoBridge.setAttributes(serviceContext);
}
@Override
public Process toEscapedModel() {
if (_escapedModel == null) {
_escapedModel = (Process) ProxyUtil.newProxyInstance(_classLoader,
_escapedModelInterfaces, new AutoEscapeBeanHandler(this));
}
return _escapedModel;
}
@Override
public Object clone() {
ProcessImpl processImpl = new ProcessImpl();
processImpl.setProcess_id(getProcess_id());
processImpl.setName(getName());
processImpl.setType(getType());
processImpl.setFeederId(getFeederId());
processImpl.resetOriginalValues();
return processImpl;
}
@Override
public int compareTo(Process process) {
long primaryKey = process.getPrimaryKey();
if (getPrimaryKey() < primaryKey) {
return -1;
} else if (getPrimaryKey() > primaryKey) {
return 1;
} else {
return 0;
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Process)) {
return false;
}
Process process = (Process) obj;
long primaryKey = process.getPrimaryKey();
if (getPrimaryKey() == primaryKey) {
return true;
} else {
return false;
}
}
@Override
public int hashCode() {
return (int) getPrimaryKey();
}
@Override
public void resetOriginalValues() {
ProcessModelImpl processModelImpl = this;
processModelImpl._originalName = processModelImpl._name;
processModelImpl._columnBitmask = 0;
}
@Override
public CacheModel<Process> toCacheModel() {
ProcessCacheModel processCacheModel = new ProcessCacheModel();
processCacheModel.process_id = getProcess_id();
processCacheModel.name = getName();
String name = processCacheModel.name;
if ((name != null) && (name.length() == 0)) {
processCacheModel.name = null;
}
processCacheModel.type = getType();
String type = processCacheModel.type;
if ((type != null) && (type.length() == 0)) {
processCacheModel.type = null;
}
processCacheModel.feederId = getFeederId();
return processCacheModel;
}
@Override
public String toString() {
StringBundler sb = new StringBundler(9);
sb.append("{process_id=");
sb.append(getProcess_id());
sb.append(", name=");
sb.append(getName());
sb.append(", type=");
sb.append(getType());
sb.append(", feederId=");
sb.append(getFeederId());
sb.append("}");
return sb.toString();
}
@Override
public String toXmlString() {
StringBundler sb = new StringBundler(16);
sb.append("<model><model-name>");
sb.append("io.gatling.liferay.model.Process");
sb.append("</model-name>");
sb.append(
"<column><column-name>process_id</column-name><column-value><![CDATA[");
sb.append(getProcess_id());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>name</column-name><column-value><![CDATA[");
sb.append(getName());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>type</column-name><column-value><![CDATA[");
sb.append(getType());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>feederId</column-name><column-value><![CDATA[");
sb.append(getFeederId());
sb.append("]]></column-value></column>");
sb.append("</model>");
return sb.toString();
}
}
| apache-2.0 |