repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
luisgoncalves/xades4j | src/test/java/xades4j/production/TestAlgorithmsParametersMarshallingProvider.java | 1331 | /*
* XAdES4j - A Java library for generation and verification of XAdES signatures.
* Copyright (C) 2017 Luis Goncalves.
*
* XAdES4j 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 any later version.
*
* XAdES4j 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 XAdES4j. If not, see <http://www.gnu.org/licenses/>.
*/
package xades4j.production;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import xades4j.UnsupportedAlgorithmException;
import xades4j.algorithms.Algorithm;
import xades4j.xml.marshalling.algorithms.AlgorithmsParametersMarshallingProvider;
/**
*
* @author luis
*/
public class TestAlgorithmsParametersMarshallingProvider implements AlgorithmsParametersMarshallingProvider
{
@Override
public List<Node> marshalParameters(Algorithm alg, Document doc) throws UnsupportedAlgorithmException
{
return null;
}
}
| lgpl-3.0 |
exoplatform/task | services/src/main/java/org/exoplatform/task/dao/condition/Conditions.java | 4553 | /*
* Copyright (C) 2015 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.exoplatform.task.dao.condition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author <a href="mailto:tuyennt@exoplatform.com">Tuyen Nguyen The</a>.
*/
public class Conditions {
public static String ID = "id";
public static String TASK_TITLE = "title";
public static String TASK_DES = "description";
public static String TASK_PRIORITY = "priority";
public static String TASK_ASSIGNEE = "assignee";
public static String TASK_COWORKER = "coworker";
public static String TASK_WATCHER = "watcher";
public static String TASK_CREATOR = "createdBy";
public static String TASK_STATUS = "status";
public static String TASK_DUEDATE = "dueDate";
public static String TASK_PROJECT = "status.project";
public static String TASK_LABEL_USERNAME = "lblMapping.label.username";
public static String TASK_LABEL_ID = "lblMapping.label.id";
public static String TASK_COMPLETED = "completed";
public static String TASK_START_DATE = "startDate";
public static String TASK_END_DATE = "endDate";
public static String TASK_MANAGER = "status.project.manager";
public static String TASK_PARTICIPATOR = "status.project.participator";
public static String TASK_MENTIONED_USERS = "mentionedUsers";
public static final String MANAGER = "manager";
public static final String PARTICIPATOR = "participator";
public static final String NAME = "name";
public static final String PARENT = "parent";
public static final String USERNAME = "username";
public static final String LABEL_TASK_ID = "lblMapping.task.id";
public static <T> SingleCondition<T> eq(String fieldName, T value) {
return new SingleCondition<T>(SingleCondition.EQ, fieldName, value);
}
public static <T> SingleCondition<T> like(String fieldName, T value) {
return new SingleCondition<T>(SingleCondition.LIKE, fieldName, value);
}
public static <T> SingleCondition<T> gt(String fieldName, T value) {
return new SingleCondition<T>(SingleCondition.GT, fieldName, value);
}
public static <T> SingleCondition<T> lt(String fieldName, T value) {
return new SingleCondition<T>(SingleCondition.LT, fieldName, value);
}
public static <T> SingleCondition<T> gte(String fieldName, T value) {
return new SingleCondition<T>(SingleCondition.GTE, fieldName, value);
}
public static <T> SingleCondition<T> lte(String fieldName, T value) {
return new SingleCondition<T>(SingleCondition.LTE, fieldName, value);
}
public static <T> SingleCondition<T> isNull(String fieldName) {
return new SingleCondition<T>(SingleCondition.IS_NULL, fieldName, null);
}
public static <T> SingleCondition<T> isEmpty(String fieldName) {
return new SingleCondition<T>(SingleCondition.IS_EMPTY, fieldName, null);
}
public static <T> SingleCondition<T> notNull(String fieldName) {
return new SingleCondition<T>(SingleCondition.NOT_NULL, fieldName, null);
}
public static <T> SingleCondition<List<T>> in(String fieldName, List<T> values) {
return new SingleCondition<List<T>>(SingleCondition.IN, fieldName, values);
}
public static <T> SingleCondition<T> isTrue(String fieldName) {
return new SingleCondition<T>(SingleCondition.IS_TRUE, fieldName, null);
}
public static <T> SingleCondition<T> isFalse(String fieldName) {
return new SingleCondition<T>(SingleCondition.IS_FALSE, fieldName, null);
}
public static AggregateCondition and(Condition... cond) {
return new AggregateCondition(AggregateCondition.AND, new ArrayList<Condition>(Arrays.asList(cond)));
}
public static AggregateCondition or(Condition... cond) {
return new AggregateCondition(AggregateCondition.OR, new ArrayList<Condition>(Arrays.asList(cond)));
}
}
| lgpl-3.0 |
tcampanella/GoEuroTest | src/main/java/com/goEuroTest/Main.java | 501 | package com.goEuroTest;
import com.sun.jersey.api.client.ClientResponse;
/**
*
* @author Tommaso Campanella
*
*/
public class Main {
public static void main(String[] args) {
/**
* Get Rest call (GET) response
*/
IGoEuro goEuro = new GoEuro();
ClientResponse clientResponse = goEuro.restCall(args[0]);
/**
* Parse Json objects to csv file
*/
goEuro.jsonToCsv(clientResponse.getEntity(String.class));
}
}
| lgpl-3.0 |
intelligentautomation/proteus-common | src/com/iai/proteus/common/sos/data/SensorData.java | 705 | /*
* Copyright (C) 2013 Intelligent Automation Inc.
*
* All Rights Reserved.
*/
package com.iai.proteus.common.sos.data;
import java.util.Date;
import java.util.List;
/**
* Interface for sensor data
*
* @author Jakob Henriksson
*
*/
public interface SensorData {
public List<Field> getFields();
public List<Field> getFields(FieldType type);
public String[] getData(Field variable);
public List<String[]> getData();
public List<String[]> getData(List<Field> variables);
public List<String[]> getData(List<Field> variables,
Date earliest, Date latest, Field timestamp);
public List<String[]> getData(Date earliest, Date latest, Field timestamp);
public int size();
}
| lgpl-3.0 |
UnifiedViews/Plugin-DevEnv | uv-dpu-helpers/src/main/java/eu/unifiedviews/helpers/dpu/config/ConfigTransformer.java | 1783 | /**
* This file is part of UnifiedViews.
*
* UnifiedViews 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.
*
* UnifiedViews 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 UnifiedViews. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.unifiedviews.helpers.dpu.config;
/**
* Can be used to transform configuration before it's loaded by DPU/add-on.
*
* @author Škoda Petr
*/
public interface ConfigTransformer {
/**
* Configure add-on before any other non {@link ConfigTransformerAddon} or DPU is configured.
*
* @param configManager
* @throws ConfigException
*/
void configure(ConfigManager configManager) throws ConfigException;
/**
* Transform configuration on string level, before it's serialized as
* an object.
*
* @param configName
* @param config
* @return
* @throws cz.cuni.mff.xrg.uv.boost.dpu.config.ConfigException
*/
String transformString(String configName, String config) throws ConfigException;
/**
* Can transform configuration object.
*
* @param <TYPE>
* @param configName
* @param config
* @throws cz.cuni.mff.xrg.uv.boost.dpu.config.ConfigException
*/
<TYPE> void transformObject(String configName, TYPE config) throws ConfigException;
}
| lgpl-3.0 |
fuinorg/srcgen4j-core | src/main/java/org/fuin/srcgen4j/core/velocity/ParameterizedTemplateModels.java | 4340 | /**
* Copyright (C) 2015 Michael Schnell. All rights reserved.
* http://www.fuin.org/
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option) any
* later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see http://www.gnu.org/licenses/.
*/
package org.fuin.srcgen4j.core.velocity;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import org.fuin.srcgen4j.commons.SrcGen4JContext;
import org.fuin.utils4j.Utils4J;
/**
* A collection of multiple {@link ParameterizedTemplateModel} objects.
*/
public final class ParameterizedTemplateModels {
@Valid
@NotEmpty
private List<ParameterizedTemplateModel> paramTemplates;
/**
* Default constructor.
*/
public ParameterizedTemplateModels() {
super();
}
/**
* Returns the list of templates.
*
* @return Template list.
*/
public final List<ParameterizedTemplateModel> getModelList() {
return paramTemplates;
}
/**
* Sets the list of templates to a new value.
*
* @param paramTemplates
* Template list to set.
*/
public final void setParamTemplates(final List<ParameterizedTemplateModel> paramTemplates) {
this.paramTemplates = paramTemplates;
}
/**
* Adds another template to the list. If the list does not exist,it will be created.
*
* @param paramTemplate
* Template to add - Cannot be NULL.
*/
public final void addParamTemplate(final ParameterizedTemplateModel paramTemplate) {
if (paramTemplates == null) {
paramTemplates = new ArrayList<ParameterizedTemplateModel>();
}
paramTemplates.add(paramTemplate);
}
/**
* Adds all templates to the list. If the list does not exist,it will be created.
*
* @param list
* LIst of templates to add - Cannot be NULL.
*/
public final void addParamTemplates(final List<ParameterizedTemplateModel> list) {
if (list != null) {
for (final ParameterizedTemplateModel template : list) {
addParamTemplate(template);
}
}
}
/**
* Initalizes the object.
*
* @param context
* Current context.
* @param vars
* Variables to use.
*/
public final void init(final SrcGen4JContext context, final Map<String, String> vars) {
if (paramTemplates != null) {
for (final ParameterizedTemplateModel paramTemplate : paramTemplates) {
paramTemplate.init(context, vars);
}
}
}
/**
* Returns a list that contains all models that reference the given template.
*
* @param templateDir
* Directory where all template files are located - Cannot be NULL.
* @param templateFile
* File to find references to - Cannot be NULL.
*
* @return List - Never NULL, but may be empty.
*/
public final List<ParameterizedTemplateModel> findReferencesTo(final File templateDir, final File templateFile) {
final List<ParameterizedTemplateModel> result = new ArrayList<ParameterizedTemplateModel>();
if ((paramTemplates != null) && Utils4J.fileInsideDirectory(templateDir, templateFile)) {
for (final ParameterizedTemplateModel paramTemplate : paramTemplates) {
if (paramTemplate.hasReferenceTo(templateDir, templateFile)) {
result.add(paramTemplate);
}
}
}
return result;
}
}
| lgpl-3.0 |
tango-controls/JTango | server/src/test/java/org/tango/server/testserver/Kill.java | 1912 | /**
* Copyright (C) : 2012
*
* Synchrotron Soleil
* L'Orme des merisiers
* Saint Aubin
* BP48
* 91192 GIF-SUR-YVETTE CEDEX
*
* This file is part of Tango.
*
* Tango 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.
*
* Tango 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 Tango. If not, see <http://www.gnu.org/licenses/>.
*/
package org.tango.server.testserver;
public class Kill {
/**
* @param args
* @throws DevFailed
*/
// public static void main(final String[] args) throws DevFailed {
// EventServer.start();
// try {
// Thread.sleep(1000);
// } catch (final InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// ServerManager.getInstance().stop();
// try {
// Thread.sleep(2000);
// } catch (final InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// EventServer.start();
// try {
// Thread.sleep(1000);
// } catch (final InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// ServerManager.getInstance().stop();
// System.out.println("stop device out");
// // System.exit(-1);
//
// }
}
| lgpl-3.0 |
fellow99/every-cloud | every-cloud-provider/src/test/java/test/disk/kanbox/TestMetadata.java | 296 | package test.disk.kanbox;
import org.junit.BeforeClass;
import test.disk.common.AbstractTestMetadata;
public class TestMetadata extends AbstractTestMetadata{
@BeforeClass
public static void setUpBeforeClass() throws Exception {
setDiskAPI(KanboxDiskTests.getDiskAPI());
}
}
| lgpl-3.0 |
pellierd/pddl4j | src/main/java/fr/uga/pddl4j/exceptions/UsageException.java | 1457 | /*
* Copyright (c) 2010 by Damien Pellier <Damien.Pellier@imag.fr>.
*
* This file is part of PDDL4J library.
*
* PDDL4J 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.
*
* PDDL4J 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 PDDL4J. If not, see <http://www.gnu.org/licenses/>
*/
package fr.uga.pddl4j.exceptions;
/**
* Exception use for call that do not respect method contract.
*
* @author Cedric Gerard
* @version 1.0 - 04/03/2016
*/
public class UsageException extends Exception {
/**
* Default constructor with only string message.
*
* @param message the error description
*/
public UsageException(String message) {
super(message);
}
/**
* Default constructor with string message and the Java Throwable cause.
*
* @param message the error description
* @param cause the cause this trigger the exception
*/
public UsageException(String message, Throwable cause) {
super(message, cause);
}
}
| lgpl-3.0 |
nuun-io/kernel | specs/src/main/java/io/nuun/kernel/api/di/UnitModule.java | 956 | /**
* This file is part of Nuun IO Kernel Specs.
*
* Nuun IO Kernel Specs 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.
*
* Nuun IO Kernel Specs 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 Nuun IO Kernel Specs. If not, see <http://www.gnu.org/licenses/>.
*/
package io.nuun.kernel.api.di;
/**
* UnitModule is the configuration unit provided by one
*
* @author epo.jemba{@literal @}kametic.com
*
*/
public interface UnitModule extends ModuleWrapper
{
}
| lgpl-3.0 |
SonarSource/sonarqube | sonar-ws/src/main/java/org/sonarqube/ws/client/qualityprofiles/AddProjectRequest.java | 2088 | /*
* SonarQube
* Copyright (C) 2009-2022 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.sonarqube.ws.client.qualityprofiles;
import javax.annotation.Generated;
/**
* This is part of the internal API.
* This is a POST request.
* @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/qualityprofiles/add_project">Further information about this action online (including a response example)</a>
* @since 5.2
*/
@Generated("sonar-ws-generator")
public class AddProjectRequest {
private String language;
private String project;
private String qualityProfile;
/**
* This is a mandatory parameter.
*/
public AddProjectRequest setLanguage(String language) {
this.language = language;
return this;
}
public String getLanguage() {
return language;
}
/**
* This is a mandatory parameter.
* Example value: "my_project"
*/
public AddProjectRequest setProject(String project) {
this.project = project;
return this;
}
public String getProject() {
return project;
}
/**
* This is a mandatory parameter.
* Example value: "Sonar way"
*/
public AddProjectRequest setQualityProfile(String qualityProfile) {
this.qualityProfile = qualityProfile;
return this;
}
public String getQualityProfile() {
return qualityProfile;
}
}
| lgpl-3.0 |
subes/invesdwin-util | invesdwin-util-parent/invesdwin-util/src/main/java/de/invesdwin/util/bean/tuple/ImmutableEntry.java | 1347 | package de.invesdwin.util.bean.tuple;
import java.util.Map.Entry;
import javax.annotation.concurrent.Immutable;
import de.invesdwin.util.bean.AValueObject;
import de.invesdwin.util.lang.Objects;
@SuppressWarnings("serial")
@Immutable
public class ImmutableEntry<K, V> extends AValueObject implements Entry<K, V> {
private final K key;
private final V value;
protected ImmutableEntry(final K key, final V value) {
this.key = key;
this.value = value;
}
public static <K, V> ImmutableEntry<K, V> of(final K key, final V value) {
return new ImmutableEntry<K, V>(key, value);
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public int hashCode() {
return Objects.hashCode(getClass(), getKey(), getValue());
}
@Override
public boolean equals(final Object obj) {
if (obj instanceof ImmutableEntry) {
final ImmutableEntry<?, ?> castObj = (ImmutableEntry<?, ?>) obj;
return Objects.equals(getKey(), castObj.getKey()) && Objects.equals(getValue(), castObj.getValue());
} else {
return false;
}
}
@Override
public V setValue(final V value) {
throw new UnsupportedOperationException();
}
}
| lgpl-3.0 |
xinghuangxu/xinghuangxu.sonarqube | sonar-plugin-api/src/test/java/org/sonar/api/config/GlobalPropertyChangeHandlerTest.java | 2024 | /*
* 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.api.config;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
public class GlobalPropertyChangeHandlerTest {
@Test
public void propertyChangeToString() {
GlobalPropertyChangeHandler.PropertyChange change = GlobalPropertyChangeHandler.PropertyChange.create("favourite.java.version", "1.5");
assertThat(change.toString(), is("[key=favourite.java.version, newValue=1.5]"));
}
@Test
public void propertyChangeGetters() {
GlobalPropertyChangeHandler.PropertyChange change = GlobalPropertyChangeHandler.PropertyChange.create("favourite.java.version", "1.5");
assertThat(change.getKey(), is("favourite.java.version"));
assertThat(change.getNewValue(), is("1.5"));
}
@Test
public void nullNewValue() {
GlobalPropertyChangeHandler.PropertyChange change = GlobalPropertyChangeHandler.PropertyChange.create("favourite.java.version", null);
assertThat(change.getNewValue(), nullValue());
assertThat(change.toString(), is("[key=favourite.java.version, newValue=null]"));
}
}
| lgpl-3.0 |
VladimirMarkovic86/citationbook | CitationBookWeb/src/java/converter/AuthorConverter.java | 1005 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import mb.controllers.Controller;
import model.Author;
/**
*
* @author Milica Karic
*/
@FacesConverter(forClass = Author.class, value="authorConverter")
public class AuthorConverter implements Converter{
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
try {
Integer id=Integer.parseInt(value);
Author a = Controller.getInstance().findAuthorById(id);
return a;
} catch (Exception ex) {
return null;
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return String.valueOf(((Author)value).getAuthorId());
}
}
| lgpl-3.0 |
Lapiman/Galacticraft | src/main/java/micdoodle8/mods/galacticraft/core/items/ItemFlag.java | 4429 | package micdoodle8.mods.galacticraft.core.items;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import micdoodle8.mods.galacticraft.api.item.IHoldableItem;
import micdoodle8.mods.galacticraft.core.GalacticraftCore;
import micdoodle8.mods.galacticraft.core.entities.EntityFlag;
import micdoodle8.mods.galacticraft.core.proxy.ClientProxyCore;
import micdoodle8.mods.galacticraft.core.util.GCCoreUtil;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumAction;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.IIcon;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.MovingObjectPosition.MovingObjectType;
import net.minecraft.world.World;
public class ItemFlag extends Item implements IHoldableItem
{
public int placeProgress;
public ItemFlag(String assetName)
{
super();
this.setMaxDamage(0);
this.setMaxStackSize(1);
this.setUnlocalizedName(assetName);
this.setTextureName("arrow");
}
@Override
public CreativeTabs getCreativeTab()
{
return GalacticraftCore.galacticraftItemsTab;
}
@Override
public void onPlayerStoppedUsing(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer, int par4)
{
final int useTime = this.getMaxItemUseDuration(par1ItemStack) - par4;
boolean placed = false;
final MovingObjectPosition var12 = this.getMovingObjectPositionFromPlayer(par2World, par3EntityPlayer, true);
float var7 = useTime / 20.0F;
var7 = (var7 * var7 + var7 * 2.0F) / 3.0F;
if (var7 > 1.0F)
{
var7 = 1.0F;
}
if (var7 == 1.0F && var12 != null && var12.typeOfHit == MovingObjectType.BLOCK)
{
final int x = var12.blockX;
final int y = var12.blockY;
final int z = var12.blockZ;
if (!par2World.isRemote)
{
final EntityFlag flag = new EntityFlag(par2World, x + 0.5F, y + 1.0F, z + 0.5F, (int) (par3EntityPlayer.rotationYaw - 90));
if (par2World.getEntitiesWithinAABB(EntityFlag.class, AxisAlignedBB.getBoundingBox(x, y, z, x + 1, y + 3, z + 1)).isEmpty())
{
par2World.spawnEntityInWorld(flag);
flag.setType(par1ItemStack.getItemDamage());
flag.setOwner(par3EntityPlayer.getGameProfile().getName());
placed = true;
}
else
{
par3EntityPlayer.addChatMessage(new ChatComponentText(GCCoreUtil.translate("gui.flag.alreadyPlaced")));
}
}
if (placed)
{
final int var2 = this.getInventorySlotContainItem(par3EntityPlayer, par1ItemStack);
if (var2 >= 0 && !par3EntityPlayer.capabilities.isCreativeMode)
{
if (--par3EntityPlayer.inventory.mainInventory[var2].stackSize <= 0)
{
par3EntityPlayer.inventory.mainInventory[var2] = null;
}
}
}
}
}
private int getInventorySlotContainItem(EntityPlayer player, ItemStack stack)
{
for (int var2 = 0; var2 < player.inventory.mainInventory.length; ++var2)
{
if (player.inventory.mainInventory[var2] != null && player.inventory.mainInventory[var2].isItemEqual(stack))
{
return var2;
}
}
return -1;
}
@Override
public ItemStack onEaten(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer)
{
return par1ItemStack;
}
@Override
public int getMaxItemUseDuration(ItemStack par1ItemStack)
{
return 72000;
}
@Override
public EnumAction getItemUseAction(ItemStack par1ItemStack)
{
return EnumAction.none;
}
@Override
public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer)
{
par3EntityPlayer.setItemInUse(par1ItemStack, this.getMaxItemUseDuration(par1ItemStack));
return par1ItemStack;
}
@Override
@SideOnly(Side.CLIENT)
public EnumRarity getRarity(ItemStack par1ItemStack)
{
return ClientProxyCore.galacticraftItem;
}
@Override
public String getUnlocalizedName(ItemStack itemStack)
{
return "item.flag";
}
@Override
public IIcon getIconFromDamage(int damage)
{
return super.getIconFromDamage(damage);
}
@Override
public boolean shouldHoldLeftHandUp(EntityPlayer player)
{
return false;
}
@Override
public boolean shouldHoldRightHandUp(EntityPlayer player)
{
return true;
}
@Override
public boolean shouldCrouch(EntityPlayer player)
{
return false;
}
}
| lgpl-3.0 |
bumper-app/bumper-utils | src/main/java/com/bumper/utils/pojo/Issue.java | 7093 | /**
* Copyright (C) 2015 Mathieu Nayrolles
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.bumper.utils.pojo;
import com.bumper.utils.pojo.changeset.AbstractChangeset;
import com.bumper.utils.pojo.interfaces.SolrSerializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
/**
*
* @author math
*/
public class Issue implements SolrSerializable {
private int id;
private String targetVersion;
private Dataset dataset;
private People reporter;
private People assignee;
private Project project;
private String exteralId;
private String status;
private String severity;
private String resolution;
private String shortDescription;
private String longDescription;
private String issueType;
private String environment;
private Set<LifecycleEvent> issueEvents = new HashSet<>();
private Set<Comment> comments = new HashSet<>();
private Set<AbstractChangeset> changesets = new HashSet<>();
/**
*
* @return
*/
public int getId() {
return id;
}
/**
*
* @param id
*/
public void setId(int id) {
this.id = id;
}
/**
*
* @return
*/
public String getTargetVersion() {
return targetVersion;
}
/**
*
* @param targetVersion
*/
public void setTargetVersion(String targetVersion) {
this.targetVersion = targetVersion;
}
/**
*
* @return
*/
public Dataset getDataset() {
return dataset;
}
/**
*
* @param dataset
*/
public void setDataset(Dataset dataset) {
this.dataset = dataset;
}
public People getReporter() {
return reporter;
}
public void setReporter(People reporter) {
this.reporter = reporter;
}
public void addComment(Comment comment) {
this.comments.add(comment);
}
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
public People getAssignee() {
return assignee;
}
public void setAssignee(People assignee) {
this.assignee = assignee;
}
/**
*
* @return
*/
public Project getProject() {
return project;
}
/**
*
* @param project
*/
public void setProject(Project project) {
this.project = project;
}
/**
*
* @return
*/
public String getExteralId() {
return exteralId;
}
/**
*
* @param exteralId
*/
public void setExteralId(String exteralId) {
this.exteralId = exteralId;
}
/**
*
* @return
*/
public String getShortDescription() {
return shortDescription;
}
/**
*
* @param shortDescription
*/
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
/**
*
* @return
*/
public String getLongDescription() {
return longDescription;
}
/**
*
* @param longDescription
*/
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
/**
*
* @return
*/
public Set<LifecycleEvent> getIssueEvents() {
return issueEvents;
}
/**
*
* @param issueEvents
*/
public void setIssueEvents(Set<LifecycleEvent> issueEvents) {
this.issueEvents = issueEvents;
}
/**
*
* @return
*/
public Set<Comment> getComments() {
return comments;
}
/**
*
* @param comments
*/
public void setComments(Set<Comment> comments) {
this.comments = comments;
}
/**
*
* @return
*/
public Set<AbstractChangeset> getChangesets() {
return changesets;
}
/**
*
* @param changesets
*/
public void setChangesets(Set<AbstractChangeset> changesets) {
this.changesets = changesets;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public String getResolution() {
return resolution;
}
public void setResolution(String resolution) {
this.resolution = resolution;
}
public String getIssueType() {
return issueType;
}
public void setIssueType(String issueType) {
this.issueType = issueType;
}
public void addLifeCycleEvent(Date date, People people, String type, String message) {
this.issueEvents.add(new LifecycleEvent(date, people, type, message));
}
public void addLifeCycleEvent(Date date, People people, String type) {
this.issueEvents.add(new LifecycleEvent(date, people, type));
}
public void addLifeCycleEvent(LifecycleEvent lifecycleEvent) {
this.issueEvents.add(lifecycleEvent);
}
@Override
public void toSolrXML(XMLStreamWriter writer) throws XMLStreamException {
writer.writeStartElement("doc");
// ID
writer.writeStartElement("field");
writer.writeAttribute("name", "id");
writer.writeCharacters(this.issueType + "_" + this.dataset.getName() + "_" + this.exteralId);
// END ID
// DATES
for (LifecycleEvent le : issueEvents) {
writer.writeStartElement("field");
writer.writeAttribute("name", "lifecyleevent");
writer.writeAttribute("name", "id");
}
}
@Override
public String toString() {
return "Issue{" + "id=" + id + " \n, targetVersion=" + targetVersion + " \n, dataset=" + dataset + " \n, reporter=" + reporter + " \n, assignee=" + assignee + " \n, project=" + project + " \n, exteralId=" + exteralId + " \n, status=" + status + " \n, severity=" + severity + " \n, resolution=" + resolution + " \n, shortDescription=" + shortDescription + " \n, longDescription=" + longDescription + " \n, issueType=" + issueType + " \n, issueEvents=" + issueEvents + " \n, comments=" + comments + " \n, changesets=" + changesets + '}';
}
}
| lgpl-3.0 |
meteoinfo/meteoinfolib | src/org/meteoinfo/legend/MarkerType.java | 763 | /* Copyright 2012 Yaqiang Wang,
* yaqiang.wang@gmail.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.
*/
package org.meteoinfo.legend;
/**
* Marker type enum
*
* @author Yaqiang Wang
*/
public enum MarkerType {
Simple,
Character,
Image;
}
| lgpl-3.0 |
PiRSquared17/zildo | zildo/src/zildo/monde/map/Area.java | 48277 | /**
* The Land of Alembrum
* Copyright (C) 2006-2013 Evariste Boussaton
*
*
* 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 zildo.monde.map;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import zildo.Zildo;
import zildo.client.sound.Ambient.Atmosphere;
import zildo.client.sound.BankSound;
import zildo.fwk.bank.SpriteBank;
import zildo.fwk.collection.IntSet;
import zildo.fwk.file.EasyBuffering;
import zildo.fwk.file.EasySerializable;
import zildo.fwk.script.xml.element.TriggerElement;
import zildo.monde.Hasard;
import zildo.monde.dialog.Behavior;
import zildo.monde.dialog.MapDialog;
import zildo.monde.items.ItemKind;
import zildo.monde.map.Case.TileLevel;
import zildo.monde.map.Tile.TileNature;
import zildo.monde.sprites.Reverse;
import zildo.monde.sprites.Rotation;
import zildo.monde.sprites.SpriteEntity;
import zildo.monde.sprites.desc.ElementDescription;
import zildo.monde.sprites.desc.EntityType;
import zildo.monde.sprites.desc.GearDescription;
import zildo.monde.sprites.desc.PersoDescription;
import zildo.monde.sprites.desc.SpriteAnimation;
import zildo.monde.sprites.desc.SpriteDescription;
import zildo.monde.sprites.elements.Element;
import zildo.monde.sprites.elements.ElementImpact;
import zildo.monde.sprites.elements.ElementImpact.ImpactKind;
import zildo.monde.sprites.persos.Perso;
import zildo.monde.sprites.persos.Perso.PersoInfo;
import zildo.monde.sprites.persos.PersoPlayer;
import zildo.monde.sprites.utils.MouvementPerso;
import zildo.monde.sprites.utils.MouvementZildo;
import zildo.monde.util.Angle;
import zildo.monde.util.Point;
import zildo.monde.util.Zone;
import zildo.resource.Constantes;
import zildo.server.EngineZildo;
import zildo.server.SpriteManagement;
/**
* Class modelizing a map where the hero can play.
*
* @author Tchegito
*
*/
public class Area implements EasySerializable {
class SpawningTile {
Case previousCase;
int x, y;
int cnt;
String awaitedQuest; // Name of the awaited quest to be done
boolean fog; // display a fog during the respawn
int floor;
}
final static int TILE_VIEWPORT_X = (Zildo.viewPortX / 16);// + 1;
final static int TILE_VIEWPORT_Y = (Zildo.viewPortY / 16);// + 1;
public static final byte MIDDLE_FLOOR = 1; // Default floor
final static int DEFAULT_SPAWNING_TIME = 5000; // Number of frames until the tile respawns
// For roundAndRange
static public int ROUND_X = 0;
static public int ROUND_Y = 0;
static public int lineSize = 128; // Max-size of a map's line
private Point offset; // For scrolling map
private byte lowestFloor = 1;
private byte highestFloor = 1; // Default (but should be read from the map)
private int dim_x, dim_y;
private String name;
private Case[][][] mapdata; // Floor x ordinate x abscissa
private List<ChainingPoint> listChainingPoint;
private MapDialog dialogs;
private Atmosphere atmosphere;
// Elements linked to a given case (into chest, bushes, jar ...)
private Map<Integer, CaseItem> caseItem;
// To diffuse changes to clients
private final Collection<Point> changes;
// To respawn removed items
private final Collection<SpawningTile> toRespawn;
// Respawn points for Zildo (multiplayer only)
private final List<Point> respawnPoints;
private Point alertLocation; // Sound able to alert enemies
private int alertDuration = 0;
public List<Point> getRespawnPoints() {
return respawnPoints;
}
public Area() {
mapdata = new Case[Constantes.TILEENGINE_FLOOR][Constantes.TILEENGINE_HEIGHT][Constantes.TILEENGINE_HEIGHT];
listChainingPoint = new ArrayList<ChainingPoint>();
changes = new HashSet<Point>();
toRespawn = new HashSet<SpawningTile>();
caseItem = new HashMap<Integer, CaseItem>();
respawnPoints = new ArrayList<Point>();
offset = new Point(0, 0);
}
public Area(Atmosphere p_atmo) {
this();
dim_x = 64;
dim_y = 64;
int empty = p_atmo.getEmptyTile();
for (int i = 0; i < dim_x * dim_y; i++) {
int x = i % dim_x;
int y = i / dim_x;
writemap(x, y, empty);
}
atmosphere = p_atmo;
dialogs = new MapDialog();
}
// /////////////////////////////////////////////////////////////////////////////////////
// get_Areacase
// /////////////////////////////////////////////////////////////////////////////////////
// IN : coordinates
// OUT: Case object at the given coordinates
// /////////////////////////////////////////////////////////////////////////////////////
/**
* Return {@link Case} object at given map coordinates.<br/>
* In this method, floor isn't provided, so we select the highest floor.
*/
public Case get_mapcase(int x, int y) {
// TODO: a method without overflow tests could be used sometimes to enhance performance
if (x < 0 || x >= dim_x) {
return null;
}
if (y < 0 || y >= dim_y) {
return null;
}
byte floor = highestFloor;
Case c = null;
while (floor>=0) {
c = mapdata[floor][y][x];
if (c != null) break;
floor--;
}
return c;
}
public Case get_mapcase(int x, int y, int floor) {
if (x < 0 || x >= dim_x) {
return null;
}
if (y < 0 || y >= dim_y) {
return null;
}
return getMapcaseWithoutOverflow(x, y, floor);
}
/** Method without overflow test, to gain some performance **/
public Case getMapcaseWithoutOverflow(int x, int y, int floor) {
return mapdata[floor][y][x];
}
/** Set a {@link Case} object in the map, without specifying floor. Default is MIDDLE_FLOOR.**/
public void set_mapcase(int x, int y, Case c) {
mapdata[highestFloor][y][x] = c;
}
public void set_mapcase(int x, int y, byte floor, Case c) {
mapdata[floor][y][x] = c;
if (floor > highestFloor) {
highestFloor = floor;
} else if (floor < lowestFloor) {
lowestFloor = floor;
}
}
// /////////////////////////////////////////////////////////////////////////////////////
// readmap
// /////////////////////////////////////////////////////////////////////////////////////
// IN : coordinates on Area
// foreground: FALSE=on the floor TRUE=foreground
// OUT: return motif + bank*256
// /////////////////////////////////////////////////////////////////////////////////////
/**
* Basically, return the higher tile from given map coordinates, with a little bit of intelligence.<ol>
* <li>if 'foreground' is asked, and if case has a foreground tile => return it</li>
* <li>if tile has a back2, return it</li>
* <li>else return back tile</li>
* </ol>
* @param x
* @param y
* @param p_foreground TRUE=> returns the foreground tile, if it exists.
* @return Tile
*/
public Tile readmap(int x, int y, boolean p_foreground) {
return readmap(x, y, p_foreground, -1);
}
public Tile readmap(int x, int y, boolean p_foreground, int floor) {
Case temp;
if (floor == -1) { // No floor, so we take the highest
temp = get_mapcase(x, y);
} else {
temp = get_mapcase(x, y, floor);
}
if (temp == null) {
return null;
}
// Is there two layers on this tile ?
boolean masked = temp.getForeTile() != null;
if (p_foreground && masked) {
return temp.getForeTile();
} else {
if (temp.getBackTile2() != null) {
return temp.getBackTile2();
} else {
return temp.getBackTile();
}
}
}
/**
* Returns TRUE if case part pointed by PIXEL coordinates is in water.
*/
public boolean isInWater(int cx, int cy) {
// TODO: for now, we only check the global case, but will be more accurate later
int val = readmap(cx / 16, cy / 16);
return val == 256*2 + 255;
}
final IntSet waterBank = new IntSet(154, 156, 188, 189, 190, 255);
final IntSet waterDeep = new IntSet().addRange(108, 138).addRange(208, 222)
.addRange(224, 228).addRange(230, 245).addRange(247, 253);
public TileNature getCaseNature(int xx, int yy) {
int x = xx / 16;
int y = yy / 16;
Case temp = this.get_mapcase(x, y);
if (temp == null) {
return null;
}
// 1: bottom less (we have to read the BACK tile
int val = temp.getBackTile().getValue();
if (Tile.isBottomLess(val)) {
return TileNature.BOTTOMLESS;
}
if (val == Tile.T_WATER_FEW) {
return TileNature.WATER_MUD;
} else if (val == Tile.T_WATER_MUD) {
// Make double check with following 'if' clause
} else {
// 2: water (could be on back or back2)
Tile tile;
if (temp.getBackTile2() != null) {
tile = temp.getBackTile2();
} else {
tile = temp.getBackTile();
}
val = tile.getValue();
}
if (val == Tile.T_WATER_MUD) {
// Double check for water mud : it doesn't cover the whole tile
int mx = xx % 16;
int my = yy % 16;
if (TileCollision.getInstance().getBottomZ(mx, my, Tile.T_WATER_MUD, false) <0)
return TileNature.WATER_MUD;
}
if ( waterBank.contains(val - 256*2) || waterDeep.contains(val)) {
return TileNature.WATER;
}
return TileNature.REGULAR;
}
/**
* Returns TRUE if case is bottom less (example: lava or void)
*/
public boolean isCaseBottomLess(int x, int y) {
Case temp = this.get_mapcase(x, y);
if (temp == null) {
return false;
}
int val = temp.getBackTile().getValue();
// As a temporary feature : 108 means water coast, to allow smarter 'ponton' collision
if (Tile.isBottomLess(val) || val == 108) {
return true;
}
return false;
}
// Return n_motif + n_banque*256 from a given position on the Area
public int readmap(int x, int y) {
Tile tile = readmap(x, y, false);
if (tile == null) {
return -1;
} else {
return tile.getValue();
}
}
public int readAltitude(int x, int y) {
Case temp = this.get_mapcase(x, y);
if (temp == null) {
return 0;
}
return temp.getZ();
}
public void writemap(int x, int y, int quoi, TileLevel level) {
writemap(x, y, quoi, level, Rotation.NOTHING);
}
/**
* writemap
* @param x,y: coordinates
* @param quoi: value (bank*256 + index)
* @param back: TRUE means back tile
* @param back2: TRUE means
*/
public void writemap(int x, int y, int quoi, TileLevel level, Rotation rot) {
Case temp = this.get_mapcase(x, y);
if (temp == null) {
temp = new Case();
set_mapcase(x, y, temp);
} else {
temp.setModified(true);
}
Tile tile;
switch (level) {
case BACK:
default:
tile = temp.getBackTile();
break;
case BACK2:
tile = temp.getBackTile2();
if (tile == null) {
tile = new Tile(0, temp);
temp.setBackTile2(tile);
}
break;
case FORE:
tile = temp.getForeTile();
if (tile == null) {
tile = new Tile(0, temp);
temp.setForeTile(tile);
}
break;
}
tile.set(quoi, rot);
changes.add(new Point(x, y));
}
public void writemap(int x, int y, int quoi) {
writemap(x, y, quoi, TileLevel.BACK, Rotation.NOTHING);
}
// /////////////////////////////////////////////////////////////////////////////////////
// roundAndRange
// /////////////////////////////////////////////////////////////////////////////////////
// IN:float to round and range, indicator on which coordinate to compute
// ROUND_X(default) -. x , ROUND_Y -. y
// /////////////////////////////////////////////////////////////////////////////////////
// Trunc a float, and get it into the Area, with limits considerations.
// /////////////////////////////////////////////////////////////////////////////////////
public int roundAndRange(float x, int whatToRound) {
int result = (int) x;
if (x < 0) {
x = 0;
}
int max = dim_x;
if (whatToRound == ROUND_Y) {
max = dim_y;
}
if (x > (max * 16 - 16)) {
x = max * 16 - 16;
}
return result;
}
// /////////////////////////////////////////////////////////////////////////////////////
// isAlongBorder
// /////////////////////////////////////////////////////////////////////////////////////
public boolean isAlongBorder(int x, int y) {
return (x < 4 || x > dim_x * 16 - 8 || y < 4 || y > dim_y * 16 - 4);
}
// /////////////////////////////////////////////////////////////////////////////////////
// isChangingArea
// /////////////////////////////////////////////////////////////////////////////////////
// IN : x,y (pixel coordinates for perso location)
// /////////////////////////////////////////////////////////////////////////////////////
// Return ChainingPoint if Zildo's crossing one (door, or Area's border)
// /////////////////////////////////////////////////////////////////////////////////////
public ChainingPoint isChangingMap(float x, float y, Angle p_angle) {
// On parcourt les points d'enchainements
int ax = (int) (x / 8);
int ay = (int) (y / 8);
boolean border;
List<ChainingPoint> candidates = new ArrayList<ChainingPoint>();
if (listChainingPoint.size() != 0) {
for (ChainingPoint chPoint : listChainingPoint) {
if (chPoint.getComingAngle() == Angle.NULL) {
continue; // This point is only a landing position
}
// Area's borders
border = isAlongBorder((int) x, (int) y);
if (chPoint.isCollide(ax, ay, border)) {
candidates.add(chPoint);
}
}
}
if (candidates.size() == 1) {
return candidates.get(0);
} else if (candidates.size() > 0) {
// More than one possibility : we must be on a map corner
for (ChainingPoint ch : candidates) {
Angle chAngle = ch.getComingAngle().opposite();
if (chAngle == p_angle) {
return ch;
}
}
// return first one (default)
return candidates.get(0);
}
return null;
}
// /////////////////////////////////////////////////////////////////////////////////////
// addContextInfos
// /////////////////////////////////////////////////////////////////////////////////////
// Fill the given ChainingPoint with two extra infos: 'orderX' and 'orderY'
// /////////////////////////////////////////////////////////////////////////////////////
void addChainingContextInfos() {
for (ChainingPoint ch : listChainingPoint) {
int orderX = 0;
int orderY = 0;
// We're gonna get a sort number in each coordinate for all chaining point referring to the same Area.
for (ChainingPoint chP : listChainingPoint) {
if (chP.getMapname().equals(ch.getMapname()) ) { // Linking to the same map
if (chP.getPx() <= ch.getPx()) {
orderX++;
}
if (chP.getPy() <= ch.getPy()) {
orderY++;
}
}
}
ch.setOrderX(orderX);
ch.setOrderY(orderY);
}
}
// /////////////////////////////////////////////////////////////////////////////////////
// getTarget
// /////////////////////////////////////////////////////////////////////////////////////
// IN : comingArea -. Area's name
// /////////////////////////////////////////////////////////////////////////////////////
public ChainingPoint getTarget(String comingArea, int orderX, int orderY) {
if (listChainingPoint.size() != 0) {
for (ChainingPoint chPoint : listChainingPoint) {
if (chPoint.getMapname().equals(comingArea)) {
if (orderX == 0 && orderY == 0) {
return chPoint;
} else {
// Get the right one, because there is several
// connections between
// the two Areas.
if (chPoint.getOrderX() == orderX && chPoint.getOrderY() == orderY) {
return chPoint;
}
}
}
}
}
return null;
}
// /////////////////////////////////////////////////////////////////////////////////////
// attackTile
// /////////////////////////////////////////////////////////////////////////////////////
public void attackTile(int floor, Point tileLocation) {
// Check if Zildo destroy something on a tile
int onmap = readmap(tileLocation.x, tileLocation.y);
switch (onmap) {
case 165: // Bushes
Point spriteLocation = new Point(tileLocation.x * 16 + 8, tileLocation.y * 16 + 8);
EngineZildo.spriteManagement.spawnSpriteGeneric(SpriteAnimation.BUSHES, spriteLocation.x, spriteLocation.y,
floor, 0, null, null);
EngineZildo.soundManagement.broadcastSound(BankSound.CasseBuisson, spriteLocation);
takeSomethingOnTile(tileLocation, true, null, true);
break;
case 374: // Mud
writemap(tileLocation.x, tileLocation.y, 375);
break;
}
}
/**
* Explode a wall at a given location, looking for a crack sprite.
* @param loc
* @param ingame TRUE means that player is doing action. FALSE means that we restore a saved state => no explosion sound
* @param givenCrack element representing the crack in the wall (if provided, don't look for any others, indeed)
*/
public void explodeTile(Point loc, boolean ingame, Element givenCrack) {
// Look for a 'crack'
Element crack = givenCrack;
if (crack == null) {
crack = EngineZildo.spriteManagement.collideElement(loc.x, loc.y+8, null, 8,
GearDescription.CRACK1, GearDescription.CRACK2, GearDescription.BOULDER);
}
if (crack != null) {
Point tileLoc = new Point(crack.getCenter());
tileLoc.x /=16;
tileLoc.y /=16;
// Remove crack and replace tile with opened wall
crack.dying = true;
Rotation rotated = crack.rotation;
if (crack.reverse == Reverse.VERTICAL) {
rotated = rotated.succ().succ();
}
int onmap = readmap(tileLoc.x, tileLoc.y);
switch (onmap) {
case 12:
tileLoc.y--;
case 31: // Hill
TilePattern.explodedHill.apply(tileLoc.x, tileLoc.y, this, rotated);
break;
case 144+256*3:
tileLoc.y--;
case 129+256*3: // Grey cave (north)
case 148+256*3: // (south)
case 150+256*3: // (west)
case 146+256*3: // (east)
TilePattern.explodedCave.apply(tileLoc.x, tileLoc.y, this, rotated);
break;
case 285:
TilePattern.explodedHouseWall.apply(tileLoc.x, tileLoc.y, this, rotated);
break;
}
// Play secret sound
if (ingame) {
EngineZildo.scriptManagement.explodeWall(name, new Point(crack.x / 16, (crack.y-1) / 16));
EngineZildo.soundManagement.broadcastSound(BankSound.ZildoSecret, loc);
}
}
}
/**
* A tile being "hammered". Can lower plots.
* @param tileLocation
*/
public void smashTile(Point tileLocation) {
int onmap = readmap(tileLocation.x, tileLocation.y);
switch (onmap) {
case 173:
writemap(tileLocation.x, tileLocation.y, 174);
EngineZildo.soundManagement.broadcastSound(BankSound.Hammer, tileLocation.multiply(16f));
break;
}
}
/**
* Something disappeared on a tile (jar, bushes, rock ...)
*
* @param tileLocation
* location
* @param p_destroy
* TRUE if tile is attacked / FALSE for simple action (ex: Zildo picks up a bush)
* @param p_spawnGoodies TODO
*/
public void takeSomethingOnTile(Point tileLocation, boolean p_destroy, Perso p_perso, boolean p_spawnGoodies) {
int x = tileLocation.getX();
int y = tileLocation.getY();
int on_Area = readmap(x, y);
int resultTile;
SpriteAnimation anim = SpriteAnimation.FROMGROUND;
if (Tile.isClosedChest(on_Area)) { // Chest ?
resultTile = Tile.getOpenedChest(on_Area);
anim = SpriteAnimation.FROM_CHEST;
} else {
switch (on_Area) {
case 165: // Bush
default:
resultTile = 166;
break;
case 167: // Rock
case 169: // Heavy rock
resultTile = 168;
break;
case 751: // Jar
resultTile = 752;
break;
}
}
// Notify that this case should reappear after a given time (only in multiplayer mode)
if (EngineZildo.game.multiPlayer) {
addSpawningTile(tileLocation, null, DEFAULT_SPAWNING_TIME, true, p_perso != null ? p_perso.floor : highestFloor);
}
// Trigger
TriggerElement trigger = TriggerElement.createLiftTrigger(name, tileLocation);
EngineZildo.scriptManagement.trigger(trigger);
// Remove tile on back2, if present
boolean spawnGoodies = true;
Case temp = this.get_mapcase(x, y);
if (temp.getBackTile2() != null) {
if (anim == SpriteAnimation.FROM_CHEST) {
// A chest is open => replace by the right tile
temp.getBackTile2().index = resultTile;
temp.setModified(true);
} else {
// Remove back2 (bush/jar/whatever is taken => remove it)
temp.setBackTile2(null);
// Particular case : button under a jar !
if (Tile.isButton(temp.getBackTile().getValue())) {
spawnGoodies = false;
}
}
} else {
writemap(tileLocation.getX(), tileLocation.getY(), resultTile);
}
// Is there something planned to appear ?
Point p = new Point(tileLocation.x * 16 + 8, tileLocation.y * 16 + 8);
CaseItem item = getCaseItem(tileLocation.x, tileLocation.y);
ElementDescription desc = item == null ? null : item.desc;
SpriteManagement sprMgt = EngineZildo.spriteManagement;
if (p_perso != null && anim == SpriteAnimation.FROM_CHEST) {
if (desc == null) {
desc = ElementDescription.THREEGOLDCOINS1;
}
Element elem = sprMgt.spawnSpriteGeneric(SpriteAnimation.FROM_CHEST, p.x, p.y + 8, p_perso.floor, 0, p_perso, desc);
if (item != null) {
elem.setName(item.name);
}
} else {
if (desc != null) {
boolean questTrigger = false;
if (desc == ElementDescription.KEY) {
if (EngineZildo.scriptManagement.isTakenItem(name, tileLocation.x, tileLocation.y, desc)) {
return; // Don't spawn item because player has already taken it
} else {
questTrigger = true;
}
}
Element elem = sprMgt.spawnSpriteGeneric(anim, p.x, p.y + 5, 1, 0, null, desc);
elem.setName(item.name);
elem.setTrigger(questTrigger);
} else {
boolean multiPlayer = EngineZildo.game.multiPlayer;
if (spawnGoodies) {
PersoPlayer zildo = EngineZildo.persoManagement.getZildo();
if ((multiPlayer || zildo.hasItem(ItemKind.BOW) && Hasard.lanceDes(Hasard.hazardBushes_Arrow))) {
sprMgt.spawnSpriteGeneric(SpriteAnimation.ARROW, p.x, p.y + 5, 1, 0, zildo, null);
} else if (Hasard.lanceDes(Hasard.hazardBushes_GoldCoin)) {
sprMgt.spawnSpriteGeneric(SpriteAnimation.GOLDCOIN, p.x, p.y + 5, 1, 0, zildo, null);
} else if (Hasard.lanceDes(Hasard.hazardBushes_BlueDrop)) {
sprMgt.spawnSpriteGeneric(SpriteAnimation.BLUE_DROP, p.x + 3, p.y + 5, 1, p_destroy ? 0 : 1, zildo, null);
} else if (multiPlayer && Hasard.lanceDes(Hasard.hazardBushes_Bombs)) {
sprMgt.spawnSpriteGeneric(SpriteAnimation.FROMGROUND, p.x + 3, p.y + 5, 1, 0,
zildo, ElementDescription.BOMBS3);
}
}
}
}
}
// /////////////////////////////////////////////////////////////////////////////////////
// translatePoints
// /////////////////////////////////////////////////////////////////////////////////////
// Shift every Area's point by this vector (shiftX, shiftY) to another Area
// /////////////////////////////////////////////////////////////////////////////////////
public void translatePoints(int shiftX, int shiftY, Area targetArea) {
Case tempCase;
for (int i = 0; i < dim_y; i++) {
for (int j = 0; j < dim_x; j++) {
tempCase = get_mapcase(j, i);
targetArea.set_mapcase(j + shiftX, i + shiftY, tempCase);
}
}
}
public void addSpawningTile(Point tileLocation, String awaitedQuest, int time, boolean fog, int floor) {
SpawningTile spawnTile = new SpawningTile();
spawnTile.x = tileLocation.x;
spawnTile.y = tileLocation.y;
spawnTile.previousCase = new Case(get_mapcase(tileLocation.x, tileLocation.y));
spawnTile.cnt = time;
spawnTile.awaitedQuest = awaitedQuest;
spawnTile.fog = fog;
spawnTile.floor = floor;
toRespawn.add(spawnTile);
}
public void addChainingPoint(ChainingPoint ch) {
listChainingPoint.add(ch);
}
/**
* Returns chaining point linked to given map name.
* @param name
* @return ChainingPoint
*/
public ChainingPoint getNamedChainingPoint(String p_name) {
for (ChainingPoint ch : listChainingPoint) {
if (ch.getMapname().equals(p_name)) {
return ch;
}
}
return null;
}
public void removeChainingPoint(ChainingPoint ch) {
listChainingPoint.remove(ch);
}
public int getDim_x() {
return dim_x;
}
public void setDim_x(int dim_x) {
this.dim_x = dim_x;
}
public int getDim_y() {
return dim_y;
}
public void setDim_y(int dim_y) {
this.dim_y = dim_y;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ChainingPoint> getChainingPoints() {
return listChainingPoint;
}
public void setListPointsEnchainement(List<ChainingPoint> listPointsEnchainement) {
this.listChainingPoint = listPointsEnchainement;
}
public boolean isModified() {
return !changes.isEmpty();
}
public Collection<Point> getChanges() {
return changes;
}
public void resetChanges() {
changes.clear();
}
/**
* Serialize the map into an EasyWritingFile object.
*
* @return EasyWritingFile
*/
@Override
public void serialize(EasyBuffering p_file) {
// Get the right lists to serialize the right number of each one
List<SpriteEntity> entities = filterExportableSprites(EngineZildo.spriteManagement.getSpriteEntities(null));
List<Perso> persos = filterExportablePersos(EngineZildo.persoManagement.tab_perso);
int n_pe = listChainingPoint.size();
int n_persos = persos.size();
int nbFloors = highestFloor - lowestFloor + 1;
// 0) Exclude "built from perso" sprites
for (Iterator<SpriteEntity> it=entities.iterator(); it.hasNext();) {
SpriteEntity entity = it.next();
if (entity.getEntityType().isElement()) {
Element elem = (Element) entity;
if (elem.getLinkedPerso() != null || elem.getDesc() instanceof PersoDescription) {
it.remove();
}
}
}
int n_sprites = entities.size();
// 1) Header
p_file.put((byte) atmosphere.ordinal());
p_file.put((byte) dim_x);
p_file.put((byte) dim_y);
p_file.put((byte) nbFloors);
p_file.put((byte) persos.size());
p_file.put((byte) n_sprites);
p_file.put((byte) n_pe);
// 2) Save the map cases
for (int fl = lowestFloor ;fl <= highestFloor ;fl++) {
p_file.put((byte) fl);
for (int i = 0; i < dim_y; i++) {
for (int j = 0; j < dim_x; j++) {
Case temp = get_mapcase(j, i, fl);
if (temp == null) {
Case.serializeNull(p_file);
} else {
temp.serialize(p_file);
}
}
}
}
// 3) Chaining points
if (n_pe != 0) {
for (ChainingPoint ch : this.getChainingPoints()) {
ch.serialize(p_file);
}
}
// 4) Sprites
if (n_sprites != 0) {
Element elem;
String entityName;
for (SpriteEntity entity : entities) {
elem = null;
if (entity.getEntityType().isElement()) {
elem = (Element) entity;
}
p_file.put((int) entity.x);
p_file.put((int) entity.y);
if (nbFloors > 1) {
p_file.put((byte) 1); // Default floor
}
int foreground = entity.isForeground() ? SpriteEntity.FOREGROUND : 0;
int repeated = (entity.repeatX > 1 || entity.repeatY > 1 || entity.rotation != Rotation.NOTHING) ? SpriteEntity.REPEATED_OR_ROTATED : 0;
int pushable = (elem != null && elem.isPushable()) ? SpriteEntity.PUSHABLE : 0;
p_file.put((byte) (entity.getNBank() | entity.reverse.getValue() | foreground | repeated | pushable));
p_file.put((byte) entity.getNSpr());
if (repeated > 0) {
if (entity.rotation != Rotation.NOTHING) {
p_file.put((byte) (entity.rotation.value | 128));
}
p_file.put(entity.repeatX);
p_file.put(entity.repeatY);
}
entityName = entity.getName();
p_file.put(entityName);
}
}
// 5) Persos (characters)
if (n_persos != 0) {
for (Perso perso : persos) {
p_file.put((int) perso.x);
p_file.put((int) perso.y);
p_file.put((int) perso.z);
if (nbFloors > 1) {
p_file.put((byte) 1); // Default floor
}
PersoDescription desc = perso.getDesc();
p_file.put((byte) desc.getBank());
p_file.put((byte) desc.first());
p_file.put((byte) perso.getInfo().ordinal());
p_file.put(perso.getDialogSwitch());
// p_file.put((byte) 0); //(byte) perso.getEn_bras());
p_file.put((byte) perso.getQuel_deplacement().ordinal());
p_file.put((byte) perso.getAngle().ordinal());
p_file.put(perso.getName());
}
}
// 6) Sentences
if (dialogs != null) {
List<String> phrases = dialogs.getDialogs();
if (phrases.size() > 0) {
p_file.put((byte) phrases.size());
// On lit les phrases
for (String s : phrases) {
p_file.put(s);
}
// On lit le nom
Map<String, Behavior> behaviors = dialogs.getBehaviors();
for (Entry<String, Behavior> entry : behaviors.entrySet()) {
p_file.put(entry.getKey());
Behavior behav = entry.getValue();
for (int i : behav.replique) {
p_file.put((byte) i);
}
}
}
}
}
/**
* @param p_buffer
* @param p_name
* map name
* @return Area
*/
public static Area deserialize(EasyBuffering p_buffer, String p_name, boolean p_spawn) {
Area map = new Area();
map.setName(p_name);
SpriteManagement spriteManagement = EngineZildo.spriteManagement;
boolean zeditor = p_spawn && EngineZildo.game.editing;
map.setAtmosphere(Atmosphere.values()[p_buffer.readUnsignedByte()]);
map.setDim_x(p_buffer.readUnsignedByte());
map.setDim_y(p_buffer.readUnsignedByte());
int nbFloors = p_buffer.readUnsignedByte();
int n_persos = p_buffer.readUnsignedByte();
int n_sprites = p_buffer.readUnsignedByte();
int n_pe = p_buffer.readUnsignedByte();
// La map
for (int n=nbFloors; n>0; n--) {
byte fl = (byte) p_buffer.readUnsignedByte();
for (int i = 0; i < map.getDim_y(); i++) {
for (int j = 0; j < map.getDim_x(); j++) {
Case temp = Case.deserialize(p_buffer);
if (temp != null) {
map.set_mapcase(j, i, fl, temp);
if (p_spawn && !EngineZildo.game.editing) {
if (temp.getOneValued(256 + 99) != null) {
// Fumée de cheminée
spriteManagement.spawnSpriteGeneric(SpriteAnimation.CHIMNEY_SMOKE, j * 16, i * 16 - 4, fl, 0,
null, null);
}
Tile tile = temp.getOneValued(512 + 231, 512 + 49, 512 + 59, 512 + 61);
// Is this chest already opened ?
if (tile != null ) {
if (EngineZildo.scriptManagement.isOpenedChest(map.getName(), new Point(j, i))) {
tile.index = Tile.getOpenedChest(tile.getValue()) & 255;
}
}
}
}
}
}
}
// Les P.E
if (n_pe != 0) {
for (int i = 0; i < n_pe; i++) {
map.addChainingPoint(ChainingPoint.deserialize(p_buffer));
}
}
// Compute chaining points
map.addChainingContextInfos();
int floor;
// Les sprites
if (n_sprites != 0) {
for (int i = 0; i < n_sprites; i++) {
int x = p_buffer.readInt();
int y = p_buffer.readInt();
floor = 1;
if (nbFloors > 1) {
floor = p_buffer.readByte();
}
short nSpr;
short multi = p_buffer.readUnsignedByte();
// Multi contains many information : 0--15 : bank
// 16 : REPEATED or ROTATED
// 32 : FOREGROUND
// 64 : PUSHABLE
int nBank = multi & 15;
int reverse = multi & Reverse.ALL.getValue();
nSpr = p_buffer.readUnsignedByte();
SpriteEntity entity = null;
Rotation rot = Rotation.NOTHING;
byte repX=0, repY=0;
if ((multi & SpriteEntity.REPEATED_OR_ROTATED) != 0) {
int temp = p_buffer.readByte();
if ((temp & 128) != 0) {
rot = Rotation.fromInt(temp & 127);
temp = p_buffer.readByte();
}
repX = (byte) temp;
repY = p_buffer.readByte();
}
String entName= p_buffer.readString();
if (p_spawn) {
// If this sprite is on a chest tile, link them
int ax = x / 16;
int ay = (y-1) / 16;
int tileDesc = map.readmap(ax, ay);
switch (tileDesc) {
case 512 + 238: // Opened chest (don't spawn the linked item)
case 512 + 48: case 512 + 58: case 512+60:
break;
case 512 + 231: // Chest
case 512 + 49: case 512 + 59: case 512 + 61:
case 165: // Bushes
case 167: // Stone
case 169: // Heavy stone
case 751: // Jar
map.setCaseItem(ax, ay, nSpr, entName);
if (!zeditor) { // We have to see the sprites in ZEditor
break;
}
default: // else, show it as a regular element
SpriteDescription desc = SpriteDescription.Locator.findSpr(nBank, nSpr);
if (desc == GearDescription.GREEN_DOOR || // Opened door ?
desc == GearDescription.CAVE_KEYDOOR) {
ChainingPoint ch = map.getCloseChainingPoint(ax, ay);
if (ch != null && EngineZildo.scriptManagement.isOpenedDoor(map.getName(), ch)) {
break;
}
}
entity = spriteManagement.spawnSprite(desc, x, y, false, Reverse.fromInt(reverse),
false);
if (desc instanceof GearDescription && ((GearDescription)desc).isExplodable()) { // Exploded wall ?
if (EngineZildo.scriptManagement.isExplodedWall(map.getName(), new Point(ax, ay))) {
map.explodeTile(new Point(x, y), false, (Element) entity);
break;
}
}
if ((multi & SpriteEntity.FOREGROUND) != 0) {
entity.setForeground(true);
}
if ((multi & SpriteEntity.REPEATED_OR_ROTATED) != 0) {
entity.rotation = rot;
entity.repeatX = repX;
entity.repeatY = repY;
}
break;
}
if (entity != null) {
entity.setName(entName);
entity.setPushable((multi & SpriteEntity.PUSHABLE) != 0);
entity.setFloor(floor);
}
}
}
}
// Les persos
if (n_persos != 0) {
for (int i = 0; i < n_persos; i++) {
int x = p_buffer.readInt();
int y = p_buffer.readInt();
int z = p_buffer.readInt();
floor = 1;
if (nbFloors > 1) {
floor = p_buffer.readByte();
}
int sprBank = p_buffer.readUnsignedByte();
int sprDesc = p_buffer.readUnsignedByte();
SpriteDescription desc = SpriteDescription.Locator.findSpr(sprBank, sprDesc);
if (desc.getBank() == SpriteBank.BANK_ZILDO) {
desc = PersoDescription.ZILDO;
}
// Read the character informations
int info = p_buffer.readUnsignedByte();
// int en_bras=p_buffer.readUnsignedByte();
// if (en_bras!= 0) {
// throw new RuntimeException("enbras="+en_bras);
// }
String dialogSwitch = p_buffer.readString();
int move = p_buffer.readUnsignedByte();
int angle = p_buffer.readUnsignedByte();
String name = p_buffer.readString();
if ("zildo".equals(name)) {
desc = PersoDescription.ZILDO;
map.respawnPoints.add(new Point(x, y));
if (!zeditor) { // We have to see persos in ZEditor
continue;
}
}
// And spawn it if necessary
if (p_spawn) {
Perso perso = EngineZildo.persoManagement.createPerso((PersoDescription) desc, x, y, z, name,
angle);
perso.setInfo(PersoInfo.values()[info]);
perso.setQuel_deplacement(MouvementPerso.fromInt(move), false);
if (desc == PersoDescription.PANNEAU && perso.getQuel_deplacement() != MouvementPerso.IMMOBILE) {
// Fix a map bug : sign perso should be unmoveable
perso.setQuel_deplacement(MouvementPerso.IMMOBILE, true);
}
Zone zo = new Zone();
zo.x1 = map.roundAndRange(perso.getX() - 16 * 5, Area.ROUND_X);
zo.y1 = map.roundAndRange(perso.getY() - 16 * 5, Area.ROUND_Y);
zo.x2 = map.roundAndRange(perso.getX() + 16 * 5, Area.ROUND_X);
zo.y2 = map.roundAndRange(perso.getY() + 16 * 5, Area.ROUND_Y);
perso.setZone_deplacement(zo);
if (perso.getMaxpv() == 0) {
perso.setMaxpv(3);
perso.setPv(3);
}
perso.setTarget(null);
perso.setMouvement(MouvementZildo.VIDE);
perso.setDialogSwitch(dialogSwitch);
perso.initPersoFX();
spriteManagement.spawnPerso(perso);
perso.setFloor(floor);
}
}
}
// Les Phrases
int n_phrases = 0;
map.dialogs = new MapDialog();
if (!p_buffer.eof()) {
n_phrases = p_buffer.readUnsignedByte();
if (n_phrases > 0) {
// On lit les phrases
for (int i = 0; i < n_phrases; i++) {
String phrase = p_buffer.readString();
map.dialogs.addSentence(phrase);
}
if (!p_buffer.eof()) {
while (!p_buffer.eof()) {
// On lit le nom
String nomPerso = p_buffer.readString();
// On lit le comportement
short[] comportement = new short[10];
p_buffer.readUnsignedBytes(comportement, 0, 10);
map.dialogs.addBehavior(nomPerso, comportement);
}
}
}
}
if (!zeditor) {
// Complete outside of map visible in the viewport with empty tile
map.arrange();
}
if (p_spawn) {
map.correctTrees();
}
return map;
}
private final static IntSet treeToBlock = new IntSet(144, 145, 148, 149, 23 + 256 * 4, 24 + 256 * 4, 27 + 256 * 4,
28 + 256 * 4, 39 + 256 * 4, 40 + 256 * 4, 43 + 256 * 4, 44 + 256 * 4);
/**
* Add blocking tile on the hidden part of the tree in order to limit the move of characters under the tree.
*/
private void correctTrees() {
for (int j = 0; j < getDim_y(); j++) {
for (int i = 0; i < getDim_x(); i++) {
Case c = get_mapcase(i, j);
if (c != null) {
Tile foreTile = c.getForeTile();
if (foreTile != null && treeToBlock.contains(foreTile.index + foreTile.bank * 256)) {
c.getBackTile().index = 152;
c.getBackTile().bank = 0;
}
}
}
}
}
/**
* Keep only the exportable sprites. Those which are eliminated are:
* <ul>
* <li>Zildo</li>
* <li>sprites related to others (ex:shadow)</li>
* <li>house's smoke (should be fixed)</li>
* </ul>
*
* @param p_spriteEntities
* @return
*/
public List<SpriteEntity> filterExportableSprites(List<SpriteEntity> p_spriteEntities) {
List<SpriteEntity> filteredEntities = new ArrayList<SpriteEntity>();
for (SpriteEntity entity : p_spriteEntities) {
EntityType type = entity.getEntityType();
boolean ok = true;
// In singleplayer, we have to exclude the sprites related to
// others. Indeed, its will be created with the mother entity.
if (!EngineZildo.game.multiPlayer && entity.getEntityType().isElement()) {
Element elem = (Element) entity;
if (elem.getLinkedPerso() != null) {
ok = false;
}
if (elem.getNSpr() == ElementDescription.SMOKE_SMALL.ordinal()
&& elem.getNBank() == SpriteBank.BANK_ELEMENTS) {
ok = false;
// Exclude smoke too (spawned on houses)
}
}
if (entity.isZildo()) {
ok = false;
}
if (entity.isVisible() && ok && (type == EntityType.ELEMENT || type == EntityType.ENTITY)) {
filteredEntities.add(entity);
}
}
return filteredEntities;
}
public List<Perso> filterExportablePersos(List<Perso> p_persos) {
List<Perso> filteredPersos = new ArrayList<Perso>();
for (Perso perso : p_persos) {
if (!perso.isZildo()) {
filteredPersos.add(perso);
}
}
return filteredPersos;
}
public MapDialog getMapDialog() {
return dialogs;
}
/**
* Respawns disappeared things in multiplayer mode.
*/
public void update() {
// Only respawn bushes and chests in multiplayer
for (Iterator<SpawningTile> it = toRespawn.iterator(); it.hasNext();) {
SpawningTile spawnTile = it.next();
if (spawnTile.awaitedQuest != null) {
if (EngineZildo.scriptManagement.isQuestProcessing(spawnTile.awaitedQuest)) {
// Wait for given quest to be over
continue;
}
}
if (spawnTile.cnt == 0) {
int x = spawnTile.x * 16 + 8;
int y = spawnTile.y * 16 + 8;
// Respawn the tile if nothing bothers at location
int radius = 8;
if (EngineZildo.mapManagement.collideSprite(x, y, radius, null)) {
spawnTile.cnt++;
} else {
set_mapcase(spawnTile.x, spawnTile.y, (byte) spawnTile.floor, spawnTile.previousCase);
spawnTile.previousCase.setModified(true);
if (spawnTile.fog) {
EngineZildo.spriteManagement.spawnSprite(new ElementImpact(x, y, ImpactKind.SMOKE, null));
}
changes.add(new Point(spawnTile.x, spawnTile.y));
it.remove();
}
} else {
spawnTile.cnt--;
}
}
if (alertDuration == 0) {
alertLocation = null;
} else {
alertDuration--;
}
}
/** Represents an item with information in a string, usually for an item coming out of a map case. **/
static class CaseItem {
ElementDescription desc;
String name; // Name is used for example to store the quantity of gold in a purse
public CaseItem(ElementDescription desc, String name) {
this.desc = desc;
this.name = name;
}
}
/**
* Link a tile with an item description. (useful for chest)
*
* @param p_x
* map X coordinate
* @param p_y
* map Y coordinate
* @param p_nSpr
* @param p_name TODO
*/
public void setCaseItem(int p_x, int p_y, int p_nSpr, String p_name) {
ElementDescription desc = ElementDescription.fromInt(p_nSpr);
caseItem.put(lineSize * p_y + p_x, new CaseItem(desc, p_name));
}
/**
* Get the linked item description from a given position (if exists).
*
* @param p_x
* map X coordinate
* @param p_y
* map Y coordinate
* @return CaseItem
*/
public CaseItem getCaseItem(int p_x, int p_y) {
return caseItem.get(lineSize * p_y + p_x);
}
public Point getOffset() {
return offset;
}
public void setOffset(Point offset) {
this.offset = offset;
}
/**
* Returns the closest chaining point from given map-coordinates.
*
* @param p_px
* int in range 0..63
* @param p_py
* int in range 0..63
* @return ChainingPoint
*/
public ChainingPoint getCloseChainingPoint(int p_px, int p_py) {
List<ChainingPoint> points = getChainingPoints();
for (ChainingPoint ch : points) {
Zone z = ch.getZone(this);
for (Angle a : Angle.values()) {
if (!a.isDiagonal()) {
int px = p_px + a.coords.x;
int py = p_py + a.coords.y;
if (z.isInto(16 * px, 16 * py)) {
return ch;
}
}
}
}
return null;
}
/**
* Returns entities outside the map range (0..dim_x, 0..dim_y). Only used in ZEditor.
*
* @return List<SpriteEntity>
*/
public List<SpriteEntity> getOutOfBoundEntities() {
List<SpriteEntity> found = new ArrayList<SpriteEntity>();
List<SpriteEntity> entities = filterExportableSprites(EngineZildo.spriteManagement.getSpriteEntities(null));
List<Perso> persos = filterExportablePersos(EngineZildo.persoManagement.tab_perso);
entities.addAll(persos);
for (SpriteEntity entity : entities) {
if (isOutside((int) entity.x, entity.getAjustedY())) {
found.add(entity);
}
}
return found;
}
/**
* Returns TRUE if the given point (in map coordinates : 0..64,0..64) is outside the map.
*
* @param tx
* @param ty
* @return boolean
*/
public boolean isOutside(int tx, int ty) {
if (EngineZildo.mapManagement.getPreviousMap() != null) {
return false;
}
return (tx < 0 || ty < 0 ||
tx > ((dim_x - 1) << 4) + 15 ||
ty > ((dim_y - 1) << 4) + 15);
}
public Atmosphere getAtmosphere() {
return atmosphere;
}
public void setAtmosphere(Atmosphere atmosphere) {
this.atmosphere = atmosphere;
}
public void alertAtLocation(Point p) {
alertLocation = p;
alertDuration = 5;
}
final float distanceHeard = 64f;
public boolean isAnAlertAtLocation(float x, float y) {
if (alertLocation == null) {
return false;
}
double distance = Point.distance(x, y, alertLocation.x, alertLocation.y);
return distance < distanceHeard;
}
public Point getAlertLocation() {
return new Point(alertLocation);
}
public byte getLowestFloor() {
return lowestFloor;
}
public byte getHighestFloor() {
return highestFloor;
}
private void arrange() {
// Complete map size with minimum viewport
int emptyTile = atmosphere.getEmptyTile();
for (int dy = dim_y ; dy < TILE_VIEWPORT_Y ; dy++) {
for (int dx = 0; dx < Math.max(TILE_VIEWPORT_X, dim_x); dx++) {
writemap(dx, dy, emptyTile);
}
}
for (int dx = dim_x ; dx < TILE_VIEWPORT_X ; dx++) {
for (int dy = 0; dy < Math.max(TILE_VIEWPORT_Y, dim_y); dy++) {
writemap(dx, dy, emptyTile);
}
}
if (dim_x < TILE_VIEWPORT_X) {
dim_x = TILE_VIEWPORT_X;
}
if (dim_y < TILE_VIEWPORT_Y) {
dim_y = TILE_VIEWPORT_Y;
}
}
public static String[] findAllAreasName() {
File[] areaFiles = Zildo.pdPlugin.listFiles(Constantes.MAP_PATH, new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".map");
}
});
String[] res = new String[areaFiles.length];
int i=0;
for (File f : areaFiles) {
String name = f.getName();
int posPoint = name.indexOf(".");
res[i++] = f.getName().substring(0, posPoint);
}
return res;
}
/** Reinitialize map tiles **/
public void clearTiles() {
mapdata = new Case[Constantes.TILEENGINE_FLOOR][Constantes.TILEENGINE_HEIGHT][Constantes.TILEENGINE_HEIGHT];
int empty = atmosphere.getEmptyTile();
for (int i = 0; i < dim_x * dim_y; i++) {
int x = i % dim_x;
int y = i / dim_x;
writemap(x, y, empty);
}
}
/** Shift everything (tiles/chaining points/sprites) with given vector **/
public void shift(int shiftX, int shiftY) {
// 0) Tiles
// Clone tiles in an array that we'll release when this method will be over
Case[][][] mapdataCloned = mapdata.clone();
// 1) Change dimension
int movedX = dim_x;
int movedY = dim_y;
dim_x = Math.min(64, dim_x + shiftX);
dim_y = Math.min(64, dim_y + shiftY);
clearTiles();
for (int f=lowestFloor;f<=highestFloor;f++) {
for (int y=0;y<movedY;y++) {
int yy = y+shiftY;
if (yy >= 0 && yy < dim_y) {
for (int x=0;x<movedX;x++) {
int xx = x+shiftX;
if (xx >=0 && xx < dim_x) {
Case c = mapdataCloned[f][y][x];
if (c != null) {
mapdata[f][yy][xx] = c;
}
}
}
}
}
}
// 2) Chaining points
for (ChainingPoint chp : listChainingPoint) {
chp.setPx((short) (chp.getPx() + shiftX*2));
chp.setPy((short) (chp.getPy() + shiftY*2));
}
// 3) Sprites
EngineZildo.spriteManagement.shiftAllEntities(shiftX*16, shiftY*16);
}
public Point getNextMapOffset(Area nextMap, Angle p_mapScrollAngle) {
Angle angleShift = p_mapScrollAngle.opposite();
Point coords = angleShift.coords;
Area mapReference = nextMap;
switch (angleShift) {
case OUEST:
case NORD:
mapReference = this;
default:
}
return new Point(coords.x * 16 * mapReference.getDim_x(),
coords.y * 16 * mapReference.getDim_y());
}
} | lgpl-3.0 |
Michal27/dp_vips_fitlayout | src/main/java/org/fit/segm/grouping/AreaImpl.java | 29870 | /**
* VisualArea.java
*
* Created on 3-�en-06, 10:58:23 by radek
*/
package org.fit.segm.grouping;
import java.awt.Color;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.fit.layout.impl.DefaultArea;
import org.fit.layout.impl.GenericTreeNode;
import org.fit.layout.model.Area;
import org.fit.layout.model.Box;
import org.fit.layout.model.Box.Type;
import org.fit.layout.model.ContentObject;
import org.fit.layout.model.Rectangular;
import org.fit.layout.model.Tag;
import org.fit.segm.grouping.op.Separator;
import org.fit.segm.grouping.op.SeparatorSet;
/**
* An area containing several visual boxes.
*
* @author radek
*/
public class AreaImpl extends DefaultArea implements Area
{
/** Set of separators */
private SeparatorSet seps;
/**
* Area level. 0 corresponds to the areas formed by boxes, greater numbers represent
* greater level of grouping
*/
private int level = 0;
/**
* Explicitly separated area
*/
private boolean separated;
/**
* Sum for computing the average font size
*/
private float fontSizeSum;
/**
* Counter for computing the average font size
*/
private int fontSizeCnt;
private float fontWeightSum;
private int fontWeightCnt;
private float fontStyleSum;
private int fontStyleCnt;
private float underlineSum;
private int underlineCnt;
private float lineThroughSum;
private int lineThroughCnt;
//================================================================================
/**
* Creates an empty area of a given size
*/
public AreaImpl(int x1, int y1, int x2, int y2)
{
this(new Rectangular(x1, y1, x2, y2));
}
/**
* Creates an empty area of a given size
*/
public AreaImpl(Rectangular r)
{
super(r);
}
/**
* Creates an area from a single box. Update the area bounds and name accordingly.
* @param box The source box that will be contained in this area
*/
public AreaImpl(Box box)
{
super(box);
}
/**
* Creates an area from a a list of boxes. Update the area bounds and name accordingly.
* @param boxList The source boxes that will be contained in this area
*/
public AreaImpl(Vector<Box> boxList)
{
super(boxList);
}
/**
* Creates a copy of another area.
* @param src The source area
*/
public AreaImpl(AreaImpl src)
{
super(src);
level = src.level;
fontSizeSum = src.fontSizeSum;
fontSizeCnt = src.fontStyleCnt;
fontStyleSum = src.fontStyleSum;
fontStyleCnt = src.fontStyleCnt;
fontWeightSum = src.fontWeightSum;
fontWeightCnt = src.fontWeightCnt;
underlineCnt = src.underlineCnt;
underlineSum = src.underlineSum;
lineThroughCnt = src.lineThroughCnt;
lineThroughSum = src.lineThroughSum;
}
@Override
public void appendChild(Area child)
{
super.appendChild(child);
updateAverages((AreaImpl) child);
}
@Override
public void appendChildren(List<Area> list)
{
for (Area child : list)
appendChild(child);
}
@Override
public void removeAllChildren()
{
super.removeAllChildren();
resetAverages();
}
/**
* Joins this area with another area and updates the layout in the grid to the given values.
* Moves the children of the other areas to this area.
* @param other The area to be joined to this area
* @param pos The position of the result in the grid
* @param horizontal Horizontal or vertical join?
*/
//@SuppressWarnings({ "rawtypes", "unchecked" })
public void joinArea(AreaImpl other, Rectangular pos, boolean horizontal)
{
setGridPosition(pos);
if (other.getChildCount() > 0)
{
Vector<GenericTreeNode> adopt = new Vector<GenericTreeNode>(other.getChildren());
for (Iterator<GenericTreeNode> it = adopt.iterator(); it.hasNext();)
appendChild((AreaImpl) it.next());
}
join(other, horizontal);
//copy the tag while preserving the higher support //TODO is this corect?
for (Map.Entry<Tag, Float> entry : other.getTags().entrySet())
{
if (!getTags().containsKey(entry.getKey()) || entry.getValue() > getTags().get(entry.getKey()))
getTags().put(entry.getKey(), entry.getValue());
}
}
/**
* Joins another area to this area. Update the bounds and the name accordingly.
* @param other The area to be joined to this area.
* @param horizontal If true, the areas are joined horizontally.
* This influences the resulting area borders. If false, the areas are joined vertically.
*/
public void join(AreaImpl other, boolean horizontal)
{
getBounds().expandToEnclose(other.getBounds());
setName(getName() + " . " + other.getName());
//update border information according to the mutual area positions
if (horizontal)
{
if (getX1() <= other.getX1())
{
if (other.hasRightBorder())
setRightBorder(other.getRightBorder());
}
else
{
if (other.hasLeftBorder())
setLeftBorder(other.getLeftBorder());
}
}
else
{
if (getY1() <= other.getY1())
{
if (other.hasBottomBorder())
setBottomBorder(other.getBottomBorder());
}
else
{
if (other.hasTopBorder())
setTopBorder(other.getTopBorder());
}
}
//add all the contained boxes
getBoxes().addAll(other.getBoxes());
updateAverages(other);
//just a test
if (!this.hasSameBackground(other))
System.err.println("Area: Warning: joining areas " + getName() + " and " + other.getName() +
" of different background colors " + this.getBackgroundColor() + " x " + other.getBackgroundColor());
}
/**
* Joins a child area to this area. Updates the bounds and the name accordingly.
* @param other The child area to be joined to this area.
*/
public void joinChild(AreaImpl other)
{
for (Box box : other.getBoxes())
addBox(box);
getBounds().expandToEnclose(other.getBounds());
setName(getName() + " . " + other.getName());
}
public int getLevel()
{
return level;
}
public void setLevel(int level)
{
this.level = level;
}
public String toString()
{
String bs = "";
//bs += "{" + getAverageFontSize() + "=" + fontSizeSum + "/" + fontSizeCnt + "}";
/* + ":" + getAverageFontWeight()
+ ":" + getAverageFontStyle() + "}";*/
if (hasTopBorder()) bs += "^";
if (hasLeftBorder()) bs += "<";
if (hasRightBorder()) bs += ">";
if (hasBottomBorder()) bs += "_";
if (isBackgroundSeparated()) bs += "*";
/*if (isHorizontalSeparator()) bs += "H";
if (isVerticalSeparator()) bs += "I";*/
/*if (getBackgroundColor() != null)
bs += "\"" + String.format("#%02x%02x%02x", getBackgroundColor().getRed(), getBackgroundColor().getGreen(), getBackgroundColor().getBlue()) + "\"";*/
if (getName() != null)
return bs + " " + getName() + " " + getBounds().toString();
else
return bs + " " + "<area> " + getBounds().toString();
}
/**
* Add the box node to the area if its bounds are inside of the area bounds.
* @param node The box node to be added
*/
public void chooseBox(Box node)
{
if (getBounds().encloses(node.getVisualBounds()))
addBox(node);
}
//=================================================================================
/**
* Checks if this area has the same background color as another area
* @param other the other area
* @return true if the areas are both transparent or they have the same
* background color declared
*/
public boolean hasSameBackground(AreaImpl other)
{
return (getBackgroundColor() == null && other.getBackgroundColor() == null) ||
(getBackgroundColor() != null && other.getBackgroundColor() != null && getBackgroundColor().equals(other.getBackgroundColor()));
}
public boolean encloses(AreaImpl other)
{
return getBounds().encloses(other.getBounds());
}
public boolean contains(int x, int y)
{
return getBounds().contains(x, y);
}
public boolean hasContent()
{
return !getBoxes().isEmpty();
}
@Override
public Color getEffectiveBackgroundColor()
{
if (getBackgroundColor() != null)
return getBackgroundColor();
else
{
if (getParentArea() != null)
return getParentArea().getEffectiveBackgroundColor();
else
return Color.WHITE; //use white as the default root color
}
}
//======================================================================================
/**
* @return true if the area contains any text
*/
public boolean containsText()
{
for (Box root : getBoxes())
{
if (recursiveContainsText(root))
return true;
}
return false;
}
private boolean recursiveContainsText(Box root)
{
if (root.getChildCount() == 0)
{
return root.getText().trim().length() > 0;
}
else
{
for (int i = 0; i < root.getChildCount(); i++)
if (recursiveContainsText(root.getChildBox(i)))
return true;
return false;
}
}
/**
* @return true if the area contains replaced boxes only
*/
@Override
public boolean isReplaced()
{
boolean empty = true;
for (Box root : getBoxes())
{
empty = false;
if (root.getType() != Box.Type.REPLACED_CONTENT)
return false;
}
return !empty;
}
/**
* Returns the text string represented by a concatenation of all
* the boxes contained directly in this area (no subareas)
*/
public String getBoxText()
{
StringBuilder ret = new StringBuilder();
boolean start = true;
for (Iterator<Box> it = getBoxes().iterator(); it.hasNext(); )
{
if (!start) ret.append(' ');
else start = false;
ret.append(it.next().getText());
}
return ret.toString();
}
/**
* Returns the text string represented by a concatenation of all
* the boxes contained directly in this area.
*/
public int getTextLength()
{
int ret = 0;
for (Box box : getBoxes())
{
ret += box.getText().length();
}
return ret;
}
/**
* @return true if the area contains any text
*/
public ContentObject getReplacedContent()
{
for (Iterator<Box> it = getBoxes().iterator(); it.hasNext(); )
{
ContentObject obj = recursiveGetReplacedContent(it.next());
if (obj != null)
return obj;
}
return null;
}
private ContentObject recursiveGetReplacedContent(Box root)
{
if (root.getChildCount() == 0)
{
return root.getContentObject();
}
else
{
for (int i = 0; i < root.getChildCount(); i++)
{
ContentObject obj = recursiveGetReplacedContent(root.getChildBox(i));
if (obj != null)
return obj;
}
return null;
}
}
/**
* Tries to guess if this area acts as a horizontal separator. The criteria are:
* <ul>
* <li>It doesn't contain any text</li>
* <li>It is visible</li>
* <li>It is low and wide</li>
* </ul>
* @return true if the area can be used as a horizontal separator
*/
@Override
public boolean isHorizontalSeparator()
{
return !containsText() &&
getBounds().getHeight() < 10 &&
getBounds().getWidth() > 20 * getBounds().getHeight();
}
/**
* Tries to guess if this area acts as a vertical separator. The criteria are the same
* as for the horizontal one.
* @return true if the area can be used as a vertical separator
*/
@Override
public boolean isVerticalSeparator()
{
return !containsText() &&
getBounds().getWidth() < 10 &&
getBounds().getHeight() > 20 * getBounds().getWidth();
}
/**
* Returns the font size declared for the first box. If there are multiple boxes,
* the first one is used. If there are no boxes (an artificial area), 0 is returned.
* @return the declared font size or 0 if there are no boxes
*/
public float getDeclaredFontSize()
{
if (getBoxes().size() > 0)
return getBoxes().firstElement().getFontSize();
else
return 0;
}
/**
* Computes the average font size of the boxes in the area
* @return the font size
*/
@Override
public float getFontSize()
{
if (fontSizeCnt == 0)
return 0;
else
return fontSizeSum / fontSizeCnt;
}
/**
* Computes the average font weight of the boxes in the area
* @return the font size
*/
@Override
public float getFontWeight()
{
if (fontWeightCnt == 0)
return 0;
else
return fontWeightSum / fontWeightCnt;
}
/**
* Computes the average font style of the boxes in the area
* @return the font style
*/
@Override
public float getFontStyle()
{
if (fontStyleCnt == 0)
return 0;
else
return fontStyleSum / fontStyleCnt;
}
@Override
public float getUnderline()
{
if (underlineCnt == 0)
return 0;
else
return underlineSum / underlineCnt;
}
@Override
public float getLineThrough()
{
if (lineThroughCnt == 0)
return 0;
else
return lineThroughSum / lineThroughCnt;
}
/**
* Computes the average luminosity of the boxes in the area
* @return the font size
*/
public float getColorLuminosity()
{
if (getBoxes().isEmpty())
return 0;
else
{
float sum = 0;
int len = 0;
for (Box box : getBoxes())
{
int l = box.getText().length();
sum += colorLuminosity(box.getColor()) * l;
len += l;
}
return sum / len;
}
}
/**
* Updates the average values when a new area is added or joined
* @param other the other area
*/
public void updateAverages(AreaImpl other)
{
fontSizeCnt += other.fontSizeCnt;
fontSizeSum += other.fontSizeSum;
fontWeightCnt += other.fontWeightCnt;
fontWeightSum += other.fontWeightSum;
fontStyleCnt += other.fontStyleCnt;
fontStyleSum += other.fontStyleSum;
underlineCnt += other.underlineCnt;
underlineSum += other.underlineSum;
lineThroughCnt += other.lineThroughCnt;
lineThroughSum += other.lineThroughSum;
}
/**
* Resets the averages to the values obtained from the text boxes
* that belong to this area only. No subareas are considered.
*/
protected void resetAverages()
{
fontSizeCnt = 0;
fontSizeSum = 0;
fontWeightCnt = 0;
fontWeightSum = 0;
fontStyleCnt = 0;
fontStyleSum = 0;
underlineCnt = 0;
underlineSum = 0;
lineThroughCnt = 0;
lineThroughSum = 0;
for (Box box : getBoxes())
updateAveragesForBox(box);
}
@Override
public String getText()
{
String ret = "";
if (isLeaf())
ret = getBoxText();
else
for (int i = 0; i < getChildCount(); i++)
ret += getChildArea(i).getText();
return ret;
}
/**
* Returns the child areas whose absolute coordinates intersect with the specified rectangle.
*/
public Vector<AreaImpl> getChildNodesInside(Rectangular r)
{
Vector<AreaImpl> ret = new Vector<AreaImpl>();
for (GenericTreeNode child : getChildren())
{
AreaImpl childarea = (AreaImpl) child;
if (childarea.getBounds().intersects(r))
ret.add(childarea);
}
return ret;
}
/**
* Check if there are some children in the given subarea of the area.
*/
public boolean isAreaEmpty(Rectangular r)
{
for (GenericTreeNode child : getChildren())
{
AreaImpl childarea = (AreaImpl) child;
if (childarea.getBounds().intersects(r))
return false;
}
return true;
}
/**
* Creates a set of the horizontal and vertical separators
*/
public void createSeparators()
{
seps = Config.createSeparators(this);
}
/**
* @return the set of separators in this area
*/
public SeparatorSet getSeparators()
{
return seps;
}
/**
* Removes simple separators from current separator set. A simple separator
* has only one or zero visual areas at each side
*/
public void removeSimpleSeparators()
{
removeSimpleSeparators(seps.getHorizontal());
removeSimpleSeparators(seps.getVertical());
removeSimpleSeparators(seps.getBoxsep());
}
/**
* Removes simple separators from a vector of separators. A simple separator
* has only one or zero visual areas at each side
*/
private void removeSimpleSeparators(Vector<Separator> v)
{
//System.out.println("Rem: this="+this);
for (Iterator<Separator> it = v.iterator(); it.hasNext();)
{
Separator sep = it.next();
if (sep.getType() == Separator.HORIZONTAL || sep.getType() == Separator.BOXH)
{
int a = countAreasAbove(sep);
int b = countAreasBelow(sep);
if (a <= 1 && b <= 1)
it.remove();
}
else
{
int a = countAreasLeft(sep);
int b = countAreasRight(sep);
if (a <= 1 && b <= 1)
it.remove();
}
}
}
/**
* @return the number of the areas directly above the separator
*/
private int countAreasAbove(Separator sep)
{
int gx1 = getGrid().findCellX(sep.getX1());
int gx2 = getGrid().findCellX(sep.getX2());
int gy = getGrid().findCellY(sep.getY1() - 1);
int ret = 0;
if (gx1 >= 0 && gx2 >= 0 && gy >= 0)
{
int i = gx1;
while (i <= gx2)
{
AreaImpl node = (AreaImpl) getGrid().getAreaAt(i, gy);
//System.out.println("Search: " + i + ":" + gy + " = " + node);
if (node != null)
{
ret++;
i += node.getGridWidth();
}
else
i++;
}
}
return ret;
}
/**
* @return the number of the areas directly below the separator
*/
private int countAreasBelow(Separator sep)
{
int gx1 = getGrid().findCellX(sep.getX1());
int gx2 = getGrid().findCellX(sep.getX2());
int gy = getGrid().findCellY(sep.getY2() + 1);
int ret = 0;
if (gx1 >= 0 && gx2 >= 0 && gy >= 0)
{
int i = gx1;
while (i <= gx2)
{
AreaImpl node = (AreaImpl) getGrid().getAreaAt(i, gy);
//System.out.println("Search: " + i + ":" + gy + " = " + node);
if (node != null)
{
ret++;
i += node.getGridWidth();
}
else
i++;
}
}
return ret;
}
/**
* @return the number of the areas directly on the left of the separator
*/
private int countAreasLeft(Separator sep)
{
int gy1 = getGrid().findCellY(sep.getY1());
int gy2 = getGrid().findCellY(sep.getY2());
int gx = getGrid().findCellX(sep.getX1() - 1);
int ret = 0;
if (gy1 >= 0 && gy2 >= 0 && gx >= 0)
{
int i = gy1;
while (i <= gy2)
{
AreaImpl node = (AreaImpl) getGrid().getAreaAt(gx, i);
if (node != null)
{
ret++;
i += node.getGridWidth();
}
else
i++;
}
}
return ret;
}
/**
* @return the number of the areas directly on the left of the separator
*/
private int countAreasRight(Separator sep)
{
int gy1 = getGrid().findCellY(sep.getY1());
int gy2 = getGrid().findCellY(sep.getY2());
int gx = getGrid().findCellX(sep.getX2() + 1);
int ret = 0;
if (gy1 >= 0 && gy2 >= 0 && gx >= 0)
{
int i = gy1;
while (i <= gy2)
{
AreaImpl node = (AreaImpl) getGrid().getAreaAt(gx, i);
if (node != null)
{
ret++;
i += node.getGridWidth();
}
else
i++;
}
}
return ret;
}
/**
* Looks for the nearest text box area placed above the separator. If there are more
* such areas in the same distance, the leftmost one is returned.
* @param sep the separator
* @return the leaf area containing the box or <code>null</code> if there is nothing above the separator
*/
public AreaImpl findContentAbove(Separator sep)
{
return recursiveFindAreaAbove(sep.getX1(), sep.getX2(), 0, sep.getY1());
}
private AreaImpl recursiveFindAreaAbove(int x1, int x2, int y1, int y2)
{
AreaImpl ret = null;
int maxx = x2;
int miny = y1;
Vector <Box> boxes = getBoxes();
for (Box box : boxes)
{
int bx = box.getBounds().getX1();
int by = box.getBounds().getY2();
if ((bx >= x1 && bx <= x2 && by < y2) && //is placed above
(by > miny ||
(by == miny && bx < maxx)))
{
ret = this; //found in our boxes
if (bx < maxx) maxx = bx;
if (by > miny) miny = by;
}
}
for (int i = 0; i < getChildCount(); i++)
{
AreaImpl child = (AreaImpl) getChildArea(i);
AreaImpl area = child.recursiveFindAreaAbove(x1, x2, miny, y2);
if (area != null)
{
int bx = area.getX1();
int by = area.getY2();
int len = area.getText().length();
if ((len > 0) && //we require some text in the area
(by > miny ||
(by == miny && bx < maxx)))
{
ret = area;
if (bx < maxx) maxx = bx;
if (by > miny) miny = by;
}
}
}
return ret;
}
//=================================================================================
/**
* Adds a new box to the area and updates the area bounds.
* @param box the new box to add
*/
protected void addBox(Box box)
{
super.addBox(box);
updateAveragesForBox(box);
}
private void updateAveragesForBox(Box box)
{
if (box.getType() == Box.Type.TEXT_CONTENT)
{
int len = box.getText().trim().length();
if (len > 0)
{
fontSizeSum += getAverageBoxFontSize(box) * len;
fontSizeCnt += len;
fontWeightSum += getAverageBoxFontWeight(box) * len;
fontWeightCnt += len;
fontStyleSum += getAverageBoxFontStyle(box) * len;
fontStyleCnt += len;
}
}
}
private float getAverageBoxFontSize(Box box)
{
if (box.getType() == Type.TEXT_CONTENT)
return box.getFontSize();
else if (box.getType() == Type.REPLACED_CONTENT)
return 0;
else
{
float sum = 0;
int cnt = 0;
for (int i = 0; i < getChildCount(); i++)
{
Box child = box.getChildBox(i);
String text = child.getText().trim();
cnt += text.length();
sum += getAverageBoxFontSize(child);
}
if (cnt > 0)
return sum / cnt;
else
return 0;
}
}
private float getAverageBoxFontWeight(Box box)
{
if (box.getType() == Type.TEXT_CONTENT)
return box.getFontWeight();
else if (box.getType() == Type.REPLACED_CONTENT)
return 0;
else
{
float sum = 0;
int cnt = 0;
for (int i = 0; i < getChildCount(); i++)
{
Box child = box.getChildBox(i);
String text = child.getText().trim();
cnt += text.length();
sum += getAverageBoxFontWeight(child);
}
if (cnt > 0)
return sum / cnt;
else
return 0;
}
}
private float getAverageBoxFontStyle(Box box)
{
if (box.getType() == Type.TEXT_CONTENT)
return box.getFontStyle();
else if (box.getType() == Type.REPLACED_CONTENT)
return 0;
else
{
float sum = 0;
int cnt = 0;
for (int i = 0; i < getChildCount(); i++)
{
Box child = box.getChildBox(i);
String text = child.getText().trim();
cnt += text.length();
sum += getAverageBoxFontStyle(child);
}
if (cnt > 0)
return sum / cnt;
else
return 0;
}
}
private float colorLuminosity(Color c)
{
float lr, lg, lb;
if (c == null)
{
lr = lg = lb = 255;
}
else
{
lr = (float) Math.pow(c.getRed() / 255.0f, 2.2f);
lg = (float) Math.pow(c.getGreen() / 255.0f, 2.2f);
lb = (float) Math.pow(c.getBlue() / 255.0f, 2.2f);
}
return lr * 0.2126f + lg * 0.7152f + lb * 0.0722f;
}
//==========================================================================
// TESTS
//==========================================================================
/**
* @return <code>true<code> if the area is separated from the areas below it
*/
public boolean separatedDown()
{
return hasBottomBorder() || isBackgroundSeparated();
}
/**
* @return <code>true<code> if the area is separated from the areas above it
*/
public boolean separatedUp()
{
return hasTopBorder() || isBackgroundSeparated();
}
/**
* @return <code>true<code> if the area is separated from the areas on the left
*/
public boolean separatedLeft()
{
return hasLeftBorder() || isBackgroundSeparated();
}
/**
* @return <code>true<code> if the area is separated from the areas on the right
*/
public boolean separatedRight()
{
return hasRightBorder() || isBackgroundSeparated();
}
/**
* When set to true, the area is considered to be separated from other
* areas explicitly, i.e. independently on its real borders or background.
* This is usually used for some new superareas.
* @return <code>true</code>, if the area is explicitly separated
*/
public boolean isExplicitlySeparated()
{
return separated;
}
/**
* When set to true, the area is considered to be separated from other
* areas explicitly, i.e. independently on its real borders or background.
* This is usually used for some new superareas.
* @param separated <code>true</code>, if the area should be explicitly separated
*/
public void setSeparated(boolean separated)
{
this.separated = separated;
}
/**
* Obtains the overall style of the area.
* @return the area style
*/
public AreaStyle getStyle()
{
return new AreaStyle(this);
}
/**
* Compares two areas and decides whether they have the same style. The thresholds of the style are taken from the {@link Config}.
* @param other the other area to be compared
* @return <code>true</code> if the areas are considered to have the same style
*/
public boolean hasSameStyle(AreaImpl other)
{
return getStyle().isSameStyle(other.getStyle());
}
}
| lgpl-3.0 |
SergiyKolesnikov/fuji | examples/Chat_casestudies/chat-luong/build/Color/ChatLineListener.java | 307 | package Color;
/**
* Listener that gets informed every time when the chat client receives a new
* message
*/
public interface ChatLineListener {
/**
* New text message received by client.
*
* @param line
* the new message
*/
void newChatLine(TextMessage msg);
} | lgpl-3.0 |
cloudstore/cloudstore | co.codewizards.cloudstore.core/src/main/java/co/codewizards/cloudstore/core/version/VersionInfoProvider.java | 879 | package co.codewizards.cloudstore.core.version;
import static co.codewizards.cloudstore.core.objectfactory.ObjectFactoryUtil.*;
import co.codewizards.cloudstore.core.dto.VersionInfoDto;
import co.codewizards.cloudstore.core.updater.CloudStoreUpdaterCore;
public class VersionInfoProvider {
protected VersionInfoProvider() {
}
public static VersionInfoProvider getInstance() {
return createObject(VersionInfoProvider.class);
}
public VersionInfoDto getVersionInfoDto() {
final VersionInfoDto versionInfoDto = new VersionInfoDto();
versionInfoDto.setLocalVersion(getLocalVersion());
versionInfoDto.setMinimumRemoteVersion(getMinimumRemoteVersion());
return versionInfoDto;
}
protected Version getLocalVersion() {
return new CloudStoreUpdaterCore().getLocalVersion();
}
protected Version getMinimumRemoteVersion() {
return new Version("0.9.12");
}
}
| lgpl-3.0 |
exoplatform/platform-qa-ui | platform/src/test/java/org/exoplatform/platform/qa/ui/platform/social/SOCPeopleSearchTestIT.java | 12474 | package org.exoplatform.platform.qa.ui.platform.social;
import static com.codeborne.selenide.Selectors.byXpath;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.refresh;
import static org.exoplatform.platform.qa.ui.selenium.Utils.getRandomString;
import static org.exoplatform.platform.qa.ui.selenium.locator.ConnectionsLocator.ELEMENT_CONNECTION_USER_NAME;
import static org.exoplatform.platform.qa.ui.selenium.logger.Logger.info;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import com.codeborne.selenide.Condition;
import org.exoplatform.platform.qa.ui.commons.Base;
import org.exoplatform.platform.qa.ui.core.PLFData;
import org.exoplatform.platform.qa.ui.selenium.platform.ConnectionsManagement;
import org.exoplatform.platform.qa.ui.selenium.platform.HomePagePlatform;
import org.exoplatform.platform.qa.ui.selenium.platform.ManageLogInOut;
import org.exoplatform.platform.qa.ui.selenium.platform.NavigationToolbar;
import org.exoplatform.platform.qa.ui.selenium.platform.social.UserProfilePage;
import org.exoplatform.platform.qa.ui.social.pageobject.AddUsers;
@Tag("social")
@Tag("sniff")
public class SOCPeopleSearchTestIT extends Base {
NavigationToolbar navigationToolbar;
AddUsers addUsers;
HomePagePlatform homePagePlatform;
ConnectionsManagement connectionsManagement;
UserProfilePage userProfilePage;
ManageLogInOut manageLogInOut;
@BeforeEach
public void setupBeforeMethod() {
info("Start setUpBeforeMethod");
navigationToolbar = new NavigationToolbar(this);
addUsers = new AddUsers(this);
homePagePlatform = new HomePagePlatform(this);
connectionsManagement = new ConnectionsManagement(this);
userProfilePage = new UserProfilePage(this);
manageLogInOut = new ManageLogInOut(this);
manageLogInOut.signInCas(PLFData.DATA_USER1, "gtngtn");
}
/**
* <li>Case ID:121904.</li>
* <li>Test Case Name: Search people by name.</li>
* <li>Case ID:121964.</li>
* <li>Test Case Name: Search people by position.</li>
* <li>Case ID:121965.</li>
* <li>Test Case Name: Search people by skill.</li>
* <li>Case ID:121966.</li>
* <li>Test Case Name: Search people by directory.</li> Step Number: 1 Step
* Name: Step 1: Search people by name PreConditions: - There's are some people
* with name has character "t" for example Step Description: - Log in and click
* Connections on the left panel - Enter keyword "n" into the [Search by name]
* box and press Enter Input Data: Expected Outcome: - Display all results match
* with keyword Step Number: 2 Step Name: Step 2: Search people by position
* PreConditions: - There's are some people who have the same position Step
* Description: - Log in and click Connections on the left panel - Enter keyword
* position into the [Search by position] box and press Enter Input Data:
* Expected Outcome: - Display all results match with keyword Step Number: 3
* Step Name: Step 3: Search people by skill PreConditions: - There's are some
* people who have the same skill Step Description: - Log in and click
* Connections on the left panel - Enter keyword skill into the [Search by
* skill] box and press Enter Input Data: Expected Outcome: - Display all
* results match with keyword Step Name: Step 4: Search people by directory Step
* Description: - Log in and click Connections on the left panel - Click on
* character from people directory characters list Input Data: Expected Outcome:
* - Display all user which has the last name starting by selected char
*/
@Test
public void test01SearchPeopleByName() {
/* Create data test */
String username1 = "ausernamea" + getRandomString();
String email1 = username1 + "@test.com";
String username2 = "busernameb" + getRandomString();
String email2 = username2 + "@test.com";
String username3 = "usernamec" + getRandomString();
String email3 = username3 + "@test.com";
String password = "123456";
info("Add user");
navigationToolbar.goToAddUser();
addUsers.addUser(username1, password, email1, username1, username1);
addUsers.addUser(username2, password, email2, username2, username2);
addUsers.addUser(username3, password, email3, username3, username3);
info("Login as John");
manageLogInOut.signIn(username3, password);
info("Click on Connections on the left panel");
homePagePlatform.goToConnections();
info("Test case 01: Search people by name");
connectionsManagement.searchPeople(username1, "", "", "");
$(byXpath(ELEMENT_CONNECTION_USER_NAME.replace("${user}", username1))).should(Condition.exist);
$(byXpath(ELEMENT_CONNECTION_USER_NAME.replace("${user}", username2))).shouldNot(Condition.exist);
refresh();
manageLogInOut.signIn(PLFData.DATA_USER1, "gtngtn");
navigationToolbar.goToManageCommunity();
addUsers.deleteUser(username1);
addUsers.deleteUser(username2);
addUsers.deleteUser(username3);
}
@Test
public void test02_SearchPeopleByPosition() {
String organization1 = "organization1" + getRandomString();
String jobTitle1 = "jobTitle1" + getRandomString();
String jobDetail1 = "jobDetail1" + getRandomString();
String skill1 = "skill1" + getRandomString();
String dStart = getDate(-7, "MM/dd/yyyy");
String organization2 = "organization2" + getRandomString();
String jobTitle2 = "jobTitle2" + getRandomString();
String jobDetail2 = "jobDetail2" + getRandomString();
String skill2 = "skill2" + getRandomString();
/* Create data test */
String username1 = "ausernamea" + getRandomString();
String email1 = username1 + "@test.com";
String username2 = "busernameb" + getRandomString();
String email2 = username2 + "@test.com";
String username3 = "usernamec" + getRandomString();
String email3 = username3 + "@test.com";
String password = "123456";
info("Add user");
navigationToolbar.goToAddUser();
addUsers.addUser(username1, password, email1, username1, username1);
addUsers.addUser(username2, password, email2, username2, username2);
addUsers.addUser(username3, password, email3, username3, username3);
manageLogInOut.signIn(username1, password);
info("Edit user profile of user 1");
info("Click on the name of user, click on My profile");
navigationToolbar.goToMyProfile();
info("Click on Edit button to change user's information");
userProfilePage.goToEditProfile();
userProfilePage.updateGenderJob("", jobTitle1);
userProfilePage.updateExperience(organization1, jobTitle1, jobDetail1, skill1, dStart, null, true);
userProfilePage.saveCancelUpdateInfo(true);
info("Edit user profile of user 1");
info("Click on the name of user, click on My profile");
refresh();
manageLogInOut.signIn(username2, password);
navigationToolbar.goToMyProfile();
info("Click on Edit button to change user's information");
userProfilePage.goToEditProfile();
userProfilePage.updateGenderJob("", jobTitle2);
userProfilePage.updateExperience(organization2, jobTitle2, jobDetail2, skill2, dStart, null, true);
userProfilePage.saveCancelUpdateInfo(true);
info("Login as John");
manageLogInOut.signIn(username3, password);
refresh();
info("Click on Connections on the left panel");
homePagePlatform.goToConnections();
info("Test case 02: Search people by Position");
connectionsManagement.searchPeople("", jobTitle2, "", "");
$(byXpath(ELEMENT_CONNECTION_USER_NAME.replace("${user}", username1))).shouldNot(Condition.exist);
$(byXpath(ELEMENT_CONNECTION_USER_NAME.replace("${user}", username2))).should(Condition.exist);
manageLogInOut.signIn(PLFData.DATA_USER1, "gtngtn");
navigationToolbar.goToManageCommunity();
addUsers.deleteUser(username1);
addUsers.deleteUser(username2);
addUsers.deleteUser(username3);
}
@Test
public void test03_SearchPeopleBySkills() {
String organization1 = "organization1" + getRandomString();
String jobTitle1 = "jobTitle1" + getRandomString();
String jobDetail1 = "jobDetail1" + getRandomString();
String skill1 = "skill1" + getRandomString();
String dStart = getDate(-7, "MM/dd/yyyy");
String organization2 = "organization2" + getRandomString();
String jobTitle2 = "jobTitle2" + getRandomString();
String jobDetail2 = "jobDetail2" + getRandomString();
String skill2 = "skill2" + getRandomString();
/* Create data test */
String username1 = "ausernamea" + getRandomString();
String email1 = username1 + "@test.com";
String username2 = "busernameb" + getRandomString();
String email2 = username2 + "@test.com";
String username3 = "usernamec" + getRandomString();
String email3 = username3 + "@test.com";
String password = "123456";
info("Add user");
navigationToolbar.goToAddUser();
addUsers.addUser(username1, password, email1, username1, username1);
addUsers.addUser(username2, password, email2, username2, username2);
addUsers.addUser(username3, password, email3, username3, username3);
manageLogInOut.signIn(username1, password);
info("Edit user profile of user 1");
info("Click on the name of user, click on My profile");
navigationToolbar.goToMyProfile();
info("Click on Edit button to change user's information");
userProfilePage.goToEditProfile();
userProfilePage.updateExperience(organization1, jobTitle1, jobDetail1, skill1, dStart, null, true);
userProfilePage.saveCancelUpdateInfo(true);
info("Edit user profile of user 1");
info("Click on the name of user, click on My profile");
refresh();
manageLogInOut.signIn(username2, password);
navigationToolbar.goToMyProfile();
info("Click on Edit button to change user's information");
userProfilePage.goToEditProfile();
userProfilePage.updateExperience(organization2, jobTitle2, jobDetail2, skill2, dStart, null, true);
userProfilePage.saveCancelUpdateInfo(true);
refresh();
info("Login as John");
manageLogInOut.signIn(username3, password);
info("Click on Connections on the left panel");
homePagePlatform.goToConnections();
info("Test case 03: Search people by skill");
connectionsManagement.searchPeople("", "", skill1, "");
$(byXpath(ELEMENT_CONNECTION_USER_NAME.replace("${user}", username1))).should(Condition.exist);
$(byXpath(ELEMENT_CONNECTION_USER_NAME.replace("${user}", username2))).shouldNot(Condition.exist);
manageLogInOut.signIn(PLFData.DATA_USER1, "gtngtn");
navigationToolbar.goToManageCommunity();
addUsers.deleteUser(username1);
addUsers.deleteUser(username2);
addUsers.deleteUser(username3);
}
@Test
public void test04_SearchPeopleByDirectory() {
/* Create data test */
String username1 = "ausernamea" + getRandomString();
String email1 = username1 + "@test.com";
String username2 = "busernameb" + getRandomString();
String email2 = username2 + "@test.com";
String username3 = "usernamec" + getRandomString();
String email3 = username3 + "@test.com";
String password = "123456";
info("Add user");
navigationToolbar.goToAddUser();
addUsers.addUser(username1, password, email1, username1, username1);
addUsers.addUser(username2, password, email2, username2, username2);
addUsers.addUser(username3, password, email3, username3, username3);
manageLogInOut.signIn(username3, password);
info("Click on Connections on the left panel");
homePagePlatform.goToConnections();
info("Test case 04: Search people by directory");
connectionsManagement.searchPeople("", "", "", "B");
$(byXpath(ELEMENT_CONNECTION_USER_NAME.replace("${user}", username1))).shouldNot(Condition.exist);
$(byXpath(ELEMENT_CONNECTION_USER_NAME.replace("${user}", username2))).should(Condition.exist);
connectionsManagement.searchPeople("", "", "", "A");
$(byXpath(ELEMENT_CONNECTION_USER_NAME.replace("${user}", username1))).should(Condition.exist);
$(byXpath(ELEMENT_CONNECTION_USER_NAME.replace("${user}", username2))).shouldNot(Condition.exist);
manageLogInOut.signIn(PLFData.DATA_USER1, "gtngtn");
navigationToolbar.goToManageCommunity();
addUsers.deleteUser(username1);
addUsers.deleteUser(username2);
addUsers.deleteUser(username3);
}
}
| lgpl-3.0 |
iplogical/res | app/manager/src/main/java/com/inspirationlogical/receipt/manager/controller/stock/StockFxmlView.java | 303 | package com.inspirationlogical.receipt.manager.controller.stock;
import de.felixroske.jfxsupport.AbstractFxmlView;
import de.felixroske.jfxsupport.FXMLView;
@FXMLView(value = "/view/fxml/Stock.fxml", bundle = "properties/manager_hu.properties")
public class StockFxmlView extends AbstractFxmlView {
}
| lgpl-3.0 |
SINTEF-9012/cloudml | ui/shell/src/main/java/org/cloudml/ui/shell/terminal/Terminal.java | 2972 | /**
* This file is part of CloudML [ http://cloudml.org ]
*
* Copyright (C) 2012 - SINTEF ICT
* Contact: Franck Chauvel <franck.chauvel@sintef.no>
*
* Module: root
*
* CloudML 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.
*
* CloudML 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 CloudML. If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.cloudml.ui.shell.terminal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jline.console.ConsoleReader;
import jline.console.completer.ArgumentCompleter;
import jline.console.completer.Completer;
import jline.console.completer.FileNameCompleter;
import jline.console.completer.StringsCompleter;
import jline.console.history.MemoryHistory;
import org.cloudml.ui.shell.configuration.Command;
import org.cloudml.ui.shell.configuration.Configuration;
/**
* Wrap the concept of feature from which one can read or paint
*/
public class Terminal implements InputDevice, OutputDevice {
private final Configuration configuration;
private final ConsoleReader reader;
public Terminal(Configuration configuration) {
try {
this.configuration = configuration;
jline.TerminalFactory.configure("auto");
reader = new ConsoleReader();
reader.setHistory(new MemoryHistory());
reader.addCompleter(new ArgumentCompleter(selectCompleters()));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private List<Completer> selectCompleters() {
final List<Completer> selection = new ArrayList<Completer>();
for (Command eachCommand: configuration.getCommands()) {
selection.add(new StringsCompleter(eachCommand.getSyntax()));
}
selection.add(new FileNameCompleter());
return selection;
}
/**
* Prompt the user for a new CloudML command
*
* @return the command entered by the user
*/
@Override
public String prompt() {
try {
reader.println("");
return reader.readLine(Color.CYAN.paint(configuration.getPrompt()));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
@Override
public void print(Message message) {
try {
reader.print(message.toString());
reader.flush();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
| lgpl-3.0 |
Wehavecookies56/Kingdom-Keys-Re-Coded | src/main/java/uk/co/wehavecookies56/kk/common/block/BlockNormalBlox.java | 414 | package uk.co.wehavecookies56.kk.common.block;
import net.minecraft.block.material.Material;
import uk.co.wehavecookies56.kk.common.block.base.BlockBlox;
public class BlockNormalBlox extends BlockBlox {
protected BlockNormalBlox (Material material, String toolClass, int level, float hardness, float resistance, String name) {
super(material, toolClass, level, hardness, resistance, name);
}
}
| lgpl-3.0 |
FoxelBox/FoxBukkitScoreboard | src/main/java/com/foxelbox/foxbukkit/scoreboard/FoxBukkitScoreboard.java | 5942 | /**
* This file is part of FoxBukkitScoreboard.
*
* FoxBukkitScoreboard 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.
*
* FoxBukkitScoreboard 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 FoxBukkitScoreboard. If not, see <http://www.gnu.org/licenses/>.
*/
package com.foxelbox.foxbukkit.scoreboard;
import com.foxelbox.foxbukkit.permissions.FoxBukkitPermissionHandler;
import com.foxelbox.foxbukkit.permissions.FoxBukkitPermissions;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scoreboard.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.UUID;
public class FoxBukkitScoreboard extends JavaPlugin implements Listener {
FoxBukkitPermissions permissions;
FoxBukkitPermissionHandler permissionHandler;
private StatsKeeper statsKeeper;
HashMap<UUID, Scoreboard> playerStatsScoreboards = new HashMap<>();
private final ArrayList<Scoreboard> registeredScoreboards = new ArrayList<>();
private boolean mainScoreboardRegistered = false;
@Override
public void onDisable() {
super.onDisable();
registeredScoreboards.clear();
playerStatsScoreboards.clear();
statsKeeper.onDisable();
}
@Override
public void onEnable() {
permissions = (FoxBukkitPermissions)getServer().getPluginManager().getPlugin("FoxBukkitPermissions");
permissionHandler = permissions.getHandler();
statsKeeper = new StatsKeeper(this);
permissionHandler.addRankChangeHandler(new FoxBukkitPermissionHandler.OnRankChange() {
@Override
public void rankChanged(UUID uuid, String rank) {
Player ply = getServer().getPlayer(uuid);
if (ply != null) {
setPlayerScoreboardTeam(ply, rank, registeredScoreboards);
}
}
});
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
@Override
public void run() {
statsKeeper.refreshAllStats();
}
}, 20, 40);
getServer().getPluginManager().registerEvents(this, this);
}
public void setPlayerScoreboard(Player ply, Scoreboard scoreboard) {
if(scoreboard == null) {
scoreboard = playerStatsScoreboards.get(ply.getUniqueId());
}
ply.setScoreboard(scoreboard);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerQuit(PlayerQuitEvent event) {
registeredScoreboards.remove(playerStatsScoreboards.remove(event.getPlayer().getUniqueId()));
statsKeeper.onDisconnect(event.getPlayer());
}
private void registerScoreboard(Scoreboard scoreboard) {
ArrayList<Scoreboard> sbList = new ArrayList<>(1);
sbList.add(scoreboard);
registeredScoreboards.add(scoreboard);
refreshScoreboards(sbList);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerJoin(PlayerJoinEvent event) {
final Player player = event.getPlayer();
Scoreboard playerScoreboard = playerStatsScoreboards.get(player.getUniqueId());
if(playerScoreboard == null) {
playerScoreboard = getServer().getScoreboardManager().getNewScoreboard();
playerStatsScoreboards.put(player.getUniqueId(), playerScoreboard);
registerScoreboard(playerScoreboard);
}
setPlayerScoreboardTeam(player, registeredScoreboards);
player.setScoreboard(playerScoreboard);
statsKeeper.refreshStats(player);
}
private void setPlayerScoreboardTeam(Player ply, Iterable<Scoreboard> scoreboards) {
setPlayerScoreboardTeam(ply, permissionHandler.getGroup(ply.getUniqueId()), scoreboards);
}
private void setPlayerScoreboardTeam(Player ply, String rank, Iterable<Scoreboard> scoreboards) {
if(!mainScoreboardRegistered) {
registeredScoreboards.add(getServer().getScoreboardManager().getMainScoreboard());
mainScoreboardRegistered = true;
}
String sbEntry = ply.getName();
String teamName = String.format("rank%09d", permissionHandler.getImmunityLevel(rank) + 100);
String correctPrefix = permissionHandler.getGroupTag(rank);
for(Scoreboard scoreboard : scoreboards) {
Team team = scoreboard.getTeam(teamName);
if (team == null) {
team = scoreboard.registerNewTeam(teamName);
team.setSuffix("\u00a7r");
}
if (!team.getPrefix().equals(correctPrefix)) {
team.setPrefix(correctPrefix);
}
if (!team.hasEntry(sbEntry)) {
team.addEntry(sbEntry);
}
}
}
private void refreshScoreboards(Iterable<Scoreboard> scoreboards) {
for(Player ply : getServer().getOnlinePlayers()) {
setPlayerScoreboardTeam(ply, scoreboards);
}
}
public Scoreboard createScoreboard() {
Scoreboard scoreboard = getServer().getScoreboardManager().getNewScoreboard();
registerScoreboard(scoreboard);
return scoreboard;
}
}
| lgpl-3.0 |
yangjiandong/appjruby | app-batch/src/main/java/org/sonar/batch/ResourceFilters.java | 1946 | /*
* 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.batch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.ResourceFilter;
import org.sonar.api.resources.Resource;
/**
* @since 1.12
*/
public class ResourceFilters {
private static final Logger LOG = LoggerFactory.getLogger(ResourceFilters.class);
private ResourceFilter[] filters;
public ResourceFilters(ResourceFilter[] filters) {
this.filters = (filters==null ? new ResourceFilter[0] : filters);
}
public ResourceFilters() {
this(null);
}
public ResourceFilter[] getFilters() {
return filters;
}
/**
* Return true if the violation must be saved. If false then it is ignored.
*/
public boolean isExcluded(Resource resource) {
boolean ignored = false;
int index = 0;
while (!ignored && index < filters.length) {
ResourceFilter filter = filters[index];
ignored = filter.isIgnored(resource);
if (ignored && LOG.isDebugEnabled()) {
LOG.debug("Resource {} is excluded by the filter {}", resource, filter);
}
index++;
}
return ignored;
}
}
| lgpl-3.0 |
schuttek/nectar | src/main/java/org/nectarframework/base/service/sql/postgresql/PostgreSqlService.java | 1148 | package org.nectarframework.base.service.sql.postgresql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.nectarframework.base.service.Log;
import org.nectarframework.base.service.sql.SqlService;
public class PostgreSqlService extends SqlService {
// TODO: there's no auto reconnect option for postgre... each connection would have to be checked for validity before use??
@Override
protected boolean openConnections(int connCount) {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
Log.fatal("Couldn't find postgresql driver!", e);
return false;
}
// Setup the connection with the DB
try {
for (int i = 0; i < connCount; i++) {
Connection c = DriverManager.getConnection("jdbc:postgresql://" + this.host + ":" + port + "/" + this.database + "?ssl=false&" + "user=" + this.user + "&password=" + this.password);
poolConnections.add(c);
idleConnections.add(c);
}
} catch (SQLException e) {
Log.fatal(this.getClass().getName()+": Unable to open database connection", e);
return false;
}
return true;
}
}
| lgpl-3.0 |
robcowell/dynamicreports | dynamicreports-core/src/test/java/net/sf/dynamicreports/test/jasper/JasperTestUtils.java | 5014 | /**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2012 Ricardo Mariaca
* http://dynamicreports.sourceforge.net
*
* This file is part of DynamicReports.
*
* DynamicReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DynamicReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.test.jasper;
import junit.framework.Assert;
import net.sf.dynamicreports.report.base.DRSubtotal;
import net.sf.dynamicreports.report.builder.column.ColumnBuilder;
import net.sf.dynamicreports.report.builder.crosstab.AbstractCrosstabGroupBuilder;
import net.sf.dynamicreports.report.builder.crosstab.CrosstabColumnGroupBuilder;
import net.sf.dynamicreports.report.builder.crosstab.CrosstabMeasureBuilder;
import net.sf.dynamicreports.report.builder.crosstab.CrosstabRowGroupBuilder;
import net.sf.dynamicreports.report.builder.group.GroupBuilder;
import net.sf.dynamicreports.report.builder.subtotal.BaseSubtotalBuilder;
/**
* @author Ricardo Mariaca (dynamicreports@gmail.com)
*/
public class JasperTestUtils {
//column detail
public static String getColumnDetailName(ColumnBuilder<?, ?> column) {
return "detail.column_" + column.build().getName() + "1";
}
//column title
public static String getColumnTitleName(ColumnBuilder<?, ?> column) {
return "columnHeader.column_" + column.build().getName() + ".title1";
}
//subtotal
private static String getSubtotalName(BaseSubtotalBuilder<?, ?> subtotal) {
String band = null;
DRSubtotal<?> subtl = subtotal.getSubtotal();
switch (subtl.getPosition()) {
case TITLE:
band = "title";
break;
case PAGE_HEADER:
band = "pageHeader";
break;
case PAGE_FOOTER:
band = "pageFooter";
break;
case COLUMN_HEADER:
band = "columnHeader";
break;
case COLUMN_FOOTER:
band = "columnFooter";
break;
case GROUP_HEADER:
case FIRST_GROUP_HEADER:
case LAST_GROUP_HEADER:
band = "subtotalGroupHeader";
break;
case GROUP_FOOTER:
case FIRST_GROUP_FOOTER:
case LAST_GROUP_FOOTER:
band = "subtotalGroupFooter";
break;
case LAST_PAGE_FOOTER:
band = "lastPageFooter";
break;
case SUMMARY:
band = "summary";
break;
default:
Assert.fail("Subtotal position " + subtl.getPosition().name() + " not found");
return null;
}
return band + ".column_" + subtl.getShowInColumn().getName() + ".subtotal";
}
public static String getSubtotalLabelName(BaseSubtotalBuilder<?, ?> subtotal, int subtotalIndex) {
return getSubtotalName(subtotal) + ".label" + subtotalIndex;
}
public static String getSubtotalName(BaseSubtotalBuilder<?, ?> subtotal, int subtotalIndex) {
return getSubtotalName(subtotal) + subtotalIndex;
}
//group header title
public static String getHeaderTitleGroupName(GroupBuilder<?> group) {
return "groupHeaderTitleAndValue.group_" + group.getGroup().getName() + ".title1";
}
//group header
public static String getHeaderGroupName(GroupBuilder<?> group) {
return "groupHeaderTitleAndValue.group_" + group.getGroup().getName() + "1";
}
//crosstab group header
public static String getCrosstabGroupHeaderName(AbstractCrosstabGroupBuilder<?, ?, ?> group) {
return "group_" + group.build().getName() + ".header1";
}
//crosstab group total header
public static String getCrosstabGroupTotalHeaderName(AbstractCrosstabGroupBuilder<?, ?, ?> group) {
return "group_" + group.build().getName() + ".totalheader1";
}
//crosstab group title header
public static String getCrosstabGroupTitleHeaderName(AbstractCrosstabGroupBuilder<?, ?, ?> group, CrosstabMeasureBuilder<?> measure) {
return "group_" + group.build().getName() + ".titleheader." + measure.build().getName() + "1";
}
//crosstab group title total header
public static String getCrosstabGroupTitleTotalHeaderName(AbstractCrosstabGroupBuilder<?, ?, ?> group, CrosstabMeasureBuilder<?> measure) {
return "group_" + group.build().getName() + ".titletotalheader." + measure.build().getName() + "1";
}
//crosstab cell
public static String getCrosstabCellName(CrosstabMeasureBuilder<?> measure, CrosstabRowGroupBuilder<?> rowGroup, CrosstabColumnGroupBuilder<?> columnGroup) {
String name = "cell_measure[" + measure.build().getName() + "]";
if (rowGroup != null) {
name += "_rowgroup[" + rowGroup.build().getName() + "]";
}
if (columnGroup != null) {
name += "_columngroup[" + columnGroup.build().getName() + "]";
}
return name + "1";
}
}
| lgpl-3.0 |
SonarSource/sonarqube | server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactoryTest.java | 18696 | /*
* SonarQube
* Copyright (C) 2009-2022 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.ce.task.projectanalysis.issue;
import com.google.common.collect.Iterators;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Collection;
import java.util.Collections;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.Duration;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.issue.commonrule.CommonRuleEngine;
import org.sonar.ce.task.projectanalysis.issue.filter.IssueFilter;
import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRule;
import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolderRule;
import org.sonar.ce.task.projectanalysis.source.SourceLinesHashRepository;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.scanner.protocol.Constants;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.IssueType;
import org.sonar.scanner.protocol.output.ScannerReport.TextRange;
import org.sonar.server.rule.CommonRuleKeys;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.issue.Issue.STATUS_OPEN;
import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW;
@RunWith(DataProviderRunner.class)
public class TrackerRawInputFactoryTest {
private static final String FILE_UUID = "fake_uuid";
private static final String ANOTHER_FILE_UUID = "another_fake_uuid";
private static int FILE_REF = 2;
private static int NOT_IN_REPORT_FILE_REF = 3;
private static int ANOTHER_FILE_REF = 4;
private static ReportComponent FILE = ReportComponent.builder(Component.Type.FILE, FILE_REF).setUuid(FILE_UUID).build();
private static ReportComponent ANOTHER_FILE = ReportComponent.builder(Component.Type.FILE, ANOTHER_FILE_REF).setUuid(ANOTHER_FILE_UUID).build();
private static ReportComponent PROJECT = ReportComponent.builder(Component.Type.PROJECT, 1).addChildren(FILE, ANOTHER_FILE).build();
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot(PROJECT);
@Rule
public BatchReportReaderRule reportReader = new BatchReportReaderRule();
@Rule
public ActiveRulesHolderRule activeRulesHolder = new ActiveRulesHolderRule();
@Rule
public RuleRepositoryRule ruleRepository = new RuleRepositoryRule();
private SourceLinesHashRepository sourceLinesHash = mock(SourceLinesHashRepository.class);
private CommonRuleEngine commonRuleEngine = mock(CommonRuleEngine.class);
private IssueFilter issueFilter = mock(IssueFilter.class);
private TrackerRawInputFactory underTest = new TrackerRawInputFactory(treeRootHolder, reportReader, sourceLinesHash,
commonRuleEngine, issueFilter, ruleRepository, activeRulesHolder);
@Test
public void load_source_hash_sequences() {
when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line"));
Input<DefaultIssue> input = underTest.create(FILE);
assertThat(input.getLineHashSequence()).isNotNull();
assertThat(input.getLineHashSequence().getHashForLine(1)).isEqualTo("line");
assertThat(input.getLineHashSequence().getHashForLine(2)).isEmpty();
assertThat(input.getLineHashSequence().getHashForLine(3)).isEmpty();
assertThat(input.getBlockHashSequence()).isNotNull();
}
@Test
public void load_source_hash_sequences_only_on_files() {
Input<DefaultIssue> input = underTest.create(PROJECT);
assertThat(input.getLineHashSequence()).isNotNull();
assertThat(input.getBlockHashSequence()).isNotNull();
}
@Test
public void load_issues_from_report() {
RuleKey ruleKey = RuleKey.of("java", "S001");
markRuleAsActive(ruleKey);
when(issueFilter.accept(any(), eq(FILE))).thenReturn(true);
when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line"));
ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
.setTextRange(TextRange.newBuilder().setStartLine(2).build())
.setMsg("the message")
.setRuleRepository(ruleKey.repository())
.setRuleKey(ruleKey.rule())
.setSeverity(Constants.Severity.BLOCKER)
.setGap(3.14)
.setQuickFixAvailable(true)
.build();
reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue));
Input<DefaultIssue> input = underTest.create(FILE);
Collection<DefaultIssue> issues = input.getIssues();
assertThat(issues).hasSize(1);
DefaultIssue issue = Iterators.getOnlyElement(issues.iterator());
// fields set by analysis report
assertThat(issue.ruleKey()).isEqualTo(ruleKey);
assertThat(issue.severity()).isEqualTo(Severity.BLOCKER);
assertThat(issue.line()).isEqualTo(2);
assertThat(issue.gap()).isEqualTo(3.14);
assertThat(issue.message()).isEqualTo("the message");
assertThat(issue.isQuickFixAvailable()).isTrue();
// fields set by compute engine
assertThat(issue.checksum()).isEqualTo(input.getLineHashSequence().getHashForLine(2));
assertThat(issue.tags()).isEmpty();
assertInitializedIssue(issue);
assertThat(issue.effort()).isNull();
}
@Test
public void set_rule_name_as_message_when_issue_message_from_report_is_empty() {
RuleKey ruleKey = RuleKey.of("java", "S001");
markRuleAsActive(ruleKey);
registerRule(ruleKey, "Rule 1");
when(issueFilter.accept(any(), eq(FILE))).thenReturn(true);
when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line"));
ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
.setRuleRepository(ruleKey.repository())
.setRuleKey(ruleKey.rule())
.setMsg("")
.build();
reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue));
Input<DefaultIssue> input = underTest.create(FILE);
Collection<DefaultIssue> issues = input.getIssues();
assertThat(issues).hasSize(1);
DefaultIssue issue = Iterators.getOnlyElement(issues.iterator());
// fields set by analysis report
assertThat(issue.ruleKey()).isEqualTo(ruleKey);
// fields set by compute engine
assertInitializedIssue(issue);
assertThat(issue.message()).isEqualTo("Rule 1");
}
// SONAR-10781
@Test
public void load_issues_from_report_missing_secondary_location_component() {
RuleKey ruleKey = RuleKey.of("java", "S001");
markRuleAsActive(ruleKey);
when(issueFilter.accept(any(), eq(FILE))).thenReturn(true);
when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line"));
ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
.setTextRange(TextRange.newBuilder().setStartLine(2).build())
.setMsg("the message")
.setRuleRepository(ruleKey.repository())
.setRuleKey(ruleKey.rule())
.setSeverity(Constants.Severity.BLOCKER)
.setGap(3.14)
.addFlow(ScannerReport.Flow.newBuilder()
.addLocation(ScannerReport.IssueLocation.newBuilder()
.setComponentRef(FILE_REF)
.setMsg("Secondary location in same file")
.setTextRange(TextRange.newBuilder().setStartLine(2).build()))
.addLocation(ScannerReport.IssueLocation.newBuilder()
.setComponentRef(NOT_IN_REPORT_FILE_REF)
.setMsg("Secondary location in a missing file")
.setTextRange(TextRange.newBuilder().setStartLine(3).build()))
.addLocation(ScannerReport.IssueLocation.newBuilder()
.setComponentRef(ANOTHER_FILE_REF)
.setMsg("Secondary location in another file")
.setTextRange(TextRange.newBuilder().setStartLine(3).build()))
.build())
.build();
reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue));
Input<DefaultIssue> input = underTest.create(FILE);
Collection<DefaultIssue> issues = input.getIssues();
assertThat(issues).hasSize(1);
DefaultIssue issue = Iterators.getOnlyElement(issues.iterator());
DbIssues.Locations locations = issue.getLocations();
// fields set by analysis report
assertThat(locations.getFlowList()).hasSize(1);
assertThat(locations.getFlow(0).getLocationList()).hasSize(2);
// Not component id if location is in the same file
assertThat(locations.getFlow(0).getLocation(0).getComponentId()).isEmpty();
assertThat(locations.getFlow(0).getLocation(1).getComponentId()).isEqualTo(ANOTHER_FILE_UUID);
}
@Test
@UseDataProvider("ruleTypeAndStatusByIssueType")
public void load_external_issues_from_report(IssueType issueType, RuleType expectedRuleType, String expectedStatus) {
when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line"));
ScannerReport.ExternalIssue reportIssue = ScannerReport.ExternalIssue.newBuilder()
.setTextRange(TextRange.newBuilder().setStartLine(2).build())
.setMsg("the message")
.setEngineId("eslint")
.setRuleId("S001")
.setSeverity(Constants.Severity.BLOCKER)
.setEffort(20L)
.setType(issueType)
.build();
reportReader.putExternalIssues(FILE.getReportAttributes().getRef(), asList(reportIssue));
Input<DefaultIssue> input = underTest.create(FILE);
Collection<DefaultIssue> issues = input.getIssues();
assertThat(issues).hasSize(1);
DefaultIssue issue = Iterators.getOnlyElement(issues.iterator());
// fields set by analysis report
assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("external_eslint", "S001"));
assertThat(issue.severity()).isEqualTo(Severity.BLOCKER);
assertThat(issue.line()).isEqualTo(2);
assertThat(issue.effort()).isEqualTo(Duration.create(20L));
assertThat(issue.message()).isEqualTo("the message");
assertThat(issue.type()).isEqualTo(expectedRuleType);
// fields set by compute engine
assertThat(issue.checksum()).isEqualTo(input.getLineHashSequence().getHashForLine(2));
assertThat(issue.tags()).isEmpty();
assertInitializedExternalIssue(issue, expectedStatus);
}
@DataProvider
public static Object[][] ruleTypeAndStatusByIssueType() {
return new Object[][] {
{IssueType.CODE_SMELL, RuleType.CODE_SMELL, STATUS_OPEN},
{IssueType.BUG, RuleType.BUG, STATUS_OPEN},
{IssueType.VULNERABILITY, RuleType.VULNERABILITY, STATUS_OPEN},
{IssueType.SECURITY_HOTSPOT, RuleType.SECURITY_HOTSPOT, STATUS_TO_REVIEW}
};
}
@Test
@UseDataProvider("ruleTypeAndStatusByIssueType")
public void load_external_issues_from_report_with_default_effort(IssueType issueType, RuleType expectedRuleType, String expectedStatus) {
when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line"));
ScannerReport.ExternalIssue reportIssue = ScannerReport.ExternalIssue.newBuilder()
.setTextRange(TextRange.newBuilder().setStartLine(2).build())
.setMsg("the message")
.setEngineId("eslint")
.setRuleId("S001")
.setSeverity(Constants.Severity.BLOCKER)
.setType(issueType)
.build();
reportReader.putExternalIssues(FILE.getReportAttributes().getRef(), asList(reportIssue));
Input<DefaultIssue> input = underTest.create(FILE);
Collection<DefaultIssue> issues = input.getIssues();
assertThat(issues).hasSize(1);
DefaultIssue issue = Iterators.getOnlyElement(issues.iterator());
// fields set by analysis report
assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("external_eslint", "S001"));
assertThat(issue.severity()).isEqualTo(Severity.BLOCKER);
assertThat(issue.line()).isEqualTo(2);
assertThat(issue.effort()).isEqualTo(Duration.create(0L));
assertThat(issue.message()).isEqualTo("the message");
assertThat(issue.type()).isEqualTo(expectedRuleType);
// fields set by compute engine
assertThat(issue.checksum()).isEqualTo(input.getLineHashSequence().getHashForLine(2));
assertThat(issue.tags()).isEmpty();
assertInitializedExternalIssue(issue, expectedStatus);
}
@Test
public void excludes_issues_on_inactive_rules() {
RuleKey ruleKey = RuleKey.of("java", "S001");
when(issueFilter.accept(any(), eq(FILE))).thenReturn(true);
when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line"));
ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
.setTextRange(TextRange.newBuilder().setStartLine(2).build())
.setMsg("the message")
.setRuleRepository(ruleKey.repository())
.setRuleKey(ruleKey.rule())
.setSeverity(Constants.Severity.BLOCKER)
.setGap(3.14)
.build();
reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue));
Input<DefaultIssue> input = underTest.create(FILE);
Collection<DefaultIssue> issues = input.getIssues();
assertThat(issues).isEmpty();
}
@Test
public void filter_excludes_issues_from_report() {
RuleKey ruleKey = RuleKey.of("java", "S001");
markRuleAsActive(ruleKey);
when(issueFilter.accept(any(), eq(FILE))).thenReturn(false);
when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line"));
ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
.setTextRange(TextRange.newBuilder().setStartLine(2).build())
.setMsg("the message")
.setRuleRepository(ruleKey.repository())
.setRuleKey(ruleKey.rule())
.setSeverity(Constants.Severity.BLOCKER)
.setGap(3.14)
.build();
reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue));
Input<DefaultIssue> input = underTest.create(FILE);
Collection<DefaultIssue> issues = input.getIssues();
assertThat(issues).isEmpty();
}
@Test
public void exclude_issues_on_common_rules() {
RuleKey ruleKey = RuleKey.of(CommonRuleKeys.commonRepositoryForLang("java"), "S001");
markRuleAsActive(ruleKey);
when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line"));
ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
.setMsg("the message")
.setRuleRepository(ruleKey.repository())
.setRuleKey(ruleKey.rule())
.setSeverity(Constants.Severity.BLOCKER)
.build();
reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue));
Input<DefaultIssue> input = underTest.create(FILE);
assertThat(input.getIssues()).isEmpty();
}
@Test
public void load_issues_of_compute_engine_common_rules() {
RuleKey ruleKey = RuleKey.of(CommonRuleKeys.commonRepositoryForLang("java"), "InsufficientCoverage");
markRuleAsActive(ruleKey);
when(issueFilter.accept(any(), eq(FILE))).thenReturn(true);
when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line"));
DefaultIssue ceIssue = new DefaultIssue()
.setRuleKey(ruleKey)
.setMessage("not enough coverage")
.setGap(10.0);
when(commonRuleEngine.process(FILE)).thenReturn(singletonList(ceIssue));
Input<DefaultIssue> input = underTest.create(FILE);
assertThat(input.getIssues()).containsOnly(ceIssue);
assertInitializedIssue(input.getIssues().iterator().next());
}
@Test
public void filter_exclude_issues_on_common_rule() {
RuleKey ruleKey = RuleKey.of(CommonRuleKeys.commonRepositoryForLang("java"), "InsufficientCoverage");
markRuleAsActive(ruleKey);
when(issueFilter.accept(any(), eq(FILE))).thenReturn(false);
when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line"));
DefaultIssue ceIssue = new DefaultIssue()
.setRuleKey(ruleKey)
.setMessage("not enough coverage")
.setGap(10.0);
when(commonRuleEngine.process(FILE)).thenReturn(singletonList(ceIssue));
Input<DefaultIssue> input = underTest.create(FILE);
assertThat(input.getIssues()).isEmpty();
}
private void assertInitializedIssue(DefaultIssue issue) {
assertInitializedExternalIssue(issue, STATUS_OPEN);
assertThat(issue.effort()).isNull();
assertThat(issue.effortInMinutes()).isNull();
}
private void assertInitializedExternalIssue(DefaultIssue issue, String expectedStatus) {
assertThat(issue.projectKey()).isEqualTo(PROJECT.getKey());
assertThat(issue.componentKey()).isEqualTo(FILE.getKey());
assertThat(issue.componentUuid()).isEqualTo(FILE.getUuid());
assertThat(issue.resolution()).isNull();
assertThat(issue.status()).isEqualTo(expectedStatus);
assertThat(issue.key()).isNull();
assertThat(issue.authorLogin()).isNull();
}
private void markRuleAsActive(RuleKey ruleKey) {
activeRulesHolder.put(new ActiveRule(ruleKey, Severity.CRITICAL, emptyMap(), 1_000L, null, "qp1"));
}
private void registerRule(RuleKey ruleKey, String name) {
DumbRule dumbRule = new DumbRule(ruleKey);
dumbRule.setName(name);
ruleRepository.add(dumbRule);
}
}
| lgpl-3.0 |
nypgit/alto | src/alto/lang/math/Statistic.java | 2774 | /*
* Copyright (C) 1998, 2009 John Pritchard and the Alto Project Group.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
package alto.lang.math;
/**
* <p> The value of a statistic, as for monitoring live quality of
* service. </p>
*
* <h3>Hash Code</h3>
*
* <p> Subclasses are mutable objects with dynamic hash codes. Their
* subclasses should override the hash code and equals methods if they
* may be used as hash table keys. </p>
*
* @author jdp
* @since 1.6
*/
public abstract class Statistic
extends java.lang.Number
implements java.lang.Comparable<java.lang.Number>
{
public final java.lang.String Format(double value){
java.lang.String re = java.lang.String.valueOf(value);
int idx = re.indexOf('.');
if (1 > idx)
return re;
else {
int trunc = (idx + 4);
if (trunc < re.length())
return re.substring(0,trunc);
else
return re;
}
}
/**
*/
protected Statistic(){
super();
}
public abstract boolean isAverage();
public abstract boolean isScalar();
public abstract java.lang.String toString();
public final int compareTo(java.lang.Number that){
if (null == that)
return 1;
else {
double thisValue = this.doubleValue();
double thatValue = that.doubleValue();
if (thisValue < thatValue)
return -1;
else if (thisValue == thatValue)
return 0;
else
return 1;
}
}
public int hashCode(){
return this.intValue();
}
public final boolean equals(Object ano){
if (this == ano)
return true;
else if (null == ano)
return false;
else if (ano instanceof java.lang.Number){
java.lang.Number that = (java.lang.Number)ano;
return (this.doubleValue() == that.doubleValue());
}
else
return this.toString().equals(ano.toString());
}
}
| lgpl-3.0 |
cismet/cids-custom-wrrl-db-mv | src/main/java/de/cismet/cids/custom/objectrenderer/wrrl_db_mv/ProjekteRenderer.java | 1327 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cids.custom.objectrenderer.wrrl_db_mv;
import de.cismet.cids.client.tools.DevelopmentTools;
import de.cismet.cids.custom.objecteditors.wrrl_db_mv.ProjekteEditor;
/**
* DOCUMENT ME!
*
* @author therter
* @version $Revision$, $Date$
*/
public class ProjekteRenderer extends ProjekteEditor {
//~ Constructors -----------------------------------------------------------
/**
* Creates a new ProjekteRenderer object.
*/
public ProjekteRenderer() {
super(true);
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param args DOCUMENT ME!
*/
public static void main(final String[] args) {
try {
DevelopmentTools.createRendererInFrameFromRMIConnectionOnLocalhost(
"WRRL_DB_MV",
"Administratoren",
"admin",
"x",
"projekte",
420,
"Test",
1280,
1024);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| lgpl-3.0 |
B3Partners/B3pCatalog | src/main/java/nl/b3p/catalog/config/CatalogAppConfig.java | 9465 | /*
* Copyright (C) 2011 B3Partners B.V.
*
* 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 nl.b3p.catalog.config;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Matthijs Laan
*/
@XmlRootElement
public class CatalogAppConfig implements ServletContextListener {
private static final Log log = LogFactory.getLog(CatalogAppConfig.class);
private static CatalogAppConfig config;
private static final String CURRENT_VERSION = "1.0";
@XmlAttribute
private String version;
private String configFilePath;
@XmlElement(name="arcobjects")
private ArcObjectsConfig arcObjectsConfig = new ArcObjectsConfig();
@XmlElementWrapper(name="roots")
@XmlElements({
@XmlElement(name="fileRoot", type=FileRoot.class),
@XmlElement(name="sdeRoot", type=SDERoot.class),
@XmlElement(name="kbRoot", type=KBRoot.class)
})
private List<Root> roots = new ArrayList<Root>();
@XmlList
private Set<String> geoFileExtensions = new HashSet<String>(Arrays.asList(
new String[] {"gml", "shp", "dxf", "dgn", "sdf", "sdl", "lyr", "ecw", "sid", "tif", "tiff", "asc", "mdb"}
));
@XmlElementWrapper
@XmlElements({
@XmlElement(name="cswServer", required=false)
})
private List<CSWServerConfig> cswServers = new ArrayList<CSWServerConfig>();
@XmlElementWrapper
private Map<String, String> mdeConfig = new HashMap<String, String>();
private String organizationsJsonFile = "organizations.json";
//<editor-fold defaultstate="collapsed" desc="getters en setters">
@XmlTransient
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getConfigFilePath() {
return configFilePath;
}
public void setConfigFilePath(String configFilePath) {
this.configFilePath = configFilePath;
}
@XmlTransient
public ArcObjectsConfig getArcObjectsConfig() {
return arcObjectsConfig;
}
public void setArcObjectsConfig(ArcObjectsConfig arcObjectsConfig) {
this.arcObjectsConfig = arcObjectsConfig;
}
@XmlTransient
public List<CSWServerConfig> getCswServers() {
return cswServers;
}
public void setCswServers(List<CSWServerConfig> cswServers) {
this.cswServers = cswServers;
}
@XmlTransient
public List<Root> getRoots() {
return roots;
}
public void setRoots(List<Root> roots) {
this.roots = roots;
}
@XmlTransient
public Set<String> getGeoFileExtensions() {
return geoFileExtensions;
}
public void setGeoFileExtensions(Set<String> geoFileExtensions) {
this.geoFileExtensions = geoFileExtensions;
}
@XmlTransient
public Map<String, String> getMdeConfig() {
return mdeConfig;
}
public void setMdeConfig(Map<String, String> mdeConfig) {
this.mdeConfig = mdeConfig;
}
public String getOrganizationsJsonFile() {
return organizationsJsonFile;
}
public void setOrganizationsJsonFile(String organizationsJsonFile) {
this.organizationsJsonFile = organizationsJsonFile;
}
//</editor-fold>
public CSWServerConfig getDefaultCswServer() {
List<CSWServerConfig> csws = getCswServers();
if (csws==null || csws.isEmpty()) {
return null;
}
CSWServerConfig csw = csws.get(0);
if (csw.getCswName()==null || csw.getCswName().isEmpty()) {
return null;
}
return csw;
}
public static CatalogAppConfig getConfig() {
return config;
}
public static CatalogAppConfig loadFromFile(File f) throws JAXBException, IOException {
JAXBContext ctx = JAXBContext.newInstance(CatalogAppConfig.class);
CatalogAppConfig cfg = (CatalogAppConfig)ctx.createUnmarshaller().unmarshal(f);
cfg.setConfigFilePath(f.getParentFile().getCanonicalPath());
return cfg;
}
@Override
public void contextInitialized(ServletContextEvent sce) {
String configParam = sce.getServletContext().getInitParameter("config");
if(configParam == null) {
throw new IllegalArgumentException("No config file specified in \"config\" context init parameter");
}
File f = new File(configParam);
if(!f.isAbsolute()) {
String catalinaBase = System.getProperty("catalina.base");
if(catalinaBase != null) {
f = new File(catalinaBase, configParam);
} else {
// just use current directory whatever that may be
}
}
String canonicalPath = null;
try {
canonicalPath = f.getCanonicalPath();
} catch(IOException e) {
canonicalPath = "[IOException: " + e.getMessage() + "]";
}
log.info("Loading configuration from file " + canonicalPath);
if(!f.exists() || !f.canRead()) {
throw new IllegalArgumentException(
String.format(Locale.ENGLISH,
"Config file specified in \"config\" context init parameter with value \"%s\" (canonical path \"%s\") does not exist or cannot be read",
configParam,
canonicalPath
));
}
try {
config = loadFromFile(f);
log.debug("Configuration loaded; marshalling for log");
JAXBContext ctx = JAXBContext.newInstance(CatalogAppConfig.class);
Marshaller m = ctx.createMarshaller();
m.setProperty("jaxb.formatted.output", Boolean.TRUE);
StringWriter sw = new StringWriter();
m.marshal(config, sw);
log.info("Parsed configuration: \n" + sw.toString());
if(!CURRENT_VERSION.equals(config.getVersion())) {
throw new Exception(String.format(
Locale.ENGLISH,
"Wrong configuration file version: %s, must be %s",
config.getVersion(),
CURRENT_VERSION
));
}
} catch(Exception e) {
log.error("Error loading configuration", e);
throw new IllegalArgumentException("Error loading configuration from file \"" + canonicalPath + '"',e );
}
if(log.isDebugEnabled()) {
config.getRoots().forEach((r) -> {
log.debug(String.format(Locale.ENGLISH, "Role access list for root %s: %s", r.getName(), r.getRoleAccessList().toString()));
});
}
}
public boolean isAddOnly(HttpServletRequest request) {
if (roots==null || roots.isEmpty()) {
return false;
}
boolean addOnly = false;
for (Root root : roots) {
AclAccess highest = root.getRequestUserHighestAccessLevel(request);
if (highest.getSecurityLevel() == AclAccess.ADD.getSecurityLevel()) {
addOnly = true;
}
if (highest.getSecurityLevel() != AclAccess.ADD.getSecurityLevel()) {
return false;
}
}
return addOnly;
}
public int getRequestUserHighestAccessLevel(HttpServletRequest request) {
int highestAccess = AclAccess.NONE.getSecurityLevel();
for (Root root : roots) {
AclAccess highest = root.getRequestUserHighestAccessLevel(request);
if (highest.getSecurityLevel() > highestAccess) {
highestAccess = highest.getSecurityLevel();
}
}
return highestAccess;
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
| lgpl-3.0 |
B3Partners/datastorelinkerEntities | src/main/java/nl/b3p/datastorelinker/entity/Process.java | 12615 | package nl.b3p.datastorelinker.entity;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import net.sf.json.JSONObject;
import net.sourceforge.stripes.util.Log;
import nl.b3p.datastorelinker.util.Nameable;
import nl.b3p.datastorelinker.util.Namespaces;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.DOMOutputter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
* @author Erik van de Pol
*/
@XmlRootElement
@XmlType(name="processType"/*, propOrder={
//"name",
"input",
"output",
"actions",
"featuresStart",
"featuresEnd",
"drop",
"writerType",
"mail"
}*/)
@XmlAccessorType(XmlAccessType.FIELD)
@Entity
@Table(name = "process")
public class Process implements Serializable, Nameable {
@XmlTransient
private static final long serialVersionUID = 1L;
@XmlTransient
private static final boolean DEFAULT_DROP = true;
@XmlTransient
private static final boolean DEFAULT_APPEND = false;
@XmlTransient
private static final boolean DEFAULT_MODIFY = false;
@XmlTransient
private static final boolean DEFAULT_MODIFY_GEOM = false;
@XmlTransient
private static final String DEFAULT_WRITER_TYPE = "ActionCombo_GeometrySplitter_Writer";
@XmlTransient
private final static Log log = Log.getInstance(nl.b3p.datastorelinker.entity.Process.class);
@Id
@Basic(optional = false)
@Column(name = "id")
@GeneratedValue
// default GeneratedValue strategy is AUTO
// wat weer default naar SEQUENCE in Oracle maar ook in Postgres
// (hier verwachtte ik IDENTITY; volgens de documentatie ook)
@XmlTransient
private Long id;
@Basic(optional = true)
@Column(name = "name")
@XmlTransient
private String name;
@Basic(optional = false)
@Column(name = "actions")
@Lob
@org.hibernate.annotations.Type(type="org.hibernate.type.StringClobType")
@XmlTransient
private String actions;
@JoinColumn(name = "input_id", referencedColumnName = "id")
@ManyToOne(optional = false)
@XmlElement(required=true, name="input")
private Inout input;
@JoinColumn(name = "output_id", referencedColumnName = "id")
@ManyToOne(optional = false)
@XmlElement(required=true, name="output")
private Inout output;
@Basic(optional = true)
@Column(name = "features_start")
private Integer featuresStart;
@Basic(optional = true)
@Column(name = "features_end")
private Integer featuresEnd;
@Basic(optional = false)
@Column(name = "drop_table")
private Boolean drop = DEFAULT_DROP;
@Basic(optional = false)
@Column(name = "append_table")
private Boolean append = DEFAULT_APPEND;
@Basic(optional = false)
@Column(name = "modify_table")
private Boolean modify = DEFAULT_MODIFY;
@Basic(optional = false)
@Column(name = "modify_geom")
private Boolean modifyGeom = DEFAULT_MODIFY_GEOM;
@Basic(optional = false)
@Column(name = "writer_type")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
private String writerType = DEFAULT_WRITER_TYPE;
@JoinColumn(name = "mail_id", referencedColumnName = "id")
@ManyToOne(optional = false, cascade = CascadeType.ALL)
private Mail mail;
@JoinColumn(name = "schedule", referencedColumnName = "id")
@ManyToOne(optional = true, cascade = CascadeType.ALL)
@XmlTransient
private Schedule schedule;
@JoinColumn(name = "process_status_id", referencedColumnName = "id")
@ManyToOne(optional = false, cascade = CascadeType.ALL)
@XmlTransient
private ProcessStatus processStatus;
@Basic(optional = true)
@Column(name = "organization_id")
private Integer organizationId;
@Basic(optional = true)
@Column(name = "user_id")
private Integer userId;
@Basic(optional = true)
@Column(name = "user_name")
private String userName;
@Basic(optional = true)
@Column(name = "remarks")
private String remarks;
@Basic(optional = true)
@Column(name = "filter")
private String filter;
@Basic(optional = true)
@Column(name = "modify_filter")
private String modifyFilter;
@Basic(optional=true)
@ManyToOne(fetch = FetchType.LAZY)
private nl.b3p.datastorelinker.entity.Process linkedProcess;
public Process() {
}
public Process(Long id) {
this.id = id;
}
public Process(Long id, String name) {
this.id = id;
this.name = name;
}
public Map toOutputMap() {
Map outputMap = new HashMap();
outputMap.put("drop", getDrop());
outputMap.put("append", getAppend());
outputMap.put("modify", getModify());
outputMap.put("modifyGeom", getModifyGeom());
outputMap.put("modifyFilter", getModifyFilter());
outputMap.put("params", getOutput().getDatabase().toGeotoolsDataStoreParametersMap());
return outputMap;
}
public JSONObject toJSONObject(){
JSONObject obj = new JSONObject();
obj.put("id", id);
obj.put("name", name);
Integer numAncestors = 0;
Process ancestor = linkedProcess;
if(ancestor != null){
obj.put("ancestor", linkedProcess.getId());
while(ancestor != null){
numAncestors++;
ancestor = ancestor.getLinkedProcess();
}
}else{
obj.put("ancestor", null);
}
obj.put("numAncestors", numAncestors);
return obj;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
if (name != null)
return name;
else
return input.getName() + " -> " + output.getName();
}
public void setName(String name) {
this.name = name;
}
public String getActionsString() {
return actions;
}
public void setActionsString(String actions) {
this.actions = actions;
}
@XmlAnyElement(lax=true)
//@XmlElement(required=false)
public Element getActions() {
try {
log.debug("getActions: " + actions);
org.jdom2.Document jdoc = new SAXBuilder().build(new StringReader(actions));
assignDslNS(jdoc.getRootElement());
Document doc = new DOMOutputter().output(jdoc);
/*DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(actions)));*/
return doc.getDocumentElement();
} catch(Exception ex) {
log.error(ex);
return null;
}
}
private void assignDslNS(org.jdom2.Element elem) {
// This is very ugly; there has to be a better way to do this.
elem.setNamespace(Namespace.getNamespace(Namespaces.DSL_NAMESPACE_STRING));
for (Object childElem : elem.getChildren()) {
assignDslNS((org.jdom2.Element) childElem);
}
}
public void setActions(Element element) {
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(element), new StreamResult(writer));
this.actions = writer.toString();
} catch(Exception ex) {
log.error(ex);
this.actions = "";
}
log.debug("setActions: " + actions);
}
public Inout getInput() {
return input;
}
public void setInput(Inout input) {
this.input = input;
}
public Inout getOutput() {
return output;
}
public void setOutput(Inout output) {
this.output = output;
}
public Integer getFeaturesStart() {
return featuresStart;
}
public void setFeaturesStart(Integer featuresStart) {
this.featuresStart = featuresStart;
}
public Integer getFeaturesEnd() {
return featuresEnd;
}
public void setFeaturesEnd(Integer featuresEnd) {
this.featuresEnd = featuresEnd;
}
public Boolean getDrop() {
return drop;
}
public void setDrop(Boolean drop) {
this.drop = drop;
}
public Boolean getAppend() {
return append;
}
public void setAppend(Boolean append) {
this.append = append;
}
public boolean getModify(){
return modify;
}
public void setModify(boolean modify){
this.modify = modify;
}
public boolean getModifyGeom(){
return modifyGeom;
}
public void setModifyGeom(boolean modifyGeom){
this.modifyGeom = modifyGeom;
}
public String getWriterType() {
return writerType;
}
public void setWriterType(String writerType) {
this.writerType = writerType;
}
public Mail getMail() {
return mail;
}
public void setMail(Mail mail) {
this.mail = mail;
}
public Schedule getSchedule() {
return schedule;
}
public void setSchedule(Schedule schedule) {
this.schedule = schedule;
}
public ProcessStatus getProcessStatus() {
return processStatus;
}
public void setProcessStatus(ProcessStatus processStatus) {
this.processStatus = processStatus;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Process)) {
return false;
}
Process other = (Process) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "nl.b3p.datastorelinker.entity.Process[id=" + id + "]";
}
public Integer getOrganizationId() {
return organizationId;
}
public void setOrganizationId(Integer organizationId) {
this.organizationId = organizationId;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getFilter(){
return filter;
}
public void setFilter(String filter){
this.filter = filter;
}
public String getModifyFilter(){
return modifyFilter;
}
public void setModifyFilter(String modifyFilter){
this.modifyFilter = modifyFilter;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Process getLinkedProcess() {
return linkedProcess;
}
public void setLinkedProcess(Process linkedProcess) {
this.linkedProcess = linkedProcess;
}
}
| lgpl-3.0 |
teryk/sonarqube | sonar-core/src/test/java/org/sonar/core/issue/IssueUpdaterTest.java | 17460 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.core.issue;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.issue.ActionPlan;
import org.sonar.api.issue.internal.DefaultIssue;
import org.sonar.api.issue.internal.FieldDiffs;
import org.sonar.api.issue.internal.IssueChangeContext;
import org.sonar.api.user.User;
import org.sonar.api.utils.Duration;
import org.sonar.core.user.DefaultUser;
import java.util.Date;
import static org.fest.assertions.Assertions.assertThat;
import static org.sonar.core.issue.IssueUpdater.*;
public class IssueUpdaterTest {
DefaultIssue issue = new DefaultIssue();
IssueChangeContext context = IssueChangeContext.createUser(new Date(), "emmerik");
IssueUpdater updater;
@Before
public void setUp() throws Exception {
updater = new IssueUpdater();
}
@Test
public void assign() throws Exception {
User user = new DefaultUser().setLogin("emmerik").setName("Emmerik");
boolean updated = updater.assign(issue, user, context);
assertThat(updated).isTrue();
assertThat(issue.assignee()).isEqualTo("emmerik");
assertThat(issue.mustSendNotifications()).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get(ASSIGNEE);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isEqualTo("Emmerik");
}
@Test
public void unassign() throws Exception {
issue.setAssignee("morgan");
boolean updated = updater.assign(issue, null, context);
assertThat(updated).isTrue();
assertThat(issue.assignee()).isNull();
assertThat(issue.mustSendNotifications()).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get(ASSIGNEE);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isNull();
}
@Test
public void change_assignee() throws Exception {
User user = new DefaultUser().setLogin("emmerik").setName("Emmerik");
issue.setAssignee("morgan");
boolean updated = updater.assign(issue, user, context);
assertThat(updated).isTrue();
assertThat(issue.assignee()).isEqualTo("emmerik");
assertThat(issue.mustSendNotifications()).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get(ASSIGNEE);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isEqualTo("Emmerik");
}
@Test
public void not_change_assignee() throws Exception {
User user = new DefaultUser().setLogin("morgan").setName("Morgan");
issue.setAssignee("morgan");
boolean updated = updater.assign(issue, user, context);
assertThat(updated).isFalse();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_severity() throws Exception {
boolean updated = updater.setSeverity(issue, "BLOCKER", context);
assertThat(updated).isTrue();
assertThat(issue.severity()).isEqualTo("BLOCKER");
assertThat(issue.manualSeverity()).isFalse();
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(SEVERITY);
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("BLOCKER");
}
@Test
public void set_past_severity() throws Exception {
issue.setSeverity("BLOCKER");
boolean updated = updater.setPastSeverity(issue, "INFO", context);
assertThat(updated).isTrue();
assertThat(issue.severity()).isEqualTo("BLOCKER");
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(SEVERITY);
assertThat(diff.oldValue()).isEqualTo("INFO");
assertThat(diff.newValue()).isEqualTo("BLOCKER");
}
@Test
public void update_severity() throws Exception {
issue.setSeverity("BLOCKER");
boolean updated = updater.setSeverity(issue, "MINOR", context);
assertThat(updated).isTrue();
assertThat(issue.severity()).isEqualTo("MINOR");
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(SEVERITY);
assertThat(diff.oldValue()).isEqualTo("BLOCKER");
assertThat(diff.newValue()).isEqualTo("MINOR");
}
@Test
public void not_change_severity() throws Exception {
issue.setSeverity("MINOR");
boolean updated = updater.setSeverity(issue, "MINOR", context);
assertThat(updated).isFalse();
assertThat(issue.mustSendNotifications()).isFalse();
assertThat(issue.currentChange()).isNull();
}
@Test
public void not_revert_manual_severity() throws Exception {
issue.setSeverity("MINOR").setManualSeverity(true);
try {
updater.setSeverity(issue, "MAJOR", context);
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Severity can't be changed");
}
}
@Test
public void set_manual_severity() throws Exception {
issue.setSeverity("BLOCKER");
boolean updated = updater.setManualSeverity(issue, "MINOR", context);
assertThat(updated).isTrue();
assertThat(issue.severity()).isEqualTo("MINOR");
assertThat(issue.manualSeverity()).isTrue();
assertThat(issue.mustSendNotifications()).isTrue();
FieldDiffs.Diff diff = issue.currentChange().get(SEVERITY);
assertThat(diff.oldValue()).isEqualTo("BLOCKER");
assertThat(diff.newValue()).isEqualTo("MINOR");
}
@Test
public void not_change_manual_severity() throws Exception {
issue.setSeverity("MINOR").setManualSeverity(true);
boolean updated = updater.setManualSeverity(issue, "MINOR", context);
assertThat(updated).isFalse();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_line() throws Exception {
boolean updated = updater.setLine(issue, 123);
assertThat(updated).isTrue();
assertThat(issue.line()).isEqualTo(123);
assertThat(issue.mustSendNotifications()).isFalse();
// do not save change
assertThat(issue.currentChange()).isNull();
}
@Test
public void set_past_line() throws Exception {
issue.setLine(42);
boolean updated = updater.setPastLine(issue, 123);
assertThat(updated).isTrue();
assertThat(issue.line()).isEqualTo(42);
assertThat(issue.mustSendNotifications()).isFalse();
// do not save change
assertThat(issue.currentChange()).isNull();
}
@Test
public void not_change_line() throws Exception {
issue.setLine(123);
boolean updated = updater.setLine(issue, 123);
assertThat(updated).isFalse();
assertThat(issue.line()).isEqualTo(123);
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_resolution() throws Exception {
boolean updated = updater.setResolution(issue, "OPEN", context);
assertThat(updated).isTrue();
assertThat(issue.resolution()).isEqualTo("OPEN");
FieldDiffs.Diff diff = issue.currentChange().get(RESOLUTION);
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("OPEN");
assertThat(issue.mustSendNotifications()).isTrue();
}
@Test
public void not_change_resolution() throws Exception {
issue.setResolution("FIXED");
boolean updated = updater.setResolution(issue, "FIXED", context);
assertThat(updated).isFalse();
assertThat(issue.resolution()).isEqualTo("FIXED");
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_status() throws Exception {
boolean updated = updater.setStatus(issue, "OPEN", context);
assertThat(updated).isTrue();
assertThat(issue.status()).isEqualTo("OPEN");
FieldDiffs.Diff diff = issue.currentChange().get(STATUS);
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("OPEN");
assertThat(issue.mustSendNotifications()).isTrue();
}
@Test
public void not_change_status() throws Exception {
issue.setStatus("CLOSED");
boolean updated = updater.setStatus(issue, "CLOSED", context);
assertThat(updated).isFalse();
assertThat(issue.status()).isEqualTo("CLOSED");
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_new_attribute_value() throws Exception {
boolean updated = updater.setAttribute(issue, "JIRA", "FOO-123", context);
assertThat(updated).isTrue();
assertThat(issue.attribute("JIRA")).isEqualTo("FOO-123");
assertThat(issue.currentChange().diffs()).hasSize(1);
assertThat(issue.currentChange().get("JIRA").oldValue()).isNull();
assertThat(issue.currentChange().get("JIRA").newValue()).isEqualTo("FOO-123");
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void unset_attribute() throws Exception {
issue.setAttribute("JIRA", "FOO-123");
boolean updated = updater.setAttribute(issue, "JIRA", null, context);
assertThat(updated).isTrue();
assertThat(issue.attribute("JIRA")).isNull();
assertThat(issue.currentChange().diffs()).hasSize(1);
assertThat(issue.currentChange().get("JIRA").oldValue()).isEqualTo("FOO-123");
assertThat(issue.currentChange().get("JIRA").newValue()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void not_update_attribute() throws Exception {
issue.setAttribute("JIRA", "FOO-123");
boolean updated = updater.setAttribute(issue, "JIRA", "FOO-123", context);
assertThat(updated).isFalse();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void plan_with_no_existing_plan() throws Exception {
ActionPlan newActionPlan = DefaultActionPlan.create("newName");
boolean updated = updater.plan(issue, newActionPlan, context);
assertThat(updated).isTrue();
assertThat(issue.actionPlanKey()).isEqualTo(newActionPlan.key());
FieldDiffs.Diff diff = issue.currentChange().get(ACTION_PLAN);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isEqualTo("newName");
assertThat(issue.mustSendNotifications()).isTrue();
}
@Test
public void plan_with_existing_plan() throws Exception {
issue.setActionPlanKey("formerActionPlan");
ActionPlan newActionPlan = DefaultActionPlan.create("newName").setKey("newKey");
boolean updated = updater.plan(issue, newActionPlan, context);
assertThat(updated).isTrue();
assertThat(issue.actionPlanKey()).isEqualTo(newActionPlan.key());
FieldDiffs.Diff diff = issue.currentChange().get(ACTION_PLAN);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isEqualTo("newName");
assertThat(issue.mustSendNotifications()).isTrue();
}
@Test
public void unplan() throws Exception {
issue.setActionPlanKey("formerActionPlan");
boolean updated = updater.plan(issue, null, context);
assertThat(updated).isTrue();
assertThat(issue.actionPlanKey()).isNull();
FieldDiffs.Diff diff = issue.currentChange().get(ACTION_PLAN);
assertThat(diff.oldValue()).isEqualTo(UNUSED);
assertThat(diff.newValue()).isNull();
assertThat(issue.mustSendNotifications()).isTrue();
}
@Test
public void not_plan_again() throws Exception {
issue.setActionPlanKey("existingActionPlan");
ActionPlan newActionPlan = DefaultActionPlan.create("existingActionPlan").setKey("existingActionPlan");
boolean updated = updater.plan(issue, newActionPlan, context);
assertThat(updated).isFalse();
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_effort_to_fix() throws Exception {
boolean updated = updater.setEffortToFix(issue, 3.14, context);
assertThat(updated).isTrue();
assertThat(issue.isChanged()).isTrue();
assertThat(issue.effortToFix()).isEqualTo(3.14);
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void not_set_effort_to_fix_if_unchanged() throws Exception {
issue.setEffortToFix(3.14);
boolean updated = updater.setEffortToFix(issue, 3.14, context);
assertThat(updated).isFalse();
assertThat(issue.isChanged()).isFalse();
assertThat(issue.effortToFix()).isEqualTo(3.14);
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_past_effort() throws Exception {
issue.setEffortToFix(3.14);
boolean updated = updater.setPastEffortToFix(issue, 1.0, context);
assertThat(updated).isTrue();
assertThat(issue.effortToFix()).isEqualTo(3.14);
// do not save change
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_past_technical_debt() throws Exception {
Duration newDebt = Duration.create(15 * 8 * 60);
Duration previousDebt = Duration.create(10 * 8 * 60);
issue.setDebt(newDebt);
boolean updated = updater.setPastTechnicalDebt(issue, previousDebt, context);
assertThat(updated).isTrue();
assertThat(issue.debt()).isEqualTo(newDebt);
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(TECHNICAL_DEBT);
assertThat(diff.oldValue()).isEqualTo(10L * 8 * 60);
assertThat(diff.newValue()).isEqualTo(15L * 8 * 60);
}
@Test
public void set_past_technical_debt_without_previous_value() throws Exception {
Duration newDebt = Duration.create(15 * 8 * 60);
issue.setDebt(newDebt);
boolean updated = updater.setPastTechnicalDebt(issue, null, context);
assertThat(updated).isTrue();
assertThat(issue.debt()).isEqualTo(newDebt);
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(TECHNICAL_DEBT);
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo(15L * 8 * 60);
}
@Test
public void set_past_technical_debt_with_null_new_value() throws Exception {
issue.setDebt(null);
Duration previousDebt = Duration.create(10 * 8 * 60);
boolean updated = updater.setPastTechnicalDebt(issue, previousDebt, context);
assertThat(updated).isTrue();
assertThat(issue.debt()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
FieldDiffs.Diff diff = issue.currentChange().get(TECHNICAL_DEBT);
assertThat(diff.oldValue()).isEqualTo(10L * 8 * 60);
assertThat(diff.newValue()).isNull();
}
@Test
public void set_message() throws Exception {
boolean updated = updater.setMessage(issue, "the message", context);
assertThat(updated).isTrue();
assertThat(issue.isChanged()).isTrue();
assertThat(issue.message()).isEqualTo("the message");
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_past_message() throws Exception {
issue.setMessage("new message");
boolean updated = updater.setPastMessage(issue, "past message", context);
assertThat(updated).isTrue();
assertThat(issue.message()).isEqualTo("new message");
// do not save change
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_author() throws Exception {
boolean updated = updater.setAuthorLogin(issue, "eric", context);
assertThat(updated).isTrue();
assertThat(issue.authorLogin()).isEqualTo("eric");
FieldDiffs.Diff diff = issue.currentChange().get("author");
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("eric");
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_project() throws Exception {
boolean updated = updater.setProject(issue, "sample", context);
assertThat(updated).isTrue();
assertThat(issue.projectKey()).isEqualTo("sample");
// do not save change
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void set_past_project() throws Exception {
issue.setProjectKey("new project key");
boolean updated = updater.setPastProject(issue, "past project key", context);
assertThat(updated).isTrue();
assertThat(issue.projectKey()).isEqualTo("new project key");
// do not save change
assertThat(issue.currentChange()).isNull();
assertThat(issue.mustSendNotifications()).isFalse();
}
@Test
public void not_set_past_project_if_no_change() throws Exception {
issue.setProjectKey("key");
boolean updated = updater.setPastProject(issue, "key", context);
assertThat(updated).isFalse();
assertThat(issue.projectKey()).isEqualTo("key");
}
}
| lgpl-3.0 |
TeamLapen/Vampirism | src/lib/java/de/teamlapen/lib/lib/client/gui/widget/ScrollableListWithDummyWidget.java | 4508 | package de.teamlapen.lib.lib.client.gui.widget;
import com.mojang.blaze3d.matrix.MatrixStack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.function.Supplier;
/**
* This is a {@link ScrollableListWidget} that supports a dummy element.
* This dummy element has the same item as the element which created it.
* This dummy element is capable to be rendered differently.
*
* @param <T> item that should be presented by a list entry
*/
public class ScrollableListWithDummyWidget<T> extends ScrollableListWidget<T> {
@Nonnull
private final ItemCreator<T> itemCreator;
@Nullable
private ListItem<T> dummyItem;
public ScrollableListWithDummyWidget(int xPos, int yPos, int width, int height, int itemHeight, Supplier<Collection<T>> baseValueSupplier, @Nonnull ItemCreator<T> itemSupplier) {
super(xPos, yPos, width, height, itemHeight, baseValueSupplier, (item, list) -> itemSupplier.apply(item, (ScrollableListWithDummyWidget<T>) list, false));
this.itemCreator = itemSupplier;
}
@Override
public void refresh() {
super.refresh();
if (this.dummyItem != null) {
this.listItems.stream().filter(l -> l.item.equals(this.dummyItem.item)).findAny().ifPresent(a -> {
this.addItem(this.dummyItem, a);
});
}
}
protected void clickItem(@Nonnull ListItem<T> listItem) {
boolean flag = false;
if (this.dummyItem != null) {
flag = listItem.item.equals(this.dummyItem.item);
this.removeItem(this.dummyItem);
this.dummyItem = null;
}
if (!flag) {
this.addItem(this.dummyItem = this.itemCreator.apply(listItem.item, this, true), listItem);
}
}
@FunctionalInterface
public interface ItemCreator<T> {
ListItem<T> apply(T item, ScrollableListWithDummyWidget<T> list, boolean isDummy);
}
public abstract static class ListItem<T> extends ScrollableListWidget.ListItem<T> {
protected final boolean isDummy;
public ListItem(T item, ScrollableListWithDummyWidget<T> list, boolean isDummy) {
super(item, list);
this.isDummy = isDummy;
}
@Override
public boolean onClick(double mouseX, double mouseY) {
if (this.isDummy) {
return this.onDummyClick(mouseX, mouseY);
} else {
((ScrollableListWithDummyWidget<T>) this.list).clickItem(this);
return true;
}
}
public boolean onDummyClick(double mouseX, double mouseY) {
return super.onClick(mouseX, mouseY);
}
@Override
public void render(MatrixStack matrixStack, int x, int y, int listWidth, int listHeight, int itemHeight, int mouseX, int mouseY, float partialTicks, float zLevel) {
if (this.isDummy) {
this.renderDummy(matrixStack, x, y, listWidth, listHeight, itemHeight, mouseX, mouseY, partialTicks, zLevel);
} else {
this.renderItem(matrixStack, x, y, listWidth, listHeight, itemHeight, mouseX, mouseY, partialTicks, zLevel);
}
}
public abstract void renderDummy(MatrixStack matrixStack, int x, int y, int listWidth, int listHeight, int itemHeight, int mouseX, int mouseY, float partialTicks, float zLevel);
public abstract void renderDummyToolTip(MatrixStack matrixStack, int x, int y, int listWidth, int listHeight, int itemHeight, int mouseX, int mouseY, float zLevel);
/**
*
*/
public abstract void renderItem(MatrixStack matrixStack, int x, int y, int listWidth, int listHeight, int itemHeight, int mouseX, int mouseY, float partialTicks, float zLevel);
public abstract void renderItemToolTip(MatrixStack matrixStack, int x, int y, int listWidth, int listHeight, int itemHeight, int mouseX, int mouseY, float zLevel);
@Override
public void renderToolTip(MatrixStack matrixStack, int x, int y, int listWidth, int listHeight, int itemHeight, int mouseX, int mouseY, float zLevel) {
if (this.isDummy) {
this.renderDummyToolTip(matrixStack, x, y, listWidth, listHeight, itemHeight, mouseX, mouseY, zLevel);
} else {
this.renderItemToolTip(matrixStack, x, y, listWidth, listHeight, itemHeight, mouseX, mouseY, zLevel);
}
}
}
}
| lgpl-3.0 |
bioinfweb/LibrAlign | main/info.bioinfweb.libralign.core/src/info/bioinfweb/libralign/model/factory/package-info.java | 234 | /**
* Contains factory classes to create instances of implementations of {@link info.bioinfweb.libralign.model.AlignmentModel}.
*
* @author Ben Stöver
* @since 0.4.0
*/
package info.bioinfweb.libralign.model.factory; | lgpl-3.0 |
ujmp/universal-java-matrix-package | ujmp-core/src/main/java/org/ujmp/core/timeseries/TimeSeriesMatrix.java | 6406 | /*
* Copyright (C) 2008-2015 by Holger Arndt
*
* This file is part of the Universal Java Matrix Package (UJMP).
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* UJMP is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* UJMP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with UJMP; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package org.ujmp.core.timeseries;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.ujmp.core.Matrix;
import org.ujmp.core.collections.composite.SortedListSet;
import org.ujmp.core.doublematrix.stub.AbstractDenseDoubleMatrix2D;
public class TimeSeriesMatrix extends AbstractDenseDoubleMatrix2D {
private static final long serialVersionUID = 4326920011599023858L;
public enum Interpolation {
NONE, STEPS, LINEAR
};
private Interpolation defaultInterpolation = Interpolation.NONE;
private final Map<Integer, Interpolation> seriesInterpolations = new HashMap<Integer, Interpolation>();
private final List<SortedMap<Long, Double>> series = new ArrayList<SortedMap<Long, Double>>();
private final SortedListSet<Long> timestampsListSet = new SortedListSet<Long>();
public TimeSeriesMatrix() {
super(1, 1);
}
public void addEvent(long timestamp, Matrix value) {
if (value.getRowCount() != 1) {
throw new RuntimeException("matrix cannot have more than one row");
}
for (int id = 0; id < value.getColumnCount(); id++) {
addEvent(timestamp, id + 1, value.getAsDouble(0, id));
}
}
public Interpolation getInterpolation(int seriesId) {
Interpolation i = seriesInterpolations.get(seriesId);
if (i == null) {
return defaultInterpolation;
} else {
return i;
}
}
public Interpolation getDefaultInterpolation() {
return defaultInterpolation;
}
public void setDefaultInterpolation(Interpolation defaultInterpolation) {
this.defaultInterpolation = defaultInterpolation;
}
/**
* Adds the events of a new Matrix to the time series. The first column of
* the matrix must contain the timestamps.
*
* @param events
* matrix with events to add
*/
public void addEvents(Matrix events) {
int seriesCount = getSeriesCount();
for (int r = 0; r < events.getRowCount(); r++) {
long timestamp = events.getAsLong(r, 0);
for (int c = 1; c < events.getColumnCount(); c++) {
double value = events.getAsDouble(r, c);
addEvent(timestamp, seriesCount + c - 1, value);
}
}
}
public void addEvent(long timestamp, int column, double value) {
int seriesId = column - 1;
while (series.size() <= seriesId) {
series.add(new TreeMap<Long, Double>());
}
SortedMap<Long, Double> map = series.get(seriesId);
map.put(timestamp, value);
timestampsListSet.add(timestamp);
}
public int getEventCount() {
return timestampsListSet.size();
}
public int getSeriesCount() {
return series.size();
}
public List<Long> getTimestamps() {
return timestampsListSet;
}
public long[] getSize() {
size[ROW] = getEventCount();
size[COLUMN] = getSeriesCount() + 1;
return size;
}
public long getRowCount() {
return getEventCount();
}
public long getColumnCount() {
return getSeriesCount() + 1;
}
public double getDouble(long row, long column) {
return getDouble((int) row, (int) column);
}
public double getDouble(int row, int column) {
if (row < 0 || column >= getColumnCount() || row >= getRowCount()) {
return Double.NaN;
}
int seriesId = column - 1;
long timestamp = timestampsListSet.get(row);
if (column == 0) {
return timestamp;
} else {
SortedMap<Long, Double> map = series.get(seriesId);
switch (getInterpolation(seriesId)) {
case NONE:
Double v = map.get(timestamp);
if (v == null) {
return Double.NaN;
} else {
return v;
}
case STEPS:
Iterator<Long> it = map.keySet().iterator();
double value = 0.0;
while (it.hasNext()) {
long t = it.next();
if (t > timestamp) {
break;
} else {
value = map.get(t);
}
}
return value;
default:
throw new RuntimeException("Interpolation method not (yet) supported: "
+ getInterpolation(seriesId));
}
}
}
public void setDouble(double value, long row, long column) {
throw new RuntimeException("please use addEvent() for making changes");
}
public void setDouble(double value, int row, int column) {
throw new RuntimeException("please use addEvent() for making changes");
}
public void setInterpolation(int column, Interpolation interpolation) {
int seriesId = column - 1;
seriesInterpolations.put(seriesId, interpolation);
}
public long getRowForTime(long time) {
long rows = getRowCount();
for (long r = 0; r < rows; r++) {
long t = getAsLong(r, 0);
if (t == time) {
return r;
}
}
return -1;
}
public double getAsDoubleForTime(long time, long column) {
long row = getRowForTime(time);
if (row < 0 || column >= getColumnCount()) {
return Double.NaN;
}
return getAsDouble(row, column);
}
public long getTimestamp(long row) {
if (row < 0 | row >= timestampsListSet.size()) {
return 0;
} else {
return timestampsListSet.get((int) row);
}
}
public long getMinTimestamp() {
if (timestampsListSet.isEmpty()) {
return 0;
} else {
return timestampsListSet.first();
}
}
public long getMaxTimestamp() {
if (timestampsListSet.isEmpty()) {
return 0;
} else {
return timestampsListSet.last();
}
}
}
| lgpl-3.0 |
sunmingshi/LittleStore | easy-snacks-share/src/main/java/com/littlestore/share/util/JsonUtil.java | 351 | package com.littlestore.share.util;
import com.alibaba.fastjson.JSON;
/**
* JSON转换工具类
*/
public class JsonUtil {
public static String toJson(Object data) {
return JSON.toJSONString(data);
}
public static <T> T fromJson(String jsonSource, Class<T> type) {
return JSON.parseObject(jsonSource,type);
}
}
| unlicense |
MaciejSzaflik/MedicalAwesomeness | EdgeDetectionAlgorithms/src/nobody/algorithms/LoG.java | 798 | package nobody.algorithms;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
public class LoG implements IEdgeDetect {
float[] matrix = {
0,1,1,2,2,2,1,1,0,
1,2,4,5,5,5,4,2,1,
1,4,5,3,0,3,5,4,2,
2,5,3,-12,-24,-12,3,5,2,
2,5,0,-24,-40,-25,0,5,2,
2,5,3,-12,-24,-12,3,5,2,
1,4,5,3,0,3,5,4,2,
1,2,4,5,5,5,4,2,1,
0,1,1,2,2,2,1,1,0
};
@Override
public BufferedImage doYourThing(BufferedImage Image) {
BufferedImageOp op = new ConvolveOp( new Kernel(9, 9,matrix));
BufferedImage dest = new BufferedImage(Image.getWidth(), Image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
return op.filter(Image, dest);
}
}
| unlicense |
Ghuillaume/CSA | src/M1/server_details/DBConnectionRoleFrom.java | 217 | package M1.server_details;
import M2.Connecteur;
import M2.RoleFrom;
public class DBConnectionRoleFrom extends RoleFrom {
public DBConnectionRoleFrom(String name, Connecteur parent) {
super(name, parent);
}
}
| unlicense |
Eitz/server-managing-multi-agents-simulation | src/websim/graphics/ComputersPanel.java | 275 | /*
* 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 websim.graphics;
/**
*
* @author eitz
*/
public class ComputersPanel {
}
| unlicense |
clilystudio/NetBook | allsrc/com/nostra13/universalimageloader/core/j.java | 839 | package com.nostra13.universalimageloader.core;
import com.nostra13.universalimageloader.core.download.ImageDownloader;
import java.io.InputStream;
final class j
implements ImageDownloader
{
private final ImageDownloader a;
public j(ImageDownloader paramImageDownloader)
{
this.a = paramImageDownloader;
}
public final InputStream a(String paramString, Object paramObject)
{
switch (h.a[com.nostra13.universalimageloader.core.download.ImageDownloader.Scheme.ofUri(paramString).ordinal()])
{
default:
return this.a.a(paramString, paramObject);
case 1:
case 2:
}
throw new IllegalStateException();
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.nostra13.universalimageloader.core.j
* JD-Core Version: 0.6.0
*/ | unlicense |
clilystudio/NetBook | allsrc/com/b/c.java | 24414 | package com.b;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class c
implements Closeable
{
private static Pattern a = Pattern.compile("[a-z0-9_]{1,64}");
private static final OutputStream o = new e();
private final File b;
private final File c;
private final File d;
private final int e;
private long f;
private final int g;
private long h = 0L;
private Writer i;
private final LinkedHashMap<String, g> j = new LinkedHashMap(0, 0.75F, true);
private int k;
private long l = 0L;
private ThreadPoolExecutor m = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue());
private final Callable<Void> n = new d(this);
private c(File paramFile, int paramInt1, int paramInt2, long paramLong)
{
this.b = paramFile;
this.e = paramInt1;
this.c = new File(paramFile, "journal");
this.d = new File(paramFile, "journal.tmp");
this.g = paramInt2;
this.f = paramLong;
}
private a a(String paramString, long paramLong)
{
monitorenter;
while (true)
{
g localg1;
a locala2;
try
{
i();
d(paramString);
localg1 = (g)this.j.get(paramString);
if (paramLong == -1L)
continue;
if (localg1 == null)
continue;
long l1 = g.e(localg1);
if (l1 == paramLong)
continue;
locala2 = null;
return locala2;
if (localg1 == null)
{
g localg3 = new g(this, paramString, 0);
this.j.put(paramString, localg3);
localg2 = localg3;
locala2 = new a(this, localg2, 0);
g.a(localg2, locala2);
this.i.write("DIRTY " + paramString + '\n');
this.i.flush();
continue;
}
}
finally
{
monitorexit;
}
a locala1 = g.a(localg1);
if (locala1 != null)
{
locala2 = null;
continue;
}
g localg2 = localg1;
}
}
public static c a(File paramFile, int paramInt1, int paramInt2, long paramLong)
{
if (paramLong <= 0L)
throw new IllegalArgumentException("maxSize <= 0");
c localc1 = new c(paramFile, 201105, 2, paramLong);
if (localc1.c.exists())
try
{
localc1.e();
localc1.f();
localc1.i = new BufferedWriter(new FileWriter(localc1.c, true));
return localc1;
}
catch (IOException localIOException)
{
System.out.println("DiskLruCache " + paramFile + " is corrupt: " + localIOException.getMessage() + ", removing");
localc1.close();
a.a(localc1.b);
}
paramFile.mkdirs();
c localc2 = new c(paramFile, 201105, 2, paramLong);
localc2.g();
return localc2;
}
private void a(a parama, boolean paramBoolean)
{
monitorenter;
g localg;
try
{
localg = a.a(parama);
if (g.a(localg) != parama)
throw new IllegalStateException();
}
finally
{
monitorexit;
}
int i1 = 0;
if (paramBoolean)
{
boolean bool = g.d(localg);
i1 = 0;
if (!bool)
for (int i2 = 0; ; i2++)
{
int i3 = this.g;
i1 = 0;
if (i2 >= i3)
break;
if (a.b(parama)[i2] == 0)
{
parama.b();
throw new IllegalStateException("Newly created entry didn't create value for index " + i2);
}
if (localg.b(i2).exists())
continue;
parama.b();
monitorexit;
return;
}
}
while (true)
{
if (i1 < this.g)
{
File localFile1 = localg.b(i1);
if (paramBoolean)
{
if (localFile1.exists())
{
File localFile2 = localg.a(i1);
localFile1.renameTo(localFile2);
long l2 = g.b(localg)[i1];
long l3 = localFile2.length();
g.b(localg)[i1] = l3;
this.h = (l3 + (this.h - l2));
}
}
else
a(localFile1);
}
else
{
this.k = (1 + this.k);
g.a(localg, null);
if ((paramBoolean | g.d(localg)))
{
g.a(localg, true);
this.i.write("CLEAN " + g.c(localg) + localg.a() + '\n');
if (paramBoolean)
{
long l1 = this.l;
this.l = (1L + l1);
g.a(localg, l1);
}
}
while (true)
{
if ((this.h <= this.f) && (!h()))
break label418;
this.m.submit(this.n);
break;
this.j.remove(g.c(localg));
this.i.write("REMOVE " + g.c(localg) + '\n');
}
label418: break;
}
i1++;
}
}
private static void a(File paramFile)
{
if ((paramFile.exists()) && (!paramFile.delete()))
throw new IOException();
}
private static void d(String paramString)
{
if (!a.matcher(paramString).matches())
throw new IllegalArgumentException("keys must match regex [a-z0-9_]{1,64}: \"" + paramString + "\"");
}
// ERROR //
private void e()
{
// Byte code:
// 0: new 334 com/b/i
// 3: dup
// 4: new 336 java/io/FileInputStream
// 7: dup
// 8: aload_0
// 9: getfield 103 com/b/c:c Ljava/io/File;
// 12: invokespecial 338 java/io/FileInputStream:<init> (Ljava/io/File;)V
// 15: getstatic 343 com/b/b:a Ljava/nio/charset/Charset;
// 18: invokespecial 346 com/b/i:<init> (Ljava/io/InputStream;Ljava/nio/charset/Charset;)V
// 21: astore_1
// 22: aload_1
// 23: invokevirtual 347 com/b/i:a ()Ljava/lang/String;
// 26: astore_3
// 27: aload_1
// 28: invokevirtual 347 com/b/i:a ()Ljava/lang/String;
// 31: astore 4
// 33: aload_1
// 34: invokevirtual 347 com/b/i:a ()Ljava/lang/String;
// 37: astore 5
// 39: aload_1
// 40: invokevirtual 347 com/b/i:a ()Ljava/lang/String;
// 43: astore 6
// 45: aload_1
// 46: invokevirtual 347 com/b/i:a ()Ljava/lang/String;
// 49: astore 7
// 51: ldc_w 349
// 54: aload_3
// 55: invokevirtual 355 java/lang/String:equals (Ljava/lang/Object;)Z
// 58: ifeq +55 -> 113
// 61: ldc_w 357
// 64: aload 4
// 66: invokevirtual 355 java/lang/String:equals (Ljava/lang/Object;)Z
// 69: ifeq +44 -> 113
// 72: aload_0
// 73: getfield 94 com/b/c:e I
// 76: invokestatic 362 java/lang/Integer:toString (I)Ljava/lang/String;
// 79: aload 5
// 81: invokevirtual 355 java/lang/String:equals (Ljava/lang/Object;)Z
// 84: ifeq +29 -> 113
// 87: aload_0
// 88: getfield 109 com/b/c:g I
// 91: invokestatic 362 java/lang/Integer:toString (I)Ljava/lang/String;
// 94: aload 6
// 96: invokevirtual 355 java/lang/String:equals (Ljava/lang/Object;)Z
// 99: ifeq +14 -> 113
// 102: ldc_w 364
// 105: aload 7
// 107: invokevirtual 355 java/lang/String:equals (Ljava/lang/Object;)Z
// 110: ifne +110 -> 220
// 113: new 182 java/io/IOException
// 116: dup
// 117: new 153 java/lang/StringBuilder
// 120: dup
// 121: ldc_w 366
// 124: invokespecial 157 java/lang/StringBuilder:<init> (Ljava/lang/String;)V
// 127: aload_3
// 128: invokevirtual 161 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 131: ldc_w 368
// 134: invokevirtual 161 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 137: aload 4
// 139: invokevirtual 161 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 142: ldc_w 368
// 145: invokevirtual 161 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 148: aload 6
// 150: invokevirtual 161 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 153: ldc_w 368
// 156: invokevirtual 161 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 159: aload 7
// 161: invokevirtual 161 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 164: ldc_w 370
// 167: invokevirtual 161 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 170: invokevirtual 168 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 173: invokespecial 371 java/io/IOException:<init> (Ljava/lang/String;)V
// 176: athrow
// 177: astore_2
// 178: aload_1
// 179: invokestatic 374 com/b/a:a (Ljava/io/Closeable;)V
// 182: aload_2
// 183: athrow
// 184: aload 10
// 186: iconst_1
// 187: aaload
// 188: astore 11
// 190: aload 10
// 192: iconst_0
// 193: aaload
// 194: ldc_w 376
// 197: invokevirtual 355 java/lang/String:equals (Ljava/lang/Object;)Z
// 200: ifeq +76 -> 276
// 203: aload 10
// 205: arraylength
// 206: iconst_2
// 207: if_icmpne +69 -> 276
// 210: aload_0
// 211: getfield 63 com/b/c:j Ljava/util/LinkedHashMap;
// 214: aload 11
// 216: invokevirtual 303 java/util/LinkedHashMap:remove (Ljava/lang/Object;)Ljava/lang/Object;
// 219: pop
// 220: aload_1
// 221: invokevirtual 347 com/b/i:a ()Ljava/lang/String;
// 224: astore 9
// 226: aload 9
// 228: ldc_w 378
// 231: invokevirtual 382 java/lang/String:split (Ljava/lang/String;)[Ljava/lang/String;
// 234: astore 10
// 236: aload 10
// 238: arraylength
// 239: iconst_2
// 240: if_icmpge -56 -> 184
// 243: new 182 java/io/IOException
// 246: dup
// 247: new 153 java/lang/StringBuilder
// 250: dup
// 251: ldc_w 384
// 254: invokespecial 157 java/lang/StringBuilder:<init> (Ljava/lang/String;)V
// 257: aload 9
// 259: invokevirtual 161 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 262: invokevirtual 168 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 265: invokespecial 371 java/io/IOException:<init> (Ljava/lang/String;)V
// 268: athrow
// 269: astore 8
// 271: aload_1
// 272: invokestatic 374 com/b/a:a (Ljava/io/Closeable;)V
// 275: return
// 276: aload_0
// 277: getfield 63 com/b/c:j Ljava/util/LinkedHashMap;
// 280: aload 11
// 282: invokevirtual 127 java/util/LinkedHashMap:get (Ljava/lang/Object;)Ljava/lang/Object;
// 285: checkcast 129 com/b/g
// 288: astore 12
// 290: aload 12
// 292: ifnonnull +254 -> 546
// 295: new 129 com/b/g
// 298: dup
// 299: aload_0
// 300: aload 11
// 302: iconst_0
// 303: invokespecial 137 com/b/g:<init> (Lcom/b/c;Ljava/lang/String;B)V
// 306: astore 13
// 308: aload_0
// 309: getfield 63 com/b/c:j Ljava/util/LinkedHashMap;
// 312: aload 11
// 314: aload 13
// 316: invokevirtual 141 java/util/LinkedHashMap:put (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
// 319: pop
// 320: aload 13
// 322: astore 15
// 324: aload 10
// 326: iconst_0
// 327: aaload
// 328: ldc_w 386
// 331: invokevirtual 355 java/lang/String:equals (Ljava/lang/Object;)Z
// 334: ifeq +126 -> 460
// 337: aload 10
// 339: arraylength
// 340: iconst_2
// 341: aload_0
// 342: getfield 109 com/b/c:g I
// 345: iadd
// 346: if_icmpne +114 -> 460
// 349: aload 15
// 351: iconst_1
// 352: invokestatic 284 com/b/g:a (Lcom/b/g;Z)Z
// 355: pop
// 356: aload 15
// 358: aconst_null
// 359: invokestatic 149 com/b/g:a (Lcom/b/g;Lcom/b/a;)Lcom/b/a;
// 362: pop
// 363: aload 10
// 365: arraylength
// 366: istore 19
// 368: aload 10
// 370: arraylength
// 371: istore 20
// 373: iconst_2
// 374: iload 19
// 376: if_icmple +11 -> 387
// 379: new 184 java/lang/IllegalArgumentException
// 382: dup
// 383: invokespecial 387 java/lang/IllegalArgumentException:<init> ()V
// 386: athrow
// 387: iconst_2
// 388: iload 20
// 390: if_icmple +11 -> 401
// 393: new 389 java/lang/ArrayIndexOutOfBoundsException
// 396: dup
// 397: invokespecial 390 java/lang/ArrayIndexOutOfBoundsException:<init> ()V
// 400: athrow
// 401: iload 19
// 403: iconst_2
// 404: isub
// 405: istore 21
// 407: iload 21
// 409: iload 20
// 411: iconst_2
// 412: isub
// 413: invokestatic 396 java/lang/Math:min (II)I
// 416: istore 22
// 418: aload 10
// 420: invokevirtual 400 java/lang/Object:getClass ()Ljava/lang/Class;
// 423: invokevirtual 405 java/lang/Class:getComponentType ()Ljava/lang/Class;
// 426: iload 21
// 428: invokestatic 411 java/lang/reflect/Array:newInstance (Ljava/lang/Class;I)Ljava/lang/Object;
// 431: checkcast 413 [Ljava/lang/Object;
// 434: astore 23
// 436: aload 10
// 438: iconst_2
// 439: aload 23
// 441: iconst_0
// 442: iload 22
// 444: invokestatic 417 java/lang/System:arraycopy (Ljava/lang/Object;ILjava/lang/Object;II)V
// 447: aload 15
// 449: aload 23
// 451: checkcast 419 [Ljava/lang/String;
// 454: invokestatic 422 com/b/g:a (Lcom/b/g;[Ljava/lang/String;)V
// 457: goto -237 -> 220
// 460: aload 10
// 462: iconst_0
// 463: aaload
// 464: ldc_w 424
// 467: invokevirtual 355 java/lang/String:equals (Ljava/lang/Object;)Z
// 470: ifeq +30 -> 500
// 473: aload 10
// 475: arraylength
// 476: iconst_2
// 477: if_icmpne +23 -> 500
// 480: aload 15
// 482: new 143 com/b/a
// 485: dup
// 486: aload_0
// 487: aload 15
// 489: iconst_0
// 490: invokespecial 146 com/b/a:<init> (Lcom/b/c;Lcom/b/g;B)V
// 493: invokestatic 149 com/b/g:a (Lcom/b/g;Lcom/b/a;)Lcom/b/a;
// 496: pop
// 497: goto -277 -> 220
// 500: aload 10
// 502: iconst_0
// 503: aaload
// 504: ldc_w 426
// 507: invokevirtual 355 java/lang/String:equals (Ljava/lang/Object;)Z
// 510: ifeq +10 -> 520
// 513: aload 10
// 515: arraylength
// 516: iconst_2
// 517: if_icmpeq -297 -> 220
// 520: new 182 java/io/IOException
// 523: dup
// 524: new 153 java/lang/StringBuilder
// 527: dup
// 528: ldc_w 384
// 531: invokespecial 157 java/lang/StringBuilder:<init> (Ljava/lang/String;)V
// 534: aload 9
// 536: invokevirtual 161 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 539: invokevirtual 168 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 542: invokespecial 371 java/io/IOException:<init> (Ljava/lang/String;)V
// 545: athrow
// 546: aload 12
// 548: astore 15
// 550: goto -226 -> 324
//
// Exception table:
// from to target type
// 22 113 177 finally
// 113 177 177 finally
// 184 220 177 finally
// 220 269 177 finally
// 276 290 177 finally
// 295 320 177 finally
// 324 373 177 finally
// 379 387 177 finally
// 393 401 177 finally
// 407 457 177 finally
// 460 497 177 finally
// 500 520 177 finally
// 520 546 177 finally
// 184 220 269 java/io/EOFException
// 220 269 269 java/io/EOFException
// 276 290 269 java/io/EOFException
// 295 320 269 java/io/EOFException
// 324 373 269 java/io/EOFException
// 379 387 269 java/io/EOFException
// 393 401 269 java/io/EOFException
// 407 457 269 java/io/EOFException
// 460 497 269 java/io/EOFException
// 500 520 269 java/io/EOFException
// 520 546 269 java/io/EOFException
}
private void f()
{
a(this.d);
Iterator localIterator = this.j.values().iterator();
while (localIterator.hasNext())
{
g localg = (g)localIterator.next();
if (g.a(localg) == null)
{
for (int i2 = 0; i2 < this.g; i2++)
this.h += g.b(localg)[i2];
continue;
}
g.a(localg, null);
for (int i1 = 0; i1 < this.g; i1++)
{
a(localg.a(i1));
a(localg.b(i1));
}
localIterator.remove();
}
}
private void g()
{
monitorenter;
BufferedWriter localBufferedWriter;
while (true)
{
g localg;
try
{
if (this.i == null)
continue;
this.i.close();
localBufferedWriter = new BufferedWriter(new FileWriter(this.d));
localBufferedWriter.write("libcore.io.DiskLruCache");
localBufferedWriter.write("\n");
localBufferedWriter.write("1");
localBufferedWriter.write("\n");
localBufferedWriter.write(Integer.toString(this.e));
localBufferedWriter.write("\n");
localBufferedWriter.write(Integer.toString(this.g));
localBufferedWriter.write("\n");
localBufferedWriter.write("\n");
Iterator localIterator = this.j.values().iterator();
if (!localIterator.hasNext())
break;
localg = (g)localIterator.next();
if (g.a(localg) != null)
{
localBufferedWriter.write("DIRTY " + g.c(localg) + '\n');
continue;
}
}
finally
{
monitorexit;
}
localBufferedWriter.write("CLEAN " + g.c(localg) + localg.a() + '\n');
}
localBufferedWriter.close();
this.d.renameTo(this.c);
this.i = new BufferedWriter(new FileWriter(this.c, true));
monitorexit;
}
private boolean h()
{
return (this.k >= 2000) && (this.k >= this.j.size());
}
private void i()
{
if (this.i == null)
throw new IllegalStateException("cache is closed");
}
private void j()
{
while (this.h > this.f)
c((String)((Map.Entry)this.j.entrySet().iterator().next()).getKey());
}
// ERROR //
public final h a(String paramString)
{
// Byte code:
// 0: iconst_0
// 1: istore_2
// 2: aload_0
// 3: monitorenter
// 4: aload_0
// 5: invokespecial 120 com/b/c:i ()V
// 8: aload_1
// 9: invokestatic 123 com/b/c:d (Ljava/lang/String;)V
// 12: aload_0
// 13: getfield 63 com/b/c:j Ljava/util/LinkedHashMap;
// 16: aload_1
// 17: invokevirtual 127 java/util/LinkedHashMap:get (Ljava/lang/Object;)Ljava/lang/Object;
// 20: checkcast 129 com/b/g
// 23: astore 4
// 25: aconst_null
// 26: astore 5
// 28: aload 4
// 30: ifnonnull +8 -> 38
// 33: aload_0
// 34: monitorexit
// 35: aload 5
// 37: areturn
// 38: aload 4
// 40: invokestatic 253 com/b/g:d (Lcom/b/g;)Z
// 43: istore 6
// 45: aconst_null
// 46: astore 5
// 48: iload 6
// 50: ifeq -17 -> 33
// 53: aload_0
// 54: getfield 109 com/b/c:g I
// 57: anewarray 478 java/io/InputStream
// 60: astore 7
// 62: iload_2
// 63: aload_0
// 64: getfield 109 com/b/c:g I
// 67: if_icmpge +26 -> 93
// 70: aload 7
// 72: iload_2
// 73: new 336 java/io/FileInputStream
// 76: dup
// 77: aload 4
// 79: iload_2
// 80: invokevirtual 269 com/b/g:a (I)Ljava/io/File;
// 83: invokespecial 338 java/io/FileInputStream:<init> (Ljava/io/File;)V
// 86: aastore
// 87: iinc 2 1
// 90: goto -28 -> 62
// 93: aload_0
// 94: iconst_1
// 95: aload_0
// 96: getfield 114 com/b/c:k I
// 99: iadd
// 100: putfield 114 com/b/c:k I
// 103: aload_0
// 104: getfield 151 com/b/c:i Ljava/io/Writer;
// 107: new 153 java/lang/StringBuilder
// 110: dup
// 111: ldc_w 480
// 114: invokespecial 157 java/lang/StringBuilder:<init> (Ljava/lang/String;)V
// 117: aload_1
// 118: invokevirtual 161 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 121: bipush 10
// 123: invokevirtual 164 java/lang/StringBuilder:append (C)Ljava/lang/StringBuilder;
// 126: invokevirtual 168 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 129: invokevirtual 483 java/io/Writer:append (Ljava/lang/CharSequence;)Ljava/io/Writer;
// 132: pop
// 133: aload_0
// 134: invokespecial 296 com/b/c:h ()Z
// 137: ifeq +15 -> 152
// 140: aload_0
// 141: getfield 83 com/b/c:m Ljava/util/concurrent/ThreadPoolExecutor;
// 144: aload_0
// 145: getfield 90 com/b/c:n Ljava/util/concurrent/Callable;
// 148: invokevirtual 300 java/util/concurrent/ThreadPoolExecutor:submit (Ljava/util/concurrent/Callable;)Ljava/util/concurrent/Future;
// 151: pop
// 152: new 485 com/b/h
// 155: dup
// 156: aload_0
// 157: aload_1
// 158: aload 4
// 160: invokestatic 134 com/b/g:e (Lcom/b/g;)J
// 163: aload 7
// 165: iconst_0
// 166: invokespecial 488 com/b/h:<init> (Lcom/b/c;Ljava/lang/String;J[Ljava/io/InputStream;B)V
// 169: astore 5
// 171: goto -138 -> 33
// 174: astore_3
// 175: aload_0
// 176: monitorexit
// 177: aload_3
// 178: athrow
// 179: astore 8
// 181: aconst_null
// 182: astore 5
// 184: goto -151 -> 33
//
// Exception table:
// from to target type
// 4 25 174 finally
// 38 45 174 finally
// 53 62 174 finally
// 62 87 174 finally
// 93 152 174 finally
// 152 171 174 finally
// 62 87 179 java/io/FileNotFoundException
}
public final File a()
{
return this.b;
}
public final long b()
{
return this.f;
}
public final a b(String paramString)
{
return a(paramString, -1L);
}
public final boolean c()
{
return this.i == null;
}
public final boolean c(String paramString)
{
monitorenter;
while (true)
{
try
{
i();
d(paramString);
g localg = (g)this.j.get(paramString);
if (localg == null)
continue;
a locala = g.a(localg);
int i1 = 0;
if (locala == null)
continue;
i2 = 0;
return i2;
this.h -= g.b(localg)[i1];
g.b(localg)[i1] = 0L;
i1++;
if (i1 < this.g)
{
File localFile = localg.a(i1);
if (localFile.delete())
continue;
throw new IOException("failed to delete " + localFile);
}
}
finally
{
monitorexit;
}
this.k = (1 + this.k);
this.i.append("REMOVE " + paramString + '\n');
this.j.remove(paramString);
if (h())
this.m.submit(this.n);
int i2 = 1;
}
}
public final void close()
{
monitorenter;
while (true)
{
try
{
Writer localWriter = this.i;
if (localWriter == null)
return;
Iterator localIterator = new ArrayList(this.j.values()).iterator();
if (localIterator.hasNext())
{
g localg = (g)localIterator.next();
if (g.a(localg) == null)
continue;
g.a(localg).b();
continue;
}
}
finally
{
monitorexit;
}
j();
this.i.close();
this.i = null;
}
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.b.c
* JD-Core Version: 0.6.0
*/ | unlicense |
cc14514/hq6 | hq-api/src/test/java/org/hyperic/hq/api/transfer/ResourceTransferTest.java | 3148 | package org.hyperic.hq.api.transfer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.List;
import org.easymock.EasyMock;
import org.hyperic.hq.api.model.AIResource;
import org.hyperic.hq.api.model.ResourceModel;
import org.hyperic.hq.api.model.ResourceTypeModel;
import org.hyperic.hq.api.transfer.impl.ResourceTransferImpl;
import org.hyperic.hq.appdef.server.session.AIQueueManagerImpl;
import org.hyperic.hq.authz.server.session.AuthzSubjectManagerImpl;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
//@DirtiesContext
//@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations =
// {"classpath*:/META-INF/spring/*-context.xml",
// "classpath:META-INF/hqapi-context.xml"})
//@Transactional
public class ResourceTransferTest {
ResourceTransferImpl resourceTransfer;
public ResourceTransferTest() {
super() ;
}//EOM
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
//resourceTransfer = new ResourceTransferImpl();
// this.serverConfigurator = EasyMock.createMock(ServerConfigurator.class);
/*resourceTransfer.setAiQueueManager(EasyMock.createMock(AIQueueManagerImpl.class));
resourceTransfer.setAuthzSubjectManager(EasyMock.createMock(AuthzSubjectManagerImpl.class));
resourceTransfer.setAiResourceMapper(EasyMock.createMock(AIResourceMapper.class));*/
}
@After
public void tearDown() throws Exception {
}
//@Test
/* public final void testGetAIResource() {
final String fqdn= "543" ;
String discoveryId = "ubuntu.eng.vmware.com";
//EasyMock.expect(resourceTransfer.getAiQueueManager().findAIPlatformByFqdn(resourceTransfer.getAuthzSubjectManager().getOverlordPojo(), fqdn)).andReturn(true);
discoveryId = "ubuntu.eng.vmware.com";
ResourceType type = ResourceType.PLATFORM;
AIResource aiResource = resourceTransfer.getAIResource(discoveryId, type);
assertNotNull("aiResource hasn't been found", aiResource);
assertEquals("Returned ai resource of incorrect type", type, aiResource.getResourceType());
assertEquals("Expected autoinventory id to be " + discoveryId + " but was " + aiResource.getUuid(), discoveryId, aiResource.getUuid());
}
@Test
public final void testApproveAIResource() {
AIResourceTransfer resourceTransfer = new AIResourceTransfer();
ResourceType type = ResourceType.PLATFORM;
List<String> ids = new ArrayList<String>(2);
ids.add("1");
ids.add("2");
List<Resource> approvedResource = resourceTransfer.approveAIResource(ids, type);
assertEquals("Number of approved resources doesn't match that of the discovered resources.", ids.size(), approvedResource.size());
}*/
}
| unlicense |
Samourai-Wallet/sentinel-android | tor/src/main/java/com/msopentech/thali/android/toronionproxy/torinstaller/NativeLoader.java | 2547 |
package com.msopentech.thali.android.toronionproxy.torinstaller;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class NativeLoader {
private final static String LIB_NAME = "tor";
private final static String LIB_SO_NAME = "tor.so";
private final static String TAG = "TorNativeLoader";
private static boolean loadFromZip(Context context, File destLocalFile, String arch) {
ZipFile zipFile = null;
InputStream stream = null;
try {
zipFile = new ZipFile(context.getApplicationInfo().sourceDir);
ZipEntry entry = zipFile.getEntry("lib/" + arch + "/" + LIB_SO_NAME);
if (entry == null) {
throw new Exception("Unable to find file in apk:" + "lib/" + arch + "/" + LIB_NAME);
}
//how we wrap this in another stream because the native .so is zipped itself
stream = zipFile.getInputStream(entry);
OutputStream out = new FileOutputStream(destLocalFile);
byte[] buf = new byte[4096];
int len;
while ((len = stream.read(buf)) > 0) {
Thread.yield();
out.write(buf, 0, len);
}
out.close();
destLocalFile.setReadable(true, false);
destLocalFile.setExecutable(true, false);
destLocalFile.setWritable(true);
return true;
} catch (Exception e) {
Log.e(TAG, e.getMessage());
} finally {
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
if (zipFile != null) {
try {
zipFile.close();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
}
return false;
}
public static synchronized File initNativeLibs(Context context, File destLocalFile) {
try {
String folder = Build.CPU_ABI;
if (loadFromZip(context, destLocalFile, folder)) {
return destLocalFile;
}
} catch (Throwable e) {
Log.e(TAG, e.getMessage(), e);
}
return null;
}
}
| unlicense |
TWiStErRob/glide-support | src/glide4/java/com/bumptech/glide/supportapp/GlideBaseImageActivity.java | 752 | package com.bumptech.glide.supportapp;
import android.view.*;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.supportapp.utils.ClearCachesTask;
public abstract class GlideBaseImageActivity extends GlideBaseActivity {
protected void clear(ImageView imageView) {
Glide.with(this).clear(imageView);
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
item(menu, 5, "Glide.arrayPool.clearMemory", "#8800ff", false);
return true;
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 5:
Glide.get(this).getArrayPool().clearMemory();
default:
return super.onOptionsItemSelected(item);
}
}
}
| unlicense |
SleepyTrousers/EnderIO | enderio-conduits-refinedstorage/src/main/java/crazypants/enderio/conduit/refinedstorage/conduit/RefinedStorageConduit.java | 18493 | package crazypants.enderio.conduit.refinedstorage.conduit;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.enderio.core.api.client.gui.ITabPanel;
import com.enderio.core.common.util.NNList;
import com.enderio.core.common.vecmath.Vector4f;
import com.raoulvdberge.refinedstorage.api.network.node.INetworkNode;
import com.raoulvdberge.refinedstorage.api.network.node.INetworkNodeManager;
import crazypants.enderio.base.conduit.ConduitUtil;
import crazypants.enderio.base.conduit.ConnectionMode;
import crazypants.enderio.base.conduit.IClientConduit;
import crazypants.enderio.base.conduit.IConduit;
import crazypants.enderio.base.conduit.IConduitNetwork;
import crazypants.enderio.base.conduit.IConduitTexture;
import crazypants.enderio.base.conduit.IGuiExternalConnection;
import crazypants.enderio.base.conduit.RaytraceResult;
import crazypants.enderio.base.conduit.geom.CollidableComponent;
import crazypants.enderio.base.filter.FilterRegistry;
import crazypants.enderio.base.filter.IFilter;
import crazypants.enderio.base.filter.capability.CapabilityFilterHolder;
import crazypants.enderio.base.filter.fluid.items.IItemFilterFluidUpgrade;
import crazypants.enderio.base.filter.item.IItemFilter;
import crazypants.enderio.base.filter.item.ItemFilter;
import crazypants.enderio.base.filter.item.items.ItemBasicItemFilter;
import crazypants.enderio.base.render.registry.TextureRegistry;
import crazypants.enderio.base.tool.ToolUtil;
import crazypants.enderio.conduit.refinedstorage.RSHelper;
import crazypants.enderio.conduit.refinedstorage.conduit.gui.RefinedStorageSettings;
import crazypants.enderio.conduit.refinedstorage.init.ConduitRefinedStorageObject;
import crazypants.enderio.conduits.capability.CapabilityUpgradeHolder;
import crazypants.enderio.conduits.conduit.AbstractConduit;
import crazypants.enderio.conduits.render.ConduitTexture;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.items.CapabilityItemHandler;
public class RefinedStorageConduit extends AbstractConduit implements IRefinedStorageConduit {
static final Map<String, IConduitTexture> ICONS = new HashMap<>();
static {
ICONS.put(ICON_KEY, new ConduitTexture(TextureRegistry.registerTexture(ICON_KEY), ConduitTexture.arm(0)));
ICONS.put(ICON_CORE_KEY, new ConduitTexture(TextureRegistry.registerTexture(ICON_CORE_KEY), ConduitTexture.core()));
}
private Map<EnumFacing, ItemStack> upgrades = new EnumMap<EnumFacing, ItemStack>(EnumFacing.class);
protected final EnumMap<EnumFacing, IFilter> outputFilters = new EnumMap<>(EnumFacing.class);
protected final EnumMap<EnumFacing, IFilter> inputFilters = new EnumMap<>(EnumFacing.class);
protected final EnumMap<EnumFacing, ItemStack> outputFilterUpgrades = new EnumMap<>(EnumFacing.class);
protected final EnumMap<EnumFacing, ItemStack> inputFilterUpgrades = new EnumMap<>(EnumFacing.class);
private ConduitRefinedStorageNode clientSideNode;
protected RefinedStorageConduitNetwork network;
public RefinedStorageConduit() {
for (EnumFacing dir : EnumFacing.VALUES) {
upgrades.put(dir, ItemStack.EMPTY);
outputFilterUpgrades.put(dir, ItemStack.EMPTY);
inputFilterUpgrades.put(dir, ItemStack.EMPTY);
}
}
@Override
public @Nonnull NNList<ItemStack> getDrops() {
NNList<ItemStack> res = super.getDrops();
for (ItemStack stack : upgrades.values()) {
res.add(stack);
}
for (ItemStack stack : inputFilterUpgrades.values()) {
res.add(stack);
}
for (ItemStack stack : outputFilterUpgrades.values()) {
res.add(stack);
}
return res;
}
@Override
public boolean canConnectToExternal(@Nonnull EnumFacing direction, boolean ignoreConnectionMode) {
TileEntity te = getBundle().getEntity();
World world = te.getWorld();
TileEntity test = world.getTileEntity(te.getPos().offset(direction));
if (test == null) {
return false;
}
if (test.hasCapability(RSHelper.NETWORK_NODE_PROXY_CAPABILITY, direction.getOpposite())
|| test.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, direction.getOpposite())
|| test.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, direction.getOpposite())) {
return true;
}
return super.canConnectToExternal(direction, ignoreConnectionMode);
}
@Override
@Nonnull
public ITabPanel createGuiPanel(@Nonnull IGuiExternalConnection gui, @Nonnull IClientConduit con) {
return new RefinedStorageSettings(gui, con);
}
@Override
public boolean updateGuiPanel(@Nonnull ITabPanel panel) {
if (panel instanceof RefinedStorageSettings) {
return ((RefinedStorageSettings) panel).updateConduit(this);
}
return false;
}
@Override
public int getGuiPanelTabOrder() {
return 4;
}
@Override
@Nonnull
public Class<? extends IConduit> getBaseConduitType() {
return IRefinedStorageConduit.class;
}
@Override
@Nonnull
public ItemStack createItem() {
return new ItemStack(ConduitRefinedStorageObject.item_refined_storage_conduit.getItemNN(), 1);
}
@Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) {
if (capability == RSHelper.NETWORK_NODE_PROXY_CAPABILITY) {
return true;
}
return false;
}
@Override
@Nullable
@SuppressWarnings("unchecked")
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) {
if (capability == RSHelper.NETWORK_NODE_PROXY_CAPABILITY) {
return RSHelper.NETWORK_NODE_PROXY_CAPABILITY.cast(this);
}
return null;
}
@Override
public boolean hasClientCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) {
if (capability == RSHelper.NETWORK_NODE_PROXY_CAPABILITY) {
return true;
}
return false;
}
@Override
@Nullable
public <T> T getClientCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) {
if (capability == RSHelper.NETWORK_NODE_PROXY_CAPABILITY) {
return RSHelper.NETWORK_NODE_PROXY_CAPABILITY.cast(this);
}
return null;
}
@Override
public boolean hasInternalCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) {
if (capability == CapabilityUpgradeHolder.UPGRADE_HOLDER_CAPABILITY || capability == CapabilityFilterHolder.FILTER_HOLDER_CAPABILITY) {
return true;
}
return false;
}
@SuppressWarnings("unchecked")
@Nullable
@Override
public <T> T getInternalCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) {
if (capability == CapabilityUpgradeHolder.UPGRADE_HOLDER_CAPABILITY || capability == CapabilityFilterHolder.FILTER_HOLDER_CAPABILITY) {
return (T) this;
}
return null;
}
@Override
@Nonnull
public RefinedStorageConduitNetwork createNetworkForType() {
return new RefinedStorageConduitNetwork();
}
@Override
@Nullable
public RefinedStorageConduitNetwork getNetwork() throws NullPointerException {
return network;
}
@Override
public boolean setNetwork(@Nonnull IConduitNetwork<?, ?> network) {
this.network = (RefinedStorageConduitNetwork) network;
return super.setNetwork(network);
}
@Override
public void clearNetwork() {
network = null;
}
@Override
@Nonnull
public ConduitRefinedStorageNode getNode() {
World world = getBundle().getBundleworld();
BlockPos pos = getBundle().getLocation();
if (world.isRemote) {
return clientSideNode != null ? clientSideNode : (clientSideNode = new ConduitRefinedStorageNode(this));
}
INetworkNodeManager manager = RSHelper.API.getNetworkNodeManager(world);
INetworkNode node = manager.getNode(pos);
if (node == null || !node.getId().equals(ConduitRefinedStorageNode.ID)) {
manager.setNode(pos, node = new ConduitRefinedStorageNode(this));
manager.markForSaving();
}
return (ConduitRefinedStorageNode) node;
}
@Override
public void onAfterRemovedFromBundle() {
super.onAfterRemovedFromBundle();
BlockPos pos = getBundle().getLocation();
INetworkNodeManager manager = RSHelper.API.getNetworkNodeManager(getBundle().getBundleworld());
INetworkNode node = manager.getNode(pos);
manager.removeNode(pos);
manager.markForSaving();
if (node != null && node.getNetwork() != null) {
node.getNetwork().getNodeGraph().rebuild();
}
}
@Override
public boolean onBlockActivated(@Nonnull EntityPlayer player, @Nonnull EnumHand hand, @Nonnull RaytraceResult res, @Nonnull List<RaytraceResult> all) {
if (ToolUtil.isToolEquipped(player, hand)) {
if (!getBundle().getEntity().getWorld().isRemote) {
final CollidableComponent component = res.component;
if (component != null) {
EnumFacing faceHit = res.movingObjectPosition.sideHit;
if (component.isCore()) {
if (getConnectionMode(faceHit) == ConnectionMode.DISABLED) {
setConnectionMode(faceHit, ConnectionMode.IN_OUT);
return true;
}
return ConduitUtil.connectConduits(this, faceHit);
} else {
EnumFacing connDir = component.getDirection();
if (externalConnections.contains(connDir)) {
setConnectionMode(connDir, getNextConnectionMode(connDir));
} else if (containsConduitConnection(connDir)) {
ConduitUtil.disconnectConduits(this, connDir);
}
}
}
}
return true;
}
return false;
}
@Override
public void onAddedToBundle() {
super.onAddedToBundle();
World world = getBundle().getBundleworld();
if (!world.isRemote) {
RSHelper.API.discoverNode(world, getBundle().getLocation());
}
}
@Override
public void setConnectionMode(@Nonnull EnumFacing dir, @Nonnull ConnectionMode mode) {
super.setConnectionMode(dir, mode);
getNode().onConduitConnectionChange();
}
@Override
public @Nonnull ConnectionMode getNextConnectionMode(@Nonnull EnumFacing dir) {
ConnectionMode mode = getConnectionMode(dir);
mode = mode == ConnectionMode.IN_OUT ? ConnectionMode.DISABLED : ConnectionMode.IN_OUT;
return mode;
}
@Override
public void writeToNBT(@Nonnull NBTTagCompound nbtRoot) {
super.writeToNBT(nbtRoot);
for (Entry<EnumFacing, ItemStack> entry : upgrades.entrySet()) {
if (entry.getValue() != null) {
ItemStack up = entry.getValue();
NBTTagCompound itemRoot = new NBTTagCompound();
up.writeToNBT(itemRoot);
nbtRoot.setTag("upgrades." + entry.getKey().name(), itemRoot);
}
}
for (Entry<EnumFacing, IFilter> entry : inputFilters.entrySet()) {
if (entry.getValue() != null) {
IFilter f = entry.getValue();
if (!isDefault(f)) {
NBTTagCompound itemRoot = new NBTTagCompound();
FilterRegistry.writeFilterToNbt(f, itemRoot);
nbtRoot.setTag("inFilts." + entry.getKey().name(), itemRoot);
}
}
}
for (Entry<EnumFacing, IFilter> entry : outputFilters.entrySet()) {
if (entry.getValue() != null) {
IFilter f = entry.getValue();
if (!isDefault(f)) {
NBTTagCompound itemRoot = new NBTTagCompound();
FilterRegistry.writeFilterToNbt(f, itemRoot);
nbtRoot.setTag("outFilts." + entry.getKey().name(), itemRoot);
}
}
}
for (Entry<EnumFacing, ItemStack> entry : inputFilterUpgrades.entrySet()) {
if (entry.getValue() != null) {
ItemStack up = entry.getValue();
IFilter filter = getInputFilter(entry.getKey());
FilterRegistry.writeFilterToStack(filter, up);
NBTTagCompound itemRoot = new NBTTagCompound();
up.writeToNBT(itemRoot);
nbtRoot.setTag("inputFilterUpgrades." + entry.getKey().name(), itemRoot);
}
}
for (Entry<EnumFacing, ItemStack> entry : outputFilterUpgrades.entrySet()) {
if (entry.getValue() != null) {
ItemStack up = entry.getValue();
IFilter filter = getOutputFilter(entry.getKey());
FilterRegistry.writeFilterToStack(filter, up);
NBTTagCompound itemRoot = new NBTTagCompound();
up.writeToNBT(itemRoot);
nbtRoot.setTag("outputFilterUpgrades." + entry.getKey().name(), itemRoot);
}
}
}
private boolean isDefault(IFilter f) {
if (f instanceof ItemFilter) {
return ((ItemFilter) f).isDefault();
}
return false;
}
@Override
public void readFromNBT(@Nonnull NBTTagCompound nbtRoot) {
super.readFromNBT(nbtRoot);
for (EnumFacing dir : EnumFacing.VALUES) {
String key = "upgrades." + dir.name();
if (nbtRoot.hasKey(key)) {
NBTTagCompound upTag = (NBTTagCompound) nbtRoot.getTag(key);
ItemStack ups = new ItemStack(upTag);
upgrades.put(dir, ups);
}
key = "inFilts." + dir.name();
if (nbtRoot.hasKey(key)) {
NBTTagCompound filterTag = (NBTTagCompound) nbtRoot.getTag(key);
IFilter filter = FilterRegistry.loadFilterFromNbt(filterTag);
inputFilters.put(dir, filter);
}
key = "inputFilterUpgrades." + dir.name();
if (nbtRoot.hasKey(key)) {
NBTTagCompound upTag = (NBTTagCompound) nbtRoot.getTag(key);
ItemStack ups = new ItemStack(upTag);
inputFilterUpgrades.put(dir, ups);
}
key = "outputFilterUpgrades." + dir.name();
if (nbtRoot.hasKey(key)) {
NBTTagCompound upTag = (NBTTagCompound) nbtRoot.getTag(key);
ItemStack ups = new ItemStack(upTag);
outputFilterUpgrades.put(dir, ups);
}
key = "outFilts." + dir.name();
if (nbtRoot.hasKey(key)) {
NBTTagCompound filterTag = (NBTTagCompound) nbtRoot.getTag(key);
IFilter filter = FilterRegistry.loadFilterFromNbt(filterTag);
outputFilters.put(dir, filter);
}
}
}
// ---------------------------------------------------------
// TEXTURES
// ---------------------------------------------------------
@Override
@Nonnull
public IConduitTexture getTextureForState(@Nonnull CollidableComponent component) {
if (component.isCore()) {
return ICONS.get(ICON_CORE_KEY);
}
return ICONS.get(ICON_KEY);
}
@Override
public IConduitTexture getTransmitionTextureForState(@Nonnull CollidableComponent component) {
return null;
}
@Override
@SideOnly(Side.CLIENT)
public Vector4f getTransmitionTextureColorForState(@Nonnull CollidableComponent component) {
return null;
}
// Upgrade Capability
@Nonnull
@Override
public ItemStack getUpgradeStack(int param1) {
return upgrades.get(EnumFacing.getFront(param1));
}
@Override
public void setUpgradeStack(int param1, @Nonnull ItemStack stack) {
upgrades.put(EnumFacing.getFront(param1), stack);
}
// Filter Capability
@Override
public IFilter getFilter(int filterId, int param1) {
if (filterId == getInputFilterIndex()) {
return getInputFilter(EnumFacing.getFront(param1));
} else if (filterId == getOutputFilterIndex()) {
return getOutputFilter(EnumFacing.getFront(param1));
}
return null;
}
@Override
public void setFilter(int filterId, EnumFacing side, @Nonnull IFilter filter) {
if (filterId == getInputFilterIndex()) {
setInputFilter(side, filter);
} else if (filterId == getOutputFilterIndex()) {
setOutputFilter(side, filter);
}
}
@Override
@Nonnull
public ItemStack getFilterStack(int filterIndex, EnumFacing side) {
if (filterIndex == getInputFilterIndex()) {
return getInputFilterUpgrade(side);
} else if (filterIndex == getOutputFilterIndex()) {
return getOutputFilterUpgrade(side);
}
return ItemStack.EMPTY;
}
@Override
public void setFilterStack(int filterIndex, EnumFacing side, @Nonnull ItemStack stack) {
if (filterIndex == getInputFilterIndex()) {
setInputFilterUpgrade(side, stack);
} else if (filterIndex == getOutputFilterIndex()) {
setOutputFilterUpgrade(side, stack);
}
}
@Override
public void setInputFilter(@Nonnull EnumFacing dir, @Nonnull IFilter filter) {
inputFilters.put(dir, filter);
setClientStateDirty();
}
@Override
public void setOutputFilter(@Nonnull EnumFacing dir, @Nonnull IFilter filter) {
outputFilters.put(dir, filter);
setClientStateDirty();
}
@Override
public IFilter getInputFilter(@Nonnull EnumFacing dir) {
return inputFilters.get(dir);
}
@Override
public IFilter getOutputFilter(@Nonnull EnumFacing dir) {
return outputFilters.get(dir);
}
@Override
public void setInputFilterUpgrade(@Nonnull EnumFacing dir, @Nonnull ItemStack stack) {
inputFilterUpgrades.put(dir, stack);
setInputFilter(dir, FilterRegistry.<IItemFilter> getFilterForUpgrade(stack));
setClientStateDirty();
}
@Override
public void setOutputFilterUpgrade(@Nonnull EnumFacing dir, @Nonnull ItemStack stack) {
outputFilterUpgrades.put(dir, stack);
setOutputFilter(dir, FilterRegistry.<IItemFilter> getFilterForUpgrade(stack));
setClientStateDirty();
}
@Override
@Nonnull
public ItemStack getInputFilterUpgrade(@Nonnull EnumFacing dir) {
return inputFilterUpgrades.get(dir);
}
@Override
@Nonnull
public ItemStack getOutputFilterUpgrade(@Nonnull EnumFacing dir) {
return outputFilterUpgrades.get(dir);
}
@Override
public int getInputFilterIndex() {
return INDEX_INPUT_REFINED_STORAGE;
}
@Override
public int getOutputFilterIndex() {
return INDEX_OUTPUT_REFINED_STROAGE;
}
@Override
public boolean isFilterUpgradeAccepted(@Nonnull ItemStack stack, boolean isInput) {
return stack.getItem() instanceof IItemFilterFluidUpgrade || stack.getItem() instanceof ItemBasicItemFilter;
}
}
| unlicense |
Almaz-KG/Hermes | hermes-core/src/main/java/org/hermes/core/utils/CSVReader.java | 4758 | package org.hermes.core.utils;
import org.hermes.core.entities.QuoteHistory;
import org.hermes.core.entities.constants.Quote;
import org.hermes.core.entities.price.Bar;
import org.hermes.core.entities.price.TimeFrame;
import org.hermes.core.exceptions.QuoteException;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class CSVReader {
private static final char DELIMITER = ',';
private static final String DATE_FORMAT_TEMPLATE = "yyyy.MM.dd HH:mm";
private static final DateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat(DATE_FORMAT_TEMPLATE);
/***
* The simple csv file parser. We have assumption about csv column structure.
*
* Expected column descriptions
* COLUMN_0 = DATE in format (yyyy.MM.dd)
* COLUMN_1 = HOUR in format (hh:mm)
* COLUMN_2 = OPEN PRICE (the DELIMITER of price is ('.'))
* COLUMN_3 = HIGH PRICE (the DELIMITER of price is ('.'))
* COLUMN_4 = LOW PRICE (the DELIMITER of price is ('.'))
* COLUMN_5 = CLOSE PRICE (the DELIMITER of price is ('.'))
* COLUMN_6 = VALUE
*/
public static QuoteHistory read(File file, Quote quote, TimeFrame timeFrame) throws IOException, ParseException, QuoteException {
List<String> allLines = Files.readAllLines(file.toPath(), Charset.defaultCharset());
QuoteHistory result = new QuoteHistory(quote, timeFrame);
for (String line : allLines) {
String[] args = line.split(String.valueOf(DELIMITER));
// Skip empty lines
if(args.length == 1 && args[0].isEmpty())
continue;
if(args.length != 7)
throw new ParseException("Illegal type of input line", 0);
Date stockBarDate = getStockBarDate(args[0], args[1]);
BigDecimal openPrice = BigDecimal.valueOf(Double.parseDouble(args[2]));
BigDecimal maxPrice = BigDecimal.valueOf(Double.parseDouble(args[3]));
BigDecimal minPrice = BigDecimal.valueOf(Double.parseDouble(args[4]));
BigDecimal closePrice = BigDecimal.valueOf(Double.parseDouble(args[5]));
BigDecimal value = BigDecimal.valueOf(Double.parseDouble(args[6]));
result.getHistory().add(new Bar(stockBarDate, openPrice, maxPrice, minPrice, closePrice, value));
}
return result;
}
public static List<QuoteHistory> load(File directory) throws IOException, ParseException, QuoteException {
if(directory.isDirectory()){
File[] files = directory.listFiles();
List<QuoteHistory> histories = new ArrayList<>();
for (File file: files){
if(file.isFile()){
Quote name = getQuoteName(file.getName());
TimeFrame timeFrame = getTimeFrame(file.getName());
QuoteHistory history = read(file, name, timeFrame);
if(history != null)
histories.add(history);
}
}
return histories;
}
return null;
}
private static Quote getQuoteName(String fileName) throws QuoteException {
if(fileName.endsWith(".csv")){
int index = 0;
if(fileName.startsWith("#"))
index = 1;
int last = fileName.indexOf(".csv");
return Quote.getQuoteByTicker(fileName.substring(index, last));
}
throw new QuoteException("Quote not found for file name, " +fileName);
}
private static TimeFrame getTimeFrame(String fileName) {
if(fileName.endsWith(".csv")){
String reverse = new StringBuilder(fileName).reverse().toString();
int start = reverse.indexOf(".");
int end = start;
char[] chars = reverse.toCharArray();
for (int i = start + 1; i < chars.length; i++) {
if(Character.isDigit(chars[i]))
end++;
else
break;
}
if(end > start){
String minutes = reverse.substring(start + 1, end + 1);
String minute = new StringBuilder(minutes).reverse().toString();
int i = Integer.parseInt(minute);
return TimeFrame.getTimeFrame(i);
}
}
return null;
}
private static Date getStockBarDate(String date, String time) throws ParseException {
return DEFAULT_DATE_FORMAT.parse(date + " " + time);
}
}
| unlicense |
dmytro-bilokha/OCEJPAD-preparation | exceptionexplorer/src/main/java/bilokhado/exceptionexplorer/exception/AppExceptionRollback.java | 230 | package bilokhado.exceptionexplorer.exception;
import javax.ejb.ApplicationException;
/**
* Application exception with rollback
*/
@ApplicationException(rollback = true)
public class AppExceptionRollback extends Exception {
}
| unlicense |
cc14514/hq6 | hq-server/src/main/java/org/hyperic/hq/scheduler/Scheduler.java | 19355 | /**
* 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.scheduler;
import org.quartz.Trigger;
public interface Scheduler {
/**
* Delegates to the Scheduler Service MBean.
* @see SchedulerServiceMBean#getQuartzProperties()
*/
public java.util.Properties getQuartzProperties( ) ;
/**
* Delegates to the Scheduler Service MBean in order to set the properties for Quartz and reinitialize th Quartz scheduler factory.
* @see SchedulerServiceMBean#setQuartzProperties(Properties)
*/
public void setQuartzProperties( java.util.Properties quartzProps ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getSchedulerName()
*/
public java.lang.String getSchedulerName( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getSchedulerInstanceId()
*/
public java.lang.String getSchedulerInstanceId( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getContext()
*/
public org.quartz.SchedulerContext getContext( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getMetaData()
*/
public org.quartz.SchedulerMetaData getMetaData( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#start()
*/
public void start( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#startScheduler()
*/
public void startScheduler( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#pause()
* @deprecated
*/
public void pause( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#isPaused()
* @deprecated
*/
public boolean isPaused( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#shutdown()
*/
public void shutdown( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#shutdown(boolean)
*/
public void shutdown( boolean waitForJobsToComplete ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#isShutdown()
*/
public boolean isShutdown( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getCurrentlyExecutingJobs()
*/
public java.util.List getCurrentlyExecutingJobs( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#scheduleJob(org.quartz.JobDetail,org.quartz.Trigger)
*/
public java.util.Date scheduleJob( org.quartz.JobDetail jobDetail,org.quartz.Trigger trigger ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#scheduleJob(org.quartz.Trigger)
*/
public java.util.Date scheduleJob( org.quartz.Trigger trigger ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#addJob(org.quartz.JobDetail, boolean)
*/
public void addJob( org.quartz.JobDetail jobDetail,boolean replace ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#deleteJob(java.lang.String,java.lang.String)
*/
public boolean deleteJob( java.lang.String jobName,java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#unscheduleJob(java.lang.String,java.lang.String)
*/
public boolean unscheduleJob( java.lang.String triggerName,java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#triggerJob(java.lang.String,java.lang.String)
*/
public void triggerJob( java.lang.String jobName,java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#triggerJobWithVolatileTrigger(java.lang.String, java.lang.String)
*/
public void triggerJobWithVolatileTrigger( java.lang.String jobName,java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#pauseTrigger(java.lang.String,java.lang.String)
*/
public void pauseTrigger( java.lang.String triggerName,java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#pauseTriggerGroup(java.lang.String)
*/
public void pauseTriggerGroup( java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#pauseJob(java.lang.String, java.lang.String)
*/
public void pauseJob( java.lang.String jobName,java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#pauseJobGroup(java.lang.String)
*/
public void pauseJobGroup( java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#resumeTrigger(java.lang.String,java.lang.String)
*/
public void resumeTrigger( java.lang.String triggerName,java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#resumeTriggerGroup(java.lang.String)
*/
public void resumeTriggerGroup( java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#resumeJob(java.lang.String,java.lang.String)
*/
public void resumeJob( java.lang.String jobName,java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#resumeJobGroup(java.lang.String)
*/
public void resumeJobGroup( java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getJobGroupNames()
*/
public java.lang.String[] getJobGroupNames( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getJobNames(java.lang.String)
*/
public java.lang.String[] getJobNames( java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getTriggersOfJob(java.lang.String,java.lang.String)
*/
public org.quartz.Trigger[] getTriggersOfJob( java.lang.String jobName,java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getTriggerGroupNames()
*/
public java.lang.String[] getTriggerGroupNames( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getTriggerNames(java.lang.String)
*/
public java.lang.String[] getTriggerNames( java.lang.String groupName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getJobDetail(java.lang.String,java.lang.String)
*/
public org.quartz.JobDetail getJobDetail( java.lang.String jobName,java.lang.String jobGroup ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getTrigger(java.lang.String,java.lang.String)
*/
public org.quartz.Trigger getTrigger( java.lang.String triggerName,java.lang.String triggerGroup ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#deleteCalendar(java.lang.String)
*/
public boolean deleteCalendar( java.lang.String calName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getCalendar(java.lang.String)
*/
public org.quartz.Calendar getCalendar( java.lang.String calName ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getCalendarNames()
*/
public java.lang.String[] getCalendarNames( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#addGlobalJobListener(org.quartz.JobListener)
*/
public void addGlobalJobListener( org.quartz.JobListener jobListener ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#addJobListener(org.quartz.JobListener)
*/
public void addJobListener( org.quartz.JobListener jobListener ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#removeGlobalJobListener(org.quartz.JobListener)
*/
public boolean removeGlobalJobListener( org.quartz.JobListener jobListener ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#removeJobListener(java.lang.String)
*/
public boolean removeJobListener( java.lang.String name ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getGlobalJobListeners()
*/
public java.util.List getGlobalJobListeners( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getJobListenerNames()
*/
public java.util.Set getJobListenerNames( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getJobListener(java.lang.String)
*/
public org.quartz.JobListener getJobListener( java.lang.String name ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#addGlobalTriggerListener(org.quartz.TriggerListener)
*/
public void addGlobalTriggerListener( org.quartz.TriggerListener triggerListener ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#addTriggerListener(org.quartz.TriggerListener)
*/
public void addTriggerListener( org.quartz.TriggerListener triggerListener ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#removeGlobalTriggerListener(org.quartz.TriggerListener)
*/
public boolean removeGlobalTriggerListener( org.quartz.TriggerListener triggerListener ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#removeTriggerListener(java.lang.String)
*/
public boolean removeTriggerListener( java.lang.String name ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getGlobalTriggerListeners()
*/
public java.util.List getGlobalTriggerListeners( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getTriggerListenerNames()
*/
public java.util.Set getTriggerListenerNames( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getTriggerListener(java.lang.String)
*/
public org.quartz.TriggerListener getTriggerListener( java.lang.String name ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#addSchedulerListener(org.quartz.SchedulerListener)
*/
public void addSchedulerListener( org.quartz.SchedulerListener schedulerListener ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#removeSchedulerListener(org.quartz.SchedulerListener)
*/
public boolean removeSchedulerListener( org.quartz.SchedulerListener schedulerListener ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.hyperic.hq.scheduler.server.mbean.SchedulerServiceMBean#getSchedulerListeners()
*/
public java.util.List getSchedulerListeners( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.quartz.Scheduler#addCalendar(java.lang.String, org.quartz.Calendar, boolean, boolean)
*/
public void addCalendar( java.lang.String calName,org.quartz.Calendar calendar,boolean replace,boolean updateTriggers ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.quartz.Scheduler#getPausedTriggerGroups()
*/
public java.util.Set getPausedTriggerGroups( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.quartz.Scheduler#getTriggerState(java.lang.String, java.lang.String)
*/
public int getTriggerState( java.lang.String triggerName,java.lang.String triggerGroup ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.quartz.Scheduler#interrupt(java.lang.String, java.lang.String)
*/
public boolean interrupt( java.lang.String jobName,java.lang.String groupName ) throws org.quartz.UnableToInterruptJobException;
/**
* Delegates to the Quartz scheduler.
* @see org.quartz.Scheduler#isInStandbyMode()
*/
public boolean isInStandbyMode( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.quartz.Scheduler#pauseAll()
*/
public void pauseAll( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.quartz.Scheduler#rescheduleJob(java.lang.String, java.lang.String, org.quartz.Trigger)
*/
public java.util.Date rescheduleJob( java.lang.String triggerName,java.lang.String groupName,org.quartz.Trigger newTrigger ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.quartz.Scheduler#resumeAll()
*/
public void resumeAll( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.quartz.Scheduler#setJobFactory(org.quartz.spi.JobFactory)
*/
public void setJobFactory( org.quartz.spi.JobFactory factory ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.quartz.Scheduler#standby()
*/
public void standby( ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.quartz.Scheduler#triggerJob(java.lang.String, java.lang.String, org.quartz.JobDataMap)
*/
public void triggerJob( java.lang.String jobName,java.lang.String groupName,org.quartz.JobDataMap data ) throws org.quartz.SchedulerException;
/**
* Delegates to the Quartz scheduler.
* @see org.quartz.Scheduler#triggerJobWithVolatileTrigger(String, String, org.quartz.JobDataMap)
*/
public void triggerJobWithVolatileTrigger( java.lang.String jobName,java.lang.String groupName,org.quartz.JobDataMap data ) throws org.quartz.SchedulerException;
}
| unlicense |
bodydomelight/tij-problems | src/test/References.java | 2012 | package test;
import java.lang.ref.*;
import java.util.*;
class VeryBig {
private static final int SIZE = 10000;
private long[] la = new long[SIZE];
private String ident;
public VeryBig(String id) {
ident = id;
}
@Override
public String toString() {
return ident;
}
@Override
protected void finalize() {
System.out.println("Finalizing " + ident);
}
}
public class References {
private static ReferenceQueue<VeryBig> rq = new ReferenceQueue<>();
public static void checkQueue() {
Reference<? extends VeryBig> inq = rq.poll();
if (inq != null) {
System.out.println("In queue: " + inq.get());
}
}
public static void main(String[] args) {
int size = 10;
// Or, choose size via the command line:
if (args.length > 0) {
size = new Integer(args[0]);
}
LinkedList<SoftReference<VeryBig>> sa = new LinkedList<>();
for (int i = 0; i < size; i++) {
sa.add(new SoftReference<>(new VeryBig("Soft " + i), rq));
System.out.println("Just created: " + sa.getLast());
checkQueue();
}
LinkedList<WeakReference<VeryBig>> wa = new LinkedList<>();
for (int i = 0; i < size; i++) {
wa.add(new WeakReference<>(new VeryBig("Weak " + i), rq));
System.out.println("Just created: " + wa.getLast());
checkQueue();
}
SoftReference<VeryBig> s = new SoftReference<>(new VeryBig("Soft"));
WeakReference<VeryBig> w = new WeakReference<>(new VeryBig("Weak"));
System.gc();
LinkedList<PhantomReference<VeryBig>> pa = new LinkedList<>();
for (int i = 0; i < size; i++) {
pa.add(new PhantomReference<>(new VeryBig("Phantom " + i), rq));
System.out.println("Just created: " + pa.getLast());
checkQueue();
}
}
}
| unlicense |
fuzzyBSc/systemdesign | Application/src/main/java/au/id/soundadvice/systemdesign/storage/files/SaveTransaction.java | 3725 | /*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org/>
*/
package au.id.soundadvice.systemdesign.storage.files;
import au.id.soundadvice.systemdesign.storage.versioning.VersionControl;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.nio.file.StandardCopyOption.ATOMIC_MOVE;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import java.util.ArrayList;
import java.util.List;
/**
* A crude two-phase commit. It doesn't guarantee atomicity but will generally
* achieve it. Importantly failure to write out some files will cause the entire
* set to be left uncommitted avoiding inconsistency in the general case. Use in
* conjunction with a configuration management system to ensure that write
* contention is negligible.
*
* @author Benjamin Carlyle <benjamincarlyle@soundadvice.id.au>
*/
public class SaveTransaction implements Closeable {
public SaveTransaction(VersionControl versionControl) {
this.versionControl = versionControl;
}
private static final class Job {
public Job(Path realFile, Path tempFile) {
this.realFile = realFile;
this.tempFile = tempFile;
}
private final Path realFile;
private final Path tempFile;
}
private final List<Job> mustLockJobs = new ArrayList<>();
private final VersionControl versionControl;
public synchronized void addJob(Path realFile, Path tempFile) {
mustLockJobs.add(new Job(realFile, tempFile));
}
public synchronized void commit() throws IOException {
List<Path> changed = new ArrayList<>();
for (Job job : mustLockJobs) {
if (Files.exists(job.tempFile)) {
if (FileUtils.contentEquals(job.tempFile, job.realFile)) {
// Don't overwrite if identical. Delete temp file in close.
} else {
Files.move(job.tempFile, job.realFile, REPLACE_EXISTING, ATOMIC_MOVE);
changed.add(job.realFile);
}
} else {
Files.deleteIfExists(job.realFile);
changed.add(job.realFile);
}
}
for (Path path : changed) {
versionControl.changed(path);
}
}
@Override
public synchronized void close() throws IOException {
for (Job job : mustLockJobs) {
Files.deleteIfExists(job.tempFile);
}
}
}
| unlicense |
JamesaFlanagan/2014Jan-Respawn | Entities/Jan2014-Respawn-Entities/src/com/me/Systems/Input/ScalingInputMapperVerticalFlip.java | 548 | package com.me.Systems.Input;
import com.me.ScreenView;
public class ScalingInputMapperVerticalFlip implements IInputMapper {
private int _originalX;
private int _originalY;
public ScalingInputMapperVerticalFlip(int originalX, int originalY)
{
_originalX = originalX;
_originalY = originalY;
}
@Override
public int MapX(int X) {
return (int) (X * (ScreenView.Width / (float) _originalX));
}
@Override
public int MapY(int Y) {
return ScreenView.Height - (int) (Y * ( ScreenView.Height / (float) _originalY));
}
}
| unlicense |
rongshang/fbi-cbs2 | common/main/java/skyline/repository/dao/PtroleMapper.java | 2922 | package skyline.repository.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import skyline.repository.model.Ptrole;
import skyline.repository.model.PtroleExample;
public interface PtroleMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table PTROLE
*
* @mbggenerated Tue Jan 12 13:50:41 AWST 2016
*/
int countByExample(PtroleExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table PTROLE
*
* @mbggenerated Tue Jan 12 13:50:41 AWST 2016
*/
int deleteByExample(PtroleExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table PTROLE
*
* @mbggenerated Tue Jan 12 13:50:41 AWST 2016
*/
int deleteByPrimaryKey(String roleid);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table PTROLE
*
* @mbggenerated Tue Jan 12 13:50:41 AWST 2016
*/
int insert(Ptrole record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table PTROLE
*
* @mbggenerated Tue Jan 12 13:50:41 AWST 2016
*/
int insertSelective(Ptrole record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table PTROLE
*
* @mbggenerated Tue Jan 12 13:50:41 AWST 2016
*/
List<Ptrole> selectByExample(PtroleExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table PTROLE
*
* @mbggenerated Tue Jan 12 13:50:41 AWST 2016
*/
Ptrole selectByPrimaryKey(String roleid);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table PTROLE
*
* @mbggenerated Tue Jan 12 13:50:41 AWST 2016
*/
int updateByExampleSelective(@Param("record") Ptrole record, @Param("example") PtroleExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table PTROLE
*
* @mbggenerated Tue Jan 12 13:50:41 AWST 2016
*/
int updateByExample(@Param("record") Ptrole record, @Param("example") PtroleExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table PTROLE
*
* @mbggenerated Tue Jan 12 13:50:41 AWST 2016
*/
int updateByPrimaryKeySelective(Ptrole record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table PTROLE
*
* @mbggenerated Tue Jan 12 13:50:41 AWST 2016
*/
int updateByPrimaryKey(Ptrole record);
} | unlicense |
cvanderkolk/gigtrakr | src/main/java/com/gigtrakr/GigtrakrApp.java | 3531 | package com.gigtrakr;
import com.gigtrakr.config.DefaultProfileUtil;
import io.github.jhipster.config.JHipsterConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.*;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
@ComponentScan
@EnableOAuth2Client
@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})
@EnableConfigurationProperties(LiquibaseProperties.class)
public class GigtrakrApp {
private static final Logger log = LoggerFactory.getLogger(GigtrakrApp.class);
private final Environment env;
public GigtrakrApp(Environment env) {
this.env = env;
}
/**
* Initializes gigtrakr.
* <p>
* Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile
* <p>
* You can find more information on how profiles work with JHipster on <a href="http://jhipster.github.io/profiles/">http://jhipster.github.io/profiles/</a>.
*/
@PostConstruct
public void initApplication() {
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
log.error("You have misconfigured your application! It should not run " +
"with both the 'dev' and 'prod' profiles at the same time.");
}
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) {
log.error("You have misconfigured your application! It should not" +
"run with both the 'dev' and 'cloud' profiles at the same time.");
}
}
/**
* Main method, used to run the application.
*
* @param args the command line arguments
* @throws UnknownHostException if the local host name could not be resolved into an address
*/
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(GigtrakrApp.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
log.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\thttp://localhost:{}\n\t" +
"External: \thttp://{}:{}\n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"),
env.getActiveProfiles());
}
}
| unlicense |
Arquisoft/censusesI2 | src/test/java/es/uniovi/asw/ReadFileTest.java | 2459 | package es.uniovi.asw;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
import es.uniovi.parser.ReadCsv;
import es.uniovi.parser.ReadXlsx;
import es.uniovi.parser.Voter;
import es.uniovi.parser.VoterFileReader;
import org.junit.Assert;
public class ReadFileTest {
private VoterFileReader readerExcel = new ReadXlsx();
private VoterFileReader readerCSV = new ReadCsv();
List<Voter> testList;
@Test
public void testReadExcel() {
try {
testList=readerExcel.read("src/test/resources/test.xlsx");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Assert.assertEquals("Juan Torres Pardo", testList.get(0).getName());
Assert.assertEquals("90500084Y", testList.get(0).getNif());
Assert.assertEquals("juantorres@yahoo.com", testList.get(0).getEmail());
Assert.assertEquals(234, testList.get(0).getPollStCode());
Assert.assertEquals("Luis López Fernando", testList.get(1).getName());
Assert.assertEquals("19160962F", testList.get(1).getNif());
Assert.assertEquals("luislopez@gmail.com", testList.get(1).getEmail());
Assert.assertEquals(345, testList.get(1).getPollStCode());
Assert.assertEquals("Ana Torres Pardo", testList.get(2).getName());
Assert.assertEquals("09940449X", testList.get(2).getNif());
Assert.assertEquals("anatorres@hotmail.com", testList.get(2).getEmail());
Assert.assertEquals(234, testList.get(2).getPollStCode());
}
@Test
public void testReadCSV() {
try {
testList=readerCSV.read("src/test/resources/test.csv");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Assert.assertEquals("Juan Torres Pardo", testList.get(0).getName());
Assert.assertEquals("90500084Y", testList.get(0).getNif());
Assert.assertEquals("juantorres@yahoo.com", testList.get(0).getEmail());
Assert.assertEquals(234, testList.get(0).getPollStCode());
Assert.assertEquals("Luis López Fernando", testList.get(1).getName());
Assert.assertEquals("19160962F", testList.get(1).getNif());
Assert.assertEquals("luislopez@gmail.com", testList.get(1).getEmail());
Assert.assertEquals(345, testList.get(1).getPollStCode());
Assert.assertEquals("Ana Torres Pardo", testList.get(2).getName());
Assert.assertEquals("09940449X", testList.get(2).getNif());
Assert.assertEquals("anatorres@hotmail.com", testList.get(2).getEmail());
Assert.assertEquals(234, testList.get(2).getPollStCode());
}
}
| unlicense |
bpmericle/gluecon2017-spring-boot | src/main/java/com/wistful/widgets/api/services/CreateService.java | 476 | package com.wistful.widgets.api.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wistful.widgets.api.data.WidgetRepository;
import com.wistful.widgets.api.models.Widget;
@Service
public class CreateService {
@Autowired
private WidgetRepository repository;
/**
*
* @param widget
* @return
*/
public String create(Widget widget) {
return repository.save(widget).getId();
}
}
| unlicense |
yelelen/sfish | app/src/main/java/com/yelelen/sfish/parser/JsonParser.java | 198 | package com.yelelen.sfish.parser;
import java.util.List;
/**
* Created by yelelen on 17-9-14.
*/
public interface JsonParser<T> {
List<T> parse(String json);
T parseOne(String json);
}
| apache-2.0 |
termsuite/termsuite-core | src/main/java/fr/univnantes/termsuite/engines/splitter/MorphologicalOptions.java | 3973 | package fr.univnantes.termsuite.engines.splitter;
import com.fasterxml.jackson.annotation.JsonProperty;
import fr.univnantes.termsuite.utils.JsonConfigObject;
public class MorphologicalOptions extends JsonConfigObject {
private boolean enabled = true;
@JsonProperty("prefix-splitter-enabled")
private boolean prefixSplitterEnabled = true;
@JsonProperty("derivatives-detector-enabled")
private boolean derivativesDetecterEnabled = true;
@JsonProperty("native-splitter-enabled")
private boolean nativeSplittingEnabled = true;
@JsonProperty("min-component-size")
private int minComponentSize;
@JsonProperty("max-component-num")
private int maxNumberOfComponents;
private double alpha;
private double beta;
private double gamma;
private double delta;
@JsonProperty("score-th")
private double scoreThreshold;
@JsonProperty("segment-similarity-th")
private double segmentSimilarityThreshold;
@Override
public boolean equals(Object obj) {
if(obj instanceof MorphologicalOptions) {
MorphologicalOptions o = (MorphologicalOptions)obj;
return enabled == o.enabled
&& prefixSplitterEnabled == o.prefixSplitterEnabled
&& derivativesDetecterEnabled == o.derivativesDetecterEnabled
&& nativeSplittingEnabled == o.nativeSplittingEnabled
&& minComponentSize == o.minComponentSize
&& maxNumberOfComponents == o.maxNumberOfComponents
&& alpha == o.alpha
&& beta == o.beta
&& gamma == o.gamma
&& delta == o.delta
&& scoreThreshold == o.scoreThreshold
&& segmentSimilarityThreshold == o.segmentSimilarityThreshold
;
} else return false;
}
public double getAlpha() {
return alpha;
}
public double getBeta() {
return beta;
}
public double getGamma() {
return gamma;
}
public double getDelta() {
return delta;
}
public int getMinComponentSize() {
return minComponentSize;
}
public int getMaxNumberOfComponents() {
return maxNumberOfComponents;
}
public double getScoreThreshold() {
return scoreThreshold;
}
public double getSegmentSimilarityThreshold() {
return segmentSimilarityThreshold;
}
public MorphologicalOptions setAlpha(double alpha) {
this.alpha = alpha;
return this;
}
public MorphologicalOptions setBeta(double beta) {
this.beta = beta;
return this;
}
public MorphologicalOptions setGamma(double gamma) {
this.gamma = gamma;
return this;
}
public MorphologicalOptions setDelta(double delta) {
this.delta = delta;
return this;
}
public MorphologicalOptions setMinComponentSize(int minComponentSize) {
this.minComponentSize = minComponentSize;
return this;
}
public MorphologicalOptions setMaxNumberOfComponents(int maxNumberOfComponents) {
this.maxNumberOfComponents = maxNumberOfComponents;
return this;
}
public MorphologicalOptions setScoreThreshold(double scoreThreshold) {
this.scoreThreshold = scoreThreshold;
return this;
}
public MorphologicalOptions setSegmentSimilarityThreshold(double segmentSimilarityThreshold) {
this.segmentSimilarityThreshold = segmentSimilarityThreshold;
return this;
}
public boolean isPrefixSplitterEnabled() {
return prefixSplitterEnabled;
}
public MorphologicalOptions setPrefixSplitterEnabled(boolean prefixSplitterEnabled) {
this.prefixSplitterEnabled = prefixSplitterEnabled;
return this;
}
public void setDerivativesDetecterEnabled(boolean derivativesDetecterEnabled) {
this.derivativesDetecterEnabled = derivativesDetecterEnabled;
}
public boolean isDerivativesDetecterEnabled() {
return derivativesDetecterEnabled;
}
public MorphologicalOptions setNativeSplittingEnabled(boolean nativeSplittingEnabled) {
this.nativeSplittingEnabled = nativeSplittingEnabled;
return this;
}
public boolean isNativeSplittingEnabled() {
return this.nativeSplittingEnabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isEnabled() {
return enabled;
}
}
| apache-2.0 |
opensingular/singular-server | requirement/requirement-module/src/main/java/org/opensingular/requirement/module/spring/security/SecurityAuthPaths.java | 2427 | /*
* Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensingular.requirement.module.spring.security;
import java.io.Serializable;
import java.util.Optional;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.cycle.RequestCycle;
import org.opensingular.requirement.module.util.url.UrlToolkit;
import org.opensingular.requirement.module.util.url.UrlToolkitBuilder;
public class SecurityAuthPaths implements Serializable {
private final String urlPath;
private final String contextPath;
private final UrlToolkitBuilder urlToolkitBuilder;
public SecurityAuthPaths(String contextPath, String urlPath,UrlToolkitBuilder urlToolkitBuilder) {
this.urlPath = urlPath;
this.contextPath = contextPath;
this.urlToolkitBuilder = urlToolkitBuilder;
}
public String getLoginPath() {
return contextPath + urlPath + "/login";
}
public String getLogoutPath(RequestCycle requestCycle) {
String baseUrl = contextPath + urlPath + "/logout";
if (requestCycle != null) {
baseUrl = mountLogoutPathWithRequectCycle(requestCycle, baseUrl);
}
return baseUrl;
}
private String mountLogoutPathWithRequectCycle(RequestCycle requestCycle, String baseUrl) {
Request request = requestCycle.getRequest();
Url url = request.getUrl();
UrlToolkit urlToolkit = urlToolkitBuilder.build(url);
Optional<String> filterPath = Optional.ofNullable(request.getFilterPath());
String logoutPath = urlToolkit.concatServerAdressWithContext(baseUrl);
logoutPath += "?service=" + urlToolkit.concatServerAdressWithContext(contextPath + filterPath.orElse(""));
return logoutPath;
}
} | apache-2.0 |
clive-jevons/joynr | java/javaapi/src/main/java/io/joynr/exceptions/SubscriptionException.java | 2056 | package io.joynr.exceptions;
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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%
*/
import com.fasterxml.jackson.annotation.JsonProperty;
public class SubscriptionException extends JoynrRuntimeException {
private static final long serialVersionUID = 1L;
@JsonProperty("subscriptionId")
private final String subscriptionId;
public String getSubscriptionId() {
return this.subscriptionId;
}
public SubscriptionException(String subscriptionId) {
this(subscriptionId, "SubscriptionId = " + subscriptionId);
}
public SubscriptionException(String subscriptionId, String errorMsg) {
super(errorMsg);
this.subscriptionId = subscriptionId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((subscriptionId == null) ? 0 : subscriptionId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
SubscriptionException other = (SubscriptionException) obj;
if (subscriptionId == null) {
if (other.subscriptionId != null)
return false;
} else if (!subscriptionId.equals(other.subscriptionId))
return false;
return true;
}
}
| apache-2.0 |
hotpads/datarouter | datarouter-aws-sqs/src/main/java/io/datarouter/aws/sqs/config/DatarouterSqsRouteSet.java | 1582 | /*
* Copyright © 2009 HotPads (admin@hotpads.com)
*
* 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.datarouter.aws.sqs.config;
import javax.inject.Inject;
import javax.inject.Singleton;
import io.datarouter.aws.sqs.web.handler.SqsUpdateQueueHandler;
import io.datarouter.storage.tag.Tag;
import io.datarouter.web.dispatcher.BaseRouteSet;
import io.datarouter.web.dispatcher.DispatchRule;
import io.datarouter.web.user.role.DatarouterUserRole;
@Singleton
public class DatarouterSqsRouteSet extends BaseRouteSet{
@Inject
public DatarouterSqsRouteSet(DatarouterSqsPaths paths){
super(paths.datarouter.sqs);
handle(paths.datarouter.sqs.deleteQueue).withHandler(SqsUpdateQueueHandler.class);
handle(paths.datarouter.sqs.deleteAllUnreferencedQueues).withHandler(SqsUpdateQueueHandler.class);
handle(paths.datarouter.sqs.purgeQueue).withHandler(SqsUpdateQueueHandler.class);
}
@Override
protected DispatchRule applyDefault(DispatchRule rule){
return rule
.allowRoles(DatarouterUserRole.DATAROUTER_ADMIN)
.withTag(Tag.DATAROUTER);
}
}
| apache-2.0 |
tanliu/SSHBBS | SHBBS/src/com/bbs/dao/BaseDaoImpl.java | 2939 | /**
*
*/
package com.bbs.dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.bbs.utils.HibernateUtils;
import com.bbs.utils.PageUtils;
import com.bbs.utils.QueryUtils;
import com.bbs.utils.TUtils;
/**
* ÏîÄ¿Ãû³Æ£ºElectricity
* ÀàÃû³Æ£ºBaseDaoImpl
* ÀàÃèÊö£º Dao²ã»ù±¾Êý¾ÝµÄ·â×°
* ´´½¨ÈË£ºÌ³×Ó
* ´´½¨Ê±¼ä£º2016Äê4ÔÂ6ÈÕ ÏÂÎç2:55:13
* ÐÞ¸ÄÈË£ºTanLiu
* ÐÞ¸Äʱ¼ä£º2016Äê4ÔÂ6ÈÕ ÏÂÎç2:55:13
* Ð޸ı¸×¢£º
* @version
*/
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {
Class entityClass;
@Resource(name="sessionFactory")
public void setDi(SessionFactory sessionFactory){
this.setSessionFactory(sessionFactory);
}
public BaseDaoImpl(){
ParameterizedType parameterizedType=(ParameterizedType) this.getClass().getGenericSuperclass();
entityClass=(Class) parameterizedType.getActualTypeArguments()[0];
}
@Override
public void save(T entity) {
getHibernateTemplate().save(entity);
}
@Override
public void update(T entity) {
getHibernateTemplate().update(entity);
}
@Override
public void deleteObjectByIds(Serializable... ids) {
if(ids!=null && ids.length>0){
for(Serializable id:ids){
//ÏȲéѯ
Object entity = this.findObjectByIds(id);
//ÔÙɾ³ý
this.getHibernateTemplate().delete(entity);
}
}
}
@Override
public T findObjectByIds(Serializable id) {
return (T) getHibernateTemplate().get(entityClass, id);
}
@Override
public PageUtils<T> getPageResult(QueryUtils queryUtils, int pageNO,
int pageSize) {
//Åжϲéѯ¹¤¾ßÊÇ·ñΪ¿Õ
if(queryUtils!=null){
//ÏÈͨ¹ýÓï¾ä²éѯһ¸ö¼¯ºÏ
Query query=getSession().createQuery(queryUtils.getQueryHql());
List<Object> parameters=queryUtils.getParams();
if(parameters!=null){
int i=0;
for (Object param :parameters) {
for(Object object:parameters){
query.setParameter(i++, object);
}
}
}
//ÉèÖ÷ÖÒ³
if(pageNO<1)pageNO=1;
query.setFirstResult((pageNO-1)*pageSize);
query.setMaxResults(pageSize);
//»ñÈ¡·ÖÒ³ºóµÄÊý¾Ý
List<T> items=query.list();
//»ñÈ¡×ܼǼÊý
Query countquery=getSession().createQuery(queryUtils.getQueryCountHql());
if(parameters!=null&¶meters.size()>0){
int i=0;
for(Object object:parameters){
countquery.setParameter(i++, object);
}
}
//»ñÈ¡×ÜÒ³Êý
long totalCount=(Long) countquery.uniqueResult();
//·µ»ØÒ»¸ö·Ö²¼¹¤¾ß
return new PageUtils(totalCount,pageNO, pageSize, items);
}
return null;
}
}
| apache-2.0 |
ow2-xlcloud/vcms | impl/src/main/java/org/xlcloud/service/manager/RepositoriesManagerImpl.java | 2116 | /*
* Copyright 2012 AMG.lab, a Bull Group Company
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.xlcloud.service.manager;
import java.util.ArrayList;
import java.util.List;
import org.xlcloud.service.CatalogScopeType;
import org.xlcloud.service.Repository;
import org.xlcloud.service.RepositoryStatus;
import org.xlcloud.service.RepositoryType;
import org.xlcloud.service.builders.RepositoryBuilder;
/**
* TODO [tadamcze] Documentation
*
* @author Tomek Adamczewski, AMG.net
*/
public class RepositoriesManagerImpl implements RepositoriesManager {
@Override
public Repository registerNewRepository(Repository repo) {
repo.setId(1l);
repo.setStatus(RepositoryStatus.QUEUED);
return repo;
}
@Override
public List<Repository> findByCatalogScope(CatalogScopeType catalogScope) {
List<Repository> repos = new ArrayList<>();
repos.add(RepositoryBuilder.newInstance().id(1l).status(RepositoryStatus.ACTIVE).type(RepositoryType.GIT)
.uri("http://fake.uri/xlcloud.git").catalogScope(catalogScope).build());
repos.add(RepositoryBuilder.newInstance().id(2l).status(RepositoryStatus.BROKEN).type(RepositoryType.SVN)
.uri("http://fake.uri/xlcloud.svn").catalogScope(catalogScope).build());
return repos;
}
@Override
public Repository get(long repoId) {
return RepositoryBuilder.newInstance().id(1l).status(RepositoryStatus.ACTIVE).type(RepositoryType.GIT)
.uri("http://fake.uri/xlcloud.git").catalogScope(CatalogScopeType.PUBLIC).build();
}
}
| apache-2.0 |
VHAINNOVATIONS/Telepathology | Source/Java/ImagingDicomUtilities/src/java/gov/va/med/imaging/dicom/utilities/exceptions/GenericDicomReconstitutionException.java | 2172 | /**
*
Package: MAG - VistA Imaging
WARNING: Per VHA Directive 2004-038, this routine should not be modified.
Date Created: September 19, 2005
Site Name: Washington OI Field Office, Silver Spring, MD
Developer: VHAISWPETERB
Description:
;; +--------------------------------------------------------------------+
;; Property of the US Government.
;; No permission to copy or redistribute this software is given.
;; Use of unreleased versions of this software requires the user
;; to execute a written test agreement with the VistA Imaging
;; Development Office of the Department of Veterans Affairs,
;; telephone (301) 734-0100.
;;
;; The Food and Drug Administration classifies this software as
;; a Class II medical device. As such, it may not be changed
;; in any way. Modifications to this software may result in an
;; adulterated medical device under 21CFR820, the use of which
;; is considered to be a violation of US Federal Statutes.
;; +--------------------------------------------------------------------+
*/
package gov.va.med.imaging.dicom.utilities.exceptions;
/**
*
* @author William Peterson
*
*/
public class GenericDicomReconstitutionException extends Exception {
/**
* Constructor
*
*
*/
public GenericDicomReconstitutionException() {
super();
// TODO Auto-generated constructor stub
}
/**
* Constructor
*
* @param message
*/
public GenericDicomReconstitutionException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
/**
* Constructor
*
* @param cause
*/
public GenericDicomReconstitutionException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
/**
* Constructor
*
* @param message
* @param cause
*/
public GenericDicomReconstitutionException(String message,
Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
}
| apache-2.0 |
Ariah-Group/Finance | af_webapp/src/main/java/org/kuali/kfs/module/external/kc/util/KcUtils.java | 1499 | /*
* Copyright 2011 The Kuali Foundation.
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.kfs.module.external.kc.util;
import java.text.MessageFormat;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.rice.core.api.config.property.ConfigurationService;
import org.kuali.rice.krad.util.ObjectUtils;
public class KcUtils {
/**
* Utility method to translate a property error to error string
*
* @param propertyKey
* @param messageParameters
* @return
*/
public static String getErrorMessage(String propertyKey, Object[] messageParameters){
// get error text
String errorText = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(propertyKey);
// apply parameters
if(ObjectUtils.isNotNull(messageParameters)){
errorText = MessageFormat.format(errorText, messageParameters);
}
return errorText;
}
}
| apache-2.0 |
luangm/jerry | src/main/java/io/luan/jerry/item/data/ItemDO.java | 1300 | package io.luan.jerry.item.data;
import io.luan.jerry.item.domain.Item;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class ItemDO {
private Long id;
private Long userId;
private String title;
private String imgUrl;
private Long price;
private Long categoryId;
private LocalDateTime gmtCreate;
private LocalDateTime gmtModified;
public static ItemDO fromEntity(Item item) {
var itemDO = new ItemDO();
itemDO.setId(item.getId());
itemDO.setUserId(item.getUserId());
itemDO.setTitle(item.getTitle());
itemDO.setImgUrl(item.getImgUrl());
itemDO.setPrice(item.getPrice());
itemDO.setCategoryId(item.getCategoryId());
itemDO.setGmtCreate(item.getGmtCreate());
itemDO.setGmtModified(item.getGmtModified());
return itemDO;
}
public Item toEntity() {
var item = new Item();
item.setId(this.getId());
item.setUserId(this.getUserId());
item.setTitle(this.getTitle());
item.setImgUrl(this.getImgUrl());
item.setPrice(this.getPrice());
item.setCategoryId(this.getCategoryId());
item.setGmtCreate(this.getGmtCreate());
item.setGmtModified(this.getGmtModified());
return item;
}
}
| apache-2.0 |
xbib/content | content-rdf/src/test/java/org/xbib/content/rdf/io/rdfxml/EuropeanaEDMReaderTest.java | 3254 | package org.xbib.content.rdf.io.rdfxml;
import static org.xbib.content.rdf.RdfContentFactory.ntripleBuilder;
import org.junit.jupiter.api.Test;
import org.xbib.content.rdf.RdfContent;
import org.xbib.content.rdf.RdfContentBuilder;
import org.xbib.content.rdf.Resource;
import org.xbib.content.rdf.Triple;
import org.xbib.content.rdf.internal.DefaultLiteral;
import org.xbib.content.rdf.internal.DefaultRdfGraph;
import org.xbib.content.rdf.internal.DefaultTriple;
import org.xbib.content.rdf.io.ntriple.NTripleContent;
import org.xbib.content.rdf.io.ntriple.NTripleContentParams;
import org.xbib.content.resource.IRI;
import org.xbib.content.resource.Node;
import org.xbib.content.rdf.StreamTester;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
/**
*
*/
public class EuropeanaEDMReaderTest extends StreamTester {
private static final IRI GEO_LAT = IRI.create("http://www.w3.org/2003/01/geo/wgs84_pos#lat");
private static final IRI GEO_LON = IRI.create("http://www.w3.org/2003/01/geo/wgs84_pos#long");
private static final IRI location = IRI.create("location");
@Test
public void testEuropeana() throws Exception {
String filename = "oai_edm.xml";
InputStream in = getClass().getResourceAsStream(filename);
if (in == null) {
throw new IOException("file " + filename + " not found");
}
DefaultRdfGraph graph = new DefaultRdfGraph();
RdfXmlContentParser<NTripleContentParams> reader = new RdfXmlContentParser<>(in);
reader.setRdfContentBuilderProvider(() -> new GeoJSONFilter(NTripleContent.nTripleContent(),
NTripleContentParams.N_TRIPLE_CONTENT_PARAMS, graph));
reader.parse();
RdfContentBuilder<NTripleContentParams> builder = ntripleBuilder();
Iterator<Resource> resourceIterator = graph.getResources();
while (resourceIterator.hasNext()) {
Resource resource = resourceIterator.next();
builder.receive(resource);
}
//System.err.println(builder.string());
assertStream(getClass().getResource("edm.nt").openStream(),
builder.streamInput());
}
private static class GeoJSONFilter extends RdfContentBuilder<NTripleContentParams> {
DefaultRdfGraph graph;
Node lat = null;
Node lon = null;
GeoJSONFilter(RdfContent<NTripleContentParams> content, NTripleContentParams params, DefaultRdfGraph graph)
throws IOException {
super(content, params);
this.graph = graph;
}
@Override
public GeoJSONFilter receive(Triple triple) {
graph.receive(triple);
if (triple.predicate().equals(GEO_LAT)) {
lat = triple.object();
}
if (triple.predicate().equals(GEO_LON)) {
lon = triple.object();
}
if (lat != null && lon != null) {
// create location string for Elasticsearch
graph.receive(new DefaultTriple(triple.subject(), location, new DefaultLiteral(lat + "," + lon)));
lon = null;
lat = null;
}
return this;
}
}
}
| apache-2.0 |
jtransc/jtransc | jtransc-rt/src/javax/sound/sampled/Control.java | 1380 | /*
* 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 javax.sound.sampled;
public abstract class Control {
private final Type type;
protected Control(Type type) {
this.type = type;
}
public Type getType() {
return type;
}
public String toString() {
return getType() + " Control";
}
public static class Type {
private final String name;
protected Type(String name) {
this.name = name;
}
public final boolean equals(Object obj) {
return obj == this;
}
public final int hashCode() {
return name.hashCode();
}
public final String toString() {
return name;
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-ioteventsdata/src/main/java/com/amazonaws/services/ioteventsdata/model/transform/ResetActionConfigurationMarshaller.java | 2029 | /*
* Copyright 2017-2022 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.ioteventsdata.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.ioteventsdata.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ResetActionConfigurationMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ResetActionConfigurationMarshaller {
private static final MarshallingInfo<String> NOTE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("note").build();
private static final ResetActionConfigurationMarshaller instance = new ResetActionConfigurationMarshaller();
public static ResetActionConfigurationMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ResetActionConfiguration resetActionConfiguration, ProtocolMarshaller protocolMarshaller) {
if (resetActionConfiguration == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(resetActionConfiguration.getNote(), NOTE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
hazendaz/assertj-core | src/main/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonDifferenceCalculator.java | 37861 | /*
* 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.
*
* Copyright 2012-2021 the original author or authors.
*/
package org.assertj.core.api.recursive.comparison;
import static java.lang.String.format;
import static java.util.Objects.deepEquals;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toMap;
import static org.assertj.core.api.recursive.comparison.ComparisonDifference.rootComparisonDifference;
import static org.assertj.core.api.recursive.comparison.DualValue.DEFAULT_ORDERED_COLLECTION_TYPES;
import static org.assertj.core.api.recursive.comparison.FieldLocation.rootFieldLocation;
import static org.assertj.core.internal.Objects.getDeclaredFieldsIncludingInherited;
import static org.assertj.core.internal.Objects.getFieldsNames;
import static org.assertj.core.util.IterableUtil.sizeOf;
import static org.assertj.core.util.IterableUtil.toCollection;
import static org.assertj.core.util.Lists.list;
import static org.assertj.core.util.Sets.newHashSet;
import static org.assertj.core.util.introspection.PropertyOrFieldSupport.COMPARISON;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;
import org.assertj.core.internal.DeepDifference;
/**
* Based on {@link DeepDifference} but takes a {@link RecursiveComparisonConfiguration}, {@link DeepDifference}
* being itself based on the deep equals implementation of https://github.com/jdereg/java-util
*
* @author John DeRegnaucourt (john@cedarsoftware.com)
* @author Pascal Schumacher
*/
public class RecursiveComparisonDifferenceCalculator {
private static final String DIFFERENT_ACTUAL_AND_EXPECTED_FIELD_TYPES = "expected field is %s but actual field is not (%s)";
private static final String ACTUAL_NOT_ORDERED_COLLECTION = "expected field is an ordered collection but actual field is not (%s), ordered collections are: "
+ describeOrderedCollectionTypes();
private static final String VALUE_FIELD_NAME = "value";
private static final String STRICT_TYPE_ERROR = "the fields are considered different since the comparison enforces strict type check and %s is not a subtype of %s";
private static final String DIFFERENT_SIZE_ERROR = "actual and expected values are %s of different size, actual size=%s when expected size=%s";
private static final String MISSING_FIELDS = "%s can't be compared to %s as %s does not declare all %s fields, it lacks these: %s";
private static final Map<Class<?>, Boolean> customEquals = new ConcurrentHashMap<>();
private static final Map<Class<?>, Boolean> customHash = new ConcurrentHashMap<>();
private static class ComparisonState {
// Not using a Set as we want to precisely track visited values, a set would remove duplicates
List<DualValue> visitedDualValues;
List<ComparisonDifference> differences = new ArrayList<>();
DualValueDeque dualValuesToCompare;
RecursiveComparisonConfiguration recursiveComparisonConfiguration;
public ComparisonState(List<DualValue> visited, RecursiveComparisonConfiguration recursiveComparisonConfiguration) {
this.visitedDualValues = visited;
this.dualValuesToCompare = new DualValueDeque(recursiveComparisonConfiguration);
this.recursiveComparisonConfiguration = recursiveComparisonConfiguration;
}
void addDifference(DualValue dualValue) {
differences.add(new ComparisonDifference(dualValue, null, getCustomErrorMessage(dualValue)));
}
void addDifference(DualValue dualValue, String description) {
differences.add(new ComparisonDifference(dualValue, description, getCustomErrorMessage(dualValue)));
}
void addKeyDifference(DualValue parentDualValue, Object actualKey, Object expectedKey) {
differences.add(new ComparisonKeyDifference(parentDualValue, actualKey, expectedKey));
}
public List<ComparisonDifference> getDifferences() {
Collections.sort(differences);
return differences;
}
public boolean hasDualValuesToCompare() {
return !dualValuesToCompare.isEmpty();
}
public DualValue pickDualValueToCompare() {
final DualValue dualValue = dualValuesToCompare.removeFirst();
if (dualValue.hasPotentialCyclingValues()) {
// visited dual values are here to avoid cycle, java types don't have cycle, there is no need to track them.
// moreover this would make should_fix_1854_minimal_test to fail (see the test for a detailed explanation)
visitedDualValues.add(dualValue);
}
return dualValue;
}
private void registerForComparison(DualValue dualValue) {
if (!visitedDualValues.contains(dualValue)) dualValuesToCompare.addFirst(dualValue);
}
private void initDualValuesToCompare(Object actual, Object expected, FieldLocation fieldLocation, boolean isRootObject) {
DualValue dualValue = new DualValue(fieldLocation, actual, expected);
boolean mustCompareFieldsRecursively = mustCompareFieldsRecursively(isRootObject, dualValue);
if (dualValue.hasNoNullValues() && dualValue.hasNoContainerValues() && mustCompareFieldsRecursively) {
// disregard the equals method and start comparing fields
Set<String> nonIgnoredActualFieldsNames = recursiveComparisonConfiguration.getNonIgnoredActualFieldNames(dualValue);
if (!nonIgnoredActualFieldsNames.isEmpty()) {
// fields to ignore are evaluated when adding their corresponding dualValues to dualValuesToCompare which filters
// ignored fields according to recursiveComparisonConfiguration
Set<String> expectedFieldsNames = getFieldsNames(expected.getClass());
if (expectedFieldsNames.containsAll(nonIgnoredActualFieldsNames)) {
// we compare actual fields vs expected, ignoring expected additional fields
for (String nonIgnoredActualFieldName : nonIgnoredActualFieldsNames) {
DualValue fieldDualValue = new DualValue(fieldLocation.field(nonIgnoredActualFieldName),
COMPARISON.getSimpleValue(nonIgnoredActualFieldName, actual),
COMPARISON.getSimpleValue(nonIgnoredActualFieldName, expected));
dualValuesToCompare.addFirst(fieldDualValue);
}
} else {
dualValuesToCompare.addFirst(dualValue);
}
} else {
dualValuesToCompare.addFirst(dualValue);
}
} else {
dualValuesToCompare.addFirst(dualValue);
}
// We need to remove already visited fields pair to avoid infinite recursion in case parent -> set{child} with child having
// a reference back to its parent but only for complex types can have cycle, this is not the case for primitive or enums.
// It occurs for unordered collection where we compare all possible combination of the collection elements recursively.
// --
// remove visited values one by one, DualValue.equals correctly compare respective actual and expected fields by reference
visitedDualValues.forEach(visitedDualValue -> dualValuesToCompare.stream()
.filter(dualValueToCompare -> dualValueToCompare.equals(visitedDualValue))
.findFirst()
.ifPresent(dualValuesToCompare::remove));
}
private boolean mustCompareFieldsRecursively(boolean isRootObject, DualValue dualValue) {
boolean noCustomComparisonForDualValue = !recursiveComparisonConfiguration.hasCustomComparator(dualValue)
&& !shouldHonorOverriddenEquals(dualValue, recursiveComparisonConfiguration);
return isRootObject || noCustomComparisonForDualValue;
}
private String getCustomErrorMessage(DualValue dualValue) {
String fieldName = dualValue.getConcatenatedPath();
// field custome messages take precedence over type messages
if (recursiveComparisonConfiguration.hasCustomMessageForField(fieldName)) {
return recursiveComparisonConfiguration.getMessageForField(fieldName);
}
Class<?> fieldType = dualValue.actual != null ? dualValue.actual.getClass() : dualValue.expected.getClass();
if (recursiveComparisonConfiguration.hasCustomMessageForType(fieldType)) {
return recursiveComparisonConfiguration.getMessageForType(fieldType);
}
return null;
}
}
/**
* Compare two objects for differences by doing a 'deep' comparison. This will traverse the
* Object graph and perform either a field-by-field comparison on each
* object (if not .equals() method has been overridden from Object), or it
* will call the customized .equals() method if it exists.
* <p>
*
* This method handles cycles correctly, for example A->B->C->A.
* Suppose a and a' are two separate instances of the A with the same values
* for all fields on A, B, and C. Then a.deepEquals(a') will return an empty list. It
* uses cycle detection storing visited objects in a Set to prevent endless
* loops.
*
* @param actual Object one to compare
* @param expected Object two to compare
* @param recursiveComparisonConfiguration the recursive comparison configuration
* @return the list of differences found or an empty list if objects are equivalent.
* Equivalent means that all field values of both subgraphs are the same,
* either at the field level or via the respectively encountered overridden
* .equals() methods during traversal.
*/
public List<ComparisonDifference> determineDifferences(Object actual, Object expected,
RecursiveComparisonConfiguration recursiveComparisonConfiguration) {
if (recursiveComparisonConfiguration.isInStrictTypeCheckingMode() && expectedTypeIsNotSubtypeOfActualType(actual, expected)) {
return list(expectedAndActualTypeDifference(actual, expected));
}
List<DualValue> visited = list();
return determineDifferences(actual, expected, rootFieldLocation(), true, visited, recursiveComparisonConfiguration);
}
// TODO keep track of ignored fields in an RecursiveComparisonExecution class ?
private static List<ComparisonDifference> determineDifferences(Object actual, Object expected, FieldLocation fieldLocation,
boolean isRootObject, List<DualValue> visited,
RecursiveComparisonConfiguration recursiveComparisonConfiguration) {
ComparisonState comparisonState = new ComparisonState(visited, recursiveComparisonConfiguration);
comparisonState.initDualValuesToCompare(actual, expected, fieldLocation, isRootObject);
while (comparisonState.hasDualValuesToCompare()) {
final DualValue dualValue = comparisonState.pickDualValueToCompare();
final Object actualFieldValue = dualValue.actual;
final Object expectedFieldValue = dualValue.expected;
// Custom comparators take precedence over all other types of comparison
if (recursiveComparisonConfiguration.hasCustomComparator(dualValue)) {
if (!areDualValueEqual(dualValue, recursiveComparisonConfiguration)) comparisonState.addDifference(dualValue);
// since we used a custom comparator we don't need to inspect the nested fields any further
continue;
}
if (actualFieldValue == expectedFieldValue) continue;
if (actualFieldValue == null || expectedFieldValue == null) {
// one of the value is null while the other is not as we already know that actualFieldValue != expectedFieldValue
comparisonState.addDifference(dualValue);
continue;
}
if (dualValue.isExpectedAnEnum()) {
compareAsEnums(dualValue, comparisonState, recursiveComparisonConfiguration);
continue;
}
// TODO move hasFieldTypesDifference check into each compareXXX
if (dualValue.isExpectedFieldAnArray()) {
compareArrays(dualValue, comparisonState);
continue;
}
// we compare ordered collections specifically as to be matching, each pair of elements at a given index must match.
// concretely we compare: (col1[0] vs col2[0]), (col1[1] vs col2[1])...(col1[n] vs col2[n])
if (dualValue.isExpectedFieldAnOrderedCollection()
&& !recursiveComparisonConfiguration.shouldIgnoreCollectionOrder(dualValue.fieldLocation)) {
compareOrderedCollections(dualValue, comparisonState);
continue;
}
if (dualValue.isExpectedFieldAnIterable()) {
compareUnorderedIterables(dualValue, comparisonState);
continue;
}
if (dualValue.isExpectedFieldAnOptional()) {
compareOptional(dualValue, comparisonState);
continue;
}
// Compare two SortedMaps taking advantage of the fact that these Maps can be compared in O(N) time due to their ordering
if (dualValue.isExpectedFieldASortedMap()) {
compareSortedMap(dualValue, comparisonState);
continue;
}
// Compare two Unordered Maps. This is a slightly more expensive comparison because order cannot be assumed, therefore a
// temporary Map must be created, however the comparison still runs in O(N) time.
if (dualValue.isExpectedFieldAMap()) {
compareUnorderedMap(dualValue, comparisonState);
continue;
}
if (shouldCompareDualValue(recursiveComparisonConfiguration, dualValue)) {
if (!actualFieldValue.equals(expectedFieldValue)) comparisonState.addDifference(dualValue);
continue;
}
Class<?> actualFieldValueClass = actualFieldValue.getClass();
Class<?> expectedFieldClass = expectedFieldValue.getClass();
if (recursiveComparisonConfiguration.isInStrictTypeCheckingMode() && expectedTypeIsNotSubtypeOfActualType(dualValue)) {
comparisonState.addDifference(dualValue,
format(STRICT_TYPE_ERROR, expectedFieldClass.getName(), actualFieldValueClass.getName()));
continue;
}
Set<String> actualNonIgnoredFieldsNames = recursiveComparisonConfiguration.getNonIgnoredActualFieldNames(dualValue);
Set<String> expectedFieldsNames = getFieldsNames(expectedFieldClass);
// Check if expected has more fields than actual, in that case the additional fields are reported as difference
if (!expectedFieldsNames.containsAll(actualNonIgnoredFieldsNames)) {
// report missing fields in actual
Set<String> actualFieldsNamesNotInExpected = newHashSet(actualNonIgnoredFieldsNames);
actualFieldsNamesNotInExpected.removeAll(expectedFieldsNames);
String missingFields = actualFieldsNamesNotInExpected.toString();
String expectedClassName = expectedFieldClass.getName();
String actualClassName = actualFieldValueClass.getName();
String missingFieldsDescription = format(MISSING_FIELDS, actualClassName, expectedClassName,
expectedFieldClass.getSimpleName(), actualFieldValueClass.getSimpleName(),
missingFields);
comparisonState.addDifference(dualValue, missingFieldsDescription);
} else { // TODO remove else to report more diff
// compare actual's fields against expected :
// - if actual has more fields than expected, the additional fields are ignored as expected is the reference
for (String actualFieldName : actualNonIgnoredFieldsNames) {
if (expectedFieldsNames.contains(actualFieldName)) {
DualValue newDualValue = new DualValue(dualValue.fieldLocation.field(actualFieldName),
COMPARISON.getSimpleValue(actualFieldName, actualFieldValue),
COMPARISON.getSimpleValue(actualFieldName, expectedFieldValue));
comparisonState.registerForComparison(newDualValue);
}
}
}
}
return comparisonState.getDifferences();
}
private static boolean shouldCompareDualValue(RecursiveComparisonConfiguration recursiveComparisonConfiguration,
final DualValue dualValue) {
return !recursiveComparisonConfiguration.shouldIgnoreOverriddenEqualsOf(dualValue)
&& hasOverriddenEquals(dualValue.actual.getClass());
}
// avoid comparing enum recursively since they contain static fields which are ignored in recursive comparison
// this would make different field enum value to be considered the same!
private static void compareAsEnums(final DualValue dualValue,
ComparisonState comparisonState,
RecursiveComparisonConfiguration recursiveComparisonConfiguration) {
if (recursiveComparisonConfiguration.isInStrictTypeCheckingMode()) {
// we can use == for comparison which checks both actual and expected values and types are the same
if (dualValue.actual != dualValue.expected) comparisonState.addDifference(dualValue);
return;
}
if (!dualValue.isActualAnEnum()) {
comparisonState.addDifference(dualValue, differentTypeErrorMessage(dualValue, "an enum"));
return;
}
// both actual and expected are enums
Enum<?> actualEnum = (Enum<?>) dualValue.actual;
Enum<?> expectedEnum = (Enum<?>) dualValue.expected;
// we must only compare actual and expected enum by value but not by type
if (!actualEnum.name().equals(expectedEnum.name())) comparisonState.addDifference(dualValue);
}
private static boolean shouldHonorOverriddenEquals(DualValue dualValue,
RecursiveComparisonConfiguration recursiveComparisonConfiguration) {
boolean shouldNotIgnoreOverriddenEqualsIfAny = !recursiveComparisonConfiguration.shouldIgnoreOverriddenEqualsOf(dualValue);
return shouldNotIgnoreOverriddenEqualsIfAny && dualValue.actual != null && hasOverriddenEquals(dualValue.actual.getClass());
}
private static void compareArrays(DualValue dualValue, ComparisonState comparisonState) {
if (!dualValue.isActualFieldAnArray()) {
// at the moment we only allow comparing arrays with arrays but we might allow comparing to collections later on
// but only if we are not in strict type mode.
comparisonState.addDifference(dualValue, differentTypeErrorMessage(dualValue, "an array"));
return;
}
// both values in dualValue are arrays
int actualArrayLength = Array.getLength(dualValue.actual);
int expectedArrayLength = Array.getLength(dualValue.expected);
if (actualArrayLength != expectedArrayLength) {
comparisonState.addDifference(dualValue, format(DIFFERENT_SIZE_ERROR, "arrays", actualArrayLength, expectedArrayLength));
// no need to inspect elements, arrays are not equal as they don't have the same size
return;
}
// register each pair of actual/expected elements for recursive comparison
FieldLocation arrayFieldLocation = dualValue.fieldLocation;
for (int i = 0; i < actualArrayLength; i++) {
Object actualElement = Array.get(dualValue.actual, i);
Object expectedElement = Array.get(dualValue.expected, i);
FieldLocation elementFieldLocation = arrayFieldLocation.field(format("[%d]", i));
comparisonState.registerForComparison(new DualValue(elementFieldLocation, actualElement, expectedElement));
}
}
/*
* Deeply compare two Collections that must be same length and in same order.
*/
private static void compareOrderedCollections(DualValue dualValue, ComparisonState comparisonState) {
if (!dualValue.isActualFieldAnOrderedCollection()) {
// at the moment if expected is an ordered collection then actual should also be one
comparisonState.addDifference(dualValue,
format(ACTUAL_NOT_ORDERED_COLLECTION, dualValue.actual.getClass().getCanonicalName()));
return;
}
Collection<?> actualCollection = (Collection<?>) dualValue.actual;
Collection<?> expectedCollection = (Collection<?>) dualValue.expected;
if (actualCollection.size() != expectedCollection.size()) {
comparisonState.addDifference(dualValue, format(DIFFERENT_SIZE_ERROR, "collections", actualCollection.size(),
expectedCollection.size()));
// no need to inspect elements, arrays are not equal as they don't have the same size
return;
}
// register pair of elements with same index for later comparison as we compare elements in order
Iterator<?> expectedIterator = expectedCollection.iterator();
int i = 0;
for (Object element : actualCollection) {
FieldLocation elementFielLocation = dualValue.fieldLocation.field(format("[%d]", i));
DualValue elementDualValue = new DualValue(elementFielLocation, element, expectedIterator.next());
comparisonState.registerForComparison(elementDualValue);
i++;
}
}
private static String differentTypeErrorMessage(DualValue dualValue, String actualTypeDescription) {
return format(DIFFERENT_ACTUAL_AND_EXPECTED_FIELD_TYPES,
actualTypeDescription, dualValue.actual.getClass().getCanonicalName());
}
private static void compareUnorderedIterables(DualValue dualValue, ComparisonState comparisonState) {
if (!dualValue.isActualFieldAnIterable()) {
// at the moment we only compare iterable with iterables (but we might allow arrays too)
comparisonState.addDifference(dualValue, differentTypeErrorMessage(dualValue, "an iterable"));
return;
}
Iterable<?> actual = (Iterable<?>) dualValue.actual;
Iterable<?> expected = (Iterable<?>) dualValue.expected;
int actualSize = sizeOf(actual);
int expectedSize = sizeOf(expected);
if (actualSize != expectedSize) {
comparisonState.addDifference(dualValue, format(DIFFERENT_SIZE_ERROR, "collections", actualSize, expectedSize));
// no need to inspect elements, iterables are not equal as they don't have the same size
return;
// TODO instead we could register the diff between expected and actual that is:
// - unexpected actual elements (the ones not matching any expected)
// - expected elements not found in actual.
}
// copy expected as we will remove elements found in actual
Collection<?> expectedCopy = new LinkedList<>(toCollection(expected));
List<Object> unmatchedActualElements = list();
for (Object actualElement : actual) {
boolean actualElementMatched = false;
// compare recursively actualElement to all remaining expected elements
Iterator<?> expectedIterator = expectedCopy.iterator();
while (expectedIterator.hasNext()) {
Object expectedElement = expectedIterator.next();
// we need to get the currently visited dual values otherwise a cycle would cause an infinite recursion.
List<ComparisonDifference> differences = determineDifferences(actualElement, expectedElement, dualValue.fieldLocation,
false, comparisonState.visitedDualValues,
comparisonState.recursiveComparisonConfiguration);
if (differences.isEmpty()) {
// found an element in expected matching actualElement, remove it as it can't be used to match other actual elements
expectedIterator.remove();
actualElementMatched = true;
// jump to next actual element check
break;
}
}
if (!actualElementMatched) unmatchedActualElements.add(actualElement);
}
if (!unmatchedActualElements.isEmpty()) {
String unmatched = format("The following actual elements were not matched in the expected %s:%n %s",
expected.getClass().getSimpleName(), unmatchedActualElements);
comparisonState.addDifference(dualValue, unmatched);
}
}
// TODO replace by ordered map
private static <K, V> void compareSortedMap(DualValue dualValue, ComparisonState comparisonState) {
if (!dualValue.isActualFieldASortedMap()) {
// at the moment we only compare iterable with iterables (but we might allow arrays too)
comparisonState.addDifference(dualValue, differentTypeErrorMessage(dualValue, "a sorted map"));
return;
}
Map<?, ?> actualMap = (Map<?, ?>) dualValue.actual;
@SuppressWarnings("unchecked")
Map<K, V> expectedMap = (Map<K, V>) dualValue.expected;
if (actualMap.size() != expectedMap.size()) {
comparisonState.addDifference(dualValue, format(DIFFERENT_SIZE_ERROR, "sorted maps", actualMap.size(), expectedMap.size()));
// no need to inspect entries, maps are not equal as they don't have the same size
return;
// TODO instead we could register the diff between expected and actual that is:
// - unexpected actual entries (the ones not matching any expected)
// - expected entries not found in actual.
}
Iterator<Map.Entry<K, V>> expectedMapEntries = expectedMap.entrySet().iterator();
for (Map.Entry<?, ?> actualEntry : actualMap.entrySet()) {
Map.Entry<?, ?> expectedEntry = expectedMapEntries.next();
// check keys are matched before comparing values as keys represents a field
if (!java.util.Objects.equals(actualEntry.getKey(), expectedEntry.getKey())) {
// report a missing key/field.
comparisonState.addKeyDifference(dualValue, actualEntry.getKey(), expectedEntry.getKey());
} else {
// as the key/field match we can simply compare field/key values
FieldLocation keyFieldLocation = keyFieldLocation(dualValue.fieldLocation, actualEntry.getKey());
comparisonState.registerForComparison(new DualValue(keyFieldLocation, actualEntry.getValue(), expectedEntry.getValue()));
}
}
}
private static void compareUnorderedMap(DualValue dualValue, ComparisonState comparisonState) {
if (!dualValue.isActualFieldAMap()) {
comparisonState.addDifference(dualValue, differentTypeErrorMessage(dualValue, "a map"));
return;
}
Map<?, ?> actualMap = (Map<?, ?>) dualValue.actual;
Map<?, ?> expectedMap = (Map<?, ?>) dualValue.expected;
if (actualMap.size() != expectedMap.size()) {
comparisonState.addDifference(dualValue, format(DIFFERENT_SIZE_ERROR, "maps", actualMap.size(), expectedMap.size()));
// no need to inspect entries, maps are not equal as they don't have the same size
return;
// TODO instead we could register the diff between expected and actual that is:
// - unexpected actual entries (the ones not matching any expected)
// - expected entries not found in actual.
}
// index expected entries by their key deep hash code
Map<Integer, Map.Entry<?, ?>> expectedEntriesByDeepHashCode = expectedMap.entrySet().stream()
.collect(toMap(entry -> deepHashCode(entry.getKey()),
entry -> entry));
// index actual keys by their deep hash code
Map<?, Integer> actualDeepHashCodesByKey = actualMap.keySet().stream().collect(toMap(key -> key, key -> deepHashCode(key)));
Map<?, ?> unmatchedActualEntries = actualDeepHashCodesByKey.entrySet().stream()
.filter(entry -> !expectedEntriesByDeepHashCode.containsKey(entry.getValue()))
// back to actual entries
.collect(toMap(entry -> entry.getKey(),
entry -> actualMap.get(entry.getKey())));
if (!unmatchedActualEntries.isEmpty()) {
comparisonState.addDifference(dualValue,
format("The following actual map entries were not found in the expected map:%n %s",
unmatchedActualEntries));
return;
}
for (Map.Entry<?, ?> actualEntry : actualMap.entrySet()) {
int deepHashCode = actualDeepHashCodesByKey.get(actualEntry.getKey());
Map.Entry<?, ?> expectedEntry = expectedEntriesByDeepHashCode.get(deepHashCode);
// since we have found an entry in expected with the actual entry key, we just need to compare entry values.
FieldLocation keyFieldLocation = keyFieldLocation(dualValue.fieldLocation, actualEntry.getKey());
comparisonState.registerForComparison(new DualValue(keyFieldLocation, actualEntry.getValue(), expectedEntry.getValue()));
}
}
private static FieldLocation keyFieldLocation(FieldLocation parentFieldLocation, Object key) {
return key == null ? parentFieldLocation : parentFieldLocation.field(key.toString());
}
private static void compareOptional(DualValue dualValue, ComparisonState comparisonState) {
if (!dualValue.isActualFieldAnOptional()) {
comparisonState.addDifference(dualValue, differentTypeErrorMessage(dualValue, "an Optional"));
return;
}
Optional<?> actual = (Optional<?>) dualValue.actual;
Optional<?> expected = (Optional<?>) dualValue.expected;
if (actual.isPresent() != expected.isPresent()) {
comparisonState.addDifference(dualValue);
return;
}
// either both are empty or present
if (!actual.isPresent()) return; // both optional are empty => end of the comparison
// both are present, we have to compare their values recursively
Object value1 = actual.get();
Object value2 = expected.get();
// we add VALUE_FIELD_NAME to the path since we register Optional.value fields.
comparisonState.registerForComparison(new DualValue(dualValue.fieldLocation.field(VALUE_FIELD_NAME), value1, value2));
}
/**
* Determine if the passed in class has a non-Object.equals() method. This
* method caches its results in static ConcurrentHashMap to benefit
* execution performance.
*
* @param c Class to check.
* @return true, if the passed in Class has a .equals() method somewhere
* between itself and just below Object in it's inheritance.
*/
static boolean hasOverriddenEquals(Class<?> c) {
if (customEquals.containsKey(c)) {
return customEquals.get(c);
}
Class<?> origClass = c;
while (!Object.class.equals(c)) {
try {
c.getDeclaredMethod("equals", Object.class);
customEquals.put(origClass, true);
return true;
} catch (Exception ignored) {}
c = c.getSuperclass();
}
customEquals.put(origClass, false);
return false;
}
/**
* Get a deterministic hashCode (int) value for an Object, regardless of
* when it was created or where it was loaded into memory. The problem with
* java.lang.Object.hashCode() is that it essentially relies on memory
* location of an object (what identity it was assigned), whereas this
* method will produce the same hashCode for any object graph, regardless of
* how many times it is created.<br>
* <br>
*
* This method will handle cycles correctly (A->B->C->A). In this
* case, Starting with object A, B, or C would yield the same hashCode. If
* an object encountered (root, subobject, etc.) has a hashCode() method on
* it (that is not Object.hashCode()), that hashCode() method will be called
* and it will stop traversal on that branch.
*
* @param obj Object who hashCode is desired.
* @return the 'deep' hashCode value for the passed in object.
*/
static int deepHashCode(Object obj) {
Set<Object> visited = new HashSet<>();
LinkedList<Object> stack = new LinkedList<>();
stack.addFirst(obj);
int hash = 0;
while (!stack.isEmpty()) {
obj = stack.removeFirst();
if (obj == null || visited.contains(obj)) {
continue;
}
visited.add(obj);
if (obj.getClass().isArray()) {
int len = Array.getLength(obj);
for (int i = 0; i < len; i++) {
stack.addFirst(Array.get(obj, i));
}
continue;
}
if (obj instanceof Collection) {
stack.addAll(0, (Collection<?>) obj);
continue;
}
if (obj instanceof Map) {
stack.addAll(0, ((Map<?, ?>) obj).keySet());
stack.addAll(0, ((Map<?, ?>) obj).values());
continue;
}
if (obj instanceof Double || obj instanceof Float) {
// just take the integral value for hashcode
// equality tests things more comprehensively
stack.add(Math.round(((Number) obj).doubleValue()));
continue;
}
if (hasCustomHashCode(obj.getClass())) {
// A real hashCode() method exists, call it.
hash += obj.hashCode();
continue;
}
Collection<Field> fields = getDeclaredFieldsIncludingInherited(obj.getClass());
for (Field field : fields) {
stack.addFirst(COMPARISON.getSimpleValue(field.getName(), obj));
}
}
return hash;
}
/**
* Determine if the passed in class has a non-Object.hashCode() method. This
* method caches its results in static ConcurrentHashMap to benefit
* execution performance.
*
* @param c Class to check.
* @return true, if the passed in Class has a .hashCode() method somewhere
* between itself and just below Object in it's inheritance.
*/
static boolean hasCustomHashCode(Class<?> c) {
Class<?> origClass = c;
if (customHash.containsKey(c)) {
return customHash.get(c);
}
while (!Object.class.equals(c)) {
try {
c.getDeclaredMethod("hashCode");
customHash.put(origClass, true);
return true;
} catch (Exception ignored) {}
c = c.getSuperclass();
}
customHash.put(origClass, false);
return false;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static boolean areDualValueEqual(DualValue dualValue,
RecursiveComparisonConfiguration recursiveComparisonConfiguration) {
final String fieldName = dualValue.getConcatenatedPath();
final Object actualFieldValue = dualValue.actual;
final Object expectedFieldValue = dualValue.expected;
// check field comparators as they take precedence over type comparators
Comparator fieldComparator = recursiveComparisonConfiguration.getComparatorForField(fieldName);
if (fieldComparator != null) return areEqualUsingComparator(actualFieldValue, expectedFieldValue, fieldComparator);
// check if a type comparators exist for the field type
Class fieldType = actualFieldValue != null ? actualFieldValue.getClass() : expectedFieldValue.getClass();
Comparator typeComparator = recursiveComparisonConfiguration.getComparatorForType(fieldType);
if (typeComparator != null) return areEqualUsingComparator(actualFieldValue, expectedFieldValue, typeComparator);
// default comparison using equals
return deepEquals(actualFieldValue, expectedFieldValue);
}
private static boolean areEqualUsingComparator(final Object actual, final Object expected, Comparator<Object> comparator) {
try {
return comparator.compare(actual, expected) == 0;
} catch (ClassCastException e) {
// this occurs when comparing field of different types, Person.id is an int and PersonDto.id is a long
return false;
}
}
private static ComparisonDifference expectedAndActualTypeDifference(Object actual, Object expected) {
String additionalInformation = format(
"actual and expected are considered different since the comparison enforces strict type check and expected type %s is not a subtype of actual type %s",
expected.getClass().getName(), actual.getClass().getName());
return rootComparisonDifference(actual, expected, additionalInformation);
}
// TODO should be checking actual!
private static boolean expectedTypeIsNotSubtypeOfActualType(DualValue dualField) {
return expectedTypeIsNotSubtypeOfActualType(dualField.actual, dualField.expected);
}
private static boolean expectedTypeIsNotSubtypeOfActualType(Object actual, Object expected) {
return !actual.getClass().isAssignableFrom(expected.getClass());
}
private static String describeOrderedCollectionTypes() {
return Stream.of(DEFAULT_ORDERED_COLLECTION_TYPES)
.map(Class::getName)
.collect(joining(", ", "[", "]"));
}
}
| apache-2.0 |
AlanJager/zstack | compute/src/main/java/org/zstack/compute/allocator/HostAllocatorChain.java | 10455 | package org.zstack.compute.allocator;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.config.GlobalConfigVO;
import org.zstack.core.config.GlobalConfigVO_;
import org.zstack.core.db.Q;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.header.allocator.*;
import org.zstack.header.core.ReturnValueCompletion;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.host.HostInventory;
import org.zstack.header.host.HostVO;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.utils.DebugUtils;
import org.zstack.utils.SizeUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import java.util.*;
import java.util.stream.Collectors;
import static org.zstack.core.Platform.err;
import static org.zstack.core.Platform.inerr;
/**
*/
@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE)
public class HostAllocatorChain implements HostAllocatorTrigger, HostAllocatorStrategy {
private static final CLogger logger = Utils.getLogger(HostAllocatorChain.class);
private HostAllocatorSpec allocationSpec;
private String name;
private List<AbstractHostAllocatorFlow> flows;
private Iterator<AbstractHostAllocatorFlow> it;
private ErrorCode errorCode;
private List<HostVO> result = null;
private boolean isDryRun;
private ReturnValueCompletion<List<HostInventory>> completion;
private ReturnValueCompletion<List<HostInventory>> dryRunCompletion;
private int skipCounter = 0;
private AbstractHostAllocatorFlow lastFlow;
private HostAllocationPaginationInfo paginationInfo;
private Set<ErrorCode> seriesErrorWhenPagination = new HashSet<>();
@Autowired
private ErrorFacade errf;
@Autowired
private PluginRegistry pluginRgty;
@Autowired
private HostCapacityOverProvisioningManager ratioMgr;
public HostAllocatorSpec getAllocationSpec() {
return allocationSpec;
}
public void setAllocationSpec(HostAllocatorSpec allocationSpec) {
this.allocationSpec = allocationSpec;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<AbstractHostAllocatorFlow> getFlows() {
return flows;
}
public void setFlows(List<AbstractHostAllocatorFlow> flows) {
this.flows = flows;
}
void reserveCapacity(final String hostUuid, final long requestCpu, final long requestMemory) {
HostCapacityUpdater updater = new HostCapacityUpdater(hostUuid);
String reservedMemoryOfGlobalConfig = Q.New(GlobalConfigVO.class).select(GlobalConfigVO_.value).eq(GlobalConfigVO_.name,"reservedMemory").findValue();
updater.run(new HostCapacityUpdaterRunnable() {
@Override
public HostCapacityVO call(HostCapacityVO cap) {
long availCpu = cap.getAvailableCpu() - requestCpu;
if (requestCpu != 0 && availCpu < 0) {
throw new UnableToReserveHostCapacityException(
String.format("no enough CPU[%s] on the host[uuid:%s]", requestCpu, hostUuid));
}
cap.setAvailableCpu(availCpu);
long availMemory = cap.getAvailableMemory() - ratioMgr.calculateMemoryByRatio(hostUuid, requestMemory);
if (requestMemory != 0 && availMemory - SizeUtils.sizeStringToBytes(reservedMemoryOfGlobalConfig) < 0) {
throw new UnableToReserveHostCapacityException(
String.format("no enough memory[%s] on the host[uuid:%s]", requestMemory, hostUuid));
}
cap.setAvailableMemory(availMemory);
return cap;
}
});
}
private void done() {
if (result == null) {
if (isDryRun) {
if (HostAllocatorError.NO_AVAILABLE_HOST.toString().equals(errorCode.getCode())) {
dryRunCompletion.success(new ArrayList<HostInventory>());
} else {
dryRunCompletion.fail(errorCode);
}
} else {
completion.fail(errorCode);
}
return;
}
// in case a wrong flow returns an empty result set
if (result.isEmpty()) {
if (isDryRun) {
dryRunCompletion.fail(err(HostAllocatorError.NO_AVAILABLE_HOST,
"host allocation flow doesn't indicate any details"));
} else {
completion.fail(err(HostAllocatorError.NO_AVAILABLE_HOST,
"host allocation flow doesn't indicate any details"));
}
return;
}
if (isDryRun) {
dryRunCompletion.success(HostInventory.valueOf(result));
} else {
completion.success(HostInventory.valueOf(result));
}
}
private void startOver() {
it = flows.iterator();
result = null;
skipCounter = 0;
runFlow(it.next());
}
private void runFlow(AbstractHostAllocatorFlow flow) {
try {
lastFlow = flow;
flow.setCandidates(result);
flow.setSpec(allocationSpec);
flow.setTrigger(this);
flow.setPaginationInfo(paginationInfo);
flow.allocate();
} catch (OperationFailureException ofe) {
if (ofe.getErrorCode().getCode().equals(HostAllocatorConstant.PAGINATION_INTERMEDIATE_ERROR.getCode())) {
logger.debug(String.format("[Host Allocation]: intermediate failure; " +
"because of pagination, will start over allocation again; " +
"current pagination info %s; failure details: %s",
JSONObjectUtil.toJsonString(paginationInfo), ofe.getErrorCode().getDetails()));
seriesErrorWhenPagination.add(ofe.getErrorCode());
startOver();
} else {
fail(ofe.getErrorCode());
}
} catch (Throwable t) {
logger.warn("unhandled throwable", t);
completion.fail(inerr(t.getMessage()));
}
}
private void start() {
for (HostAllocatorPreStartExtensionPoint processor : pluginRgty.getExtensionList(HostAllocatorPreStartExtensionPoint.class)) {
processor.beforeHostAllocatorStart(allocationSpec, flows);
}
if (HostAllocatorGlobalConfig.USE_PAGINATION.value(Boolean.class)) {
paginationInfo = new HostAllocationPaginationInfo();
paginationInfo.setLimit(HostAllocatorGlobalConfig.PAGINATION_LIMIT.value(Integer.class));
}
it = flows.iterator();
DebugUtils.Assert(it.hasNext(), "can not run an empty host allocation chain");
runFlow(it.next());
}
private void allocate(ReturnValueCompletion<List<HostInventory>> completion) {
isDryRun = false;
this.completion = completion;
start();
}
private void dryRun(ReturnValueCompletion<List<HostInventory>> completion) {
isDryRun = true;
this.dryRunCompletion = completion;
start();
}
@Override
public void next(List<HostVO> candidates) {
DebugUtils.Assert(candidates != null, "cannot pass null to next() method");
DebugUtils.Assert(!candidates.isEmpty(), "cannot pass empty candidates to next() method");
result = candidates;
VmInstanceInventory vm = allocationSpec.getVmInstance();
logger.debug(String.format("[Host Allocation]: flow[%s] successfully found %s candidate hosts for vm[uuid:%s, name:%s]",
lastFlow.getClass().getName(), result.size(), vm.getUuid(), vm.getName()));
if (logger.isTraceEnabled()) {
StringBuilder sb = new StringBuilder("[Host Allocation Details]:");
for (HostVO vo : result) {
sb.append(String.format("\ncandidate host[name:%s, uuid:%s, zoneUuid:%s, clusterUuid:%s, hypervisorType:%s]",
vo.getName(), vo.getUuid(), vo.getZoneUuid(), vo.getClusterUuid(), vo.getHypervisorType()));
}
logger.trace(sb.toString());
}
if (it.hasNext()) {
runFlow(it.next());
return;
}
done();
}
@Override
public void skip() {
logger.debug(String.format("[Host Allocation]: flow[%s] asks to skip itself, we are running to the next flow",
lastFlow.getClass()));
if (it.hasNext()) {
if (isFirstFlow(lastFlow)) {
skipCounter++;
}
runFlow(it.next());
return;
}
done();
}
@Override
public boolean isFirstFlow(AbstractHostAllocatorFlow flow) {
return flows.indexOf(flow) == skipCounter;
}
private void fail(ErrorCode errorCode) {
result = null;
if (seriesErrorWhenPagination.isEmpty()) {
logger.debug(String.format("[Host Allocation] flow[%s] failed to allocate host; %s",
lastFlow.getClass().getName(), errorCode.getDetails()));
this.errorCode = errorCode;
} else {
this.errorCode = err(HostAllocatorError.NO_AVAILABLE_HOST, seriesErrorWhenPagination.iterator().next(), "unable to allocate hosts; due to pagination is enabled, " +
"there might be several allocation failures happened before;" +
" the error list is %s", seriesErrorWhenPagination.stream().map(ErrorCode::getDetails).collect(Collectors.toList()));
logger.debug(this.errorCode.getDetails());
}
done();
}
@Override
public void allocate(HostAllocatorSpec spec, ReturnValueCompletion<List<HostInventory>> completion) {
this.allocationSpec = spec;
allocate(completion);
}
@Override
public void dryRun(HostAllocatorSpec spec, ReturnValueCompletion<List<HostInventory>> completion) {
this.allocationSpec = spec;
dryRun(completion);
}
}
| apache-2.0 |
arnost-starosta/midpoint | infra/util/src/main/java/com/evolveum/midpoint/util/LocalizableMessageBuilder.java | 2456 | /**
* Copyright (c) 2017 Evolveum
*
* 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.evolveum.midpoint.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author semancik
*
*/
public class LocalizableMessageBuilder {
private String key;
private final List<Object> args = new ArrayList<>();
private String fallbackMessage;
private LocalizableMessage fallbackLocalizableMessage;
public LocalizableMessageBuilder() {
}
public LocalizableMessageBuilder key(String key) {
this.key = key;
return this;
}
public static SingleLocalizableMessage buildKey(String key) {
return new SingleLocalizableMessage(key, null, (SingleLocalizableMessage) null);
}
public LocalizableMessageBuilder args(Object... args) {
Collections.addAll(this.args, args);
return this;
}
public LocalizableMessageBuilder args(List<Object> args) {
this.args.addAll(args);
return this;
}
public LocalizableMessageBuilder arg(Object arg) {
this.args.add(arg);
return this;
}
public LocalizableMessageBuilder fallbackMessage(String fallbackMessage) {
this.fallbackMessage = fallbackMessage;
return this;
}
public LocalizableMessageBuilder fallbackLocalizableMessage(LocalizableMessage fallbackLocalizableMessage) {
this.fallbackLocalizableMessage = fallbackLocalizableMessage;
return this;
}
public static SingleLocalizableMessage buildFallbackMessage(String fallbackMessage) {
return new SingleLocalizableMessage(null, null, fallbackMessage);
}
public SingleLocalizableMessage build() {
if (fallbackMessage != null) {
if (fallbackLocalizableMessage != null) {
throw new IllegalStateException("fallbackMessage and fallbackLocalizableMessage cannot be both set");
}
return new SingleLocalizableMessage(key, args.toArray(), fallbackMessage);
} else {
return new SingleLocalizableMessage(key, args.toArray(), fallbackLocalizableMessage);
}
}
}
| apache-2.0 |
joewalnes/idea-community | xml/impl/src/com/intellij/xml/actions/xmlbeans/GenerateSchemaFromInstanceDocumentDialog.java | 6907 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.xml.actions.xmlbeans;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.xml.XmlBundle;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Arrays;
import java.util.List;
/**
* @author Konstantin Bulenkov
*/
public class GenerateSchemaFromInstanceDocumentDialog extends DialogWrapper {
private JPanel panel;
private TextFieldWithBrowseButton generateFromUrl;
private JLabel status;
private JLabel statusText;
private JLabel generateFromUrlText;
private JLabel designTypeText;
private JTextField detectEnumerationsLimit;
private ComboBox detectSimpleContentTypes;
private ComboBox designType;
private JLabel detectEnumerationsLimitText;
private JLabel detectSimpleContentTypesText;
private JLabel resultSchemaFileNameText;
private JTextField resultSchemaFileName;
static final String LOCAL_ELEMENTS_GLOBAL_COMPLEX_TYPES = XmlBundle.message("local.elements.global.complex.types.option.name");
static final String LOCAL_ELEMENTS_TYPES = XmlBundle.message("local.elements.types.option.name");
static final String GLOBAL_ELEMENTS_LOCAL_TYPES = XmlBundle.message("global.elements.local.types.option.name");
private static final List<String> designTypes = Arrays.asList(
LOCAL_ELEMENTS_GLOBAL_COMPLEX_TYPES,
LOCAL_ELEMENTS_TYPES,
GLOBAL_ELEMENTS_LOCAL_TYPES
);
static final String STRING_TYPE = "string";
static final String SMART_TYPE = "smart";
private static final List<String> simpleContentTypes = Arrays.asList(STRING_TYPE, SMART_TYPE);
private Runnable myOkAction;
public GenerateSchemaFromInstanceDocumentDialog(Project project, VirtualFile file) {
super(project, true);
setTitle(XmlBundle.message("generate.schema.from.instance.document.dialog.title"));
doInitFor(designTypeText, designType);
configureComboBox(designType,designTypes);
doInitFor(detectSimpleContentTypesText, detectSimpleContentTypes);
configureComboBox(detectSimpleContentTypes, simpleContentTypes);
doInitFor(detectEnumerationsLimitText, detectEnumerationsLimit);
detectEnumerationsLimit.setText("10");
UIUtils.configureBrowseButton(project, generateFromUrl, new String[] {"xml"}, XmlBundle.message("select.xml.document.dialog.title"), false);
doInitFor(generateFromUrlText, generateFromUrl.getTextField());
doInitFor(resultSchemaFileNameText, resultSchemaFileName);
init();
generateFromUrl.setText(file.getPresentableUrl());
resultSchemaFileName.setText(file.getNameWithoutExtension() + ".xsd");
}
private void validateData() {
String msg = doValidateWithData();
setOKActionEnabled(msg == null);
status.setText(msg == null ? "" : msg);
status.setForeground(Color.RED);
}
public static void configureComboBox(JComboBox combo, List<String> lastValues) {
combo.setModel(new DefaultComboBoxModel(ArrayUtil.toStringArray(lastValues)));
if (combo.getItemCount() != 0) {
combo.setSelectedIndex(0);
combo.getEditor().selectAll();
}
}
public void setFileUrl(String url) {
generateFromUrl.setText(url);
}
@Override
protected void doOKAction() {
super.doOKAction();
if (myOkAction != null) {
myOkAction.run();
}
}
public void setOkAction(Runnable okAction) {
myOkAction = okAction;
}
public void doInitFor(JLabel textComponent, JComponent component) {
textComponent.setLabelFor(component);
if (component instanceof JTextField) {
((JTextField)component).getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
validateData();
}
public void removeUpdate(DocumentEvent e) {
validateData();
}
public void changedUpdate(DocumentEvent e) {
validateData();
}
});
} else if (component instanceof JComboBox) {
JComboBox jComboBox = ((JComboBox) component);
jComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
validateData();
}
});
if (jComboBox.isEditable()) {
jComboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
validateData();
}
});
}
}
}
protected TextFieldWithBrowseButton getUrl() {
return generateFromUrl;
}
protected JLabel getUrlText() {
return generateFromUrlText;
}
protected JLabel getStatusTextField() {
return statusText;
}
protected JLabel getStatusField() {
return status;
}
protected JComponent createCenterPanel() {
return panel;
}
String getDesignType() {
return (String) designType.getSelectedItem();
}
String getSimpleContentType() {
return (String) detectSimpleContentTypes.getSelectedItem();
}
String getEnumerationsLimit() {
return detectEnumerationsLimit.getText();
}
public String getTargetSchemaName() {
return resultSchemaFileName.getText();
}
protected String doValidateWithData() {
if (! new File(generateFromUrl.getText()).exists()) {
return XmlBundle.message("instance.document.file.is.not.exist");
}
try {
int i = Integer.parseInt(getEnumerationsLimit());
if (i < 0) return XmlBundle.message("negative.number.validation.problem");
} catch(NumberFormatException ex) {
return XmlBundle.message("invalid.number.validation.problem");
}
if (getTargetSchemaName() == null || getTargetSchemaName().length() == 0) {
return XmlBundle.message("result.schema.file.name.is.empty.validation.problem");
}
return null;
}
@NotNull
protected String getHelpId() {
return "webservices.GenerateSchemaFromInstanceDocument";
}
}
| apache-2.0 |
GideonLeGrange/mikrotik-java | src/main/java/examples/SimpleCommandWithResults.java | 717 | package examples;
import java.util.List;
import java.util.Map;
import me.legrange.mikrotik.MikrotikApiException;
/**
* Example 2: A command that returns results. Print all interfaces
*
* @author gideon
*/
public class SimpleCommandWithResults extends Example {
public static void main(String... args) throws Exception {
SimpleCommandWithResults ex = new SimpleCommandWithResults();
ex.connect();
ex.test();
ex.disconnect();
}
private void test() throws MikrotikApiException {
List<Map<String, String>> results = con.execute("/interface/print");
for (Map<String, String> result : results) {
System.out.println(result);
}
}
}
| apache-2.0 |
vanitasvitae/smack-omemo | smack-integration-test/src/main/java/org/jivesoftware/smack/LoginIntegrationTest.java | 2682 | /**
*
* Copyright 2015 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import org.jivesoftware.smack.sasl.SASLError;
import org.jivesoftware.smack.sasl.SASLErrorException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smack.util.StringUtils;
import org.igniterealtime.smack.inttest.AbstractSmackLowLevelIntegrationTest;
import org.igniterealtime.smack.inttest.SmackIntegrationTest;
import org.igniterealtime.smack.inttest.SmackIntegrationTestEnvironment;
public class LoginIntegrationTest extends AbstractSmackLowLevelIntegrationTest {
public LoginIntegrationTest(SmackIntegrationTestEnvironment environment) {
super(environment);
}
/**
* Check that the server is returning the correct error when trying to login using an invalid
* (i.e. non-existent) user.
*
* @throws InterruptedException
* @throws XMPPException
* @throws IOException
* @throws SmackException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
@SmackIntegrationTest
public void testInvalidLogin() throws SmackException, IOException, XMPPException,
InterruptedException, KeyManagementException, NoSuchAlgorithmException {
final String nonExistentUserString = StringUtils.insecureRandomString(24);
XMPPTCPConnectionConfiguration conf = getConnectionConfiguration().setUsernameAndPassword(
nonExistentUserString, "invalidPassword").build();
XMPPTCPConnection connection = new XMPPTCPConnection(conf);
connection.connect();
try {
connection.login();
fail("Exception expected");
}
catch (SASLErrorException e) {
assertEquals(SASLError.not_authorized, e.getSASLFailure().getSASLError());
}
}
}
| apache-2.0 |
savvasdalkitsis/betwixt | app/src/main/java/com/savvasdalkitsis/betwixt/demo/InterpolatorView.java | 7729 | /*
* Copyright (C) 2016 Savvas Dalkitsis
*
* 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.savvasdalkitsis.betwixt.demo;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.v4.graphics.ColorUtils;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Interpolator;
import static com.savvasdalkitsis.betwixt.Interpolators.*;
public class InterpolatorView extends View {
private static final int STEPS = 128;
private final Paint dim = new Paint();
private final Paint linePaint = new Paint();
private final TextPaint textPaint = new TextPaint();
private Interpolator interpolator = linear();
private Paint paint;
private Paint rectPaint;
private final Paint circlePaint = new Paint();
private float progress;
private float radius;
private int animationInset;
private boolean animating;
private final Path linePath = new Path();
private final ValueAnimator playAnimator = ValueAnimator.ofFloat(0, 1);
private String description;
private int textHeight;
private int textPaddingLeft;
public InterpolatorView(Context context) {
super(context);
init();
}
public InterpolatorView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public InterpolatorView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStrokeWidth(getResources().getDimensionPixelSize(R.dimen.interpolation_width));
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);
paint.setStrokeCap(Paint.Cap.ROUND);
linePaint.setColor(Color.WHITE);
linePaint.setStrokeWidth(getResources().getDimensionPixelSize(R.dimen.interpolation_width));
float dashSize = getResources().getDimensionPixelSize(R.dimen.dash_size);
linePaint.setPathEffect(new DashPathEffect(new float[]{dashSize, dashSize}, 0));
linePaint.setStyle(Paint.Style.STROKE);
rectPaint = new Paint();
rectPaint.setARGB(255, 255, 200, 200);
radius = getResources().getDimensionPixelSize(R.dimen.circle_radius);
animationInset = getResources().getDimensionPixelSize(R.dimen.play_inset);
circlePaint.setColor(Color.RED);
circlePaint.setAntiAlias(true);
textPaint.setColor(Color.BLACK);
textPaint.setAntiAlias(true);
textPaint.setTextSize(getResources().getDimensionPixelSize(R.dimen.interpolator_description_size));
textPaddingLeft = getResources().getDimensionPixelSize(R.dimen.text_padding_left);
dim.setColor(ColorUtils.setAlphaComponent(Color.BLACK, 200));
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
play();
}
});
playAnimator.setStartDelay(500);
playAnimator.setDuration(1000);
playAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
progress = animation.getAnimatedFraction();
postInvalidate();
}
});
playAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationCancel(Animator animation) {
endAnimation();
}
@Override
public void onAnimationEnd(final Animator animation) {
postDelayed(new Runnable() {
@Override
public void run() {
endAnimation();
}
}, 500);
}
});
}
private void endAnimation() {
animating = false;
postInvalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
int inset = (getHeight() - rectHeight()) / 2;
canvas.drawRect(getPaddingLeft(), getPaddingTop() + inset,
getWidth() - getPaddingRight(),
getHeight() - inset - getPaddingBottom(), rectPaint);
float x = 0;
float y = 0;
for (int i = 0; i < STEPS; i++) {
float newX = i / (float) STEPS;
float newY = interpolator.getInterpolation(newX);
if (i == 0) {
x = newX;
y = newY;
}
canvas.drawLine(x(x), y(y), x(newX), y(newY), paint);
x = newX;
y = newY;
}
canvas.drawText(description, getPaddingLeft() + textPaddingLeft, getHeight() - textHeight, textPaint);
if (animating) {
canvas.drawRect(getPaddingLeft(), getPaddingTop(), getWidth() - getPaddingRight(),
getHeight() - getPaddingBottom(), dim);
int areaWidth = getWidth() - getPaddingLeft() - getPaddingRight() - animationInset * 2;
float circleX = getPaddingLeft() + animationInset + areaWidth * progress;
linePath.reset();
linePath.moveTo(getPaddingLeft() + animationInset , getPaddingTop());
linePath.lineTo(getPaddingLeft() + animationInset , getHeight() - getPaddingBottom());
linePath.moveTo(getWidth() - getPaddingRight() - animationInset , getPaddingTop());
linePath.lineTo(getWidth() - getPaddingRight() - animationInset , getHeight() - getPaddingBottom());
canvas.drawPath(linePath, linePaint);
canvas.drawCircle(circleX, getHeight() / 2, radius, circlePaint);
}
}
private float y(float y) {
return getPaddingTop() + rectHeight() - (y * rectHeight()) + ((getHeight() - rectHeight()) / 2);
}
private int rectHeight() {
return (int) (getHeight() * 0.75);
}
private float x(float x) {
return getPaddingLeft() + x * (getWidth() - getPaddingLeft() - getPaddingRight());
}
public void setInterpolator(Interpolator interpolator) {
this.interpolator = interpolator;
playAnimator.cancel();
}
public void setDescription(String description) {
this.description = description;
StaticLayout textLayout = new StaticLayout(description, textPaint, Integer.MAX_VALUE, Layout.Alignment.ALIGN_CENTER, 0, 0, false);
textHeight = textLayout.getHeight();
}
public void play() {
if (animating) {
return;
}
progress = 0;
animating = true;
invalidate();
playAnimator.setInterpolator(interpolator);
playAnimator.cancel();
playAnimator.start();
}
}
| apache-2.0 |
devicehive/devicehive-java-server | devicehive-common/src/main/java/com/devicehive/auth/HivePrincipal.java | 6882 | package com.devicehive.auth;
/*
* #%L
* DeviceHive Common Module
* %%
* Copyright (C) 2016 DataArt
* %%
* 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%
*/
import com.devicehive.exceptions.InvalidPrincipalException;
import com.devicehive.vo.PluginVO;
import com.devicehive.vo.UserVO;
import com.hazelcast.nio.serialization.Portable;
import com.hazelcast.nio.serialization.PortableReader;
import com.hazelcast.nio.serialization.PortableWriter;
import java.io.IOException;
import java.security.Principal;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Implements authentication principal for a permission-based security system.
* User - if present, represents the user the is accessing the system
* Actions - if present, represents the set of actions that the principal has permission to execute
* Subnets - if present, represents the set of ips that the principal has permission to access
* Networks - if present, represents the set of networks that the principal has permission to access
* Device types - if present, represents the set of the device types that the principal has permission to access
* Devices - if present, represents the set of the devices that the principal has permission to access
*/
public class HivePrincipal implements Principal, Portable {
public static final int FACTORY_ID = 1;
public static final int CLASS_ID = 3;
private UserVO user;
private Set<HiveAction> actions;
private Set<Long> networkIds;
private Set<Long> deviceTypeIds;
private PluginVO plugin;
private Boolean allNetworksAvailable = false;
private Boolean allDeviceTypesAvailable = true;
public HivePrincipal(UserVO user,
Set<HiveAction> actions,
Set<Long> networkIds,
Set<Long> deviceTypeIds,
PluginVO plugin,
Boolean allNetworksAvailable,
Boolean allDeviceTypesAvailable) {
this.user = user;
this.actions = actions;
this.networkIds = networkIds;
this.deviceTypeIds = deviceTypeIds;
this.plugin = plugin;
if (allNetworksAvailable != null) {
this.allNetworksAvailable = allNetworksAvailable;
}
if (allDeviceTypesAvailable != null) {
this.allDeviceTypesAvailable = allDeviceTypesAvailable;
}
}
public HivePrincipal(Set<HiveAction> actions) {
this.actions = actions;
}
public HivePrincipal(UserVO user) {
this.user = user;
}
public HivePrincipal() {
//anonymous
}
public UserVO getUser() {
return user;
}
public void setUser(UserVO user) {
this.user = user;
}
public Set<HiveAction> getActions() {
return actions;
}
public void setActions(Set<HiveAction> actions) {
this.actions = actions;
}
public Set<Long> getNetworkIds() {
return networkIds;
}
public void setNetworkIds(Set<Long> networkIds) {
this.networkIds = networkIds;
}
public Set<Long> getDeviceTypeIds() {
return deviceTypeIds;
}
public void setDeviceTypeIds(Set<Long> deviceTypeIds) {
this.deviceTypeIds = deviceTypeIds;
}
public PluginVO getPlugin() {
return plugin;
}
public void setPlugin(PluginVO plugin) {
this.plugin = plugin;
}
public Boolean areAllNetworksAvailable() {
return allNetworksAvailable;
}
public void setAllNetworksAvailable(Boolean allNetworksAvailable) {
this.allNetworksAvailable = allNetworksAvailable;
}
public Boolean areAllDeviceTypesAvailable() {
return allDeviceTypesAvailable;
}
public void setAllDeviceTypesAvailable(Boolean allDeviceTypesAvailable) {
this.allDeviceTypesAvailable = allDeviceTypesAvailable;
}
public boolean hasAccessToNetwork(long networkId) {
return allNetworksAvailable || networkIds.contains(networkId);
}
public boolean hasAccessToDeviceType(long deviceTypeId) {
return allDeviceTypesAvailable || deviceTypeIds.contains(deviceTypeId);
}
@Override
public String getName() {
if (user != null) {
return user.getLogin();
}
if (actions != null) {
return actions.toString();
}
if (networkIds != null) {
return networkIds.toString();
}
if (deviceTypeIds != null) {
return deviceTypeIds.toString();
}
return "anonymousPrincipal";
}
public boolean isAuthenticated() {
if (user != null || actions != null || networkIds != null || deviceTypeIds != null) {
return true;
}
throw new InvalidPrincipalException("Unauthorized");
}
@Override
public String toString() {
return "HivePrincipal{" +
"name=" + getName() +
'}';
}
@Override
public int getFactoryId() {
return FACTORY_ID;
}
@Override
public int getClassId() {
return CLASS_ID;
}
@Override
public void writePortable(PortableWriter writer) throws IOException {
// write only required fields for com.devicehive.model.eventbus.Filter
writer.writeBoolean("allNetworksAvailable", allNetworksAvailable);
writer.writeBoolean("allDeviceTypesAvailable", allDeviceTypesAvailable);
writer.writeLongArray("networkIds", networkIds != null ? networkIds.stream().mapToLong(Long::longValue).toArray() : new long[0]);
writer.writeLongArray("deviceTypeIds", deviceTypeIds != null ? deviceTypeIds.stream().mapToLong(Long::longValue).toArray() : new long[0]);
}
@Override
public void readPortable(PortableReader reader) throws IOException {
// read only required fields for com.devicehive.model.eventbus.Filter
allNetworksAvailable = reader.readBoolean("allNetworksAvailable");
allNetworksAvailable = reader.readBoolean("allDeviceTypesAvailable");
networkIds = Arrays.stream(reader.readLongArray("networkIds")).boxed().collect(Collectors.toSet());
deviceTypeIds = Arrays.stream(reader.readLongArray("deviceTypeIds")).boxed().collect(Collectors.toSet());
}
}
| apache-2.0 |
RoyXing/Employment | app/src/main/java/com/employment/presenter/contract/CheckPostContract.java | 297 | package com.employment.presenter.contract;
import com.employment.base.BasePresenter;
import com.employment.base.BaseView;
/**
* Created by roy on 2017/4/9.
*/
public interface CheckPostContract {
interface View extends BaseView{}
interface Presenter extends BasePresenter<View>{}
}
| apache-2.0 |
advantio/advant-orm | src/test/java/io/advant/orm/test/service/ProductService.java | 6337 | /**
* Copyright 2016 Advant I/O
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.advant.orm.test.service;
import io.advant.orm.DBConnection;
import io.advant.orm.Transaction;
import io.advant.orm.exception.OrmException;
import io.advant.orm.test.dao.BrandDAO;
import io.advant.orm.test.dao.CategoryDAO;
import io.advant.orm.test.dao.ProductDAO;
import io.advant.orm.test.dao.impl.BrandDAOImpl;
import io.advant.orm.test.dao.impl.CategoryDAOImpl;
import io.advant.orm.test.dao.impl.ProductDAOImpl;
import io.advant.orm.test.entity.BrandEntity;
import io.advant.orm.test.entity.CategoryEntity;
import io.advant.orm.test.entity.ProductEntity;
import io.advant.orm.test.testcase.PrintUtil;
import org.junit.Assert;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Marco Romagnolo
*/
public class ProductService {
private static final Logger LOGGER = Logger.getLogger(ProductService.class.getName());
private Transaction tx;
private BrandDAO<BrandEntity> brandDAO;
private CategoryDAO<CategoryEntity> categoryDAO;
private ProductDAO<ProductEntity> productDAO;
public ProductService(DBConnection connection) {
tx = new Transaction(connection);
brandDAO = new BrandDAOImpl(connection);
categoryDAO = new CategoryDAOImpl(connection);
productDAO = new ProductDAOImpl(connection);
}
public void insert() throws ServiceException {
try {
tx.setAutoCommit(false);
// Insert Brands
PrintUtil.action("Inserting brands");
BrandEntity brand = new BrandEntity();
brand.setId(1000L);
brand.setName("Brand");
brandDAO.insert(brand);
PrintUtil.result("Inserted brand: " + brand);
BrandEntity brand1 = new BrandEntity();
brand1.setId(1001L);
brand1.setName("Brand1");
brandDAO.insert(brand1);
PrintUtil.result("Inserted brand: " + brand1);
BrandEntity brand2 = new BrandEntity();
brand2.setName("Brand2");
brandDAO.insert(brand2);
PrintUtil.result("Inserted brand: " + brand2);
tx.commit();
} catch (OrmException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
tx.rollback();
throw new ServiceException(e);
}
}
public void update() throws ServiceException {
BrandEntity brand1;
try {
tx.setAutoCommit(false);
brand1 = new BrandEntity();
brand1.setId(1001L);
brand1.setName("Brand1_updated");
} catch (OrmException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
tx.rollback();
throw new ServiceException(e);
}
try {
brandDAO.update(brand1);
} catch (OrmException e) {
Assert.assertTrue("Unsynchronized exception expected", true);
}
try {
BrandEntity brand = brandDAO.find(1000L);
brand.setName("Brand_updated");
brandDAO.update(brand);
PrintUtil.result("Updated brand: " + brand);
brand.setName("Brand_updated2");
brandDAO.update(brand);
PrintUtil.result("Updated brand: " + brand);
tx.commit();
} catch (OrmException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
tx.rollback();
throw new ServiceException(e);
}
}
public void save() throws ServiceException {
try {
PrintUtil.action("Save brand");
BrandEntity brand = new BrandEntity();
brand.setId(1001L);
brand.setName("Brand1_updated");
brandDAO.save(brand);
Assert.assertNotEquals(new ArrayList<>(), brand);
PrintUtil.result("Saved brand:" + brand);
} catch (OrmException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
throw new ServiceException(e);
}
}
public void findAll() throws ServiceException {
try {
PrintUtil.action("Finding all brands");
List<BrandEntity> brands = brandDAO.findAll();
Assert.assertNotEquals(new ArrayList<>(), brands);
PrintUtil.result("Founded brands:" + brands);
} catch (OrmException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
throw new ServiceException(e);
}
}
public void find() throws ServiceException {
try {
PrintUtil.action("Finding brand");
BrandEntity brand = brandDAO.find(1000L);
Assert.assertNotNull(brand);
PrintUtil.result("Found brand:" + brand);
} catch (OrmException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
throw new ServiceException(e);
}
}
public void delete() throws ServiceException {
try {
PrintUtil.action("Deleting brand");
tx.setAutoCommit(false);
BrandEntity brand = new BrandEntity();
brand.setId(1000L);
brandDAO.delete(brand);
tx.commit();
} catch (OrmException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
tx.rollback();
throw new ServiceException(e);
}
}
public void deleteAll() throws ServiceException {
try {
PrintUtil.action("Deleting all brands");
tx.setAutoCommit(false);
brandDAO.deleteAll();
tx.commit();
} catch (OrmException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
throw new ServiceException(e);
}
}
}
| apache-2.0 |
weipoint/j2objc | src/main/java/com/google/devtools/j2objc/Options.java | 15945 | /*
* Copyright 2012 Google Inc. 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.j2objc;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Resources;
import com.google.devtools.j2objc.J2ObjC.Language;
import com.google.devtools.j2objc.util.DeadCodeMap;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The set of tool properties, initialized by the command-line arguments.
* This class was extracted from the main class, to make it easier for
* other classes to access options.
*
* @author Tom Ball
*/
public class Options {
private static Map<String, String> compilerOptions;
private static List<String> sourcePathEntries = Lists.newArrayList( "." );
private static List<String> classPathEntries = Lists.newArrayList( "." );
private static List<String> pluginPathEntries = Lists.newArrayList();
private static String pluginOptionString = "";
private static List<Plugin> plugins = new ArrayList<Plugin>();
private static File outputDirectory = new File(".");
private static Language language = Language.OBJECTIVE_C;
private static boolean printConvertedSources = false;
private static boolean ignoreMissingImports = false;
private static MemoryManagementOption memoryManagementOption = null;
private static boolean emitLineDirectives = false;
private static boolean warningsAsErrors = false;
private static boolean inlineFieldAccess = true;
private static Map<String, String> methodMappings = Maps.newLinkedHashMap();
private static boolean generateTestMain = true;
private static DeadCodeMap deadCodeMap = null;
private static File proGuardUsageFile = null;
private static final String JRE_MAPPINGS_FILE = "JRE.mappings";
private static final List<String> mappingFiles = Lists.newArrayList(JRE_MAPPINGS_FILE);
private static String fileHeader;
private static final String FILE_HEADER_KEY = "file-header";
private static String usageMessage;
private static String helpMessage;
private static final String USAGE_MSG_KEY = "usage-message";
private static final String HELP_MSG_KEY = "help-message";
private static String temporaryDirectory;
private static final String XBOOTCLASSPATH = "-Xbootclasspath:";
private static String bootclasspath = null;
private static Map<String, String> packagePrefixes = Maps.newHashMap();
static {
// Load string resources.
URL propertiesUrl = Resources.getResource(J2ObjC.class, "J2ObjC.properties");
Properties properties = new Properties();
try {
properties.load(propertiesUrl.openStream());
} catch (IOException e) {
System.err.println("unable to access tool properties: " + e);
System.exit(1);
}
fileHeader = properties.getProperty(FILE_HEADER_KEY);
Preconditions.checkNotNull(fileHeader);
usageMessage = properties.getProperty(USAGE_MSG_KEY);
Preconditions.checkNotNull(usageMessage);
helpMessage = properties.getProperty(HELP_MSG_KEY);
Preconditions.checkNotNull(helpMessage);
}
public static enum MemoryManagementOption { REFERENCE_COUNTING, GC, ARC }
private static final MemoryManagementOption DEFAULT_MEMORY_MANAGEMENT_OPTION =
MemoryManagementOption.REFERENCE_COUNTING;
// Share a single logger so it's level is easily configurable.
private static final Logger logger = Logger.getLogger(J2ObjC.class.getName());
/**
* Load the options from a command-line, returning the arguments that were
* not option-related (usually files). If help is requested or an error is
* detected, the appropriate status method is invoked and the app terminates.
* @throws IOException
*/
public static String[] load(String[] args) throws IOException {
compilerOptions = Maps.newHashMap();
compilerOptions.put(org.eclipse.jdt.core.JavaCore.COMPILER_SOURCE, "1.6");
compilerOptions.put(org.eclipse.jdt.core.JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.6");
compilerOptions.put(org.eclipse.jdt.core.JavaCore.COMPILER_COMPLIANCE, "1.6");
logger.setLevel(Level.INFO);
// Create a temporary directory as the sourcepath's first entry, so that
// modified sources will take precedence over regular files.
sourcePathEntries = Lists.newArrayList();
int nArg = 0;
String[] noFiles = new String[0];
while (nArg < args.length) {
String arg = args[nArg];
if (arg.equals("-classpath")) {
if (++nArg == args.length) {
return noFiles;
}
classPathEntries = getPathArgument(args[nArg]);
} else if (arg.equals("-sourcepath")) {
if (++nArg == args.length) {
usage();
}
sourcePathEntries.addAll(getPathArgument(args[nArg]));
} else if (arg.equals("-pluginpath")) {
if (++nArg == args.length) {
usage();
}
pluginPathEntries = getPathArgument(args[nArg]);
} else if (arg.equals("-pluginoptions")) {
if (++nArg == args.length){
usage();
}
pluginOptionString = args[nArg];
} else if (arg.equals("-d")) {
if (++nArg == args.length) {
usage();
}
outputDirectory = new File(args[nArg]);
} else if (arg.equals("--mapping")) {
if (++nArg == args.length) {
usage();
}
mappingFiles.add(args[nArg]);
} else if (arg.equals("--dead-code-report")) {
if (++nArg == args.length) {
usage();
}
proGuardUsageFile = new File(args[nArg]);
} else if (arg.equals("--prefix")) {
if (++nArg == args.length) {
usage();
}
addPrefixOption(args[nArg]);
} else if (arg.equals("--prefixes")) {
if (++nArg == args.length) {
usage();
}
addPrefixesFile(args[nArg]);
} else if (arg.equals("-x")) {
if (++nArg == args.length) {
usage();
}
String s = args[nArg];
if (s.equals("objective-c")) {
language = Language.OBJECTIVE_C;
} else if (s.equals("objective-c++")) {
language = Language.OBJECTIVE_CPP;
} else {
usage();
}
} else if (arg.equals("--print-converted-sources")) {
printConvertedSources = true;
} else if (arg.equals("--ignore-missing-imports")) {
ignoreMissingImports = true;
} else if (arg.equals("-use-reference-counting")) {
checkMemoryManagementOption(MemoryManagementOption.REFERENCE_COUNTING);
} else if (arg.equals("--inline-field-access")) {
inlineFieldAccess = true;
} else if (arg.equals("--no-inline-field-access")) {
inlineFieldAccess = false;
} else if (arg.equals("--generate-test-main")) {
generateTestMain = true;
} else if (arg.equals("--no-generate-test-main")) {
generateTestMain = false;
} else if (arg.equals("-use-gc")) {
checkMemoryManagementOption(MemoryManagementOption.GC);
} else if (arg.equals("-use-arc")) {
checkMemoryManagementOption(MemoryManagementOption.ARC);
} else if (arg.equals("-g")) {
emitLineDirectives = true;
} else if (arg.equals("-Werror")) {
warningsAsErrors = true;
} else if (arg.equals("-q") || arg.equals("--quiet")) {
logger.setLevel(Level.WARNING);
} else if (arg.equals("-t") || arg.equals("--timing-info")) {
logger.setLevel(Level.FINE);
} else if (arg.equals("-v") || arg.equals("--verbose")) {
logger.setLevel(Level.FINEST);
} else if (arg.startsWith(XBOOTCLASSPATH)) {
bootclasspath = arg.substring(XBOOTCLASSPATH.length());
} else if (arg.startsWith("-h") || arg.equals("--help")) {
help();
} else if (arg.startsWith("-")) {
usage();
} else {
break;
}
++nArg;
}
if (memoryManagementOption == null) {
memoryManagementOption = MemoryManagementOption.REFERENCE_COUNTING;
}
int nFiles = args.length - nArg;
String[] files = new String[nFiles];
for (int i = 0; i < nFiles; i++) {
String path = args[i + nArg];
if (path.endsWith(".jar")) {
appendSourcePath(path);
}
files[i] = path;
}
return files;
}
/**
* Add prefix option, which has a format of "<package>=<prefix>".
*/
private static void addPrefixOption(String arg) {
int i = arg.indexOf('=');
// Make sure key and value are at least 1 character.
if (i < 1 || i >= arg.length() - 1) {
usage();
}
String pkg = arg.substring(0, i);
String prefix = arg.substring(i + 1);
addPackagePrefix(pkg, prefix);
}
/**
* Add a file map of packages to their respective prefixes, using the
* Properties file format.
*/
private static void addPrefixesFile(String filename) throws IOException {
Properties props = new Properties();
FileInputStream fis = new FileInputStream(filename);
props.load(fis);
fis.close();
for (String pkg : props.stringPropertyNames()) {
addPackagePrefix(pkg, props.getProperty(pkg));
}
}
/**
* Check that the memory management option wasn't previously set to a
* different value. If okay, then set the option.
*/
private static void checkMemoryManagementOption(MemoryManagementOption option) {
if (memoryManagementOption != null &&
memoryManagementOption != option) {
System.err.println("Multiple memory management options cannot be set.");
usage();
}
setMemoryManagementOption(option);
}
private static void usage() {
System.err.println(usageMessage);
System.exit(1);
}
private static void help() {
System.err.println(helpMessage);
System.exit(0);
}
private static List<String> getPathArgument(String argument) {
List<String> entries = Lists.newArrayList();
for (String entry : Splitter.on(':').split(argument)) {
if (new File(entry).exists()) { // JDT fails with bad path entries.
entries.add(entry);
} else if (entry.startsWith("~/")) {
// Expand bash/csh tildes, which don't get expanded by the shell
// first if in the middle of a path string.
String expanded = System.getProperty("user.home") + entry.substring(1);
if (new File(expanded).exists()) {
entries.add(expanded);
}
}
}
return entries;
}
public static Map<String, String> getCompilerOptions() {
return compilerOptions;
}
public static String[] getSourcePathEntries() {
return sourcePathEntries.toArray(new String[0]);
}
public static void appendSourcePath(String entry) {
sourcePathEntries.add(entry);
}
public static void insertSourcePath(int index, String entry) {
sourcePathEntries.add(index, entry);
}
public static String[] getClassPathEntries() {
return classPathEntries.toArray(new String[classPathEntries.size()]);
}
public static String[] getPluginPathEntries() {
return pluginPathEntries.toArray(new String[pluginPathEntries.size()]);
}
public static String getPluginOptionString() {
return pluginOptionString;
}
public static List<Plugin> getPlugins() {
return plugins;
}
public static File getOutputDirectory() {
return outputDirectory;
}
public static Language getLanguage() {
return language;
}
public static boolean printConvertedSources() {
return printConvertedSources;
}
public static boolean ignoreMissingImports() {
return ignoreMissingImports;
}
public static boolean inlineFieldAccess() {
return inlineFieldAccess;
}
public static boolean useReferenceCounting() {
return memoryManagementOption == MemoryManagementOption.REFERENCE_COUNTING;
}
public static boolean useGC() {
return memoryManagementOption == MemoryManagementOption.GC;
}
public static boolean useARC() {
return memoryManagementOption == MemoryManagementOption.ARC;
}
public static MemoryManagementOption getMemoryManagementOption() {
return memoryManagementOption;
}
// Used by tests.
public static void setMemoryManagementOption(MemoryManagementOption option) {
memoryManagementOption = option;
}
public static void resetMemoryManagementOption() {
memoryManagementOption = DEFAULT_MEMORY_MANAGEMENT_OPTION;
}
public static boolean emitLineDirectives() {
return emitLineDirectives;
}
public static void setEmitLineDirectives(boolean b) {
emitLineDirectives = b;
}
public static boolean treatWarningsAsErrors() {
return warningsAsErrors;
}
public static Map<String, String> getMethodMappings() {
return methodMappings;
}
public static List<String> getMappingFiles() {
return mappingFiles;
}
public static String getUsageMessage() {
return usageMessage;
}
public static String getHelpMessage() {
return helpMessage;
}
public static String getFileHeader() {
return fileHeader;
}
public static boolean generateTestMain() {
return generateTestMain;
}
public static File getProGuardUsageFile() {
return proGuardUsageFile;
}
public static DeadCodeMap getDeadCodeMap() {
return deadCodeMap;
}
public static void setDeadCodeMap(DeadCodeMap map) {
deadCodeMap = map;
}
public static String getBootClasspath() {
return bootclasspath != null ? bootclasspath : System.getProperty("sun.boot.class.path");
}
public static Map<String, String> getPackagePrefixes() {
return packagePrefixes;
}
public static void addPackagePrefix(String pkg, String prefix) {
packagePrefixes.put(pkg, prefix);
}
@VisibleForTesting
public static void clearPackagePrefixes() {
packagePrefixes.clear();
}
public static String getTemporaryDirectory() throws IOException {
if (temporaryDirectory != null) {
return temporaryDirectory;
}
File tmpfile = File.createTempFile("j2objc", Long.toString(System.nanoTime()));
if (!tmpfile.delete()) {
throw new IOException("Could not delete temp file: " + tmpfile.getAbsolutePath());
}
if (!tmpfile.mkdir()) {
throw new IOException("Could not create temp directory: " + tmpfile.getAbsolutePath());
}
temporaryDirectory = tmpfile.getAbsolutePath();
return temporaryDirectory;
}
// Called on exit. This is done here rather than using File.deleteOnExit(),
// so the package directories created by the dead-code-eliminator don't have
// to be tracked.
public static void deleteTemporaryDirectory() {
if (temporaryDirectory != null) {
deleteDir(new File(temporaryDirectory));
temporaryDirectory = null;
}
}
private static void deleteDir(File dir) {
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
deleteDir(f);
} else if (f.getName().endsWith(".java")) {
// Only delete Java files, as other temporary files (like hsperfdata)
// may also be in tmpdir.
f.delete();
}
}
dir.delete(); // Will fail if other files in dir, which is fine.
}
}
| apache-2.0 |
liyanippon/working | java开发资料/dataStu/BottomTabDemo/src/com/xiaowu/bottomtab/demo/MainActivity.java | 5252 | package com.xiaowu.bottomtab.demo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* 主Activity
*
* @author wwj_748
*
*/
public class MainActivity extends FragmentActivity implements OnClickListener {
// 三个tab布局
private RelativeLayout knowLayout, iWantKnowLayout, meLayout;
// 底部标签切换的Fragment
private Fragment knowFragment, iWantKnowFragment, meFragment,
currentFragment;
// 底部标签图片
private ImageView knowImg, iWantKnowImg, meImg;
// 底部标签的文本
private TextView knowTv, iWantKnowTv, meTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
initTab();
}
/**
* 初始化UI
*/
private void initUI() {
knowLayout = (RelativeLayout) findViewById(R.id.rl_know);
iWantKnowLayout = (RelativeLayout) findViewById(R.id.rl_want_know);
meLayout = (RelativeLayout) findViewById(R.id.rl_me);
knowLayout.setOnClickListener(this);
iWantKnowLayout.setOnClickListener(this);
meLayout.setOnClickListener(this);
knowImg = (ImageView) findViewById(R.id.iv_know);
iWantKnowImg = (ImageView) findViewById(R.id.iv_i_want_know);
meImg = (ImageView) findViewById(R.id.iv_me);
knowTv = (TextView) findViewById(R.id.tv_know);
iWantKnowTv = (TextView) findViewById(R.id.tv_i_want_know);
meTv = (TextView) findViewById(R.id.tv_me);
}
/**
* 初始化底部标签
*/
private void initTab() {
if (knowFragment == null) {
knowFragment = new ZhidaoFragment();
}
if (!knowFragment.isAdded()) {
// 提交事务
getSupportFragmentManager().beginTransaction()
.add(R.id.content_layout, knowFragment).commit();
// 记录当前Fragment
currentFragment = knowFragment;
// 设置图片文本的变化
knowImg.setImageResource(R.drawable.btn_know_pre);
knowTv.setTextColor(getResources()
.getColor(R.color.bottomtab_press));
iWantKnowImg.setImageResource(R.drawable.btn_wantknow_nor);
iWantKnowTv.setTextColor(getResources().getColor(
R.color.bottomtab_normal));
meImg.setImageResource(R.drawable.btn_my_nor);
meTv.setTextColor(getResources().getColor(R.color.bottomtab_normal));
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.rl_know: // 知道
clickTab1Layout();
break;
case R.id.rl_want_know: // 我想知道
clickTab2Layout();
break;
case R.id.rl_me: // 我的
clickTab3Layout();
break;
default:
break;
}
}
/**
* 点击第一个tab
*/
private void clickTab1Layout() {
if (knowFragment == null) {
knowFragment = new ZhidaoFragment();
}
addOrShowFragment(getSupportFragmentManager().beginTransaction(), knowFragment);
// 设置底部tab变化
knowImg.setImageResource(R.drawable.btn_know_pre);
knowTv.setTextColor(getResources().getColor(R.color.bottomtab_press));
iWantKnowImg.setImageResource(R.drawable.btn_wantknow_nor);
iWantKnowTv.setTextColor(getResources().getColor(
R.color.bottomtab_normal));
meImg.setImageResource(R.drawable.btn_my_nor);
meTv.setTextColor(getResources().getColor(R.color.bottomtab_normal));
}
/**
* 点击第二个tab
*/
private void clickTab2Layout() {
if (iWantKnowFragment == null) {
iWantKnowFragment = new IWantKnowFragment();
}
addOrShowFragment(getSupportFragmentManager().beginTransaction(), iWantKnowFragment);
knowImg.setImageResource(R.drawable.btn_know_nor);
knowTv.setTextColor(getResources().getColor(R.color.bottomtab_normal));
iWantKnowImg.setImageResource(R.drawable.btn_wantknow_pre);
iWantKnowTv.setTextColor(getResources().getColor(
R.color.bottomtab_press));
meImg.setImageResource(R.drawable.btn_my_nor);
meTv.setTextColor(getResources().getColor(R.color.bottomtab_normal));
}
/**
* 点击第三个tab
*/
private void clickTab3Layout() {
if (meFragment == null) {
meFragment = new MeFragment();
}
addOrShowFragment(getSupportFragmentManager().beginTransaction(), meFragment);
knowImg.setImageResource(R.drawable.btn_know_nor);
knowTv.setTextColor(getResources().getColor(R.color.bottomtab_normal));
iWantKnowImg.setImageResource(R.drawable.btn_wantknow_nor);
iWantKnowTv.setTextColor(getResources().getColor(
R.color.bottomtab_normal));
meImg.setImageResource(R.drawable.btn_my_pre);
meTv.setTextColor(getResources().getColor(R.color.bottomtab_press));
}
/**
* 添加或者显示碎片
*
* @param transaction
* @param fragment
*/
private void addOrShowFragment(FragmentTransaction transaction,
Fragment fragment) {
if (currentFragment == fragment)
return;
if (!fragment.isAdded()) { // 如果当前fragment未被添加,则添加到Fragment管理器中
transaction.hide(currentFragment)
.add(R.id.content_layout, fragment).commit();
} else {
transaction.hide(currentFragment).show(fragment).commit();
}
currentFragment = fragment;
}
}
| apache-2.0 |
shantanusharma/closure-compiler | test/com/google/javascript/jscomp/lint/CheckJSDocStyleTest.java | 34880 | /*
* Copyright 2015 The Closure Compiler 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 com.google.javascript.jscomp.lint;
import static com.google.javascript.jscomp.lint.CheckJSDocStyle.CLASS_DISALLOWED_JSDOC;
import static com.google.javascript.jscomp.lint.CheckJSDocStyle.EXTERNS_FILES_SHOULD_BE_ANNOTATED;
import static com.google.javascript.jscomp.lint.CheckJSDocStyle.INCORRECT_PARAM_NAME;
import static com.google.javascript.jscomp.lint.CheckJSDocStyle.MISSING_JSDOC;
import static com.google.javascript.jscomp.lint.CheckJSDocStyle.MISSING_PARAMETER_JSDOC;
import static com.google.javascript.jscomp.lint.CheckJSDocStyle.MISSING_RETURN_JSDOC;
import static com.google.javascript.jscomp.lint.CheckJSDocStyle.MIXED_PARAM_JSDOC_STYLES;
import static com.google.javascript.jscomp.lint.CheckJSDocStyle.MUST_BE_PRIVATE;
import static com.google.javascript.jscomp.lint.CheckJSDocStyle.MUST_HAVE_TRAILING_UNDERSCORE;
import static com.google.javascript.jscomp.lint.CheckJSDocStyle.OPTIONAL_PARAM_NOT_MARKED_OPTIONAL;
import static com.google.javascript.jscomp.lint.CheckJSDocStyle.PREFER_BACKTICKS_TO_AT_SIGN_CODE;
import static com.google.javascript.jscomp.lint.CheckJSDocStyle.WRONG_NUMBER_OF_PARAMS;
import com.google.javascript.jscomp.CheckLevel;
import com.google.javascript.jscomp.ClosureCodingConvention;
import com.google.javascript.jscomp.CodingConvention;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.CompilerPass;
import com.google.javascript.jscomp.CompilerTestCase;
import com.google.javascript.jscomp.GoogleCodingConvention;
import com.google.javascript.jscomp.parsing.Config;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Test case for {@link CheckJSDocStyle}. */
@RunWith(JUnit4.class)
public final class CheckJSDocStyleTest extends CompilerTestCase {
public CheckJSDocStyleTest() {
super("/** @fileoverview\n * @externs\n */");
}
private CodingConvention codingConvention;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
codingConvention = new GoogleCodingConvention();
setAcceptedLanguage(LanguageMode.ECMASCRIPT_NEXT);
}
@Override
protected CompilerPass getProcessor(Compiler compiler) {
return new CheckJSDocStyle(compiler);
}
@Override
protected CompilerOptions getOptions(CompilerOptions options) {
super.getOptions(options);
options.setParseJsDocDocumentation(Config.JsDocParsing.INCLUDE_DESCRIPTIONS_NO_WHITESPACE);
options.setWarningLevel(CheckJSDocStyle.ALL_DIAGNOSTICS, CheckLevel.WARNING);
return options;
}
@Override
protected CodingConvention getCodingConvention() {
return codingConvention;
}
@Test
public void testValidSuppress_onDeclaration() {
testSame("/** @const */ var global = this;");
testSame("/** @const */ goog.global = this;");
}
@Test
public void testValidSuppress_withES6Modules01() {
testSame("export /** @suppress {missingRequire} */ var x = new y.Z();");
}
@Test
public void testValidSuppress_withES6Modules03() {
testSame("export /** @const @suppress {duplicate} */ var google = {};");
}
@Test
public void testExtraneousClassAnnotations() {
testWarning(
lines(
"/**",
" * @constructor",
" */",
"var X = class {};"),
CLASS_DISALLOWED_JSDOC);
testWarning(
lines(
"/**",
" * @constructor",
" */",
"class X {};"),
CLASS_DISALLOWED_JSDOC);
// TODO(tbreisacher): Warn for @extends too. We need to distinguish between cases like this
// which are totally redundant...
testSame(
lines(
"/**",
" * @extends {Y}",
" */",
"class X extends Y {};"));
// ... and ones like this which are not.
testSame(
lines(
"/**",
" * @extends {Y<number>}",
" */",
"class X extends Y {};"));
testSame(
lines(
"/**",
" * @implements {Z}",
" */",
"class X extends Y {};"));
testSame(
lines(
"/**",
" * @interface",
" * @extends {Y}",
" */",
"class X extends Y {};"));
testSame(
lines(
"/**",
" * @record",
" * @extends {Y}",
" */",
"class X extends Y {};"));
}
@Test
public void testInvalidExtraneousClassAnnotations_withES6Modules() {
testWarning(
lines(
"export",
"/**",
" * @constructor",
" */",
"var X = class {};"),
CLASS_DISALLOWED_JSDOC);
}
@Test
public void testValidExtraneousClassAnnotations_withES6Modules() {
testSame("export /** @extends {Y} */ class X extends Y {};");
}
@Test
public void testNestedArrowFunctions() {
testSame(
lines(
"/**",
" * @param {Object} a",
" * @return {function(Object): boolean}",
" */",
"var haskellStyleEquals = a => b => a == b;"));
}
@Test
public void testNestedArrowFunctions_withES6Modules() {
testSame(
lines(
"export",
"/**",
" * @param {Object} a",
" * @return {function(Object): boolean}",
" */",
"var haskellStyleEquals = a => b => a == b;"));
}
@Test
public void testGetterSetterMissingJsDoc() {
testWarning("class Foo { get twentyone() { return 21; } }", MISSING_JSDOC);
testWarning("class Foo { set someString(s) { this.someString_ = s; } }", MISSING_JSDOC);
testSame("class Foo { /** @return {number} */ get twentyone() { return 21; } }");
testSame("class Foo { /** @param {string} s */ set someString(s) { this.someString_ = s; } }");
}
@Test
public void testGetterSetter_withES6Modules() {
testSame("export class Foo { /** @return {number} */ get twentyone() { return 21; } }");
}
@Test
public void testMissingJsDoc() {
testWarning("function f() {}", MISSING_JSDOC);
testWarning("var f = function() {}", MISSING_JSDOC);
testWarning("let f = function() {}", MISSING_JSDOC);
testWarning("const f = function() {}", MISSING_JSDOC);
testWarning("foo.bar = function() {}", MISSING_JSDOC);
testWarning("Foo.prototype.bar = function() {}", MISSING_JSDOC);
testWarning("class Foo { bar() {} }", MISSING_JSDOC);
testWarning("class Foo { constructor(x) {} }", MISSING_JSDOC);
testWarning("var Foo = class { bar() {} };", MISSING_JSDOC);
testWarning("if (COMPILED) { var f = function() {}; }", MISSING_JSDOC);
testWarning("var f = async function() {};", MISSING_JSDOC);
testWarning("async function f() {};", MISSING_JSDOC);
testWarning("Polymer({ method() {} });", MISSING_JSDOC);
testWarning("Polymer({ method: function() {} });", MISSING_JSDOC);
testSame("/** @return {string} */ function f() {}");
testSame("/** @return {string} */ var f = function() {}");
testSame("/** @return {string} */ let f = function() {}");
testSame("/** @return {string} */ const f = function() {}");
testSame("/** @return {string} */ foo.bar = function() {}");
testSame("/** @return {string} */ Foo.prototype.bar = function() {}");
testSame("class Foo { /** @return {string} */ bar() {} }");
testSame("class Foo { constructor(/** string */ x) {} }");
testSame("var Foo = class { /** @return {string} */ bar() {} };");
testSame("/** @param {string} s */ var f = async function(s) {};");
testSame("/** @param {string} s */ async function f(s) {};");
testSame("Polymer({ /** @return {null} */ method() {} });");
testSame("Polymer({ /** @return {null} */ method: function() {} });");
}
@Test
public void testMissingJsDoc_withES6Modules01() {
testWarning("export function f() {}", MISSING_JSDOC);
}
@Test
public void testMissingJsDoc_withES6Modules02() {
testWarning("export var f = function() {}", MISSING_JSDOC);
}
@Test
public void testMissingJsDoc_withES6Modules03() {
testWarning("export let f = function() {}", MISSING_JSDOC);
}
@Test
public void testMissingJsDoc_withES6Modules04() {
testWarning("export const f = function() {}", MISSING_JSDOC);
}
@Test
public void testMissingJsDoc_withES6Modules09() {
testWarning("export var f = async function() {};", MISSING_JSDOC);
}
@Test
public void testMissingJsDoc_noWarningIfInlineJsDocIsPresent() {
testSame("function /** string */ f() {}");
testSame("function f(/** string */ x) {}");
testSame("var f = function(/** string */ x) {}");
testSame("let f = function(/** string */ x) {}");
testSame("const f = function(/** string */ x) {}");
testSame("foo.bar = function(/** string */ x) {}");
testSame("Foo.prototype.bar = function(/** string */ x) {}");
testSame("class Foo { bar(/** string */ x) {} }");
testSame("var Foo = class { bar(/** string */ x) {} };");
}
@Test
public void testMissingJsDoc_noWarningIfInlineJsDocIsPresent_withES6Modules() {
testSame("export function /** string */ f() {}");
}
@Test
public void testMissingJsDoc_noWarningIfNotTopLevel() {
testSame(inIIFE("function f() {}"));
testSame(inIIFE("var f = function() {}"));
testSame(inIIFE("let f = function() {}"));
testSame(inIIFE("const f = function() {}"));
testSame(inIIFE("foo.bar = function() {}"));
testSame(inIIFE("class Foo { bar() {} }"));
testSame(inIIFE("var Foo = class { bar() {} };"));
testSame("myArray.forEach(function(elem) { alert(elem); });");
testSame(lines(
"Polymer({",
" is: 'example-elem',",
" /** @return {null} */",
" someMethod: function() {},",
"});"));
testSame(lines(
"Polymer({",
" is: 'example-elem',",
" /** @return {null} */",
" someMethod() {},",
"});"));
}
@Test
public void testMissingJsDoc_noWarningIfNotTopLevelAndNoParams() {
testSame(lines(
"describe('a karma test', function() {",
" /** @ngInject */",
" var helperFunction = function($compile, $rootScope) {};",
"})"));
}
@Test
public void testMissingJsDoc_noWarningOnTestFunctions() {
testSame("function testSomeFunctionality() {}");
testSame("var testSomeFunctionality = function() {};");
testSame("let testSomeFunctionality = function() {};");
testSame("window.testSomeFunctionality = function() {};");
testSame("const testSomeFunctionality = function() {};");
testSame("function setUp() {}");
testSame("function tearDown() {}");
testSame("var setUp = function() {};");
testSame("var tearDown = function() {};");
}
@Test
public void testMissingJsDoc_noWarningOnTestFunctions_withES6Modules() {
testSame("export function testSomeFunctionality() {}");
}
@Test
public void testMissingJsDoc_noWarningOnEmptyConstructor() {
testSame("class Foo { constructor() {} }");
}
@Test
public void testMissingJsDoc_noWarningOnEmptyConstructor_withES6Modules() {
testSame("export class Foo { constructor() {} }");
}
@Test
public void testMissingJsDoc_googModule() {
testWarning("goog.module('a.b.c'); function f() {}", MISSING_JSDOC);
testWarning("goog.module('a.b.c'); var f = function() {};", MISSING_JSDOC);
}
@Test
public void testMissingJsDoc_ES6Module01() {
testWarning("export default abc; function f() {}", MISSING_JSDOC);
}
@Test
public void testMissingJsDoc_ES6Module02() {
testWarning("export default abc; var f = function() {};", MISSING_JSDOC);
}
@Test
public void testMissingJsDoc_ES6Module03() {
testWarning("export function f() {};", MISSING_JSDOC);
}
@Test
public void testMissingJsDoc_ES6Module04() {
testWarning("export default function () {}", MISSING_JSDOC);
}
@Test
public void testMissingJsDoc_ES6Module05() {
testWarning("export default (foo) => { alert(foo); }", MISSING_JSDOC);
}
@Test
public void testMissingJsDoc_googModule_noWarning() {
testSame("goog.module('a.b.c'); /** @type {function()} */ function f() {}");
testSame("goog.module('a.b.c'); /** @type {function()} */ var f = function() {};");
}
@Test
public void testMissingJsDoc_ES6Module_noWarning01() {
testSame("export default abc; /** @type {function()} */ function f() {}");
}
@Test
public void testMissingJsDoc_ES6Module_noWarning02() {
testSame("export default abc; /** @type {function()} */ var f = function() {};");
}
private static String inIIFE(String js) {
return "(function() {\n" + js + "\n})()";
}
@Test
public void testMissingParam_noWarning() {
testSame(lines(
"/**",
" * @param {string} x",
" * @param {string} y",
" */",
"function f(x, y) {}"));
testSame(lines(
"/** @override */",
"Foo.bar = function(x, y) {}"));
testSame(lines(
"/**",
" * @param {string=} x",
" */",
"function f(x = 1) {}"));
testSame(lines(
"/**",
" * @param {number=} x",
" * @param {number=} y",
" * @param {number=} z",
" */",
"function f(x = 1, y = 2, z = 3) {}"));
testSame(lines(
"/**",
" * @param {...string} args",
" */",
"function f(...args) {}"));
testSame(lines(
"(function() {",
" myArray.forEach(function(elem) { alert(elem); });",
"})();"));
testSame(lines(
"(function() {",
" myArray.forEach(elem => alert(elem));",
"})();"));
testSame("/** @type {function(number)} */ function f(x) {}");
testSame("function f(/** string */ inlineArg) {}");
testSame("/** @export */ function f(/** string */ inlineArg) {}");
testSame("class Foo { constructor(/** string */ inlineArg) {} }");
testSame("class Foo { method(/** string */ inlineArg) {} }");
testSame("/** @export */ class Foo { constructor(/** string */ inlineArg) {} }");
testSame("class Foo { /** @export */ method(/** string */ inlineArg) {} }");
}
@Test
public void testMissingParam_noWarning_withES6Modules() {
testSame("export class Foo { /** @export */ method(/** string */ inlineArg) {} }");
}
@Test
public void testMissingParam() {
testWarning(
lines(
"/**",
" * @param {string} x",
// No @param for y.
" */",
"function f(x, y) {}"),
WRONG_NUMBER_OF_PARAMS);
testWarning(
lines(
"/**",
" * @param {string} x",
" */",
"function f(x = 1) {}"),
OPTIONAL_PARAM_NOT_MARKED_OPTIONAL);
testWarning(
lines(
"/**",
" * @param {string} x",
// No @param for y.
" */",
"function f(x, y = 1) {}"),
WRONG_NUMBER_OF_PARAMS);
testWarning("function f(/** string */ x, y) {}", MISSING_PARAMETER_JSDOC);
testWarning("function f(x, /** string */ y) {}", MISSING_PARAMETER_JSDOC);
testWarning("function /** string */ f(x) {}", MISSING_PARAMETER_JSDOC);
testWarning(inIIFE("function f(/** string */ x, y) {}"), MISSING_PARAMETER_JSDOC);
testWarning(inIIFE("function f(x, /** string */ y) {}"), MISSING_PARAMETER_JSDOC);
testWarning(inIIFE("function /** string */ f(x) {}"), MISSING_PARAMETER_JSDOC);
}
@Test
public void testMissingParam_withES6Modules01() {
testWarning(
lines(
"export",
"/**",
" * @param {string} x",
// No @param for y.
" */",
"function f(x, y) {}"),
WRONG_NUMBER_OF_PARAMS);
}
@Test
public void testMissingParam_withES6Modules02() {
testWarning(
"export /** @param {string} x */ function f(x = 1) {}",
OPTIONAL_PARAM_NOT_MARKED_OPTIONAL);
}
@Test
public void testMissingParam_withES6Modules03() {
testWarning("export function f(/** string */ x, y) {}", MISSING_PARAMETER_JSDOC);
}
@Test
public void testMissingParamWithDestructuringPattern() {
testWarning(
lines(
"/**",
" * @param {string} namedParam",
" * @return {void}",
" */",
"function f(namedParam, {destructuring:pattern}) {",
"}"),
WRONG_NUMBER_OF_PARAMS);
testWarning(
lines(
"/**",
" * @param {string} namedParam",
" * @return {void}",
" */",
"function f({destructuring:pattern}, namedParam) {",
"}"),
WRONG_NUMBER_OF_PARAMS);
testWarning(
lines(
"/**",
" * @param {string} namedParam",
" * @return {void}",
" */",
"function f(namedParam, [pattern]) {",
"}"),
WRONG_NUMBER_OF_PARAMS);
testWarning(
lines(
"/**",
" * @param {string} namedParam",
" * @return {void}",
" */",
"function f([pattern], namedParam) {",
"}"),
WRONG_NUMBER_OF_PARAMS);
testWarning(
lines(
"/**",
" * @param {{",
" * a: (string|undefined),",
" * b: (number|undefined),",
" * c: (boolean|undefined)",
" * }} obj",
" */",
"function create({a = 'hello', b = 8, c = false} = {}) {}"),
OPTIONAL_PARAM_NOT_MARKED_OPTIONAL);
// Same as above except there's an '=' to indicate that it's optional.
testSame(
lines(
"/**",
" * @param {{",
" * a: (string|undefined),",
" * b: (number|undefined),",
" * c: (boolean|undefined)",
" * }=} obj",
" */",
"function create({a = 'hello', b = 8, c = false} = {}) {}"));
}
@Test
public void testInvalidMissingParamWithDestructuringPattern_withES6Modules01() {
testWarning(
lines(
"export",
"/**",
" * @param {string} namedParam",
" * @return {void}",
" */",
"function f(namedParam, {destructuring:pattern}) {",
"}"),
WRONG_NUMBER_OF_PARAMS);
}
@Test
public void testInvalidMissingParamWithDestructuringPattern_withES6Modules02() {
testWarning(
lines(
"export",
"/**",
" * @param {{",
" * a: (string|undefined),",
" * b: (number|undefined),",
" * c: (boolean|undefined)",
" * }} obj",
" */",
"function create({a = 'hello', b = 8, c = false} = {}) {}"),
OPTIONAL_PARAM_NOT_MARKED_OPTIONAL);
}
@Test
public void testValidMissingParamWithDestructuringPattern_withES6Modules() {
testSame(
lines(
"export",
"/**",
" * @param {{",
" * a: (string|undefined),",
" * b: (number|undefined),",
" * c: (boolean|undefined)",
" * }=} obj",
" */",
"function create({a = 'hello', b = 8, c = false} = {}) {}"));
}
@Test
public void testMissingParamWithDestructuringPatternWithDefault() {
testWarning(
lines(
"/**",
" * @param {string} namedParam",
" * @return {void}",
" */",
"function f(namedParam, {destructuring:pattern} = defaultValue) {",
"}"),
WRONG_NUMBER_OF_PARAMS);
testWarning(
lines(
"/**",
" * @param {string} namedParam",
" * @return {void}",
" */",
"function f(namedParam, [pattern] = defaultValue) {",
"}"),
WRONG_NUMBER_OF_PARAMS);
}
@Test
public void testMissingParamWithDestructuringPatternWithDefault_withES6Modules() {
testWarning(
lines(
"export",
"/**",
" * @param {string} namedParam",
" * @return {void}",
" */",
"function f(namedParam, {destructuring:pattern} = defaultValue) {",
"}"),
WRONG_NUMBER_OF_PARAMS);
}
@Test
public void testParamWithNoTypeInfo() {
testSame(
lines(
"/**",
" * @param x A param with no type information.",
" */",
"function f(x) { }"));
}
@Test
public void testParamWithNoTypeInfo_withES6Modules() {
testSame(
lines(
"export",
"/**",
" * @param x A param with no type information.",
" */",
"function f(x) { }"));
}
@Test
public void testMissingPrivate_noWarningWithClosureConvention() {
codingConvention = new ClosureCodingConvention();
testSame(
lines(
"/**",
" * @return {number}",
" * @private",
" */",
"X.prototype.foo = function() { return 0; }"));
}
@Test
public void testMissingPrivate() {
testWarning(
lines(
"/** @return {number} */",
"X.prototype.foo_ = function() { return 0; }"),
MUST_BE_PRIVATE);
testWarning(
lines(
"/** @type {?number} */",
"X.prototype.foo_ = null;"),
MUST_BE_PRIVATE);
testWarning(
lines(
"/**",
" * @return {number}",
" * @private",
" */",
"X.prototype.foo = function() { return 0; }"),
MUST_HAVE_TRAILING_UNDERSCORE);
testWarning(
lines(
"/**",
" * @type {number}",
" * @private",
" */",
"X.prototype.foo = 0;"),
MUST_HAVE_TRAILING_UNDERSCORE);
testSame(
lines(
"/**",
" * @return {number}",
" * @private",
" */",
"X.prototype.foo_ = function() { return 0; }"));
testSame(
lines(
"/**",
" * @type {number}",
" * @private",
" */",
"X.prototype.foo_ = 0;"));
testSame(
lines(
"/** @type {number} */",
"X.prototype['@some_special_property'] = 0;"));
}
@Test
public void testMissingPrivate_class() {
testWarning(
lines(
"class Example {",
" /** @return {number} */",
" foo_() { return 0; }",
"}"),
MUST_BE_PRIVATE);
testWarning(
lines(
"class Example {",
" /** @return {number} */",
" get foo_() { return 0; }",
"}"),
MUST_BE_PRIVATE);
testWarning(
lines(
"class Example {",
" /** @param {number} val */",
" set foo_(val) {}",
"}"),
MUST_BE_PRIVATE);
testWarning(
lines(
"class Example {",
" /**",
" * @return {number}",
" * @private",
" */",
" foo() { return 0; }",
"}"),
MUST_HAVE_TRAILING_UNDERSCORE);
testWarning(
lines(
"class Example {",
" /**",
" * @return {number}",
" * @private",
" */",
" get foo() { return 0; }",
"}"),
MUST_HAVE_TRAILING_UNDERSCORE);
testWarning(
lines(
"class Example {",
" /**",
" * @param {number} val",
" * @private",
" */",
" set foo(val) { }",
"}"),
MUST_HAVE_TRAILING_UNDERSCORE);
}
@Test
public void testMissingPrivate_class_withES6Modules01() {
testWarning(
"export class Example { /** @return {number} */ foo_() { return 0; } }",
MUST_BE_PRIVATE);
}
@Test
public void testMissingPrivate_class_withES6Modules02() {
testWarning(
lines(
"export class Example {",
" /**",
" * @return {number}",
" * @private",
" */",
" foo() { return 0; }",
"}"),
MUST_HAVE_TRAILING_UNDERSCORE);
}
@Test
public void testMissingPrivate_dontWarnOnObjectLiteral() {
testSame(
lines(
"var obj = {",
" /** @return {number} */",
" foo_() { return 0; }",
"}"));
}
@Test
public void testMissingPrivate_dontWarnOnObjectLiteral_withES6Modules() {
testSame("export var obj = { /** @return {number} */ foo_() { return 0; } }");
}
@Test
public void testOptionalArgs() {
testSame(
lines(
"/**",
" * @param {number=} n",
" */",
"function f(n) {}"));
testSame(
lines(
"/**",
" * @param {number} opt_n",
" */",
"function f(opt_n) {}"),
OPTIONAL_PARAM_NOT_MARKED_OPTIONAL);
testSame(lines(
"/**",
" * @param {number=} opt_n",
" */",
"function f(opt_n) {}"));
}
@Test
public void testValidOptionalArgs_withES6Modules() {
testSame("export /** @param {number=} n */ function f(n) {}");
}
@Test
public void testInvalidOptionalArgs_withES6Modules() {
testSame(
"export /** @param {number} opt_n */ function f(opt_n) {}",
OPTIONAL_PARAM_NOT_MARKED_OPTIONAL);
}
@Test
public void testParamsOutOfOrder() {
testWarning(
lines(
"/**",
" * @param {?} second",
" * @param {?} first",
" */",
"function f(first, second) {}"),
INCORRECT_PARAM_NAME);
}
@Test
public void testParamsOutOfOrder_withES6Modules() {
testWarning(
lines(
"export",
"/**",
" * @param {?} second",
" * @param {?} first",
" */",
"function f(first, second) {}"),
INCORRECT_PARAM_NAME);
}
@Test
public void testMixedStyles() {
testWarning(
lines(
"/**",
" * @param {?} first",
" * @param {string} second",
" */",
"function f(first, /** string */ second) {}"),
MIXED_PARAM_JSDOC_STYLES);
}
@Test
public void testMixedStyles_withES6Modules() {
testWarning(
lines(
"export",
"/**",
" * @param {?} first",
" * @param {string} second",
" */",
"function f(first, /** string */ second) {}"),
MIXED_PARAM_JSDOC_STYLES);
}
@Test
public void testDestructuring() {
testSame(
lines(
"/**",
" * @param {{x: number, y: number}} point",
" */",
"function getDistanceFromZero({x, y}) {}"));
testSame("function getDistanceFromZero(/** {x: number, y: number} */ {x, y}) {}");
}
@Test
public void testDestructuring_withES6Modules() {
testSame("export function getDistanceFromZero(/** {x: number, y: number} */ {x, y}) {}");
}
@Test
public void testMissingReturn_functionStatement_noWarning() {
testSame("/** @param {number} x */ function f(x) {}");
testSame("/** @constructor */ function f() {}");
testSame("/** @param {number} x */ function f(x) { function bar() { return x; } }");
testSame("/** @param {number} x */ function f(x) { return; }");
testSame("/** @param {number} x\n * @return {number} */ function f(x) { return x; }");
testSame("/** @param {number} x */ function /** number */ f(x) { return x; }");
testSame("/** @inheritDoc */ function f(x) { return x; }");
testSame("/** @override */ function f(x) { return x; }");
}
@Test
public void testMissingReturn_functionStatement_noWarning_withES6Modules() {
testSame("export /** @param {number} x */ function f(x) {}");
}
@Test
public void testMissingReturn_assign_noWarning() {
testSame("/** @param {number} x */ f = function(x) {}");
testSame("/** @constructor */ f = function() {}");
testSame("/** @param {number} x */ f = function(x) { function bar() { return x; } }");
testSame("/** @param {number} x */ f = function(x) { return; }");
testSame("/** @param {number} x\n * @return {number} */ f = function(x) { return x; }");
testSame("/** @inheritDoc */ f = function(x) { return x; }");
testSame("/** @override */ f = function(x) { return x; }");
}
@Test
public void testMissingReturn_var_noWarning() {
testSame("/** @param {number} x */ var f = function(x) {}");
testSame("/** @constructor */ var f = function() {}");
testSame("/** @param {number} x */ var f = function(x) { function bar() { return x; } }");
testSame("/** @param {number} x */ var f = function(x) { return; }");
testSame("/** @param {number} x\n * @return {number} */ var f = function(x) { return x; }");
testSame("/** @const {function(number): number} */ var f = function(x) { return x; }");
testSame("/** @inheritDoc */ var f = function(x) { return x; }");
testSame("/** @override */ var f = function(x) { return x; }");
}
@Test
public void testMissingReturn_constructor_noWarning() {
testSame("/** @constructor */ var C = function() { return null; }");
}
@Test
public void testMissingReturn_class_constructor_noWarning() {
testSame("class C { /** @param {Array} x */ constructor(x) { return x; } }");
}
@Test
public void testMissingReturn_var_noWarning_withES6Modules() {
testSame("export /** @param {number} x */ var f = function(x) {}");
}
@Test
public void testMissingReturn_functionStatement() {
testWarning("/** @param {number} x */ function f(x) { return x; }", MISSING_RETURN_JSDOC);
testWarning(
lines(
"/** @param {number} x */",
"function f(x) {",
" /** @param {number} x */",
" function bar(x) {",
" return x;",
" }",
"}"),
MISSING_RETURN_JSDOC);
testWarning(
"/** @param {number} x */ function f(x) { if (true) { return x; } }", MISSING_RETURN_JSDOC);
testWarning(
"/** @param {number} x @constructor */ function f(x) { return x; }", MISSING_RETURN_JSDOC);
}
@Test
public void testMissingReturn_functionStatement_withES6Modules() {
testWarning(
"export /** @param {number} x */ function f(x) { return x; }", MISSING_RETURN_JSDOC);
}
@Test
public void testMissingReturn_assign() {
testWarning("/** @param {number} x */ f = function(x) { return x; }", MISSING_RETURN_JSDOC);
testWarning(
lines(
"/** @param {number} x */",
"function f(x) {",
" /** @param {number} x */",
" bar = function(x) {",
" return x;",
" }",
"}"),
MISSING_RETURN_JSDOC);
testWarning(
"/** @param {number} x */ f = function(x) { if (true) { return x; } }",
MISSING_RETURN_JSDOC);
testWarning(
"/** @param {number} x @constructor */ f = function(x) { return x; }",
MISSING_RETURN_JSDOC);
}
@Test
public void testMissingReturn_assign_withES6Modules() {
testWarning(
lines(
"/** @param {number} x */",
"export",
"function f(x) {",
" /** @param {number} x */",
" bar = function(x) {",
" return x;",
" }",
"}"),
MISSING_RETURN_JSDOC);
}
@Test
public void testMissingReturn_var() {
testWarning("/** @param {number} x */ var f = function(x) { return x; }", MISSING_RETURN_JSDOC);
testWarning(
lines(
"/** @param {number} x */",
"function f(x) {",
" /** @param {number} x */",
" var bar = function(x) {",
" return x;",
" }",
"}"),
MISSING_RETURN_JSDOC);
testWarning(
"/** @param {number} x */ var f = function(x) { if (true) { return x; } }",
MISSING_RETURN_JSDOC);
testWarning(
"/** @param {number} x @constructor */ var f = function(x) { return x; }",
MISSING_RETURN_JSDOC);
}
@Test
public void testMissingReturn_var_withES6Modules() {
testWarning(
"export /** @param {number} x */ var f = function(x) { return x; }", MISSING_RETURN_JSDOC);
}
@Test
public void testExternsAnnotation() {
test(
externs("function Example() {}"),
srcs(""),
warning(EXTERNS_FILES_SHOULD_BE_ANNOTATED));
testSame(
externs(
"/** @fileoverview Some super cool externs.\n * @externs\n */ function Example() {}"),
srcs(""));
testSame(
externs(
lines(
"/** @fileoverview Some super cool externs.\n * @externs\n */",
"/** @constructor */ function Example() {}",
"/** @param {number} x */ function example2(x) {}")),
srcs(""));
test(
new String[] {
"/** @fileoverview Some externs.\n * @externs\n */ /** @const */ var example;",
"/** @fileoverview Some more.\n * @externs\n */ /** @const */ var example2;",
},
new String[] {});
}
@Test
public void testInvalidExternsAnnotation_withES6Modules() {
test(
externs("export function Example() {}"),
srcs(""),
warning(EXTERNS_FILES_SHOULD_BE_ANNOTATED));
}
@Test
public void testValidExternsAnnotation_withES6Modules() {
testSame(
externs(
lines(
"export /** @fileoverview Some super cool externs.",
" * @externs",
" */",
"function Example() {}")),
srcs(""));
}
@Test
public void testAtSignCodeDetectedWhenPresent() {
testWarning(
"/** blah blah {@code blah blah} blah blah */ function f() {}",
PREFER_BACKTICKS_TO_AT_SIGN_CODE);
}
}
| apache-2.0 |
myteksp/util.strings | src/main/java/com/gf/util/string/StartArgs.java | 3120 | package com.gf.util.string;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
public final class StartArgs {
private final ConcurrentHashMap<String, List<String>> cache;
private final String[] args;
private final char splitOn;
public StartArgs(final String[] args, final char splitOn){
this.cache = new ConcurrentHashMap<String, List<String>>();
this.args = args;
this.splitOn = splitOn;
}
public StartArgs(final String[] args){
this(args, '=');
}
public final boolean getBoolean(final String key){
final String val = getOneArg(key);
if (val == null)
throw new RuntimeException("arg '" + key + "' not found.");
return Boolean.parseBoolean(val);
}
public final long getLong(final String key){
final String val = getOneArg(key);
if (val == null)
throw new RuntimeException("arg '" + key + "' not found.");
return Long.parseLong(val);
}
public final double getDouble(final String key){
final String val = getOneArg(key);
if (val == null)
throw new RuntimeException("arg '" + key + "' not found.");
return Double.parseDouble(val);
}
public final int getInt(final String key){
final String val = getOneArg(key);
if (val == null)
throw new RuntimeException("arg '" + key + "' not found.");
return Integer.parseInt(val);
}
public final List<String> setOneArg(final String key, final String val){
final List<String> n = new ArrayList<String>(1);
n.add(val);
return setArgs(key, n);
}
public final List<String> setArgs(final String key, final List<String> arg){
return cache.put(key.toLowerCase(), arg);
}
public final List<String> getArgs(final String key){
final String l_key = key.toLowerCase();
List<String> cached = cache.get(l_key);
if (cached != null)
return cached;
cached = new ArrayList<String>();
cache.put(l_key, cached);
for(final String val:args){
final String[] splitted = Splitter.split(val, splitOn);
switch(splitted.length){
case 2:
if (l_key.equalsIgnoreCase(splitted[0])){
cached.add(splitted[1]);
}
break;
}
}
return cached;
}
public final String getOneArg(final String key){
final List<String> result = getArgs(key);
if (result.size() > 0)
return result.get(0);
return null;
}
public final String get(final int index){
return args[index];
}
public final void set(final int index, final String value){
args[index] = value;
}
public final int getInt(final int index){
return Integer.parseInt(get(index));
}
public final double getDouble(final int index){
return Double.parseDouble(get(index));
}
public final boolean getBoolean(final int index){
return Boolean.parseBoolean(get(index));
}
public final void set(final int index, final double value){
set(index, Double.toString(value));
}
public final void set(final int index, final int value){
set(index, Integer.toString(value));
}
public final void set(final int index, final boolean value){
set(index, Boolean.toString(value));
}
public final int size(){
return args.length;
}
}
| apache-2.0 |
dkincade/pentaho-hadoop-shims | common/common-shim/src/test/java/org/pentaho/hadoop/mapreduce/GenericTransReduceTest.java | 11918 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.hadoop.mapreduce;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Reporter;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogLevel;
import org.pentaho.di.core.logging.LoggingRegistry;
import org.pentaho.di.trans.TransConfiguration;
import org.pentaho.di.trans.TransMeta;
/**
* User: Dzmitry Stsiapanau Date: 10/29/14 Time: 12:44 PM
*/
@SuppressWarnings( { "unchecked", "rawtypes" } )
public class GenericTransReduceTest {
private static final String REDUCE_OUTPUT_STEPNAME = "reduce-output-stepname";
private static final String REDUCE_INPUT_STEPNAME = "reduce-input-stepname";
private static final String REDUCER_TRANS_META_NAME = "Reducer transformation";
/**
* We expect 4 log channels per run. The total should never grow past logChannelsBefore + 4.
*/
final int EXPECTED_CHANNELS_PER_RUN = 4;
/**
* Run the reducer this many times
*/
final int RUNS = 10;
private static TransConfiguration reducerTransExecConfig;
private Reporter reporterMock = mock( Reporter.class );
private GenericTransReduce genericTransReduce;
private JobConf mrJobConfig;
private TransMeta transMeta;
private MockOutputCollector outputCollectorMock = new MockOutputCollector();
@BeforeClass
public static void before() throws KettleException {
KettleEnvironment.init();
reducerTransExecConfig = MRTestUtil.getTransExecConfig( MRTestUtil.getTransMeta( REDUCER_TRANS_META_NAME ) );
}
@Before
public void setUp() throws KettleException, IOException {
genericTransReduce = new GenericTransReduce();
mrJobConfig = new JobConf();
// Turn off all debug messages from PentahoMapRunnable to reduce unit test logs
mrJobConfig.set( "logLevel", LogLevel.ERROR.name() );
}
@Test
public void testClose() throws KettleException, IOException {
GenericTransReduce gtr = new GenericTransReduce();
try {
gtr.close();
} catch ( NullPointerException ex ) {
ex.printStackTrace();
fail( " Null pointer on close look PDI-13080 " + ex.getMessage() );
}
}
@Test
public void testReducerOutputClasses() throws IOException, KettleException {
mrJobConfig.set( MRTestUtil.TRANSFORMATION_REDUCE_XML, reducerTransExecConfig.getXML() );
mrJobConfig.setOutputKeyClass( Text.class );
mrJobConfig.setOutputValueClass( LongWritable.class );
genericTransReduce.configure( mrJobConfig );
assertEquals( mrJobConfig.getOutputKeyClass(), genericTransReduce.getOutClassK() );
assertEquals( mrJobConfig.getOutputValueClass(), genericTransReduce.getOutClassV() );
}
@Test
public void testReducerInputOutputSteps() throws IOException, KettleException {
mrJobConfig.set( MRTestUtil.TRANSFORMATION_REDUCE_XML, reducerTransExecConfig.getXML() );
mrJobConfig.set( MRTestUtil.TRANSFORMATION_REDUCE_INPUT_STEPNAME, REDUCE_INPUT_STEPNAME );
mrJobConfig.set( MRTestUtil.TRANSFORMATION_REDUCE_OUTPUT_STEPNAME, REDUCE_OUTPUT_STEPNAME );
assertNull( genericTransReduce.getInputStepName() );
assertNull( genericTransReduce.getOutputStepName() );
genericTransReduce.configure( mrJobConfig );
assertEquals( REDUCE_INPUT_STEPNAME, genericTransReduce.getInputStepName() );
assertEquals( REDUCE_OUTPUT_STEPNAME, genericTransReduce.getOutputStepName() );
}
@Test
public void testReducer_null_output_value() throws Exception {
transMeta = new TransMeta( getClass().getResource( MRTestUtil.PATH_TO_NULL_TEST_TRANSFORMATION ).toURI().getPath() );
MRTestUtil.configJobReducerBaseCase( transMeta, mrJobConfig, genericTransReduce );
genericTransReduce.reduce( MRTestUtil.KEY_TO_NULL, Arrays.asList( MRTestUtil.VALUE_TO_NULL ).iterator(), outputCollectorMock, reporterMock );
genericTransReduce.close();
outputCollectorMock.close();
Exception ex = genericTransReduce.getException();
assertNull( "Exception thrown", ex );
assertEquals( "Received output when we didn't expect any. <null>s aren't passed through.", 0, outputCollectorMock.getCollection().size() );
}
@Test
public void testReducer_not_null_outputValues() throws Exception {
transMeta = new TransMeta( getClass().getResource( MRTestUtil.PATH_TO_NOT_NULL_TEST_TRANSFORMATION ).toURI().getPath() );
MRTestUtil.configJobReducerBaseCase( transMeta, mrJobConfig, genericTransReduce );
Text expectedKey = new Text( "test" );
List<IntWritable> expectedValue = Arrays.asList( new IntWritable( 8 ), new IntWritable( 9 ) );
genericTransReduce.reduce( expectedKey, expectedValue.iterator(), outputCollectorMock, reporterMock );
genericTransReduce.close();
outputCollectorMock.close();
Exception ex = genericTransReduce.getException();
assertNull( "Exception thrown", ex );
assertEquals( 1, outputCollectorMock.getCollection().size() );
assertEquals( expectedValue, outputCollectorMock.getCollection().get( expectedKey ) );
}
@Test
public void testReducer_WordCount() throws Exception {
transMeta = new TransMeta( getClass().getResource( MRTestUtil.PATH_TO_WORDCOUNT_REDUCER_TEST_TRANSFORMATION ).toURI().getPath() );
MRTestUtil.configJobReducerBaseCase( transMeta, mrJobConfig, genericTransReduce );
Text wordToCount = new Text( "test" );
IntWritable[] wordCountArray = new IntWritable[] { new IntWritable( 8 ), new IntWritable( 9 ), new IntWritable( 1 ) };
IntWritable expectedWordCount = new IntWritable( Arrays.stream( wordCountArray ).mapToInt( IntWritable::get ).sum() );
genericTransReduce.reduce( wordToCount, Arrays.asList( wordCountArray ).iterator(), outputCollectorMock, reporterMock );
genericTransReduce.close();
outputCollectorMock.close();
Exception ex = genericTransReduce.getException();
assertNull( "Exception thrown", ex );
assertEquals( 1, outputCollectorMock.getCollection().size() );
assertEquals( expectedWordCount, outputCollectorMock.getCollection().get( wordToCount ).get( 0 ) );
}
@Test
public void testLogChannelLeaking() throws Exception {
transMeta = new TransMeta( getClass().getResource( MRTestUtil.PATH_TO_WORDCOUNT_REDUCER_TEST_TRANSFORMATION ).toURI().getPath() );
MRTestUtil.configJobReducerBaseCase( transMeta, mrJobConfig, genericTransReduce );
int logChannels = LoggingRegistry.getInstance().getMap().size();
Text wordToCount = null;
int expectedOutputCollectorMockSize = 0;
assertEquals( "Incorrect output", expectedOutputCollectorMockSize, outputCollectorMock.getCollection().size() );
for ( int i = 0; i < RUNS; i++ ) {
// set up test key and value for reducer as a pair of elements: word1-->[1], word2-->[1,2] ...,
// wordN-->[1,...,N-1,N]
wordToCount = new Text( "word" + ( i + 1 ) );
List<IntWritable> wordCounts = IntStream.rangeClosed( 1, i + 1 ).mapToObj( value -> new IntWritable( value ) ).collect( Collectors.toList() );
IntWritable expectedWordCount = new IntWritable( wordCounts.stream().mapToInt( IntWritable::get ).sum() );
genericTransReduce.reduce( wordToCount, wordCounts.iterator(), outputCollectorMock, reporterMock );
genericTransReduce.close();
expectedOutputCollectorMockSize++;
assertNull( "Exception thrown", genericTransReduce.getException() );
assertEquals( "Incorrect output", expectedOutputCollectorMockSize, outputCollectorMock.getCollection().size() );
assertEquals( expectedWordCount, outputCollectorMock.getCollection().get( wordToCount ).get( 0 ) );
assertEquals( "LogChannels are not being cleaned up. On Run #" + ( i + 1 ) + " we have too many.", logChannels + EXPECTED_CHANNELS_PER_RUN, LoggingRegistry.getInstance().getMap().size() );
}
outputCollectorMock.close();
assertEquals( logChannels + EXPECTED_CHANNELS_PER_RUN, LoggingRegistry.getInstance().getMap().size() );
}
@Test
public void testReducerNoOutputStep() throws KettleException, URISyntaxException {
//Turn off displaying stack trace of expected exception to reduce unit test logs
mrJobConfig.set( "debug", "false" );
try {
transMeta = new TransMeta( getClass().getResource( MRTestUtil.PATH_TO_NO_OUTPUT_STEP_TEST_TRANSFORMATION ).toURI().getPath() );
MRTestUtil.configJobReducerBaseCase( transMeta, mrJobConfig, genericTransReduce );
genericTransReduce.reduce( new Text( "key" ), Arrays.asList( new IntWritable( 8 ) ).iterator(), outputCollectorMock, reporterMock );
genericTransReduce.close();
fail( "Should have thrown an exception " );
} catch ( IOException e ) {
assertTrue( "Test for KettleException", e.getMessage().contains( "Output step not defined in transformation" ) );
}
}
@Test
public void testReducerBadInjectorFields() throws KettleException, URISyntaxException {
//Turn off displaying stack trace of expected exception to reduce unit test logs
mrJobConfig.set( "debug", "false" );
try {
transMeta = new TransMeta( getClass().getResource( MRTestUtil.PATH_TO_BAD_INJECTOR_STEP_TEST_TRANSFORMATION ).toURI().getPath() );
MRTestUtil.configJobReducerBaseCase( transMeta, mrJobConfig, genericTransReduce );
genericTransReduce.reduce( new Text( "key" ), Arrays.asList( new IntWritable( 8 ) ).iterator(), outputCollectorMock, reporterMock );
fail( "Should have thrown an exception" );
} catch ( IOException e ) {
assertTrue( "Test for KettleException", e.getMessage().contains( "key or value is not defined in transformation injector step" ) );
}
}
@Test
public void testReducerNoInjectorStep() throws IOException, KettleException, URISyntaxException {
//Turn off displaying stack trace of expected exception to reduce unit test logs
mrJobConfig.set( "debug", "false" );
try {
transMeta = new TransMeta( getClass().getResource( MRTestUtil.PATH_TO_NO_INJECTOR_STEP_TEST_TRANSFORMATION ).toURI().getPath() );
MRTestUtil.configJobReducerBaseCase( transMeta, mrJobConfig, genericTransReduce );
genericTransReduce.reduce( new Text( "key" ), Arrays.asList( new IntWritable( 8 ) ).iterator(), outputCollectorMock, reporterMock );
fail( "Should have thrown an exception" );
} catch ( IOException e ) {
assertTrue( "Test for KettleException", e.getMessage().contains( "Unable to find thread with name Injector and copy number 0" ) );
}
}
}
| apache-2.0 |
kubatatami/JudoNetworking | base/src/main/java/com/github/kubatatami/judonetworking/internals/RequestConnector.java | 25139 | package com.github.kubatatami.judonetworking.internals;
import android.app.ActivityManager;
import android.util.Base64;
import com.github.kubatatami.judonetworking.AsyncResult;
import com.github.kubatatami.judonetworking.CacheInfo;
import com.github.kubatatami.judonetworking.Endpoint;
import com.github.kubatatami.judonetworking.Request;
import com.github.kubatatami.judonetworking.annotations.Base64Param;
import com.github.kubatatami.judonetworking.annotations.LocalCache;
import com.github.kubatatami.judonetworking.controllers.ProtocolController;
import com.github.kubatatami.judonetworking.exceptions.CancelException;
import com.github.kubatatami.judonetworking.exceptions.ConnectionException;
import com.github.kubatatami.judonetworking.exceptions.JudoException;
import com.github.kubatatami.judonetworking.internals.cache.CacheMethod;
import com.github.kubatatami.judonetworking.internals.requests.RequestImpl;
import com.github.kubatatami.judonetworking.internals.results.CacheResult;
import com.github.kubatatami.judonetworking.internals.results.ErrorResult;
import com.github.kubatatami.judonetworking.internals.results.RequestResult;
import com.github.kubatatami.judonetworking.internals.results.RequestSuccessResult;
import com.github.kubatatami.judonetworking.internals.stats.MethodStat;
import com.github.kubatatami.judonetworking.internals.stats.TimeStat;
import com.github.kubatatami.judonetworking.internals.streams.RequestInputStream;
import com.github.kubatatami.judonetworking.internals.virtuals.VirtualCallback;
import com.github.kubatatami.judonetworking.internals.virtuals.VirtualServerInfo;
import com.github.kubatatami.judonetworking.logs.JudoLogger;
import com.github.kubatatami.judonetworking.transports.TransportLayer;
import com.github.kubatatami.judonetworking.utils.FileUtils;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class RequestConnector {
private final EndpointImpl rpc;
private final TransportLayer transportLayer;
private final Random randomGenerator = new Random();
public RequestConnector(EndpointImpl rpc, TransportLayer transportLayer) {
this.rpc = rpc;
this.transportLayer = transportLayer;
}
private static void longLog(String tag, String message, JudoLogger.LogLevel level) {
JudoLogger.longLog(tag, message, level);
}
private RequestResult sendRequest(RequestImpl request, TimeStat timeStat) {
TransportLayer.Connection conn = null;
try {
RequestResult result;
ProtocolController controller = rpc.getProtocolController();
result = handleVirtualServerRequest(request, timeStat);
if (result == null) {
ProtocolController.RequestInfo requestInfo = controller.createRequest(
request.getCustomUrl() == null ? rpc.getUrl() : request.getCustomUrl(),
request);
timeStat.tickCreateTime();
throwErrorOnMonkey(request);
lossCheck();
EndpointImpl.checkThread();
delay(request.getDelay());
EndpointImpl.checkThread();
conn = transportLayer.send(request.getName(), controller, requestInfo, request.getTimeout(), timeStat,
rpc.getDebugFlags(), request.getMethod());
EndpointImpl.checkThread();
InputStream connectionStream = conn.getStream();
if ((rpc.getDebugFlags() & Endpoint.RESPONSE_DEBUG) > 0) {
String resStr = FileUtils.convertStreamToString(conn.getStream());
longLog("Response body(" + request.getName() + ", " + resStr.length() + " Bytes)", resStr, JudoLogger.LogLevel.INFO);
connectionStream = new ByteArrayInputStream(resStr.getBytes());
}
RequestInputStream stream = new RequestInputStream(connectionStream, timeStat, conn.getContentLength());
EndpointImpl.checkThread();
request.setHeaders(conn.getHeaders());
result = controller.parseResponse(request, stream, conn.getHeaders());
EndpointImpl.checkThread();
try {
stream.close();
} catch (Exception ignored) {
}
timeStat.tickParseTime();
}
return result;
} catch (JudoException e) {
return new ErrorResult(request.getId(), e);
} catch (Exception e) {
return new ErrorResult(request.getId(), new JudoException(e));
} finally {
if (conn != null) {
conn.close();
}
}
}
public static Object[] addElement(Object[] org, Object added) {
Object[] result = new Object[org.length + 1];
System.arraycopy(org, 0, result, 0, org.length);
result[org.length] = added;
return result;
}
private RequestResult handleVirtualServerRequest(RequestImpl request, TimeStat timeStat) throws JudoException {
try {
if (request.getMethod() != null) {
VirtualServerInfo virtualServerInfo = rpc.getVirtualServers().get(request.getMethod().getDeclaringClass());
if (virtualServerInfo != null) {
if (request.getCallback() == null) {
try {
Object object = request.getMethod().invoke(virtualServerInfo.server, request.getArgs());
int delay = randDelay(virtualServerInfo.minDelay, virtualServerInfo.maxDelay);
for (int i = 0; i <= TimeStat.TICKS; i++) {
Thread.sleep(delay / TimeStat.TICKS);
timeStat.tickTime(i);
}
return new RequestSuccessResult(request.getId(), object);
} catch (InvocationTargetException ex) {
if (ex.getCause() == null || !(ex.getCause() instanceof UnsupportedOperationException)) {
throw ex;
}
}
} else {
VirtualCallback callback = new VirtualCallback(request.getId());
Object[] args = request.getArgs() != null ? addElement(request.getArgs(), callback) : new Object[]{callback};
boolean implemented = true;
try {
AsyncResult asyncResult = (AsyncResult) request.getMethod().invoke(virtualServerInfo.server, args);
if (asyncResult != null) {
request.setHeaders(asyncResult.getHeaders());
}
int delay = randDelay(virtualServerInfo.minDelay, virtualServerInfo.maxDelay);
for (int i = 0; i <= TimeStat.TICKS; i++) {
Thread.sleep(delay / TimeStat.TICKS);
timeStat.tickTime(i);
}
} catch (InvocationTargetException ex) {
if (ex.getCause() != null && ex.getCause() instanceof UnsupportedOperationException) {
implemented = false;
} else {
throw ex;
}
}
if (implemented) {
return callback.getResult();
}
}
}
}
return null;
} catch (Exception e) {
throw new JudoException("Can't invoke virtual server", e);
}
}
protected Base64Param findBase64Annotation(Annotation[] annotations) {
for (Annotation annotation : annotations) {
if (annotation instanceof Base64Param) {
return (Base64Param) annotation;
}
}
return null;
}
protected void findAndCreateBase64(RequestImpl request) {
if (request.getArgs() != null) {
int i = 0;
if (request.getMethod() != null) {
Annotation[][] annotations = request.getMethod().getParameterAnnotations();
for (Object object : request.getArgs()) {
if (object instanceof byte[]) {
Base64Param ann = findBase64Annotation(annotations[i]);
if (ann != null) {
request.getArgs()[i] = ann.prefix() + Base64.encodeToString((byte[]) object, ann.type()) + ann.suffix();
}
}
i++;
}
}
}
}
@SuppressWarnings("unchecked")
public Object call(RequestImpl request) throws JudoException {
try {
CacheResult localCacheObject = null;
TimeStat timeStat = new TimeStat(request);
if ((rpc.isCacheEnabled() && request.isLocalCacheable())) {
LocalCache.CacheLevel cacheLevel = request.getLocalCacheLevel();
localCacheObject = rpc.getMemoryCache().get(request.getMethodId(), request.getArgs(), request.getLocalCacheLifeTime(), request.getLocalCacheSize());
if (localCacheObject.result) {
if (request.getLocalCacheOnlyOnErrorMode().equals(LocalCache.OnlyOnError.NO)) {
request.invokeStart(new CacheInfo(true, localCacheObject.time));
request.setHeaders(localCacheObject.headers);
timeStat.tickCacheTime();
if (rpc.getCacheMode() == Endpoint.CacheMode.CLONE) {
localCacheObject.object = rpc.getClonner().clone(localCacheObject.object);
}
return localCacheObject.object;
}
} else if (cacheLevel != LocalCache.CacheLevel.MEMORY_ONLY) {
CacheMethod cacheMethod = new CacheMethod(CacheMethod.getMethodId(request.getMethod()), request.getName(), request.getMethod().getDeclaringClass().getSimpleName(), rpc.getUrl(), cacheLevel);
localCacheObject = rpc.getDiskCache().get(cacheMethod, Arrays.deepToString(request.getArgs()), request.getLocalCacheLifeTime());
if (localCacheObject.result) {
rpc.getMemoryCache().put(request.getMethodId(),
request.getArgs(),
localCacheObject.object,
request.getLocalCacheSize(),
localCacheObject.headers);
if (request.getLocalCacheOnlyOnErrorMode().equals(LocalCache.OnlyOnError.NO)) {
request.invokeStart(new CacheInfo(true, localCacheObject.time));
request.setHeaders(localCacheObject.headers);
timeStat.tickCacheTime();
return localCacheObject.object;
}
}
}
}
findAndCreateBase64(request);
request.invokeStart(new CacheInfo(false, 0L));
RequestResult result = sendRequest(request, timeStat);
if (result instanceof ErrorResult) {
if (localCacheObject != null && localCacheObject.result) {
LocalCache.OnlyOnError onlyOnErrorMode = request.getLocalCacheOnlyOnErrorMode();
if (onlyOnErrorMode.equals(LocalCache.OnlyOnError.ON_ALL_ERROR) ||
(onlyOnErrorMode.equals(LocalCache.OnlyOnError.ON_CONNECTION_ERROR) && result.error instanceof ConnectionException)) {
timeStat.tickCacheTime();
return localCacheObject.object;
}
}
}
if (result.error != null) {
throw result.error;
}
timeStat.tickEndTime();
if (rpc.isTimeProfiler()) {
refreshStat(request.getName(),
timeStat.getMethodTime(),
timeStat.getAllTime()
);
}
if ((rpc.getDebugFlags() & Endpoint.TIME_DEBUG) > 0) {
timeStat.logTime("End single request(" + request.getName() + "):");
}
if ((rpc.isCacheEnabled() && request.isLocalCacheable())) {
rpc.getMemoryCache().put(request.getMethodId(), request.getArgs(), result.result, request.getLocalCacheSize(), request.getHeaders());
if (rpc.getCacheMode() == Endpoint.CacheMode.CLONE) {
result.result = rpc.getClonner().clone(result.result);
}
LocalCache.CacheLevel cacheLevel = request.getLocalCacheLevel();
if (cacheLevel != LocalCache.CacheLevel.MEMORY_ONLY) {
CacheMethod cacheMethod = new CacheMethod(CacheMethod.getMethodId(request.getMethod()), request.getName(), request.getMethod().getDeclaringClass().getSimpleName(), rpc.getUrl(), cacheLevel);
rpc.getDiskCache().put(cacheMethod, Arrays.deepToString(request.getArgs()), result.result, request.getLocalCacheSize(), request.getHeaders());
}
}
return result.result;
} catch (JudoException e) {
refreshErrorStat(request);
throw e;
}
}
public List<RequestResult> callBatch(List<RequestImpl> requests, ProgressObserver progressObserver, Integer timeout) throws JudoException {
final List<RequestResult> results = new ArrayList<>(requests.size());
if (requests.size() > 0) {
if (rpc.getProtocolController().isBatchSupported()) {
List<RequestImpl> copyRequest = new ArrayList<>(requests);
VirtualServerInfo virtualServerInfo = rpc.getVirtualServers().get(requests.get(0).getMethod().getDeclaringClass());
if (virtualServerInfo != null) {
TimeStat timeStat = new TimeStat(progressObserver);
int delay = randDelay(virtualServerInfo.minDelay, virtualServerInfo.maxDelay);
for (int i = copyRequest.size() - 1; i >= 0; i--) {
RequestImpl request = copyRequest.get(i);
VirtualCallback callback = new VirtualCallback(request.getId());
Object[] args = request.getArgs() != null ? addElement(request.getArgs(), callback) : new Object[]{callback};
boolean implemented = true;
try {
request.invokeStart(new CacheInfo(false, 0L));
try {
request.getMethod().invoke(virtualServerInfo.server, args);
} catch (IllegalAccessException e) {
throw new JudoException("Can't invoke virtual server", e);
}
} catch (InvocationTargetException ex) {
if (ex.getCause() != null && ex.getCause() instanceof UnsupportedOperationException) {
implemented = false;
} else {
throw new JudoException("Can't invoke virtual server", ex);
}
}
if (implemented) {
results.add(callback.getResult());
copyRequest.remove(request);
}
}
if (copyRequest.size() == 0) {
for (int z = 0; z < TimeStat.TICKS; z++) {
try {
Thread.sleep(delay / TimeStat.TICKS);
} catch (InterruptedException e) {
throw new JudoException("Thread sleep error", e);
}
timeStat.tickTime(z);
}
}
}
String requestsName = "";
for (RequestImpl request : requests) {
requestsName += " " + request.getName();
findAndCreateBase64(request);
}
if (copyRequest.size() > 0) {
results.addAll(callRealBatch(copyRequest, progressObserver, timeout, requestsName));
}
} else {
for (RequestImpl request : requests) {
findAndCreateBase64(request);
}
synchronized (progressObserver) {
progressObserver.setMaxProgress(progressObserver.getMaxProgress() + (requests.size() - 1) * TimeStat.TICKS);
}
final TimeStat timeStat = new TimeStat(progressObserver);
sendBatchAsNormalRequests(requests, timeStat, results);
}
}
return results;
}
private void sendBatchAsNormalRequests(List<RequestImpl> requests, TimeStat timeStat, List<RequestResult> results) {
List<Thread> threads = new ArrayList<>();
for (final RequestImpl request : requests) {
if (!request.isCancelled()) {
threads.add(sendBatchAsNormalRequest(request, results, timeStat));
}
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
throw new JudoException(e);
}
}
}
private Thread sendBatchAsNormalRequest(final RequestImpl request, final List<RequestResult> results, final TimeStat timeStat) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
RequestResult result = sendRequest(request, timeStat);
timeStat.tickEndTime();
if (rpc.isTimeProfiler()) {
if (result.error != null) {
refreshErrorStat(request);
} else {
refreshStat(request.getName(),
timeStat.getMethodTime(),
timeStat.getAllTime()
);
}
}
synchronized (results) {
results.add(result);
}
}
});
thread.start();
return thread;
}
private void delay(int requestDelay) {
int delay = rpc.getDelay() + requestDelay;
if (delay > 0) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
throw new CancelException();
}
}
}
public List<RequestResult> callRealBatch(List<RequestImpl> requests, ProgressObserver progressObserver, Integer timeout, String requestsName) throws JudoException {
TransportLayer.Connection conn = null;
try {
ProtocolController controller = rpc.getProtocolController();
List<RequestResult> responses;
TimeStat timeStat = new TimeStat(progressObserver);
ProtocolController.RequestInfo requestInfo = controller.createRequests(rpc.getUrl(), (List) requests);
timeStat.tickCreateTime();
List<RequestResult> monkeyResponses = removeErrorOnMonkeyRequests(requests);
lossCheck();
int maxDelay = 0;
for (RequestImpl request : requests) {
maxDelay = Math.max(maxDelay, request.getDelay());
}
EndpointImpl.checkThread();
delay(maxDelay);
conn = transportLayer.send(requestsName, controller, requestInfo, timeout, timeStat, rpc.getDebugFlags(), null);
EndpointImpl.checkThread();
InputStream connectionStream = conn.getStream();
if ((rpc.getDebugFlags() & Endpoint.RESPONSE_DEBUG) > 0) {
String resStr = FileUtils.convertStreamToString(conn.getStream());
longLog("Response body(" + requestsName + ", " + resStr.length() + " Bytes)", resStr, JudoLogger.LogLevel.INFO);
connectionStream = new ByteArrayInputStream(resStr.getBytes());
}
EndpointImpl.checkThread();
RequestInputStream stream = new RequestInputStream(connectionStream, timeStat, conn.getContentLength());
for (RequestImpl request : requests) {
request.setHeaders(conn.getHeaders());
}
responses = controller.parseResponses((List) requests, stream, conn.getHeaders());
responses.addAll(monkeyResponses);
EndpointImpl.checkThread();
timeStat.tickParseTime();
timeStat.tickEndTime();
calcTimeProfiler(requests, timeStat);
if ((rpc.getDebugFlags() & Endpoint.TIME_DEBUG) > 0) {
timeStat.logTime("End batch request(" + requestsName.substring(1) + "):");
}
return responses;
} catch (JudoException e) {
for (RequestImpl request : requests) {
refreshErrorStat(request);
rpc.saveStat();
}
RequestProxy.addToExceptionMessage(requestsName.substring(1), e);
throw e;
} finally {
if (conn != null) {
conn.close();
}
}
}
private List<RequestResult> removeErrorOnMonkeyRequests(List<RequestImpl> requests) {
List<RequestResult> responses = new ArrayList<>();
for (int i = requests.size(); i >= 0; i--) {
try {
throwErrorOnMonkey(requests.get(i));
} catch (ConnectionException ex) {
requests.remove(i);
responses.add(new ErrorResult(requests.get(i).getId(), ex));
}
}
return responses;
}
private void calcTimeProfiler(List<RequestImpl> requests, TimeStat timeStat) {
if (rpc.isTimeProfiler()) {
for (RequestImpl request : requests) {
refreshStat(request.getName(),
timeStat.getMethodTime() / requests.size(),
timeStat.getAllTime() / requests.size()
);
}
rpc.saveStat();
}
}
private void throwErrorOnMonkey(RequestImpl request) throws JudoException {
if (ActivityManager.isUserAMonkey() && request.isRejectOnMonkeyTest()) {
throw new ConnectionException("Rejected during monkey test.");
}
}
private void lossCheck() throws JudoException {
float percentLoss = rpc.getPercentLoss();
float random = randomGenerator.nextFloat();
if (percentLoss != 0 && random < percentLoss) {
throw new ConnectionException("Random package lost.");
}
}
private synchronized MethodStat getStat(String method) {
MethodStat stat = rpc.getStats().get(method);
if (stat == null) {
stat = new MethodStat();
rpc.getStats().put(method, stat);
}
return stat;
}
private void refreshStat(String method, long methodTime, long allTime) {
MethodStat stat = getStat(method);
stat.methodTime = ((stat.methodTime * stat.requestCount) + methodTime) / (stat.requestCount + 1);
stat.allTime = ((stat.allTime * stat.requestCount) + allTime) / (stat.requestCount + 1);
stat.requestCount++;
rpc.saveStat();
}
private void refreshErrorStat(Request request) {
if (!request.isCancelled()) {
MethodStat stat = getStat(request.getName());
stat.errors++;
stat.requestCount++;
rpc.saveStat();
}
}
public void setConnectTimeout(int connectTimeout) {
transportLayer.setConnectTimeout(connectTimeout);
}
public void setMethodTimeout(int methodTimeout) {
transportLayer.setMethodTimeout(methodTimeout);
}
public int getMethodTimeout() {
return transportLayer.getMethodTimeout();
}
public int randDelay(int minDelay, int maxDelay) {
if (maxDelay == 0) {
return 0;
}
Random random = new Random();
if (maxDelay != minDelay) {
return minDelay + random.nextInt(maxDelay - minDelay);
} else {
return minDelay;
}
}
}
| apache-2.0 |
wjsl/jaredcumulo | test/src/main/java/org/apache/accumulo/test/randomwalk/security/CreateTable.java | 3253 | /*
* 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.accumulo.test.randomwalk.security;
import java.util.Properties;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.TableExistsException;
import org.apache.accumulo.core.client.security.SecurityErrorCode;
import org.apache.accumulo.core.security.TablePermission;
import org.apache.accumulo.test.randomwalk.State;
import org.apache.accumulo.test.randomwalk.Test;
public class CreateTable extends Test {
@Override
public void visit(State state, Properties props) throws Exception {
Connector conn = state.getInstance().getConnector(WalkingSecurity.get(state).getSysUserName(), WalkingSecurity.get(state).getSysToken());
String tableName = WalkingSecurity.get(state).getTableName();
boolean exists = WalkingSecurity.get(state).getTableExists();
boolean hasPermission = WalkingSecurity.get(state).canCreateTable(WalkingSecurity.get(state).getSysCredentials());
try {
conn.tableOperations().create(tableName);
} catch (AccumuloSecurityException ae) {
if (ae.getSecurityErrorCode().equals(SecurityErrorCode.PERMISSION_DENIED)) {
if (hasPermission)
throw new AccumuloException("Got a security exception when I should have had permission.", ae);
else
// create table anyway for sake of state
{
try {
state.getConnector().tableOperations().create(tableName);
WalkingSecurity.get(state).initTable(tableName);
} catch (TableExistsException tee) {
if (exists)
return;
else
throw new AccumuloException("Test and Accumulo are out of sync");
}
return;
}
} else
throw new AccumuloException("Got unexpected error", ae);
} catch (TableExistsException tee) {
if (!exists)
throw new TableExistsException(null, tableName, "Got a TableExistsException but it shouldn't have existed", tee);
else
return;
}
WalkingSecurity.get(state).initTable(tableName);
for (TablePermission tp : TablePermission.values())
WalkingSecurity.get(state).grantTablePermission(conn.whoami(), tableName, tp);
if (!hasPermission)
throw new AccumuloException("Didn't get Security Exception when we should have");
}
}
| apache-2.0 |
OpenBEL/openbel-framework | org.openbel.framework.compiler/src/main/java/org/openbel/framework/compiler/kam/KAMStoreSchemaServiceImpl.java | 11251 | /**
* Copyright (C) 2012-2013 Selventa, Inc.
*
* This file is part of the OpenBEL Framework.
*
* 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.
*
* The OpenBEL Framework is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the OpenBEL Framework. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms under LGPL v3:
*
* This license does not authorize you and you are prohibited from using the
* name, trademarks, service marks, logos or similar indicia of Selventa, Inc.,
* or, in the discretion of other licensors or authors of the program, the
* name, trademarks, service marks, logos or similar indicia of such authors or
* licensors, in any marketing or advertising materials relating to your
* distribution of the program or any covered product. This restriction does
* not waive or limit your obligation to keep intact all copyright notices set
* forth in the program as delivered to you.
*
* If you distribute the program in whole or in part, or any modified version
* of the program, and you assume contractual liability to the recipient with
* respect to the program or modified version, then you will indemnify the
* authors and licensors of the program for any liabilities that these
* contractual assumptions directly impose on those licensors and authors.
*/
package org.openbel.framework.compiler.kam;
import static org.openbel.framework.common.cfg.SystemConfiguration.getSystemConfiguration;
import static org.openbel.framework.core.df.AbstractJdbcDAO.SCHEMA_NAME_PLACEHOLDER;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import org.apache.commons.io.IOUtils;
import org.openbel.framework.api.internal.KAMCatalogDao;
import org.openbel.framework.api.internal.KamDbObject;
import org.openbel.framework.core.df.DBConnection;
import org.openbel.framework.core.df.DatabaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* KAMStoreSchemaServiceImpl implements a service to setup a KAM schema
* instance to store a single KAM.
*
* @author Anthony Bargnesi {@code <abargnesi@selventa.com>}
*/
public class KAMStoreSchemaServiceImpl implements KAMStoreSchemaService {
private final String SQL_SCRIPT_DELIMITER = "##";
/**
* Statically-loads the slf4j application log.
*/
private static Logger log = LoggerFactory
.getLogger(KAMStoreSchemaServiceImpl.class);
/**
* The classpath location where the KAM schema .sql files are located:
* {@value #KAM_SQL_PATH}
*/
private static final String KAM_SQL_PATH = "/kam/";
/**
* The classpath location where the .sql files to delete KAM schema are located:
* {@value #DELETE_KAM_SQL_PATH}
*/
private static final String DELETE_KAM_SQL_PATH = "/kam_delete/";
/**
* The classpath location where the KAM catalog schema .sql files are
* located: {@value #KAM_CATALOG_SQL_PATH}
*/
private static final String KAM_CATALOG_SQL_PATH = "/kam_catalog/";
/**
* The database service bean dependency.
*/
private final DatabaseService databaseService;
/**
* Create the KAMStoreSchemaServiceImpl with the {@link DatabaseService}
* bean.
*
* @param databaseService {@link DatabaseService} the database service
* bean
*/
public KAMStoreSchemaServiceImpl(final DatabaseService databaseService) {
this.databaseService = databaseService;
}
/**
* {@inheritDoc}
*/
@Override
public void setupKAMCatalogSchema() throws SQLException, IOException {
DBConnection kamDbc = null;
try {
kamDbc = createConnection();
runScripts(kamDbc, "/" + kamDbc.getType() + KAM_CATALOG_SQL_PATH,
getSystemConfiguration().getKamCatalogSchema(),
getSchemaManagementStatus(kamDbc));
} finally {
closeConnection(kamDbc);
}
}
/**
* {@inheritDoc}
*/
@Override
public void setupKAMStoreSchema(DBConnection dbc, String schemaName)
throws IOException {
runScripts(dbc, "/" + dbc.getType() + KAM_SQL_PATH, schemaName,
getSchemaManagementStatus(dbc));
}
/**
* {@inheritDoc}
*/
@Override
public boolean deleteKAMStoreSchema(DBConnection dbc, String schemaName)
throws IOException {
boolean deleteSchemas = getSchemaManagementStatus(dbc);
if (deleteSchemas) {
runScripts(dbc, "/" + dbc.getType() + DELETE_KAM_SQL_PATH,
schemaName, deleteSchemas);
} else {
// Truncate the schema instead of deleting it.
InputStream sqlStream = null;
if (dbc.isMysql()) {
sqlStream =
getClass().getResourceAsStream(
"/" + dbc.getType() + KAM_SQL_PATH + "1.sql");
} else if (dbc.isOracle()) {
sqlStream =
getClass().getResourceAsStream(
"/" + dbc.getType() + KAM_SQL_PATH + "0.sql");
}
if (sqlStream != null) {
runScript(dbc, sqlStream, schemaName);
}
}
return deleteSchemas;
}
/**
* Check to see if the system is managing the KAMStore schemas. The system manages Derby schemas
* by default. Oracle is only DBA managed and MySQL can be either although the default is to
* enable system managed
*
* @param dbc
* @return
*/
private boolean getSchemaManagementStatus(DBConnection dbc) {
boolean createSchemas = false;
if (dbc.isDerby()) {
createSchemas = true;
} else if (dbc.isMysql() || dbc.isPostgresql()) {
createSchemas = getSystemConfiguration().getSystemManagedSchemas();
}
return createSchemas;
}
/**
* {@inheritDoc}
*/
@Override
public String saveToKAMCatalog(KamDbObject kamDb)
throws SQLException {
KAMCatalogDao catalogDAO = null;
try {
catalogDAO = createCatalogDao();
catalogDAO.saveToCatalog(kamDb);
} finally {
if (catalogDAO != null) {
closeCatalogDao(catalogDAO);
}
}
return kamDb.getSchemaName();
}
/**
* {@inheritDoc}
*/
@Override
public void deleteFromKAMCatalog(final String kamName)
throws SQLException {
KAMCatalogDao catalogDAO = null;
try {
catalogDAO = createCatalogDao();
catalogDAO.deleteFromCatalog(kamName);
} finally {
if (catalogDAO != null) {
closeCatalogDao(catalogDAO);
}
}
}
private KAMCatalogDao createCatalogDao() throws SQLException {
String catalogSchema = getSystemConfiguration().getKamCatalogSchema();
String kamSchemaPrefix = getSystemConfiguration().getKamSchemaPrefix();
return new KAMCatalogDao(createConnection(), catalogSchema,
kamSchemaPrefix);
}
private void closeCatalogDao(KAMCatalogDao catalogDAO) {
if (catalogDAO != null) {
catalogDAO.terminate();
}
}
private DBConnection createConnection() throws SQLException {
return databaseService.dbConnection(
getSystemConfiguration().getKamURL(),
getSystemConfiguration().getKamUser(),
getSystemConfiguration().getKamPassword());
}
private void closeConnection(DBConnection dbc) {
if (dbc != null) {
try {
dbc.getConnection().close();
} catch (SQLException e) {}
}
}
/**
* Finds .sql scripts in <tt>dropRoot</tt> and executes each statement
* againsts the {@link DBConnection} <tt>dbc</tt>.
*
* @param dbc {@link DBConnection}, the database connection
* @param dropRoot {@link String}, the classpath root where .sql files
* are found
* @param schemaName {@link String}, the schema name, which can be null
* @param createSchemas {@link boolean}, true if the system should create new schemas, false otherwise
* @throws IOException Thrown if an I/O error occurred reading a .sql file
* from the classpath
*/
private void runScripts(DBConnection dbc, String dropRoot,
String schemaName, boolean createSchemas) throws IOException {
int fi = 0;
boolean fnf = false;
while (!fnf) {
InputStream sqlStream =
getClass().getResourceAsStream(dropRoot + fi + ".sql");
if (sqlStream == null) {
fnf = true;
break;
}
String script = IOUtils.toString(sqlStream);
String[] sqlStatements = script.split(SQL_SCRIPT_DELIMITER);
for (String sqlStatement : sqlStatements) {
// MySQL allows schemas to by system or dba managed. If dba managed we must
// skip the schema creation phase which is always the first sql script (0.sql)
if (createSchemas == false && fi == 0) {
continue;
}
if (schemaName != null) {
sqlStatement =
sqlStatement.replace(SCHEMA_NAME_PLACEHOLDER,
schemaName);
}
try {
databaseService.update(dbc, sqlStatement);
} catch (SQLException e) {
log.debug("Error running script, message:\n{}\n\n{}\n",
new Object[] { e.getMessage(), sqlStatement });
//swallow since DROP statements might fail.
}
}
fi++;
}
}
private void runScript(DBConnection dbc, InputStream sqlStream,
String schemaName) throws IOException {
String script = IOUtils.toString(sqlStream);
String[] sqlStatements = script.split(SQL_SCRIPT_DELIMITER);
for (String sqlStatement : sqlStatements) {
if (schemaName != null) {
sqlStatement =
sqlStatement.replace(SCHEMA_NAME_PLACEHOLDER,
schemaName);
}
try {
databaseService.update(dbc, sqlStatement);
} catch (SQLException e) {
log.debug("Error running script, message:\n{}\n\n{}\n",
new Object[] { e.getMessage(), sqlStatement });
//swallow since DROP statements might fail.
}
}
}
}
| apache-2.0 |
CodeArcsInc/candlestack | src/main/java/io/codearcs/candlestack/aws/s3/S3Location.java | 317 | package io.codearcs.candlestack.aws.s3;
public class S3Location {
private String id, name, bucket, key;
S3Location() {}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getBucket() {
return bucket;
}
public String getKey() {
return key;
}
}
| apache-2.0 |
spring-cloud/spring-cloud-netflix | spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration.java | 15701 | /*
* Copyright 2013-2022 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.cloud.netflix.eureka;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.cloud.client.CommonsClientAutoConfiguration;
import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled;
import org.springframework.cloud.client.actuator.HasFeatures;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.cloud.client.serviceregistry.ServiceRegistryAutoConfiguration;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.cloud.netflix.eureka.metadata.DefaultManagementMetadataProvider;
import org.springframework.cloud.netflix.eureka.metadata.ManagementMetadata;
import org.springframework.cloud.netflix.eureka.metadata.ManagementMetadataProvider;
import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration;
import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration;
import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry;
import org.springframework.cloud.util.ProxyUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.StringUtils;
import static org.springframework.cloud.commons.util.IdUtils.getDefaultInstanceId;
/**
* @author Dave Syer
* @author Spencer Gibb
* @author Jon Schneider
* @author Matt Jenkins
* @author Ryan Baxter
* @author Daniel Lavoie
* @author Olga Maciaszek-Sharma
* @author Tim Ysewyn
*/
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
@ConditionalOnClass(EurekaClientConfig.class)
@ConditionalOnProperty(value = "eureka.client.enabled", matchIfMissing = true)
@ConditionalOnDiscoveryEnabled
@AutoConfigureBefore({ CommonsClientAutoConfiguration.class, ServiceRegistryAutoConfiguration.class })
@AutoConfigureAfter(name = { "org.springframework.cloud.netflix.eureka.config.DiscoveryClientOptionalArgsConfiguration",
"org.springframework.cloud.autoconfigure.RefreshAutoConfiguration",
"org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration",
"org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration" })
public class EurekaClientAutoConfiguration {
private ConfigurableEnvironment env;
public EurekaClientAutoConfiguration(ConfigurableEnvironment env) {
this.env = env;
}
@Bean
public HasFeatures eurekaFeature() {
return HasFeatures.namedFeature("Eureka Client", EurekaClient.class);
}
@Bean
@ConditionalOnMissingBean(value = EurekaClientConfig.class, search = SearchStrategy.CURRENT)
public EurekaClientConfigBean eurekaClientConfigBean(ConfigurableEnvironment env) {
return new EurekaClientConfigBean();
}
@Bean
@ConditionalOnMissingBean
public ManagementMetadataProvider serviceManagementMetadataProvider() {
return new DefaultManagementMetadataProvider();
}
private String getProperty(String property) {
return this.env.containsProperty(property) ? this.env.getProperty(property) : "";
}
@Bean
@ConditionalOnMissingBean(value = EurekaInstanceConfig.class, search = SearchStrategy.CURRENT)
public EurekaInstanceConfigBean eurekaInstanceConfigBean(InetUtils inetUtils,
ManagementMetadataProvider managementMetadataProvider) {
String hostname = getProperty("eureka.instance.hostname");
boolean preferIpAddress = Boolean.parseBoolean(getProperty("eureka.instance.prefer-ip-address"));
String ipAddress = getProperty("eureka.instance.ip-address");
boolean isSecurePortEnabled = Boolean.parseBoolean(getProperty("eureka.instance.secure-port-enabled"));
String serverContextPath = env.getProperty("server.servlet.context-path", "/");
int serverPort = Integer.parseInt(env.getProperty("server.port", env.getProperty("port", "8080")));
Integer managementPort = env.getProperty("management.server.port", Integer.class);
String managementContextPath = env.getProperty("management.server.servlet.context-path");
if (!StringUtils.hasText(managementContextPath)) {
managementContextPath = env.getProperty("management.server.base-path");
}
Integer jmxPort = env.getProperty("com.sun.management.jmxremote.port", Integer.class);
EurekaInstanceConfigBean instance = new EurekaInstanceConfigBean(inetUtils);
instance.setNonSecurePort(serverPort);
instance.setInstanceId(getDefaultInstanceId(env));
instance.setPreferIpAddress(preferIpAddress);
instance.setSecurePortEnabled(isSecurePortEnabled);
if (StringUtils.hasText(ipAddress)) {
instance.setIpAddress(ipAddress);
}
if (isSecurePortEnabled) {
instance.setSecurePort(serverPort);
}
if (StringUtils.hasText(hostname)) {
instance.setHostname(hostname);
}
String statusPageUrlPath = getProperty("eureka.instance.status-page-url-path");
String healthCheckUrlPath = getProperty("eureka.instance.health-check-url-path");
if (StringUtils.hasText(statusPageUrlPath)) {
instance.setStatusPageUrlPath(statusPageUrlPath);
}
if (StringUtils.hasText(healthCheckUrlPath)) {
instance.setHealthCheckUrlPath(healthCheckUrlPath);
}
ManagementMetadata metadata = managementMetadataProvider.get(instance, serverPort, serverContextPath,
managementContextPath, managementPort);
if (metadata != null) {
instance.setStatusPageUrl(metadata.getStatusPageUrl());
instance.setHealthCheckUrl(metadata.getHealthCheckUrl());
if (instance.isSecurePortEnabled()) {
instance.setSecureHealthCheckUrl(metadata.getSecureHealthCheckUrl());
}
Map<String, String> metadataMap = instance.getMetadataMap();
metadataMap.computeIfAbsent("management.port", k -> String.valueOf(metadata.getManagementPort()));
}
else {
// without the metadata the status and health check URLs will not be set
// and the status page and health check url paths will not include the
// context path so set them here
if (StringUtils.hasText(managementContextPath)) {
instance.setHealthCheckUrlPath(managementContextPath + instance.getHealthCheckUrlPath());
instance.setStatusPageUrlPath(managementContextPath + instance.getStatusPageUrlPath());
}
}
setupJmxPort(instance, jmxPort);
return instance;
}
private void setupJmxPort(EurekaInstanceConfigBean instance, Integer jmxPort) {
Map<String, String> metadataMap = instance.getMetadataMap();
if (metadataMap.get("jmx.port") == null && jmxPort != null) {
metadataMap.put("jmx.port", String.valueOf(jmxPort));
}
}
@Bean
public EurekaServiceRegistry eurekaServiceRegistry() {
return new EurekaServiceRegistry();
}
// @Bean
// @ConditionalOnBean(AutoServiceRegistrationProperties.class)
// @ConditionalOnProperty(value =
// "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
// public EurekaRegistration eurekaRegistration(EurekaClient eurekaClient,
// CloudEurekaInstanceConfig instanceConfig, ApplicationInfoManager
// applicationInfoManager, ObjectProvider<HealthCheckHandler> healthCheckHandler) {
// return EurekaRegistration.builder(instanceConfig)
// .with(applicationInfoManager)
// .with(eurekaClient)
// .with(healthCheckHandler)
// .build();
// }
@Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
public EurekaAutoServiceRegistration eurekaAutoServiceRegistration(ApplicationContext context,
EurekaServiceRegistry registry, EurekaRegistration registration) {
return new EurekaAutoServiceRegistration(context, registry, registration);
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingRefreshScope
protected static class EurekaClientConfiguration {
@Autowired
private ApplicationContext context;
@Autowired
private AbstractDiscoveryClientOptionalArgs<?> optionalArgs;
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT)
public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config) {
return new CloudEurekaClient(manager, config, this.optionalArgs, this.context);
}
@Bean
@ConditionalOnMissingBean(value = ApplicationInfoManager.class, search = SearchStrategy.CURRENT)
public ApplicationInfoManager eurekaApplicationInfoManager(EurekaInstanceConfig config) {
InstanceInfo instanceInfo = new InstanceInfoFactory().create(config);
return new ApplicationInfoManager(config, instanceInfo);
}
@Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
public EurekaRegistration eurekaRegistration(EurekaClient eurekaClient,
CloudEurekaInstanceConfig instanceConfig, ApplicationInfoManager applicationInfoManager,
@Autowired(required = false) ObjectProvider<HealthCheckHandler> healthCheckHandler) {
return EurekaRegistration.builder(instanceConfig).with(applicationInfoManager).with(eurekaClient)
.with(healthCheckHandler).build();
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnRefreshScope
protected static class RefreshableEurekaClientConfiguration {
@Autowired
private ApplicationContext context;
@Autowired
private AbstractDiscoveryClientOptionalArgs<?> optionalArgs;
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT)
@org.springframework.cloud.context.config.annotation.RefreshScope
@Lazy
public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config,
EurekaInstanceConfig instance, @Autowired(required = false) HealthCheckHandler healthCheckHandler) {
// If we use the proxy of the ApplicationInfoManager we could run into a
// problem
// when shutdown is called on the CloudEurekaClient where the
// ApplicationInfoManager bean is
// requested but wont be allowed because we are shutting down. To avoid this
// we use the
// object directly.
ApplicationInfoManager appManager;
if (AopUtils.isAopProxy(manager)) {
appManager = ProxyUtils.getTargetObject(manager);
}
else {
appManager = manager;
}
CloudEurekaClient cloudEurekaClient = new CloudEurekaClient(appManager, config, this.optionalArgs,
this.context);
cloudEurekaClient.registerHealthCheck(healthCheckHandler);
return cloudEurekaClient;
}
@Bean
@ConditionalOnMissingBean(value = ApplicationInfoManager.class, search = SearchStrategy.CURRENT)
@org.springframework.cloud.context.config.annotation.RefreshScope
@Lazy
public ApplicationInfoManager eurekaApplicationInfoManager(EurekaInstanceConfig config) {
InstanceInfo instanceInfo = new InstanceInfoFactory().create(config);
return new ApplicationInfoManager(config, instanceInfo);
}
@Bean
@org.springframework.cloud.context.config.annotation.RefreshScope
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
public EurekaRegistration eurekaRegistration(EurekaClient eurekaClient,
CloudEurekaInstanceConfig instanceConfig, ApplicationInfoManager applicationInfoManager,
@Autowired(required = false) ObjectProvider<HealthCheckHandler> healthCheckHandler) {
return EurekaRegistration.builder(instanceConfig).with(applicationInfoManager).with(eurekaClient)
.with(healthCheckHandler).build();
}
}
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnMissingRefreshScopeCondition.class)
@interface ConditionalOnMissingRefreshScope {
}
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ConditionalOnClass(RefreshScope.class)
@ConditionalOnBean(RefreshAutoConfiguration.class)
@ConditionalOnProperty(value = "eureka.client.refresh.enable", havingValue = "true", matchIfMissing = true)
@interface ConditionalOnRefreshScope {
}
private static class OnMissingRefreshScopeCondition extends AnyNestedCondition {
OnMissingRefreshScopeCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnMissingClass("org.springframework.cloud.context.scope.refresh.RefreshScope")
static class MissingClass {
}
@ConditionalOnMissingBean(RefreshAutoConfiguration.class)
static class MissingScope {
}
@ConditionalOnProperty(value = "eureka.client.refresh.enable", havingValue = "false")
static class OnPropertyDisabled {
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Health.class)
protected static class EurekaHealthIndicatorConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnEnabledHealthIndicator("eureka")
public EurekaHealthIndicator eurekaHealthIndicator(EurekaClient eurekaClient,
EurekaInstanceConfig instanceConfig, EurekaClientConfig clientConfig) {
return new EurekaHealthIndicator(eurekaClient, instanceConfig, clientConfig);
}
}
}
| apache-2.0 |
shaolinwu/uimaster | modules/designtime/src/main/java/org/shaolin/bmdp/designtime/andriod/datamodel/ScrollView.java | 1969 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.08.28 at 04:10:22 PM CST
//
package org.shaolin.bmdp.designtime.andriod.datamodel;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ScrollView complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ScrollView">
* <complexContent>
* <extension base="{}FrameLayout">
* <attribute ref="{http://schemas.android.com/apk/res/android}fillViewport"/>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ScrollView")
@XmlRootElement(name = "ScrollView")
public class ScrollView
extends FrameLayout
implements Serializable
{
private final static long serialVersionUID = 1L;
@XmlAttribute(name = "fillViewport", namespace = "http://schemas.android.com/apk/res/android")
protected String fillViewport;
/**
* Gets the value of the fillViewport property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFillViewport() {
return fillViewport;
}
/**
* Sets the value of the fillViewport property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFillViewport(String value) {
this.fillViewport = value;
}
}
| apache-2.0 |
SteveGodwin/mock-xquery | src/main/java/me/stuarthicks/xquery/XQueryConstants.java | 1087 | package me.stuarthicks.xquery;
import net.sf.saxon.value.SequenceType;
public final class XQueryConstants {
/**
* These constants exist for convenience and as reference. They will never be an exhaustive list.
*/
// Method signatures you might want to stub
public static final SequenceType[] ARGUMENTS_NONE = new SequenceType[]{};
public static final SequenceType[] ARGUMENTS_SINGLE_STRING = new SequenceType[]{SequenceType.SINGLE_STRING};
public static final SequenceType[] ARGUMENTS_SINGLE_INT = new SequenceType[]{SequenceType.SINGLE_INTEGER};
public static final SequenceType[] ARGUMENTS_SINGLE_FLOAT = new SequenceType[]{SequenceType.SINGLE_FLOAT};
// Types your stubs might want to return
public static final SequenceType RETURNS_SINGLE_STRING = SequenceType.SINGLE_STRING;
public static final SequenceType RETURNS_SINGLE_INT = SequenceType.SINGLE_INTEGER;
public static final SequenceType RETURNS_SINGLE_FLOAT = SequenceType.SINGLE_FLOAT;
public static final SequenceType RETURNS_SINGLE_NODE = SequenceType.SINGLE_NODE;
}
| apache-2.0 |
pdrados/cas | support/cas-server-support-aup-jdbc/src/main/java/org/apereo/cas/aup/JdbcAcceptableUsagePolicyRepository.java | 4366 | package org.apereo.cas.aup;
import org.apereo.cas.authentication.Credential;
import org.apereo.cas.authentication.principal.Principal;
import org.apereo.cas.configuration.model.support.aup.AcceptableUsagePolicyProperties;
import org.apereo.cas.ticket.registry.TicketRegistrySupport;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.LoggingUtils;
import org.apereo.cas.web.support.WebUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.webflow.execution.RequestContext;
import javax.sql.DataSource;
/**
* This is {@link JdbcAcceptableUsagePolicyRepository}.
* Examines the principal attribute collection to determine if
* the policy has been accepted, and if not, allows for a configurable
* way so that user's choice can later be remembered and saved back into
* the jdbc instance.
*
* @author Misagh Moayyed
* @since 5.2
*/
@Slf4j
public class JdbcAcceptableUsagePolicyRepository extends BaseAcceptableUsagePolicyRepository {
private static final long serialVersionUID = 1600024683199961892L;
private final transient JdbcTemplate jdbcTemplate;
/**
* Instantiates a new Jdbc acceptable usage policy repository.
*
* @param ticketRegistrySupport the ticket registry support
* @param aupProperties the aup properties
* @param dataSource the data source
*/
public JdbcAcceptableUsagePolicyRepository(final TicketRegistrySupport ticketRegistrySupport,
final AcceptableUsagePolicyProperties aupProperties,
final DataSource dataSource) {
super(ticketRegistrySupport, aupProperties);
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public boolean submit(final RequestContext requestContext, final Credential credential) {
try {
val jdbc = aupProperties.getJdbc();
var aupColumnName = aupProperties.getAupAttributeName();
if (StringUtils.isNotBlank(jdbc.getAupColumn())) {
aupColumnName = jdbc.getAupColumn();
}
val sql = String.format(jdbc.getSqlUpdate(), jdbc.getTableName(), aupColumnName, jdbc.getPrincipalIdColumn());
val principal = WebUtils.getAuthentication(requestContext).getPrincipal();
val principalId = determinePrincipalId(principal);
LOGGER.debug("Executing update query [{}] for principal [{}]", sql, principalId);
return this.jdbcTemplate.update(sql, principalId) > 0;
} catch (final Exception e) {
LoggingUtils.error(LOGGER, e);
}
return false;
}
/**
* Extracts principal ID from a principal attribute or the provided credentials.
*
* @param principal the principal
* @return the principal ID to update the AUP setting in the database for
*/
protected String determinePrincipalId(final Principal principal) {
if (StringUtils.isBlank(aupProperties.getJdbc().getPrincipalIdAttribute())) {
return principal.getId();
}
val pIdAttribName = aupProperties.getJdbc().getPrincipalIdAttribute();
if (!principal.getAttributes().containsKey(pIdAttribName)) {
throw new IllegalStateException("Principal attribute [" + pIdAttribName + "] cannot be found");
}
val pIdAttributeValue = principal.getAttributes().get(pIdAttribName);
val pIdAttributeValues = CollectionUtils.toCollection(pIdAttributeValue);
var principalId = StringUtils.EMPTY;
if (!pIdAttributeValues.isEmpty()) {
principalId = pIdAttributeValues.iterator().next().toString().trim();
}
if (pIdAttributeValues.size() > 1) {
LOGGER.warn("Principal attribute [{}] was found, but its value [{}] is multi-valued. "
+ "Proceeding with the first element [{}]", pIdAttribName, pIdAttributeValue, principalId);
}
if (principalId.isEmpty()) {
throw new IllegalStateException("Principal attribute [" + pIdAttribName + "] was found, but it is either empty"
+ " or multi-valued with an empty element");
}
return principalId;
}
}
| apache-2.0 |
VHAINNOVATIONS/AVS | ll-avs/ll-avs-web/src/main/java/gov/va/med/lom/avs/client/thread/RemoteNonVaMedicationsThread.java | 5098 | package gov.va.med.lom.avs.client.thread;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import gov.va.med.lom.foundation.service.response.CollectionServiceResponse;
import gov.va.med.lom.javaUtils.misc.DateUtils;
import gov.va.med.lom.javaUtils.misc.StringUtils;
import gov.va.med.lom.avs.client.model.MedicationJson;
import gov.va.med.lom.avs.web.util.AvsWebUtils;
import gov.va.med.lom.avs.model.MedicationRdv;
import gov.va.med.lom.avs.model.EncounterInfo;
public class RemoteNonVaMedicationsThread extends SheetDataThread {
private boolean formatAsHtml = false;
public RemoteNonVaMedicationsThread() {
this(false);
}
public RemoteNonVaMedicationsThread(boolean formatAsHtml) {
super();
this.formatAsHtml = formatAsHtml;
}
public void run() {
StringBuffer body = null;
List<MedicationJson> remoteNonVaMedsList = null;
if (this.formatAsHtml) {
body = new StringBuffer();
} else {
remoteNonVaMedsList = new ArrayList<MedicationJson>();
}
try {
CollectionServiceResponse<MedicationRdv> response =
super.getSheetService().getRemoteNonVaMedicationsRdv(super.securityContext, super.getEncounterInfo(),
AvsWebUtils.getStartDate(DEF_EXPIRED_MED_DAYS));
Collection<MedicationRdv> remoteNonVaMedications = response.getCollection();
int i = 1;
for (MedicationRdv med : remoteNonVaMedications) {
MedicationJson rmJson = null;
if (!this.formatAsHtml) {
rmJson = new MedicationJson();
remoteNonVaMedsList.add(rmJson);
rmJson.setId(String.valueOf(i++));
rmJson.setName(StringUtils.mixedCase(med.getName()));
rmJson.setType("Non-VA");
rmJson.setSig(SIG_PATTERN.matcher(med.getSig()).replaceAll(""));
try {
Date dt = DateUtils.convertDateStr(med.getStartDate(), "mm/dd/yyyy");
rmJson.setStartDate(DateUtils.formatDate(dt, "MMMM dd, yyyy"));
} catch(Exception e) {
rmJson.setStartDate(super.getStringResource("na"));
}
try {
Date dt = DateUtils.convertDateStr(med.getStopDate(), "mm/dd/yyyy");
rmJson.setStopDate(DateUtils.formatDate(dt, "MMMM dd, yyyy"));
} catch(Exception e) {
rmJson.setStopDate(super.getStringResource("na"));
}
rmJson.setSite(med.getStationName());
rmJson.setStationNo(med.getStationNo());
rmJson.setProvider(med.getDocumentor());
} else {
body.append("<div class=\"med-name\">");
if (super.docType.equals(EncounterInfo.PVS)) {
body.append("<input type=\"checkbox\"> ");
}
body.append(StringUtils.mixedCase(med.getName()))
.append("</div>\n");
StringBuffer sig = new StringBuffer(SIG_PATTERN.matcher(med.getSig()).replaceAll(""));
if (!sig.toString().isEmpty()) {
sig.insert(0, super.getStringResource("take") + " ");
if (sig.toString().contains("MOUTH") && !sig.toString().contains(" BY ")) {
sig.insert(sig.indexOf("MOUTH"), super.getStringResource("by") + " ");
}
}
body.append("<div class=\"med-detail\">")
.append(sig.toString())
.append("</div>\n");
body.append("<div class=\"med-detail\">");
if ((med.getStartDate() != null) && !med.getStartDate().isEmpty()) {
try {
Date dt = DateUtils.convertDateStr(med.getStartDate(), "mm/dd/yyyy");
body.append(super.getStringResource("startDate") + ": ")
.append(DateUtils.formatDate(dt, "MMMM dd, yyyy"))
.append(" ");
} catch(Exception e) {
}
}
if ((med.getStopDate() != null) && !med.getStopDate().isEmpty()) {
try {
Date dt = DateUtils.convertDateStr(med.getStopDate(), "mm/dd/yyyy");
body.append(super.getStringResource("stopDate") + ": ")
.append(DateUtils.formatDate(dt, "MMMM dd, yyyy"));
} catch(Exception e) {
}
}
if ((med.getStartDate() != null) && !med.getStartDate().isEmpty() &&
(med.getStopDate() != null) && !med.getStopDate().isEmpty()) {
body.append("<br/>");
}
body.append(super.getStringResource("documentingFacility") + ": ")
.append(med.getStationName())
.append("</div>\n");
}
}
} finally {
if (this.formatAsHtml) {
super.setContent("remote-non_va_medications", body.toString());
} else {
super.setData("remote-non_va_medications", remoteNonVaMedsList);
}
}
}
}
| apache-2.0 |
JohannesKlug/hbird | src/application/czml-writer/translatedSrc/cesiumlanguagewriter/VectorCesiumWriter.java | 16068 | package cesiumlanguagewriter;
import agi.foundation.compatibility.*;
import agi.foundation.compatibility.DisposeHelper;
import agi.foundation.compatibility.Func1;
import agi.foundation.compatibility.Lazy;
import cesiumlanguagewriter.advanced.*;
import cesiumlanguagewriter.BooleanCesiumWriter;
import cesiumlanguagewriter.ColorCesiumWriter;
import cesiumlanguagewriter.DirectionCesiumWriter;
import cesiumlanguagewriter.DoubleCesiumWriter;
import java.awt.Color;
import java.util.List;
/**
*
Writes a <code>Vector</code> to a {@link CesiumOutputStream}. A <code>Vector</code> defines a graphical vector that originates at the `position` property and extends in the provided direction for the provided length.
*/
public class VectorCesiumWriter extends CesiumPropertyWriter<VectorCesiumWriter> {
/**
*
The name of the <code>show</code> property.
*/
public static final String ShowPropertyName = "show";
/**
*
The name of the <code>color</code> property.
*/
public static final String ColorPropertyName = "color";
/**
*
The name of the <code>width</code> property.
*/
public static final String WidthPropertyName = "width";
/**
*
The name of the <code>direction</code> property.
*/
public static final String DirectionPropertyName = "direction";
/**
*
The name of the <code>length</code> property.
*/
public static final String LengthPropertyName = "length";
private Lazy<BooleanCesiumWriter> m_show = new Lazy<cesiumlanguagewriter.BooleanCesiumWriter>(new Func1<cesiumlanguagewriter.BooleanCesiumWriter>() {
public cesiumlanguagewriter.BooleanCesiumWriter invoke() {
return new BooleanCesiumWriter(ShowPropertyName);
}
}, false);
private Lazy<ColorCesiumWriter> m_color = new Lazy<cesiumlanguagewriter.ColorCesiumWriter>(new Func1<cesiumlanguagewriter.ColorCesiumWriter>() {
public cesiumlanguagewriter.ColorCesiumWriter invoke() {
return new ColorCesiumWriter(ColorPropertyName);
}
}, false);
private Lazy<DoubleCesiumWriter> m_width = new Lazy<cesiumlanguagewriter.DoubleCesiumWriter>(new Func1<cesiumlanguagewriter.DoubleCesiumWriter>() {
public cesiumlanguagewriter.DoubleCesiumWriter invoke() {
return new DoubleCesiumWriter(WidthPropertyName);
}
}, false);
private Lazy<DirectionCesiumWriter> m_direction = new Lazy<cesiumlanguagewriter.DirectionCesiumWriter>(new Func1<cesiumlanguagewriter.DirectionCesiumWriter>() {
public cesiumlanguagewriter.DirectionCesiumWriter invoke() {
return new DirectionCesiumWriter(DirectionPropertyName);
}
}, false);
private Lazy<DoubleCesiumWriter> m_length = new Lazy<cesiumlanguagewriter.DoubleCesiumWriter>(new Func1<cesiumlanguagewriter.DoubleCesiumWriter>() {
public cesiumlanguagewriter.DoubleCesiumWriter invoke() {
return new DoubleCesiumWriter(LengthPropertyName);
}
}, false);
/**
*
Initializes a new instance.
*/
public VectorCesiumWriter(String propertyName) {
super(propertyName);
}
/**
*
Initializes a new instance as a copy of an existing instance.
* @param existingInstance The existing instance to copy.
*/
protected VectorCesiumWriter(VectorCesiumWriter existingInstance) {
super(existingInstance);
}
@Override
public VectorCesiumWriter clone() {
return new VectorCesiumWriter(this);
}
/**
* Gets the writer for the <code>show</code> property. The returned instance must be opened by calling the {@link CesiumElementWriter#open} method before it can be used for writing. The <code>show</code> property defines whether or not the vector is shown.
*/
public final BooleanCesiumWriter getShowWriter() {
return m_show.getValue();
}
/**
*
Opens and returns the writer for the <code>show</code> property. The <code>show</code> property defines whether or not the vector is shown.
*/
public final BooleanCesiumWriter openShowProperty() {
openIntervalIfNecessary();
return this.<BooleanCesiumWriter> openAndReturn(getShowWriter());
}
/**
*
Writes a value for the <code>show</code> property as a <code>boolean</code> value. The <code>show</code> property specifies whether or not the vector is shown.
* @param value The value.
*/
public final void writeShowProperty(boolean value) {
{
cesiumlanguagewriter.BooleanCesiumWriter writer = openShowProperty();
try {
writer.writeBoolean(value);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
* Gets the writer for the <code>color</code> property. The returned instance must be opened by calling the {@link CesiumElementWriter#open} method before it can be used for writing. The <code>color</code> property defines the color of the vector.
*/
public final ColorCesiumWriter getColorWriter() {
return m_color.getValue();
}
/**
*
Opens and returns the writer for the <code>color</code> property. The <code>color</code> property defines the color of the vector.
*/
public final ColorCesiumWriter openColorProperty() {
openIntervalIfNecessary();
return this.<ColorCesiumWriter> openAndReturn(getColorWriter());
}
/**
*
Writes a value for the <code>color</code> property as a <code>rgba</code> value. The <code>color</code> property specifies the color of the vector.
* @param color The color.
*/
public final void writeColorProperty(Color color) {
{
cesiumlanguagewriter.ColorCesiumWriter writer = openColorProperty();
try {
writer.writeRgba(color);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
*
Writes a value for the <code>color</code> property as a <code>rgba</code> value. The <code>color</code> property specifies the color of the vector.
* @param red The red component in the range 0 to 255.
* @param green The green component in the range 0 to 255.
* @param blue The blue component in the range 0 to 255.
* @param alpha The alpha component in the range 0 to 255.
*/
public final void writeColorProperty(int red, int green, int blue, int alpha) {
{
cesiumlanguagewriter.ColorCesiumWriter writer = openColorProperty();
try {
writer.writeRgba(red, green, blue, alpha);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
*
Writes a value for the <code>color</code> property as a <code>rgba</code> value. The <code>color</code> property specifies the color of the vector.
* @param dates The dates at which the value is specified.
* @param colors The color corresponding to each date.
* @param startIndex The index of the first element to use in the `colors` collection.
* @param length The number of elements to use from the `colors` collection.
*/
public final void writeColorProperty(List<JulianDate> dates, List<Color> colors, int startIndex, int length) {
{
cesiumlanguagewriter.ColorCesiumWriter writer = openColorProperty();
try {
writer.writeRgba(dates, colors, startIndex, length);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
*
Writes a value for the <code>color</code> property as a <code>rgbaf</code> value. The <code>color</code> property specifies the color of the vector.
* @param red The red component in the range 0 to 1.0.
* @param green The green component in the range 0 to 1.0.
* @param blue The blue component in the range 0 to 1.0.
* @param alpha The alpha component in the range 0 to 1.0.
*/
public final void writeColorPropertyRgbaf(float red, float green, float blue, float alpha) {
{
cesiumlanguagewriter.ColorCesiumWriter writer = openColorProperty();
try {
writer.writeRgbaf(red, green, blue, alpha);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
* Gets the writer for the <code>width</code> property. The returned instance must be opened by calling the {@link CesiumElementWriter#open} method before it can be used for writing. The <code>width</code> property defines the width of the vector.
*/
public final DoubleCesiumWriter getWidthWriter() {
return m_width.getValue();
}
/**
*
Opens and returns the writer for the <code>width</code> property. The <code>width</code> property defines the width of the vector.
*/
public final DoubleCesiumWriter openWidthProperty() {
openIntervalIfNecessary();
return this.<DoubleCesiumWriter> openAndReturn(getWidthWriter());
}
/**
*
Writes a value for the <code>width</code> property as a <code>number</code> value. The <code>width</code> property specifies the width of the vector.
* @param value The value.
*/
public final void writeWidthProperty(double value) {
{
cesiumlanguagewriter.DoubleCesiumWriter writer = openWidthProperty();
try {
writer.writeNumber(value);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
*
Writes a value for the <code>width</code> property as a <code>number</code> value. The <code>width</code> property specifies the width of the vector.
* @param dates The dates at which the value is specified.
* @param values The value corresponding to each date.
* @param startIndex The index of the first element to use in the `values` collection.
* @param length The number of elements to use from the `values` collection.
*/
public final void writeWidthProperty(List<JulianDate> dates, List<Double> values, int startIndex, int length) {
{
cesiumlanguagewriter.DoubleCesiumWriter writer = openWidthProperty();
try {
writer.writeNumber(dates, values, startIndex, length);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
* Gets the writer for the <code>direction</code> property. The returned instance must be opened by calling the {@link CesiumElementWriter#open} method before it can be used for writing. The <code>direction</code> property defines the direction of the vector.
*/
public final DirectionCesiumWriter getDirectionWriter() {
return m_direction.getValue();
}
/**
*
Opens and returns the writer for the <code>direction</code> property. The <code>direction</code> property defines the direction of the vector.
*/
public final DirectionCesiumWriter openDirectionProperty() {
openIntervalIfNecessary();
return this.<DirectionCesiumWriter> openAndReturn(getDirectionWriter());
}
/**
*
Writes a value for the <code>direction</code> property as a <code>unitCartesian</code> value. The <code>direction</code> property specifies the direction of the vector.
* @param value The value.
*/
public final void writeDirectionProperty(UnitCartesian value) {
{
cesiumlanguagewriter.DirectionCesiumWriter writer = openDirectionProperty();
try {
writer.writeUnitCartesian(value);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
*
Writes a value for the <code>direction</code> property as a <code>unitCartesian</code> value. The <code>direction</code> property specifies the direction of the vector.
* @param dates The dates at which the vector is specified.
* @param values The values corresponding to each date.
*/
public final void writeDirectionProperty(List<JulianDate> dates, List<UnitCartesian> values) {
{
cesiumlanguagewriter.DirectionCesiumWriter writer = openDirectionProperty();
try {
writer.writeUnitCartesian(dates, values);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
*
Writes a value for the <code>direction</code> property as a <code>unitCartesian</code> value. The <code>direction</code> property specifies the direction of the vector.
* @param dates The dates at which the vector is specified.
* @param values The values corresponding to each date.
* @param startIndex The index of the first element to use in the `values` collection.
* @param length The number of elements to use from the `values` collection.
*/
public final void writeDirectionProperty(List<JulianDate> dates, List<UnitCartesian> values, int startIndex, int length) {
{
cesiumlanguagewriter.DirectionCesiumWriter writer = openDirectionProperty();
try {
writer.writeUnitCartesian(dates, values, startIndex, length);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
*
Writes a value for the <code>direction</code> property as a <code>unitSpherical</code> value. The <code>direction</code> property specifies the direction of the vector.
* @param value The value.
*/
public final void writeDirectionPropertyUnitSpherical(UnitSpherical value) {
{
cesiumlanguagewriter.DirectionCesiumWriter writer = openDirectionProperty();
try {
writer.writeUnitSpherical(value);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
*
Writes a value for the <code>direction</code> property as a <code>unitSpherical</code> value. The <code>direction</code> property specifies the direction of the vector.
* @param dates The dates at which the vector is specified.
* @param values The values corresponding to each date.
*/
public final void writeDirectionPropertyUnitSpherical(List<JulianDate> dates, List<UnitSpherical> values) {
{
cesiumlanguagewriter.DirectionCesiumWriter writer = openDirectionProperty();
try {
writer.writeUnitSpherical(dates, values);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
*
Writes a value for the <code>direction</code> property as a <code>unitSpherical</code> value. The <code>direction</code> property specifies the direction of the vector.
* @param dates The dates at which the vector is specified.
* @param values The values corresponding to each date.
* @param startIndex The index of the first element to use in the `values` collection.
* @param length The number of elements to use from the `values` collection.
*/
public final void writeDirectionPropertyUnitSpherical(List<JulianDate> dates, List<UnitSpherical> values, int startIndex, int length) {
{
cesiumlanguagewriter.DirectionCesiumWriter writer = openDirectionProperty();
try {
writer.writeUnitSpherical(dates, values, startIndex, length);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
* Gets the writer for the <code>length</code> property. The returned instance must be opened by calling the {@link CesiumElementWriter#open} method before it can be used for writing. The <code>length</code> property defines the graphical length of the vector.
*/
public final DoubleCesiumWriter getLengthWriter() {
return m_length.getValue();
}
/**
*
Opens and returns the writer for the <code>length</code> property. The <code>length</code> property defines the graphical length of the vector.
*/
public final DoubleCesiumWriter openLengthProperty() {
openIntervalIfNecessary();
return this.<DoubleCesiumWriter> openAndReturn(getLengthWriter());
}
/**
*
Writes a value for the <code>length</code> property as a <code>number</code> value. The <code>length</code> property specifies the graphical length of the vector.
* @param value The value.
*/
public final void writeLengthProperty(double value) {
{
cesiumlanguagewriter.DoubleCesiumWriter writer = openLengthProperty();
try {
writer.writeNumber(value);
} finally {
DisposeHelper.dispose(writer);
}
}
}
/**
*
Writes a value for the <code>length</code> property as a <code>number</code> value. The <code>length</code> property specifies the graphical length of the vector.
* @param dates The dates at which the value is specified.
* @param values The value corresponding to each date.
* @param startIndex The index of the first element to use in the `values` collection.
* @param length The number of elements to use from the `values` collection.
*/
public final void writeLengthProperty(List<JulianDate> dates, List<Double> values, int startIndex, int length) {
{
cesiumlanguagewriter.DoubleCesiumWriter writer = openLengthProperty();
try {
writer.writeNumber(dates, values, startIndex, length);
} finally {
DisposeHelper.dispose(writer);
}
}
}
} | apache-2.0 |
haikuowuya/android_system_code | src/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java | 5025 | /*
* Copyright (c) 2007-2008, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* 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.sun.org.apache.xml.internal.security.utils.resolver.implementations;
import java.io.FileInputStream;
import com.sun.org.apache.xml.internal.utils.URI;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
import org.w3c.dom.Attr;
/**
* A simple ResourceResolver for requests into the local filesystem.
*
* @author $Author: mullan $
*/
public class ResolverLocalFilesystem extends ResourceResolverSpi {
/** {@link java.util.logging} logging facility */
static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(
ResolverLocalFilesystem.class.getName());
public boolean engineIsThreadSafe() {
return true;
}
/**
* @inheritDoc
*/
public XMLSignatureInput engineResolve(Attr uri, String BaseURI)
throws ResourceResolverException {
try {
URI uriNew = getNewURI(uri.getNodeValue(), BaseURI);
// if the URI contains a fragment, ignore it
URI uriNewNoFrag = new URI(uriNew);
uriNewNoFrag.setFragment(null);
String fileName =
ResolverLocalFilesystem
.translateUriToFilename(uriNewNoFrag.toString());
FileInputStream inputStream = new FileInputStream(fileName);
XMLSignatureInput result = new XMLSignatureInput(inputStream);
result.setSourceURI(uriNew.toString());
return result;
} catch (Exception e) {
throw new ResourceResolverException("generic.EmptyMessage", e, uri,
BaseURI);
}
}
private static int FILE_URI_LENGTH="file:/".length();
/**
* Method translateUriToFilename
*
* @param uri
* @return the string of the filename
*/
private static String translateUriToFilename(String uri) {
String subStr = uri.substring(FILE_URI_LENGTH);
if (subStr.indexOf("%20") > -1)
{
int offset = 0;
int index = 0;
StringBuffer temp = new StringBuffer(subStr.length());
do
{
index = subStr.indexOf("%20",offset);
if (index == -1) temp.append(subStr.substring(offset));
else
{
temp.append(subStr.substring(offset,index));
temp.append(' ');
offset = index+3;
}
}
while(index != -1);
subStr = temp.toString();
}
if (subStr.charAt(1) == ':') {
// we're running M$ Windows, so this works fine
return subStr;
}
// we're running some UNIX, so we have to prepend a slash
return "/" + subStr;
}
/**
* @inheritDoc
*/
public boolean engineCanResolve(Attr uri, String BaseURI) {
if (uri == null) {
return false;
}
String uriNodeValue = uri.getNodeValue();
if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#') ||
uriNodeValue.startsWith("http:")) {
return false;
}
try {
//URI uriNew = new URI(new URI(BaseURI), uri.getNodeValue());
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + uriNodeValue/*uriNew.toString()*/);
if ( uriNodeValue.startsWith("file:") ||
BaseURI.startsWith("file:")/*uriNew.getScheme().equals("file")*/) {
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "I state that I can resolve " + uriNodeValue/*uriNew.toString()*/);
return true;
}
} catch (Exception e) {}
log.log(java.util.logging.Level.FINE, "But I can't");
return false;
}
private static URI getNewURI(String uri, String BaseURI)
throws URI.MalformedURIException {
if ((BaseURI == null) || "".equals(BaseURI)) {
return new URI(uri);
}
return new URI(new URI(BaseURI), uri);
}
}
| apache-2.0 |
hazendaz/assertj-core | src/main/java/org/assertj/core/error/ShouldBeFalse.java | 924 | /*
* 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.
*
* Copyright 2012-2021 the original author or authors.
*/
package org.assertj.core.error;
public class ShouldBeFalse extends BasicErrorMessageFactory {
public static ErrorMessageFactory shouldBeFalse(boolean actual) {
return new ShouldBeFalse(actual);
}
private ShouldBeFalse(Object actual) {
super("%nExpecting value to be false but was %s", actual);
}
}
| apache-2.0 |
d2rq/r2rml-kit | src/test/java/org/d2rq/db/schema/ColumnNameTest.java | 4843 | package org.d2rq.db.schema;
import static org.d2rq.db.schema.ColumnName.parse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import java.util.TreeMap;
import org.d2rq.db.schema.ColumnName;
import org.d2rq.db.schema.TableName;
import org.junit.Before;
import org.junit.Test;
/**
* @author Richard Cyganiak (richard@cyganiak.de)
*/
public class ColumnNameTest {
private ColumnName col, xCol, xColB, yCol, fooCol1, fooCol1b, fooCol2, barCol1, barCol2;
private ColumnName uq1, uq1b, uq2;
@Before
public void setUp() {
col = parse("table.column");
xCol = parse("x.table.column");
xColB = parse("x.table.column");
yCol = parse("y.table.column");
fooCol1 = parse("foo.col1");
fooCol1b = parse("foo.col1");
fooCol2 = parse("foo.col2");
barCol1 = parse("bar.col1");
barCol2 = parse("bar.col2");
uq1 = parse("col1");
uq1b = parse("col1");
uq2 = parse("col2");
}
@Test
public void testNames() {
assertEquals("table.column", col.toString());
assertNull(col.getQualifier().getSchema());
assertEquals("table", col.getQualifier().getTable().getName());
assertEquals("column", col.getColumn().getName());
assertEquals(TableName.parse("table"), col.getQualifier());
}
@Test
public void testNameWithSchema() {
assertEquals("x.table.column", xCol.toString());
assertEquals("x", xCol.getQualifier().getSchema().getName());
assertEquals("table", xCol.getQualifier().getTable().getName());
assertEquals("column", xCol.getColumn().getName());
assertEquals(TableName.parse("x.table"), xCol.getQualifier());
}
@Test
public void testEqualTrivial() {
assertTrue(fooCol1.equals(fooCol1b));
assertEquals(fooCol1.hashCode(), fooCol1b.hashCode());
assertTrue(xCol.equals(xColB));
assertEquals(xCol.hashCode(), xColB.hashCode());
}
@Test
public void testDifferentColumnsNotEqual() {
assertFalse(fooCol1.equals(fooCol2));
assertFalse(fooCol2.equals(fooCol1));
assertFalse(fooCol1.hashCode() == fooCol2.hashCode());
}
@Test
public void testDifferentTablesNotEqual() {
assertFalse(fooCol1.equals(barCol1));
assertFalse(barCol1.equals(fooCol1));
assertFalse(fooCol1.hashCode() == barCol1.hashCode());
}
@Test
public void testNotEqualNull() {
assertFalse(fooCol1.equals(null));
}
@Test
public void testNotEqualToOtherClass() {
assertFalse(fooCol1.equals(new Integer(42)));
assertFalse(new Integer(42).equals(fooCol1));
}
@Test
public void testEqualityWithSchema() {
assertFalse(col.equals(xCol));
assertFalse(xCol.equals(col));
assertFalse(xCol.equals(yCol));
assertTrue(xCol.equals(xColB));
}
@Test
public void testEqualityUnqualifiedSame() {
assertEquals(uq1, uq1b);
assertEquals(uq1.hashCode(), uq1b.hashCode());
}
@Test
public void testEqualityUnqualifiedDifferent() {
assertFalse(uq1.equals(uq2));
assertFalse(uq1.hashCode() == uq2.hashCode());
}
@Test
public void testQualifiedUnqualifiedDifferent() {
assertFalse(uq1.equals(fooCol1));
assertFalse(fooCol1.equals(uq1));
assertFalse(uq1.hashCode() == fooCol1.hashCode());
}
@Test
public void testToString() {
assertEquals("table.column", col.toString());
assertEquals("x.table.column", xCol.toString());
}
@Test
public void testCompareSame() {
assertEquals(0, fooCol1.compareTo(fooCol1));
}
@Test
public void testCompareSameTable() {
assertTrue(fooCol1.compareTo(fooCol2) < 0);
assertTrue(fooCol2.compareTo(fooCol1) > 0);
}
@Test
public void testCompareSameColumnDifferentTable() {
assertTrue(barCol1.compareTo(fooCol1) < 0);
assertTrue(fooCol1.compareTo(barCol2) > 0);
}
@Test
public void testCompareDifferentColumnDifferentTable() {
assertTrue(barCol2.compareTo(fooCol1) < 0);
assertTrue(fooCol1.compareTo(barCol2) > 0);
}
@Test
public void testNoSchemaSmallerThanSchema() {
assertTrue(uq1.compareTo(fooCol1) < 0);
assertTrue(fooCol1.compareTo(uq1) > 0);
ColumnName noSchema = parse("z.col");
ColumnName schema = parse("schema.a.col");
assertTrue(noSchema.compareTo(schema) < 0);
assertTrue(schema.compareTo(noSchema) > 0);
}
@Test
public void testGetUnqualified() {
assertFalse(uq1.isQualified());
assertTrue(fooCol1.isQualified());
assertEquals(uq1, fooCol1.getUnqualified());
assertFalse(fooCol1.equals(fooCol1.getUnqualified()));
assertTrue(uq1.equals(uq1.getUnqualified()));
}
@Test
public void testTreeMap() {
ColumnName fooBar = ColumnName.parse("foo.bar");
Map<ColumnName,String> test = new TreeMap<ColumnName,String>();
test.put(fooBar, "x");
assertTrue(test.containsKey(fooBar));
assertFalse(test.containsKey(fooBar.getUnqualified()));
test.put(fooBar.getUnqualified(), "y");
assertEquals(2, test.size());
}
}
| apache-2.0 |
TomRoush/PdfBox-Android | library/src/main/java/com/tom_roush/pdfbox/contentstream/operator/text/MoveTextSetLeading.java | 2283 | /*
* 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 com.tom_roush.pdfbox.contentstream.operator.text;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.tom_roush.pdfbox.contentstream.operator.MissingOperandException;
import com.tom_roush.pdfbox.cos.COSBase;
import com.tom_roush.pdfbox.cos.COSFloat;
import com.tom_roush.pdfbox.cos.COSNumber;
import com.tom_roush.pdfbox.contentstream.operator.Operator;
import com.tom_roush.pdfbox.contentstream.operator.OperatorName;
import com.tom_roush.pdfbox.contentstream.operator.OperatorProcessor;
/**
* TD: Move text position and set leading.
*
* @author Laurent Huault
*/
public class MoveTextSetLeading extends OperatorProcessor
{
@Override
public void process(Operator operator, List<COSBase> arguments) throws IOException
{
if (arguments.size() < 2)
{
throw new MissingOperandException(operator, arguments);
}
//move text position and set leading
COSBase base1 = arguments.get(1);
if (!(base1 instanceof COSNumber))
{
return;
}
COSNumber y = (COSNumber) base1;
List<COSBase> args = new ArrayList<COSBase>();
args.add(new COSFloat(-1 * y.floatValue()));
context.processOperator(OperatorName.SET_TEXT_LEADING, args);
context.processOperator(OperatorName.MOVE_TEXT, arguments);
}
@Override
public String getName()
{
return OperatorName.MOVE_TEXT_SET_LEADING;
}
}
| apache-2.0 |