repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
adrienlauer/kernel | core/src/test/java/io/nuun/kernel/core/internal/scanner/sample/HolderForContext.java | 996 | /**
* Copyright (C) 2013-2014 Kametic <epo.jemba@kametic.com>
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007;
* or any later version
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.nuun.kernel.core.internal.scanner.sample;
import io.nuun.kernel.api.plugin.context.Context;
import javax.inject.Inject;
public class HolderForContext
{
public final Context context;
@Inject
public HolderForContext(Context context)
{
this.context = context;
}
} | lgpl-3.0 |
datacleaner/AnalyzerBeans | components/html-rendering/src/main/java/org/eobjects/analyzer/result/renderer/CrosstabHtmlFragment.java | 2095 | /**
* AnalyzerBeans
* Copyright (C) 2014 Neopost - Customer Information Management
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.eobjects.analyzer.result.renderer;
import java.util.List;
import org.eobjects.analyzer.result.Crosstab;
import org.eobjects.analyzer.result.html.BodyElement;
import org.eobjects.analyzer.result.html.HeadElement;
import org.eobjects.analyzer.result.html.HtmlFragment;
import org.eobjects.analyzer.result.html.HtmlRenderingContext;
public class CrosstabHtmlFragment implements HtmlFragment {
private final Crosstab<?> _crosstab;
private final RendererFactory _rendererFactory;
private HtmlFragment _htmlFragment;
public CrosstabHtmlFragment(Crosstab<?> crosstab, RendererFactory rendererFactory) {
_crosstab = crosstab;
_rendererFactory = rendererFactory;
}
@Override
public void initialize(HtmlRenderingContext context) {
CrosstabRenderer crosstabRenderer = new CrosstabRenderer(_crosstab);
HtmlFragment htmlFragment = crosstabRenderer.render(new HtmlCrosstabRendererCallback(_rendererFactory,
context));
_htmlFragment = htmlFragment;
}
@Override
public List<HeadElement> getHeadElements() {
return _htmlFragment.getHeadElements();
}
@Override
public List<BodyElement> getBodyElements() {
return _htmlFragment.getBodyElements();
}
}
| lgpl-3.0 |
zenframework/z8 | org.zenframework.z8.server/src/main/java/org/zenframework/z8/server/db/sql/functions/conversion/GuidToString.java | 1365 | package org.zenframework.z8.server.db.sql.functions.conversion;
import java.util.Collection;
import org.zenframework.z8.server.base.table.value.Field;
import org.zenframework.z8.server.base.table.value.IField;
import org.zenframework.z8.server.db.DatabaseVendor;
import org.zenframework.z8.server.db.FieldType;
import org.zenframework.z8.server.db.sql.FormatOptions;
import org.zenframework.z8.server.db.sql.SqlField;
import org.zenframework.z8.server.db.sql.SqlToken;
import org.zenframework.z8.server.exceptions.db.UnknownDatabaseException;
public class GuidToString extends SqlToken {
private SqlToken guid;
public GuidToString(Field field) {
this(new SqlField(field));
}
public GuidToString(SqlToken guid) {
this.guid = guid;
}
@Override
public void collectFields(Collection<IField> fields) {
guid.collectFields(fields);
}
@Override
public String format(DatabaseVendor vendor, FormatOptions options, boolean logicalContext) {
String param = guid.format(vendor, options);
switch(vendor) {
case Postgres:
return param + "::text";
case Oracle:
return "RAWTOHEX(" + param + ")";
case SqlServer:
return "Convert(nvarchar(40), " + param + ")";
default:
throw new UnknownDatabaseException();
}
}
@Override
public FieldType type() {
return FieldType.String;
}
}
| lgpl-3.0 |
IlyaAI/xacml4j | xacml-core/src/main/java/org/xacml4j/v30/spi/function/AggregatingFunctionProvider.java | 3611 | package org.xacml4j.v30.spi.function;
/*
* #%L
* Xacml4J Core Engine Implementation
* %%
* Copyright (C) 2009 - 2014 Xacml4J.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xacml4j.v30.pdp.FunctionSpec;
import com.google.common.base.Preconditions;
/**
* An implementation of {@link FunctionProvider} which
* aggregates instances of {@link FunctionProvider}
*
* @author Giedrius Trumpickas
*/
public class AggregatingFunctionProvider
implements FunctionProvider
{
private final static Logger log = LoggerFactory.getLogger(AggregatingFunctionProvider.class);
private Map<String, FunctionProvider> functions;
public AggregatingFunctionProvider(){
this.functions = new ConcurrentHashMap<String, FunctionProvider>();
}
public AggregatingFunctionProvider(FunctionProvider ...providers){
this(Arrays.asList(providers));
}
/**
* Creates aggregating function provider with a given providers
*
* @param providers a collection of {@link FunctionProvider} instances
*/
public AggregatingFunctionProvider(Collection<FunctionProvider> providers){
this.functions = new ConcurrentHashMap<String, FunctionProvider>();
for(FunctionProvider p : providers){
add(p);
}
}
/**
* Adds {@link FunctionProvider} to this aggregating provider
*
* @param provider a provider instance
* @exception IllegalArgumentException if function exported via
* given provider already exported via provider previously registered
* with this aggregating provider
*/
public final void add(FunctionProvider provider)
{
Preconditions.checkNotNull(provider);
for(String functionId : provider.getProvidedFunctions())
{
if(functions.containsKey(functionId)){
throw new IllegalArgumentException(
String.format(
"Function provider already contains a function with functionId=\"%s\"",
functionId));
}
FunctionSpec spec = provider.getFunction(functionId);
if(log.isDebugEnabled()){
log.debug("Adding function=\"{}\"", functionId);
}
Preconditions.checkArgument(spec != null);
this.functions.put(functionId, provider);
}
}
@Override
public final FunctionSpec remove(String functionId) {
FunctionProvider p = functions.remove(functionId);
return (p != null)?p.getFunction(functionId):null;
}
@Override
public final FunctionSpec getFunction(String functionId) {
FunctionProvider provider = functions.get(functionId);
return (provider != null)?provider.getFunction(functionId):null;
}
@Override
public final Iterable<String> getProvidedFunctions() {
return Collections.unmodifiableCollection(functions.keySet());
}
@Override
public final boolean isFunctionProvided(String functionId) {
return functions.containsKey(functionId);
}
}
| lgpl-3.0 |
qspin/qtaste | plugins_src/opcua/src/main/java/com/prosysopc/ua/ServiceException.java | 798 | /* This file is derived from the javadoc API provided in the Prosys OPC-UA Java SDK Client/Server evaluation package (release 2.2.6-708)
* As seen as, for licensing reasons, QTaste may not redistribute the Prosys OPC-UA Java SDK client jar file, the needed classes and methods are mocked-up to allow to build QTaste and all the testAPIs without requiring the Prosys OPC-UA Java SDK client jar file at build time.
* None of those mock-up classes are present in the QTaste jars file.
*
* For using the QTaste OPC-UA testAPI, you'll need to contact Prosys (www.prosysopc.com) to obtain the OPC-UA Java SDK client jar file and add a dependency to this jar file in the pom.xml of your testapi folder.
*/
package com.prosysopc.ua;
public class ServiceException extends Exception {
} | lgpl-3.0 |
SergiyKolesnikov/fuji | benchmark_typechecker/subjectSystems/Notepad/FormatStyled_stubfix/Notepad.java | 700 | import de.uni_passau.spl.bytecodecomposer.stubs.Stub;
import java.lang.String;
import java.lang.Object;
import java.awt.event.ActionEvent;
import javax.swing.text.StyleConstants;
import javax.swing.JComboBox;
import java.awt.Container;
import javax.swing.text.StyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleContext;
import javax.swing.JTextPane;
import java.awt.event.ActionListener;
import javax.swing.JToolBar;
public class Notepad extends javax.swing.JFrame {
@Stub
public javax.swing.JTextPane getTextPane() {
return null;
}
@Stub
public Actions actions;
@Stub
public javax.swing.JToolBar original() {
return null;
}
}
| lgpl-3.0 |
ArticulatedSocialAgentsPlatform/AsapRealizer | Experimental/AsapStompROSNaoEngine/src/asap/srnao/planunit/NaoUnit.java | 2840 | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package asap.srnao.planunit;
import asap.realizer.feedback.FeedbackManager;
import asap.realizer.pegboard.BMLBlockPeg;
import asap.realizer.planunit.KeyPositionManager;
import asap.realizer.planunit.ParameterException;
import asap.srnao.loader.StompROSNaoEmbodiment;
/**
* Contains a set of keys that map to 'world' time to animation time.
* @author Daniel
*/
public interface NaoUnit extends KeyPositionManager
{
void setFloatParameterValue(String name, float value)throws ParameterException;
void setParameterValue(String name, String value)throws ParameterException;
String getParameterValue(String name)throws ParameterException;
float getFloatParameterValue(String name)throws ParameterException;
boolean hasValidParameters();
/** start the unit.*/
void startUnit(double time) throws NUPlayException;
/**
* Executes the nao unit
* @param t execution time, 0 < t < 1
* @throws NUPlayException if the play fails for some reason
*/
void play(double t)throws NUPlayException;
/** Clean up the unit - i.e. remove traces of this naounit */
void cleanup();
/**
* Creates the TimedNaoUnit corresponding to this nao unit
* @param bmlId BML block id
* @param id behavior id
* @return the TNU
*/
TimedNaoUnit createTNU(FeedbackManager bfm, BMLBlockPeg bbPeg,String bmlId,String id);
boolean isBehaviorRunning();
/**
* @return Preferred duration (in seconds) of this nao unit, 0 means not determined/infinite
*/
double getPreferedDuration();
/**
* Create a copy of this nao unit
*/
NaoUnit copy(StompROSNaoEmbodiment naoEmbodiment);
} | lgpl-3.0 |
chatcenter/android | src/main/java/ly/appsocial/chatcenter/dto/ws/response/WsMessagesResponseDto.java | 201 | package ly.appsocial.chatcenter.dto.ws.response;
import ly.appsocial.chatcenter.dto.ChatItem;
/**
* [WebSocket message:message] response.
*/
public class WsMessagesResponseDto extends ChatItem {
}
| lgpl-3.0 |
cismet/watergis-client | src/main/java/de/cismet/watergis/gui/actions/merge/MergeException.java | 914 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* 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 de.cismet.watergis.gui.actions.merge;
/**
* DOCUMENT ME!
*
* @author therter
* @version $Revision$, $Date$
*/
public class MergeException extends Exception {
//~ Constructors -----------------------------------------------------------
/**
* Creates a new MergeException object.
*/
public MergeException() {
}
/**
* Creates a new MergeException object.
*
* @param message DOCUMENT ME!
*/
public MergeException(final String message) {
super(message);
}
}
| lgpl-3.0 |
devmix/java-commons | commons-i18n/src/main/java/com/github/devmix/commons/i18n/core/exceptions/CircularReferenceException.java | 1118 | /*
* Commons Library
* Copyright (c) 2015 Sergey Grachev (sergey.grachev@yahoo.com). All rights reserved.
*
* This software 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 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, see <http://www.gnu.org/licenses/>.
*/
package com.github.devmix.commons.i18n.core.exceptions;
/**
* @author Sergey Grachev
*/
public final class CircularReferenceException extends RuntimeException {
private static final long serialVersionUID = -7130053754903630354L;
public CircularReferenceException(final String message) {
super(message);
}
}
| lgpl-3.0 |
lmu-bioinformatics/xmlpipedb | godb/src/generated/impl/SubsetdefImpl.java | 14943 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v1.0.5-09/29/2005 11:56 AM(valikov)-fcs
// 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: 2016.10.09 at 03:44:18 PM PDT
//
package generated.impl;
public class SubsetdefImpl implements generated.Subsetdef, com.sun.xml.bind.RIElement, com.sun.xml.bind.JAXBObject, generated.impl.runtime.UnmarshallableObject, generated.impl.runtime.XMLSerializable, generated.impl.runtime.ValidatableObject
{
protected com.sun.xml.bind.util.ListImpl _Content;
public final static java.lang.Class version = (generated.impl.JAXBVersion.class);
private static com.sun.msv.grammar.Grammar schemaFragment;
protected java.lang.Long _Hjid;
protected java.lang.Long _Hjversion;
private final static java.lang.Class PRIMARY_INTERFACE_CLASS() {
return (generated.Subsetdef.class);
}
public java.lang.String ____jaxb_ri____getNamespaceURI() {
return "";
}
public java.lang.String ____jaxb_ri____getLocalName() {
return "subsetdef";
}
protected com.sun.xml.bind.util.ListImpl _getContent() {
if (_Content == null) {
_Content = new com.sun.xml.bind.util.ListImpl(new java.util.ArrayList());
}
return _Content;
}
public java.util.List getContent() {
return _getContent();
}
public generated.impl.runtime.UnmarshallingEventHandler createUnmarshaller(generated.impl.runtime.UnmarshallingContext context) {
return new generated.impl.SubsetdefImpl.Unmarshaller(context);
}
public void serializeBody(generated.impl.runtime.XMLSerializer context)
throws org.xml.sax.SAXException
{
int idx1 = 0;
final int len1 = ((_Content == null)? 0 :_Content.size());
context.startElement("", "subsetdef");
int idx_0 = idx1;
while (idx_0 != len1) {
context.childAsURIs(((com.sun.xml.bind.JAXBObject) _Content.get(idx_0 ++)), "Content");
}
context.endNamespaceDecls();
int idx_1 = idx1;
while (idx_1 != len1) {
context.childAsAttributes(((com.sun.xml.bind.JAXBObject) _Content.get(idx_1 ++)), "Content");
}
context.endAttributes();
while (idx1 != len1) {
context.childAsBody(((com.sun.xml.bind.JAXBObject) _Content.get(idx1 ++)), "Content");
}
context.endElement();
}
public void serializeAttributes(generated.impl.runtime.XMLSerializer context)
throws org.xml.sax.SAXException
{
int idx1 = 0;
final int len1 = ((_Content == null)? 0 :_Content.size());
}
public void serializeURIs(generated.impl.runtime.XMLSerializer context)
throws org.xml.sax.SAXException
{
int idx1 = 0;
final int len1 = ((_Content == null)? 0 :_Content.size());
}
public java.lang.Class getPrimaryInterface() {
return (generated.Subsetdef.class);
}
public com.sun.msv.verifier.DocumentDeclaration createRawValidator() {
if (schemaFragment == null) {
schemaFragment = com.sun.xml.bind.validator.SchemaDeserializer.deserialize((
"\u00ac\u00ed\u0000\u0005sr\u0000\'com.sun.msv.grammar.trex.ElementPattern\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0001L\u0000"
+"\tnameClasst\u0000\u001fLcom/sun/msv/grammar/NameClass;xr\u0000\u001ecom.sun.msv."
+"grammar.ElementExp\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0002Z\u0000\u001aignoreUndeclaredAttributesL\u0000"
+"\fcontentModelt\u0000 Lcom/sun/msv/grammar/Expression;xr\u0000\u001ecom.sun."
+"msv.grammar.Expression\u00f8\u0018\u0082\u00e8N5~O\u0002\u0000\u0002L\u0000\u0013epsilonReducibilityt\u0000\u0013Lj"
+"ava/lang/Boolean;L\u0000\u000bexpandedExpq\u0000~\u0000\u0003xppp\u0000sr\u0000 com.sun.msv.gra"
+"mmar.OneOrMoreExp\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0000xr\u0000\u001ccom.sun.msv.grammar.UnaryExp"
+"\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0001L\u0000\u0003expq\u0000~\u0000\u0003xq\u0000~\u0000\u0004ppsr\u0000\u001dcom.sun.msv.grammar.Choice"
+"Exp\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0000xr\u0000\u001dcom.sun.msv.grammar.BinaryExp\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0002L\u0000"
+"\u0004exp1q\u0000~\u0000\u0003L\u0000\u0004exp2q\u0000~\u0000\u0003xq\u0000~\u0000\u0004ppsq\u0000~\u0000\nsr\u0000\u0011java.lang.Boolean\u00cd r"
+"\u0080\u00d5\u009c\u00fa\u00ee\u0002\u0000\u0001Z\u0000\u0005valuexp\u0000psq\u0000~\u0000\nq\u0000~\u0000\u000fpsq\u0000~\u0000\u0000q\u0000~\u0000\u000fp\u0000sq\u0000~\u0000\nppsq\u0000~\u0000\u0007q"
+"\u0000~\u0000\u000fpsr\u0000 com.sun.msv.grammar.AttributeExp\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0002L\u0000\u0003expq\u0000"
+"~\u0000\u0003L\u0000\tnameClassq\u0000~\u0000\u0001xq\u0000~\u0000\u0004q\u0000~\u0000\u000fpsr\u00002com.sun.msv.grammar.Expr"
+"ession$AnyStringExpression\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0000xq\u0000~\u0000\u0004sq\u0000~\u0000\u000e\u0001q\u0000~\u0000\u0017sr\u0000 c"
+"om.sun.msv.grammar.AnyNameClass\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0000xr\u0000\u001dcom.sun.msv.gr"
+"ammar.NameClass\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0000xpsr\u00000com.sun.msv.grammar.Expressi"
+"on$EpsilonExpression\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0000xq\u0000~\u0000\u0004q\u0000~\u0000\u0018q\u0000~\u0000\u001dsr\u0000#com.sun.m"
+"sv.grammar.SimpleNameClass\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002\u0000\u0002L\u0000\tlocalNamet\u0000\u0012Ljava/la"
+"ng/String;L\u0000\fnamespaceURIq\u0000~\u0000\u001fxq\u0000~\u0000\u001at\u0000\fgenerated.Idt\u0000+http:/"
+"/java.sun.com/jaxb/xjc/dummy-elementssq\u0000~\u0000\u0000q\u0000~\u0000\u000fp\u0000sq\u0000~\u0000\nppsq"
+"\u0000~\u0000\u0007q\u0000~\u0000\u000fpsq\u0000~\u0000\u0014q\u0000~\u0000\u000fpq\u0000~\u0000\u0017q\u0000~\u0000\u001bq\u0000~\u0000\u001dsq\u0000~\u0000\u001et\u0000\u000egenerated.Name"
+"q\u0000~\u0000\"sq\u0000~\u0000\u0007q\u0000~\u0000\u000fpsq\u0000~\u0000\u0000q\u0000~\u0000\u000fp\u0000sq\u0000~\u0000\nppsq\u0000~\u0000\u0007q\u0000~\u0000\u000fpsq\u0000~\u0000\u0014q\u0000~\u0000"
+"\u000fpq\u0000~\u0000\u0017q\u0000~\u0000\u001bq\u0000~\u0000\u001dsq\u0000~\u0000\u001et\u0000\u0010generated.Dbxrefq\u0000~\u0000\"q\u0000~\u0000\u001dsq\u0000~\u0000\u001et\u0000"
+"\tsubsetdeft\u0000\u0000sr\u0000\"com.sun.msv.grammar.ExpressionPool\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u0002"
+"\u0000\u0001L\u0000\bexpTablet\u0000/Lcom/sun/msv/grammar/ExpressionPool$ClosedHa"
+"sh;xpsr\u0000-com.sun.msv.grammar.ExpressionPool$ClosedHash\u00d7j\u00d0N\u00ef\u00e8"
+"\u00ed\u001c\u0003\u0000\u0003I\u0000\u0005countB\u0000\rstreamVersionL\u0000\u0006parentt\u0000$Lcom/sun/msv/gramma"
+"r/ExpressionPool;xp\u0000\u0000\u0000\u000b\u0001pq\u0000~\u0000\fq\u0000~\u0000)q\u0000~\u0000\u0010q\u0000~\u0000\tq\u0000~\u0000\u0013q\u0000~\u0000%q\u0000~\u0000,"
+"q\u0000~\u0000\rq\u0000~\u0000\u0012q\u0000~\u0000$q\u0000~\u0000+x"));
}
return new com.sun.msv.verifier.regexp.REDocumentDeclaration(schemaFragment);
}
public boolean equals(java.lang.Object obj) {
if (this == obj) {
return true;
}
if ((null == obj)||(!(obj instanceof generated.Subsetdef))) {
return false;
}
generated.impl.SubsetdefImpl target = ((generated.impl.SubsetdefImpl) obj);
{
java.util.List value = this.getContent();
java.util.List targetValue = target.getContent();
if (!((value == targetValue)||((value!= null)&&value.equals(targetValue)))) {
return false;
}
}
return true;
}
public int hashCode() {
int hash = 7;
{
java.util.List value = this.getContent();
hash = ((31 *hash)+((null == value)? 0 :value.hashCode()));
}
return hash;
}
public java.lang.Long getHjid() {
return _Hjid;
}
public void setHjid(java.lang.Long value) {
_Hjid = value;
}
public java.lang.Long getHjversion() {
return _Hjversion;
}
public void setHjversion(java.lang.Long value) {
_Hjversion = value;
}
public class Unmarshaller
extends generated.impl.runtime.AbstractUnmarshallingEventHandlerImpl
{
public Unmarshaller(generated.impl.runtime.UnmarshallingContext context) {
super(context, "----");
}
protected Unmarshaller(generated.impl.runtime.UnmarshallingContext context, int startState) {
this(context);
state = startState;
}
public java.lang.Object owner() {
return generated.impl.SubsetdefImpl.this;
}
public void enterElement(java.lang.String ___uri, java.lang.String ___local, java.lang.String ___qname, org.xml.sax.Attributes __atts)
throws org.xml.sax.SAXException
{
int attIdx;
outer:
while (true) {
switch (state) {
case 0 :
if (("subsetdef" == ___local)&&("" == ___uri)) {
context.pushAttributes(__atts, false);
state = 1;
return ;
}
break;
case 1 :
if (("id" == ___local)&&("" == ___uri)) {
_getContent().add(((generated.impl.IdImpl) spawnChildFromEnterElement((generated.impl.IdImpl.class), 2, ___uri, ___local, ___qname, __atts)));
return ;
}
if (("name" == ___local)&&("" == ___uri)) {
_getContent().add(((generated.impl.NameImpl) spawnChildFromEnterElement((generated.impl.NameImpl.class), 2, ___uri, ___local, ___qname, __atts)));
return ;
}
if (("dbxref" == ___local)&&("" == ___uri)) {
_getContent().add(((generated.impl.DbxrefImpl) spawnChildFromEnterElement((generated.impl.DbxrefImpl.class), 2, ___uri, ___local, ___qname, __atts)));
return ;
}
state = 2;
continue outer;
case 2 :
if (("id" == ___local)&&("" == ___uri)) {
_getContent().add(((generated.impl.IdImpl) spawnChildFromEnterElement((generated.impl.IdImpl.class), 2, ___uri, ___local, ___qname, __atts)));
return ;
}
if (("name" == ___local)&&("" == ___uri)) {
_getContent().add(((generated.impl.NameImpl) spawnChildFromEnterElement((generated.impl.NameImpl.class), 2, ___uri, ___local, ___qname, __atts)));
return ;
}
if (("dbxref" == ___local)&&("" == ___uri)) {
_getContent().add(((generated.impl.DbxrefImpl) spawnChildFromEnterElement((generated.impl.DbxrefImpl.class), 2, ___uri, ___local, ___qname, __atts)));
return ;
}
break;
case 3 :
revertToParentFromEnterElement(___uri, ___local, ___qname, __atts);
return ;
}
super.enterElement(___uri, ___local, ___qname, __atts);
break;
}
}
public void leaveElement(java.lang.String ___uri, java.lang.String ___local, java.lang.String ___qname)
throws org.xml.sax.SAXException
{
int attIdx;
outer:
while (true) {
switch (state) {
case 1 :
state = 2;
continue outer;
case 2 :
if (("subsetdef" == ___local)&&("" == ___uri)) {
context.popAttributes();
state = 3;
return ;
}
break;
case 3 :
revertToParentFromLeaveElement(___uri, ___local, ___qname);
return ;
}
super.leaveElement(___uri, ___local, ___qname);
break;
}
}
public void enterAttribute(java.lang.String ___uri, java.lang.String ___local, java.lang.String ___qname)
throws org.xml.sax.SAXException
{
int attIdx;
outer:
while (true) {
switch (state) {
case 1 :
state = 2;
continue outer;
case 3 :
revertToParentFromEnterAttribute(___uri, ___local, ___qname);
return ;
}
super.enterAttribute(___uri, ___local, ___qname);
break;
}
}
public void leaveAttribute(java.lang.String ___uri, java.lang.String ___local, java.lang.String ___qname)
throws org.xml.sax.SAXException
{
int attIdx;
outer:
while (true) {
switch (state) {
case 1 :
state = 2;
continue outer;
case 3 :
revertToParentFromLeaveAttribute(___uri, ___local, ___qname);
return ;
}
super.leaveAttribute(___uri, ___local, ___qname);
break;
}
}
public void handleText(final java.lang.String value)
throws org.xml.sax.SAXException
{
int attIdx;
outer:
while (true) {
try {
switch (state) {
case 1 :
state = 2;
continue outer;
case 3 :
revertToParentFromText(value);
return ;
}
} catch (java.lang.RuntimeException e) {
handleUnexpectedTextException(value, e);
}
break;
}
}
}
}
| lgpl-3.0 |
hylkevds/Configurable | src/main/java/de/fraunhofer/iosb/ilt/configurable/editor/EditorBigDecimal.java | 6277 | /*
* Copyright (C) 2017 Fraunhofer IOSB
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.fraunhofer.iosb.ilt.configurable.editor;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonPrimitive;
import static de.fraunhofer.iosb.ilt.configurable.ConfigEditor.DEFAULT_PROFILE_NAME;
import de.fraunhofer.iosb.ilt.configurable.GuiFactoryFx;
import de.fraunhofer.iosb.ilt.configurable.GuiFactorySwing;
import static de.fraunhofer.iosb.ilt.configurable.annotations.AnnotationHelper.csvToReadOnlySet;
import de.fraunhofer.iosb.ilt.configurable.editor.fx.FactoryBigDecimalFx;
import de.fraunhofer.iosb.ilt.configurable.editor.swing.FactoryBigDecimalSwing;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Set;
/**
*
* @author Hylke van der Schaaf
*/
public class EditorBigDecimal extends EditorDefault<BigDecimal> {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public static @interface EdOptsBigDecimal {
double min() default Double.NEGATIVE_INFINITY;
double max() default Double.POSITIVE_INFINITY;
/**
* The default value, must not be NaN, NEGATIVE_INFINITY nor
* POSITIVE_INFINITY
*
* @return The default value. Used if dfltIsNull is false.
*/
double dflt() default 0;
/**
* If set to true, the default value of the editor is null.
*
* @return if true, the default value of the editor is null, not the
* value of dflt.
*/
boolean dfltIsNull() default false;
/**
* A comma separated, case insensitive list of profile names. This field
* is only editable when one of these profiles is active. The "default"
* profile is automatically added to the list.
*
* @return A comma separated, case insensitive list of profile names.
*/
String profilesEdit() default "";
}
private BigDecimal min;
private BigDecimal max;
private BigDecimal dflt;
private BigDecimal value;
public Set<String> profilesEdit = csvToReadOnlySet("");
private String profile = DEFAULT_PROFILE_NAME;
private FactoryBigDecimalSwing factorySwing;
private FactoryBigDecimalFx factoryFx;
public EditorBigDecimal() {
}
public EditorBigDecimal(BigDecimal min, BigDecimal max, BigDecimal deflt) {
this.dflt = deflt;
this.value = deflt;
this.min = min;
this.max = max;
}
public EditorBigDecimal(BigDecimal min, BigDecimal max, BigDecimal deflt, String label, String description) {
this.dflt = deflt;
this.value = deflt;
this.min = min;
this.max = max;
setLabel(label);
setDescription(description);
}
private BigDecimal fromDouble(double value) {
if (value == Double.NEGATIVE_INFINITY || value == Double.POSITIVE_INFINITY || value == Double.NaN) {
return null;
}
return new BigDecimal(value);
}
@Override
public void initFor(Field field) {
EdOptsBigDecimal annotation = field.getAnnotation(EdOptsBigDecimal.class);
if (annotation == null) {
throw new IllegalArgumentException("Field must have an EdOptsDouble annotation to use this editor: " + field.getName());
}
min = fromDouble(annotation.min());
max = fromDouble(annotation.max());
if (!annotation.dfltIsNull()) {
dflt = new BigDecimal(annotation.dflt());
}
value = dflt;
profilesEdit = csvToReadOnlySet(annotation.profilesEdit());
}
@Override
public void setConfig(JsonElement config) {
if (config != null && config.isJsonPrimitive()) {
value = config.getAsBigDecimal();
} else {
value = dflt;
}
fillComponent();
}
@Override
public JsonElement getConfig() {
readComponent();
if (value == null) {
return JsonNull.INSTANCE;
}
return new JsonPrimitive(value);
}
@Override
public GuiFactorySwing getGuiFactorySwing() {
if (factoryFx != null) {
throw new IllegalArgumentException("Can not mix different types of editors.");
}
if (factorySwing == null) {
factorySwing = new FactoryBigDecimalSwing(this);
}
return factorySwing;
}
@Override
public GuiFactoryFx getGuiFactoryFx() {
if (factorySwing != null) {
throw new IllegalArgumentException("Can not mix different types of editors.");
}
if (factoryFx == null) {
factoryFx = new FactoryBigDecimalFx(this);
}
return factoryFx;
}
private void fillComponent() {
if (factorySwing != null) {
factorySwing.fillComponent();
}
if (factoryFx != null) {
factoryFx.fillComponent();
}
}
private void readComponent() {
if (factorySwing != null) {
factorySwing.readComponent();
}
if (factoryFx != null) {
factoryFx.readComponent();
}
}
public BigDecimal getMin() {
return min;
}
public BigDecimal getMax() {
return max;
}
public BigDecimal getDeflt() {
return dflt;
}
public BigDecimal getRawValue() {
return value;
}
public void setRawValue(BigDecimal value) {
if (min != null && min.compareTo(value) > 0) {
value = min;
}
if (max != null && max.compareTo(value) < 0) {
value = max;
}
this.value = value;
}
@Override
public BigDecimal getValue() {
readComponent();
return value;
}
@Override
public void setValue(BigDecimal value) {
this.value = value;
fillComponent();
}
@Override
public void setProfile(String profile) {
this.profile = profile;
fillComponent();
}
public void setProfilesEdit(String csv) {
profilesEdit = csvToReadOnlySet(csv);
}
@Override
public boolean canEdit() {
return profilesEdit.contains(profile);
}
@Override
public boolean isDefault() {
readComponent();
return dflt == value;
}
}
| lgpl-3.0 |
nuun-io/kernel | core/src/test/java/io/nuun/kernel/core/internal/concerns/sample/BugConcern.java | 1092 | /**
* This file is part of Nuun IO Kernel Core.
*
* Nuun IO Kernel Core 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 Core 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 Core. If not, see <http://www.gnu.org/licenses/>.
*/
package io.nuun.kernel.core.internal.concerns.sample;
import io.nuun.kernel.spi.Concern;
import java.lang.annotation.*;
@Concern(name = "bug", priority = Concern.Priority.HIGHEST, order = Integer.MAX_VALUE)
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface BugConcern
{
}
| lgpl-3.0 |
loftuxab/community-edition-old | projects/alfresco-jlan/source/java/org/alfresco/jlan/util/MemorySize.java | 4973 | /*
* Copyright (C) 2006-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.jlan.util;
/**
* Memory Size Class
*
* <p>Convenience class to convert memory size value specified as 'nK' for kilobytes, 'nM' for megabytes and 'nG' for
* gigabytes, to an absolute value.
*
* @author gkspencer
*/
public class MemorySize {
// Convertor constants
public static final long KILOBYTE = 1024L;
public static final long MEGABYTE = 1024L * KILOBYTE;
public static final long GIGABYTE = 1024L * MEGABYTE;
public static final long TERABYTE = 1024L * GIGABYTE;
/**
* Convert a memory size to an integer byte value.
*
* @param memSize String
* @return int
* @exception NumberFormatException
*/
public static final int getByteValueInt(String memSize) {
return (int) (getByteValue(memSize) & 0xFFFFFFFFL);
}
/**
* Convert a memory size to a byte value
*
* @param memSize String
* @return long
* @exception NumberFormatException
*/
public static final long getByteValue(String memSize) {
// Check if the string is valid
if ( memSize == null || memSize.length() == 0)
return -1L;
// Check for a kilobyte value
String sizeStr = memSize.toUpperCase();
long mult = 1;
long val = 0;
if ( sizeStr.endsWith("K")) {
// Use the kilobyte multiplier
mult = KILOBYTE;
val = getValue(sizeStr);
}
else if ( sizeStr.endsWith("M")) {
// Use the megabyte nultiplier
mult = MEGABYTE;
val = getValue(sizeStr);
}
else if ( sizeStr.endsWith("G")) {
// Use the gigabyte multiplier
mult = GIGABYTE;
val = getValue(sizeStr);
}
else if ( sizeStr.endsWith("T")) {
// Use the terabyte multiplier
mult = TERABYTE;
val = getValue(sizeStr);
}
else {
// Convert a numeric byte value
val = Long.valueOf(sizeStr).longValue();
}
// Apply the multiplier
return val * mult;
}
/**
* Get the size value from a string and return the numeric value
*
* @param val String
* @return long
* @exception NumberFormatException
*/
private final static long getValue(String val) {
// Strip the trailing size indicator
String sizStr = val.substring(0, val.length() - 1);
return Long.valueOf(sizStr).longValue();
}
/**
* Return a byte value as a kilobyte string
*
* @param val long
* @return String
*/
public final static String asKilobyteString(long val) {
// Calculate the kilobyte value
long mbVal = val / KILOBYTE;
return "" + mbVal + "Kb";
}
/**
* Return a byte value as a megabyte string
*
* @param val long
* @return String
*/
public final static String asMegabyteString(long val) {
// Calculate the megabyte value
long mbVal = val / MEGABYTE;
return "" + mbVal + "Mb";
}
/**
* Return a byte value as a gigabyte string
*
* @param val long
* @return String
*/
public final static String asGigabyteString(long val) {
// Calculate the gigabyte value
long mbVal = val / GIGABYTE;
return "" + mbVal + "Gb";
}
/**
* Return a byte value as a terabyte string
*
* @param val long
* @return String
*/
public final static String asTerabyteString(long val) {
// Calculate the terabyte value
long mbVal = val / TERABYTE;
return "" + mbVal + "Tb";
}
/**
* Return a byte value as a scaled string
*
* @param val long
* @return String
*/
public final static String asScaledString(long val) {
// Determine the scaling to apply
String ret = null;
if ( val < (KILOBYTE * 2L))
ret = Long.toString(val);
else if ( val < (MEGABYTE * 2L))
ret = asKilobyteString(val);
else if ( val < (GIGABYTE * 2L))
ret = asMegabyteString(val);
else if ( val < (TERABYTE * 2L))
ret = asGigabyteString(val);
else
ret = asTerabyteString(val);
return ret;
}
/**
* Round up the size value to a 512 byte boundary
*
* @param lSize long
* @return long
*/
public static long roundupLongSize(long lSize) {
return ( lSize + 512L) & 0xFFFFFFFFFFFFFE00L;
}
/**
* Round up the size value to a 512 byte boundary
*
* @param iSize int
* @return int
*/
public static int roundupIntSize(int iSize) {
return ( iSize + 512) & 0xFFFFFE00;
}
}
| lgpl-3.0 |
ZyorTaelon/eveapi | src/test/java/com/beimin/eveapi/AbstractOnlineTest.java | 14473 | package com.beimin.eveapi;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.BeforeClass;
import com.beimin.eveapi.connectors.ApiConnector;
import com.beimin.eveapi.connectors.LoggingConnector;
import com.beimin.eveapi.handler.ApiError;
import com.beimin.eveapi.model.shared.NamedList;
import com.beimin.eveapi.parser.ApiAuthorization;
import com.beimin.eveapi.parser.shared.AbstractApiParser;
import com.beimin.eveapi.response.ApiResponse;
public abstract class AbstractOnlineTest {
private final ApiAuthorization account = new ApiAuthorization(4428355, "Efnyja8S6pawB4EzefgZBFLDWGGTv0U9RZTfC6bD3vZ1pIc45FdgOUiCL6bpEssm");
private final ApiAuthorization character = new ApiAuthorization(5669026, 1528592227L, "Ud0aGh79j4ugLNmBhct4o9cHjbzFOmoMkbemN0ZSolsDfX0JXpXob4OwUU9Dw4Hu");
private final ApiAuthorization corp = new ApiAuthorization(4428366, "5TDpVttAXfTtJhWvPYKZnVfwIZPj8kAIDGa3YzP3MlVRwa2pYI6KP2qXBZseSoKa");
private final long charID = 1528592227L;
private final String charName = "Glazeg";
private final long corpID = 98400559;
private final int typeID = 1230; // Veldspar
private final List<Class<?>> nullCheckClasses = Arrays.asList(new Class<?>[] { Date.class, Boolean.class, boolean.class, ApiError.class });
private final List<Class<?>> fieldChecks = Arrays.asList(new Class<?>[] { String.class, Date.class, Boolean.class, boolean.class, Long.class, long.class, Integer.class, int.class, Double.class, double.class, Float.class, float.class });
private final Set<String> allowNull = new HashSet<String>();
private final Set<String> allowEmpty = new HashSet<String>();
private final Map<String, Map<String, String>> xmlAlias = new HashMap<>();
private final Map<String, Map<String, String>> classAlias = new HashMap<>();
private final Set<String> ignoreXmlIdentifiers = new HashSet<>();
private final Map<String, Set<String>> ignoreClassFields = new HashMap<>();
private Map<String, Set<String>> fields;
protected final void allowNull(final String methodName) {
allowNull.add(methodName);
}
protected final void allowEmpty(final String methodName) {
allowEmpty.add(methodName);
}
protected final void ignoreXmlField(final String xmlField) {
ignoreXmlIdentifiers.add(xmlField.toLowerCase());
}
protected final void ignoreClassField(final Class<?> clazz, final String classField) {
Set<String> set = ignoreClassFields.get(clazz.getName());
if (set == null) {
set = new HashSet<>();
ignoreClassFields.put(clazz.getName(), set);
}
set.add(classField.toLowerCase());
}
protected final void setAlias(final Class<?> clazz, final String xmlIdentifier, final String fieldName) {
Map<String, String> xmlMap = xmlAlias.get(clazz.getName());
if (xmlMap == null) {
xmlMap = new HashMap<>();
xmlAlias.put(clazz.getName(), xmlMap);
}
xmlMap.put(xmlIdentifier.toLowerCase(), fieldName.toLowerCase());
Map<String, String> classMap = classAlias.get(clazz.getName());
if (classMap == null) {
classMap = new HashMap<>();
classAlias.put(clazz.getName(), classMap);
}
classMap.put(fieldName.toLowerCase(), xmlIdentifier.toLowerCase());
}
@BeforeClass
public static void setUp() {
if (TestControl.logResponse()) {
AbstractApiParser.setConnector(new LoggingConnector(new ApiConnector()));
} else {
AbstractApiParser.setConnector(new ApiConnector());
}
}
@Before
public void before() {
allowNull.clear();
allowEmpty.clear();
ignoreXmlIdentifiers.clear();
ignoreClassFields.clear();
xmlAlias.clear();
classAlias.clear();
allowNull("getCachedUntil");
allowNull("getCurrentTime");
allowNull("getVersion");
allowNull("getError");
}
protected void prepareParser(AbstractApiParser<?> parser) {
prepareParser(parser, false);
}
protected void prepareParser(AbstractApiParser<?> parser, boolean fullPath) {
fields = parser.enableStrictCheckMode(fullPath);
}
private void checkBean(final Object bean) throws Exception {
// Test methods
for (final Method method : bean.getClass().getMethods()) {
if ((method.getParameterCount() == 0) && (method.getName().startsWith("get") || method.getName().startsWith("is")) && !method.getName().equals("getClass")) {
testValue(method.getName(), method.invoke(bean), method.getReturnType());
}
}
// Check for new fields
final Class<?> clazz = bean.getClass();
Set<String> classFields = getFields(clazz); // Count fields (to ignore logical methods)
Set<String> xmlFields = fields.get(bean.getClass().getName());
if (xmlFields != null) {
// Looks for added xml fields
Map<String, String> xmlAliasMap = xmlAlias.get(clazz.getName());
for (String xml : xmlFields) {
if (ignoreXmlIdentifiers.contains(xml)) {
continue; // Ignore XML
}
String testName = xml;
if (xmlAliasMap != null) {
String className = xmlAliasMap.get(xml);
if (className != null) {
testName = className;
}
}
assertThat(clazz.getSimpleName() + "." + testName + " is not included in class: ", classFields.contains(testName), equalTo(true));
}
// Looks for removed xml fields
Set<String> ignoreClassFieldsSet = ignoreClassFields.get(clazz.getName());
Map<String, String> classAliasMap = classAlias.get(clazz.getName());
for (String classField : classFields) {
if (ignoreClassFieldsSet != null && ignoreClassFieldsSet.contains(classField)) {
continue; // Ignore XML
}
String testName = classField;
if (classAliasMap != null) {
String className = classAliasMap.get(classField);
if (className != null) {
testName = className;
}
}
assertThat(clazz.getSimpleName() + "." + testName + " is not include in the xml result: ", xmlFields.contains(testName), equalTo(true));
}
}
}
private Set<String> getFields(final Class<?> clazz) {
Set<String> classFields = new HashSet<>();
if (clazz.getName().equals(Object.class.getName())) {
return classFields;
}
for (final Field field : clazz.getDeclaredFields()) {
final Class<?> type = field.getType();
if (fieldChecks.contains(type) || NamedList.class.equals(type) || Enum.class.isAssignableFrom(type) || Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)) {
classFields.add(field.getName().toLowerCase());
}
}
final Class<?> superclass = clazz.getSuperclass();
if (superclass != null && !superclass.equals(ApiResponse.class)) {
classFields.addAll(getFields(superclass));
}
return classFields;
}
private void testValue(final String id, final Object value) throws Exception {
assertThat(id + " was null: ", value, notNullValue());
testValue(id, value, value.getClass());
}
private void testValue(final String id, final Object value, final Class<?> type) throws Exception {
if (type.equals(String.class)) { // String
// null
if (!allowNull.contains(id)) { // null
assertThat(id + " was null: ", value, notNullValue());
}
// empty
if (!allowNull.contains(id) && !allowEmpty.contains(id)) { // Empty
final String result = (String) value;
assertThat(id + " was empty: ", result.length(), greaterThan(0));
}
} else if (Double.class.isAssignableFrom(type) || double.class.isAssignableFrom(type)) { // Double
// null
if (!allowNull.contains(id)) { // null
assertThat(id + " was null: ", value, notNullValue());
}
// empty
if (!allowNull.contains(id) && !allowEmpty.contains(id)) { // Empty
final double result = (Double) value;
assertThat(id + " was empty: ", result, not(equalTo(0.0)));
}
} else if (Float.class.isAssignableFrom(type) || float.class.isAssignableFrom(type)) { // Float
// null
if (!allowNull.contains(id)) { // null
assertThat(id + " was null: ", value, notNullValue());
}
// empty
if (!allowNull.contains(id) && !allowEmpty.contains(id)) { // Empty
final float result = (Float) value;
assertThat(id + " was empty: ", result, not(equalTo(0.0f)));
}
} else if (Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type)) { // Long
// null
if (!allowNull.contains(id)) { // null
assertThat(id + " was null: ", value, notNullValue());
}
// empty
if (!allowNull.contains(id) && !allowEmpty.contains(id)) { // Empty
final long result = (Long) value;
assertThat(id + " was empty: ", result, not(equalTo(0L)));
}
} else if (Integer.class.isAssignableFrom(type) || int.class.isAssignableFrom(type)) { // Enum
// null
if (!allowNull.contains(id)) { // null
assertThat(id + " was null: ", value, notNullValue());
}
// empty
if (!allowNull.contains(id) && !allowEmpty.contains(id)) { // Empty
final int result = (Integer) value;
assertThat(id + " was empty: ", result, not(equalTo(0)));
}
} else if (nullCheckClasses.contains(type)) { // Values
// null
if (!allowNull.contains(id)) { // null
assertThat(id + " was null: ", value, notNullValue());
}
} else if (Enum.class.isAssignableFrom(type)) { // Enum
// null
if (!allowNull.contains(id)) { // null
assertThat(id + " was null: ", value, notNullValue());
}
} else if (Collection.class.isAssignableFrom(type)) { // Collection
// null
if (!allowNull.contains(id)) {
assertThat(id + " was null: ", value, notNullValue());
}
// empty
final Collection<?> result = (Collection<?>) value;
if (!allowNull.contains(id) && !allowEmpty.contains(id) && TestControl.failOnEmptyCollection()) {
assertThat(id + " was empty: ", result.size(), greaterThan(0));
}
if (result != null && !result.isEmpty()) {
testValue(id + "->Collection", result.iterator().next());
}
} else if (Map.class.isAssignableFrom(type)) { // Map
// null
if (!allowNull.contains(id)) {
assertThat(id + " was null: ", value, notNullValue());
}
// empty
final Map<?, ?> result = (Map<?, ?>) value;
if (!allowNull.contains(id) && !allowEmpty.contains(id) && TestControl.failOnEmptyCollection()) {
assertThat(id + " was empty: ", result.size(), greaterThan(0));
}
if (result != null && !result.isEmpty()) {
testValue(id + "->MapKey", result.keySet().iterator().next()); // Test first key
testValue(id + "->MapValue", result.values().iterator().next()); // Test first value
}
} else { // Other Objects
checkBean(value);
}
}
protected long getCorpID() {
return corpID;
}
protected long getCharacterID() {
return charID;
}
protected String getCharacterName() {
return charName;
}
protected int getTypeID() {
return typeID;
}
protected void test(final Collection<?> collection) throws Exception {
if (!TestControl.failOnEmptyCollection()) {
assumeTrue("Empty collections allowed: ", false); // Ignore empty collection
}
assertThat("Collection was null: ", collection, notNullValue());
assertThat("Collection was empty: ", collection.size(), greaterThan(0));
}
protected void testResponse(final ApiResponse response) throws Exception {
testResponse(response, 2);
}
protected void testResponse(final ApiResponse response, final int version) throws Exception {
assertThat("ApiResponse was null: ", response, notNullValue());
assertThat("ApiResponse.cachedUntil was null: ", response.getCachedUntil(), notNullValue());
assertThat("ApiResponse.currentTime was null: ", response.getCurrentTime(), notNullValue());
assertThat("ApiResponse.version was wrong: ", response.getVersion(), equalTo(version));
assertThat("ApiResponse.error was not null: ", response.getError(), nullValue());
checkBean(response);
}
protected void testFail(final String s) {
fail(s);
}
protected ApiAuthorization getAccount() {
return account;
}
protected ApiAuthorization getCharacter() {
return character;
}
protected ApiAuthorization getCorp() {
return corp;
}
protected ApiAuthorization getEve() {
return character;
}
}
| lgpl-3.0 |
ndevisscher/Programmeerproject | ReceptenHulp/app/src/main/java/mprog/nl/receptenhulp/AddRecipe.java | 5725 | package mprog.nl.receptenhulp;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
/**
* Created by Niek de Visscher (10667474)
*/
public class AddRecipe extends AppCompatActivity {
//Declaring the various variables
DatabaseHelper myDB;
private ArrayList<String> ingredients;
private ArrayAdapter<String> adapter;
TextView idView;
EditText recipeLine;
EditText ingLine;
Button add;
Button search;
String descript = "";
String ings = "";
String preperation = "";
String item;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_recipe);
//Initializing the buttons and inputfields
idView = (TextView) findViewById(R.id.RecipeName);
recipeLine = (EditText) findViewById(R.id.addRecipe);
ingLine = (EditText) findViewById(R.id.searchRecipe);
add = (Button) findViewById(R.id.add);
search = (Button) findViewById(R.id.adding);
//Setting up the ingredient listview to use for adding ingredients
ListView ings = (ListView)findViewById(R.id.ingredients);
String[] items = {};
ingredients = new ArrayList<>(Arrays.asList(items));
adapter = new ArrayAdapter<String>(this,R.layout.list_item,R.id.ing,ingredients);
ings.setAdapter(adapter);
ings.setOnItemClickListener(new itemClick());
//Initializing the database
myDB = new DatabaseHelper(this);
//This allows us to use the back button on the toolbar
Toolbar object = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(object);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
//Using the back button from the toolbar to go to the previous screen
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
//Adding the Recipe to the database
public void addRecipe(View view) {
//Getting the name of the Recipe
String recipeName = recipeLine.getText().toString();
//Sorting the ingredients
Collections.sort(ingredients);
for (String ing : ingredients) {
ings = ings + "," + ing;
}
//Adding the Recipe to the database with the given info
myDB.addRecipe(recipeName, descript,ings);
show("Het volgende recept is toegevoegd: \n", recipeName);
//Clearing the datafields
recipeLine.setText("");
ingredients.clear();
ings = "";
adapter.notifyDataSetChanged();
}
//Adding ingredients to the list to add to the Recipe
public void addings (View view){
String ingName = ingLine.getText().toString().toLowerCase();
ingredients.add(ingName);
adapter.notifyDataSetChanged();
ingLine.setText("");
}
//A popup so you can add the description for the Recipe
private void descriptInput() {
AlertDialog.Builder descriptBuilder = new AlertDialog.Builder(this);
descriptBuilder.setTitle("bereidingswijze");
descriptBuilder.setMessage("Voer hier de bereidingswijze van het recept in.");
final EditText descInput = new EditText(this);
descInput.setText(preperation);
descriptBuilder.setView(descInput);
descriptBuilder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
descript = descInput.getText().toString();
preperation = descript;
}
});
//Pop-up for the description input
AlertDialog descript = descriptBuilder.create();
descript.show();
}
//Actually dispalying the popup for the description when te button is pressed
public void showDescriptInput (View view){
descriptInput();
}
//Getting the index of an ingredient
public int getIndexByname(String name) {
for (String ing : ingredients) {
if (ing.equals(name))
return ingredients.indexOf(ing);
}
return -1;
}
//Deleting ingredients from the recipe and listview by index when you click them
class itemClick implements AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ViewGroup vg = (ViewGroup) view;
TextView name = (TextView) vg.findViewById(R.id.ing);
item = name.getText().toString();
ingredients.remove(getIndexByname(item));
adapter.notifyDataSetChanged();
}
}
//Used for showing error messages
public void show(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
| lgpl-3.0 |
SonarSource/sonarqube | sonar-plugin-api/src/main/java/org/sonar/api/resources/Qualifiers.java | 2659 | /*
* 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.api.resources;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
/**
* The qualifier determines the exact type of a resource.
* Plugins can define their own qualifiers.
*
* @since 2.6
*/
public final class Qualifiers {
/**
* Root portfolios. Scope of portfolios is Scopes.PROJECT
*/
public static final String VIEW = "VW";
/**
* Sub-portfolios, defined in root portfolios. Scope of sub-portfolios is Scopes.PROJECT
*/
public static final String SUBVIEW = "SVW";
/**
* Application portfolios. Scope of application is Scopes.PROJECT
*/
public static final String APP = "APP";
/**
* Library, for example a JAR dependency of Java projects.
* Scope of libraries is Scopes.PROJECT
* @deprecated since 5.2 No more design features
*/
@Deprecated
public static final String LIBRARY = "LIB";
/**
* Project
* Scope is Scopes.PROJECT
*/
public static final String PROJECT = "TRK";
/**
* Module of a multi-modules project. It's sometimes called "sub-project".
* Scope of modules is Scopes.PROJECT
*
* @deprecated since 7.7 as modules doesn't exist anymore
*/
@Deprecated
public static final String MODULE = "BRC";
public static final String DIRECTORY = "DIR";
public static final String FILE = "FIL";
// ugly, should be replaced by "natures"
public static final String UNIT_TEST_FILE = "UTS";
/**
* List of qualifiers, ordered from bottom to up regarding position
* in tree of components
*
* @since 7.0
*/
public static final List<String> ORDERED_BOTTOM_UP = unmodifiableList(asList(
FILE, UNIT_TEST_FILE, DIRECTORY, MODULE, PROJECT, APP, SUBVIEW, VIEW));
private Qualifiers() {
// only static methods
}
}
| lgpl-3.0 |
PGWelch/com.opendoorlogistics | com.opendoorlogistics.core/src/com/opendoorlogistics/core/geometry/operations/GeomUnion.java | 5353 | /*******************************************************************************
* Copyright (c) 2014 Open Door Logistics (www.opendoorlogistics.com)
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License 3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
******************************************************************************/
package com.opendoorlogistics.core.geometry.operations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import org.geotools.geometry.jts.JTS;
import com.opendoorlogistics.api.geometry.ODLGeom;
import com.opendoorlogistics.core.cache.ApplicationCache;
import com.opendoorlogistics.core.cache.RecentlyUsedCache;
import com.opendoorlogistics.core.geometry.ODLGeomImpl;
import com.opendoorlogistics.core.geometry.ODLLoadedGeometry;
import com.opendoorlogistics.core.geometry.Spatial;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryCollection;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.PrecisionModel;
import com.vividsolutions.jts.precision.GeometryPrecisionReducer;
/**
* Perform union on multiple geomtries, caching the result. Union is performed in the input grid system.
*
* @author Phil
*
*/
public class GeomUnion {
private Geometry combineIntoOneGeometry(Collection<com.vividsolutions.jts.geom.Geometry> geometryCollection) {
if (geometryCollection.size() == 1) {
return geometryCollection.iterator().next();
}
GeometryFactory factory = new GeometryFactory();
// note the following geometry collection may be invalid (say with overlapping polygons)
GeometryCollection gc = (GeometryCollection) factory.buildGeometry(geometryCollection);
return gc.union();
}
private Object createCacheKey(Iterable<ODLGeom> inputGeoms, String ESPGCode) {
class CacheKey {
HashSet<ODLGeom> set = new HashSet<>();
String espg;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((espg == null) ? 0 : espg.hashCode());
result = prime * result + ((set == null) ? 0 : set.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CacheKey other = (CacheKey) obj;
if (espg == null) {
if (other.espg != null)
return false;
} else if (!espg.equals(other.espg))
return false;
if (set == null) {
if (other.set != null)
return false;
} else if (!set.equals(other.set))
return false;
return true;
}
}
CacheKey key = new CacheKey();
key.espg = ESPGCode;
// put all geoms in a hashset
for (ODLGeom geom : inputGeoms) {
key.set.add(geom);
}
return key;
}
private static final String INVALID_UNION = "invalid-union";
public ODLGeom union(Iterable<ODLGeom> inputGeoms, String ESPGCode) {
Object key = createCacheKey(inputGeoms, ESPGCode);
RecentlyUsedCache cache = ApplicationCache.singleton().get(ApplicationCache.GEOMETRY_MERGER_CACHE);
Object cached = cache.get(key);
if (cached == INVALID_UNION) {
return null;
}
ODLGeom ret = (ODLGeom) cached;
if (ret == null) {
// estimate the key size, assuming the input geometries are stored elsewhere
int estimatedKeySize = 8 + com.opendoorlogistics.core.utils.iterators.IteratorUtils.size(inputGeoms) * 8 + 20;
try {
ret = calculateUnion(inputGeoms, ESPGCode);
} catch (Exception e) {
// record the union as invalid in-case we do it again
cache.put(key, INVALID_UNION, estimatedKeySize);
throw new RuntimeException(e);
}
if (ret != null) {
// estimate size of geometry in bytes
long size = ((ODLGeomImpl) ret).getEstimatedSizeInBytes();
size += estimatedKeySize;
cache.put(key, ret, size);
}
}
return ret;
}
private ODLGeom calculateUnion(Iterable<ODLGeom> inputGeoms, String ESPGCode) {
try {
Spatial.initSpatial();
GridTransforms transforms = new GridTransforms(ESPGCode);
PrecisionModel pm = new PrecisionModel(PrecisionModel.FLOATING_SINGLE);
GeometryPrecisionReducer reducer = new GeometryPrecisionReducer(pm);
// process shapes into grid with reduced precision
ArrayList<Geometry> gridGeoms = new ArrayList<>();
for (ODLGeom geom : inputGeoms) {
if (geom != null) {
ODLGeomImpl gimpl = (ODLGeomImpl) geom;
if (gimpl.getJTSGeometry() != null) {
com.vividsolutions.jts.geom.Geometry g = gimpl.getJTSGeometry();
// convert to grid
g = JTS.transform(g, transforms.getWGS84ToGrid().getMathTransform());
// reduce precision as it stops holes appearing with our UK postcode data
g = reducer.reduce(g);
gridGeoms.add(g);
}
}
}
if (gridGeoms.size() == 0) {
return null;
}
// combine
Geometry combinedGrid = combineIntoOneGeometry(gridGeoms);
// transform back
Geometry combinedWGS84 = JTS.transform(combinedGrid, transforms.getGridToWGS84().getMathTransform());
return new ODLLoadedGeometry(combinedWGS84);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| lgpl-3.0 |
felipebz/sonar-plsql | plsql-custom-rules/src/test/java/com/company/plsql/PlSqlCustomRulesDefinitionTest.java | 696 | package com.company.plsql;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.sonar.api.Plugin;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.utils.Version;
import com.company.plsql.PlSqlCustomRulesPlugin;
public class PlSqlCustomRulesDefinitionTest {
@Test
public void test() {
Plugin.Context context = new Plugin.Context(SonarRuntimeImpl.forSonarQube(Version.create(6, 0), SonarQubeSide.SERVER));
PlSqlCustomRulesPlugin plugin = new PlSqlCustomRulesPlugin();
plugin.define(context);
assertThat(context.getExtensions().size()).isEqualTo(1);
}
}
| lgpl-3.0 |
git-moss/DrivenByMoss | src/main/java/de/mossgrabers/framework/command/continuous/LoopPositionCommand.java | 1404 | // Written by Jürgen Moßgraber - mossgrabers.de
// (c) 2017-2022
// Licensed under LGPLv3 - http://www.gnu.org/licenses/lgpl-3.0.txt
package de.mossgrabers.framework.command.continuous;
import de.mossgrabers.framework.command.core.AbstractContinuousCommand;
import de.mossgrabers.framework.configuration.Configuration;
import de.mossgrabers.framework.controller.IControlSurface;
import de.mossgrabers.framework.daw.IModel;
import de.mossgrabers.framework.daw.ITransport;
/**
* Command to change the position of the arranger loop start.
*
* @param <S> The type of the control surface
* @param <C> The type of the configuration
*
* @author Jürgen Moßgraber
*/
public class LoopPositionCommand<S extends IControlSurface<C>, C extends Configuration> extends AbstractContinuousCommand<S, C>
{
protected final ITransport transport;
/**
* Constructor.
*
* @param model The model
* @param surface The surface
*/
public LoopPositionCommand (final IModel model, final S surface)
{
super (model, surface);
this.transport = this.model.getTransport ();
}
/** {@inheritDoc} */
@Override
public void execute (final int value)
{
this.transport.changeLoopStart (this.model.getValueChanger ().isIncrease (value), this.surface.isKnobSensitivitySlow ());
}
}
| lgpl-3.0 |
luisgoncalves/xades4j | src/main/java/xades4j/xml/bind/xades/XmlReferenceInfoType.java | 4587 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 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: 2010.04.09 at 09:56:29 PM BST
//
package xades4j.xml.bind.xades;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlID;
import jakarta.xml.bind.annotation.XmlSchemaType;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.CollapsedStringAdapter;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import xades4j.xml.bind.Base64XmlAdapter;
import xades4j.xml.bind.xmldsig.XmlDigestMethodType;
/**
* <p>Java class for ReferenceInfoType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ReferenceInfoType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://www.w3.org/2000/09/xmldsig#}DigestMethod"/>
* <element ref="{http://www.w3.org/2000/09/xmldsig#}DigestValue"/>
* </sequence>
* <attribute name="Id" type="{http://www.w3.org/2001/XMLSchema}ID" />
* <attribute name="URI" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ReferenceInfoType", propOrder = {
"digestMethod",
"digestValue"
})
public class XmlReferenceInfoType {
@XmlElement(name = "DigestMethod", namespace = "http://www.w3.org/2000/09/xmldsig#", required = true)
protected XmlDigestMethodType digestMethod;
@XmlElement(name = "DigestValue", namespace = "http://www.w3.org/2000/09/xmldsig#", required = true, type = String.class)
@XmlJavaTypeAdapter(Base64XmlAdapter .class)
protected byte[] digestValue;
@XmlAttribute(name = "Id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
@XmlAttribute(name = "URI")
@XmlSchemaType(name = "anyURI")
protected String uri;
/**
* Gets the value of the digestMethod property.
*
* @return
* possible object is
* {@link XmlDigestMethodType }
*
*/
public XmlDigestMethodType getDigestMethod() {
return digestMethod;
}
/**
* Sets the value of the digestMethod property.
*
* @param value
* allowed object is
* {@link XmlDigestMethodType }
*
*/
public void setDigestMethod(XmlDigestMethodType value) {
this.digestMethod = value;
}
/**
* Gets the value of the digestValue property.
*
* @return
* possible object is
* {@link String }
*
*/
public byte[] getDigestValue() {
return digestValue;
}
/**
* Sets the value of the digestValue property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDigestValue(byte[] value) {
this.digestValue = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the uri property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getURI() {
return uri;
}
/**
* Sets the value of the uri property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setURI(String value) {
this.uri = value;
}
}
| lgpl-3.0 |
openbase/bco.ontology | lib/src/main/java/org/openbase/bco/ontology/lib/manager/abox/configuration/OntInstanceMapping.java | 3959 | package org.openbase.bco.ontology.lib.manager.abox.configuration;
/*-
* #%L
* BCO Ontology Library
* %%
* Copyright (C) 2016 - 2021 openbase.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import org.openbase.bco.ontology.lib.utility.sparql.RdfTriple;
import org.openbase.type.domotic.service.ServiceTemplateType.ServiceTemplate.ServiceType;
import org.openbase.type.domotic.unit.UnitConfigType.UnitConfig;
import java.util.List;
/**
* @author agatting on 09.01.17.
*/
public interface OntInstanceMapping {
/**
* Method returns instance information of units, services and states.
*
* @param unitConfigs contains the the units. Services and states are taken from the rst environment.
* If {@code null} services and states triple are returned only.
* @return a list with rdf triples to insert the units, services and states.
*/
List<RdfTriple> getInsertConfigInstances(final List<UnitConfig> unitConfigs);
/**
* Method returns instance information of ALL services and states.
*
* @return a list with rdf triples to insert the services and states.
*/
List<RdfTriple> getInsertStateAndServiceAndValueInstances();
/**
* Method returns instance information of units based on the input unitConfigs.
*
* @param unitConfigs contains the units.
* @return a list with rdf triples to insert the units.
*/
List<RdfTriple> getInsertUnitInstances(final List<UnitConfig> unitConfigs);
/**
* Method returns instance information of all services, which are taken from the rst environment.
*
* @return a list with rdf triples to insert the services.
*/
List<RdfTriple> getInsertProviderServiceInstances();
/**
* Method returns instance information of states, which are taken from the rst environment.
*
* @return a list with rdf triples to insert the states.
*/
List<RdfTriple> getInsertStateInstances();
/**
* Method returns instance information of state values, which are taken from the rst environment.
*
* @return a list with rdf triples to insert the state values.
*/
List<RdfTriple> getInsertStateValueInstances();
/**
* Method returns instance information to delete units, which are represented in the ontology.
*
* @param unitConfigs contains the units, which should be deleted in the ontology.
* @return a list with rdf triples to delete the units.
*/
List<RdfTriple> getDeleteUnitInstances(final List<UnitConfig> unitConfigs);
/**
* Method returns instance information to delete services, which are represented in the ontology.
*
* @param serviceTypes contains the services, which should be deleted in the ontology.
* @return a list with rdf triples to delete the services.
*/
List<RdfTriple> getDeleteProviderServiceInstances(final List<ServiceType> serviceTypes);
/**
* Method returns instance information to delete states, which are represented in the ontology.
*
* @param serviceTypes contains the states, which should be deleted in the ontology.
* @return a list with rdf triples to delete the states.
*/
List<RdfTriple> getDeleteStateInstances(final List<ServiceType> serviceTypes);
}
| lgpl-3.0 |
mar9000/plantuml | src/net/sourceforge/plantuml/ugraphic/USegmentType.java | 1833 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2014, Arnaud Roques
*
* Project Info: http://plantuml.sourceforge.net
*
* This file is part of PlantUML.
*
* PlantUML 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.
*
* PlantUML distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.ugraphic;
import java.awt.geom.PathIterator;
import java.util.EnumSet;
import net.sourceforge.plantuml.ugraphic.arc.ExtendedPathIterator;
public enum USegmentType {
SEG_MOVETO(PathIterator.SEG_MOVETO), SEG_LINETO(PathIterator.SEG_LINETO), SEG_QUADTO(PathIterator.SEG_QUADTO), SEG_CUBICTO(
PathIterator.SEG_CUBICTO), SEG_CLOSE(PathIterator.SEG_CLOSE), SEG_ARCTO(ExtendedPathIterator.SEG_ARCTO);
private final int code;
private USegmentType(int code) {
this.code = code;
}
public static USegmentType getByCode(int code) {
for (USegmentType p : EnumSet.allOf(USegmentType.class)) {
if (p.code == code) {
return p;
}
}
throw new IllegalArgumentException();
}
}
| lgpl-3.0 |
datacleaner/metamodel_extras | dbase/src/main/java/org/xBaseJ/Message.java | 5891 | /**
* eobjects.org MetaModel
* Copyright (C) 2010 eobjects.org
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.xBaseJ;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.Vector;
/**
* This class is courtesy of the xBaseJ project: http://xbasej.sourceforge.net/
*
* Copyright 1997-2007 - American Coders, LTD - Raleigh NC USA
*
* <pre>
* American Coders, Ltd
* P. O. Box 97462
* Raleigh, NC 27615 USA
* 1-919-846-2014
* http://www.americancoders.com
* </pre>
*
* @author Joe McVerry, American Coders Ltd.
*/
public class Message {
private Vector<String> idVector;
private Vector<String> dataVector;
/**
* creates a message class used by the client/server objects
*/
public Message() {
idVector = new Vector<String>();
dataVector = new Vector<String>();
}
/**
* creates a message class used by the client/server objects
*
* @param InStream
* data input
* @throws IOException
* communication line error
* @throws xBaseJException
* error conversing with server
*/
public Message(DataInputStream InStream) throws IOException,
xBaseJException {
int dataLen, j, i;
int waitLen;
String inString;
dataLen = 0;
do {
waitLen = InStream.available();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
} finally {
}
} while (waitLen < 4);
try {
dataLen = InStream.readInt();
} catch (EOFException e) {
System.out.println("caught a " + e.getMessage());
}
finally {
}
byte DataIn[] = new byte[dataLen];
waitLen = dataLen;
InStream.readFully(DataIn, 0, dataLen);
idVector = new Vector<String>();
dataVector = new Vector<String>();
for (i = 0; i < dataLen;) {
for (j = i; j < dataLen && DataIn[j] != 0; j++)
;
// 1.0inString = new String(DataIn, 0, i, j-i);
inString = new String(DataIn, i, j - i);
idVector.addElement(inString);
i = j + 1;
for (j = i; j < dataLen && DataIn[j] != 0; j++)
;
// 1.0 inString = new String(DataIn, 0, i, j-i);
inString = new String(DataIn, i, j - i);
dataVector.addElement(inString);
i = j + 1;
}
inString = (String) idVector.elementAt(0);
if (inString.compareTo("Exception") == 0) {
inString = (String) dataVector.elementAt(0);
throw new xBaseJException(inString);
}
if (inString.compareTo("xBaseJException") == 0) {
inString = (String) dataVector.elementAt(0);
throw new xBaseJException(inString);
}
}
/**
* writes to the queue
*
* @param OutStream
* data output
* @throws IOException
* communication line error
*/
public void write(DataOutputStream OutStream) throws IOException {
String tString;
int i, outLength = 0;
byte dataByteOut[];
for (i = 0; i < idVector.size(); i++) {
tString = (String) idVector.elementAt(i);
outLength += tString.length();
tString = (String) dataVector.elementAt(i);
outLength += tString.length();
outLength += 2;
}
OutStream.writeInt(outLength);
for (i = 0; i < idVector.size(); i++) {
tString = (String) idVector.elementAt(i);
dataByteOut = new byte[tString.length()];
// 1.0 tString.getBytes(0, tString.length(), dataByteOut, 0);
dataByteOut = tString.getBytes();
// 1.0tString.getBytes(0, tString.length(), dataByteOut, 0);
dataByteOut = tString.getBytes();
OutStream.write(dataByteOut, 0, tString.length());
OutStream.writeByte(0);
tString = (String) dataVector.elementAt(i);
dataByteOut = new byte[tString.length()];
// 1.0 tString.getBytes(0, tString.length(), dataByteOut, 0);
dataByteOut = tString.getBytes();
OutStream.write(dataByteOut, 0, tString.length());
OutStream.writeByte(0);
}
OutStream.flush();
}
/**
* set header information
*/
public void setHeader(String ID, String DBFName) {
if (idVector.size() == 0) {
idVector.addElement(ID);
dataVector.addElement(DBFName);
} else {
idVector.setElementAt(ID, 0);
dataVector.setElementAt(DBFName, 0);
}
return;
}
public void setField(String ID, String FieldData) {
int i;
String idt;
for (i = 1; i < idVector.size(); i++) {
idt = (String) idVector.elementAt(i);
if (idt.compareTo(ID) == 0) {
dataVector.setElementAt(FieldData, i);
return;
}
}
idVector.addElement(ID);
dataVector.addElement(FieldData);
return;
}
public void setException(String ID, String FieldData) {
idVector.removeAllElements();
dataVector.removeAllElements();
idVector.addElement(ID);
dataVector.addElement(FieldData);
return;
}
public String getID(int i) {
return (String) idVector.elementAt(i);
}
public String getField(String ID) throws xBaseJException {
int i;
String idt;
for (i = 0; i < idVector.size(); i++) {
idt = (String) idVector.elementAt(i);
if (idt.compareTo(ID) == 0) {
return (String) dataVector.elementAt(i);
}
}
throw new xBaseJException("Field " + ID + " not found");
}
public String getField(int pos) throws xBaseJException {
return (String) dataVector.elementAt(pos);
}
public int getCount() {
return dataVector.size();
}
}
| lgpl-3.0 |
Randy-Blancett/DarkNet | parent/DarkObjects/src/main/java/net/darkowl/darkNet/darkObjects/util/DarkNetObjectUtil.java | 927 | /**
*
*/
package net.darkowl.darkNet.darkObjects.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import net.darkowl.darkNet.darkObjects.interfaces.DarkNetDAO;
/**
* @author Randy Blancett
* @since Jan 3, 2016
*
*/
public class DarkNetObjectUtil {
@SuppressWarnings("unchecked")
public static DarkNetDAO form(Map<String, String> map)
throws ClassNotFoundException, NoSuchMethodException,
SecurityException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
String type = map.get(DarkNetDAO.COL_TYPE);
DarkNetDAO objectInstance = null;
Class<DarkNetDAO> object;
object = (Class<DarkNetDAO>) Class.forName(type);
final Constructor<DarkNetDAO> constructor = object
.getConstructor(Map.class);
objectInstance = constructor.newInstance(map);
return objectInstance;
}
}
| lgpl-3.0 |
claudejin/evosuite | master/src/test/java/org/evosuite/ga/problems/singleobjective/TestThreeHump.java | 4204 | /**
* Copyright (C) 2010-2016 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite 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.0 of the License, or
* (at your option) any later version.
*
* EvoSuite 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.ga.problems.singleobjective;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.evosuite.Properties;
import org.evosuite.ga.Chromosome;
import org.evosuite.ga.ChromosomeFactory;
import org.evosuite.ga.FitnessFunction;
import org.evosuite.ga.NSGAChromosome;
import org.evosuite.ga.metaheuristics.GeneticAlgorithm;
import org.evosuite.ga.metaheuristics.NSGAII;
import org.evosuite.ga.metaheuristics.RandomFactory;
import org.evosuite.ga.operators.crossover.SBXCrossover;
import org.evosuite.ga.operators.selection.BinaryTournamentSelectionCrowdedComparison;
import org.evosuite.ga.problems.Problem;
import org.evosuite.ga.variables.DoubleVariable;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class TestThreeHump
{
@BeforeClass
public static void setUp() {
Properties.POPULATION = 100;
Properties.SEARCH_BUDGET = 250;
Properties.CROSSOVER_RATE = 0.9;
Properties.RANDOM_SEED = 1l;
}
@Test
public void testThreeHumpFitness()
{
Problem p = new ThreeHump();
FitnessFunction f1 = (FitnessFunction) p.getFitnessFunctions().get(0);
double[] values = {-2.0, 3.0};
NSGAChromosome c = new NSGAChromosome(-5.0, 5.0, values);
Assert.assertEquals(((DoubleVariable) c.getVariables().get(0)).getValue(), -2.0, 0.0);
Assert.assertEquals(((DoubleVariable) c.getVariables().get(1)).getValue(), 3.0, 0.0);
Assert.assertEquals(f1.getFitness(c), 4.87, 0.01);
}
/**
* Testing NSGA-II with ThreeHump Problem
*
* @throws IOException
* @throws NumberFormatException
*/
@Test
public void testThreeHump() throws NumberFormatException, IOException
{
Properties.MUTATION_RATE = 1d / 2d;
ChromosomeFactory<?> factory = new RandomFactory(false, 2, -5.0, 5.0);
//GeneticAlgorithm<?> ga = new NSGAII(factory);
GeneticAlgorithm<?> ga = new NSGAII(factory);
BinaryTournamentSelectionCrowdedComparison ts = new BinaryTournamentSelectionCrowdedComparison();
//BinaryTournament ts = new BinaryTournament();
ga.setSelectionFunction(ts);
ga.setCrossOverFunction(new SBXCrossover());
Problem p = new ThreeHump();
final FitnessFunction f1 = (FitnessFunction) p.getFitnessFunctions().get(0);
ga.addFitnessFunction(f1);
// execute
ga.generateSolution();
List<Chromosome> chromosomes = (List<Chromosome>) ga.getPopulation();
Collections.sort(chromosomes, new Comparator<Chromosome>() {
@Override
public int compare(Chromosome arg0, Chromosome arg1) {
return Double.compare(arg0.getFitness(f1), arg1.getFitness(f1));
}
});
for (Chromosome chromosome : chromosomes)
Assert.assertEquals(chromosome.getFitness(f1), 0.000, 0.001);
for (Chromosome chromosome : chromosomes) {
NSGAChromosome nsga_c = (NSGAChromosome)chromosome;
DoubleVariable x = (DoubleVariable) nsga_c.getVariables().get(0);
DoubleVariable y = (DoubleVariable) nsga_c.getVariables().get(1);
System.out.printf("%f,%f : %f\n", x.getValue(), y.getValue(), chromosome.getFitness(f1));
}
}
}
| lgpl-3.0 |
npklein/molgenis | molgenis-security/src/test/java/org/molgenis/security/login/MolgenisLoginControllerTest.java | 1925 | package org.molgenis.security.login;
import org.molgenis.security.login.MolgenisLoginControllerTest.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebAppConfiguration
@ContextConfiguration(classes = { Config.class })
public class MolgenisLoginControllerTest extends AbstractTestNGSpringContextTests
{
@Autowired
private MolgenisLoginController molgenisLoginController;
private MockMvc mockMvc;
@BeforeMethod
public void setUp()
{
mockMvc = MockMvcBuilders.standaloneSetup(molgenisLoginController).build();
}
@Test
public void getLoginPage() throws Exception
{
this.mockMvc.perform(get("/login")).andExpect(status().isOk()).andExpect(view().name("view-login"));
}
@Test
public void getLoginErrorPage() throws Exception
{
this.mockMvc.perform(get("/login").param("error", "")).andExpect(status().isOk())
.andExpect(view().name("view-login")).andExpect(model().attributeExists("errorMessage"));
}
@Configuration
public static class Config extends WebMvcConfigurerAdapter
{
@Bean
public MolgenisLoginController molgenisLoginController()
{
return new MolgenisLoginController();
}
}
}
| lgpl-3.0 |
arcuri82/pg4200 | lessons/src/main/java/org/pg4200/les01/linkedlist/MyDelegateListString.java | 1741 | package org.pg4200.les01.linkedlist;
import org.pg4200.les01.MyListString;
import java.util.LinkedList;
import java.util.List;
/**
* Created by arcuri82 on 15-Aug-17.
*/
public class MyDelegateListString implements MyListString {
/*
The Java API provides many implementations for containers, eg in
the "java.util.*" package.
It is unlikely that you will ever need to implement your own containers,
as we do here in this course.
The point is that, to properly choose which container to use, you need
to understand how they work internally.
Technically, to fulfil the contract of the MyListString interface,
I could use internally an actual list from the Java API, and "delegate" all the
methods on such list.
It is technically correct, although quite pointless: why not using the Java API directly?
In the exercises in this course (and the exam), you are NOT allowed to write this kind
of delegate code, unless otherwise specified.
Even worse, do NOT do it in a job interview...
Note: we will looking into "Generics" (eg, "<String>") next class.
*/
private List<String> delegate = new LinkedList<>();
@Override
public String get(int index) {
try {
return delegate.get(index);
} catch (Exception e){
/*
The Java API has different semantics regarding how to
handle invalid inputs, ie it throws an exception
*/
return null;
}
}
@Override
public void add(String value) {
delegate.add(value);
}
@Override
public int size() {
return delegate.size();
}
}
| lgpl-3.0 |
jsmithe/ari4java | classes/ch/loway/oss/ari4java/generated/ari_1_6_0/models/ChannelTalkingFinished_impl_ari_1_6_0.java | 1479 | package ch.loway.oss.ari4java.generated.ari_1_6_0.models;
// ----------------------------------------------------
// THIS CLASS WAS GENERATED AUTOMATICALLY
// PLEASE DO NOT EDIT
// Generated on: Sat Feb 04 15:23:09 CET 2017
// ----------------------------------------------------
import ch.loway.oss.ari4java.generated.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**********************************************************
* Talking is no longer detected on the channel.
*
* Defined in file: events.json
* Generated by: Model
*********************************************************/
public class ChannelTalkingFinished_impl_ari_1_6_0 extends Event_impl_ari_1_6_0 implements ChannelTalkingFinished, java.io.Serializable {
private static final long serialVersionUID = 1L;
/** The channel on which talking completed. */
private Channel channel;
public Channel getChannel() {
return channel;
}
@JsonDeserialize( as=Channel_impl_ari_1_6_0.class )
public void setChannel(Channel val ) {
channel = val;
}
/** The length of time, in milliseconds, that talking was detected on the channel */
private int duration;
public int getDuration() {
return duration;
}
@JsonDeserialize( as=int.class )
public void setDuration(int val ) {
duration = val;
}
/** No missing signatures from interface */
}
| lgpl-3.0 |
logsniffer/logsniffer | logsniffer-core/src/main/java/com/logsniffer/model/support/ByteLogInputStream.java | 1173 | /*******************************************************************************
* logsniffer, open source tool for viewing, monitoring and analysing log data.
* Copyright (c) 2015 Scaleborn UG, www.scaleborn.com
*
* logsniffer 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.
*
* logsniffer 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.logsniffer.model.support;
import java.io.InputStream;
import com.logsniffer.model.LogInputStream;
public abstract class ByteLogInputStream extends InputStream implements LogInputStream {
}
| lgpl-3.0 |
sefaakca/EvoSuite-Sefa | client/src/test/java/com/examples/with/different/packagename/concolic/MemoryCell.java | 1025 | /**
* Copyright (C) 2010-2017 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite 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.0 of the License, or
* (at your option) any later version.
*
* EvoSuite 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package com.examples.with.different.packagename.concolic;
public class MemoryCell {
private final int intVal;
public MemoryCell(int int0) {
intVal = int0;
}
public MemoryCell anotherCell;
public int getValue() {
return intVal;
}
} | lgpl-3.0 |
ari-zah/gaiasandbox | core/src/gaiasky/util/gdx/shader/provider/BaseIntShaderProvider.java | 1895 | /*
* This file is part of Gaia Sky, which is released under the Mozilla Public License 2.0.
* See the file LICENSE.md in the project root for full license details.
*/
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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 gaiasky.util.gdx.shader.provider;
import com.badlogic.gdx.utils.Array;
import gaiasky.util.gdx.IntRenderable;
import gaiasky.util.gdx.shader.IntShader;
public abstract class BaseIntShaderProvider implements IntShaderProvider {
protected Array<IntShader> shaders = new Array<>();
@Override
public IntShader getShader (IntRenderable renderable) {
IntShader suggestedShader = renderable.shader;
if (suggestedShader != null && suggestedShader.canRender(renderable)) return suggestedShader;
for (IntShader shader : shaders) {
if (shader.canRender(renderable)) return shader;
}
final IntShader shader = createShader(renderable);
shader.init();
shaders.add(shader);
return shader;
}
protected abstract IntShader createShader (final IntRenderable renderable);
@Override
public void dispose () {
for (IntShader shader : shaders) {
shader.dispose();
}
shaders.clear();
}
}
| lgpl-3.0 |
dihedron/dihedron-strutlets | dihedron-strutlets/src/main/java/org/dihedron/strutlets/annotations/Result.java | 3564 | /*
* Copyright (c) 2012-2015, Andrea Funto'. All rights reserved. See LICENSE for details.
*/
package org.dihedron.strutlets.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.dihedron.strutlets.renderers.impl.JspRenderer;
/**
* Annotation representing the view handler that will
* create the visual representation for the given result.
* Results can be represented as free text strings, and
* are mapped to the appropriate view handler by the action
* controller, based on what's in these annotations.
*
* @author Andrea Funto'
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Result {
/**
* The result string for which the mapping to the renderer is
* being described.
*
* @return
* the result string.
*/
String value() default "success";
/**
* The new mode of the portlet, after the action has been executed; this
* parameter only makes sense when the action is executed in an action or
* event phase, since portlets cannot change mode in render or resource
* phase. If "same" is specified here (the default), the portlet mode is
* not changed.
*
* @return
* the name of the renderer class.
*/
String mode() default "same";
/**
* The window state after the action has been executed; an action can only
* change its state while in the action or event phase, otherwise this
* parameter is not considered. If "same" is specified here, the portlet
* does not change state.
*
* The class of the view handler, which will format the output
* based on the annotated action's outcome and the parameters,
* as a class object; this propery can be used when the renderer
* is known at build time and eagerly bound; if it is not known
* at build time, e.g. because it is in a plug-in that is only
* loaded at runtime, use the <code>classname</code> property
* instead.
* based on the annotated action's outcome and the parameters,
* as a class name; this property can be used when the renderer
* is loaded lazily, and only bound at runtime, e.g. because it is
* in a plug-in and must be located by name; if it is known at build
* time, use the <code>classref</code> property instead.
*
* @return
* the renderer class.
*/
String state() default "same";
/**
* The type of renderer; this parameter can contain the name of a registered
* renderer, e.g. "jsp", which must have been registered. A set of core
* renderers are registered by default by the framework, while the user can
* specify some additional ones which must implement the {@code Renderer}
* interface and be located in a package, as per the portlet's initialisation.
*
* @return
* the alias of the renderer.
*/
String renderer() default JspRenderer.ID;
/**
* The data to be passed on to the renderer; in the case of a JSP renderer,
* this data would be the URL of the JSP page to show, whereas in the case
* of a JSON or XML renderer, this data would be the name of the variable or
* of the parameter to be rendered as JSON or XML.
*
* @return
* the data to be used by the renderer to provide a meaningful output; in
* the case of a JSP renderer, this would typically be the URL of the JSP
* to be included, whereas for JSON and XML it would be the name of the
* parameter containing the object to be JSON- or XML-encoded.
*/
String data() default "";
} | lgpl-3.0 |
anthonysomerset/js3tream | src/net/sourceforge/js3tream/StdoutOperation.java | 10120 | /*******************************************************
*
* @author spowell
* StdinOperation.java
* Dec 21, 2006
* $Id: StdoutOperation.java,v 1.3 2007/10/26 13:23:29 shaneapowell Exp $
Copyright (C) 2006 Shane Powell
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
******************************************************/
package net.sourceforge.js3tream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.security.MessageDigest;
import org.apache.axis.attachments.AttachmentPart;
import net.sourceforge.js3tream.StdinOperation.ExposedByteArrayOutputStream;
import net.sourceforge.js3tream.util.Access;
import net.sourceforge.js3tream.util.Common;
import net.sourceforge.js3tream.util.Log;
import com.amazonaws.s3.doc._2006_03_01.AmazonS3SoapBindingStub;
import com.amazonaws.s3.doc._2006_03_01.AmazonS3_ServiceLocator;
import com.amazonaws.s3.doc._2006_03_01.GetObjectResult;
import com.amazonaws.s3.doc._2006_03_01.ListBucketResult;
import com.amazonaws.s3.doc._2006_03_01.ListEntry;
/*******************************************************
* Read the S3 bucket data, and write it's data to the
* STDOUT stream.
******************************************************/
public class StdoutOperation extends Operation
{
private OutputStream os_ = null;
private File tempFile_ = null;
private boolean useFile_ = false;
private ExposedByteArrayOutputStream memoryBuffer_ = null;
private boolean neverDie_ = false;
private double kBytesProcessed_ = 0.0;
/******************************************************
* @param pretend IN - pretend to send to S3 or not.
* @param bucket IN - the bucket to write the data to.
* @param os IN - the output stream to write the data to.
******************************************************/
StdoutOperation(boolean pretend, boolean neverDie, boolean useFile, String bucket, OutputStream os) throws Exception
{
super(pretend, bucket);
this.os_ = os;
this.useFile_ = useFile;
this.neverDie_ = neverDie;
/* Setup the temp buffer */
if (!this.useFile_)
{
this.memoryBuffer_ = new ExposedByteArrayOutputStream(DEFAULT_BUCKET_OBJECT_BYTES);
}
else
{
this.tempFile_ = File.createTempFile("s3stream", "io");
this.tempFile_.deleteOnExit();
}
}
/*******************************************************
* Override
* @see net.sourceforge.js3tream.Operation#start()
*******************************************************/
@Override
public void start() throws Exception
{
Log.info("Sending S3 data to STDOUT\n");
Log.info("Bucket [" + getBucketName() + "]\n");
if (getPrefixName() != null)
{
Log.info("Prefix [" + getPrefixName() + "]\n");
}
ListOperation listOp = new ListOperation(getBucketName(), getPrefixName());
String marker = null;
/* Get the list of files from S3 */
ListBucketResult listResult = null;
/* This do while loop deals with the paging of s3 lists */
do
{
/* Get a page of results */
listResult = listOp.getBucketObjectList(marker, getBucketName(), getPrefixName(), MAX_KEYS_PER_LIST);
if (listResult.getContents() != null)
{
/* Process this list of keys */
for (ListEntry listEntry : listResult.getContents())
{
marker = listEntry.getKey();
restoreS3Object(listEntry.getKey());
}
}
}
while(listResult.isIsTruncated());
if (this.kBytesProcessed_ > 10000)
{
Log.info(String.format("%.2fM transfered\n", (this.kBytesProcessed_ / 1000.0)));
}
else
{
Log.info(String.format("%.2fK transfered\n", this.kBytesProcessed_));
}
}
/*******************************************************
* Returns the buffer output stream used to store
* the bytes before sending to S3. Each call to this
* method will result in a fresh buffer returned. That
* is, the byte array will be reset, or the temp file
* will be cleared.
*
* @return
*******************************************************/
private OutputStream createBufferOutputStream() throws Exception
{
if (!this.useFile_)
{
this.memoryBuffer_.reset();
return this.memoryBuffer_;
}
else
{
return new FileOutputStream(this.tempFile_, false);
}
}
/*******************************************************
* Get the buffer in the form of an input stream.
* Each call to this method results in the return of a
* new input stream object, so once called, hang onto your
* reference.
* @return
*******************************************************/
private InputStream createBufferInputStream() throws Exception
{
if (!this.useFile_)
{
return new ByteArrayInputStream(this.memoryBuffer_.getBytes(), 0, this.memoryBuffer_.getCount());
}
else
{
return new FileInputStream(this.tempFile_);
}
}
/********************************************************
* @param key
*******************************************************/
public void restoreS3Object(String key) throws Exception
{
Log.info("Fetching S3 object [" + key + "] \n");
if (isPretendMode())
{
Log.info("\n");
return;
}
Access access = new Access();
/* Get the metadata for the given file */
GetObjectResult result = null;
/* Try a few times to get the object */
/* Put the file, We'll try a few times */
int attemptCount = 0;
while (attemptCount < MAX_S3_READWRITE_ATTEMPTS)
{
attemptCount++;
try
{
long startTime = System.currentTimeMillis();
AmazonS3_ServiceLocator locator = new AmazonS3_ServiceLocator();
AmazonS3SoapBindingStub binding = new AmazonS3SoapBindingStub(new URL(locator.getAmazonS3Address()), locator);
result = binding.getObject(getBucketName(),
key,
false,
true,
false,
access.getAccessKey(),
access.getAccessCalendar(),
access.generateSignature("GetObject"),
null);
long endTime = System.currentTimeMillis();
/* Get the attachments. Note, the getAttachments() method will ONLY return the object[] on the first call. Subsiquent calls will return null */
Object[] attachments = binding.getAttachments();
if (attachments.length != 1)
{
throw new Exception("The S3 Object returned [" + attachments.length + "] when we expected exactly 1");
}
/* Setup the MD5 digest */
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
/* Get the attachment, and pipe it's data to the buffer */
OutputStream os = createBufferOutputStream();
AttachmentPart part = (AttachmentPart) attachments[0];
InputStream attachmentStream = part.getDataHandler().getInputStream();
long byteCount = 0;
int b = 0;
while ((b = attachmentStream.read()) != -1)
{
byteCount++;
messageDigest.update((byte)b);
os.write(b);
if (byteCount % 1000 == 0)
{
Log.info("\r" + byteCount + " bytes read...");
}
}
Log.info("\r" + byteCount + " bytes read...");
os.flush();
os.close();
this.kBytesProcessed_ += ((double)byteCount / 1000.0);
Log.info(String.format("%6.02f Kb/s\n", (((double)((double)byteCount * (double)Byte.SIZE)) / 1000D) / ((endTime - startTime) / 1000)));
Log.debug(byteCount + " bytes written to buffer\n");
/* Calculate the MD5 value */
String md5 = Common.toHex(messageDigest.digest());
/* compare md5 hashes */
if (md5.equals(result.getETag().replaceAll("\"", "")) == false)
{
throw new Exception("After getting the S3 object [" + key + "], we compared the md5 hash codes. They did not match\n" + "original: [" + md5 + "]\nS3: [" + result.getETag() + "]");
}
/* Now, stream the file to stdout */
byteCount = 0;
InputStream is = createBufferInputStream();
while ((b = is.read()) != -1)
{
byteCount++;
this.os_.write(b);
}
is.close();
is = null;
this.os_.flush();
Log.debug(byteCount + " bytes sent to STDOUT\n");
return;
}
catch(Exception e)
{
Log.warn("Attempt [" + attemptCount + " of " + MAX_S3_READWRITE_ATTEMPTS + "] failed on: [" + key + "]\n");
Log.debug("S3 Get Failure\n", e);
/* If we've exceeded our max try count, then fail the whole process */
if (attemptCount >= MAX_S3_READWRITE_ATTEMPTS)
{
String warningMessage = attemptCount + " attempts were made to get object [" + key + "] to S3.\nNone of which were successfull.";
if (this.neverDie_)
{
attemptCount = 0;
Log.warn(warningMessage + "\n we'll try again in " + NEVER_DIE_SLEEP_TIME + " minutes");
Thread.sleep(NEVER_DIE_SLEEP_TIME * 60 * 1000);
}
else
{
throw new Exception(warningMessage + "\nHere is the last error", e);
}
}
} /* end catch */
} /* end while attempt loop */
}
}
| lgpl-3.0 |
Albloutant/Galacticraft | common/micdoodle8/mods/galacticraft/mars/entities/GCMarsEntitySlimeling.java | 16713 | package micdoodle8.mods.galacticraft.mars.entities;
import micdoodle8.mods.galacticraft.api.entity.IEntityBreathable;
import micdoodle8.mods.galacticraft.core.GalacticraftCore;
import micdoodle8.mods.galacticraft.core.entities.player.GCCorePlayerMP;
import micdoodle8.mods.galacticraft.mars.GalacticraftMars;
import micdoodle8.mods.galacticraft.mars.inventory.GCMarsInventorySlimeling;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityAgeable;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.WatchableObject;
import net.minecraft.entity.ai.EntityAIAttackOnCollide;
import net.minecraft.entity.ai.EntityAIFollowOwner;
import net.minecraft.entity.ai.EntityAIHurtByTarget;
import net.minecraft.entity.ai.EntityAILeapAtTarget;
import net.minecraft.entity.ai.EntityAILookIdle;
import net.minecraft.entity.ai.EntityAIMate;
import net.minecraft.entity.ai.EntityAIOwnerHurtByTarget;
import net.minecraft.entity.ai.EntityAIOwnerHurtTarget;
import net.minecraft.entity.ai.EntityAISit;
import net.minecraft.entity.ai.EntityAISwimming;
import net.minecraft.entity.ai.EntityAITargetNonTamed;
import net.minecraft.entity.ai.EntityAIWander;
import net.minecraft.entity.ai.EntityAIWatchClosest;
import net.minecraft.entity.monster.EntityCreeper;
import net.minecraft.entity.monster.EntityGhast;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.passive.EntityHorse;
import net.minecraft.entity.passive.EntityTameable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.pathfinding.PathEntity;
import net.minecraft.util.ChatMessageComponent;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSource;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
/**
* GCMarsEntitySlimeling.java
*
* This file is part of the Galacticraft project
*
* @author micdoodle8
* @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html)
*
*/
public class GCMarsEntitySlimeling extends EntityTameable implements IEntityBreathable
{
public GCMarsInventorySlimeling slimelingInventory = new GCMarsInventorySlimeling(this);
public float colorRed;
public float colorGreen;
public float colorBlue;
public long ticksAlive;
public int age = 0;
public final int MAX_AGE = 100000;
public String slimelingName = "Unnamed";
public int favFoodID = 1;
public float attackDamage = 0.05F;
public int kills;
public GCMarsEntitySlimeling(World par1World)
{
super(par1World);
this.setSize(0.25F, 0.7F);
this.getNavigator().setAvoidsWater(true);
this.tasks.addTask(1, new EntityAISwimming(this));
this.tasks.addTask(2, this.aiSit);
this.tasks.addTask(3, new EntityAILeapAtTarget(this, 0.4F));
this.tasks.addTask(4, new EntityAIAttackOnCollide(this, 1.0D, true));
this.tasks.addTask(5, new EntityAIFollowOwner(this, 1.0D, 10.0F, 2.0F));
this.tasks.addTask(6, new EntityAIMate(this, 1.0D));
this.tasks.addTask(7, new EntityAIWander(this, 1.0D));
this.tasks.addTask(9, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F));
this.tasks.addTask(9, new EntityAILookIdle(this));
this.targetTasks.addTask(1, new EntityAIOwnerHurtByTarget(this));
this.targetTasks.addTask(2, new EntityAIOwnerHurtTarget(this));
this.targetTasks.addTask(3, new EntityAIHurtByTarget(this, true));
this.targetTasks.addTask(4, new EntityAITargetNonTamed(this, GCMarsEntitySludgeling.class, 200, false));
this.setTamed(false);
switch (this.rand.nextInt(3))
{
case 0:
this.colorRed = 1.0F;
break;
case 1:
this.colorBlue = 1.0F;
break;
case 2:
this.colorRed = 1.0F;
this.colorGreen = 1.0F;
break;
}
this.setRandomFavFood();
}
public float getSlimelingSize()
{
return this.getScale() * 2.0F;
}
@Override
public void setScaleForAge(boolean par1)
{
this.setScale(this.getSlimelingSize());
}
@Override
public boolean isChild()
{
return this.getAge() / (float) this.MAX_AGE < 0.4F;
}
private void setRandomFavFood()
{
switch (this.rand.nextInt(10))
{
case 0:
this.favFoodID = Item.ingotGold.itemID;
break;
case 1:
this.favFoodID = Item.flintAndSteel.itemID;
break;
case 2:
this.favFoodID = Item.bakedPotato.itemID;
break;
case 3:
this.favFoodID = Item.swordStone.itemID;
break;
case 4:
this.favFoodID = Item.gunpowder.itemID;
break;
case 5:
this.favFoodID = Item.doorWood.itemID;
break;
case 6:
this.favFoodID = Item.emerald.itemID;
break;
case 7:
this.favFoodID = Item.fishCooked.itemID;
break;
case 8:
this.favFoodID = Item.redstoneRepeater.itemID;
break;
case 9:
this.favFoodID = Item.boat.itemID;
break;
}
}
public GCMarsEntitySlimeling(World par1World, float red, float green, float blue)
{
this(par1World);
this.colorRed = red;
this.colorGreen = green;
this.colorBlue = blue;
}
@Override
protected void applyEntityAttributes()
{
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setAttribute(0.30000001192092896D);
this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setAttribute(this.getMaxHealthSlimeling());
}
@Override
public boolean isAIEnabled()
{
return true;
}
@Override
protected void updateAITick()
{
this.dataWatcher.updateObject(18, Float.valueOf(this.getHealth()));
}
@Override
protected void entityInit()
{
super.entityInit();
this.dataWatcher.addObject(18, new Float(this.getHealth()));
this.dataWatcher.addObject(19, new Float(this.colorRed));
this.dataWatcher.addObject(20, new Float(this.colorGreen));
this.dataWatcher.addObject(21, new Float(this.colorBlue));
this.dataWatcher.addObject(22, new Integer(this.age));
this.dataWatcher.addObject(23, "");
this.dataWatcher.addObject(24, new Integer(this.favFoodID));
this.dataWatcher.addObject(25, new Float(this.attackDamage));
this.dataWatcher.addObject(26, new Integer(this.kills));
this.dataWatcher.addObject(27, new ItemStack(Block.stone));
this.setName("Unnamed");
}
@Override
public void writeEntityToNBT(NBTTagCompound nbt)
{
super.writeEntityToNBT(nbt);
nbt.setTag("SlimelingInventory", this.slimelingInventory.writeToNBT(new NBTTagList()));
nbt.setFloat("SlimeRed", this.colorRed);
nbt.setFloat("SlimeGreen", this.colorGreen);
nbt.setFloat("SlimeBlue", this.colorBlue);
nbt.setInteger("SlimelingAge", this.age);
nbt.setString("SlimelingName", this.slimelingName);
nbt.setInteger("FavFoodID", this.favFoodID);
nbt.setFloat("SlimelingDamage", this.attackDamage);
nbt.setInteger("SlimelingKills", this.kills);
}
@Override
public void readEntityFromNBT(NBTTagCompound nbt)
{
super.readEntityFromNBT(nbt);
this.slimelingInventory.readFromNBT(nbt.getTagList("SlimelingInventory"));
this.colorRed = nbt.getFloat("SlimeRed");
this.colorGreen = nbt.getFloat("SlimeGreen");
this.colorBlue = nbt.getFloat("SlimeBlue");
this.age = nbt.getInteger("SlimelingAge");
this.slimelingName = nbt.getString("SlimelingName");
this.favFoodID = nbt.getInteger("FavFoodID");
this.attackDamage = nbt.getFloat("SlimelingDamage");
this.kills = nbt.getInteger("SlimelingKills");
this.setColorRed(this.colorRed);
this.setColorGreen(this.colorGreen);
this.setColorBlue(this.colorBlue);
this.setAge(this.age);
this.setName(this.slimelingName);
this.setKillCount(this.kills);
}
@Override
protected String getLivingSound()
{
return "";
}
@Override
protected String getHurtSound()
{
return "";
}
@Override
protected String getDeathSound()
{
this.playSound(GalacticraftCore.ASSET_PREFIX + "entity.slime_death", this.getSoundVolume(), 0.8F);
return "";
}
@Override
protected int getDropItemId()
{
return Item.slimeBall.itemID;
}
@Override
public void onLivingUpdate()
{
super.onLivingUpdate();
if (!this.worldObj.isRemote)
{
if (this.ticksAlive <= 0)
{
this.setColorRed(this.colorRed);
this.setColorGreen(this.colorGreen);
this.setColorBlue(this.colorBlue);
}
this.ticksAlive++;
if (this.ticksAlive >= Long.MAX_VALUE)
{
this.ticksAlive = 0;
}
if (this.ticksAlive % 2 == 0)
{
if (this.age < this.MAX_AGE)
{
this.age++;
}
this.setAge(Math.min(this.age, this.MAX_AGE));
}
this.setFavoriteFood(this.favFoodID);
this.setAttackDamage(this.attackDamage);
this.setKillCount(this.kills);
this.setCargoSlot(this.slimelingInventory.getStackInSlot(1));
}
if (!this.worldObj.isRemote)
{
this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setAttribute(this.getMaxHealthSlimeling());
}
}
private double getMaxHealthSlimeling()
{
if (this.isTamed())
{
return 20 + 30.0 * ((double) this.age / (double) this.MAX_AGE);
}
else
{
return 8.0D;
}
}
@Override
public float getEyeHeight()
{
return this.height * 0.8F;
}
@Override
public boolean attackEntityFrom(DamageSource par1DamageSource, float par2)
{
if (this.isEntityInvulnerable())
{
return false;
}
else
{
Entity entity = par1DamageSource.getEntity();
this.aiSit.setSitting(false);
if (entity != null && !(entity instanceof EntityPlayer) && !(entity instanceof EntityArrow))
{
par2 = (par2 + 1.0F) / 2.0F;
}
return super.attackEntityFrom(par1DamageSource, par2);
}
}
@Override
public boolean attackEntityAsMob(Entity par1Entity)
{
return par1Entity.attackEntityFrom(new EntityDamageSource("slimeling", this), this.getDamage());
}
public float getDamage()
{
int i = this.isTamed() ? 5 : 2;
return i * this.getAttackDamage();
}
@Override
public void setTamed(boolean par1)
{
super.setTamed(par1);
this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setAttribute(this.getMaxHealthSlimeling());
}
@Override
public boolean interact(EntityPlayer par1EntityPlayer)
{
ItemStack itemstack = par1EntityPlayer.inventory.getCurrentItem();
if (this.isTamed())
{
if (itemstack != null)
{
if (itemstack.itemID == this.getFavoriteFood())
{
if (par1EntityPlayer.username.equals(this.getOwnerName()))
{
--itemstack.stackSize;
if (itemstack.stackSize <= 0)
{
par1EntityPlayer.inventory.setInventorySlotContents(par1EntityPlayer.inventory.currentItem, (ItemStack) null);
}
if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT)
{
GalacticraftMars.proxy.opengSlimelingGui(this, 1);
}
if (this.rand.nextInt(2) == 0)
{
this.setRandomFavFood();
}
}
else
{
if (par1EntityPlayer instanceof GCCorePlayerMP)
{
if (((GCCorePlayerMP) par1EntityPlayer).getChatCooldown() == 0)
{
par1EntityPlayer.sendChatToPlayer(ChatMessageComponent.createFromText("This isn't my Slimeling!"));
((GCCorePlayerMP) par1EntityPlayer).setChatCooldown(100);
}
}
}
}
else
{
if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT)
{
GalacticraftMars.proxy.opengSlimelingGui(this, 0);
}
}
}
else
{
if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT)
{
GalacticraftMars.proxy.opengSlimelingGui(this, 0);
}
}
}
else if (itemstack != null && itemstack.itemID == Item.slimeBall.itemID)
{
if (!par1EntityPlayer.capabilities.isCreativeMode)
{
--itemstack.stackSize;
}
if (itemstack.stackSize <= 0)
{
par1EntityPlayer.inventory.setInventorySlotContents(par1EntityPlayer.inventory.currentItem, (ItemStack) null);
}
if (!this.worldObj.isRemote)
{
if (this.rand.nextInt(3) == 0)
{
this.setTamed(true);
this.setPathToEntity((PathEntity) null);
this.setAttackTarget((EntityLivingBase) null);
this.aiSit.setSitting(true);
this.setHealth(20.0F);
this.setOwner(par1EntityPlayer.getCommandSenderName());
this.playTameEffect(true);
this.worldObj.setEntityState(this, (byte) 7);
}
else
{
this.playTameEffect(false);
this.worldObj.setEntityState(this, (byte) 6);
}
}
return true;
}
return super.interact(par1EntityPlayer);
}
@Override
public boolean isBreedingItem(ItemStack par1ItemStack)
{
return false;
}
public GCMarsEntitySlimeling spawnBabyAnimal(EntityAgeable par1EntityAgeable)
{
if (par1EntityAgeable instanceof GCMarsEntitySlimeling)
{
GCMarsEntitySlimeling otherSlimeling = (GCMarsEntitySlimeling) par1EntityAgeable;
GCMarsEntitySlimeling newSlimeling = new GCMarsEntitySlimeling(this.worldObj, (this.getColorRed() + otherSlimeling.getColorRed()) / 2, (this.getColorGreen() + otherSlimeling.getColorGreen()) / 2, (this.getColorBlue() + otherSlimeling.getColorBlue()) / 2);
String s = this.getOwnerName();
if (s != null && s.trim().length() > 0)
{
newSlimeling.setOwner(s);
newSlimeling.setTamed(true);
}
return newSlimeling;
}
return null;
}
@Override
public boolean canMateWith(EntityAnimal par1EntityAnimal)
{
if (par1EntityAnimal == this)
{
return false;
}
else if (!this.isTamed())
{
return false;
}
else if (!(par1EntityAnimal instanceof GCMarsEntitySlimeling))
{
return false;
}
else
{
GCMarsEntitySlimeling slimeling = (GCMarsEntitySlimeling) par1EntityAnimal;
return !slimeling.isTamed() ? false : slimeling.isSitting() ? false : this.isInLove() && slimeling.isInLove();
}
}
@Override
public boolean func_142018_a(EntityLivingBase par1EntityLivingBase, EntityLivingBase par2EntityLivingBase)
{
if (!(par1EntityLivingBase instanceof EntityCreeper) && !(par1EntityLivingBase instanceof EntityGhast))
{
if (par1EntityLivingBase instanceof GCMarsEntitySlimeling)
{
GCMarsEntitySlimeling slimeling = (GCMarsEntitySlimeling) par1EntityLivingBase;
if (slimeling.isTamed() && slimeling.func_130012_q() == par2EntityLivingBase)
{
return false;
}
}
return par1EntityLivingBase instanceof EntityPlayer && par2EntityLivingBase instanceof EntityPlayer && !((EntityPlayer) par2EntityLivingBase).canAttackPlayer((EntityPlayer) par1EntityLivingBase) ? false : !(par1EntityLivingBase instanceof EntityHorse) || !((EntityHorse) par1EntityLivingBase).isTame();
}
else
{
return false;
}
}
@Override
public EntityAgeable createChild(EntityAgeable par1EntityAgeable)
{
return this.spawnBabyAnimal(par1EntityAgeable);
}
public float getColorRed()
{
return this.dataWatcher.getWatchableObjectFloat(19);
}
public void setColorRed(float color)
{
this.dataWatcher.updateObject(19, color);
}
public float getColorGreen()
{
return this.dataWatcher.getWatchableObjectFloat(20);
}
public void setColorGreen(float color)
{
this.dataWatcher.updateObject(20, color);
}
public float getColorBlue()
{
return this.dataWatcher.getWatchableObjectFloat(21);
}
public void setColorBlue(float color)
{
this.dataWatcher.updateObject(21, color);
}
@Override
public int getAge()
{
return this.dataWatcher.getWatchableObjectInt(22);
}
public void setAge(int age)
{
this.dataWatcher.updateObject(22, age);
}
public String getName()
{
return this.dataWatcher.getWatchableObjectString(23);
}
public void setName(String name)
{
this.dataWatcher.updateObject(23, name);
}
public int getFavoriteFood()
{
return this.dataWatcher.getWatchableObjectInt(24);
}
public void setFavoriteFood(int foodID)
{
this.dataWatcher.updateObject(24, foodID);
}
public float getAttackDamage()
{
return this.dataWatcher.getWatchableObjectFloat(25);
}
public void setAttackDamage(float damage)
{
this.dataWatcher.updateObject(25, damage);
}
public int getKillCount()
{
return this.dataWatcher.getWatchableObjectInt(26);
}
public void setKillCount(int damage)
{
this.dataWatcher.updateObject(26, damage);
}
@Override
public boolean canBreath()
{
return true;
}
public float getScale()
{
return this.getAge() / (float) this.MAX_AGE * 0.5F + 0.5F;
}
public EntityAISit getAiSit()
{
return this.aiSit;
}
public ItemStack getCargoSlot()
{
return this.dataWatcher.getWatchableObjectItemStack(27);
}
public void setCargoSlot(ItemStack stack)
{
WatchableObject obj = this.dataWatcher.getWatchedObject(27);
if (stack != obj.getObject())
{
obj.setObject(stack);
this.dataWatcher.setObjectWatched(27);
}
}
}
| lgpl-3.0 |
samanthamccabe/didelphis-common | didelphis-common-language/src/main/java/org/didelphis/language/phonetic/ModelBearer.java | 2301 | /******************************************************************************
* General components for language modeling and analysis *
* *
* Copyright (C) 2014-2019 Samantha F McCabe *
* *
* 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 <https://www.gnu.org/licenses/>. *
******************************************************************************/
package org.didelphis.language.phonetic;
import lombok.NonNull;
import org.didelphis.language.phonetic.model.FeatureModel;
import org.didelphis.language.phonetic.model.FeatureSpecification;
import org.didelphis.utilities.Templates;
/**
* Interface {@code ModelBearer}
*
* @since 0.1.0
*/
@FunctionalInterface
public interface ModelBearer<T> extends SpecificationBearer {
@NonNull
FeatureModel<T> getFeatureModel();
@NonNull
@Override
default FeatureSpecification getSpecification() {
return getFeatureModel().getSpecification();
}
default void consistencyCheck(@NonNull ModelBearer<T> bearer) {
if (!getFeatureModel().equals(bearer.getFeatureModel())) {
String message = Templates.create()
.add("Mismatch between models")
.data(this)
.data(bearer)
.build();
throw new IllegalArgumentException(message);
}
}
}
| lgpl-3.0 |
ArticulatedSocialAgentsPlatform/AsapRealizer | AsapRealizer/test/src/asap/realizer/scheduler/BMLBBlockTest.java | 8042 | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package asap.realizer.scheduler;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashSet;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import saiba.bml.BMLGestureSync;
import asap.bml.ext.bmla.feedback.BMLABlockStatus;
import asap.realizer.pegboard.PegBoard;
import asap.realizer.planunit.TimedPlanUnitState;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
/**
* Unit testcases for the BMLBBlock
* @author hvanwelbergen
*
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(BMLScheduler.class)
public class BMLBBlockTest
{
private static final String BLOCKID = "block1";
private BMLScheduler mockScheduler = mock(BMLScheduler.class);
private PegBoard pegBoard = new PegBoard();
private final static ImmutableMap<String, TimedPlanUnitState> EMPTY_UPDATE_MAP = new ImmutableMap.Builder<String, TimedPlanUnitState>()
.build();
@Test
public void testUpdate()
{
BMLBBlock block = new BMLBBlock(BLOCKID, mockScheduler, pegBoard);
block.setState(TimedPlanUnitState.LURKING);
block.update(EMPTY_UPDATE_MAP, 0);
verify(mockScheduler, times(1)).startBlock(BLOCKID, 0);
}
@Test
public void testNoUpdateInPending()
{
BMLBBlock block = new BMLBBlock(BLOCKID, mockScheduler, pegBoard);
block.setState(TimedPlanUnitState.PENDING);
block.update(EMPTY_UPDATE_MAP, 0);
verify(mockScheduler, times(0)).startBlock(BLOCKID, 0);
}
@Test
public void testNoUpdateWhenAppending()
{
BMLBBlock block = new BMLBBlock(BLOCKID, mockScheduler, pegBoard, Sets.newHashSet("bml2"), new ArrayList<String>(),
new HashSet<String>());
block.setState(TimedPlanUnitState.LURKING);
block.update(ImmutableMap.of("bml2", TimedPlanUnitState.IN_EXEC), 0);
verify(mockScheduler, times(0)).startBlock(BLOCKID, 0);
}
@Test
public void testFinishEmptyBlock()
{
BMLBBlock block = new BMLBBlock(BLOCKID, mockScheduler, pegBoard);
block.setState(TimedPlanUnitState.IN_EXEC);
block.update(EMPTY_UPDATE_MAP, 0);
assertEquals(TimedPlanUnitState.DONE, block.getState());
verify(mockScheduler, times(1)).blockStopFeedback(BLOCKID, BMLABlockStatus.DONE, 0);
}
@Test
public void testNotFinishNonEmptyBlock()
{
BMLBBlock block = new BMLBBlock(BLOCKID, mockScheduler, pegBoard);
block.setState(TimedPlanUnitState.IN_EXEC);
when(mockScheduler.getBehaviours(BLOCKID)).thenReturn(Sets.newHashSet("beh1"));
block.update(EMPTY_UPDATE_MAP, 0);
assertEquals(TimedPlanUnitState.IN_EXEC, block.getState());
verify(mockScheduler, times(0)).blockStopFeedback(BLOCKID, BMLABlockStatus.DONE, 0);
}
@Test
public void testFinishNonEmptyBlock()
{
BMLBBlock block = new BMLBBlock(BLOCKID, mockScheduler, pegBoard);
block.setState(TimedPlanUnitState.IN_EXEC);
when(mockScheduler.getBehaviours(BLOCKID)).thenReturn(Sets.newHashSet("beh1"));
block.behaviorProgress("beh1", BMLGestureSync.END.getId());
block.update(EMPTY_UPDATE_MAP, 0);
assertEquals(TimedPlanUnitState.DONE, block.getState());
verify(mockScheduler, times(1)).blockStopFeedback(BLOCKID, BMLABlockStatus.DONE, 0);
}
@Test
public void testSubsiding()
{
BMLBBlock block = new BMLBBlock(BLOCKID, mockScheduler, pegBoard);
block.setState(TimedPlanUnitState.IN_EXEC);
when(mockScheduler.getBehaviours(BLOCKID)).thenReturn(Sets.newHashSet("beh1"));
block.behaviorProgress("beh1", BMLGestureSync.RELAX.getId());
block.update(EMPTY_UPDATE_MAP, 0);
assertEquals(TimedPlanUnitState.SUBSIDING, block.getState());
}
@Test
public void testSubsidingToDone()
{
BMLBBlock block = new BMLBBlock(BLOCKID, mockScheduler, pegBoard);
block.setState(TimedPlanUnitState.SUBSIDING);
when(mockScheduler.getBehaviours(BLOCKID)).thenReturn(Sets.newHashSet("beh1"));
block.behaviorProgress("beh1", BMLGestureSync.END.getId());
block.update(EMPTY_UPDATE_MAP, 0);
assertEquals(TimedPlanUnitState.DONE, block.getState());
verify(mockScheduler, times(1)).blockStopFeedback(BLOCKID, BMLABlockStatus.DONE, 0);
}
@Test
public void testChunk()
{
BMLBBlock block = new BMLBBlock(BLOCKID, mockScheduler, pegBoard, new HashSet<String>(), new ArrayList<String>(),
Sets.newHashSet("bml2"));
block.setState(TimedPlanUnitState.LURKING);
block.update(ImmutableMap.of("bml2", TimedPlanUnitState.SUBSIDING), 0);
verify(mockScheduler, times(1)).startBlock(BLOCKID, 0);
}
@Test
public void testChunkGone()
{
BMLBBlock block = new BMLBBlock(BLOCKID, mockScheduler, pegBoard, new HashSet<String>(), new ArrayList<String>(),
Sets.newHashSet("bml2"));
block.setState(TimedPlanUnitState.LURKING);
block.update(EMPTY_UPDATE_MAP, 0);
verify(mockScheduler, times(1)).startBlock(BLOCKID, 0);
}
@Test
public void testNotChunk()
{
BMLBBlock block = new BMLBBlock(BLOCKID, mockScheduler, pegBoard, new HashSet<String>(), new ArrayList<String>(),
Sets.newHashSet("bml2"));
block.setState(TimedPlanUnitState.LURKING);
block.update(ImmutableMap.of("bml2", TimedPlanUnitState.IN_EXEC), 0);
verify(mockScheduler, times(0)).startBlock(BLOCKID, 0);
}
@Test
public void testChunkAndAppend()
{
BMLBBlock block = new BMLBBlock(BLOCKID, mockScheduler, pegBoard, new HashSet<String>(), ImmutableList.of("bml3"),
Sets.newHashSet("bml2"));
block.setState(TimedPlanUnitState.LURKING);
block.update(ImmutableMap.of("bml2", TimedPlanUnitState.SUBSIDING, "bml3", TimedPlanUnitState.DONE), 0);
verify(mockScheduler, times(1)).startBlock(BLOCKID, 0);
}
@Test
public void testChunkAndNoAppend()
{
BMLBBlock block = new BMLBBlock(BLOCKID, mockScheduler, pegBoard, new HashSet<String>(), ImmutableList.of("bml3"),
Sets.newHashSet("bml2"));
block.setState(TimedPlanUnitState.LURKING);
block.update(ImmutableMap.of("bml2", TimedPlanUnitState.SUBSIDING, "bml3", TimedPlanUnitState.SUBSIDING), 0);
verify(mockScheduler, times(1)).startBlock(BLOCKID, 0);
}
}
| lgpl-3.0 |
Lapiman/Galacticraft | src/main/java/micdoodle8/mods/galacticraft/api/transmission/grid/IReflectorNode.java | 236 | package micdoodle8.mods.galacticraft.api.transmission.grid;
import micdoodle8.mods.galacticraft.api.vector.Vector3;
public interface IReflectorNode
{
public Vector3 getInputPoint();
public Vector3 getOutputPoint(boolean offset);
}
| lgpl-3.0 |
vamsirajendra/sonarqube | sonar-ws/src/main/java/org/sonarqube/ws/client/permission/ApplyTemplateWsRequest.java | 2010 | /*
* 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.sonarqube.ws.client.permission;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
public class ApplyTemplateWsRequest {
private String projectId;
private String projectKey;
private String templateId;
private String templateName;
@CheckForNull
public String getProjectId() {
return projectId;
}
public ApplyTemplateWsRequest setProjectId(@Nullable String projectId) {
this.projectId = projectId;
return this;
}
@CheckForNull
public String getProjectKey() {
return projectKey;
}
public ApplyTemplateWsRequest setProjectKey(@Nullable String projectKey) {
this.projectKey = projectKey;
return this;
}
@CheckForNull
public String getTemplateId() {
return templateId;
}
public ApplyTemplateWsRequest setTemplateId(@Nullable String templateId) {
this.templateId = templateId;
return this;
}
@CheckForNull
public String getTemplateName() {
return templateName;
}
public ApplyTemplateWsRequest setTemplateName(@Nullable String templateName) {
this.templateName = templateName;
return this;
}
}
| lgpl-3.0 |
schuttek/nectar | src/main/java/org/nectarframework/base/form/Form.java | 7133 | package org.nectarframework.base.form;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.nectarframework.base.service.Log;
import org.nectarframework.base.service.directory.DirForm;
import org.nectarframework.base.service.directory.DirFormvar;
import org.nectarframework.base.service.pathfinder.FormResolution;
import org.nectarframework.base.service.pathfinder.FormvarResolution;
import org.nectarframework.base.service.session.Session;
import org.nectarframework.base.service.xml.Element;
import org.simpleframework.http.Request;
public class Form {
private Element element;
private List<ValidationError> validationErrors = null;
private Session session = null;
public enum VarType {
Long, String, StringArray, IntegerArray, Double;
public static VarType getByString(String typeStr) {
if (typeStr.equalsIgnoreCase("double"))
return Double;
if (typeStr.equalsIgnoreCase("integer") || typeStr.equalsIgnoreCase("long") || typeStr.equalsIgnoreCase("int"))
return Long;
if (typeStr.equalsIgnoreCase("string"))
return String;
if (typeStr.equalsIgnoreCase("integer_array") || typeStr.equalsIgnoreCase("int_array") || typeStr.equalsIgnoreCase("long_array"))
return IntegerArray;
if (typeStr.equalsIgnoreCase("string_array"))
return StringArray;
Log.warn("invalid typeStr " + typeStr + " while parsing formvars, defaulting to String.");
return String;
}
};
public Form(String name) {
element = new Element(name);
}
public Form(FormResolution formRes, Map<String, List<String>> parameters) {
element = new Element(formRes.getName());
for (FormvarResolution dfv : formRes.getFormvars()) {
List<String> valueList = parameters.get(dfv.getName());
validateFormVariable(dfv.getName(), dfv.getType(), dfv.isNullAllowed(), valueList);
}
}
public Form(DirForm dirForm, Map<String, List<String>> parameters) {
element = new Element(dirForm.name);
for (DirFormvar dfv : dirForm.formvars) {
List<String> valueList = parameters.get(dfv.name);
validateFormVariable(dfv.name, dfv.type, dfv.nullAllowed, valueList);
}
}
public void validateFormVariable(String name, Form.VarType type, boolean nullAllowed, List<String> valueList) {
if (valueList == null && !nullAllowed) {
addValidationError(new ValidationError(name, ValidationError.ErrorType.NULL_NOT_ALLOWED));
return;
}
String strValue = null;
switch (type) {
case String:
strValue = valueList.get(0);
if (strValue == null && !nullAllowed) {
addValidationError(new ValidationError(name, ValidationError.ErrorType.NULL_NOT_ALLOWED));
}
element.add(name, strValue);
break;
case Long:
strValue = valueList.get(0);
if (strValue == null && !nullAllowed) {
addValidationError(new ValidationError(name, ValidationError.ErrorType.NULL_NOT_ALLOWED));
}
try {
long l = Long.parseLong(strValue);
element.add(name, l);
} catch (NumberFormatException e) {
addValidationError(new ValidationError(name, ValidationError.ErrorType.NUMBER_PARSING_ERROR, strValue + " is not an Integer"));
}
break;
case Double:
strValue = valueList.get(0);
if (strValue == null && !nullAllowed) {
addValidationError(new ValidationError(name, ValidationError.ErrorType.NULL_NOT_ALLOWED));
}
try {
double d = Double.parseDouble(strValue);
element.add(name, d);
} catch (NumberFormatException e) {
addValidationError(new ValidationError(name, ValidationError.ErrorType.NUMBER_PARSING_ERROR, strValue + " is not a Double"));
}
break;
case StringArray:
if (valueList.isEmpty() && !nullAllowed) {
addValidationError(new ValidationError(name, ValidationError.ErrorType.NULL_NOT_ALLOWED));
}
for (String strElm : valueList) {
if (strElm == null && !nullAllowed) {
addValidationError(new ValidationError(name, ValidationError.ErrorType.NULL_NOT_ALLOWED));
break;
} else {
element.add(new Element(name).add("value", strElm));
}
}
break;
case IntegerArray:
if (valueList.isEmpty() && !nullAllowed) {
addValidationError(new ValidationError(name, ValidationError.ErrorType.NULL_NOT_ALLOWED));
}
for (String intElm : valueList) {
if (intElm == null && !nullAllowed) {
addValidationError(new ValidationError(name, ValidationError.ErrorType.NULL_NOT_ALLOWED));
} else {
try {
Long intElmInt = Long.parseLong(intElm);
element.add(new Element(name).add("value", intElmInt));
} catch (NumberFormatException e) {
addValidationError(new ValidationError(name, ValidationError.ErrorType.NULL_NOT_ALLOWED));
addValidationError(new ValidationError(name, ValidationError.ErrorType.NUMBER_PARSING_ERROR, intElm + " is not an Integer"));
}
}
}
break;
}
}
public String getString(String name) {
String ret = element.get(name);
if (ret != null) {
return ret;
} else if (element.getChildren().size() > 1) {
for (Element e : element.getChildren()) {
if (e.isName(name)) {
return e.get("value");
}
}
}
return null;
}
public Double getDouble(String name) {
String s = getString(name);
if (s != null) {
return Double.parseDouble(s);
}
return null;
}
public Long getLong(String name) {
String s = getString(name);
if (s != null) {
return Long.parseLong(s);
}
return null;
}
public Integer getInt(String name) {
String s = getString(name);
if (s != null) {
return Integer.parseInt(s);
}
return null;
}
public Byte getByte(String name) {
String s = getString(name);
if (s != null) {
return Byte.parseByte(s);
}
return null;
}
public Set<String> getVariableNames() {
Set<String> set = element.getAttributes().keySet();
for (Element e : element.getChildren()) {
String n = e.getName();
if (set.contains(n)) {
set.add(n);
}
}
return set;
}
public String getName() {
return element.getName();
}
public String toString() {
return "Form " + element.toString();
}
public String debugString() {
// TODO: add in request information.
return "Form " + element.toString();
}
public boolean isValid() {
return (validationErrors == null);
}
public List<ValidationError> getValidationErrors() {
return validationErrors;
}
public void addValidationError(ValidationError ve) {
if (ve != null) {
if (validationErrors == null) {
validationErrors = new LinkedList<ValidationError>();
}
validationErrors.add(ve);
}
}
public Long uid() {
return Long.parseLong(session.getVars().get("userId"));
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public Element getElement() {
return element;
}
public void setHttpRequest(Request request) {
// TODO Auto-generated method stub
}
}
| lgpl-3.0 |
eorodrig/eorodrigTravelLogger | TravelLogger/src/com/eorodrig/TravelLogger/NewClaimActivity.java | 6183 | /*
* <one line to give the program's name and a brief idea of what it does.>
Copyright (C) <2015> <Edwin Rodriguez eorodrig@ualberta.ca>
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.eorodrig.TravelLogger;
import java.util.Date;
import com.eorodrig.TravelLogger.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
public class NewClaimActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_claim);
/*This inits the Date pickers*/
DatePicker fdp = (DatePicker) findViewById(R.id.fromDate);
DatePicker tdp = (DatePicker) findViewById(R.id.toDatePicker);
fdp.setCalendarViewShown(false);
tdp.setCalendarViewShown(false);
}
@Override
protected void onResume(){
super.onResume();
/*Claim controller for the app*/
ClaimController claimController = new ClaimController();
//if this is null, we make a new claim, else we edit a claim
if (claimController.getClaimToEdit() ==null){
this.initNewClaim(claimController);
}
else
{
this.initEditClaim(claimController);
}
}
/*This will make format the page so that it looks like a new claim*/
private void initNewClaim(ClaimController claimController){
claimController.setEditStatus(false);
Button button = (Button) findViewById(R.id.NewClaimAddButton);
button.setText("Add New Claim");
}
/*This will extract the claim information and place it their fields*/
private void initEditClaim(ClaimController claimController) {
/*Extracts the claim we need to edit*/
Claim editableClaim = claimController.getClaimToEdit();
/*These Things we need to edit*/
TextView dataExtractor;
DatePicker datePicker;
/*We set the claim name*/
dataExtractor = (TextView)findViewById(R.id.NewClaimNameText);
dataExtractor.setText(editableClaim.getName());
/*we set the claim description*/
dataExtractor = (TextView)findViewById(R.id.NewClaimDescriptionText);
dataExtractor.setText(editableClaim.getDescription());
/*we set the claim from date*/
datePicker = (DatePicker) findViewById(R.id.fromDate);
datePicker.init(editableClaim.getStartDate().getYear()+1900, editableClaim.getStartDate().getMonth(), editableClaim.getStartDate().getDate(), null);
/*we set the claim from date*/
datePicker = (DatePicker) findViewById(R.id.toDatePicker);
datePicker.init(editableClaim.getEndDate().getYear()+1900, editableClaim.getEndDate().getMonth(), editableClaim.getEndDate().getDate(), null);
/*resets the edit parameter*/
claimController.resetClaimToEdit();
/*Sets the state of the claim to edit*/
claimController.setEditStatus(true);
Button button = (Button) findViewById(R.id.NewClaimAddButton);
button.setText("Edit Claim");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_claim, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* This is the Button call for the Add/Edit Claim button
* @param view
*/
public void onClickAddClaimButton(View view){
String claim, claimDescription;
Date start,end;
TextView dataExtractor;
DatePicker dateExtractor;
/*These will extract the data fields from the new claim/edit claim page*/
/*extract claim name*/
dataExtractor = (TextView)findViewById(R.id.NewClaimNameText);
claim = dataExtractor.getText().toString();
/*extract claim description*/
dataExtractor = (TextView)findViewById(R.id.NewClaimDescriptionText);
claimDescription = dataExtractor.getText().toString();
/*from Date*/
dateExtractor = (DatePicker) findViewById(R.id.fromDate);
start = new Date(dateExtractor.getYear()-1900, dateExtractor.getMonth(), dateExtractor.getDayOfMonth());
/*to Date*/
dateExtractor = (DatePicker) findViewById(R.id.toDatePicker);
end = new Date(dateExtractor.getYear()-1900, dateExtractor.getMonth(), dateExtractor.getDayOfMonth());
/*verify that the fields are field in*/
if ((claim.isEmpty()) || (claimDescription.isEmpty()) )
{
Toast toast = Toast.makeText(NewClaimActivity.this, "Complete All Fields Before Adding Claim", Toast.LENGTH_LONG);
toast.show();
}
/*Add the claim*/
else
{
Claim newClaim = new Claim(claim, claimDescription, start, end);
ClaimController claimController = new ClaimController();
if (claimController.getEditStatus() == false){
claimController.addClaim(newClaim);
Toast toast = Toast.makeText(NewClaimActivity.this, "New Claim Added", Toast.LENGTH_SHORT);
toast.show();
}
/*Edit the claim*/
else
{
claimController.editClaim(claim, claimDescription, start, end);
Toast toast = Toast.makeText(NewClaimActivity.this, "Edited Claim", Toast.LENGTH_SHORT);
toast.show();
}
finish();
}
}
}
| lgpl-3.0 |
jsteenbeeke/andalite | java/src/main/java/com/jeroensteenbeeke/andalite/java/transformation/navigation/ContainingDenominationMethodNavigation.java | 3177 | /**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jeroensteenbeeke.andalite.java.transformation.navigation;
import com.jeroensteenbeeke.andalite.core.exceptions.NavigationException;
import com.jeroensteenbeeke.andalite.java.analyzer.*;
import com.jeroensteenbeeke.andalite.java.transformation.ParameterDescriptor;
import com.jeroensteenbeeke.andalite.java.util.AnalyzeUtil;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
import java.util.List;
public class ContainingDenominationMethodNavigation<T extends ContainingDenomination<T,?>> extends
ChainedNavigation<T, AnalyzedMethod> {
private final String name;
private final String type;
private final AccessModifier modifier;
private final List<ParameterDescriptor> descriptors;
public ContainingDenominationMethodNavigation(
@NotNull IJavaNavigation<T> denominationNavigation,
@NotNull String name, @Nullable String type,
@Nullable AccessModifier modifier,
@NotNull List<ParameterDescriptor> descriptors) {
super(denominationNavigation);
this.name = name;
this.type = type;
this.modifier = modifier;
this.descriptors = descriptors;
}
@Override
public String getStepDescription() {
return String.format("go to method %s",
AnalyzeUtil.getMethodSignature(name, descriptors));
}
@Override
public AnalyzedMethod navigate(T chainedTarget)
throws NavigationException {
for (AnalyzedMethod analyzedMethod : chainedTarget.getMethods()) {
if (name.equals(analyzedMethod.getName())) {
if (AnalyzeUtil.matchesSignature(analyzedMethod, descriptors)) {
AnalyzedType returnType = analyzedMethod.getReturnType();
final String returnTypeAsString = returnType != null ? returnType
.toJavaString() : "void";
if (type != null && !type.equals(returnTypeAsString)) {
throw new NavigationException(
"Method %s found, but has incorrect return type %s (expected %s)",
AnalyzeUtil.getMethodSignature(name,
descriptors), returnTypeAsString, type);
}
if (modifier != null
&& !modifier.equals(analyzedMethod
.getAccessModifier())) {
throw new NavigationException(
"Method %s found, but has incorrect access type %s (expected %s)",
AnalyzeUtil.getMethodSignature(name,
descriptors), analyzedMethod
.getAccessModifier(), modifier);
}
return analyzedMethod;
}
}
}
throw new NavigationException("Could not find method %s",
AnalyzeUtil.getMethodSignature(name, descriptors));
}
}
| lgpl-3.0 |
waldheinz/fat32-lib | src/main/java/de/waldheinz/fs/fat/FsInfoSector.java | 5914 | /*
* Copyright (C) 2009-2013 Matthias Treydte <mt@waldheinz.de>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; If not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package de.waldheinz.fs.fat;
import de.waldheinz.fs.BlockDevice;
import java.io.IOException;
/**
* The FAT32 File System Information Sector.
*
* @author Matthias Treydte <waldheinz at gmail.com>
* @see http://en.wikipedia.org/wiki/File_Allocation_Table#FS_Information_Sector
*/
final class FsInfoSector extends Sector {
/**
* The offset to the free cluster count value in the FS info sector.
*/
public static final int FREE_CLUSTERS_OFFSET = 0x1e8;
/**
* The offset to the "last allocated cluster" value in this sector.
*/
public static final int LAST_ALLOCATED_OFFSET = 0x1ec;
/**
* The offset to the signature of this sector.
*/
public static final int SIGNATURE_OFFSET = 0x1fe;
private FsInfoSector(BlockDevice device, long offset) {
super(device, offset, BootSector.SIZE);
}
/**
* Reads a {@code FsInfoSector} as specified by the given
* {@code Fat32BootSector}.
*
* @param bs the boot sector that specifies where the FS info sector is
* stored
* @return the FS info sector that was read
* @throws IOException on read error
* @see Fat32BootSector#getFsInfoSectorNr()
*/
public static FsInfoSector read(Fat32BootSector bs) throws IOException {
final FsInfoSector result =
new FsInfoSector(bs.getDevice(), offset(bs));
result.read();
result.verify();
return result;
}
/**
* Creates an new {@code FsInfoSector} where the specified
* {@code Fat32BootSector} indicates it should be.
*
* @param bs the boot sector specifying the FS info sector storage
* @return the FS info sector instance that was created
* @throws IOException on write error
* @see Fat32BootSector#getFsInfoSectorNr()
*/
public static FsInfoSector create(Fat32BootSector bs) throws IOException {
final int offset = offset(bs);
if (offset == 0) throw new IOException(
"creating a FS info sector at offset 0 is strange");
final FsInfoSector result =
new FsInfoSector(bs.getDevice(), offset(bs));
result.init();
result.write();
return result;
}
private static int offset(Fat32BootSector bs) {
return bs.getFsInfoSectorNr() * bs.getBytesPerSector();
}
/**
* Sets the number of free clusters on the file system stored at
* {@link #FREE_CLUSTERS_OFFSET}.
*
* @param value the new free cluster count
* @see Fat#getFreeClusterCount()
*/
public void setFreeClusterCount(long value) {
if (getFreeClusterCount() == value) return;
set32(FREE_CLUSTERS_OFFSET, value);
}
/**
* Returns the number of free clusters on the file system as sepcified by
* the 32-bit value at {@link #FREE_CLUSTERS_OFFSET}.
*
* @return the number of free clusters
* @see Fat#getFreeClusterCount()
*/
public long getFreeClusterCount() {
return get32(FREE_CLUSTERS_OFFSET);
}
/**
* Sets the last allocated cluster that was used in the {@link Fat}.
*
* @param value the FAT's last allocated cluster number
* @see Fat#getLastAllocatedCluster()
*/
public void setLastAllocatedCluster(long value) {
if (getLastAllocatedCluster() == value) return;
super.set32(LAST_ALLOCATED_OFFSET, value);
}
/**
* Returns the last allocated cluster number of the {@link Fat} of the
* file system this FS info sector is part of.
*
* @return the last allocated cluster number
* @see Fat#getLastAllocatedCluster()
*/
public long getLastAllocatedCluster() {
return super.get32(LAST_ALLOCATED_OFFSET);
}
private void init() {
buffer.position(0x00);
buffer.put((byte) 0x52);
buffer.put((byte) 0x52);
buffer.put((byte) 0x61);
buffer.put((byte) 0x41);
/* 480 reserved bytes */
buffer.position(0x1e4);
buffer.put((byte) 0x72);
buffer.put((byte) 0x72);
buffer.put((byte) 0x41);
buffer.put((byte) 0x61);
setFreeClusterCount(-1);
setLastAllocatedCluster(Fat.FIRST_CLUSTER);
buffer.position(SIGNATURE_OFFSET);
buffer.put((byte) 0x55);
buffer.put((byte) 0xaa);
markDirty();
}
private void verify() throws IOException {
if (!(get8(SIGNATURE_OFFSET) == 0x55) ||
!(get8(SIGNATURE_OFFSET + 1) == 0xaa)) {
throw new IOException("invalid FS info sector signature");
}
}
@Override
public String toString() {
return FsInfoSector.class.getSimpleName() +
" [freeClusterCount=" + getFreeClusterCount() + //NOI18N
", lastAllocatedCluster=" + getLastAllocatedCluster() + //NOI18N
", offset=" + getOffset() + //NOI18N
", dirty=" + isDirty() + //NOI18N
"]"; //NOI18N
}
}
| lgpl-3.0 |
kevoree/kevoree-java | adaptation/src/main/java/org/kevoree/adaptation/operation/RemoveDeployUnit.java | 997 | package org.kevoree.adaptation.operation;
import org.kevoree.DeployUnit;
import org.kevoree.adaptation.operation.util.AdaptationOperation;
import org.kevoree.adaptation.operation.util.OperationOrder;
/**
* Created by mleduc on 18/12/15.
*/
public class RemoveDeployUnit extends AdaptationOperation{
public RemoveDeployUnit(final DeployUnit du) {
super(du.uuid());
}
@Override
public OperationOrder getOperationOrder() {
return OperationOrder.REMOVE_DEPLOY_UNIT;
}
@Override
public String toString() {
return "RemoveDeployUnit{" +
"uuid=" + uuid +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RemoveDeployUnit that = (RemoveDeployUnit) o;
return uuid == that.uuid;
}
@Override
public int hashCode() {
return (int) (uuid ^ (uuid >>> 32));
}
}
| lgpl-3.0 |
jsteenbeeke/andalite | java/src/main/java/com/jeroensteenbeeke/andalite/java/transformation/operations/impl/EnsurePackageEnum.java | 3084 | /**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jeroensteenbeeke.andalite.java.transformation.operations.impl;
import java.util.List;
import com.google.common.collect.ImmutableList;
import com.jeroensteenbeeke.lux.ActionResult;
import com.jeroensteenbeeke.andalite.core.ILocatable;
import com.jeroensteenbeeke.andalite.core.Transformation;
import com.jeroensteenbeeke.andalite.java.analyzer.AccessModifier;
import com.jeroensteenbeeke.andalite.java.analyzer.AnalyzedEnum;
import com.jeroensteenbeeke.andalite.java.analyzer.AnalyzedSourceFile;
import com.jeroensteenbeeke.andalite.java.transformation.operations.ICompilationUnitOperation;
import org.jetbrains.annotations.NotNull;
/**
* Ensures that a given compilation unit will have a enum with default
* (package) scope and the specified name
*
* @author Jeroen Steenbeeke
*
*/
public class EnsurePackageEnum implements ICompilationUnitOperation {
private final String expectedEnumName;
/**
* Create a new EnsurePackageEnum operation
*
* @param expectedEnumName
* The name of the class we want to ensure the existence of.
* Needs to be a valid Java identifier
*/
public EnsurePackageEnum(String expectedEnumName) {
if (!isValidJavaIdentifier(expectedEnumName)) {
throw new IllegalArgumentException(String.format(
"%s is not a valid Java identifier", expectedEnumName));
}
this.expectedEnumName = expectedEnumName;
}
@Override
public List<Transformation> perform(@NotNull AnalyzedSourceFile input) {
for (AnalyzedEnum analyzedEnum : input.getEnums()) {
if (analyzedEnum.getAccessModifier() == AccessModifier.DEFAULT
&& expectedEnumName.equals(analyzedEnum.getEnumName())) {
return ImmutableList.of();
}
}
return ImmutableList
.of(input.insertAt(AnalyzedSourceFile.SourceFileInsertionPoint.AFTER_LAST_DENOMINATION,
String.format("enum %s {\n\n}\n", expectedEnumName)));
}
@Override
public String getDescription() {
return String.format("presence of a package-level class named %s",
expectedEnumName);
}
@Override
public ActionResult verify(@NotNull AnalyzedSourceFile input) {
for (AnalyzedEnum analyzedEnum : input.getEnums()) {
if (analyzedEnum.getAccessModifier() == AccessModifier.DEFAULT
&& expectedEnumName.equals(analyzedEnum.getEnumName())) {
return ActionResult.ok();
}
}
return ActionResult.error("No package enum named %s", expectedEnumName);
}
}
| lgpl-3.0 |
jsmithe/ari4java | classes/ch/loway/oss/ari4java/generated/ari_1_9_0/AriBuilder_impl_ari_1_9_0.java | 7628 | package ch.loway.oss.ari4java.generated.ari_1_9_0;
// ----------------------------------------------------
// THIS CLASS WAS GENERATED AUTOMATICALLY
// PLEASE DO NOT EDIT
// Generated on: Sat Feb 04 15:23:09 CET 2017
// ----------------------------------------------------
import ch.loway.oss.ari4java.generated.ari_1_9_0.models.*;
import ch.loway.oss.ari4java.generated.ari_1_9_0.actions.*;
import ch.loway.oss.ari4java.generated.*;
import ch.loway.oss.ari4java.ARI;
public class AriBuilder_impl_ari_1_9_0 implements AriBuilder {
public ActionAsterisk actionAsterisk() {
return new ActionAsterisk_impl_ari_1_9_0();
};
public ActionPlaybacks actionPlaybacks() {
return new ActionPlaybacks_impl_ari_1_9_0();
};
public ActionApplications actionApplications() {
return new ActionApplications_impl_ari_1_9_0();
};
public ActionSounds actionSounds() {
return new ActionSounds_impl_ari_1_9_0();
};
public ActionEvents actionEvents() {
return new ActionEvents_impl_ari_1_9_0();
};
public ActionEndpoints actionEndpoints() {
return new ActionEndpoints_impl_ari_1_9_0();
};
public ActionRecordings actionRecordings() {
return new ActionRecordings_impl_ari_1_9_0();
};
public ActionChannels actionChannels() {
return new ActionChannels_impl_ari_1_9_0();
};
public ActionBridges actionBridges() {
return new ActionBridges_impl_ari_1_9_0();
};
public ActionDeviceStates actionDeviceStates() {
return new ActionDeviceStates_impl_ari_1_9_0();
};
public CallerID callerID() {
return new CallerID_impl_ari_1_9_0();
};
public Event event() {
return new Event_impl_ari_1_9_0();
};
public ChannelStateChange channelStateChange() {
return new ChannelStateChange_impl_ari_1_9_0();
};
public ChannelCallerId channelCallerId() {
return new ChannelCallerId_impl_ari_1_9_0();
};
public PlaybackFinished playbackFinished() {
return new PlaybackFinished_impl_ari_1_9_0();
};
public StasisStart stasisStart() {
return new StasisStart_impl_ari_1_9_0();
};
public Playback playback() {
return new Playback_impl_ari_1_9_0();
};
public ChannelEnteredBridge channelEnteredBridge() {
return new ChannelEnteredBridge_impl_ari_1_9_0();
};
public TextMessageReceived textMessageReceived() {
return new TextMessageReceived_impl_ari_1_9_0();
};
public StasisEnd stasisEnd() {
return new StasisEnd_impl_ari_1_9_0();
};
public ChannelHold channelHold() {
return new ChannelHold_impl_ari_1_9_0();
};
public FormatLangPair formatLangPair() {
return new FormatLangPair_impl_ari_1_9_0();
};
public BridgeAttendedTransfer bridgeAttendedTransfer() {
return new BridgeAttendedTransfer_impl_ari_1_9_0();
};
public Bridge bridge() {
return new Bridge_impl_ari_1_9_0();
};
public ChannelVarset channelVarset() {
return new ChannelVarset_impl_ari_1_9_0();
};
public ChannelTalkingFinished channelTalkingFinished() {
return new ChannelTalkingFinished_impl_ari_1_9_0();
};
public PlaybackStarted playbackStarted() {
return new PlaybackStarted_impl_ari_1_9_0();
};
public SetId setId() {
return new SetId_impl_ari_1_9_0();
};
public RecordingFinished recordingFinished() {
return new RecordingFinished_impl_ari_1_9_0();
};
public BridgeDestroyed bridgeDestroyed() {
return new BridgeDestroyed_impl_ari_1_9_0();
};
public ChannelCreated channelCreated() {
return new ChannelCreated_impl_ari_1_9_0();
};
public PeerStatusChange peerStatusChange() {
return new PeerStatusChange_impl_ari_1_9_0();
};
public Application application() {
return new Application_impl_ari_1_9_0();
};
public Variable variable() {
return new Variable_impl_ari_1_9_0();
};
public ConfigTuple configTuple() {
return new ConfigTuple_impl_ari_1_9_0();
};
public EndpointStateChange endpointStateChange() {
return new EndpointStateChange_impl_ari_1_9_0();
};
public ChannelLeftBridge channelLeftBridge() {
return new ChannelLeftBridge_impl_ari_1_9_0();
};
public RecordingStarted recordingStarted() {
return new RecordingStarted_impl_ari_1_9_0();
};
public StoredRecording storedRecording() {
return new StoredRecording_impl_ari_1_9_0();
};
public DeviceStateChanged deviceStateChanged() {
return new DeviceStateChanged_impl_ari_1_9_0();
};
public ChannelConnectedLine channelConnectedLine() {
return new ChannelConnectedLine_impl_ari_1_9_0();
};
public ChannelUserevent channelUserevent() {
return new ChannelUserevent_impl_ari_1_9_0();
};
public Dial dial() {
return new Dial_impl_ari_1_9_0();
};
public BuildInfo buildInfo() {
return new BuildInfo_impl_ari_1_9_0();
};
public DialplanCEP dialplanCEP() {
return new DialplanCEP_impl_ari_1_9_0();
};
public Endpoint endpoint() {
return new Endpoint_impl_ari_1_9_0();
};
public ChannelDestroyed channelDestroyed() {
return new ChannelDestroyed_impl_ari_1_9_0();
};
public Channel channel() {
return new Channel_impl_ari_1_9_0();
};
public MissingParams missingParams() {
return new MissingParams_impl_ari_1_9_0();
};
public Module module() {
return new Module_impl_ari_1_9_0();
};
public ChannelDialplan channelDialplan() {
return new ChannelDialplan_impl_ari_1_9_0();
};
public LogChannel logChannel() {
return new LogChannel_impl_ari_1_9_0();
};
public AsteriskInfo asteriskInfo() {
return new AsteriskInfo_impl_ari_1_9_0();
};
public StatusInfo statusInfo() {
return new StatusInfo_impl_ari_1_9_0();
};
public ChannelHangupRequest channelHangupRequest() {
return new ChannelHangupRequest_impl_ari_1_9_0();
};
public Dialed dialed() {
return new Dialed_impl_ari_1_9_0();
};
public ChannelTalkingStarted channelTalkingStarted() {
return new ChannelTalkingStarted_impl_ari_1_9_0();
};
public Sound sound() {
return new Sound_impl_ari_1_9_0();
};
public TextMessage textMessage() {
return new TextMessage_impl_ari_1_9_0();
};
public DeviceState deviceState() {
return new DeviceState_impl_ari_1_9_0();
};
public BridgeMerged bridgeMerged() {
return new BridgeMerged_impl_ari_1_9_0();
};
public ChannelDtmfReceived channelDtmfReceived() {
return new ChannelDtmfReceived_impl_ari_1_9_0();
};
public ChannelUnhold channelUnhold() {
return new ChannelUnhold_impl_ari_1_9_0();
};
public ContactStatusChange contactStatusChange() {
return new ContactStatusChange_impl_ari_1_9_0();
};
public BridgeCreated bridgeCreated() {
return new BridgeCreated_impl_ari_1_9_0();
};
public ConfigInfo configInfo() {
return new ConfigInfo_impl_ari_1_9_0();
};
public SystemInfo systemInfo() {
return new SystemInfo_impl_ari_1_9_0();
};
public TextMessageVariable textMessageVariable() {
return new TextMessageVariable_impl_ari_1_9_0();
};
public ContactInfo contactInfo() {
return new ContactInfo_impl_ari_1_9_0();
};
public LiveRecording liveRecording() {
return new LiveRecording_impl_ari_1_9_0();
};
public ApplicationReplaced applicationReplaced() {
return new ApplicationReplaced_impl_ari_1_9_0();
};
public Peer peer() {
return new Peer_impl_ari_1_9_0();
};
public BridgeBlindTransfer bridgeBlindTransfer() {
return new BridgeBlindTransfer_impl_ari_1_9_0();
};
public Message message() {
return new Message_impl_ari_1_9_0();
};
public RecordingFailed recordingFailed() {
return new RecordingFailed_impl_ari_1_9_0();
};
public BridgeVideoSourceChanged bridgeVideoSourceChanged() {
throw new UnsupportedOperationException();
};
public PlaybackContinuing playbackContinuing() {
throw new UnsupportedOperationException();
};
public ARI.ClassFactory getClassFactory() {
return new ClassTranslator_impl_ari_1_9_0();
};
};
| lgpl-3.0 |
Sankore/Editeur_Sankore---LENUOS- | sources/lenuos/editor-modules/src/com/paraschool/editor/modules/relier/client/ui/RelierNodeContent.java | 7436 | package com.paraschool.editor.modules.relier.client.ui;
import java.util.ArrayList;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLTable;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;
import com.paraschool.editor.api.client.ModuleObject;
import com.paraschool.editor.api.client.ViewModuleContext;
import com.paraschool.editor.modules.commons.client.EventBus;
import com.paraschool.editor.modules.commons.client.jso.BlocJSO;
import com.paraschool.editor.modules.commons.client.jso.NodeContentJSO;
import com.paraschool.editor.modules.commons.client.jso.NodeJSO;
import com.paraschool.editor.modules.commons.client.jso.OptionJSO;
import com.paraschool.editor.modules.commons.client.jso.StatementJSO;
import com.paraschool.editor.modules.commons.client.ui.MediaContainer;
import com.paraschool.editor.modules.commons.client.ui.NodeContent;
import com.paraschool.editor.modules.relier.client.i18n.RelierModuleMessages;
import com.paraschool.editor.modules.relier.client.jso.RelierNodeContentJSO;
public class RelierNodeContent extends Composite implements NodeContent {
private static RelierNodeContentUiBinder uiBinder = GWT.create(RelierNodeContentUiBinder.class);
interface RelierNodeContentUiBinder extends UiBinder<Widget, RelierNodeContent> {}
class SelectablePin extends Pin {
private int column;
private SelectablePin link;
SelectablePin(int id, int column) {
super(id);
this.column = column;
}
}
interface CssResource extends com.google.gwt.resources.client.CssResource {
String part();
String statement();
String cells();
String cell();
String switched();
String text();
@ClassName("has-sound") String hasSound();
@ClassName("has-text") String hasText();
String activated();
String linked();
String pin();
String left();
String right();
}
private final boolean isInverse;
private boolean random = false;
private final ViewModuleContext context;
private SelectablePin selected;
@UiField CssResource css;
@UiField FlowPanel root;
@UiField MediaContainer resource;
@UiField MediaContainer sound;
@UiField HTML text;
@UiField Panel soundTextContainer;
@UiField AbsolutePanel blocsContainer;
@UiField HTMLTable blocs;
public RelierNodeContent(boolean isInverse, EventBus eventBus, ViewModuleContext context, RelierModuleMessages messages) {
initWidget(uiBinder.createAndBindUi(this));
this.isInverse = isInverse;
this.context = context;
}
@Override
public Widget widget(NodeJSO jso) {
RelierNodeContentJSO contentJSO = null;
if(jso != null && (contentJSO = jso.getContent().cast()) != null) {
StatementJSO statementJSO = contentJSO.getStatement();
if(statementJSO != null) {
text.setHTML(statementJSO.getStatement());
if(text.getText().trim().length() != 0) soundTextContainer.addStyleName(css.hasText());
ModuleObject temp = null;
String sId = statementJSO.getSound();
if(sId != null && (temp = context.getObject(sId)) != null) {
sound.setMedia(temp, null);
soundTextContainer.addStyleName(css.hasSound());
}
String rId = statementJSO.getResource();
if(rId != null && (temp = context.getObject(rId)) != null) resource.setMedia(temp, null);
}
proceedOptions(jso.getOptions());
createFromJSOS(contentJSO.getLeftBlocs(), RelierEditNodeContent.LEFT_BLOC_COLUMN, random);
createFromJSOS(contentJSO.getRightBlocs(), RelierEditNodeContent.RIGHT_BLOC_COLUMN, random);
if(isInverse)
root.insert(blocsContainer, 0);
}
return this;
}
@Override
public NodeContentJSO getJSO() {
// TODO Create result data
return null;
}
protected void proceedOptions(JsArray<OptionJSO> jsos) {
for(int i=0 ; jsos != null && i<jsos.length() ; i++) {
OptionJSO jso = jsos.get(i);
if(jso != null){
if("random".equals(jso.getName()) && jso.getValue() != null){
random = true;
}
}
}
}
private void createFromJSOS(final JsArray<BlocJSO> jsos, final int column, boolean random) {
if(jsos != null) {
if(!random)
Scheduler.get().scheduleIncremental(new Scheduler.RepeatingCommand() {
int i=0;
@Override
public boolean execute() {
createFromJSO(i, column, i, jsos.get(i));
return ++i < jsos.length();
}
});
else
Scheduler.get().scheduleIncremental(new Scheduler.RepeatingCommand() {
ArrayList<Integer> meeted = new ArrayList<Integer>();
@Override
public boolean execute() {
int next = Random.nextInt(jsos.length());
while (meeted.contains(next)) {
next = Random.nextInt(jsos.length());
}
createFromJSO(meeted.size(), column, next, jsos.get(next));
meeted.add(next);
return meeted.size() < jsos.length();
}
});
}
}
private void createFromJSO(int row, int column, int id, BlocJSO jso) {
HTML text = new HTML();
MediaContainer resource = new MediaContainer();
MediaContainer sound = new MediaContainer();
text.setStyleName(css.text());
if(jso != null) {
text.setHTML(jso.getText());
ModuleObject temp = null;
String rId = jso.getResource();
if(rId != null && (temp = context.getObject(rId)) != null) resource.setMedia(temp, null);
String sId = jso.getSound();
if(sId != null && (temp = context.getObject(sId)) != null) sound.setMedia(temp, null);
}
FlowPanel bloc = new FlowPanel();
bloc.addStyleName(css.cell());
bloc.add(resource);
bloc.add(sound);
bloc.add(text);
blocs.setWidget(row, column, bloc);
blocs.setWidget(row, column == RelierEditNodeContent.LEFT_BLOC_COLUMN ? RelierEditNodeContent.LEFT_BLOC_COLUMN + 1 : RelierEditNodeContent.RIGHT_BLOC_COLUMN - 1, createPin(id, column));
}
private SelectablePin createPin(final int id, final int column) {
final SelectablePin p = new SelectablePin(id, column);
p.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
pinClicked(p);
}
});
p.addStyleName(css.pin());
p.addStyleName(column == RelierEditNodeContent.LEFT_BLOC_COLUMN ? css.left() : css.right());
return p;
}
private void pinClicked(SelectablePin p) {
if(p.link != null) {
unlink(p);
return;
}
if(selected != null){
selected.removeStyleName(css.activated());
if(selected.column != p.column){
link(selected, p);
selected = null;
return;
}
}
if(selected != p) {
p.addStyleName(css.activated());
selected = p;
}else
selected = null;
}
private void link(SelectablePin source, SelectablePin destination) {
source.addStyleName(css.linked());
destination.addStyleName(css.linked());
source.link = destination;
destination.link = source;
}
private void unlink(SelectablePin p) {
p.link.link = null;
p.link.removeStyleName(css.linked());
p.link = null;
p.removeStyleName(css.linked());
}
}
| lgpl-3.0 |
erickdarwin/sentinela | Sentinela/src/pe/edu/upeupoo/evaluacion2/Controldeasistensia.java | 80 | package pe.edu.upeupoo.evaluacion2;
public class Controldeasistensia {
}
| lgpl-3.0 |
lusardim/Facturacion | src/main/java/ar/com/jumperinformatica/gui/controller/listeners/CambioTablaDetalleListener.java | 1096 | package ar.com.jumperinformatica.gui.controller.listeners;
import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import ar.com.jumperinformatica.core.exceptions.LogicaException;
import ar.com.jumperinformatica.core.persistent.Factura;
import ar.com.jumperinformatica.gui.controller.interfaces.AMController;
public class CambioTablaDetalleListener implements TableModelListener {
private AMController controller;
private Factura factura;
public CambioTablaDetalleListener(Factura pFactura , AMController pController){
this.controller = pController;
this.factura = pFactura;
}
@Override
public void tableChanged(TableModelEvent e) {
try {
this.controller.actualizarModelo();
this.factura.calcularSubTotalDetalle();
this.factura.calcularTotalIva();
this.factura.calcularTotal();
this.controller.actualizarVista();
} catch (LogicaException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(this.controller.getVista(), e1.getMessage(),
"Error",JOptionPane.ERROR_MESSAGE);
}
}
}
| lgpl-3.0 |
vamsirajendra/sonarqube | sonar-db/src/test/java/org/sonar/db/version/AddColumnsBuilderTest.java | 3086 | /*
* 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.db.version;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.MySql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
public class AddColumnsBuilderTest {
static final String TABLE_NAME = "issues";
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void add_columns_on_h2() {
assertThat(createSampleBuilder(new H2()).build())
.isEqualTo("ALTER TABLE issues ADD (date_in_ms BIGINT NULL, name VARCHAR (10) NOT NULL)");
}
@Test
public void add_columns_on_mysql() {
assertThat(createSampleBuilder(new MySql()).build())
.isEqualTo("ALTER TABLE issues ADD (date_in_ms BIGINT NULL, name VARCHAR (10) NOT NULL)");
}
@Test
public void add_columns_on_oracle() {
assertThat(createSampleBuilder(new Oracle()).build())
.isEqualTo("ALTER TABLE issues ADD (date_in_ms NUMBER (38) NULL, name VARCHAR (10) NOT NULL)");
}
@Test
public void add_columns_on_postgresql() {
assertThat(createSampleBuilder(new PostgreSql()).build())
.isEqualTo("ALTER TABLE issues ADD COLUMN date_in_ms BIGINT NULL, ADD COLUMN name VARCHAR (10) NOT NULL");
}
@Test
public void add_columns_on_mssql() {
assertThat(createSampleBuilder(new MsSql()).build())
.isEqualTo("ALTER TABLE issues ADD date_in_ms BIGINT NULL, name NVARCHAR (10) COLLATE Latin1_General_CS_AS NOT NULL");
}
@Test
public void fail_with_ISE_if_no_column() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("No column has been defined");
new AddColumnsBuilder(new H2(), TABLE_NAME).build();
}
private AddColumnsBuilder createSampleBuilder(Dialect dialect) {
return new AddColumnsBuilder(dialect, TABLE_NAME)
.addColumn(new BigDecimalColumnDef.Builder().setColumnName("date_in_ms").setIsNullable(true).build())
.addColumn(new VarcharColumnDef.Builder().setColumnName("name").setLimit(10).setIsNullable(false).build());
}
}
| lgpl-3.0 |
alexbodogit/AnchorFX | src/main/java/com/anchorage/docks/containers/SingleDockContainer.java | 4398 | /*
* Copyright 2015-2016 Alessio Vinerbi. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package com.anchorage.docks.containers;
import com.anchorage.docks.containers.common.DockCommons;
import com.anchorage.docks.containers.interfaces.DockContainableComponent;
import com.anchorage.docks.containers.interfaces.DockContainer;
import com.anchorage.docks.containers.subcontainers.DockSplitterContainer;
import com.anchorage.docks.containers.subcontainers.DockTabberContainer;
import com.anchorage.docks.node.DockNode;
import com.anchorage.docks.stations.DockStation;
import javafx.scene.Node;
import javafx.scene.layout.StackPane;
public class SingleDockContainer extends StackPane implements DockContainer {
private DockContainer container;
@Override
public void putDock(DockNode node, DockNode.DockPosition position, double percentage) {
if (getChildren().isEmpty()) {
getChildren().add(node);
node.setParentContainer(this);
} else {
manageSubContainers(node, position, percentage);
}
}
@Override
public void putDock(DockNode node, DockNode nodeTarget, DockNode.DockPosition position, double percentage) {
if (getChildren().get(0) == nodeTarget) {
manageSubContainers(node, position, percentage);
}
}
@Override
public boolean isDockVisible(DockNode node) {
return true;
}
@Override
public int indexOf(Node node) {
return (getChildren().get(0) == node) ? 0 : -1;
}
@Override
public void removeNode(Node node) {
getChildren().remove(node);
((DockContainableComponent) node).setParentContainer(null);
}
@Override
public void insertNode(Node node, int index) {
getChildren().set(index, node);
((DockContainableComponent) node).setParentContainer(this);
}
@Override
public void undock(DockNode node) {
if (getChildren().get(0) == node) {
getChildren().remove(node);
node.setParentContainer(null);
}
}
private void manageSubContainers(DockNode node, DockNode.DockPosition position, double percentage) {
Node existNode = getChildren().get(0);
if (DockCommons.isABorderPosition(position)) {
getChildren().remove(existNode);
DockSplitterContainer splitter = DockCommons.createSplitter(existNode, node, position, percentage);
getChildren().add(splitter);
splitter.setParentContainer(this);
} else if (existNode instanceof DockTabberContainer) {
DockTabberContainer tabber = (DockTabberContainer) existNode;
tabber.putDock(node, DockNode.DockPosition.CENTER, percentage);
} else if (existNode instanceof DockSplitterContainer) {
position = DockNode.DockPosition.BOTTOM;
DockSplitterContainer splitter = (DockSplitterContainer) existNode;
node.dock((DockStation)this, position);
} else {
getChildren().remove(existNode);
DockTabberContainer tabber = DockCommons.createTabber(existNode, node, position);
getChildren().add(tabber);
tabber.setParentContainer(this);
}
}
@Override
public void setParentContainer(DockContainer container) {
this.container = container;
}
@Override
public DockContainer getParentContainer() {
return container;
}
}
| lgpl-3.0 |
ClouDesire/tisana4j | src/main/java/com/cloudesire/tisana4j/exceptions/InternalServerErrorException.java | 316 | package com.cloudesire.tisana4j.exceptions;
public class InternalServerErrorException extends RestException
{
private static final long serialVersionUID = -4816182894418292549L;
public InternalServerErrorException( int responseCode, String msgError )
{
super( responseCode, msgError );
}
}
| lgpl-3.0 |
andygibson/datavalve | datavalve-seam/src/main/java/org/fluttercode/datavalve/provider/seam/SeamParameterResolver.java | 2207 | /*
* Copyright 2010, Andrew M Gibson
*
* www.andygibson.net
*
* This file is part of DataValve.
*
* DataValve 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.
*
* DataValve 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 DataValve. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.fluttercode.datavalve.provider.seam;
import java.io.Serializable;
import org.jboss.seam.core.Expressions;
import org.fluttercode.datavalve.ParameterResolver;
import org.fluttercode.datavalve.params.Parameter;
import org.fluttercode.datavalve.provider.ParameterizedDataProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A DataValve parameter resolver that determines the parameter value by treating
* the parameter as an EL expression. It uses Seams Expression instance to
* evaluate the expression.
*
* @author Andy Gibson
*
*/
public class SeamParameterResolver implements ParameterResolver, Serializable {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory
.getLogger(SeamParameterResolver.class);
public boolean resolveParameter(
ParameterizedDataProvider<? extends Object> dataset,
Parameter parameter) {
// log.debug("Resolving Seam Parameter : {}", parameter);
Object result = Expressions.instance().createValueExpression(
parameter.getName()).getValue();
log.debug("Expression {} evaluated to {}", parameter.getName(), result);
if (result != null) {
// log.debug("Result type is {}", result.getClass().getName());
parameter.setValue(result);
return true;
}
return false;
}
public boolean acceptParameter(String parameter) {
return parameter.startsWith("#{") && parameter.endsWith("}");
}
}
| lgpl-3.0 |
kralisch/jams | JAMSOptas/src/optas/gui/wizard/NumericFocusListener.java | 2829 | package optas.gui.wizard;
import optas.optimizer.management.NumericOptimizerParameter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JTextField;
class NumericFocusListener implements FocusListener {
public static final int MODE_LOWERBOUND = 0;
public static final int MODE_UPPERBOUND = 1;
public static final int MODE_STARTVALUE = 2;
public static final int MODE_PARAMETERVALUE = 3;
NumericFocusListener() {
}
public void focusLost(FocusEvent e) {
JTextField src = (JTextField) e.getSource();
Parameter p = (Parameter) src.getClientProperty("parameter");
Integer mode = (Integer) src.getClientProperty("mode");
try {
//try to convert text
double value = Double.parseDouble(src.getText());
if (mode.intValue() == MODE_PARAMETERVALUE) {
}
switch (mode.intValue()) {
case MODE_LOWERBOUND:
p.setLowerBound(Double.parseDouble(src.getText()));
break;
case MODE_UPPERBOUND:
p.setUpperBound(Double.parseDouble(src.getText()));
break;
case MODE_STARTVALUE:
p.setStartValue(new double[]{Double.parseDouble(src.getText())});
break;
case MODE_PARAMETERVALUE:
NumericOptimizerParameter p2 = (NumericOptimizerParameter) src.getClientProperty("property");
p2.setValue(Double.parseDouble(src.getText()));
NumericOptimizerParameter param = (NumericOptimizerParameter) src.getClientProperty("property");
if (value < param.getLowerBound() || value > param.getUpperBound()) {
throw new NumberFormatException();
}
break;
}
} catch (NumberFormatException nfe) {
switch (mode.intValue()) {
case MODE_LOWERBOUND:
src.setText(Double.toString(p.getLowerBound()));
break;
case MODE_UPPERBOUND:
src.setText(Double.toString(p.getUpperBound()));
break;
case MODE_STARTVALUE:
if (p.getStartValue().length>0) {
src.setText(Double.toString(p.getStartValue()[0]));
} else {
src.setText("");
}
break;
case MODE_PARAMETERVALUE:
src.setText(Double.toString(((NumericOptimizerParameter) src.getClientProperty("property")).getValue()));
break;
}
}
}
public void focusGained(FocusEvent e) {
}
}
| lgpl-3.0 |
teryk/sonarqube | server/sonar-server/src/test/java/org/sonar/server/component/ws/ProjectsWsTest.java | 2607 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.component.ws;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.server.ws.RailsHandler;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.ws.WsTester;
import static org.fest.assertions.Assertions.assertThat;
public class ProjectsWsTest {
WebService.Controller controller;
@Before
public void setUp() throws Exception {
WsTester tester = new WsTester(new ProjectsWs());
controller = tester.controller("api/projects");
}
@Test
public void define_controller() throws Exception {
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
assertThat(controller.since()).isEqualTo("2.10");
assertThat(controller.actions()).hasSize(3);
}
@Test
public void define_index_action() throws Exception {
WebService.Action action = controller.action("index");
assertThat(action).isNotNull();
assertThat(action.handler()).isInstanceOf(RailsHandler.class);
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.params()).hasSize(8);
}
@Test
public void define_create_action() throws Exception {
WebService.Action action = controller.action("create");
assertThat(action).isNotNull();
assertThat(action.handler()).isInstanceOf(RailsHandler.class);
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.params()).hasSize(3);
}
@Test
public void define_destroy_action() throws Exception {
WebService.Action action = controller.action("destroy");
assertThat(action).isNotNull();
assertThat(action.handler()).isInstanceOf(RailsHandler.class);
assertThat(action.params()).hasSize(1);
}
}
| lgpl-3.0 |
bowlofstew/Chronicle-Wire | src/test/java/net/openhft/chronicle/wire/PrimitiveTypeWrappersTest.java | 2825 | package net.openhft.chronicle.wire;
import net.openhft.chronicle.bytes.Bytes;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
/**
* @author Rob Austin.
*/
@RunWith(value = Parameterized.class)
public class PrimitiveTypeWrappersTest {
private boolean isTextWire;
public PrimitiveTypeWrappersTest(Object isTextWire) {
this.isTextWire = (Boolean) isTextWire;
}
@Parameterized.Parameters
public static Collection<Object[]> data() throws IOException {
return Arrays.asList(
new Object[]{Boolean.FALSE}
, new Object[]{Boolean.TRUE}
);
}
@Test
public void testNumbers() throws Exception {
final Class[] types = new Class[]{Byte.class,
Short.class, Float.class,
Integer.class, Long.class, Double.class};
for (Class type : types) {
final Wire wire = wireFactory();
wire.write().object(1);
final Object object = wire.read().object(type);
Assert.assertTrue(type.isAssignableFrom(object.getClass()));
Assert.assertEquals(1, ((Number) object).intValue());
}
}
@Test
public void testCharacter() throws Exception {
final Wire wire = wireFactory();
wire.write().object('1');
final Object object = wire.read().object(Character.class);
Assert.assertTrue(object instanceof Character);
Assert.assertEquals('1', object);
}
@Test
public void testCharacterWritenAsString() throws Exception {
final Wire wire = wireFactory();
wire.write().object("1");
final Object object = wire.read().object(Character.class);
Assert.assertTrue(object instanceof Character);
Assert.assertEquals('1', object);
}
@Test
public void testCharReadAsString() throws Exception {
final Wire wire = wireFactory();
wire.write().object('1');
final Object object = wire.read().object(String.class);
Assert.assertTrue(object instanceof String);
Assert.assertEquals("1", object);
}
@Test
public void testStoreStringReadAsChar() throws Exception {
final Wire wire = wireFactory();
wire.write().object("LONG STRING");
final Object object = wire.read().object(Character.class);
Assert.assertTrue(object instanceof Character);
Assert.assertEquals('L', object);
}
@NotNull
private Wire wireFactory() {
final Bytes bytes = Bytes.allocateElasticDirect();
return (isTextWire) ? new TextWire(bytes) : new BinaryWire(bytes);
}
}
| lgpl-3.0 |
tyotann/tyo-java-frame | src/com/ihidea/component/jcaptcha/ImageServlet.java | 3274 | package com.ihidea.component.jcaptcha;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet {
public static final String JCAPTCHA_NAME = "valiCode";
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置页面不缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 设置默认生成4个验证码
int length = 4;
if (request.getParameter("len") != null) {
length = Integer.valueOf(request.getParameter("len"));
}
String allstring = "abcdefghijklmnopqrstuvwxyz0123456789";
String numstring = "0123456789";
String base;
if (request.getParameter("onlynum") != null) {
if (Boolean.valueOf(request.getParameter("onlynum"))) {
base = numstring;
} else {
base = allstring;
}
} else {
base = allstring;
}
// 设置图片的长宽
int width = 15 * length, height = 22;
// 创建内存图像
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.createGraphics();
// 设定图像背景色(因为是做背景,所以偏淡)
g.setColor(getRandColor(180, 250));
g.fillRect(0, 0, width, height);
// 设置字体
g.setFont(new Font("Tahoma", Font.PLAIN, 17));
java.util.Random rand = new Random(); // 设置随机种子
// 设置备选验证码:包括"a-z"和数字"0-9"
int size = base.length();
StringBuffer str = new StringBuffer();
for (int i = 0; i < length; i++) {
int start = rand.nextInt(size);
String tmpStr = base.substring(start, start + 1);
str.append(tmpStr);
// 生成随机颜色(因为是做前景,所以偏深)
g.setColor(getRandColor(10, 150));
// 将此字画到图片上
g.drawString(tmpStr, 13 * i + 6 + rand.nextInt(5), 14 + rand.nextInt(6));
}
// 将认证码存入session
request.getSession().setAttribute(ImageServlet.JCAPTCHA_NAME, str.toString());
// 图象生效
g.dispose();
// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
// encoder.encode(image);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
@Override
public void destroy() {
}
@Override
public void init() throws ServletException {
}
/**
* 给定范围获得一个随机颜色
* @param fc
* @param bc
* @return
*/
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
| lgpl-3.0 |
SonarSource/sonarqube | server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/EnableAnalysisStepTest.java | 4277 | /*
* 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.step;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolderRule;
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.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.component.SnapshotTesting;
import static org.assertj.core.api.Assertions.assertThat;
public class EnableAnalysisStepTest {
private static final ReportComponent REPORT_PROJECT = ReportComponent.builder(Component.Type.PROJECT, 1).build();
private static final String PREVIOUS_ANALYSIS_UUID = "ANALYSIS_1";
private static final String CURRENT_ANALYSIS_UUID = "ANALYSIS_2";
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
@Rule
public MutableAnalysisMetadataHolderRule analysisMetadataHolder = new MutableAnalysisMetadataHolderRule();
private EnableAnalysisStep underTest = new EnableAnalysisStep(db.getDbClient(), treeRootHolder, analysisMetadataHolder);
@Test
public void switch_islast_flag_and_mark_analysis_as_processed() {
ComponentDto project = ComponentTesting.newPrivateProjectDto(REPORT_PROJECT.getUuid());
db.components().insertComponent(project);
insertAnalysis(project, PREVIOUS_ANALYSIS_UUID, SnapshotDto.STATUS_PROCESSED, true);
insertAnalysis(project, CURRENT_ANALYSIS_UUID, SnapshotDto.STATUS_UNPROCESSED, false);
db.commit();
treeRootHolder.setRoot(REPORT_PROJECT);
analysisMetadataHolder.setUuid(CURRENT_ANALYSIS_UUID);
underTest.execute(new TestComputationStepContext());
verifyAnalysis(PREVIOUS_ANALYSIS_UUID, SnapshotDto.STATUS_PROCESSED, false);
verifyAnalysis(CURRENT_ANALYSIS_UUID, SnapshotDto.STATUS_PROCESSED, true);
}
@Test
public void set_islast_flag_and_mark_as_processed_if_no_previous_analysis() {
ComponentDto project = ComponentTesting.newPrivateProjectDto(REPORT_PROJECT.getUuid());
db.components().insertComponent(project);
insertAnalysis(project, CURRENT_ANALYSIS_UUID, SnapshotDto.STATUS_UNPROCESSED, false);
db.commit();
treeRootHolder.setRoot(REPORT_PROJECT);
analysisMetadataHolder.setUuid(CURRENT_ANALYSIS_UUID);
underTest.execute(new TestComputationStepContext());
verifyAnalysis(CURRENT_ANALYSIS_UUID, SnapshotDto.STATUS_PROCESSED, true);
}
private void verifyAnalysis(String uuid, String expectedStatus, boolean expectedLastFlag) {
Optional<SnapshotDto> analysis = db.getDbClient().snapshotDao().selectByUuid(db.getSession(), uuid);
assertThat(analysis.get().getStatus()).isEqualTo(expectedStatus);
assertThat(analysis.get().getLast()).isEqualTo(expectedLastFlag);
}
private void insertAnalysis(ComponentDto project, String uuid, String status, boolean isLastFlag) {
SnapshotDto snapshot = SnapshotTesting.newAnalysis(project)
.setLast(isLastFlag)
.setStatus(status)
.setUuid(uuid);
db.getDbClient().snapshotDao().insert(db.getSession(), snapshot);
}
}
| lgpl-3.0 |
MrRiegel/Various-Items | src/main/java/mrriegel/various/items/ItemMaterial.java | 1015 | package mrriegel.various.items;
import java.util.List;
import mrriegel.various.CreativeTab;
import mrriegel.various.VariousItems;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class ItemMaterial extends Item {
public static final int NUMBER = 6;
public ItemMaterial() {
super();
this.setCreativeTab(CreativeTab.tab1);
this.setHasSubtypes(true);
this.setUnlocalizedName(VariousItems.MODID + ":material");
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(Item item, CreativeTabs tab, List list) {
for (int i = 0; i < NUMBER; i++) {
list.add(new ItemStack(item, 1, i));
}
}
@Override
public String getUnlocalizedName(ItemStack stack) {
return this.getUnlocalizedName() + "_" + stack.getItemDamage();
}
@Override
public boolean hasEffect(ItemStack stack) {
return stack.getItemDamage() > 1;
}
}
| lgpl-3.0 |
ecologylab/ecologylabFundamental | src/ecologylab/collections/WeightSet.java | 10232 | /*
* Copyright 1996-2002 by Andruid Kerne. All rights reserved. CONFIDENTIAL. Use is subject to
* license terms.
*/
package ecologylab.collections;
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 ecologylab.appframework.Memory;
import ecologylab.generic.ObservableDebug;
import ecologylab.generic.ThreadMaster;
/**
* Provides the facility of efficient weighted random selection from a set elements, each of whicn
* includes a characterizing floating point weight.
* <p>
*
* Works in cooperation w <code>SetElement</code>s; requiring that user object to keep an integer
* index slot, which only we should be accessing. This impure oo style is an adaption to Java's lack
* of multiple inheritance.
* <p>
*
* Gotta be careful to be thread safe. Seems no operations can safely occur concurrently. There are
* a bunch of synchronized methods to affect this.
**/
public class WeightSet<E extends AbstractSetElement> extends ObservableDebug implements Iterable<E>, Collection<E>
{
private static final int NO_MAX_SIZE = -1;
private final ArrayListX<E> arrayList;
private final HashSet<E> hashSet;
private final WeightingStrategy<E> weightingStrategy;
private final Comparator<E> comparator;
private int maxSize = NO_MAX_SIZE;
private static final int DEFAULT_SIZE = 16;
/**
* This might pause us before we do an expensive operation.
*/
ThreadMaster threadMaster;
public WeightSet (int maxSize, int initialSize, WeightingStrategy<E> weightingStrategy)
{
assert weightingStrategy != null;
this.hashSet = new HashSet<E>(initialSize);
this.arrayList = new ArrayListX<E>(initialSize);
this.maxSize = maxSize;
this.weightingStrategy = weightingStrategy;
this.comparator = new FloatWeightComparator(weightingStrategy);
// for (E e : arrayList)
// weightingStrategy.insert(e);
}
public WeightSet ( WeightingStrategy<E> getWeightStrategy )
{
this(NO_MAX_SIZE, DEFAULT_SIZE, getWeightStrategy);
}
public WeightSet (int maxSize, ThreadMaster threadMaster, WeightingStrategy<E> weightStrategy )
{
this(maxSize, maxSize, weightStrategy);
this.threadMaster = threadMaster;
}
// ///////////////////////////////////////////////////////
// DEFAULT COMPARATOR
// ///////////////////////////////////////////////////////
public final class FloatWeightComparator implements Comparator<E>
{
private WeightingStrategy<E> strat;
public FloatWeightComparator ( WeightingStrategy<E> getWeightStrategy )
{
strat = getWeightStrategy;
}
@Override
public int compare ( E o1, E o2 )
{
return Double.compare(strat.getWeight(o1), strat.getWeight(o2));
}
};
private void sortIfWeShould ( )
{
// TODO remove this check, make getWeightStrategy call sort?
if (weightingStrategy.hasChanged())
{
Collections.sort(arrayList, comparator);
setChanged();
notifyObservers();
weightingStrategy.clearChanged();
}
}
public synchronized double mean ( )
{
if (arrayList.size() == 0)
return 0;
double mean = 0;
for (E e : arrayList)
mean += weightingStrategy.getWeight(e);
return mean / arrayList.size();
}
private synchronized void clearAndRecycle (int start, int end)
{
int size = arrayList.size();
debug("^^^size before = " + size);
for (int i=end - 1; i>=start; i--)
{
E element = arrayList.get(i); // was remove(i), but that's inefficent
element.deleteHook();
element.recycle(true);// will also call deleteHook?!
}
// all of these elements are probably at the beginning of the list
// remove from there is worst case behavior of arrayList, because all of the higher elements
// must be moved.
// minimize this by doing it once.
//
// in case of CfContainers, recycle removes them from a set; however a weird case results in
// some of them not being removed, so this makes sure that all recycled elements are removed.
int expectedSize = size - (end - start);
int newSize = arrayList.size();
if (expectedSize < newSize)
{
int sizeDiff = newSize - expectedSize;
arrayList.removeRange(start, sizeDiff);
}
}
/**
* Selects the top weighted element from the set.<br>
* This method removes the selected from the set.
*
* @return
*/
public synchronized E maxSelect ( )
{
ArrayList<E> list = this.arrayList;
int size = list.size();
if (size == 0)
return null;
try
{
sortIfWeShould();
} catch (Throwable t)
{
t.printStackTrace();
boolean foundNulls = false;
for (int i=list.size() - 1; i>=0; i--)
{
E entry = list.get(i);
if (entry == null)
{
error("Oh my! Null Entry!!!!!");
list.remove(i);
foundNulls = true;
}
}
if (foundNulls)
return maxSelect();
}
return list.remove(--size);
}
public synchronized E maxPeek ( )
{
ArrayList<E> list = this.arrayList;
int size = list.size();
if (size == 0)
return null;
sortIfWeShould();
return list.get(--size);
}
public synchronized E maxPeek(int index)
{
ArrayList<E> list = this.arrayList;
int size = list.size();
if (size == 0)
return null;
sortIfWeShould();
int desiredIndex = size - index - 1;
return list.get(desiredIndex);
}
/**
* Default implementation of the prune to keep only maxSize elements
*/
public synchronized void prune()
{
prune(maxSize);
}
public synchronized void prune ( int numToKeep )
{
if (maxSize < 0)
return;
ArrayList<E> list = this.arrayList;
int numToDelete = list.size() - numToKeep;
if (numToDelete <= 0)
return;
debug("prune() -> "+numToKeep);
sortIfWeShould();
// List<E> deletionList = list.subList(0, numToDelete);
clearAndRecycle(0, numToDelete);
Memory.reclaim();
}
@Override
public boolean add(E el)
{
return insert(el);
}
public synchronized boolean insert ( E el )
{
boolean result = false;
if (!hashSet.contains(el))
{
weightingStrategy.insert(el);
result |= arrayList.add(el);
hashSet.add(el);
el.addSet(this);
el.insertHook();
}
return result;
}
public synchronized boolean remove ( E el )
{
boolean result = removeFromSet(el);
el.removeSet(this);
return result;
}
protected synchronized boolean removeFromSet ( E e )
{
weightingStrategy.remove(e);
boolean result = arrayList.remove(e);
hashSet.remove(e);
return result;
}
public E get(int i)
{
return arrayList.get(i);
}
/**
* Delete all the elements in the set, as fast as possible.
*
* @param doRecycleElements
* TODO
*
*/
public synchronized void clear ( boolean doRecycleElements )
{
synchronized (arrayList)
{
for (int i=size()-1; i>0; i--)
{
E e = arrayList.remove(i);
e.deleteHook();
if (doRecycleElements)
e.recycle(false);
}
arrayList.clear();
}
hashSet.clear();
}
/**
* Prune to the set's specified maxSize, if necessary, then do a maxSelect(). The reason for
* doing these operations together is because both require sorting.
*
* @return element in the set with the highest weight, or in case of a tie, a random pick of
* those.
*/
public synchronized E pruneAndMaxSelect ( )
{
prune(maxSize);
return maxSelect();
}
@Override
public int size ( )
{
return arrayList.size();
}
@Override
public String toString ( )
{
return super.toString() + "[" + size() + "]";
}
/**
* Check to see if the set has any elements.
*
* @return
*/
@Override
public boolean isEmpty ( )
{
return size() == 0;
}
/**
* Fetches the i'th element in the sorted list.
*
* @param i
* index into the list
* @return the element at index i
*/
public synchronized E at ( int i )
{
ArrayList<E> list = this.arrayList;
if (list.size() == 0 || i >= list.size())
return null;
sortIfWeShould();
return list.get(i);
}
/**
* Fetches the weight of the i'th element in the sorted list.
*
* @param i
* index into the list
* @return the weight of the element at index i
*/
public synchronized Double weightAt ( int i )
{
ArrayList<E> list = this.arrayList;
if (list.size() == 0)
return null;
sortIfWeShould();
return weightingStrategy.getWeight(list.get(i));
}
/**
* Fetches the highest weight in this set
* @return
*/
public synchronized Double maxWeight()
{
return weightAt(this.arrayList.size() - 1);
}
/**
* Fetches the weight of the passed in element.
*
* @param e
* Element to weigh. Doesn't have to be a member of the set.
* @return the weight of the element
*/
public double getWeight ( E e )
{
return weightingStrategy.getWeight(e);
}
/**
* Method Overriden by {@link cf.model.VisualPool VisualPool} to return true
*
* @return
*/
public boolean isRunnable ( )
{
return false;
}
public WeightingStrategy<E> getWeightStrategy ( )
{
return weightingStrategy;
}
@Override
public synchronized Iterator<E> iterator ( )
{
return arrayList.iterator();
}
@Override
public boolean addAll(Collection<? extends E> arg0)
{
boolean result = false;
for (E element: arg0)
result |= add(element);
return result;
}
@Override
public void clear()
{
clear(false);
}
@Override
public boolean contains(Object arg0)
{
// TODO Auto-generated method stub
return hashSet.contains(arg0);
}
@Override
public boolean containsAll(Collection<?> arg0)
{
throw new RuntimeException("not implemented.");
}
@Override
public boolean remove(Object arg0)
{
return remove((E) arg0);
}
@Override
public boolean removeAll(Collection<?> arg0)
{
boolean result = false;
for (Object o : arg0)
result |= remove(o);
return result;
}
@Override
public boolean retainAll(Collection<?> arg0)
{
throw new RuntimeException("not implemented.");
}
@Override
public Object[] toArray()
{
return arrayList.toArray();
}
@Override
public <T> T[] toArray(T[] arg0)
{
return arrayList.toArray(arg0);
}
public void toArray(E[] arg0, int start)
{
int pos = start;
for (int i = 0; i < size(); i++)
arg0[pos++] = arrayList.get(i);
}
}
| lgpl-3.0 |
thucoldwind/ucore_mips | Decaf/src/decaf/error/BadArgCountError.java | 611 | package decaf.error;
import decaf.Location;
/**
* example:function 'gotoMars' expects 1 argument(s) but 3 given<br>
* PA2
*/
public class BadArgCountError extends DecafError {
private String method;
private int expect;
private int count;
public BadArgCountError(Location location, String method, int expect,
int count) {
super(location);
this.method = method;
this.expect = expect;
this.count = count;
}
@Override
protected String getErrMsg() {
return "function '" + method + "' expects " + expect
+ " argument(s) but " + count + " given";
}
}
| unlicense |
haks1999/hakstrace | src/test/java/sample/data/jpa/SampleDataJpaApplicationTests.java | 1567 | package sample.data.jpa;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Integration test to run the application.
*
* @author Oliver Gierke
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class)
@WebAppConfiguration
@ActiveProfiles("scratch")
// Separate profile for web tests to avoid clashing databases
public class SampleDataJpaApplicationTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setUp() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
@Test
public void testHome() throws Exception {
this.mvc.perform(get("/")).andExpect(status().isOk())
.andExpect(content().string("Bath"));
}
}
| unlicense |
Phylogeny/ExtraBitManipulation | src/main/java/com/phylogeny/extrabitmanipulation/armor/DataChiseledArmorPiece.java | 6319 | package com.phylogeny.extrabitmanipulation.armor;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants.NBT;
import org.lwjgl.opengl.GL11;
import com.phylogeny.extrabitmanipulation.helper.ItemStackHelper;
import com.phylogeny.extrabitmanipulation.item.ItemChiseledArmor.ArmorType;
import com.phylogeny.extrabitmanipulation.reference.NBTKeys;
public class DataChiseledArmorPiece
{
private List<GlOperation> globalGlOperationsPre = new ArrayList<GlOperation>();
private List<GlOperation> globalGlOperationsPost = new ArrayList<GlOperation>();
private List<ArmorItem>[] partItemLists;
private ArmorType armorType;
public DataChiseledArmorPiece(ArmorType armorType)
{
this.armorType = armorType;
partItemLists = new ArrayList[armorType.getMovingpartCount()];
for (int i = 0; i < partItemLists.length; i++)
partItemLists[i] = new ArrayList<ArmorItem>();
}
public DataChiseledArmorPiece(NBTTagCompound nbt, ArmorType armorType)
{
this(armorType);
loadFromNBT(nbt);
}
private List<GlOperation> getGlobalGlOperationsInternal(boolean isPre)
{
return isPre ? globalGlOperationsPre : globalGlOperationsPost;
}
public List<GlOperation> getGlobalGlOperations(boolean isPre)
{
List<GlOperation> glOperations = new ArrayList<GlOperation>();
glOperations.addAll(getGlobalGlOperationsInternal(isPre));
return glOperations;
}
public void addGlobalGlOperation(GlOperation glOperation, boolean isPre)
{
getGlobalGlOperationsInternal(isPre).add(glOperation);
}
public void addGlobalGlOperation(int index, GlOperation glOperation, boolean isPre)
{
getGlobalGlOperationsInternal(isPre).add(index, glOperation);
}
public void removeGlobalGlOperation(int index, boolean isPre)
{
getGlobalGlOperationsInternal(isPre).remove(index);
}
public void addItemToPart(int partIndex, ArmorItem armorItem)
{
if (outOfPartRange(partIndex))
return;
partItemLists[partIndex].add(armorItem);
}
public void addItemToPart(int partIndex, int armorItemIndex, ArmorItem armorItem)
{
if (outOfPartRange(partIndex))
return;
partItemLists[partIndex].add(armorItemIndex, armorItem);
}
public void removeItemFromPart(int partIndex, int armorItemIndex)
{
if (outOfPartRange(partIndex))
return;
partItemLists[partIndex].remove(armorItemIndex);
}
public List<ArmorItem> getArmorItemsForPart(int partIndex)
{
List<ArmorItem> armorItems = new ArrayList<ArmorItem>();
if (outOfPartRange(partIndex))
return armorItems;
armorItems.addAll(partItemLists[partIndex]);
return armorItems;
}
public ArmorItem getArmorItemForPart(int partIndex, int armorItemIndex)
{
return outOfPartRange(partIndex) ? new ArmorItem() : partItemLists[partIndex].get(armorItemIndex);
}
public int generateDisplayList(int partIndex, EntityLivingBase entity, float scale)
{
GlStateManager.pushMatrix();
int displayList = GLAllocation.generateDisplayLists(1);
GlStateManager.glNewList(displayList, GL11.GL_COMPILE);
GlOperation.executeList(globalGlOperationsPre);
for (ArmorItem armorItem : partItemLists[partIndex])
{
if (armorItem.isEmpty())
continue;
GlStateManager.pushMatrix();
armorItem.executeGlOperations();
GlOperation.executeList(globalGlOperationsPost);
armorItem.render(entity, scale, (armorType == ArmorType.BOOTS && partIndex == 0) || (armorType == ArmorType.LEGGINGS && partIndex == 1));
GlStateManager.popMatrix();
}
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.glEndList();
GlStateManager.popMatrix();
return displayList;
}
private boolean outOfPartRange(int partIndex)
{
return partIndex < 0 || partIndex >= partItemLists.length;
}
public void saveToNBT(NBTTagCompound nbt)
{
NBTTagCompound data = new NBTTagCompound();
data.setInteger(NBTKeys.ARMOR_TYPE, armorType.ordinal());
NBTTagList movingParts = new NBTTagList();
boolean empty = true;
for (List<ArmorItem> partItemList : partItemLists)
{
NBTTagList itemList = new NBTTagList();
for (ArmorItem armorItem : partItemList)
{
NBTTagCompound armorItemNbt = new NBTTagCompound();
armorItem.saveToNBT(armorItemNbt);
itemList.appendTag(armorItemNbt);
if (!armorItem.getStack().isEmpty())
empty = false;
}
movingParts.appendTag(itemList);
}
data.setTag(NBTKeys.ARMOR_PART_DATA, movingParts);
data.setBoolean(NBTKeys.ARMOR_NOT_EMPTY, !empty);
GlOperation.saveListToNBT(data, NBTKeys.ARMOR_GL_OPERATIONS_PRE, globalGlOperationsPre);
GlOperation.saveListToNBT(data, NBTKeys.ARMOR_GL_OPERATIONS_POST, globalGlOperationsPost);
nbt.setTag(NBTKeys.ARMOR_DATA, data);
}
public void loadFromNBT(NBTTagCompound nbt)
{
NBTTagCompound data = ItemStackHelper.getArmorData(nbt);
NBTTagList movingParts = data.getTagList(NBTKeys.ARMOR_PART_DATA, NBT.TAG_LIST);
for (int i = 0; i < movingParts.tagCount(); i++)
{
NBTBase nbtBase = movingParts.get(i);
if (nbtBase.getId() != NBT.TAG_LIST)
continue;
partItemLists[i].clear();
NBTTagList itemList = (NBTTagList) nbtBase;
for (int j = 0; j < itemList.tagCount(); j++)
partItemLists[i].add(new ArmorItem(itemList.getCompoundTagAt(j)));
}
GlOperation.loadListFromNBT(data, NBTKeys.ARMOR_GL_OPERATIONS_PRE, globalGlOperationsPre);
GlOperation.loadListFromNBT(data, NBTKeys.ARMOR_GL_OPERATIONS_POST, globalGlOperationsPost);
}
public static void setPartData(NBTTagCompound data, NBTTagList movingParts)
{
data.setTag(NBTKeys.ARMOR_PART_DATA, movingParts);
boolean empty = true;
for (int i = 0; i < movingParts.tagCount(); i++)
{
NBTBase nbtBase = movingParts.get(i);
if (nbtBase.getId() != NBT.TAG_LIST)
continue;
NBTTagList itemList = (NBTTagList) nbtBase;
for (int j = 0; j < itemList.tagCount(); j++)
{
if (!ItemStackHelper.loadStackFromNBT(itemList.getCompoundTagAt(j), NBTKeys.ARMOR_ITEM).isEmpty())
{
empty = false;
break;
}
}
if (!empty) break;
}
data.setBoolean(NBTKeys.ARMOR_NOT_EMPTY, !empty);
}
} | unlicense |
raywang999/TIJ4 | Chapter9/src/Exercise20.java | 301 | /*
Exercise 20: (1) Create an interface containing a nested class. Implement this interface and create an instance of the nested class.
*/
public class Exercise20 implements In{
public static void main(String[] args){
In.Nested i = new In.Nested();
}
}
interface In{class Nested{}}
| unlicense |
xxing1982/EDU_SYZT | SunReadSource/src/main/java/com/syzton/sunread/model/book/Category.java | 1557 | package com.syzton.sunread.model.book;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OrderColumn;
import javax.persistence.Table;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.syzton.sunread.model.common.AbstractEntity;
/**
* @author Jerry zhang
*/
@Entity
@Table(name="category")
public class Category extends AbstractEntity{
public static final int MAX_LENGTH_NAME = 20;
private int value;
@Column(name="name",nullable = false,length = MAX_LENGTH_NAME)
private String name;
@OneToMany(cascade = {CascadeType.PERSIST,CascadeType.REFRESH,CascadeType.MERGE},fetch = FetchType.EAGER)
@JoinColumn(name = "parent_id")
@OrderColumn
private Set<Category> children = new HashSet<>() ;
public Category() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Category> getChildren() {
return children;
}
public void setChildren(Set<Category> children) {
this.children = children;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
| unlicense |
Ckorvus/FuBerlin.SWP.1415 | SWP/src/geometryImpl/PolygonImpl.java | 3754 | /**
*
*/
package geometryImpl;
import java.util.Map;
import geometry.APRectangle;
import geometry.ConvexPolygon;
import geometry.IllegalPolygonException;
import geometry.Polygon;
import geometry.Vertex;
/**
* @author Corvus
*
*/
class PolygonImpl implements Polygon {
Vertex[] vertices;
Map<Integer, double[]> adjacencies;
public PolygonImpl(Vertex[] vertices) throws IllegalPolygonException{
if(vertices.length < 3) {
throw new IllegalPolygonException();
} else {
this.vertices = vertices;
adjacencies = null;
}
}
/* (non-Javadoc)
* @see geometry.Polygon#rotate(double, geometry.Vertex)
*/
@Override
public void rotate(double angle, Vertex center) {
TwoDvector centre = new TwoDvector(center);
TwoDvector position = new TwoDvector(vertices[0]);
TwoDvector first_translation = centre.sub(position);
TwoDvector second_translation = first_translation.rotate(180);
second_translation = second_translation.rotate(angle);
TwoDvector merged_translation = first_translation.add(second_translation);
translate(merged_translation.x, merged_translation.y);
}
/* (non-Javadoc)
* @see geometry.Polygon#translate(double, double)
*/
@Override
public void translate(double x, double y) {
TwoDvector translation = new TwoDvector(x, y);
int size = vertices.length;
for(; size > 0; size--) {
vertices[size] = new TwoDvector(vertices[size]).add(translation).toVertex();
}
}
/* (non-Javadoc)
* @see geometry.Polygon#isConvex()
*/
@Override
public boolean isConvex() {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see geometry.Polygon#getConvexHull()
*/
@Override
public ConvexPolygon getConvexHull() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see geometry.Polygon#getConvexHull(geometry.Polygon[])
*/
@Override
public ConvexPolygon getConvexHull(Polygon[] polygons) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see geometry.Polygon#getAPBoundingBox()
*/
@Override
public APRectangle getAPBoundingBox() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see geometry.Polygon#getAPBoundingBox(geometry.Polygon[])
*/
@Override
public APRectangle getAPBoundingBox(Polygon[] polygons) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see geometry.Polygon#overlaps(geometry.Polygon)
*/
@Override
public boolean overlaps(Polygon polygon) {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see geometry.Polygon#getVertices()
*/
@Override
public Vertex[] getVertices() {
return vertices;
}
/* (non-Javadoc)
* @see geometry.Polygon#toConvexPolygon()
*/
@Override
public ConvexPolygon toConvexPolygon() throws IllegalPolygonException {
// TODO Auto-generated method stub
return null;
}
private double getArea(){
int n = vertices.length;
double sum = 0;
for(int i = 0; i < n; i++) {
sum =+ (vertices[i].x*vertices[(i+1)%n].y-vertices[(i+1)%n].x*vertices[i].y);
}
return 0.5*sum;
}
private Vertex getCentroid() {
double A = getArea();
int n = vertices.length;
double sum = 0;
for(int i = 0; i < n; i++) {
sum =+ (vertices[i].x+vertices[(i+1)%n].x)*(vertices[i].x*vertices[(i+1)%n].y-vertices[(i+1)%n].x*vertices[i].y);
}
double x = (1/(6*A))*sum;
for(int i = 0; i < n; i++) {
sum =+ (vertices[i].y+vertices[(i+1)%n].y)*(vertices[i].x*vertices[(i+1)%n].y-vertices[(i+1)%n].x*vertices[i].y);
}
double y = (1/(6*A))*sum;
return new Vertex(x, y);
}
}
| unlicense |
RedTriplane/RedTriplane | r3-box2d-jf/src/org/jbox2d/f/dynamics/Body.java | 33319 | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.f.dynamics;
import org.jbox2d.f.collision.broadphase.BroadPhase;
import org.jbox2d.f.collision.shapes.MassData;
import org.jbox2d.f.collision.shapes.Shape;
import org.jbox2d.f.common.MathUtils;
import org.jbox2d.f.common.Rot;
import org.jbox2d.f.common.Sweep;
import org.jbox2d.f.common.Transform;
import org.jbox2d.f.common.Vector2;
import org.jbox2d.f.dynamics.contacts.Contact;
import org.jbox2d.f.dynamics.contacts.ContactEdge;
import org.jbox2d.f.dynamics.joints.JointEdge;
/**
* A rigid body. These are created via World.createBody.
*
* @author Daniel Murphy
*/
public class Body {
public static final int e_islandFlag = 0x0001;
public static final int e_awakeFlag = 0x0002;
public static final int e_autoSleepFlag = 0x0004;
public static final int e_bulletFlag = 0x0008;
public static final int e_fixedRotationFlag = 0x0010;
public static final int e_activeFlag = 0x0020;
public static final int e_toiFlag = 0x0040;
public BodyType m_type;
public int m_flags;
public int m_islandIndex;
/**
* The body origin transform.
*/
public final Transform m_xf = new Transform();
/**
* The previous transform for particle simulation
*/
public final Transform m_xf0 = new Transform();
/**
* The swept motion for CCD
*/
public final Sweep m_sweep = new Sweep();
public final Vector2 m_linearVelocity = new Vector2();
public float m_angularVelocity = 0;
public final Vector2 m_force = new Vector2();
public float m_torque = 0;
public World m_world;
public Body m_prev;
public Body m_next;
public Fixture m_fixtureList;
public int m_fixtureCount;
public JointEdge m_jointList;
public ContactEdge m_contactList;
public float m_mass, m_invMass;
// Rotational inertia about the center of mass.
public float m_I, m_invI;
public float m_linearDamping;
public float m_angularDamping;
public float m_gravityScale;
public float m_sleepTime;
public Object m_userData;
public Body(final BodyDef bd, World world) {
assert (bd.position.isValid());
assert (bd.linearVelocity.isValid());
assert (bd.gravityScale >= 0.0f);
assert (bd.angularDamping >= 0.0f);
assert (bd.linearDamping >= 0.0f);
m_flags = 0;
if (bd.bullet) {
m_flags |= e_bulletFlag;
}
if (bd.fixedRotation) {
m_flags |= e_fixedRotationFlag;
}
if (bd.allowSleep) {
m_flags |= e_autoSleepFlag;
}
if (bd.awake) {
m_flags |= e_awakeFlag;
}
if (bd.active) {
m_flags |= e_activeFlag;
}
m_world = world;
m_xf.p.set(bd.position);
m_xf.q.set(bd.angle);
m_sweep.localCenter.setZero();
m_sweep.c0.set(m_xf.p);
m_sweep.c.set(m_xf.p);
m_sweep.a0 = bd.angle;
m_sweep.a = bd.angle;
m_sweep.alpha0 = 0.0f;
m_jointList = null;
m_contactList = null;
m_prev = null;
m_next = null;
m_linearVelocity.set(bd.linearVelocity);
m_angularVelocity = bd.angularVelocity;
m_linearDamping = bd.linearDamping;
m_angularDamping = bd.angularDamping;
m_gravityScale = bd.gravityScale;
m_force.setZero();
m_torque = 0.0f;
m_sleepTime = 0.0f;
m_type = bd.type;
if (m_type == BodyType.DYNAMIC) {
m_mass = 1f;
m_invMass = 1f;
} else {
m_mass = 0f;
m_invMass = 0f;
}
m_I = 0.0f;
m_invI = 0.0f;
m_userData = bd.userData;
m_fixtureList = null;
m_fixtureCount = 0;
}
/**
* Creates a fixture and attach it to this body. Use this function if you need to set some fixture
* parameters, like friction. Otherwise you can create the fixture directly from a shape. If the
* density is non-zero, this function automatically updates the mass of the body. Contacts are not
* created until the next time step.
*
* @param def the fixture definition.
* @warning This function is locked during callbacks.
*/
public final Fixture createFixture(FixtureDef def) {
assert (m_world.isLocked() == false);
if (m_world.isLocked() == true) {
return null;
}
Fixture fixture = new Fixture();
fixture.create(this, def);
if ((m_flags & e_activeFlag) == e_activeFlag) {
BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase;
fixture.createProxies(broadPhase, m_xf);
}
fixture.m_next = m_fixtureList;
m_fixtureList = fixture;
++m_fixtureCount;
fixture.m_body = this;
// Adjust mass properties if needed.
if (fixture.m_density > 0.0f) {
resetMassData();
}
// Let the world know we have a new fixture. This will cause new contacts
// to be created at the beginning of the next time step.
m_world.m_flags |= World.NEW_FIXTURE;
return fixture;
}
private final FixtureDef fixDef = new FixtureDef();
/**
* Creates a fixture from a shape and attach it to this body. This is a convenience function. Use
* FixtureDef if you need to set parameters like friction, restitution, user data, or filtering.
* If the density is non-zero, this function automatically updates the mass of the body.
*
* @param shape the shape to be cloned.
* @param density the shape density (set to zero for static bodies).
* @warning This function is locked during callbacks.
*/
public final Fixture createFixture(Shape shape, float density) {
fixDef.shape = shape;
fixDef.density = density;
return createFixture(fixDef);
}
/**
* Destroy a fixture. This removes the fixture from the broad-phase and destroys all contacts
* associated with this fixture. This will automatically adjust the mass of the body if the body
* is dynamic and the fixture has positive density. All fixtures attached to a body are implicitly
* destroyed when the body is destroyed.
*
* @param fixture the fixture to be removed.
* @warning This function is locked during callbacks.
*/
public final void destroyFixture(Fixture fixture) {
assert (m_world.isLocked() == false);
if (m_world.isLocked() == true) {
return;
}
assert (fixture.m_body == this);
// Remove the fixture from this body's singly linked list.
assert (m_fixtureCount > 0);
Fixture node = m_fixtureList;
Fixture last = null; // java change
boolean found = false;
while (node != null) {
if (node == fixture) {
node = fixture.m_next;
found = true;
break;
}
last = node;
node = node.m_next;
}
// You tried to remove a shape that is not attached to this body.
assert (found);
// java change, remove it from the list
if (last == null) {
m_fixtureList = fixture.m_next;
} else {
last.m_next = fixture.m_next;
}
// Destroy any contacts associated with the fixture.
ContactEdge edge = m_contactList;
while (edge != null) {
Contact c = edge.contact;
edge = edge.next;
Fixture fixtureA = c.getFixtureA();
Fixture fixtureB = c.getFixtureB();
if (fixture == fixtureA || fixture == fixtureB) {
// This destroys the contact and removes it from
// this body's contact list.
m_world.m_contactManager.destroy(c);
}
}
if ((m_flags & e_activeFlag) == e_activeFlag) {
BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase;
fixture.destroyProxies(broadPhase);
}
fixture.destroy();
fixture.m_body = null;
fixture.m_next = null;
fixture = null;
--m_fixtureCount;
// Reset the mass data.
resetMassData();
}
/**
* Set the position of the body's origin and rotation. This breaks any contacts and wakes the
* other bodies. Manipulating a body's transform may cause non-physical behavior. Note: contacts
* are updated on the next call to World.step().
*
* @param position the world position of the body's local origin.
* @param angle the world rotation in radians.
*/
public final void setTransform(Vector2 position, float angle) {
assert (m_world.isLocked() == false);
if (m_world.isLocked() == true) {
return;
}
m_xf.q.set(angle);
m_xf.p.set(position);
// m_sweep.c0 = m_sweep.c = Mul(m_xf, m_sweep.localCenter);
Transform.mulToOutUnsafe(m_xf, m_sweep.localCenter, m_sweep.c);
m_sweep.a = angle;
m_sweep.c0.set(m_sweep.c);
m_sweep.a0 = m_sweep.a;
BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase;
for (Fixture f = m_fixtureList; f != null; f = f.m_next) {
f.synchronize(broadPhase, m_xf, m_xf);
}
}
/**
* Get the body transform for the body's origin.
*
* @return the world transform of the body's origin.
*/
public final Transform getTransform() {
return m_xf;
}
/**
* Get the world body origin position. Do not modify.
*
* @return the world position of the body's origin.
*/
public final Vector2 getPosition() {
return m_xf.p;
}
/**
* Get the angle in radians.
*
* @return the current world rotation angle in radians.
*/
public final float getAngle() {
return m_sweep.a;
}
/**
* Get the world position of the center of mass. Do not modify.
*/
public final Vector2 getWorldCenter() {
return m_sweep.c;
}
/**
* Get the local position of the center of mass. Do not modify.
*/
public final Vector2 getLocalCenter() {
return m_sweep.localCenter;
}
/**
* Set the linear velocity of the center of mass.
*
* @param v the new linear velocity of the center of mass.
*/
public final void setLinearVelocity(Vector2 v) {
if (m_type == BodyType.STATIC) {
return;
}
if (Vector2.dot(v, v) > 0.0f) {
setAwake(true);
}
m_linearVelocity.set(v);
}
/**
* Get the linear velocity of the center of mass. Do not modify, instead use
* {@link #setLinearVelocity(Vector2)}.
*
* @return the linear velocity of the center of mass.
*/
public final Vector2 getLinearVelocity() {
return m_linearVelocity;
}
/**
* Set the angular velocity.
*
* @param omega the new angular velocity in radians/second.
*/
public final void setAngularVelocity(float w) {
if (m_type == BodyType.STATIC) {
return;
}
if (w * w > 0f) {
setAwake(true);
}
m_angularVelocity = w;
}
/**
* Get the angular velocity.
*
* @return the angular velocity in radians/second.
*/
public final float getAngularVelocity() {
return m_angularVelocity;
}
/**
* Get the gravity scale of the body.
*
* @return
*/
public float getGravityScale() {
return m_gravityScale;
}
/**
* Set the gravity scale of the body.
*
* @param gravityScale
*/
public void setGravityScale(float gravityScale) {
this.m_gravityScale = gravityScale;
}
/**
* Apply a force at a world point. If the force is not applied at the center of mass, it will
* generate a torque and affect the angular velocity. This wakes up the body.
*
* @param force the world force vector, usually in Newtons (N).
* @param point the world position of the point of application.
*/
public final void applyForce(Vector2 force, Vector2 point) {
if (m_type != BodyType.DYNAMIC) {
return;
}
if (isAwake() == false) {
setAwake(true);
}
// m_force.addLocal(force);
// Vec2 temp = tltemp.get();
// temp.set(point).subLocal(m_sweep.c);
// m_torque += Vec2.cross(temp, force);
m_force.x += force.x;
m_force.y += force.y;
m_torque += (point.x - m_sweep.c.x) * force.y - (point.y - m_sweep.c.y) * force.x;
}
/**
* Apply a force to the center of mass. This wakes up the body.
*
* @param force the world force vector, usually in Newtons (N).
*/
public final void applyForceToCenter(Vector2 force) {
if (m_type != BodyType.DYNAMIC) {
return;
}
if (isAwake() == false) {
setAwake(true);
}
m_force.x += force.x;
m_force.y += force.y;
}
/**
* Apply a torque. This affects the angular velocity without affecting the linear velocity of the
* center of mass. This wakes up the body.
*
* @param torque about the z-axis (out of the screen), usually in N-m.
*/
public final void applyTorque(float torque) {
if (m_type != BodyType.DYNAMIC) {
return;
}
if (isAwake() == false) {
setAwake(true);
}
m_torque += torque;
}
/**
* Apply an impulse at a point. This immediately modifies the velocity. It also modifies the
* angular velocity if the point of application is not at the center of mass. This wakes up the
* body if 'wake' is set to true. If the body is sleeping and 'wake' is false, then there is no
* effect.
*
* @param impulse the world impulse vector, usually in N-seconds or kg-m/s.
* @param point the world position of the point of application.
* @param wake also wake up the body
*/
public final void applyLinearImpulse(Vector2 impulse, Vector2 point, boolean wake) {
if (m_type != BodyType.DYNAMIC) {
return;
}
if (!isAwake()) {
if (wake) {
setAwake(true);
} else {
return;
}
}
m_linearVelocity.x += impulse.x * m_invMass;
m_linearVelocity.y += impulse.y * m_invMass;
m_angularVelocity +=
m_invI * ((point.x - m_sweep.c.x) * impulse.y - (point.y - m_sweep.c.y) * impulse.x);
}
/**
* Apply an angular impulse.
*
* @param impulse the angular impulse in units of kg*m*m/s
*/
public void applyAngularImpulse(float impulse) {
if (m_type != BodyType.DYNAMIC) {
return;
}
if (isAwake() == false) {
setAwake(true);
}
m_angularVelocity += m_invI * impulse;
}
/**
* Get the total mass of the body.
*
* @return the mass, usually in kilograms (kg).
*/
public final float getMass() {
return m_mass;
}
/**
* Get the central rotational inertia of the body.
*
* @return the rotational inertia, usually in kg-m^2.
*/
public final float getInertia() {
return m_I
+ m_mass
* (m_sweep.localCenter.x * m_sweep.localCenter.x + m_sweep.localCenter.y
* m_sweep.localCenter.y);
}
/**
* Get the mass data of the body. The rotational inertia is relative to the center of mass.
*
* @return a struct containing the mass, inertia and center of the body.
*/
public final void getMassData(MassData data) {
// data.mass = m_mass;
// data.I = m_I + m_mass * Vec2.dot(m_sweep.localCenter, m_sweep.localCenter);
// data.center.set(m_sweep.localCenter);
data.mass = m_mass;
data.I =
m_I
+ m_mass
* (m_sweep.localCenter.x * m_sweep.localCenter.x + m_sweep.localCenter.y
* m_sweep.localCenter.y);
data.center.x = m_sweep.localCenter.x;
data.center.y = m_sweep.localCenter.y;
}
/**
* Set the mass properties to override the mass properties of the fixtures. Note that this changes
* the center of mass position. Note that creating or destroying fixtures can also alter the mass.
* This function has no effect if the body isn't dynamic.
*
* @param massData the mass properties.
*/
public final void setMassData(MassData massData) {
// TODO_ERIN adjust linear velocity and torque to account for movement of center.
assert (m_world.isLocked() == false);
if (m_world.isLocked() == true) {
return;
}
if (m_type != BodyType.DYNAMIC) {
return;
}
m_invMass = 0.0f;
m_I = 0.0f;
m_invI = 0.0f;
m_mass = massData.mass;
if (m_mass <= 0.0f) {
m_mass = 1f;
}
m_invMass = 1.0f / m_mass;
if (massData.I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) {
m_I = massData.I - m_mass * Vector2.dot(massData.center, massData.center);
assert (m_I > 0.0f);
m_invI = 1.0f / m_I;
}
final Vector2 oldCenter = m_world.getPool().popVec2();
// Move center of mass.
oldCenter.set(m_sweep.c);
m_sweep.localCenter.set(massData.center);
// m_sweep.c0 = m_sweep.c = Mul(m_xf, m_sweep.localCenter);
Transform.mulToOutUnsafe(m_xf, m_sweep.localCenter, m_sweep.c0);
m_sweep.c.set(m_sweep.c0);
// Update center of mass velocity.
// m_linearVelocity += Cross(m_angularVelocity, m_sweep.c - oldCenter);
final Vector2 temp = m_world.getPool().popVec2();
temp.set(m_sweep.c).subLocal(oldCenter);
Vector2.crossToOut(m_angularVelocity, temp, temp);
m_linearVelocity.addLocal(temp);
m_world.getPool().pushVec2(2);
}
private final MassData pmd = new MassData();
/**
* This resets the mass properties to the sum of the mass properties of the fixtures. This
* normally does not need to be called unless you called setMassData to override the mass and you
* later want to reset the mass.
*/
public final void resetMassData() {
// Compute mass data from shapes. Each shape has its own density.
m_mass = 0.0f;
m_invMass = 0.0f;
m_I = 0.0f;
m_invI = 0.0f;
m_sweep.localCenter.setZero();
// Static and kinematic bodies have zero mass.
if (m_type == BodyType.STATIC || m_type == BodyType.KINEMATIC) {
// m_sweep.c0 = m_sweep.c = m_xf.position;
m_sweep.c0.set(m_xf.p);
m_sweep.c.set(m_xf.p);
m_sweep.a0 = m_sweep.a;
return;
}
assert (m_type == BodyType.DYNAMIC);
// Accumulate mass over all fixtures.
final Vector2 localCenter = m_world.getPool().popVec2();
localCenter.setZero();
final Vector2 temp = m_world.getPool().popVec2();
final MassData massData = pmd;
for (Fixture f = m_fixtureList; f != null; f = f.m_next) {
if (f.m_density == 0.0f) {
continue;
}
f.getMassData(massData);
m_mass += massData.mass;
// center += massData.mass * massData.center;
temp.set(massData.center).mulLocal(massData.mass);
localCenter.addLocal(temp);
m_I += massData.I;
}
// Compute center of mass.
if (m_mass > 0.0f) {
m_invMass = 1.0f / m_mass;
localCenter.mulLocal(m_invMass);
} else {
// Force all dynamic bodies to have a positive mass.
m_mass = 1.0f;
m_invMass = 1.0f;
}
if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) {
// Center the inertia about the center of mass.
m_I -= m_mass * Vector2.dot(localCenter, localCenter);
assert (m_I > 0.0f);
m_invI = 1.0f / m_I;
} else {
m_I = 0.0f;
m_invI = 0.0f;
}
Vector2 oldCenter = m_world.getPool().popVec2();
// Move center of mass.
oldCenter.set(m_sweep.c);
m_sweep.localCenter.set(localCenter);
// m_sweep.c0 = m_sweep.c = Mul(m_xf, m_sweep.localCenter);
Transform.mulToOutUnsafe(m_xf, m_sweep.localCenter, m_sweep.c0);
m_sweep.c.set(m_sweep.c0);
// Update center of mass velocity.
// m_linearVelocity += Cross(m_angularVelocity, m_sweep.c - oldCenter);
temp.set(m_sweep.c).subLocal(oldCenter);
final Vector2 temp2 = oldCenter;
Vector2.crossToOutUnsafe(m_angularVelocity, temp, temp2);
m_linearVelocity.addLocal(temp2);
m_world.getPool().pushVec2(3);
}
/**
* Get the world coordinates of a point given the local coordinates.
*
* @param localPoint a point on the body measured relative the the body's origin.
* @return the same point expressed in world coordinates.
*/
public final Vector2 getWorldPoint(Vector2 localPoint) {
Vector2 v = new Vector2();
getWorldPointToOut(localPoint, v);
return v;
}
public final void getWorldPointToOut(Vector2 localPoint, Vector2 out) {
Transform.mulToOut(m_xf, localPoint, out);
}
/**
* Get the world coordinates of a vector given the local coordinates.
*
* @param localVector a vector fixed in the body.
* @return the same vector expressed in world coordinates.
*/
public final Vector2 getWorldVector(Vector2 localVector) {
Vector2 out = new Vector2();
getWorldVectorToOut(localVector, out);
return out;
}
public final void getWorldVectorToOut(Vector2 localVector, Vector2 out) {
Rot.mulToOut(m_xf.q, localVector, out);
}
public final void getWorldVectorToOutUnsafe(Vector2 localVector, Vector2 out) {
Rot.mulToOutUnsafe(m_xf.q, localVector, out);
}
/**
* Gets a local point relative to the body's origin given a world point.
*
* @param a point in world coordinates.
* @return the corresponding local point relative to the body's origin.
*/
public final Vector2 getLocalPoint(Vector2 worldPoint) {
Vector2 out = new Vector2();
getLocalPointToOut(worldPoint, out);
return out;
}
public final void getLocalPointToOut(Vector2 worldPoint, Vector2 out) {
Transform.mulTransToOut(m_xf, worldPoint, out);
}
/**
* Gets a local vector given a world vector.
*
* @param a vector in world coordinates.
* @return the corresponding local vector.
*/
public final Vector2 getLocalVector(Vector2 worldVector) {
Vector2 out = new Vector2();
getLocalVectorToOut(worldVector, out);
return out;
}
public final void getLocalVectorToOut(Vector2 worldVector, Vector2 out) {
Rot.mulTrans(m_xf.q, worldVector, out);
}
public final void getLocalVectorToOutUnsafe(Vector2 worldVector, Vector2 out) {
Rot.mulTransUnsafe(m_xf.q, worldVector, out);
}
/**
* Get the world linear velocity of a world point attached to this body.
*
* @param a point in world coordinates.
* @return the world velocity of a point.
*/
public final Vector2 getLinearVelocityFromWorldPoint(Vector2 worldPoint) {
Vector2 out = new Vector2();
getLinearVelocityFromWorldPointToOut(worldPoint, out);
return out;
}
public final void getLinearVelocityFromWorldPointToOut(Vector2 worldPoint, Vector2 out) {
final float tempX = worldPoint.x - m_sweep.c.x;
final float tempY = worldPoint.y - m_sweep.c.y;
out.x = -m_angularVelocity * tempY + m_linearVelocity.x;
out.y = m_angularVelocity * tempX + m_linearVelocity.y;
}
/**
* Get the world velocity of a local point.
*
* @param a point in local coordinates.
* @return the world velocity of a point.
*/
public final Vector2 getLinearVelocityFromLocalPoint(Vector2 localPoint) {
Vector2 out = new Vector2();
getLinearVelocityFromLocalPointToOut(localPoint, out);
return out;
}
public final void getLinearVelocityFromLocalPointToOut(Vector2 localPoint, Vector2 out) {
getWorldPointToOut(localPoint, out);
getLinearVelocityFromWorldPointToOut(out, out);
}
/** Get the linear damping of the body. */
public final float getLinearDamping() {
return m_linearDamping;
}
/** Set the linear damping of the body. */
public final void setLinearDamping(float linearDamping) {
m_linearDamping = linearDamping;
}
/** Get the angular damping of the body. */
public final float getAngularDamping() {
return m_angularDamping;
}
/** Set the angular damping of the body. */
public final void setAngularDamping(float angularDamping) {
m_angularDamping = angularDamping;
}
public BodyType getType() {
return m_type;
}
/**
* Set the type of this body. This may alter the mass and velocity.
*
* @param type
*/
public void setType(BodyType type) {
assert (m_world.isLocked() == false);
if (m_world.isLocked() == true) {
return;
}
if (m_type == type) {
return;
}
m_type = type;
resetMassData();
if (m_type == BodyType.STATIC) {
m_linearVelocity.setZero();
m_angularVelocity = 0.0f;
m_sweep.a0 = m_sweep.a;
m_sweep.c0.set(m_sweep.c);
synchronizeFixtures();
}
setAwake(true);
m_force.setZero();
m_torque = 0.0f;
// Delete the attached contacts.
ContactEdge ce = m_contactList;
while (ce != null) {
ContactEdge ce0 = ce;
ce = ce.next;
m_world.m_contactManager.destroy(ce0.contact);
}
m_contactList = null;
// Touch the proxies so that new contacts will be created (when appropriate)
BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase;
for (Fixture f = m_fixtureList; f != null; f = f.m_next) {
int proxyCount = f.m_proxyCount;
for (int i = 0; i < proxyCount; ++i) {
broadPhase.touchProxy(f.m_proxies[i].proxyId);
}
}
}
/** Is this body treated like a bullet for continuous collision detection? */
public final boolean isBullet() {
return (m_flags & e_bulletFlag) == e_bulletFlag;
}
/** Should this body be treated like a bullet for continuous collision detection? */
public final void setBullet(boolean flag) {
if (flag) {
m_flags |= e_bulletFlag;
} else {
m_flags &= ~e_bulletFlag;
}
}
/**
* You can disable sleeping on this body. If you disable sleeping, the body will be woken.
*
* @param flag
*/
public void setSleepingAllowed(boolean flag) {
if (flag) {
m_flags |= e_autoSleepFlag;
} else {
m_flags &= ~e_autoSleepFlag;
setAwake(true);
}
}
/**
* Is this body allowed to sleep
*
* @return
*/
public boolean isSleepingAllowed() {
return (m_flags & e_autoSleepFlag) == e_autoSleepFlag;
}
/**
* Set the sleep state of the body. A sleeping body has very low CPU cost.
*
* @param flag set to true to put body to sleep, false to wake it.
* @param flag
*/
public void setAwake(boolean flag) {
if (flag) {
if ((m_flags & e_awakeFlag) == 0) {
m_flags |= e_awakeFlag;
m_sleepTime = 0.0f;
}
} else {
m_flags &= ~e_awakeFlag;
m_sleepTime = 0.0f;
m_linearVelocity.setZero();
m_angularVelocity = 0.0f;
m_force.setZero();
m_torque = 0.0f;
}
}
/**
* Get the sleeping state of this body.
*
* @return true if the body is awake.
*/
public boolean isAwake() {
return (m_flags & e_awakeFlag) == e_awakeFlag;
}
/**
* Set the active state of the body. An inactive body is not simulated and cannot be collided with
* or woken up. If you pass a flag of true, all fixtures will be added to the broad-phase. If you
* pass a flag of false, all fixtures will be removed from the broad-phase and all contacts will
* be destroyed. Fixtures and joints are otherwise unaffected. You may continue to create/destroy
* fixtures and joints on inactive bodies. Fixtures on an inactive body are implicitly inactive
* and will not participate in collisions, ray-casts, or queries. Joints connected to an inactive
* body are implicitly inactive. An inactive body is still owned by a World object and remains in
* the body list.
*
* @param flag
*/
public void setActive(boolean flag) {
assert (m_world.isLocked() == false);
if (flag == isActive()) {
return;
}
if (flag) {
m_flags |= e_activeFlag;
// Create all proxies.
BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase;
for (Fixture f = m_fixtureList; f != null; f = f.m_next) {
f.createProxies(broadPhase, m_xf);
}
// Contacts are created the next time step.
} else {
m_flags &= ~e_activeFlag;
// Destroy all proxies.
BroadPhase broadPhase = m_world.m_contactManager.m_broadPhase;
for (Fixture f = m_fixtureList; f != null; f = f.m_next) {
f.destroyProxies(broadPhase);
}
// Destroy the attached contacts.
ContactEdge ce = m_contactList;
while (ce != null) {
ContactEdge ce0 = ce;
ce = ce.next;
m_world.m_contactManager.destroy(ce0.contact);
}
m_contactList = null;
}
}
/**
* Get the active state of the body.
*
* @return
*/
public boolean isActive() {
return (m_flags & e_activeFlag) == e_activeFlag;
}
/**
* Set this body to have fixed rotation. This causes the mass to be reset.
*
* @param flag
*/
public void setFixedRotation(boolean flag) {
if (flag) {
m_flags |= e_fixedRotationFlag;
} else {
m_flags &= ~e_fixedRotationFlag;
}
resetMassData();
}
/**
* Does this body have fixed rotation?
*
* @return
*/
public boolean isFixedRotation() {
return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag;
}
/** Get the list of all fixtures attached to this body. */
public final Fixture getFixtureList() {
return m_fixtureList;
}
/** Get the list of all joints attached to this body. */
public final JointEdge getJointList() {
return m_jointList;
}
/**
* Get the list of all contacts attached to this body.
*
* @warning this list changes during the time step and you may miss some collisions if you don't
* use ContactListener.
*/
public final ContactEdge getContactList() {
return m_contactList;
}
/** Get the next body in the world's body list. */
public final Body getNext() {
return m_next;
}
/** Get the user data pointer that was provided in the body definition. */
public final Object getUserData() {
return m_userData;
}
/**
* Set the user data. Use this to store your application specific data.
*/
public final void setUserData(Object data) {
m_userData = data;
}
/**
* Get the parent world of this body.
*/
public final World getWorld() {
return m_world;
}
// djm pooling
private final Transform pxf = new Transform();
protected final void synchronizeFixtures() {
final Transform xf1 = pxf;
// xf1.position = m_sweep.c0 - Mul(xf1.R, m_sweep.localCenter);
// xf1.q.set(m_sweep.a0);
// Rot.mulToOutUnsafe(xf1.q, m_sweep.localCenter, xf1.p);
// xf1.p.mulLocal(-1).addLocal(m_sweep.c0);
// inlined:
xf1.q.s = MathUtils.sin(m_sweep.a0);
xf1.q.c = MathUtils.cos(m_sweep.a0);
xf1.p.x = m_sweep.c0.x - xf1.q.c * m_sweep.localCenter.x + xf1.q.s * m_sweep.localCenter.y;
xf1.p.y = m_sweep.c0.y - xf1.q.s * m_sweep.localCenter.x - xf1.q.c * m_sweep.localCenter.y;
// end inline
for (Fixture f = m_fixtureList; f != null; f = f.m_next) {
f.synchronize(m_world.m_contactManager.m_broadPhase, xf1, m_xf);
}
}
public final void synchronizeTransform() {
// m_xf.q.set(m_sweep.a);
//
// // m_xf.position = m_sweep.c - Mul(m_xf.R, m_sweep.localCenter);
// Rot.mulToOutUnsafe(m_xf.q, m_sweep.localCenter, m_xf.p);
// m_xf.p.mulLocal(-1).addLocal(m_sweep.c);
//
m_xf.q.s = MathUtils.sin(m_sweep.a);
m_xf.q.c = MathUtils.cos(m_sweep.a);
Rot q = m_xf.q;
Vector2 v = m_sweep.localCenter;
m_xf.p.x = m_sweep.c.x - q.c * v.x + q.s * v.y;
m_xf.p.y = m_sweep.c.y - q.s * v.x - q.c * v.y;
}
/**
* This is used to prevent connected bodies from colliding. It may lie, depending on the
* collideConnected flag.
*
* @param other
* @return
*/
public boolean shouldCollide(Body other) {
// At least one body should be dynamic.
if (m_type != BodyType.DYNAMIC && other.m_type != BodyType.DYNAMIC) {
return false;
}
// Does a joint prevent collision?
for (JointEdge jn = m_jointList; jn != null; jn = jn.next) {
if (jn.other == other) {
if (jn.joint.getCollideConnected() == false) {
return false;
}
}
}
return true;
}
protected final void advance(float t) {
// Advance to the new safe time. This doesn't sync the broad-phase.
m_sweep.advance(t);
m_sweep.c.set(m_sweep.c0);
m_sweep.a = m_sweep.a0;
m_xf.q.set(m_sweep.a);
// m_xf.position = m_sweep.c - Mul(m_xf.R, m_sweep.localCenter);
Rot.mulToOutUnsafe(m_xf.q, m_sweep.localCenter, m_xf.p);
m_xf.p.mulLocal(-1).addLocal(m_sweep.c);
}
}
| unlicense |
kyorohiro/HetimaStun | test_nat/net/hetimatan/net/stun/message/TestForHtunHeader.java | 8079 | package net.hetimatan.net.stun.message;
import java.io.IOException;
import net.hetimatan.io.file.MarkableFileReader;
import net.hetimatan.io.filen.CashKyoroFile;
import net.hetimatan.io.filen.CashKyoroFileHelper;
import net.hetimatan.net.stun.HtunServer;
import net.hetimatan.net.stun.message.attribute.HtunChangeRequest;
import net.hetimatan.net.stun.message.attribute.HtunXxxAddress;
import net.hetimatan.util.http.HttpObject;
import junit.framework.TestCase;
public class TestForHtunHeader extends TestCase {
public void testEmptyAttribute() throws IOException {
byte[] id = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
HtunHeader header = new HtunHeader(HtunHeader.BINDING_REQUEST, id);
CashKyoroFile output = new CashKyoroFile(1000);
header.encode(output.getLastOutput());
byte[] buffer = CashKyoroFileHelper.newBinary(output);
{
byte[] expected = {
//0x00, 0x00,
0x00, HtunHeader.BINDING_REQUEST,
0x00, 0x00, // length
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 //id
};
for(int i=0;i<expected.length;i++) {
assertEquals("["+i+"]", expected[i], buffer[i]);
}
}
{//decode
MarkableFileReader reader = new MarkableFileReader(buffer);
HtunHeader exHeader = HtunHeader.decode(reader);
assertEquals(HtunHeader.BINDING_REQUEST, exHeader.getType());
reader.close();
}
}
public void testChangeReauestAttribute() throws IOException {
byte[] id = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
HtunHeader header = new HtunHeader(HtunHeader.BINDING_REQUEST, id);
header.addAttribute(new HtunChangeRequest(HtunChangeRequest.STATUS_CHANGE_IP));
CashKyoroFile output = new CashKyoroFile(1000);
header.encode(output.getLastOutput());
byte[] buffer = CashKyoroFileHelper.newBinary(output);
{
byte[] expected = {
//0x00, 0x00,
0x00, HtunHeader.BINDING_REQUEST,
0x00, 0x08, // length
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, //id
0x00, HtunAttribute.CHANGE_RESUQEST,
0x00, 0x04,
0x00, 0x00, 0x00, HtunChangeRequest.STATUS_CHANGE_IP
};
for(int i=0;i<expected.length;i++) {
assertEquals("["+i+"]", expected[i], buffer[i]);
}
}
{//decode
MarkableFileReader reader = new MarkableFileReader(buffer);
HtunHeader exHeader = HtunHeader.decode(reader);
assertEquals(HtunHeader.BINDING_REQUEST, exHeader.getType());
assertEquals(1, exHeader.numOfAttribute());
assertEquals(false, ((HtunChangeRequest)exHeader.getHtunAttribute(0)).chagePort());
assertEquals(true, ((HtunChangeRequest)exHeader.getHtunAttribute(0)).changeIp());
reader.close();
}
}
public void testChangeResponseAttribute() throws IOException {
byte[] id = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
HtunHeader header = new HtunHeader(HtunHeader.BINDING_RESPONSE, id);
header.addAttribute(new HtunXxxAddress(
HtunAttribute.SOURCE_ADDRESS, 0x01,
800, HttpObject.aton("127.0.0.1")
));
// encode test
CashKyoroFile output = new CashKyoroFile(1000);
header.encode(output.getLastOutput());
byte[] buffer = CashKyoroFileHelper.newBinary(output);
{
byte[] expected = {
//0x00, 0x00,
0xFF&(HtunHeader.BINDING_RESPONSE>>8), 0xFF&HtunHeader.BINDING_RESPONSE,
0x00, 0x0C, // length
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, //id
0x00, HtunAttribute.SOURCE_ADDRESS,
0x00, 0x08, //length
0x00, 0x01, //family
0x03, (byte)(0xFF&0x20), //port
127, 0, 0, 1
};
for(int i=0;i<expected.length;i++) {
assertEquals("["+i+"]", 0xFF&expected[i], 0xFF&buffer[i]);
}
}
//decode test
{//decode
MarkableFileReader reader = new MarkableFileReader(buffer);
HtunHeader exHeader = HtunHeader.decode(reader);
assertEquals(HtunHeader.BINDING_RESPONSE, exHeader.getType());
assertEquals(1, exHeader.numOfAttribute());
assertEquals(HtunAttribute.SOURCE_ADDRESS, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getType());
assertEquals(0x01, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getFamily());
assertEquals(800, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getPort());
assertEquals(127, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getIp()[0]);
assertEquals(0, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getIp()[1]);
assertEquals(0, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getIp()[2]);
assertEquals(1, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getIp()[3]);
reader.close();
}
}
public void testChangeResponseAttribute001() throws IOException {
byte[] id = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
HtunHeader header = new HtunHeader(HtunHeader.BINDING_RESPONSE, id);
header.addAttribute(new HtunXxxAddress(
HtunAttribute.SOURCE_ADDRESS, 0x01,
800, HttpObject.aton("127.0.0.1")
));
header.addAttribute(new HtunXxxAddress(
HtunAttribute.MAPPED_ADDRESS, 0x01,
800, HttpObject.aton("127.0.0.1")
));
header.addAttribute(new HtunXxxAddress(
HtunAttribute.CHANGE_ADDRESS, 0x01,
800, HttpObject.aton("127.0.0.1")
));
// encode test
CashKyoroFile output = new CashKyoroFile(1000);
header.encode(output.getLastOutput());
byte[] buffer = CashKyoroFileHelper.newBinary(output);
{
byte[] expected = {
//0x00, 0x00,
0xFF&(HtunHeader.BINDING_RESPONSE>>8), 0xFF&HtunHeader.BINDING_RESPONSE,
0x00, 36, // length
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, //id
0x00, HtunAttribute.SOURCE_ADDRESS,
0x00, 0x08, //length
0x00, 0x01, //family
0x03, (byte)(0xFF&0x20), //port
127, 0, 0, 1,
0x00, HtunAttribute.MAPPED_ADDRESS,
0x00, 0x08, //length
0x00, 0x01, //family
0x03, (byte)(0xFF&0x20), //port
127, 0, 0, 1,
0x00, HtunAttribute.CHANGE_ADDRESS,
0x00, 0x08, //length
0x00, 0x01, //family
0x03, (byte)(0xFF&0x20), //port
127, 0, 0, 1,
};
for(int i=0;i<expected.length;i++) {
assertEquals("["+i+"]", 0xFF&expected[i], 0xFF&buffer[i]);
}
}
//decode test
{//decode
MarkableFileReader reader = new MarkableFileReader(buffer);
HtunHeader exHeader = HtunHeader.decode(reader);
assertEquals(HtunHeader.BINDING_RESPONSE, exHeader.getType());
assertEquals(3, exHeader.numOfAttribute());
{
assertEquals(HtunAttribute.SOURCE_ADDRESS, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getType());
assertEquals(0x01, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getFamily());
assertEquals(800, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getPort());
assertEquals(127, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getIp()[0]);
assertEquals(0, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getIp()[1]);
assertEquals(0, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getIp()[2]);
assertEquals(1, ((HtunXxxAddress)exHeader.getHtunAttribute(0)).getIp()[3]);
}
{
assertEquals(HtunAttribute.MAPPED_ADDRESS, ((HtunXxxAddress)exHeader.getHtunAttribute(1)).getType());
assertEquals(0x01, ((HtunXxxAddress)exHeader.getHtunAttribute(1)).getFamily());
assertEquals(800, ((HtunXxxAddress)exHeader.getHtunAttribute(1)).getPort());
assertEquals(127, ((HtunXxxAddress)exHeader.getHtunAttribute(1)).getIp()[0]);
assertEquals(0, ((HtunXxxAddress)exHeader.getHtunAttribute(1)).getIp()[1]);
assertEquals(0, ((HtunXxxAddress)exHeader.getHtunAttribute(1)).getIp()[2]);
assertEquals(1, ((HtunXxxAddress)exHeader.getHtunAttribute(1)).getIp()[3]);
}
{
assertEquals(HtunAttribute.CHANGE_ADDRESS, ((HtunXxxAddress)exHeader.getHtunAttribute(2)).getType());
assertEquals(0x01, ((HtunXxxAddress)exHeader.getHtunAttribute(2)).getFamily());
assertEquals(800, ((HtunXxxAddress)exHeader.getHtunAttribute(2)).getPort());
assertEquals(127, ((HtunXxxAddress)exHeader.getHtunAttribute(2)).getIp()[0]);
assertEquals(0, ((HtunXxxAddress)exHeader.getHtunAttribute(2)).getIp()[1]);
assertEquals(0, ((HtunXxxAddress)exHeader.getHtunAttribute(2)).getIp()[2]);
assertEquals(1, ((HtunXxxAddress)exHeader.getHtunAttribute(2)).getIp()[3]);
}
reader.close();
}
}
}
| unlicense |
AeroScripts/OSRSMapRestorationProject | src/org/aero/osrsmap/imagesearch/POI.java | 978 | /*
* 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 org.aero.osrsmap.imagesearch;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
/**
*
* @author Luke
*/
public class POI {
public ArrayList<Pixel> compares = new ArrayList<Pixel>();
BufferedImage image;
public String name;
public POI(BufferedImage image, String name){
this.image = image;
this.name = name;
}
void generateComparator() {
int avoid = image.getRGB(0,0);
int rgb = 0;
for(int x = 0; x < 15; x++){
for(int y = 0; y < 15; y++){
if(!POIDB.pixmatch[x][y] && (rgb = image.getRGB(x, y)) != avoid){
compares.add(new Pixel(x, y, rgb));
}
}
}
}
}
| unlicense |
6tail/nlf | src/nc/liat6/frame/validate/rule/RuleDate.java | 618 | package nc.liat6.frame.validate.rule;
import java.text.ParseException;
import nc.liat6.frame.locale.L;
import nc.liat6.frame.util.Dater;
/**
* 年-月-日形式
*
* @author 6tail
*
*/
public class RuleDate extends AbstractRule{
public RuleDate(String item){
setErrorMessage(item+L.get("reg.date_suffix"));
}
public RuleDate(){
setErrorMessage(L.get("reg.date"));
}
public boolean validate(String key){
if(null==key)
return false;
try{
Dater.ymd2Date(key);
}catch(ParseException e){
return false;
}
return true;
}
}
| unlicense |
clilystudio/NetBook | allsrc/com/qq/e/comm/net/rr/PlainRequest.java | 687 | package com.qq.e.comm.net.rr;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
public class PlainRequest extends AbstractRequest
{
public PlainRequest(String paramString, Request.Method paramMethod, byte[] paramArrayOfByte)
{
super(paramString, paramMethod, paramArrayOfByte);
}
public Response initResponse(HttpUriRequest paramHttpUriRequest, HttpResponse paramHttpResponse)
{
return new PlainResponse(paramHttpResponse, paramHttpUriRequest);
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.qq.e.comm.net.rr.PlainRequest
* JD-Core Version: 0.6.0
*/ | unlicense |
JFixby/jfixby-Fields | battlefields-terrain-red/src/com/jfixby/r3/ext/red/terrain/landscape/RedLandscapeSpecs.java | 440 |
package com.jfixby.r3.ext.red.terrain.landscape;
import com.jfixby.util.terain.test.api.landscape.LandscapeSpecs;
import com.jfixby.util.terain.test.api.palette.TerrainPalette;
public class RedLandscapeSpecs implements LandscapeSpecs {
private TerrainPalette palette;
@Override
public void setPalette (TerrainPalette palette) {
this.palette = palette;
}
@Override
public TerrainPalette getPalette () {
return palette;
}
}
| unlicense |
clilystudio/NetBook | allsrc/android/support/v7/internal/widget/AbsActionBarView.java | 5959 | package android.support.v7.internal.widget;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
import android.os.Build.VERSION;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorCompat;
import android.support.v7.appcompat.R.attr;
import android.support.v7.appcompat.R.styleable;
import android.support.v7.internal.view.h;
import android.support.v7.widget.ActionMenuPresenter;
import android.support.v7.widget.ActionMenuView;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
abstract class AbsActionBarView extends ViewGroup
{
private static final Interpolator h = new DecelerateInterpolator();
protected final Context a;
protected ActionMenuView b;
protected ActionMenuPresenter c;
protected ViewGroup d;
protected boolean e;
protected int f;
protected ViewPropertyAnimatorCompat g;
private AbsActionBarView.VisibilityAnimListener i = new AbsActionBarView.VisibilityAnimListener(this);
AbsActionBarView(Context paramContext)
{
this(paramContext, null);
}
AbsActionBarView(Context paramContext, AttributeSet paramAttributeSet)
{
this(paramContext, paramAttributeSet, 0);
}
AbsActionBarView(Context paramContext, AttributeSet paramAttributeSet, int paramInt)
{
super(paramContext, paramAttributeSet, paramInt);
TypedValue localTypedValue = new TypedValue();
if ((paramContext.getTheme().resolveAttribute(R.attr.actionBarPopupTheme, localTypedValue, true)) && (localTypedValue.resourceId != 0))
{
this.a = new ContextThemeWrapper(paramContext, localTypedValue.resourceId);
return;
}
this.a = paramContext;
}
protected static int a(int paramInt1, int paramInt2, boolean paramBoolean)
{
if (paramBoolean)
return paramInt1 - paramInt2;
return paramInt1 + paramInt2;
}
protected static int a(View paramView, int paramInt1, int paramInt2, int paramInt3)
{
paramView.measure(View.MeasureSpec.makeMeasureSpec(paramInt1, -2147483648), paramInt2);
return Math.max(0, paramInt1 - paramView.getMeasuredWidth());
}
protected static int a(View paramView, int paramInt1, int paramInt2, int paramInt3, boolean paramBoolean)
{
int j = paramView.getMeasuredWidth();
int k = paramView.getMeasuredHeight();
int m = paramInt2 + (paramInt3 - k) / 2;
if (paramBoolean)
paramView.layout(paramInt1 - j, m, paramInt1, k + m);
while (true)
{
if (paramBoolean)
j = -j;
return j;
paramView.layout(paramInt1, m, paramInt1 + j, k + m);
}
}
public void a(int paramInt)
{
if (this.g != null)
this.g.cancel();
if (paramInt == 0)
{
if (getVisibility() != 0)
{
ViewCompat.setAlpha(this, 0.0F);
if ((this.d != null) && (this.b != null))
ViewCompat.setAlpha(this.b, 0.0F);
}
ViewPropertyAnimatorCompat localViewPropertyAnimatorCompat3 = ViewCompat.animate(this).alpha(1.0F);
localViewPropertyAnimatorCompat3.setDuration(200L);
localViewPropertyAnimatorCompat3.setInterpolator(h);
if ((this.d != null) && (this.b != null))
{
h localh2 = new h();
ViewPropertyAnimatorCompat localViewPropertyAnimatorCompat4 = ViewCompat.animate(this.b).alpha(1.0F);
localViewPropertyAnimatorCompat4.setDuration(200L);
localh2.a(this.i.a(localViewPropertyAnimatorCompat3, paramInt));
localh2.a(localViewPropertyAnimatorCompat3).a(localViewPropertyAnimatorCompat4);
localh2.a();
return;
}
localViewPropertyAnimatorCompat3.setListener(this.i.a(localViewPropertyAnimatorCompat3, paramInt));
localViewPropertyAnimatorCompat3.start();
return;
}
ViewPropertyAnimatorCompat localViewPropertyAnimatorCompat1 = ViewCompat.animate(this).alpha(0.0F);
localViewPropertyAnimatorCompat1.setDuration(200L);
localViewPropertyAnimatorCompat1.setInterpolator(h);
if ((this.d != null) && (this.b != null))
{
h localh1 = new h();
ViewPropertyAnimatorCompat localViewPropertyAnimatorCompat2 = ViewCompat.animate(this.b).alpha(0.0F);
localViewPropertyAnimatorCompat2.setDuration(200L);
localh1.a(this.i.a(localViewPropertyAnimatorCompat1, paramInt));
localh1.a(localViewPropertyAnimatorCompat1).a(localViewPropertyAnimatorCompat2);
localh1.a();
return;
}
localViewPropertyAnimatorCompat1.setListener(this.i.a(localViewPropertyAnimatorCompat1, paramInt));
localViewPropertyAnimatorCompat1.start();
}
public boolean a()
{
if (this.c != null)
return this.c.f();
return false;
}
protected void onConfigurationChanged(Configuration paramConfiguration)
{
if (Build.VERSION.SDK_INT >= 8)
super.onConfigurationChanged(paramConfiguration);
TypedArray localTypedArray = getContext().obtainStyledAttributes(null, R.styleable.ActionBar, R.attr.actionBarStyle, 0);
setContentHeight(localTypedArray.getLayoutDimension(R.styleable.ActionBar_height, 0));
localTypedArray.recycle();
if (this.c != null)
this.c.e();
}
public void setContentHeight(int paramInt)
{
this.f = paramInt;
requestLayout();
}
public void setSplitToolbar(boolean paramBoolean)
{
this.e = paramBoolean;
}
public void setSplitView(ViewGroup paramViewGroup)
{
this.d = paramViewGroup;
}
public void setSplitWhenNarrow(boolean paramBoolean)
{
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: android.support.v7.internal.widget.AbsActionBarView
* JD-Core Version: 0.6.0
*/ | unlicense |
clilystudio/NetBook | allsrc/android/support/v4/media/session/MediaControllerCompat$TransportControlsApi21.java | 2817 | package android.support.v4.media.session;
import android.os.Bundle;
import android.support.v4.media.RatingCompat;
class MediaControllerCompat$TransportControlsApi21 extends MediaControllerCompat.TransportControls
{
private final Object mControlsObj;
public MediaControllerCompat$TransportControlsApi21(Object paramObject)
{
this.mControlsObj = paramObject;
}
public void fastForward()
{
MediaControllerCompatApi21.TransportControls.fastForward(this.mControlsObj);
}
public void pause()
{
MediaControllerCompatApi21.TransportControls.pause(this.mControlsObj);
}
public void play()
{
MediaControllerCompatApi21.TransportControls.play(this.mControlsObj);
}
public void playFromMediaId(String paramString, Bundle paramBundle)
{
MediaControllerCompatApi21.TransportControls.playFromMediaId(this.mControlsObj, paramString, paramBundle);
}
public void playFromSearch(String paramString, Bundle paramBundle)
{
MediaControllerCompatApi21.TransportControls.playFromSearch(this.mControlsObj, paramString, paramBundle);
}
public void rewind()
{
MediaControllerCompatApi21.TransportControls.rewind(this.mControlsObj);
}
public void seekTo(long paramLong)
{
MediaControllerCompatApi21.TransportControls.seekTo(this.mControlsObj, paramLong);
}
public void sendCustomAction(PlaybackStateCompat.CustomAction paramCustomAction, Bundle paramBundle)
{
MediaControllerCompatApi21.TransportControls.sendCustomAction(this.mControlsObj, paramCustomAction.getAction(), paramBundle);
}
public void sendCustomAction(String paramString, Bundle paramBundle)
{
MediaControllerCompatApi21.TransportControls.sendCustomAction(this.mControlsObj, paramString, paramBundle);
}
public void setRating(RatingCompat paramRatingCompat)
{
Object localObject1 = this.mControlsObj;
if (paramRatingCompat != null);
for (Object localObject2 = paramRatingCompat.getRating(); ; localObject2 = null)
{
MediaControllerCompatApi21.TransportControls.setRating(localObject1, localObject2);
return;
}
}
public void skipToNext()
{
MediaControllerCompatApi21.TransportControls.skipToNext(this.mControlsObj);
}
public void skipToPrevious()
{
MediaControllerCompatApi21.TransportControls.skipToPrevious(this.mControlsObj);
}
public void skipToQueueItem(long paramLong)
{
MediaControllerCompatApi21.TransportControls.skipToQueueItem(this.mControlsObj, paramLong);
}
public void stop()
{
MediaControllerCompatApi21.TransportControls.stop(this.mControlsObj);
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: android.support.v4.media.session.MediaControllerCompat.TransportControlsApi21
* JD-Core Version: 0.6.0
*/ | unlicense |
beamka/Polyclinic | Clinic/src/main/java/ua/clinic/services/UgroupMapper.java | 1334 | package ua.clinic.services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ua.clinic.jpa.Group;
import ua.clinic.repository.UgroupRepository;
import ua.clinic.repository.UserRepository;
import ua.ibt.clinic.api.GroupAPI;
/**
* Created by Iryna Tkachova on 08.03.2017.
*/
@Component
public class UgroupMapper {
private static final Logger logger = LoggerFactory.getLogger(UgroupMapper.class);
@Autowired
UgroupRepository ugroupRepository;
@Autowired
UserRepository userRepository;
public Group toInside(GroupAPI inData) {
Group newGroup = null;
if(inData != null){
newGroup = new Group(inData.group_id, inData.group_name, inData.description);
logger.debug("##### newGroup: "+newGroup);
}
return newGroup;
}
public GroupAPI toOutside(Group inData) {
GroupAPI groupAPI = null;
if (inData != null) {
groupAPI = new GroupAPI();
groupAPI.group_id = inData.getIdgroup();
groupAPI.group_name = inData.getGroupname();
groupAPI.description = inData.getDescription();
}
return groupAPI;
}
}
| unlicense |
Shahar2k5/app2go | app/src/main/java/com/example/android/app2go/TravelingManagerService.java | 4141 | package com.example.android.app2go;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import java.util.List;
public class TravelingManagerService extends Service {
public static int NEXT_LOCATION_ROUTING_DELAY = 5000;
public TravelingManagerService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
List<LocationPoint> points = null;
Route route = (Route) intent.getSerializableExtra("points");
points = route.getPoints();
lastDestination = points.get(0).getDestination();
sendRoutingIntent(points.get(0));
/* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// You need to ask the user to enable the permissions
} else {
final List<LocationPoint> finalPoints = points;
LocationTracker tracker = new LocationTracker(this) {
@Override
public void onLocationFound(Location location) {
Log.i("location", location.toString());
checkLocation(finalPoints, location);
}
@Override
public void onTimeout() {
Log.i("location tracker", "time out");
}
};
tracker.startListening();
}
} else {
final List<LocationPoint> finalPoints1 = points;
LocationTracker tracker = new LocationTracker(this) {
@Override
public void onLocationFound(Location location) {
Log.i("location", location.toString());
checkLocation(finalPoints1, location);
}
@Override
public void onTimeout() {
Log.i("location tracker", "time out");
}
};
tracker.startListening();
}*/
return START_NOT_STICKY;
}
private void checkLocation(final List<LocationPoint> points, Location location) {
for (int i = 0; i < points.size(); i++) {
LocationPoint p = points.get(i);
double distance = p.getDestination(this).distanceTo(location);
if (Math.abs(distance) < 50) {
final int indexOfLocation = i;
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(NEXT_LOCATION_ROUTING_DELAY);
sendRoutingIntent(points.get(indexOfLocation));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
}
private void sendRoutingIntent(final LocationPoint locationPoint) {
Location source = locationPoint.getSource(getApplicationContext());
Location destination = locationPoint.getDestination(getApplicationContext());
String intentUrl = "http://maps.google.com/maps?saddr=" + source.getLatitude() + "," + source.getLongitude() +
"&daddr=" + destination.getLatitude() + "," + destination.getLongitude();
// "&daddr=32.2334178,35.0017312";
Intent i = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(intentUrl));
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.i("routing url", intentUrl);
startActivity(i);
}
public static String lastDestination = "";
}
| unlicense |
nezuvian/Library-webapp | src/main/java/top2lz/libapp/repository/CustomAuditEventRepository.java | 2487 | package top2lz.libapp.repository;
import top2lz.libapp.config.audit.AuditEventConverter;
import top2lz.libapp.domain.PersistentAuditEvent;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.actuate.audit.AuditEventRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.Date;
import java.util.List;
/**
* Wraps an implementation of Spring Boot's AuditEventRepository.
*/
@Repository
public class CustomAuditEventRepository {
@Inject
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Bean
public AuditEventRepository auditEventRepository() {
return new AuditEventRepository() {
@Inject
private AuditEventConverter auditEventConverter;
@Override
public List<AuditEvent> find(String principal, Date after) {
Iterable<PersistentAuditEvent> persistentAuditEvents;
if (principal == null && after == null) {
persistentAuditEvents = persistenceAuditEventRepository.findAll();
} else if (after == null) {
persistentAuditEvents = persistenceAuditEventRepository.findByPrincipal(principal);
} else {
persistentAuditEvents =
persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfter(principal, new LocalDateTime(after));
}
return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void add(AuditEvent event) {
PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent();
persistentAuditEvent.setPrincipal(event.getPrincipal());
persistentAuditEvent.setAuditEventType(event.getType());
persistentAuditEvent.setAuditEventDate(new LocalDateTime(event.getTimestamp()));
persistentAuditEvent.setData(auditEventConverter.convertDataToStrings(event.getData()));
persistenceAuditEventRepository.save(persistentAuditEvent);
}
};
}
}
| unlicense |
bjartek/vertx-rx | rx-java2/src/test/java/io/vertx/reactivex/test/ApiTest.java | 4695 | package io.vertx.reactivex.test;
import io.reactivex.Completable;
import io.reactivex.Maybe;
import io.reactivex.Single;
import io.vertx.codegen.annotations.Nullable;
import io.vertx.codegen.testmodel.NullableTCKImpl;
import io.vertx.codegen.testmodel.TestInterfaceImpl;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.reactivex.codegen.rxjava2.MethodWithMultiCallback;
import io.vertx.reactivex.codegen.rxjava2.MethodWithNullableTypeVariableParamByVoidArg;
import io.vertx.reactivex.codegen.testmodel.NullableTCK;
import io.vertx.reactivex.codegen.testmodel.TestInterface;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
public class ApiTest {
@Test
public void testSingle() {
TestInterface obj = new TestInterface(new TestInterfaceImpl());
Single<String> fut = obj.rxMethodWithHandlerAsyncResultString(false);
AtomicInteger result = new AtomicInteger();
AtomicInteger fail = new AtomicInteger();
fut.subscribe(res -> {
result.getAndIncrement();
}, err -> {
fail.getAndIncrement();
});
assertEquals(1, result.get());
assertEquals(0, fail.get());
}
@Test
public void testCompletable() {
TestInterface obj = new TestInterface(new TestInterfaceImpl());
Completable failure = obj.rxMethodWithHandlerAsyncResultVoid(true);
AtomicInteger count = new AtomicInteger();
failure.subscribe(Assert::fail, err -> {
count.incrementAndGet();
});
assertEquals(1, count.getAndSet(0));
Completable success = obj.rxMethodWithHandlerAsyncResultVoid(false);
success.subscribe(count::incrementAndGet, err -> fail());
assertEquals(1, count.get());
}
@Test
public void testMaybe() {
NullableTCK obj = new NullableTCK(new NullableTCKImpl());
List<String> result = new ArrayList<>();
List<Throwable> failure = new ArrayList<>();
AtomicInteger completions = new AtomicInteger();
Maybe<String> maybeNotNull = obj.rxMethodWithNullableStringHandlerAsyncResult(true);
maybeNotNull.subscribe(result::add, failure::add, completions::incrementAndGet);
assertEquals(Collections.singletonList("the_string_value"), result);
assertEquals(Collections.emptyList(), failure);
assertEquals(0, completions.get());
result.clear();
maybeNotNull = obj.rxMethodWithNullableStringHandlerAsyncResult(false);
maybeNotNull.subscribe(result::add, failure::add, completions::incrementAndGet);
assertEquals(Collections.emptyList(), result);
assertEquals(Collections.emptyList(), failure);
assertEquals(1, completions.get());
result.clear();
}
@Test
public void testMultiCompletions() {
MethodWithMultiCallback objectMethodWithMultiCompletable = MethodWithMultiCallback.newInstance(new io.vertx.codegen.rxjava2.MethodWithMultiCallback() {
@Override
public void multiCompletable(Handler<AsyncResult<Void>> handler) {
handler.handle(Future.succeededFuture());
handler.handle(Future.succeededFuture());
}
@Override
public void multiMaybe(Handler<AsyncResult<@Nullable String>> handler) {
handler.handle(Future.succeededFuture());
handler.handle(Future.succeededFuture("foo"));
}
@Override
public void multiSingle(Handler<AsyncResult<String>> handler) {
handler.handle(Future.succeededFuture("foo"));
handler.handle(Future.succeededFuture("foo"));
}
});
AtomicInteger count = new AtomicInteger();
objectMethodWithMultiCompletable.rxMultiCompletable().subscribe(count::incrementAndGet);
assertEquals(1, count.getAndSet(0));
objectMethodWithMultiCompletable.rxMultiMaybe().subscribe(s -> count.incrementAndGet(), err -> {}, count::incrementAndGet);
assertEquals(1, count.getAndSet(0));
objectMethodWithMultiCompletable.rxMultiSingle().subscribe(s -> count.incrementAndGet());
assertEquals(1, count.getAndSet(0));
}
@Test
public void testNullableTypeVariableParamByVoidArg() {
MethodWithNullableTypeVariableParamByVoidArg abc = MethodWithNullableTypeVariableParamByVoidArg.newInstance(handler -> handler.handle(Future.succeededFuture()));
Maybe<Void> maybe = abc.rxDoSomethingWithMaybeResult();
AtomicInteger count = new AtomicInteger();
maybe.subscribe(o -> fail(), err -> fail(err.getMessage()), count::incrementAndGet);
assertEquals(1, count.get());
}
}
| apache-2.0 |
leapframework/framework | web/api/src/main/java/leap/web/api/orm/SimpleModelExecutorContext.java | 3295 | /*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package leap.web.api.orm;
import leap.lang.accessor.MapAttributeAccessor;
import leap.orm.dao.Dao;
import leap.orm.mapping.EntityMapping;
import leap.web.action.ActionParams;
import leap.web.api.Api;
import leap.web.api.config.ApiConfig;
import leap.web.api.meta.ApiMetadata;
import leap.web.api.meta.model.MApiModel;
import leap.web.api.remote.RestResourceFactory;
import java.util.Map;
public class SimpleModelExecutorContext extends MapAttributeAccessor implements ModelExecutorContext {
protected ApiConfig ac;
protected ApiMetadata amd;
protected MApiModel apiModel;
protected Dao dao;
protected EntityMapping entityMapping;
protected ActionParams actionParams;
protected RestResourceFactory restResourceFactory;
protected ModelExecutorHelper helper;
public SimpleModelExecutorContext(Api api, Dao dao, MApiModel am, EntityMapping em, ActionParams params) {
this(api.getConfig(), api.getMetadata(), dao, am, em, params);
}
public SimpleModelExecutorContext(ApiConfig ac, ApiMetadata md, Dao dao, MApiModel am, EntityMapping em) {
this(ac, md, dao, am, em, null);
}
public SimpleModelExecutorContext(ApiConfig ac, ApiMetadata md, Dao dao, MApiModel am, EntityMapping em, ActionParams params) {
this.ac = ac;
this.amd = md;
this.apiModel = am;
this.dao = dao;
this.entityMapping = em;
this.actionParams = params;
}
public void setAttributes(Map<String, Object> m) {
if (null != m) {
attributes.putAll(m);
}
}
@Override
public ApiConfig getApiConfig() {
return ac;
}
@Override
public ApiMetadata getApiMetadata() {
return amd;
}
@Override
public MApiModel getApiModel() {
return apiModel;
}
@Override
public Dao getDao() {
return dao;
}
public void setDao(Dao dao) {
this.dao = dao;
}
@Override
public EntityMapping getEntityMapping() {
return entityMapping;
}
@Override
public ActionParams getActionParams() {
return actionParams;
}
@Override
public RestResourceFactory getRestResourceFactory() {
return restResourceFactory;
}
@Override
public void setRestResourceFactory(RestResourceFactory restResourceFactory) {
this.restResourceFactory = restResourceFactory;
}
@Override
public ModelExecutorHelper getHelper() {
return helper;
}
@Override
public void setHelper(ModelExecutorHelper helper) {
this.helper = helper;
}
}
| apache-2.0 |
hotpads/datarouter | datarouter-util/src/main/java/io/datarouter/util/ComparableTool.java | 2169 | /*
* 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.util;
import java.util.Iterator;
public class ComparableTool{
public static <T extends Comparable<? super T>> boolean lt(T object1, T object2){
int diff = nullFirstCompareTo(object1, object2);
return diff < 0;
}
/**
* is a > b
*/
public static <T extends Comparable<? super T>> boolean gt(T object1, T object2){
int diff = nullFirstCompareTo(object1, object2);
return diff > 0;
}
public static <T extends Comparable<? super T>> int nullFirstCompareTo(T object1, T object2){
if(object1 == null && object2 == null){
return 0;
}else if(object1 == null){
return -1;
}else if(object2 == null){
return 1;
}else{
return object1.compareTo(object2);
}
}
public static <T extends Comparable<? super T>> int nullLastCompareTo(T object1, T object2){
if(object1 == null && object2 == null){
return 0;
}else if(object1 == null){
return 1;
}else if(object2 == null){
return -1;
}else{
return object1.compareTo(object2);
}
}
public static <T extends Comparable<? super T>> boolean isSorted(Iterable<? extends T> ins){
if(ins == null){
return true;
}// null is considered sorted
Iterator<? extends T> iter = ins.iterator();
if(!iter.hasNext()){
return true;
}// 0 elements is sorted
T previous = iter.next();
if(!iter.hasNext()){
return true;
}// 1 element is sorted
T current = null;
while(iter.hasNext()){
current = iter.next();
if(previous.compareTo(current) > 0){
return false;
}
previous = current;
}
return true;
}
}
| apache-2.0 |
freeVM/freeVM | enhanced/archive/classlib/modules/crypto2/test/ar/org/fitc/test/integration/crypto/chat/EncryptedChatServerV2.java | 9402 | /*
* Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
*
* 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.
*/
/**
* @author Hugo Beilis
* @author Osvaldo Demo
* @author Jorge Rafael
* @version 1.0
*/
package ar.org.fitc.test.integration.crypto.chat;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Vector;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NullCipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import ar.org.fitc.test.integration.crypto.agreement.ServerDHKeyAgreement;
import ar.org.fitc.test.integration.crypto.util.Authenticator;
import ar.org.fitc.test.integration.crypto.wrapunwrap.SecretKeyWrapUnwrap_imp;
/**
*
* Main server class, it listen for new clients and adds them to a client
* vector. This version is for testing purposes and do not require user
* intervention.
*
* @author Osvaldo C. Demo
*
*/
public class EncryptedChatServerV2 {
private int port = 1024, maxClients = 1024;
private ServerSocket server;
private Vector clients;
private Message msg;
private int messageCounter = 0;
OutputStream debugOut;
/**
* Used to start the server EncryptedChatServerV2
*
* @param newport
* the port to listen connections
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws InterruptedException
*/
public @SuppressWarnings("unchecked")
EncryptedChatServerV2(int newport) throws Exception {
port = newport;
// System.out.println("Server started.");
server = new ServerSocket(port, maxClients);
clients = new Vector();
// while (true) {
clients.addElement(new ThreadedSocket(server.accept()));
// }
}
public static void main(String[] args) throws Exception {
try {
Registry reg = LocateRegistry.createRegistry(1099);
try {
@SuppressWarnings("unused")
Object o = (Object) new SecretKeyWrapUnwrap_imp();
new EncryptedChatServerV2(2000);
} catch (java.rmi.ConnectException e) {
System.err.println("RMIRegistry is required. Run: ");
System.err
.println("\t rmiregistry -J-Djava.rmi.server.codebase=file:<project home>");
} finally {
UnicastRemoteObject.unexportObject(reg,true);
}
} catch (IOException e) {
try {
@SuppressWarnings("unused")
Object o = (Object) new SecretKeyWrapUnwrap_imp();
new EncryptedChatServerV2(2000);
} catch (java.rmi.ConnectException t) {
System.err.println("RMIRegistry is required. Run: ");
System.err
.println("\t rmiregistry -J-Djava.rmi.server.codebase=file:<project home>");
}
}
}
/**
* This class is used to create a thread for each client connected
*
* @author Osvaldo C. Demo
*
*/
private class ThreadedSocket extends Thread {
private Socket client;
private byte[] password = { (byte) 0x00, (byte) 0xaa, (byte) 0x1b,
(byte) 0xc2, (byte) 0x34, (byte) 0xde, (byte) 0x5f, (byte) 0xa6 };;
private byte[] iv = { 24, 51, -15, 5, 91, -126, 23, 80 };
private Key key;
private Authenticator ar;
private ObjectOutputStream out;
private ObjectInputStream in;
private String[] messages = {
"This is a test to see what's the minimun size accepted",
"What's that?", "Are you allright?", "Wich one?",
"The weight of the world seems lighter", "Shut up and dance",
"You wont regret" };
public ThreadedSocket(Socket socketChosen) throws Exception {
client = socketChosen;
password = ServerDHKeyAgreement.agree(socketChosen);
iv = new byte[8];
System.arraycopy(ServerDHKeyAgreement.agree(socketChosen), 0, iv,
0, 8);
ar = new Authenticator(password);
key = SecretKeyFactory.getInstance("DES").translateKey(
new SecretKeySpec(password, "DES"));
out = new ObjectOutputStream(new CipherOutputStream(client
.getOutputStream(), getCipher(Cipher.ENCRYPT_MODE)));
// System.out.println("Step 1...Done");
in = new ObjectInputStream(new CipherInputStream(client
.getInputStream(), getCipher(Cipher.DECRYPT_MODE)));
// System.out.println("Step 2...Done");
runWithException();
}
public void runWithException() throws Exception {
while (messageCounter < messages.length) {
msg = (Message) in.readObject();
// System.out.println("Recieved Message " + messageCounter + ":
// "
// + msg.getText());
checkIntegrity();
checkMsg(messages[messageCounter]);
}
msg = (Message) in.readObject();
if (msg.getText().equals("GoodBye")) {
// main System.out.println("Client closed connection");
client.close();
out.close();
in.close();
}
}
public void run() {
try {
runWithException();
} catch (EOFException t) {
// System.out.println("Lost connection with: "
// + client.getInetAddress());
} catch (Throwable t) {
t.printStackTrace();
}
}
private void checkMsg(String string) throws Exception {
if (msg.getText().equals(string)) {
sendAck(out);
} else {
sendErr(out);
throw new ServerError("Received ERR message from server");
}
messageCounter++;
}
private void checkIntegrity() {
if (!ar.isHashOk(msg.getHash(), msg.getText().getBytes())) {
// System.err.println("Message integrity check FAILED");
// System.err.println("Hash on message: "
// + Arrays.toString(msg.getHash()));
// System.err.println("Hash calculated: "
// + Arrays.toString(ar.getHash(msg.getText().getBytes())));
}
}
/**
* This method prepares a cipher for its use
*
* @param mode
* Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE
* @return an initialized instance of cipher ready for use
*/
private Cipher getCipher(int mode) {
Cipher cipher = new NullCipher();
try {
cipher = Cipher.getInstance("DES/CFB8/NoPadding", "SunJCE");
cipher.init(mode, key, new IvParameterSpec(iv));
// System.out.println("Cipher BlockSize:
// "+cipher.getBlockSize());
} catch (Throwable t) {
// System.out.println("Unable to init a cipher. Using
// NullCipher...");
cipher = new NullCipher();
}
return cipher;
}
private void sendErr(ObjectOutputStream out) {
sendMessage(new Message("Message ERR", ar.getHash(("Message ERR")
.getBytes())), out);
}
private void sendAck(ObjectOutputStream out) {
sendMessage(new Message("Message OK", ar.getHash(("Message OK")
.getBytes())), out);
}
/**
* This method sends a message to all clients registered
*
* @param message
* A Message instance
*/
private void sendMessage(Message message, ObjectOutputStream out) {
try {
message.setHash(ar.getHash(message.toString().getBytes()));
// System.err.println("Sending: "+message.toString());
// System.err.println(Arrays.toString(message.getHash()));
out.writeObject(message);
out.flush();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
| apache-2.0 |
objectos/csv | csv/src/main/java/br/com/objectos/csv/MandatoryFieldException.java | 1105 | /*
* Copyright 2015 Objectos, Fábrica de Software LTDA.
*
* 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 br.com.objectos.csv;
/**
* @author marcio.endo@objectos.com.br (Marcio Endo)
*/
public class MandatoryFieldException extends ParseException {
private static final long serialVersionUID = 1L;
private final Object value;
MandatoryFieldException(AbstractLine<?> line, String fieldName, Object value) {
super(line, fieldName);
this.value = value;
}
@Override
public String getMessage() {
return message("Field is mandatory but found '%s'", value);
}
} | apache-2.0 |
dimone-kun/cuba | modules/gui/src/com/haulmont/cuba/gui/app/core/scheduled/ScheduledExecutionBrowser.java | 1529 | /*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.haulmont.cuba.gui.app.core.scheduled;
import com.haulmont.cuba.core.app.PersistenceManagerService;
import com.haulmont.cuba.gui.components.AbstractWindow;
import com.haulmont.cuba.gui.components.Table;
import com.haulmont.cuba.gui.components.actions.RefreshAction;
import com.haulmont.cuba.gui.data.CollectionDatasource;
import javax.inject.Inject;
import java.util.Map;
public class ScheduledExecutionBrowser extends AbstractWindow {
@Inject
protected Table executionsTable;
@Inject
protected CollectionDatasource executionsDs;
@Inject
protected PersistenceManagerService persistenceManager;
@Override
public void init(Map<String, Object> params) {
executionsTable.addAction(new RefreshAction(executionsTable));
int maxResults = persistenceManager.getFetchUI(executionsDs.getMetaClass().getName());
executionsDs.setMaxResults(maxResults);
}
} | apache-2.0 |
lehnhu/edmetl | src/test/java/com/citics/edm/etf/TestOne.java | 435 | package com.citics.edm.etf;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestOne {
public static void main(String [] args){
SimpleDateFormat fmt=new SimpleDateFormat("yyyymmdd");
try {
Date d=fmt.parse("20130201");
System.out.println(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| apache-2.0 |
egacl/gatewayio | GatewayProjects/Gateway/src/main/java/cl/io/gateway/InternalGatewayService.java | 1362 | /*
* Copyright 2017 GetSoftware (http://www.getsoftware.cl)
*
* 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 cl.io.gateway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cl.io.gateway.service.IGatewayService;
public class InternalGatewayService extends AbstractGateway<IGatewayService, InternalService> {
private static final Logger logger = LoggerFactory.getLogger(InternalGatewayService.class);
public InternalGatewayService(Gateway gateway, InternalService service) throws Exception {
super(gateway, service);
}
@Override
public void init() throws Exception {
logger.info("Initialiazing gateway element '" + this.getGatewayId() + "' from '" + this.getContextId()
+ "' context");
super.init();
this.getElementInstance().initialize(this);
}
}
| apache-2.0 |
mcwarman/interlok | adapter/src/test/java/com/adaptris/core/jms/activemq/ActiveMqPasPollingConsumerTest.java | 6899 | /*
* Copyright 2015 Adaptris Ltd.
*
* 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.adaptris.core.jms.activemq;
import static com.adaptris.core.jms.JmsProducerCase.assertMessages;
import static com.adaptris.core.jms.JmsProducerCase.createMessage;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import com.adaptris.core.AdaptrisPollingConsumer;
import com.adaptris.core.BaseCase;
import com.adaptris.core.ConfiguredConsumeDestination;
import com.adaptris.core.ConfiguredProduceDestination;
import com.adaptris.core.CoreException;
import com.adaptris.core.RandomIntervalPoller;
import com.adaptris.core.StandaloneConsumer;
import com.adaptris.core.StandaloneProducer;
import com.adaptris.core.StandardWorkflow;
import com.adaptris.core.jms.JmsConnection;
import com.adaptris.core.jms.PasPollingConsumer;
import com.adaptris.core.jms.PasProducer;
import com.adaptris.core.stubs.MockMessageListener;
import com.adaptris.core.util.LifecycleHelper;
import com.adaptris.core.util.ManagedThreadFactory;
import com.adaptris.util.SafeGuidGenerator;
import com.adaptris.util.TimeInterval;
public class ActiveMqPasPollingConsumerTest extends BaseCase {
private static final String MY_SUBSCRIPTION_ID = new SafeGuidGenerator().safeUUID();
private static final ManagedThreadFactory MY_THREAD_FACTORY = new ManagedThreadFactory();
public ActiveMqPasPollingConsumerTest(String arg0) {
super(arg0);
}
@Override
protected void setUp() throws Exception {
}
@Override
protected void tearDown() throws Exception {
}
public void testInitNoClientIdOrSubscriptionId() throws Exception {
PasPollingConsumer consumer = create();
try {
consumer.init();
fail("Should fail due to missing subscription Id, client Id");
}
catch (CoreException e) {
// expected
}
}
public void testInitClientOnly() throws Exception {
PasPollingConsumer consumer = create();
consumer.setClientId("xxxx");
try {
consumer.init();
fail("Should fail due to missing subscription Id");
}
catch (CoreException e) {
// expected
}
}
public void testInitSubscriptionOnly() throws Exception {
PasPollingConsumer consumer = create();
consumer.setSubscriptionId("xxxx");
try {
consumer.init();
fail("Should fail due to missing client Id");
}
catch (CoreException e) {
// expected
}
}
public void testInitClientAndSubscriptionSet() throws Exception {
PasPollingConsumer consumer = create();
consumer.setClientId("xxxx");
consumer.setSubscriptionId("xxxx");
try {
consumer.init();
}
catch (CoreException e) {
fail(e.getMessage());
}
}
public void testProduceConsume() throws Exception {
int msgCount = 5;
final EmbeddedActiveMq activeBroker = new EmbeddedActiveMq();
final StandaloneProducer sender = new StandaloneProducer(activeBroker.getJmsConnection(), new PasProducer(
new ConfiguredProduceDestination(getName())));
final StandaloneConsumer receiver = createStandalone(activeBroker, "testProduceConsume", getName());
activeBroker.start();
try {
MockMessageListener jms = new MockMessageListener();
receiver.registerAdaptrisMessageListener(jms);
startAndStop(receiver);
start(receiver);
start(sender);
for (int i = 0; i < msgCount; i++) {
sender.doService(createMessage());
}
long totalWaitTime = 0;
waitForMessages(jms, msgCount);
assertMessages(jms, msgCount);
}
finally {
shutdownQuietly(sender, receiver, activeBroker);
}
}
static void startAndStop(StandaloneConsumer c) throws Exception {
LifecycleHelper.init(c);
LifecycleHelper.start(c);
while (!((Sometime) ((AdaptrisPollingConsumer) c.getConsumer()).getPoller()).hasTriggered()) {
Thread.sleep(100);
}
LifecycleHelper.stop(c);
LifecycleHelper.close(c);
}
private StandaloneConsumer createStandalone(EmbeddedActiveMq mq, String threadName, String destinationName) throws Exception {
PasPollingConsumer consumer = new PasPollingConsumer(new ConfiguredConsumeDestination(destinationName, null, threadName));
consumer.setPoller(new Sometime());
JmsConnection c = mq.getJmsConnection();
consumer.setVendorImplementation(c.getVendorImplementation());
consumer.setClientId(c.getClientId());
consumer.setSubscriptionId(MY_SUBSCRIPTION_ID);
consumer.setReacquireLockBetweenMessages(true);
consumer.setAdditionalDebug(true);
consumer.setReceiveTimeout(new TimeInterval(new Integer(new Random().nextInt(100) + 100).longValue(), TimeUnit.MILLISECONDS));
StandaloneConsumer sc = new StandaloneConsumer(consumer);
return sc;
}
private static PasPollingConsumer create() {
PasPollingConsumer consumer = new PasPollingConsumer(new ConfiguredConsumeDestination("destination"));
consumer.setVendorImplementation(new BasicActiveMqImplementation());
consumer.registerAdaptrisMessageListener(new StandardWorkflow());
return consumer;
}
static class Sometime extends RandomIntervalPoller {
private boolean hasTriggered = false;
public Sometime() {
super(new TimeInterval(1L, TimeUnit.SECONDS));
}
@Override
protected void scheduleTask() {
if (executor != null && !executor.isShutdown()) {
long delay = ThreadLocalRandom.current().nextLong(1000);
pollerTask = executor.schedule(new MyPollerTask(), delay, TimeUnit.MILLISECONDS);
}
}
boolean hasTriggered() {
return hasTriggered;
}
private class MyPollerTask implements Runnable {
@Override
public void run() {
processMessages();
scheduleTask();
hasTriggered = true;
}
}
}
static void waitQuietly(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
}
}
static void shutdownQuietly(final StandaloneProducer sender, final StandaloneConsumer receiver,
final EmbeddedActiveMq activeMqBroker) {
MY_THREAD_FACTORY.newThread(new Runnable() {
public void run() {
waitQuietly(1000);
stop(sender);
waitQuietly(1000);
stop(receiver);
waitQuietly(1000);
activeMqBroker.destroy();
}
}).start();
}
}
| apache-2.0 |
inbloom/legacy-projects | gateway/gateway/gateway-boot/src/main/java/org/inbloom/gateway/util/mapper/DomainVerificationModelMapper.java | 734 | package org.inbloom.gateway.util.mapper;
import org.inbloom.gateway.common.domain.Verification;
import org.inbloom.gateway.persistence.domain.VerificationEntity;
import org.modelmapper.ModelMapper;
import org.springframework.core.convert.converter.Converter;
/**
* Created with IntelliJ IDEA.
* User: benjaminmorgan
* Date: 3/25/14
* Time: 10:21 AM
* To change this template use File | Settings | File Templates.
*/
public class DomainVerificationModelMapper implements Converter<VerificationEntity, Verification> {
@Override
public Verification convert(VerificationEntity verificationEntity) {
ModelMapper mapper = new ModelMapper();
return mapper.map(verificationEntity, Verification.class);
}
}
| apache-2.0 |
cvielma/ProgrammingExercises | src/Algorithms/LargestBstImproved.java | 11542 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Algorithms;
/**
* Proposed solution to find the largest Binary Search Tree in a Binary Tree.
*
* Proposed Solution:
* To find the largest BST in a tree there are different options to traverse the tree: we could take an top-down approach
* or a bottom-up.
*
* The top-down approach require us to check at each node from the root if the tree starting at that node is a BST. This
* makes us traverse multiple times the tree to find the bst. Although it stops as soon as it find a BST because it will be
* the largest. This solution has a time complexity of O(n^2) in worst-case (degenerated tree into list) or O(nLogn) (balanced tree)
* where n is the number of nodes in the tree.
*
* A better approach will be bottom-up where we check from the bottom of the tree the nodes to check if the trees created are BST.
* This makes the evaluation of a BST in O(1) for each node, although we still have to traverse the tree completely, so this
* approach has a time complexity of O(n) (in fact we have to traverse the tree twice because to get to the bottom nodes we must
* traverse from the root and then again from the bottom to the top). THIS IS THE IMPLEMENTATION SHOWN BELOW. Given the
* implementation is recursive, this has a space complexity of O(n).
*
* Assumptions:
* - A null tree is not a BST.
* - A one node Tree is a BST (assuming this, any not null tree will have at least one BST).
* - Although there can be repeated nodes in the tree, the BST will not have repeated nodes (BST definition).
* - Tree nodes will have non-null integer values.
* - Although problem says that there are no two same-sized largest BSTs, if there were any, it will return the leftmost one.
* - There are no "leaf" kind of nodes. Although there are nodes that have left and right children null.
*
* Some assumptions:
* - A null tree is not a BST.
* - A one node Tree is a BST.
* - When there are several same sized BSTs it will return any of the trees.
* - There are no "leaf" type of nodes.
* - All nodes have left and right sons, although they might be null to
* simulate final leaves.
* - Nodes contain int values (there might be limitation in the range).
* - Nodes cannot contain empty values.
* - There can be repeated nodes in the tree. Although there cannot be repeated
* nodes in the BST.
*
* @author Christian Vielma <cvielma@librethinking.com>
*/
public class LargestBstImproved{
/**
* Binary Tree Class
*/
public static class TreeNode {
int value;
TreeNode left;
TreeNode right;
/**
* Not implementing constructor, getters or setters for simplicity in
* this case Following OO value, left and right should be private and be
* accessed only through getters and setters.
*
* Some methods it would have:
* - Constructors (default and with parameters)
* - Getters and setters
* - AddNode (it will depend on how is suppose to behave this tree, if it going to be balanced or not for example)
* - DeleteNode (by value (if assumption of repeated values is removed or deleting all nodes with that value) or giving a TreeNode)
* - Implementation of equals and hashCode.
* - GetNode (by value (if assumption of repeated values is removed or returning a list of nodes with that value) or giving a TreeNode)
*/
/**
* This Method creates a Tree from an array assuming each value
* i in the array will have its children in positions
* 2*i + 1 and 2*i +2. The array can contain null values.
*
* @param nodes Array with node values.
* @return A complete tree.
*/
public static TreeNode createTree(Integer[] nodes) {
return createTree(nodes, 0);
}
/**
* This method implements the createTree method recursively and
* prevents the first to be called with bad arguments.
* @param nodes Array with node values.
* @param i Position of current node.
* @return A complete tree for node i.
*
* This method has O(n) time complexity (since it traverse the whole array)
* and O(n) space complexity because it is implemented recursively.
*/
private static TreeNode createTree(Integer[] nodes, int i) {
if (nodes == null || i >= nodes.length || nodes[i] == null) { //Possible wrong cases.
return null;
}
TreeNode node = new TreeNode();
node.value = nodes[i];
node.left = createTree(nodes, 2 * i + 1);
node.right = createTree(nodes, 2 * i + 2);
return node;
}
/**
* Just for testing and debugging purposes
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
this.toString(sb, 0, "");
return sb.toString();
}
/**
* The next two methods help printing the tree nicely on console.
*/
private void toString(StringBuilder sb, int level, String branch) {
for (int i = 0; i < level; i++) {
sb.append("-");
}
sb.append(value);
sb.append(branch);
if (left != null) {
printNode(sb, left, level, "(L)");
}
if (right != null) {
printNode(sb, right, level, "(R)");
}
}
private void printNode(StringBuilder sb, TreeNode node, int level, String branch) {
sb.append("\n");
for (int i = 0; i < level * 3; i++) {
sb.append(" ");
}
sb.append("|\n");
for (int i = 0; i < level * 3; i++) {
sb.append(" ");
}
sb.append("|");
node.toString(sb, level + 1, branch);
}
}
/**
* This class is a wrapper (although it could implement
* decorator pattern if methods were implemented) for a
* TreeNode to contain extra information about the current node, needed to
* determine the largestBST while going up. This is because a Java's
* limitation to only return one type.
*/
public static class TreeNodeHelper {
TreeNode node;
int nodes; //number of nodes
Integer maxValue;
Integer minValue;
boolean isBST;
public TreeNodeHelper() {
}
public TreeNodeHelper(TreeNode node, int nodes, Integer maxValue, Integer minValue, boolean isBST) {
this.node = node;
this.nodes = nodes;
this.maxValue = maxValue;
this.minValue = minValue;
this.isBST = isBST;
}
/**
* To keep it simple, given the time, this class is exposing its attributes.
* They should be encapsulated and getting them through methods.
*/
}
/**
* This is the main method. This method determines if a tree has BST inside
* and return the largest (through a helper class) and how many nodes has it.
* @param tree The root of the tree to be analyzed.
* @return TreeNodeHelper with some information as: number of nodes in
* largestBST and the link to the BST node.
*
*/
public static TreeNodeHelper getLargestBST(TreeNode tree) {
if (tree == null) {
return new TreeNodeHelper(null, 0, null, null, false);
}
if (tree.left == null && tree.right == null) {
TreeNodeHelper helper = new TreeNodeHelper(tree, 1, tree.value, tree.value, true);
return helper;
} else {
TreeNodeHelper leftBst = getLargestBST(tree.left);
TreeNodeHelper rightBst = getLargestBST(tree.right);
if (!(rightBst.isBST && rightBst.minValue > tree.value)) {
rightBst.isBST = false;
}
if (!(leftBst.isBST && leftBst.maxValue < tree.value)) {
leftBst.isBST = false;
}
if (leftBst.isBST && rightBst.isBST) { //Both leaves are BST and BST is satisfied with current root
return new TreeNodeHelper(tree, rightBst.nodes + leftBst.nodes + 1, rightBst.maxValue, leftBst.minValue, true);
} else if (tree.left == null && rightBst.isBST) { //Only right leaf and BST is satisfied with current root
return new TreeNodeHelper(tree, ++rightBst.nodes, rightBst.maxValue, tree.value, true);
} else if (tree.right == null && leftBst.isBST) {//Only left leaf and BST is satisfied with current root.
return new TreeNodeHelper(tree, ++leftBst.nodes, tree.value, leftBst.minValue, true);
} else { //No BST is satisfied with current root
//At this point is determined that no BST can include current node, so we return
//the leaf that had the largest BST until now (if there was one)
return leftBst.nodes >= rightBst.nodes ? leftBst : rightBst;
}
}
}
public static void main(String[] args) {
Integer[] treeA = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
TreeNode tree = TreeNode.createTree(treeA);
System.out.println("\n---\n" + tree);
TreeNodeHelper result = getLargestBST(tree);
System.out.println("1 - Largest BST: \n" + result.node);
treeA = new Integer[]{8, 3, 4, 2, 4, 9, 7, 1, null, null, null, 8, 9};
tree = TreeNode.createTree(treeA);
System.out.println("\n---\n" + tree);
result = getLargestBST(tree);
System.out.println("2 - Largest BST: \n" + result.node);
treeA = new Integer[]{null};
tree = TreeNode.createTree(treeA);
System.out.println("\n---\n" + tree);
result = getLargestBST(tree);
System.out.println("3 - Largest BST: \n" + result.node);
treeA = null;
tree = TreeNode.createTree(treeA);
System.out.println("\n---\n" + tree);
result = getLargestBST(tree);
System.out.println("3.1 - Largest BST: \n" + result.node);
treeA = new Integer[]{1};
tree = TreeNode.createTree(treeA);
System.out.println("\n---\n" + tree);
result = getLargestBST(tree);
System.out.println("4 - Largest BST: \n" + result.node);
treeA = new Integer[]{9, 4, 14, 2, 6, 12, 16, 1, 3, 5, 7, 10, 15, 22, 15, -1, null, null, null, null, null, null, 8};
tree = TreeNode.createTree(treeA);
System.out.println("\n---\n" + tree);
result = getLargestBST(tree);
System.out.println("5 - Largest BST: \n" + result.node);
treeA = new Integer[]{14, 12, 16, 10, 15, 22, 15};
tree = TreeNode.createTree(treeA);
System.out.println("\n---\n" + tree);
result = getLargestBST(tree);
System.out.println("6 - Largest BST: \n" + result.node);
treeA = new Integer[]{4, 2, 6, 1, 3, 5, 7, -1, null, null, null, null, null, null, 8};
tree = TreeNode.createTree(treeA);
System.out.println("\n---\n" + tree);
result = getLargestBST(tree);
System.out.println("7 - Largest BST: \n" + result.node);
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-networkmanager/src/main/java/com/amazonaws/services/networkmanager/model/transform/GetTransitGatewayConnectPeerAssociationsRequestMarshaller.java | 3436 | /*
* 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.networkmanager.model.transform;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.networkmanager.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* GetTransitGatewayConnectPeerAssociationsRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GetTransitGatewayConnectPeerAssociationsRequestMarshaller {
private static final MarshallingInfo<String> GLOBALNETWORKID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PATH).marshallLocationName("globalNetworkId").build();
private static final MarshallingInfo<List> TRANSITGATEWAYCONNECTPEERARNS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
.marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("transitGatewayConnectPeerArns").build();
private static final MarshallingInfo<Integer> MAXRESULTS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("maxResults").build();
private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("nextToken").build();
private static final GetTransitGatewayConnectPeerAssociationsRequestMarshaller instance = new GetTransitGatewayConnectPeerAssociationsRequestMarshaller();
public static GetTransitGatewayConnectPeerAssociationsRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(GetTransitGatewayConnectPeerAssociationsRequest getTransitGatewayConnectPeerAssociationsRequest, ProtocolMarshaller protocolMarshaller) {
if (getTransitGatewayConnectPeerAssociationsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getTransitGatewayConnectPeerAssociationsRequest.getGlobalNetworkId(), GLOBALNETWORKID_BINDING);
protocolMarshaller.marshall(getTransitGatewayConnectPeerAssociationsRequest.getTransitGatewayConnectPeerArns(),
TRANSITGATEWAYCONNECTPEERARNS_BINDING);
protocolMarshaller.marshall(getTransitGatewayConnectPeerAssociationsRequest.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(getTransitGatewayConnectPeerAssociationsRequest.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
lime-company/powerauth-webflow | powerauth-data-adapter-model/src/main/java/io/getlime/security/powerauth/lib/dataadapter/model/enumeration/AccountStatus.java | 1172 | /*
* PowerAuth Web Flow and related software components
* Copyright (C) 2017 Wultra s.r.o.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.getlime.security.powerauth.lib.dataadapter.model.enumeration;
/**
* Enumeration representing current user account status.
*
* @author Roman Strobl, roman.strobl@wultra.com
*/
public enum AccountStatus {
/**
* User account status is active.
*/
ACTIVE,
/**
* User account is not active (e.g. blocked or suspended for any other reason).
*/
NOT_ACTIVE
}
| apache-2.0 |
nerdammer/spash | core/src/main/java/it/nerdammer/spash/shell/command/spi/LsCommand.java | 4940 | package it.nerdammer.spash.shell.command.spi;
import com.google.common.collect.ImmutableMap;
import it.nerdammer.spash.shell.api.fs.SpashFileSystem;
import it.nerdammer.spash.shell.command.AbstractCommand;
import it.nerdammer.spash.shell.command.CommandResult;
import it.nerdammer.spash.shell.command.ExecutionContext;
import it.nerdammer.spash.shell.common.SerializableFunction;
import it.nerdammer.spash.shell.common.SpashCollection;
import it.nerdammer.spash.shell.common.SpashCollectionListAdapter;
import it.nerdammer.spash.shell.common.TabulatedValue;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* A command that lists the files contained in the current directory.
*
* @author Nicola Ferraro
*/
public class LsCommand extends AbstractCommand {
public LsCommand(String commandString) {
super(commandString, ImmutableMap.<String, Boolean>builder()
.put("l", false)
.build());
}
@Override
public CommandResult execute(ExecutionContext ctx) {
List<String> args = this.getArguments();
if(args.size()>0) {
return CommandResult.error(this, "Unexpected arguments: " + args);
}
SpashCollection<Path> files = SpashFileSystem.get().ls(ctx.getSession().getWorkingDir());
SpashCollection<String> fileNames = files.map(new SerializableFunction<Path, String>() {
@Override
public String apply(Path v1) {
return v1.getFileName().toString();
}
});
SpashCollection<String> res = fileNames;
if(this.getOptions().containsKey("l")) {
res = toDetail(ctx, fileNames);
}
return CommandResult.success(this, res);
}
private SpashCollection<String> toDetail(ExecutionContext ctx, SpashCollection<String> fileColl) {
List<String> files = fileColl.collect();
if(files.isEmpty()) {
return fileColl;
}
SimpleDateFormat fmtThisYear = new SimpleDateFormat("dd MMM HH:mm");
SimpleDateFormat fmtPast = new SimpleDateFormat("dd MMM yyyy");
List<TabulatedValue> fileDets = new ArrayList<>();
for(String file : files) {
String fullFile = SpashFileSystem.get().getAbsolutePath(ctx.getSession().getWorkingDir(), file).normalize().toString();
TabulatedValue val = new TabulatedValue();
PosixFileAttributes attr = SpashFileSystem.get().getAttributes(fullFile);
Set<PosixFilePermission> perms = attr.permissions();
StringBuilder permStr = new StringBuilder();
permStr.append(attr.isDirectory() ? "d" : "-");
permStr.append(perms.contains(PosixFilePermission.OWNER_READ) ? "r" : "-");
permStr.append(perms.contains(PosixFilePermission.OWNER_WRITE) ? "w" : "-");
permStr.append(perms.contains(PosixFilePermission.OWNER_EXECUTE) ? "x" : "-");
permStr.append(perms.contains(PosixFilePermission.GROUP_READ) ? "r" : "-");
permStr.append(perms.contains(PosixFilePermission.GROUP_WRITE) ? "w" : "-");
permStr.append(perms.contains(PosixFilePermission.GROUP_EXECUTE) ? "x" : "-");
permStr.append(perms.contains(PosixFilePermission.OTHERS_READ) ? "r" : "-");
permStr.append(perms.contains(PosixFilePermission.OTHERS_WRITE) ? "w" : "-");
permStr.append(perms.contains(PosixFilePermission.OTHERS_EXECUTE) ? "x" : "-");
val.add(permStr.toString());
val.add(String.valueOf(SpashFileSystem.get().ls(fullFile).collect().size() + 2));
val.add(attr.owner().getName());
val.add(attr.group().getName());
val.add(String.valueOf(attr.size()));
long fileTime = attr.lastModifiedTime().toMillis();
Date fileDate = new Date(fileTime);
Calendar lastYear = Calendar.getInstance();
lastYear.add(Calendar.YEAR, -1);
long lastYearTime = lastYear.getTimeInMillis();
if(fileTime>lastYearTime) {
val.add(fmtThisYear.format(fileDate));
} else {
val.add(fmtPast.format(fileDate));
}
val.add(file);
fileDets.add(val);
}
List<Integer> combinedColSizes = fileDets.get(0).columnSizes();
for(TabulatedValue val : fileDets) {
List<Integer> colSizes = val.columnSizes();
combinedColSizes = TabulatedValue.combineColumnSizes(combinedColSizes, colSizes);
}
List<String> res = new ArrayList<>();
for(TabulatedValue val : fileDets) {
String vStr = val.toString(combinedColSizes);
res.add(vStr);
}
return new SpashCollectionListAdapter<>(res);
}
}
| apache-2.0 |
Talend/data-prep | dataprep-api/src/main/java/org/talend/dataprep/configuration/DatasetProxyConfiguration.java | 1222 | package org.talend.dataprep.configuration;
import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
// TODO : not sure if it should be only for catalog mode: frontend should not use /api/v1/datasets anyway in legacy mode
@ConditionalOnProperty(name = "dataset.service.provider", havingValue = "catalog")
public class DatasetProxyConfiguration {
@Value("${dataset.service.url}")
private String datasetServiceUrl;
@Bean
public ServletRegistrationBean servletRegistrationBean() {
ProxyServlet servlet = new ProxyServlet();
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "/api/v1/datasets/*");
servletRegistrationBean.addInitParameter("targetUri", datasetServiceUrl + "/api/v1/datasets");
servletRegistrationBean.addInitParameter(ProxyServlet.P_LOG, "true");
return servletRegistrationBean;
}
}
| apache-2.0 |
joewalnes/idea-community | plugins/groovy/src/org/jetbrains/plugins/groovy/dsl/FactorTree.java | 2128 | package org.jetbrains.plugins.groovy.dsl;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.containers.ConcurrentHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.dsl.holders.CustomMembersHolder;
import java.util.Map;
/**
* @author peter
*/
public class FactorTree {
private static final Object ourHolderKey = new Object();
private final Map myCache = new ConcurrentHashMap();
public void cache(GroovyClassDescriptor descriptor, CustomMembersHolder holder) {
Map current = myCache;
for (Factor factor : descriptor.affectingFactors) {
Object key;
switch (factor) {
case placeElement: key = descriptor.getPlace(); break;
case placeFile: key = descriptor.getPlaceFile(); break;
case qualifierType: key = descriptor.getTypeText(); break;
default: throw new IllegalStateException("Unknown variant: "+ factor);
}
Map next = (Map)current.get(key);
if (next == null) current.put(key, next = new ConcurrentHashMap());
current = next;
}
current.put(ourHolderKey, holder);
}
@Nullable
public CustomMembersHolder retrieve(PsiElement place, PsiFile placeFile, String qualifierType) {
return retrieveImpl(place, placeFile, qualifierType, myCache);
}
@Nullable
private static CustomMembersHolder retrieveImpl(@NotNull PsiElement place, @NotNull PsiFile placeFile, @NotNull String qualifierType, @Nullable Map current) {
if (current == null) return null;
CustomMembersHolder result;
result = (CustomMembersHolder)current.get(ourHolderKey);
if (result != null) return result;
result = retrieveImpl(place, placeFile, qualifierType, (Map)current.get(qualifierType));
if (result != null) return result;
result = retrieveImpl(place, placeFile, qualifierType, (Map)current.get(placeFile));
if (result != null) return result;
return retrieveImpl(place, placeFile, qualifierType, (Map)current.get(place));
}
}
enum Factor {
qualifierType, placeElement, placeFile
}
| apache-2.0 |
haozhun/presto | presto-product-tests/src/main/java/com/facebook/presto/tests/TestGroups.java | 3600 | /*
* 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.facebook.presto.tests;
public final class TestGroups
{
public static final String CREATE_TABLE = "create_table";
public static final String CREATE_DROP_VIEW = "create_drop_view";
public static final String ALTER_TABLE = "alter_table";
public static final String SIMPLE = "simple";
public static final String QUARANTINE = "quarantine";
public static final String FUNCTIONS = "functions";
public static final String CLI = "cli";
public static final String HIVE_CONNECTOR = "hive_connector";
public static final String SYSTEM_CONNECTOR = "system";
public static final String JMX_CONNECTOR = "jmx";
public static final String BLACKHOLE_CONNECTOR = "blackhole";
public static final String SMOKE = "smoke";
public static final String JDBC = "jdbc";
public static final String MYSQL = "mysql";
public static final String PRESTO_JDBC = "presto_jdbc";
public static final String SIMBA_JDBC = "simba_jdbc";
public static final String QUERY_ENGINE = "qe";
public static final String COMPARISON = "comparison";
public static final String LOGICAL = "logical";
public static final String SET_OPERATION = "set_operation";
public static final String JSON_FUNCTIONS = "json_functions";
public static final String URL_FUNCTIONS = "url_functions";
public static final String ARRAY_FUNCTIONS = "array_functions";
public static final String BINARY_FUNCTIONS = "binary_functions";
public static final String CONVERSION_FUNCTIONS = "conversion_functions";
public static final String HOROLOGY_FUNCTIONS = "horology_functions";
public static final String MAP_FUNCTIONS = "map_functions";
public static final String REGEX_FUNCTIONS = "regex_functions";
public static final String STRING_FUNCTIONS = "string_functions";
public static final String MATH_FUNCTIONS = "math_functions";
public static final String STORAGE_FORMATS = "storage_formats";
public static final String PROFILE_SPECIFIC_TESTS = "profile_specific_tests";
public static final String HDFS_IMPERSONATION = "hdfs_impersonation";
public static final String HDFS_NO_IMPERSONATION = "hdfs_no_impersonation";
public static final String BASIC_SQL = "basic_sql";
public static final String AUTHORIZATION = "authorization";
public static final String POST_HIVE_1_0_1 = "post_hive_1_0_1";
public static final String HIVE_COERCION = "hive_coercion";
public static final String CASSANDRA = "cassandra";
public static final String SQL_SERVER = "sqlserver";
public static final String LDAP = "ldap";
public static final String LDAP_CLI = "ldap_cli";
public static final String SKIP_ON_CDH = "skip_on_cdh";
public static final String TLS = "tls";
public static final String CANCEL_QUERY = "cancel_query";
public static final String BIG_QUERY = "big_query";
public static final String HIVE_TABLE_STATISTICS = "hive_table_statistics";
public static final String KAFKA = "kafka";
private TestGroups() {}
}
| apache-2.0 |
JimRoid/BaseSupportAndroidModel | ble/src/main/java/com/easyapp/ble/utils/hook/utils/HookUtils.java | 1566 | package com.easyapp.ble.utils.hook.utils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by dingjikerbo on 2016/8/27.
*/
public class HookUtils {
public static Class<?> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static Method getMethod(Class<?> clazz, String name, Class<?>... parameterTypes) {
return MethodUtils.getAccessibleMethod(clazz, name, parameterTypes);
}
public static Field getField(Class<?> clazz, String name) {
if (clazz != null) {
return FieldUtils.getDeclaredField(clazz, name, true);
}
return null;
}
public static <T> T getValue(Field field) {
return getValue(field, null);
}
public static <T> T getValue(Field field, Object object) {
try {
if (field != null) {
return (T) field.get(object);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public static <T> T invoke(Method method, Object object, Object... parameters) {
try {
return (T) method.invoke(object, parameters);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
| apache-2.0 |
rpudil/midpoint | model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/general/ApprovingDummyResourceChangesScenarioBean.java | 3045 | /*
* Copyright (c) 2010-2014 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.wf.impl.general;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.wf.impl.processors.general.scenarios.BaseGcpScenarioBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.xml.namespace.QName;
/**
* This scenario bean simply puts "dummyResourceDelta" process variable into externalized state.
*
* @author mederly
*/
@Component
public class ApprovingDummyResourceChangesScenarioBean extends BaseGcpScenarioBean {
private static final Trace LOGGER = TraceManager.getTrace(ApprovingDummyResourceChangesScenarioBean.class);
// public static final QName DUMMY_RESOURCE_DELTA_QNAME = new QName(SchemaConstants.NS_WFCF, "dummyResourceDelta");
@Autowired
private PrismContext prismContext;
// @Override
// public ProcessSpecificState externalizeInstanceState(Map<String, Object> variables) throws SchemaException {
// PrismContainerDefinition<ProcessSpecificState> extDefinition = prismContext.getSchemaRegistry().findContainerDefinitionByType(ProcessSpecificState.COMPLEX_TYPE);
// PrismContainer<ProcessSpecificState> extStateContainer = extDefinition.instantiate();
// ProcessSpecificState extState = extStateContainer.createNewValue().asContainerable();
//
// PrismPropertyDefinition deltaDefinition = new PrismPropertyDefinition(
// DUMMY_RESOURCE_DELTA_QNAME,
// new QName(SchemaConstantsGenerated.NS_TYPES, "ObjectDeltaType"),
// prismContext);
//
// JaxbValueContainer<ObjectDeltaType> deltaInProcess = (JaxbValueContainer) variables.get("dummyResourceDelta");
// if (deltaInProcess != null) {
// deltaInProcess.setPrismContext(prismContext);
// PrismProperty deltaProperty = extStateContainer.getValue().findOrCreateItem(new ItemPath(DUMMY_RESOURCE_DELTA_QNAME), PrismProperty.class, deltaDefinition);
// deltaProperty.setRealValue(deltaInProcess.getValue());
// LOGGER.info("deltaProperty = {}", deltaProperty.debugDump());
// } else {
// LOGGER.warn("No dummyResourceDelta variable in process instance");
// }
// return extState;
// }
}
| apache-2.0 |
marcus-nl/flowable-engine | modules/flowable-ui-modeler/flowable-ui-modeler-rest/src/main/java/org/flowable/app/rest/editor/ModelsResource.java | 12519 | /* 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.flowable.app.rest.editor;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.flowable.app.domain.editor.AbstractModel;
import org.flowable.app.domain.editor.Model;
import org.flowable.app.model.common.ResultListDataRepresentation;
import org.flowable.app.model.editor.ModelKeyRepresentation;
import org.flowable.app.model.editor.ModelRepresentation;
import org.flowable.app.security.SecurityUtils;
import org.flowable.app.service.api.ModelService;
import org.flowable.app.service.editor.FlowableModelQueryService;
import org.flowable.app.service.exception.ConflictingRequestException;
import org.flowable.app.service.exception.InternalServerErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
@RestController
public class ModelsResource {
private static final Logger LOGGER = LoggerFactory.getLogger(ModelsResource.class);
@Autowired
protected FlowableModelQueryService modelQueryService;
@Autowired
protected ModelService modelService;
@Autowired
protected ObjectMapper objectMapper;
@RequestMapping(value = "/rest/models", method = RequestMethod.GET, produces = "application/json")
public ResultListDataRepresentation getModels(@RequestParam(required = false) String filter, @RequestParam(required = false) String sort, @RequestParam(required = false) Integer modelType,
HttpServletRequest request) {
return modelQueryService.getModels(filter, sort, modelType, request);
}
@RequestMapping(value = "/rest/models-for-app-definition", method = RequestMethod.GET, produces = "application/json")
public ResultListDataRepresentation getModelsToIncludeInAppDefinition() {
return modelQueryService.getModelsToIncludeInAppDefinition();
}
@RequestMapping(value = "/rest/cmmn-models-for-app-definition", method = RequestMethod.GET, produces = "application/json")
public ResultListDataRepresentation getCmmnModelsToIncludeInAppDefinition() {
return modelQueryService.getCmmnModelsToIncludeInAppDefinition();
}
@RequestMapping(value = "/rest/import-process-model", method = RequestMethod.POST, produces = "application/json")
public ModelRepresentation importProcessModel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
return modelQueryService.importProcessModel(request, file);
}
/*
* specific endpoint for IE9 flash upload component
*/
@RequestMapping(value = "/rest/import-process-model/text", method = RequestMethod.POST)
public String importProcessModelText(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
ModelRepresentation modelRepresentation = modelQueryService.importProcessModel(request, file);
String modelRepresentationJson = null;
try {
modelRepresentationJson = objectMapper.writeValueAsString(modelRepresentation);
} catch (Exception e) {
LOGGER.error("Error while processing Model representation json", e);
throw new InternalServerErrorException("Model Representation could not be saved");
}
return modelRepresentationJson;
}
@RequestMapping(value = "/rest/import-case-model", method = RequestMethod.POST, produces = "application/json")
public ModelRepresentation importCaseModel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
return modelQueryService.importCaseModel(request, file);
}
/*
* specific endpoint for IE9 flash upload component
*/
@RequestMapping(value = "/rest/import-case-model/text", method = RequestMethod.POST)
public String importCaseModelText(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
ModelRepresentation modelRepresentation = modelQueryService.importCaseModel(request, file);
String modelRepresentationJson = null;
try {
modelRepresentationJson = objectMapper.writeValueAsString(modelRepresentation);
} catch (Exception e) {
LOGGER.error("Error while processing Model representation json", e);
throw new InternalServerErrorException("Model Representation could not be saved");
}
return modelRepresentationJson;
}
@RequestMapping(value = "/rest/models", method = RequestMethod.POST, produces = "application/json")
public ModelRepresentation createModel(@RequestBody ModelRepresentation modelRepresentation) {
modelRepresentation.setKey(modelRepresentation.getKey().replaceAll(" ", ""));
checkForDuplicateKey(modelRepresentation);
String json = modelService.createModelJson(modelRepresentation);
Model newModel = modelService.createModel(modelRepresentation, json, SecurityUtils.getCurrentUserObject());
return new ModelRepresentation(newModel);
}
protected void checkForDuplicateKey(ModelRepresentation modelRepresentation) {
ModelKeyRepresentation modelKeyInfo = modelService.validateModelKey(null, modelRepresentation.getModelType(), modelRepresentation.getKey());
if (modelKeyInfo.isKeyAlreadyExists()) {
throw new ConflictingRequestException("Provided model key already exists: " + modelRepresentation.getKey());
}
}
@RequestMapping(value = "/rest/models/{modelId}/clone", method = RequestMethod.POST, produces = "application/json")
public ModelRepresentation duplicateModel(@PathVariable String modelId, @RequestBody ModelRepresentation modelRepresentation) {
String json = null;
Model model = null;
if (modelId != null) {
model = modelService.getModel(modelId);
json = model.getModelEditorJson();
}
if (model == null) {
throw new InternalServerErrorException("Error duplicating model : Unknown original model");
}
modelRepresentation.setKey(modelRepresentation.getKey().replaceAll(" ", ""));
checkForDuplicateKey(modelRepresentation);
if (modelRepresentation.getModelType() == null || modelRepresentation.getModelType().equals(AbstractModel.MODEL_TYPE_BPMN)) {
// BPMN model
ObjectNode editorNode = null;
try {
ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(json);
editorNode = deleteEmbededReferencesFromBPMNModel(editorJsonNode);
ObjectNode propertiesNode = (ObjectNode) editorNode.get("properties");
String processId = modelRepresentation.getName().replaceAll(" ", "");
propertiesNode.put("process_id", processId);
propertiesNode.put("name", modelRepresentation.getName());
if (StringUtils.isNotEmpty(modelRepresentation.getDescription())) {
propertiesNode.put("documentation", modelRepresentation.getDescription());
}
editorNode.set("properties", propertiesNode);
} catch (IOException e) {
e.printStackTrace();
}
if (editorNode != null) {
json = editorNode.toString();
}
}
// create the new model
Model newModel = modelService.createModel(modelRepresentation, json, SecurityUtils.getCurrentUserObject());
// copy also the thumbnail
byte[] imageBytes = model.getThumbnail();
newModel = modelService.saveModel(newModel, newModel.getModelEditorJson(), imageBytes, false, newModel.getComment(), SecurityUtils.getCurrentUserObject());
return new ModelRepresentation(newModel);
}
protected ObjectNode deleteEmbededReferencesFromBPMNModel(ObjectNode editorJsonNode) {
try {
internalDeleteNodeByNameFromBPMNModel(editorJsonNode, "formreference");
internalDeleteNodeByNameFromBPMNModel(editorJsonNode, "subprocessreference");
return editorJsonNode;
} catch (Exception e) {
throw new InternalServerErrorException("Cannot delete the external references");
}
}
protected ObjectNode deleteEmbededReferencesFromStepModel(ObjectNode editorJsonNode) {
try {
JsonNode startFormNode = editorJsonNode.get("startForm");
if (startFormNode != null) {
editorJsonNode.remove("startForm");
}
internalDeleteNodeByNameFromStepModel(editorJsonNode.get("steps"), "formDefinition");
internalDeleteNodeByNameFromStepModel(editorJsonNode.get("steps"), "subProcessDefinition");
return editorJsonNode;
} catch (Exception e) {
throw new InternalServerErrorException("Cannot delete the external references");
}
}
protected void internalDeleteNodeByNameFromBPMNModel(JsonNode editorJsonNode, String propertyName) {
JsonNode childShapesNode = editorJsonNode.get("childShapes");
if (childShapesNode != null && childShapesNode.isArray()) {
ArrayNode childShapesArrayNode = (ArrayNode) childShapesNode;
for (JsonNode childShapeNode : childShapesArrayNode) {
// Properties
ObjectNode properties = (ObjectNode) childShapeNode.get("properties");
if (properties != null && properties.has(propertyName)) {
JsonNode propertyNode = properties.get(propertyName);
if (propertyNode != null) {
properties.remove(propertyName);
}
}
// Potential nested child shapes
if (childShapeNode.has("childShapes")) {
internalDeleteNodeByNameFromBPMNModel(childShapeNode, propertyName);
}
}
}
}
private void internalDeleteNodeByNameFromStepModel(JsonNode stepsNode, String propertyName) {
if (stepsNode == null || !stepsNode.isArray()) {
return;
}
for (JsonNode jsonNode : stepsNode) {
ObjectNode stepNode = (ObjectNode) jsonNode;
if (stepNode.has(propertyName)) {
JsonNode propertyNode = stepNode.get(propertyName);
if (propertyNode != null) {
stepNode.remove(propertyName);
}
}
// Nested steps
if (stepNode.has("steps")) {
internalDeleteNodeByNameFromStepModel(stepNode.get("steps"), propertyName);
}
// Overdue steps
if (stepNode.has("overdueSteps")) {
internalDeleteNodeByNameFromStepModel(stepNode.get("overdueSteps"), propertyName);
}
// Choices is special, can have nested steps inside
if (stepNode.has("choices")) {
ArrayNode choicesArrayNode = (ArrayNode) stepNode.get("choices");
for (JsonNode choiceNode : choicesArrayNode) {
if (choiceNode.has("steps")) {
internalDeleteNodeByNameFromStepModel(choiceNode.get("steps"), propertyName);
}
}
}
}
}
}
| apache-2.0 |
trangvh/elasticsearch | core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexService.java | 31912 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.cluster.metadata;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest;
import org.elasticsearch.cluster.AckedClusterStateUpdateTask;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ack.ClusterStateUpdateResponse;
import org.elasticsearch.cluster.block.ClusterBlock;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.metadata.IndexMetaData.Custom;
import org.elasticsearch.cluster.metadata.IndexMetaData.State;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardRoutingState;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.ValidationException;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.PathUtils;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.NodeServicesProvider;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.shard.DocsStats;
import org.elasticsearch.indices.IndexAlreadyExistsException;
import org.elasticsearch.indices.IndexCreationException;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.indices.InvalidIndexNameException;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_AUTO_EXPAND_REPLICAS;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_CREATION_DATE;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_INDEX_UUID;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_VERSION_CREATED;
/**
* Service responsible for submitting create index requests
*/
public class MetaDataCreateIndexService extends AbstractComponent {
public final static int MAX_INDEX_NAME_BYTES = 255;
private static final DefaultIndexTemplateFilter DEFAULT_INDEX_TEMPLATE_FILTER = new DefaultIndexTemplateFilter();
private final ClusterService clusterService;
private final IndicesService indicesService;
private final AllocationService allocationService;
private final Version version;
private final AliasValidator aliasValidator;
private final IndexTemplateFilter indexTemplateFilter;
private final Environment env;
private final NodeServicesProvider nodeServicesProvider;
private final IndexScopedSettings indexScopedSettings;
@Inject
public MetaDataCreateIndexService(Settings settings, ClusterService clusterService,
IndicesService indicesService, AllocationService allocationService,
Version version, AliasValidator aliasValidator,
Set<IndexTemplateFilter> indexTemplateFilters, Environment env, NodeServicesProvider nodeServicesProvider, IndexScopedSettings indexScopedSettings) {
super(settings);
this.clusterService = clusterService;
this.indicesService = indicesService;
this.allocationService = allocationService;
this.version = version;
this.aliasValidator = aliasValidator;
this.env = env;
this.nodeServicesProvider = nodeServicesProvider;
this.indexScopedSettings = indexScopedSettings;
if (indexTemplateFilters.isEmpty()) {
this.indexTemplateFilter = DEFAULT_INDEX_TEMPLATE_FILTER;
} else {
IndexTemplateFilter[] templateFilters = new IndexTemplateFilter[indexTemplateFilters.size() + 1];
templateFilters[0] = DEFAULT_INDEX_TEMPLATE_FILTER;
int i = 1;
for (IndexTemplateFilter indexTemplateFilter : indexTemplateFilters) {
templateFilters[i++] = indexTemplateFilter;
}
this.indexTemplateFilter = new IndexTemplateFilter.Compound(templateFilters);
}
}
public void validateIndexName(String index, ClusterState state) {
if (state.routingTable().hasIndex(index)) {
throw new IndexAlreadyExistsException(state.routingTable().index(index).getIndex());
}
if (state.metaData().hasIndex(index)) {
throw new IndexAlreadyExistsException(state.metaData().index(index).getIndex());
}
if (!Strings.validFileName(index)) {
throw new InvalidIndexNameException(index, "must not contain the following characters " + Strings.INVALID_FILENAME_CHARS);
}
if (index.contains("#")) {
throw new InvalidIndexNameException(index, "must not contain '#'");
}
if (index.charAt(0) == '_') {
throw new InvalidIndexNameException(index, "must not start with '_'");
}
if (!index.toLowerCase(Locale.ROOT).equals(index)) {
throw new InvalidIndexNameException(index, "must be lowercase");
}
int byteCount = 0;
try {
byteCount = index.getBytes("UTF-8").length;
} catch (UnsupportedEncodingException e) {
// UTF-8 should always be supported, but rethrow this if it is not for some reason
throw new ElasticsearchException("Unable to determine length of index name", e);
}
if (byteCount > MAX_INDEX_NAME_BYTES) {
throw new InvalidIndexNameException(index,
"index name is too long, (" + byteCount +
" > " + MAX_INDEX_NAME_BYTES + ")");
}
if (state.metaData().hasAlias(index)) {
throw new InvalidIndexNameException(index, "already exists as alias");
}
if (index.equals(".") || index.equals("..")) {
throw new InvalidIndexNameException(index, "must not be '.' or '..'");
}
}
public void createIndex(final CreateIndexClusterStateUpdateRequest request, final ActionListener<ClusterStateUpdateResponse> listener) {
Settings.Builder updatedSettingsBuilder = Settings.builder();
updatedSettingsBuilder.put(request.settings()).normalizePrefix(IndexMetaData.INDEX_SETTING_PREFIX);
indexScopedSettings.validate(updatedSettingsBuilder);
request.settings(updatedSettingsBuilder.build());
clusterService.submitStateUpdateTask("create-index [" + request.index() + "], cause [" + request.cause() + "]",
new AckedClusterStateUpdateTask<ClusterStateUpdateResponse>(Priority.URGENT, request, listener) {
@Override
protected ClusterStateUpdateResponse newResponse(boolean acknowledged) {
return new ClusterStateUpdateResponse(acknowledged);
}
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
Index createdIndex = null;
String removalReason = null;
try {
validate(request, currentState);
for (Alias alias : request.aliases()) {
aliasValidator.validateAlias(alias, request.index(), currentState.metaData());
}
// we only find a template when its an API call (a new index)
// find templates, highest order are better matching
List<IndexTemplateMetaData> templates = findTemplates(request, currentState, indexTemplateFilter);
Map<String, Custom> customs = new HashMap<>();
// add the request mapping
Map<String, Map<String, Object>> mappings = new HashMap<>();
Map<String, AliasMetaData> templatesAliases = new HashMap<>();
List<String> templateNames = new ArrayList<>();
for (Map.Entry<String, String> entry : request.mappings().entrySet()) {
mappings.put(entry.getKey(), MapperService.parseMapping(entry.getValue()));
}
for (Map.Entry<String, Custom> entry : request.customs().entrySet()) {
customs.put(entry.getKey(), entry.getValue());
}
// apply templates, merging the mappings into the request mapping if exists
for (IndexTemplateMetaData template : templates) {
templateNames.add(template.getName());
for (ObjectObjectCursor<String, CompressedXContent> cursor : template.mappings()) {
if (mappings.containsKey(cursor.key)) {
XContentHelper.mergeDefaults(mappings.get(cursor.key), MapperService.parseMapping(cursor.value.string()));
} else {
mappings.put(cursor.key, MapperService.parseMapping(cursor.value.string()));
}
}
// handle custom
for (ObjectObjectCursor<String, Custom> cursor : template.customs()) {
String type = cursor.key;
IndexMetaData.Custom custom = cursor.value;
IndexMetaData.Custom existing = customs.get(type);
if (existing == null) {
customs.put(type, custom);
} else {
IndexMetaData.Custom merged = existing.mergeWith(custom);
customs.put(type, merged);
}
}
//handle aliases
for (ObjectObjectCursor<String, AliasMetaData> cursor : template.aliases()) {
AliasMetaData aliasMetaData = cursor.value;
//if an alias with same name came with the create index request itself,
// ignore this one taken from the index template
if (request.aliases().contains(new Alias(aliasMetaData.alias()))) {
continue;
}
//if an alias with same name was already processed, ignore this one
if (templatesAliases.containsKey(cursor.key)) {
continue;
}
//Allow templatesAliases to be templated by replacing a token with the name of the index that we are applying it to
if (aliasMetaData.alias().contains("{index}")) {
String templatedAlias = aliasMetaData.alias().replace("{index}", request.index());
aliasMetaData = AliasMetaData.newAliasMetaData(aliasMetaData, templatedAlias);
}
aliasValidator.validateAliasMetaData(aliasMetaData, request.index(), currentState.metaData());
templatesAliases.put(aliasMetaData.alias(), aliasMetaData);
}
}
Settings.Builder indexSettingsBuilder = Settings.builder();
// apply templates, here, in reverse order, since first ones are better matching
for (int i = templates.size() - 1; i >= 0; i--) {
indexSettingsBuilder.put(templates.get(i).settings());
}
// now, put the request settings, so they override templates
indexSettingsBuilder.put(request.settings());
if (indexSettingsBuilder.get(SETTING_NUMBER_OF_SHARDS) == null) {
indexSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, settings.getAsInt(SETTING_NUMBER_OF_SHARDS, 5));
}
if (indexSettingsBuilder.get(SETTING_NUMBER_OF_REPLICAS) == null) {
indexSettingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 1));
}
if (settings.get(SETTING_AUTO_EXPAND_REPLICAS) != null && indexSettingsBuilder.get(SETTING_AUTO_EXPAND_REPLICAS) == null) {
indexSettingsBuilder.put(SETTING_AUTO_EXPAND_REPLICAS, settings.get(SETTING_AUTO_EXPAND_REPLICAS));
}
if (indexSettingsBuilder.get(SETTING_VERSION_CREATED) == null) {
DiscoveryNodes nodes = currentState.nodes();
final Version createdVersion = Version.smallest(version, nodes.getSmallestNonClientNodeVersion());
indexSettingsBuilder.put(SETTING_VERSION_CREATED, createdVersion);
}
if (indexSettingsBuilder.get(SETTING_CREATION_DATE) == null) {
indexSettingsBuilder.put(SETTING_CREATION_DATE, new DateTime(DateTimeZone.UTC).getMillis());
}
indexSettingsBuilder.put(SETTING_INDEX_UUID, UUIDs.randomBase64UUID());
final Index shrinkFromIndex = request.shrinkFrom();
if (shrinkFromIndex != null) {
prepareShrinkIndexSettings(currentState, mappings.keySet(), indexSettingsBuilder, shrinkFromIndex,
request.index());
}
Settings actualIndexSettings = indexSettingsBuilder.build();
// Set up everything, now locally create the index to see that things are ok, and apply
final IndexMetaData tmpImd = IndexMetaData.builder(request.index()).settings(actualIndexSettings).build();
// create the index here (on the master) to validate it can be created, as well as adding the mapping
final IndexService indexService = indicesService.createIndex(nodeServicesProvider, tmpImd, Collections.emptyList());
createdIndex = indexService.index();
// now add the mappings
MapperService mapperService = indexService.mapperService();
try {
mapperService.merge(mappings, request.updateAllTypes());
} catch (MapperParsingException mpe) {
removalReason = "failed on parsing default mapping/mappings on index creation";
throw mpe;
}
final QueryShardContext queryShardContext = indexService.newQueryShardContext();
for (Alias alias : request.aliases()) {
if (Strings.hasLength(alias.filter())) {
aliasValidator.validateAliasFilter(alias.name(), alias.filter(), queryShardContext);
}
}
for (AliasMetaData aliasMetaData : templatesAliases.values()) {
if (aliasMetaData.filter() != null) {
aliasValidator.validateAliasFilter(aliasMetaData.alias(), aliasMetaData.filter().uncompressed(), queryShardContext);
}
}
// now, update the mappings with the actual source
Map<String, MappingMetaData> mappingsMetaData = new HashMap<>();
for (DocumentMapper mapper : mapperService.docMappers(true)) {
MappingMetaData mappingMd = new MappingMetaData(mapper);
mappingsMetaData.put(mapper.type(), mappingMd);
}
final IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(request.index()).settings(actualIndexSettings);
for (MappingMetaData mappingMd : mappingsMetaData.values()) {
indexMetaDataBuilder.putMapping(mappingMd);
}
for (AliasMetaData aliasMetaData : templatesAliases.values()) {
indexMetaDataBuilder.putAlias(aliasMetaData);
}
for (Alias alias : request.aliases()) {
AliasMetaData aliasMetaData = AliasMetaData.builder(alias.name()).filter(alias.filter())
.indexRouting(alias.indexRouting()).searchRouting(alias.searchRouting()).build();
indexMetaDataBuilder.putAlias(aliasMetaData);
}
for (Map.Entry<String, Custom> customEntry : customs.entrySet()) {
indexMetaDataBuilder.putCustom(customEntry.getKey(), customEntry.getValue());
}
indexMetaDataBuilder.state(request.state());
final IndexMetaData indexMetaData;
try {
indexMetaData = indexMetaDataBuilder.build();
} catch (Exception e) {
removalReason = "failed to build index metadata";
throw e;
}
indexService.getIndexEventListener().beforeIndexAddedToCluster(indexMetaData.getIndex(),
indexMetaData.getSettings());
MetaData newMetaData = MetaData.builder(currentState.metaData())
.put(indexMetaData, false)
.build();
String maybeShadowIndicator = IndexMetaData.isIndexUsingShadowReplicas(indexMetaData.getSettings()) ? "s" : "";
logger.info("[{}] creating index, cause [{}], templates {}, shards [{}]/[{}{}], mappings {}",
request.index(), request.cause(), templateNames, indexMetaData.getNumberOfShards(),
indexMetaData.getNumberOfReplicas(), maybeShadowIndicator, mappings.keySet());
ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(currentState.blocks());
if (!request.blocks().isEmpty()) {
for (ClusterBlock block : request.blocks()) {
blocks.addIndexBlock(request.index(), block);
}
}
blocks.updateBlocks(indexMetaData);
ClusterState updatedState = ClusterState.builder(currentState).blocks(blocks).metaData(newMetaData).build();
if (request.state() == State.OPEN) {
RoutingTable.Builder routingTableBuilder = RoutingTable.builder(updatedState.routingTable())
.addAsNew(updatedState.metaData().index(request.index()));
RoutingAllocation.Result routingResult = allocationService.reroute(
ClusterState.builder(updatedState).routingTable(routingTableBuilder.build()).build(),
"index [" + request.index() + "] created");
updatedState = ClusterState.builder(updatedState).routingResult(routingResult).build();
}
removalReason = "cleaning up after validating index on master";
return updatedState;
} finally {
if (createdIndex != null) {
// Index was already partially created - need to clean up
indicesService.removeIndex(createdIndex, removalReason != null ? removalReason : "failed to create index");
}
}
}
});
}
private List<IndexTemplateMetaData> findTemplates(CreateIndexClusterStateUpdateRequest request, ClusterState state, IndexTemplateFilter indexTemplateFilter) throws IOException {
List<IndexTemplateMetaData> templates = new ArrayList<>();
for (ObjectCursor<IndexTemplateMetaData> cursor : state.metaData().templates().values()) {
IndexTemplateMetaData template = cursor.value;
if (indexTemplateFilter.apply(request, template)) {
templates.add(template);
}
}
CollectionUtil.timSort(templates, new Comparator<IndexTemplateMetaData>() {
@Override
public int compare(IndexTemplateMetaData o1, IndexTemplateMetaData o2) {
return o2.order() - o1.order();
}
});
return templates;
}
private void validate(CreateIndexClusterStateUpdateRequest request, ClusterState state) {
validateIndexName(request.index(), state);
validateIndexSettings(request.index(), request.settings());
}
public void validateIndexSettings(String indexName, Settings settings) throws IndexCreationException {
List<String> validationErrors = getIndexSettingsValidationErrors(settings);
if (validationErrors.isEmpty() == false) {
ValidationException validationException = new ValidationException();
validationException.addValidationErrors(validationErrors);
throw new IndexCreationException(indexName, validationException);
}
}
List<String> getIndexSettingsValidationErrors(Settings settings) {
String customPath = IndexMetaData.INDEX_DATA_PATH_SETTING.get(settings);
List<String> validationErrors = new ArrayList<>();
if (Strings.isEmpty(customPath) == false && env.sharedDataFile() == null) {
validationErrors.add("path.shared_data must be set in order to use custom data paths");
} else if (Strings.isEmpty(customPath) == false) {
Path resolvedPath = PathUtils.get(new Path[]{env.sharedDataFile()}, customPath);
if (resolvedPath == null) {
validationErrors.add("custom path [" + customPath + "] is not a sub-path of path.shared_data [" + env.sharedDataFile() + "]");
}
}
//norelease - this can be removed?
Integer number_of_primaries = settings.getAsInt(IndexMetaData.SETTING_NUMBER_OF_SHARDS, null);
Integer number_of_replicas = settings.getAsInt(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, null);
if (number_of_primaries != null && number_of_primaries <= 0) {
validationErrors.add("index must have 1 or more primary shards");
}
if (number_of_replicas != null && number_of_replicas < 0) {
validationErrors.add("index must have 0 or more replica shards");
}
return validationErrors;
}
private static class DefaultIndexTemplateFilter implements IndexTemplateFilter {
@Override
public boolean apply(CreateIndexClusterStateUpdateRequest request, IndexTemplateMetaData template) {
return Regex.simpleMatch(template.template(), request.index());
}
}
/**
* Validates the settings and mappings for shrinking an index.
* @return the list of nodes at least one instance of the source index shards are allocated
*/
static List<String> validateShrinkIndex(ClusterState state, String sourceIndex,
Set<String> targetIndexMappingsTypes, String targetIndexName,
Settings targetIndexSettings) {
if (state.metaData().hasIndex(targetIndexName)) {
throw new IndexAlreadyExistsException(state.metaData().index(targetIndexName).getIndex());
}
final IndexMetaData sourceMetaData = state.metaData().index(sourceIndex);
if (sourceMetaData == null) {
throw new IndexNotFoundException(sourceIndex);
}
// ensure index is read-only
if (state.blocks().indexBlocked(ClusterBlockLevel.WRITE, sourceIndex) == false) {
throw new IllegalStateException("index " + sourceIndex + " must be read-only to shrink index. use \"index.blocks.write=true\"");
}
if (sourceMetaData.getNumberOfShards() == 1) {
throw new IllegalArgumentException("can't shrink an index with only one shard");
}
if ((targetIndexMappingsTypes.size() > 1 ||
(targetIndexMappingsTypes.isEmpty() || targetIndexMappingsTypes.contains(MapperService.DEFAULT_MAPPING)) == false)) {
throw new IllegalArgumentException("mappings are not allowed when shrinking indices" +
", all mappings are copied from the source index");
}
if (IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING.exists(targetIndexSettings)
&& IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING.get(targetIndexSettings) > 1) {
throw new IllegalArgumentException("can not shrink index into more than one shard");
}
// now check that index is all on one node
final IndexRoutingTable table = state.routingTable().index(sourceIndex);
Map<String, AtomicInteger> nodesToNumRouting = new HashMap<>();
int numShards = sourceMetaData.getNumberOfShards();
for (ShardRouting routing : table.shardsWithState(ShardRoutingState.STARTED)) {
nodesToNumRouting.computeIfAbsent(routing.currentNodeId(), (s) -> new AtomicInteger(0)).incrementAndGet();
}
List<String> nodesToAllocateOn = new ArrayList<>();
for (Map.Entry<String, AtomicInteger> entries : nodesToNumRouting.entrySet()) {
int numAllocations = entries.getValue().get();
assert numAllocations <= numShards : "wait what? " + numAllocations + " is > than num shards " + numShards;
if (numAllocations == numShards) {
nodesToAllocateOn.add(entries.getKey());
}
}
if (nodesToAllocateOn.isEmpty()) {
throw new IllegalStateException("index " + sourceIndex +
" must have all shards allocated on the same node to shrink index");
}
return nodesToAllocateOn;
}
static void prepareShrinkIndexSettings(ClusterState currentState, Set<String> mappingKeys, Settings.Builder indexSettingsBuilder, Index shrinkFromIndex, String shrinkIntoName) {
final IndexMetaData sourceMetaData = currentState.metaData().index(shrinkFromIndex.getName());
final List<String> nodesToAllocateOn = validateShrinkIndex(currentState, shrinkFromIndex.getName(),
mappingKeys, shrinkIntoName, indexSettingsBuilder.build());
final Predicate<String> analysisSimilarityPredicate = (s) -> s.startsWith("index.similarity.")
|| s.startsWith("index.analysis.");
indexSettingsBuilder
// we can only shrink to 1 shard so far!
.put("index.number_of_shards", 1)
// we use "i.r.a.initial_recovery" rather than "i.r.a.require|include" since we want the replica to allocate right away
// once we are allocated.
.put("index.routing.allocation.initial_recovery._id",
Strings.arrayToCommaDelimitedString(nodesToAllocateOn.toArray()))
// we only try once and then give up with a shrink index
.put("index.allocation.max_retries", 1)
// now copy all similarity / analysis settings - this overrides all settings from the user unless they
// wanna add extra settings
.put(sourceMetaData.getSettings().filter(analysisSimilarityPredicate))
.put(IndexMetaData.INDEX_SHRINK_SOURCE_NAME.getKey(), shrinkFromIndex.getName())
.put(IndexMetaData.INDEX_SHRINK_SOURCE_UUID.getKey(), shrinkFromIndex.getUUID());
}
}
| apache-2.0 |
sarvex/guava | guava/src/com/google/common/base/Preconditions.java | 19475 | /*
* Copyright (C) 2007 The Guava 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.common.base;
import com.google.common.annotations.GwtCompatible;
import javax.annotation.Nullable;
/**
* Static convenience methods that help a method or constructor check whether it was invoked
* correctly (whether its <i>preconditions</i> have been met). These methods generally accept a
* {@code boolean} expression which is expected to be {@code true} (or in the case of {@code
* checkNotNull}, an object reference which is expected to be non-null). When {@code false} (or
* {@code null}) is passed instead, the {@code Preconditions} method throws an unchecked exception,
* which helps the calling method communicate to <i>its</i> caller that <i>that</i> caller has made
* a mistake. Example: <pre> {@code
*
* /**
* * Returns the positive square root of the given value.
* *
* * @throws IllegalArgumentException if the value is negative
* *}{@code /
* public static double sqrt(double value) {
* Preconditions.checkArgument(value >= 0.0, "negative value: %s", value);
* // calculate the square root
* }
*
* void exampleBadCaller() {
* double d = sqrt(-1.0);
* }}</pre>
*
* In this example, {@code checkArgument} throws an {@code IllegalArgumentException} to indicate
* that {@code exampleBadCaller} made an error in <i>its</i> call to {@code sqrt}.
*
* <h3>Warning about performance</h3>
*
* <p>The goal of this class is to improve readability of code, but in some circumstances this may
* come at a significant performance cost. Remember that parameter values for message construction
* must all be computed eagerly, and autoboxing and varargs array creation may happen as well, even
* when the precondition check then succeeds (as it should almost always do in production). In some
* circumstances these wasted CPU cycles and allocations can add up to a real problem.
* Performance-sensitive precondition checks can always be converted to the customary form:
* <pre> {@code
*
* if (value < 0.0) {
* throw new IllegalArgumentException("negative value: " + value);
* }}</pre>
*
* <h3>Other types of preconditions</h3>
*
* <p>Not every type of precondition failure is supported by these methods. Continue to throw
* standard JDK exceptions such as {@link java.util.NoSuchElementException} or {@link
* UnsupportedOperationException} in the situations they are intended for.
*
* <h3>Non-preconditions</h3>
*
* <p>It is of course possible to use the methods of this class to check for invalid conditions
* which are <i>not the caller's fault</i>. Doing so is <b>not recommended</b> because it is
* misleading to future readers of the code and of stack traces. See
* <a href="http://code.google.com/p/guava-libraries/wiki/ConditionalFailuresExplained">Conditional
* failures explained</a> in the Guava User Guide for more advice.
*
* <h3>{@code java.util.Objects.requireNonNull()}</h3>
*
* <p>Projects which use {@code com.google.common} should generally avoid the use of {@link
* java.util.Objects#requireNonNull(Object)}. Instead, use whichever of {@link
* #checkNotNull(Object)} or {@link Verify#verifyNotNull(Object)} is appropriate to the situation.
* (The same goes for the message-accepting overloads.)
*
* <h3>Only {@code %s} is supported</h3>
*
* <p>In {@code Preconditions} error message template strings, only the {@code "%s"} specifier is
* supported, not the full range of {@link java.util.Formatter} specifiers.
*
* <h3>More information</h3>
*
* <p>See the Guava User Guide on
* <a href="http://code.google.com/p/guava-libraries/wiki/PreconditionsExplained">using {@code
* Preconditions}</a>.
*
* @author Kevin Bourrillion
* @since 2.0
*/
@GwtCompatible
public final class Preconditions {
private Preconditions() {}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message
* in square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @throws IllegalArgumentException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or
* {@code errorMessageArgs} is null (don't let this happen)
*/
public static void checkArgument(
boolean expression,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message
* in square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @throws IllegalStateException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or
* {@code errorMessageArgs} is null (don't let this happen)
*/
public static void checkState(
boolean expression,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message
* in square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(
T reference, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) {
if (reference == null) {
// If either of these parameters is null, the right thing happens anyway
throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs));
}
return reference;
}
/*
* All recent hotspots (as of 2009) *really* like to have the natural code
*
* if (guardExpression) {
* throw new BadException(messageExpression);
* }
*
* refactored so that messageExpression is moved to a separate String-returning method.
*
* if (guardExpression) {
* throw new BadException(badMsg(...));
* }
*
* The alternative natural refactorings into void or Exception-returning methods are much slower.
* This is a big deal - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This
* is a hotspot optimizer bug, which should be fixed, but that's a separate, big project).
*
* The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a
* RangeCheckMicroBenchmark in the JDK that was used to test this.
*
* But the methods in this class want to throw different exceptions, depending on the args, so it
* appears that this pattern is not directly applicable. But we can use the ridiculous, devious
* trick of throwing an exception in the middle of the construction of another exception. Hotspot
* is fine with that.
*/
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size
* {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list or string
* @param size the size of that array, list or string
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkElementIndex(int index, int size) {
return checkElementIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size
* {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkElementIndex(int index, int size, @Nullable String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(badElementIndex(index, size, desc));
}
return index;
}
private static String badElementIndex(int index, int size, String desc) {
if (index < 0) {
return format("%s (%s) must not be negative", desc, index);
} else if (size < 0) {
throw new IllegalArgumentException("negative size: " + size);
} else { // index >= size
return format("%s (%s) must be less than size (%s)", desc, index, size);
}
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of
* size {@code size}. A position index may range from zero to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list or string
* @param size the size of that array, list or string
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkPositionIndex(int index, int size) {
return checkPositionIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of
* size {@code size}. A position index may range from zero to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkPositionIndex(int index, int size, @Nullable String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc));
}
return index;
}
private static String badPositionIndex(int index, int size, String desc) {
if (index < 0) {
return format("%s (%s) must not be negative", desc, index);
} else if (size < 0) {
throw new IllegalArgumentException("negative size: " + size);
} else { // index > size
return format("%s (%s) must not be greater than size (%s)", desc, index, size);
}
}
/**
* Ensures that {@code start} and {@code end} specify a valid <i>positions</i> in an array, list
* or string of size {@code size}, and are in order. A position index may range from zero to
* {@code size}, inclusive.
*
* @param start a user-supplied index identifying a starting position in an array, list or string
* @param end a user-supplied index identifying a ending position in an array, list or string
* @param size the size of that array, list or string
* @throws IndexOutOfBoundsException if either index is negative or is greater than {@code size},
* or if {@code end} is less than {@code start}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkPositionIndexes(int start, int end, int size) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (start < 0 || end < start || end > size) {
throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size));
}
}
private static String badPositionIndexes(int start, int end, int size) {
if (start < 0 || start > size) {
return badPositionIndex(start, size, "start index");
}
if (end < 0 || end > size) {
return badPositionIndex(end, size, "end index");
}
// end < start
return format("end index (%s) must not be less than start index (%s)", end, start);
}
/**
* Substitutes each {@code %s} in {@code template} with an argument. These are matched by
* position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than
* placeholders, the unmatched arguments will be appended to the end of the formatted message in
* square braces.
*
* @param template a non-null string containing 0 or more {@code %s} placeholders.
* @param args the arguments to be substituted into the message template. Arguments are converted
* to strings using {@link String#valueOf(Object)}. Arguments can be null.
*/
// Note that this is somewhat-improperly used from Verify.java as well.
static String format(String template, @Nullable Object... args) {
template = String.valueOf(template); // null -> "null"
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
}
| apache-2.0 |
spinnaker/kayenta | kayenta-google/src/main/java/com/netflix/kayenta/google/security/GoogleNamedAccountCredentials.java | 1645 | /*
* Copyright 2017 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.kayenta.google.security;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.api.services.monitoring.v3.Monitoring;
import com.google.api.services.storage.Storage;
import com.netflix.kayenta.security.AccountCredentials;
import java.util.List;
import javax.validation.constraints.NotNull;
import lombok.Builder;
import lombok.Data;
import lombok.Singular;
@Builder
@Data
public class GoogleNamedAccountCredentials implements AccountCredentials<GoogleClientFactory> {
@NotNull private String name;
@NotNull @Singular private List<Type> supportedTypes;
@NotNull private GoogleClientFactory credentials;
@NotNull private String project;
private String bucket;
private String bucketLocation;
private String rootFolder;
@Override
public String getType() {
return "google";
}
public String getMetricsStoreType() {
return supportedTypes.contains(Type.METRICS_STORE) ? "stackdriver" : null;
}
@JsonIgnore private Monitoring monitoring;
@JsonIgnore private Storage storage;
}
| apache-2.0 |