repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
spoilt-exile/RibbonSystem
src/java/org/ribbon/commands/ComLogout.java
2021
/* * Copyright (C) 2014 Stanislav Nepochatov * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.ribbon.commands; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.ribbon.controller.Router; import javax.persistence.*; import org.ribbon.jpa.JPAManager; import org.ribbon.jpa.enteties.*; /** * LOGOUT command (for exit from the system). * @author Stanislav Nepochatov */ public class ComLogout implements Command{ @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { EntityManager em = JPAManager.getEntityManager(); TypedQuery<User> qr = em.createNamedQuery("User.findByLogin", User.class); qr.setParameter("login", request.getSession().getAttribute("username")); User findedUser = qr.getSingleResult(); EntityTransaction tr = em.getTransaction(); tr.begin(); if (findedUser != null) { findedUser.setIsActive(false); request.getSession().removeAttribute("username"); } tr.commit(); em.close(); return Router.DEFAULT_PAGE; } @Override public Boolean isAuthRequired() { return true; } }
gpl-2.0
biddyweb/checker-framework
checker/jdk/nullness/src/java/lang/Class.java
7450
package java.lang; import org.checkerframework.dataflow.qual.Pure; import org.checkerframework.dataflow.qual.SideEffectFree; import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.PolyNull; public final class Class<T extends @Nullable Object> extends Object implements java.io.Serializable, java.lang.reflect.GenericDeclaration, java.lang.reflect.Type, java.lang.reflect.AnnotatedElement { private static final long serialVersionUID = 0; protected Class() {} @SideEffectFree public String toString() { throw new RuntimeException("skeleton method"); } public static Class<?> forName(String a1) throws ClassNotFoundException { throw new RuntimeException("skeleton method"); } public static Class<?> forName(String a1, boolean a2, @Nullable ClassLoader a3) throws ClassNotFoundException { throw new RuntimeException("skeleton method"); } public @NonNull T newInstance() throws InstantiationException, IllegalAccessException { throw new RuntimeException("skeleton method"); } @Pure public boolean isAnnotation() { throw new RuntimeException("skeleton method"); } @Pure public native boolean isInstance(@Nullable Object a1); @Pure public boolean isSynthetic() { throw new RuntimeException("skeleton method"); } public String getName() { throw new RuntimeException("skeleton method"); } public @Nullable ClassLoader getClassLoader() { throw new RuntimeException("skeleton method"); } public java.lang.reflect.TypeVariable<Class<T>>[] getTypeParameters() { throw new RuntimeException("skeleton method"); } public java.lang.reflect. @Nullable Type getGenericSuperclass() { throw new RuntimeException("skeleton method"); } @Pure public @Nullable Package getPackage() { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Type[] getGenericInterfaces() { throw new RuntimeException("skeleton method"); } public java.lang.reflect. @Nullable Method getEnclosingMethod() { throw new RuntimeException("skeleton method"); } public java.lang.reflect. @Nullable Constructor<?> getEnclosingConstructor() { throw new RuntimeException("skeleton method"); } public @Nullable Class<?> getEnclosingClass() { throw new RuntimeException("skeleton method"); } public String getSimpleName() { throw new RuntimeException("skeleton method"); } @Pure public native @Nullable Class<? super T> getSuperclass(); @Pure public native Class<?>[] getInterfaces(); public @Nullable String getCanonicalName() { throw new RuntimeException("skeleton method"); } @Pure public boolean isAnonymousClass() { throw new RuntimeException("skeleton method"); } @Pure public boolean isLocalClass() { throw new RuntimeException("skeleton method"); } @Pure public boolean isMemberClass() { throw new RuntimeException("skeleton method"); } public Class<?>[] getClasses() { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Field[] getFields() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Method[] getMethods() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Constructor<?>[] getConstructors() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Field getField(String a1) throws NoSuchFieldException, SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Method getMethod(String a1, Class<?> @Nullable ... a2) throws NoSuchMethodException, SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Constructor<T> getConstructor(Class<?>... a1) throws NoSuchMethodException, SecurityException { throw new RuntimeException("skeleton method"); } public Class<?>[] getDeclaredClasses() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Field[] getDeclaredFields() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Method[] getDeclaredMethods() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Constructor<?>[] getDeclaredConstructors() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Field getDeclaredField(String a1) throws NoSuchFieldException, SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Method getDeclaredMethod(String a1, Class<?>... a2) throws NoSuchMethodException, SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Constructor<T> getDeclaredConstructor(Class<?>... a1) throws NoSuchMethodException, SecurityException { throw new RuntimeException("skeleton method"); } public java.io. @Nullable InputStream getResourceAsStream(String a1) { throw new RuntimeException("skeleton method"); } public java.net. @Nullable URL getResource(String a1) { throw new RuntimeException("skeleton method"); } public java.security.ProtectionDomain getProtectionDomain() { throw new RuntimeException("skeleton method"); } public boolean desiredAssertionStatus() { throw new RuntimeException("skeleton method"); } @Pure public boolean isEnum() { throw new RuntimeException("skeleton method"); } public T @Nullable [] getEnumConstants() { throw new RuntimeException("skeleton method"); } java.util.Map<String, T> enumConstantDirectory() { throw new RuntimeException("skeleton method"); } public @PolyNull T cast(@PolyNull Object a1) { throw new RuntimeException("skeleton method"); } public <U> Class<? extends U> asSubclass(Class<U> a1) { throw new RuntimeException("skeleton method"); } public <A extends java.lang.annotation.Annotation> @Nullable A getAnnotation(Class<A> a1) { throw new RuntimeException("skeleton method"); } @Pure public boolean isAnnotationPresent(Class<? extends java.lang.annotation.Annotation> a1) { throw new RuntimeException("skeleton method"); } public java.lang.annotation.Annotation[] getAnnotations() { throw new RuntimeException("skeleton method"); } public java.lang.annotation.Annotation[] getDeclaredAnnotations() { throw new RuntimeException("skeleton method"); } @Pure public native @Nullable Class<?> getComponentType(); public native Object @Nullable [] getSigners(); public native @Nullable Class<?> getDeclaringClass(); @Pure public native boolean isPrimitive(); @EnsuresNonNullIf(expression="getComponentType()", result=true) @Pure public native boolean isArray(); @Pure public native boolean isAssignableFrom(Class<? extends @Nullable Object> cls); @Pure public native boolean isInterface(); @Pure public native int getModifiers(); @Pure public boolean isTypeAnnotationPresent(Class<? extends java.lang.annotation.Annotation> annotationClass) { throw new RuntimeException("skeleton method"); } public <T extends java.lang.annotation.Annotation> T getTypeAnnotation(Class<T> annotationClass) { throw new RuntimeException("skeleton method"); } public java.lang.annotation.Annotation[] getTypeAnnotations() { throw new RuntimeException("skeleton method"); } public java.lang.annotation.Annotation[] getDeclaredTypeAnnotations() { throw new RuntimeException("skeleton method"); } }
gpl-2.0
aktion-hip/vif
org.hip.vif.web/src/org/hip/vif/web/exc/VIFExceptionHandler.java
3265
/** This package is part of the application VIF. Copyright (C) 2012-2014, Benno Luthiger This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.hip.vif.web.exc; import org.hip.kernel.exc.ExceptionHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Handler for VIF exceptions. * * @author lbenno */ public enum VIFExceptionHandler implements ExceptionHandler { INSTANCE; private static final Logger LOG = LoggerFactory .getLogger(VIFExceptionHandler.class); @Override public Throwable convert(final Throwable inThrowable) { return postProcess(inThrowable, new VIFWebException()); } @Override public Throwable convert(final Throwable inThrowable, final String inMessage) { return postProcess(inThrowable, new VIFWebException(inMessage)); } @Override public void handle(final Object inCatchingObject, final Throwable inThrowable) { printStackTrace(inCatchingObject, inThrowable); } @Override public void handle(final Object inCatchingObject, final Throwable inThrowable, final boolean inPrintStackTrace) { if (inPrintStackTrace) { printStackTrace(inCatchingObject, inThrowable); } } private void printStackTrace(final Object inCatchingObject, final Throwable inThrowable) { LOG.error("VIF application: Error catched in {}.", inCatchingObject .getClass().getName(), inThrowable); } private void printStackTrace(final Throwable inThrowable) { LOG.error("VIF application: Error handled:", inThrowable); } @Override public void handle(final Throwable inThrowable) { printStackTrace(inThrowable); } @Override public void handle(final Throwable inThrowable, final boolean inPrintStackTrace) { if (inPrintStackTrace) { printStackTrace(inThrowable); } } @Override public void rethrow(final Throwable inThrowable) throws Throwable { LOG.error("VIF application: Error rethrow:", inThrowable); throw inThrowable; } /** @param inThrowableToBeConverted java.lang.Throwable * @param inException org.hip.kernel.exc.VException * @return java.lang.Throwable */ private Throwable postProcess(final Throwable inThrowableToBeConverted, final VIFWebException inException) { LOG.error("Root cause:", inThrowableToBeConverted); inException.setRootCause(inThrowableToBeConverted); inException.fillInStackTrace(); return inException; } }
gpl-2.0
sungsoo/esper
esper/src/test/java/com/espertech/esper/regression/epl/TestSubselectIndex.java
12082
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.regression.epl; import com.espertech.esper.client.Configuration; import com.espertech.esper.client.EPServiceProvider; import com.espertech.esper.client.EPServiceProviderManager; import com.espertech.esper.client.EPStatement; import com.espertech.esper.client.annotation.Hint; import com.espertech.esper.client.scopetest.EPAssertionUtil; import com.espertech.esper.client.scopetest.SupportUpdateListener; import com.espertech.esper.support.bean.SupportBean; import com.espertech.esper.support.bean.SupportBean_S0; import com.espertech.esper.support.bean.SupportSimpleBeanOne; import com.espertech.esper.support.bean.SupportSimpleBeanTwo; import com.espertech.esper.support.client.SupportConfigFactory; import com.espertech.esper.support.epl.SupportQueryPlanIndexHook; import com.espertech.esper.support.util.IndexAssertionEventSend; import com.espertech.esper.support.util.IndexBackingTableInfo; import junit.framework.TestCase; public class TestSubselectIndex extends TestCase implements IndexBackingTableInfo { private EPServiceProvider epService; private SupportUpdateListener listener; public void setUp() { Configuration config = SupportConfigFactory.getConfiguration(); config.getEngineDefaults().getLogging().setEnableQueryPlan(true); epService = EPServiceProviderManager.getDefaultProvider(config); epService.initialize(); listener = new SupportUpdateListener(); } protected void tearDown() throws Exception { listener = null; } public void testIndexChoicesOverdefinedWhere() { epService.getEPAdministrator().getConfiguration().addEventType("SSB1", SupportSimpleBeanOne.class); epService.getEPAdministrator().getConfiguration().addEventType("SSB2", SupportSimpleBeanTwo.class); // test no where clause with unique IndexAssertionEventSend assertNoWhere = new IndexAssertionEventSend() { public void run() { String[] fields = "c0,c1".split(","); epService.getEPRuntime().sendEvent(new SupportSimpleBeanTwo("E1", 1, 2, 3)); epService.getEPRuntime().sendEvent(new SupportSimpleBeanOne("EX", 10, 11, 12)); EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[]{"EX", "E1"}); epService.getEPRuntime().sendEvent(new SupportSimpleBeanTwo("E2", 1, 2, 3)); epService.getEPRuntime().sendEvent(new SupportSimpleBeanOne("EY", 10, 11, 12)); EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[]{"EY", null}); } }; runAssertion(false, "s2,i2", "", BACKING_UNINDEXED, assertNoWhere); // test no where clause with unique on multiple props, exact specification of where-clause IndexAssertionEventSend assertSendEvents = new IndexAssertionEventSend() { public void run() { String[] fields = "c0,c1".split(","); epService.getEPRuntime().sendEvent(new SupportSimpleBeanTwo("E1", 1, 3, 10)); epService.getEPRuntime().sendEvent(new SupportSimpleBeanTwo("E2", 1, 2, 0)); epService.getEPRuntime().sendEvent(new SupportSimpleBeanTwo("E3", 1, 3, 9)); epService.getEPRuntime().sendEvent(new SupportSimpleBeanOne("EX", 1, 3, 9)); EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[]{"EX", "E3"}); } }; runAssertion(false, "d2,i2", "where ssb2.i2 = ssb1.i1 and ssb2.d2 = ssb1.d1", BACKING_MULTI_UNIQUE, assertSendEvents); runAssertion(false, "d2,i2", "where ssb2.d2 = ssb1.d1 and ssb2.i2 = ssb1.i1", BACKING_MULTI_UNIQUE, assertSendEvents); runAssertion(false, "d2,i2", "where ssb2.l2 = ssb1.l1 and ssb2.d2 = ssb1.d1 and ssb2.i2 = ssb1.i1", BACKING_MULTI_UNIQUE, assertSendEvents); runAssertion(false, "d2,i2", "where ssb2.l2 = ssb1.l1 and ssb2.i2 = ssb1.i1", BACKING_MULTI_DUPS, assertSendEvents); runAssertion(false, "d2,i2", "where ssb2.d2 = ssb1.d1", BACKING_SINGLE_DUPS, assertSendEvents); runAssertion(false, "d2,i2", "where ssb2.i2 = ssb1.i1 and ssb2.d2 = ssb1.d1 and ssb2.l2 between 1 and 1000", BACKING_MULTI_UNIQUE, assertSendEvents); runAssertion(false, "d2,i2", "where ssb2.d2 = ssb1.d1 and ssb2.l2 between 1 and 1000", BACKING_COMPOSITE, assertSendEvents); runAssertion(false, "i2,d2,l2", "where ssb2.l2 = ssb1.l1 and ssb2.d2 = ssb1.d1", BACKING_MULTI_DUPS, assertSendEvents); runAssertion(false, "i2,d2,l2", "where ssb2.l2 = ssb1.l1 and ssb2.i2 = ssb1.i1 and ssb2.d2 = ssb1.d1", BACKING_MULTI_UNIQUE, assertSendEvents); runAssertion(false, "d2,l2,i2", "where ssb2.l2 = ssb1.l1 and ssb2.i2 = ssb1.i1 and ssb2.d2 = ssb1.d1", BACKING_MULTI_UNIQUE, assertSendEvents); runAssertion(false, "d2,l2,i2", "where ssb2.l2 = ssb1.l1 and ssb2.i2 = ssb1.i1 and ssb2.d2 = ssb1.d1 and ssb2.s2 between 'E3' and 'E4'", BACKING_MULTI_UNIQUE, assertSendEvents); runAssertion(false, "l2", "where ssb2.l2 = ssb1.l1", BACKING_SINGLE_UNIQUE, assertSendEvents); runAssertion(true, "l2", "where ssb2.l2 = ssb1.l1", BACKING_SINGLE_DUPS, assertSendEvents); runAssertion(false, "l2", "where ssb2.l2 = ssb1.l1 and ssb1.i1 between 1 and 20", BACKING_SINGLE_UNIQUE, assertSendEvents); } private void runAssertion(boolean disableImplicitUniqueIdx, String uniqueFields, String whereClause, String backingTable, IndexAssertionEventSend assertion) { String eplUnique = INDEX_CALLBACK_HOOK + "select s1 as c0, " + "(select s2 from SSB2.std:unique(" + uniqueFields + ") as ssb2 " + whereClause + ") as c1 " + "from SSB1 as ssb1"; if (disableImplicitUniqueIdx) { eplUnique = "@Hint('DISABLE_UNIQUE_IMPLICIT_IDX')" + eplUnique; } EPStatement stmtUnique = epService.getEPAdministrator().createEPL(eplUnique); stmtUnique.addListener(listener); SupportQueryPlanIndexHook.assertSubqueryAndReset(0, null, backingTable); assertion.run(); stmtUnique.destroy(); } public void testUniqueIndexCorrelated() { epService.getEPAdministrator().getConfiguration().addEventType("SupportBean", SupportBean.class); epService.getEPAdministrator().getConfiguration().addEventType("S0", SupportBean_S0.class); String[] fields = "c0,c1".split(","); // test std:unique String eplUnique = INDEX_CALLBACK_HOOK + "select id as c0, " + "(select intPrimitive from SupportBean.std:unique(theString) where theString = s0.p00) as c1 " + "from S0 as s0"; EPStatement stmtUnique = epService.getEPAdministrator().createEPL(eplUnique); stmtUnique.addListener(listener); SupportQueryPlanIndexHook.assertSubqueryAndReset(0, null, BACKING_SINGLE_UNIQUE); epService.getEPRuntime().sendEvent(new SupportBean("E1", 1)); epService.getEPRuntime().sendEvent(new SupportBean("E2", 2)); epService.getEPRuntime().sendEvent(new SupportBean("E1", 3)); epService.getEPRuntime().sendEvent(new SupportBean("E2", 4)); epService.getEPRuntime().sendEvent(new SupportBean_S0(10, "E2")); EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[] {10, 4}); epService.getEPRuntime().sendEvent(new SupportBean_S0(11, "E1")); EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[]{11, 3}); stmtUnique.destroy(); // test std:firstunique String eplFirstUnique = INDEX_CALLBACK_HOOK + "select id as c0, " + "(select intPrimitive from SupportBean.std:firstunique(theString) where theString = s0.p00) as c1 " + "from S0 as s0"; EPStatement stmtFirstUnique = epService.getEPAdministrator().createEPL(eplFirstUnique); stmtFirstUnique.addListener(listener); SupportQueryPlanIndexHook.assertSubqueryAndReset(0, null, BACKING_SINGLE_UNIQUE); epService.getEPRuntime().sendEvent(new SupportBean("E1", 1)); epService.getEPRuntime().sendEvent(new SupportBean("E2", 2)); epService.getEPRuntime().sendEvent(new SupportBean("E1", 3)); epService.getEPRuntime().sendEvent(new SupportBean("E2", 4)); epService.getEPRuntime().sendEvent(new SupportBean_S0(10, "E2")); EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[] {10, 2}); epService.getEPRuntime().sendEvent(new SupportBean_S0(11, "E1")); EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[]{11, 1}); stmtFirstUnique.destroy(); // test intersection std:firstunique String eplIntersection = INDEX_CALLBACK_HOOK + "select id as c0, " + "(select intPrimitive from SupportBean.win:time(1).std:unique(theString) where theString = s0.p00) as c1 " + "from S0 as s0"; EPStatement stmtIntersection = epService.getEPAdministrator().createEPL(eplIntersection); stmtIntersection.addListener(listener); SupportQueryPlanIndexHook.assertSubqueryAndReset(0, null, BACKING_SINGLE_UNIQUE); epService.getEPRuntime().sendEvent(new SupportBean("E1", 1)); epService.getEPRuntime().sendEvent(new SupportBean("E1", 2)); epService.getEPRuntime().sendEvent(new SupportBean("E1", 3)); epService.getEPRuntime().sendEvent(new SupportBean("E2", 4)); epService.getEPRuntime().sendEvent(new SupportBean_S0(10, "E2")); EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[] {10, 4}); epService.getEPRuntime().sendEvent(new SupportBean_S0(11, "E1")); EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[]{11, 3}); stmtIntersection.destroy(); // test grouped unique String eplGrouped = INDEX_CALLBACK_HOOK + "select id as c0, " + "(select longPrimitive from SupportBean.std:groupwin(theString).std:unique(intPrimitive) where theString = s0.p00 and intPrimitive = s0.id) as c1 " + "from S0 as s0"; EPStatement stmtGrouped = epService.getEPAdministrator().createEPL(eplGrouped); stmtGrouped.addListener(listener); SupportQueryPlanIndexHook.assertSubqueryAndReset(0, null, BACKING_MULTI_UNIQUE); epService.getEPRuntime().sendEvent(makeBean("E1", 1, 100)); epService.getEPRuntime().sendEvent(makeBean("E1", 2, 101)); epService.getEPRuntime().sendEvent(makeBean("E1", 1, 102)); epService.getEPRuntime().sendEvent(new SupportBean_S0(1, "E1")); EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[] {1, 102L}); stmtGrouped.destroy(); } private SupportBean makeBean(String theString, int intPrimitive, long longPrimitive) { SupportBean bean = new SupportBean(theString, intPrimitive); bean.setLongPrimitive(longPrimitive); return bean; } }
gpl-2.0
diging/quadriga
Quadriga/src/main/java/edu/asu/spring/quadriga/validator/CollaboratorFormDeleteValidator.java
1384
package edu.asu.spring.quadriga.validator; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import edu.asu.spring.quadriga.web.workbench.backing.ModifyCollaborator; import edu.asu.spring.quadriga.web.workbench.backing.ModifyCollaboratorForm; /** * This class validates the collaborator form used for deletion. * @author kiran batna * */ @Service public class CollaboratorFormDeleteValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return clazz.isAssignableFrom(ModifyCollaboratorForm.class); } @Override public void validate(Object target, Errors errors) { ModifyCollaboratorForm collaboratorForm = (ModifyCollaboratorForm)target; List<ModifyCollaborator> collaboratorList = collaboratorForm.getCollaborators(); String userName; boolean isAllNull = true; for(int i=0;i<collaboratorList.size();i++) { userName = collaboratorList.get(i).getUserName(); if(userName != null) { isAllNull = false; } } if(isAllNull == true) { for(int i=0;i<collaboratorList.size();i++) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "collaborators["+i+"].userName", "collaborator_delete_selection.required"); } } } }
gpl-2.0
crotwell/fissuresUtil
src/main/java/edu/sc/seis/fissuresUtil/display/SeismogramPDFBuilder.java
9449
package edu.sc.seis.fissuresUtil.display; import java.awt.Dimension; import java.awt.Graphics2D; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.JComponent; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.PageSize; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfTemplate; import com.lowagie.text.pdf.PdfWriter; import edu.sc.seis.fissuresUtil.display.borders.TimeBorder; import edu.sc.seis.fissuresUtil.display.borders.TitleBorder; import edu.sc.seis.fissuresUtil.exceptionHandler.GlobalExceptionHandler; public class SeismogramPDFBuilder { public SeismogramPDFBuilder() { this(true, 1, true); } public SeismogramPDFBuilder(boolean landscape, int dispPerPage, boolean separateDisplays) { this(landscape, PAGE_SIZE, MARGIN, dispPerPage, separateDisplays); } public SeismogramPDFBuilder(boolean landscape, Rectangle pageSize, int margin, int dispPerPage, boolean separateDisplays) { this(landscape, pageSize, margin, margin, margin, margin, dispPerPage, separateDisplays); } public SeismogramPDFBuilder(boolean landscape, Rectangle pageSize, int topMargin, int rightMargin, int bottomMargin, int leftMargin, int dispPerPage, boolean separateDisplays) { setPageSize(landscape ? pageSize.rotate() : pageSize); setMargins(topMargin, rightMargin, bottomMargin, leftMargin); setDispPerPage(dispPerPage); } public void setPageSize(Rectangle pageSize) { this.pageSize = pageSize; } public Rectangle getPageSize() { return pageSize; } public void setMargins(int margin) { setMargins(margin, margin, margin, margin); } public void setMargins(int topMargin, int rightMargin, int bottomMargin, int leftMargin) { setTopMargin(topMargin); setRightMargin(rightMargin); setBottomMargin(bottomMargin); setLeftMargin(leftMargin); } public void setTopMargin(int topMargin) { this.topMargin = topMargin; recalculateVertMargins(); } public int getTopMargin() { return topMargin; } public void setRightMargin(int rightMargin) { this.rightMargin = rightMargin; recalculateHorizMargins(); } public int getRightMargin() { return rightMargin; } public void setBottomMargin(int bottomMargin) { this.bottomMargin = bottomMargin; recalculateVertMargins(); } public int getBottomMargin() { return bottomMargin; } public void setLeftMargin(int leftMargin) { this.leftMargin = leftMargin; recalculateHorizMargins(); } public int getLeftMargin() { return leftMargin; } public void setDispPerPage(int dispPerPage) { this.dispPerPage = dispPerPage; } public int getDispPerPage() { return dispPerPage; } public void setSeparateDisplays(boolean separateDisplays) { this.separateDisplays = separateDisplays; } public boolean getSeparateDisplays() { return separateDisplays; } public void setHeader(TitleBorder header) { this.header = header; } public TitleBorder getHeader() { return header; } public Dimension getPrintableSize() { return new Dimension((int)(pageSize.getWidth() - leftMargin - rightMargin), (int)(pageSize.getHeight() - topMargin - bottomMargin)); } public void createPDF(JComponent disp, File file) throws IOException { file.getCanonicalFile().getParentFile().mkdirs(); File temp = File.createTempFile(file.getName(), null, file.getParentFile()); createPDF(disp, new FileOutputStream(temp)); file.delete(); temp.renameTo(file); } public void createPDF(JComponent comp, OutputStream out) { List displays = new ArrayList(); if(separateDisplays && comp instanceof VerticalSeismogramDisplay) { displays.addAll(breakOutSeparateDisplays((VerticalSeismogramDisplay)comp)); } else { displays.add(comp); } createPDF((JComponent[])displays.toArray(new JComponent[0]), out); } public void createPDF(JComponent[] comps, OutputStream out) { Document document = new Document(pageSize); try { int headerHeight = 0; if(header != null) { header.setSize(header.getPreferredSize()); headerHeight = header.getHeight(); } PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); int pageW = (int)pageSize.getWidth(); int pageH = (int)pageSize.getHeight(); int pixelsPerDisplayH = (int)Math.floor((pageH - vertMargins - headerHeight) / (double)dispPerPage); int pixelsPerDisplayW = (int)Math.floor(pageW - horizMargins); PdfContentByte cb = writer.getDirectContent(); // layer for SeismogramDisplay PdfTemplate tpTraces = cb.createTemplate(pageW, pageH); Graphics2D g2Traces = tpTraces.createGraphics(pageW, pageH); g2Traces.translate(rightMargin, topMargin); if(header != null) { header.setSize(new Dimension(pixelsPerDisplayW, headerHeight)); boolean bufferingStatus = header.isDoubleBuffered(); header.setDoubleBuffered(false); header.paint(g2Traces); header.setDoubleBuffered(bufferingStatus); g2Traces.translate(0, headerHeight); } int seisOnCurPage = 0; for(int i = 0; i < comps.length; i++) { // loop over all traces boolean bufferingStatus = comps[i].isDoubleBuffered(); comps[i].setDoubleBuffered(false); if(comps[i] instanceof Graphics2DRenderer) { ((Graphics2DRenderer)comps[i]).renderToGraphics(g2Traces, new Dimension(pixelsPerDisplayW, pixelsPerDisplayH)); } else { comps[i].paint(g2Traces); } comps[i].setDoubleBuffered(bufferingStatus); if(++seisOnCurPage == dispPerPage) { // page is full, finish page and create a new page. cb.addTemplate(tpTraces, 0, 0); g2Traces.dispose(); document.newPage(); tpTraces = cb.createTemplate(pageW, pageH); g2Traces = tpTraces.createGraphics(pageW, pageH); g2Traces.translate(rightMargin, topMargin); // reset current count seisOnCurPage = 0; } else { // step down the page g2Traces.translate(0, pixelsPerDisplayH); } } if(seisOnCurPage != 0) { // finish writing to the Graphics2D cb.addTemplate(tpTraces, 0, 0); } g2Traces.dispose(); } catch(DocumentException ex) { GlobalExceptionHandler.handle("problem saving to pdf", ex); } // step 5: we close the document document.close(); } private List breakOutSeparateDisplays(VerticalSeismogramDisplay disp) { List displays = ((VerticalSeismogramDisplay)disp).getDisplays(); Iterator it = displays.iterator(); while(it.hasNext()) { BasicSeismogramDisplay cur = (BasicSeismogramDisplay)it.next(); cur.clear(BorderedDisplay.BOTTOM_CENTER); if(!cur.isFilled(BorderedDisplay.TOP_CENTER)) { cur.add(new TimeBorder(cur), BorderedDisplay.TOP_CENTER); } } return displays; } private void recalculateHorizMargins() { horizMargins = leftMargin + rightMargin; } private void recalculateVertMargins() { vertMargins = topMargin + bottomMargin; } private int topMargin, rightMargin, bottomMargin, leftMargin; private int horizMargins, vertMargins; private Rectangle pageSize; private int dispPerPage; private boolean separateDisplays; private TitleBorder header; public static final Rectangle PAGE_SIZE = PageSize.LETTER; public static final int MARGIN = 50; }
gpl-2.0
methical/xkpasswd-lib
src/main/java/de/_0x29/xkpasswd/PasswordFactory.java
2376
/* * Copyright (c) 2014. Licensed under GPL-2. See license.txt in project folder. */ package de._0x29.xkpasswd; import java.io.IOException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; /** * Created by christian on 1/26/14. */ public class PasswordFactory { private int mAmount = 4; private int mMaxWordLength = 8; private int mMinWordLength = 5; private String mDelimiter = " "; private int mDigitsBefore = 0; private int mDigitsAfter = 0; public PasswordFactory setNumberOfWords(int amount) { mAmount = amount; return this; } public PasswordFactory setMinimumWordLength(int min) { mMinWordLength = min; return this; } public PasswordFactory setMaximumWordLength(int max) { mMaxWordLength = max; return this; } public PasswordFactory setWordDelimiter(String delimiter) { mDelimiter = delimiter; return this; } public PasswordFactory setDigitsBeforePassphrase(int digitsBefore) { mDigitsBefore = digitsBefore; return this; } public PasswordFactory setDigitsAfterPassphrase(int digitsAfter) { mDigitsAfter = digitsAfter; return this; } public String create() { ArrayList<String> availableWords = new ArrayList<String>(); SecureRandom secureRandom = new SecureRandom(); StringBuffer buffer = new StringBuffer(); try { Dictionary dictionary = new Dictionary(); HashMap<Integer, ArrayList<String>> words = dictionary.getWords(); for (Integer wordLength : words.keySet()) { if (wordLength <= mMaxWordLength && wordLength >= mMinWordLength) { availableWords.addAll(words.get(wordLength)); } } for (int i = 0; i < mAmount; i++) { int randomIndex = secureRandom.nextInt(availableWords.size()); String s = availableWords.get(randomIndex); buffer.append(s); availableWords.remove(randomIndex); if ((i + 1) < mAmount) { buffer.append(mDelimiter); } } } catch (IOException e) { e.printStackTrace(); } return buffer.toString(); } }
gpl-2.0
software-jessies-org/scm
src/e/scm/Patch.java
6750
package e.scm; import java.io.*; import java.nio.file.*; import java.util.*; import java.util.regex.*; import e.util.*; public class Patch { private ArrayList<String> lines; private ArrayList<String> errors; private LineMapper lineMapper; public static final class HunkRange { /** * Matches the "@@ -111,41 +113,41 @@" lines at the start of a hunk. * We allow anything after the trailing "@@" because that gap is used for annotations, both by our annotate-patch.rb script and by "diff -p". * GNU Diff's "print_unidiff_number_range" has a special case when outputting a,b where if a and b are equal, only a is output. */ private static final Pattern AT_AT_PATTERN = Pattern.compile("^@@ -(\\d+)(,\\d+)? \\+(\\d+)(,\\d+)? @@(.*)$"); private boolean matches; // "from" is the first comma-separated pair. "to" is the second comma-separated pair. // "begin" is the first number in each pair. "end" is the second number in each pair. private int fromBegin; private int fromEnd; private int toBegin; private int toEnd; public HunkRange(String atAtLine) { Matcher matcher = AT_AT_PATTERN.matcher(atAtLine); matches = matcher.matches(); if (matches) { fromBegin = parseInt(matcher.group(1), 0); fromEnd = parseInt(matcher.group(2), fromBegin); toBegin = parseInt(matcher.group(3), 0); toEnd = parseInt(matcher.group(4), toBegin); } } private int parseInt(String value, int fallback) { if (value == null) { return fallback; } if (value.startsWith(",")) { value = value.substring(1); } int result = Integer.parseInt(value); return result; } public boolean matches() { return matches; } public int fromBegin() { return fromBegin; } public int toBegin() { return toBegin; } } private interface PatchLineParser { public void parseHunkHeader(int fromBegin, int toBegin); public void parseFromLine(String sourceLine); public void parseToLine(String sourceLine); public void parseContextLine(String sourceLine); } private void parsePatch(boolean isPatchReversed, PatchLineParser patchLineParser) { String fromPrefix = isPatchReversed ? "+" : "-"; String toPrefix = isPatchReversed ? "-" : "+"; for (int lineNumberWithinPatch = 0; lineNumberWithinPatch < lines.size(); ++lineNumberWithinPatch) { String patchLine = lines.get(lineNumberWithinPatch); if (patchLine.startsWith("@@")) { HunkRange hunkRange = new HunkRange(patchLine); if (isPatchReversed) { patchLineParser.parseHunkHeader(hunkRange.toBegin(), hunkRange.fromBegin()); } else { patchLineParser.parseHunkHeader(hunkRange.fromBegin(), hunkRange.toBegin()); } } else if (patchLine.length() > 0) { String sourceLine = patchLine.substring(1); if (patchLine.startsWith(fromPrefix)) { patchLineParser.parseFromLine(sourceLine); } else if (patchLine.startsWith(toPrefix)) { patchLineParser.parseToLine(sourceLine); } else if (patchLine.startsWith(" ")) { patchLineParser.parseContextLine(sourceLine); } else if (patchLine.startsWith("=====") || patchLine.startsWith("Index: ") || patchLine.startsWith("RCS file: ") || patchLine.startsWith("retrieving revision ") || patchLine.startsWith("diff ") || patchLine.startsWith("new mode ") || patchLine.startsWith("old mode ") || patchLine.startsWith("index ") || patchLine.startsWith("\\ No newline at end of file")) { // Ignore lines like this for the minute: // bk: // ===== makerules/vars-not-previously-included.make 1.33 vs 1.104 ===== // Index: src/e/scm/RevisionWindow.java // svn: // =================================================================== // cvs: // RCS file: /home/repositories/cvsroot/edit/src/e/edit/InsertNewlineAction.java,v // retrieving revision 1.7 // diff -u -r1.7 -r1.9 } else { // throw new RuntimeException("Malformed patch line \"" + patchLine + "\""); } } } } public Patch(RevisionControlSystem backEnd, String filePath, Revision olderRevision, Revision newerRevision, boolean isPatchReversed, boolean ignoreWhiteSpace) { Path directory = backEnd.getRoot(); String[] command = backEnd.getDifferencesCommand(olderRevision, newerRevision, filePath, ignoreWhiteSpace); this.lines = new ArrayList<String>(); this.errors = new ArrayList<String>(); ProcessUtilities.backQuote(directory, command, lines, errors); // CVS returns the number of differences as the status or some such idiocy. if (errors.size() > 0) { lines.addAll(errors); } initLineMapper(isPatchReversed); } private void initLineMapper(boolean isPatchReversed) { lineMapper = new LineMapper(); parsePatch(isPatchReversed, new PatchLineParser() { private int fromLine = 0; private int toLine = 0; public void parseHunkHeader(int fromBegin, int toBegin) { fromLine = fromBegin; toLine = toBegin; } public void parseFromLine(String sourceLine) { ++fromLine; } public void parseToLine(String sourceLine) { ++toLine; } public void parseContextLine(String sourceLine) { lineMapper.addMapping(fromLine, toLine); // Context lines count for both revisions. ++fromLine; ++toLine; } }); } public int translateLineNumberInFromRevision(int fromLineNumber) { return lineMapper.translate(fromLineNumber); } public ArrayList<String> getPatchLines() { ArrayList<String> result = new ArrayList<>(); result.addAll(lines); return result; } }
gpl-2.0
indiyskiy/WorldOnline
src/model/xmlparser/xmlview/mainmenudata/MainMenuData.java
450
package model.xmlparser.xmlview.mainmenudata; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; import java.util.List; @Root(name = "data") public class MainMenuData { @ElementList(inline = true, name = "Submenu") List<Submenu> submenus; public List<Submenu> getSubmenus() { return submenus; } public void setSubmenus(List<Submenu> submenus) { this.submenus = submenus; } }
gpl-2.0
sandlex/run2gather
src/main/java/com/sandlex/run2gather/runkeeper/model/types/ActivityType.java
1076
package com.sandlex.run2gather.runkeeper.model.types; import com.google.gson.annotations.SerializedName; /** * author: Alexey Peskov */ public enum ActivityType { RUNNING("Running"), CYCLING("Cycling"), MOUNTAIN_BIKING("Mountain Biking"), WALKING("Walking"), HIKING("Hiking"), DOWNHILL_SKIING("Downhill Skiing"), CROSS_COUNTRY_SKIING("Cross-Country Skiing"), SNOWBOARDING("Snowboarding"), SKATING("Skating"), SWIMMING("Swimming"), WHEELCHAIR("Wheelchair"), ROWING("Rowing"), ELLIPTICAL("Elliptical"), OTHER("Other"); @SerializedName("type") private final String code; ActivityType(String code) { this.code = code; } @Override public String toString() { return code; } public static ActivityType fromValue(String code) { for (ActivityType type : ActivityType.values()) { if (type.code.equals(code)) { return type; } } throw new IllegalArgumentException("Invalid ActivityType code: " + code); } }
gpl-2.0
adum/bitbath
hackjvm/src/ojvm/loading/instructions/Ins_lreturn.java
585
package ojvm.loading.instructions; import ojvm.data.JavaException; import ojvm.operations.InstructionVisitor; import ojvm.util.RuntimeConstants; /** * The encapsulation of a lreturn instruction. * @author Amr Sabry * @version jdk-1.1 */ public class Ins_lreturn extends Instruction { public Ins_lreturn (InstructionInputStream classFile) { super(RuntimeConstants.opc_lreturn); } public void accept (InstructionVisitor iv) throws JavaException { iv.visit_lreturn (this); } public String toString () { return opcodeName; } }
gpl-2.0
liyue80/GmailAssistant20
src/javax/mail/internet/SharedInputStream.java
3737
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ /* * @(#)SharedInputStream.java 1.5 07/05/04 */ package javax.mail.internet; import java.io.*; /** * An InputStream that is backed by data that can be shared by multiple * readers may implement this interface. This allows users of such an * InputStream to determine the current position in the InputStream, and * to create new InputStreams representing a subset of the data in the * original InputStream. The new InputStream will access the same * underlying data as the original, without copying the data. <p> * * Note that implementations of this interface must ensure that the * <code>close</code> method does not close any underlying stream * that might be shared by multiple instances of <code>SharedInputStream</code> * until all shared instances have been closed. * * @version 1.5, 07/05/04 * @author Bill Shannon * @since JavaMail 1.2 */ public interface SharedInputStream { /** * Return the current position in the InputStream, as an * offset from the beginning of the InputStream. * * @return the current position */ public long getPosition(); /** * Return a new InputStream representing a subset of the data * from this InputStream, starting at <code>start</code> (inclusive) * up to <code>end</code> (exclusive). <code>start</code> must be * non-negative. If <code>end</code> is -1, the new stream ends * at the same place as this stream. The returned InputStream * will also implement the SharedInputStream interface. * * @param start the starting position * @param end the ending position + 1 * @return the new stream */ public InputStream newStream(long start, long end); }
gpl-2.0
Norkart/NK-VirtualGlobe
Xj3D/spec_examples/x3d/SAIExample1.java
2730
// Standard imports import java.util.Map; // Application specific imports import org.web3d.x3d.sai.*; public class SAIExample1 implements X3DScriptImplementation, X3DFieldEventListener { /** Color Constant, RED */ private static final float[] RED = new float[] {1.0f, 0, 0}; /** Color Constant, BLUE */ private static final float[] BLUE = new float[] {0, 0, 1.0f}; /** A mapping for fieldName(String) to an X3DField object */ private Map fields; /** The isOver field */ private SFBool isOver; /** The diffuseColor_changed field */ private SFColor diffuseColor; //---------------------------------------------------------- // Methods from the X3DScriptImplementation interface. //---------------------------------------------------------- /** * Set the browser instance to be used by this script implementation. * * @param browser The browser reference to keep */ public void setBrowser(Browser browser) { } /** * Set the listing of fields that have been declared in the file for * this node. . * * @param The external view of ourselves, so you can add routes to yourself * using the standard API calls * @param fields The mapping of field names to instances */ public void setFields(X3DScriptNode externalView, Map fields) { this.fields = fields; } /** * Notification that the script has completed the setup and should go * about its own internal initialization. */ public void initialize() { isOver = (SFBool) fields.get("isOver"); diffuseColor = (SFColor) fields.get("diffuseColor_changed"); // Listen to events on isOver isOver.addX3DEventListener(this); } /** * Notification that this script instance is no longer in use by the * scene graph and should now release all resources. */ public void shutdown() { } /** * Notification that all the events in the current cascade have finished * processing. */ public void eventsProcessed() { } //---------------------------------------------------------- // Methods from the X3DFieldEventListener interface. //---------------------------------------------------------- /** * Handle field changes. * * @param evt The field event */ public void readableFieldChanged(X3DFieldEvent evt) { if (evt.getSource() == isOver) { if (isOver.getValue() == true) diffuseColor.setValue(RED); else diffuseColor.setValue(BLUE); } else { System.out.println("Unhandled event: " + evt); } } }
gpl-2.0
rex-xxx/mt6572_x201
mediatek/frameworks/opt/ngin3d/demos/App/ngin3dDemo/src/com/mediatek/ngin3d/demo/DemolistGlo3D.java
7673
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ package com.mediatek.ngin3d.demo; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class DemolistGlo3D extends Activity { private ListView mListView; private MyAdapter mMyAdapter; public List<String> mListTag = new ArrayList<String>(); private List<String> mData = new ArrayList<String>(); private HashMap<String, Object> mImageMap = new HashMap<String, Object>(); private static final String packageName = "com.mediatek.ngin3d.demo"; private String[] mGloActivity3 = { "Glo3DDemo", "ProjectionsDemo", "Glo3DTextureDemo", "Glo3DAntiAliasingDemo", "Glo3DScaleRotationDemo", "EularAngleDemo", "EulerOrderDemo", "OptimusPrime", "CustomMaterials", "LightDemo" }; /*** * this method to avoid loading the picture from Resource caused by OOM * * @param context * @param resId * @return Bitmap */ public static Bitmap readBitMap(Context context, int resId) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; InputStream is = context.getResources().openRawResource(resId); return BitmapFactory.decodeStream(is, null, opt); } private void initImageMap() { mImageMap.clear(); mImageMap.put("Glo3DDemo", R.drawable.demo_glo3ddemo); mImageMap.put("ProjectionsDemo", R.drawable.demo_projectionsdemo); mImageMap.put("Glo3DTextureDemo", R.drawable.demo_glo3dtexturedemo); mImageMap.put("Glo3DAntiAliasingDemo", R.drawable.demo_glo3dantialiasingdemoapp); mImageMap.put("Glo3DScaleRotationDemo", R.drawable.demo_glo3dscalerotationdemoapp); mImageMap.put("EularAngleDemo", R.drawable.demo_eularabgledemoapp); mImageMap.put("StereoSpace3DDemo", R.drawable.demo_stereo3ddemoapp); mImageMap.put("EulerOrderDemo", R.drawable.demo_eulerorderdemoapp); mImageMap.put("OptimusPrime", R.drawable.demo_optimusprimedemoapp); mImageMap.put("CustomMaterials", R.drawable.demo_custommaterials); mImageMap.put("LightDemo", R.drawable.demo_lightdemo); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mListView = (ListView) findViewById(R.id.list); mMyAdapter = new MyAdapter(this, android.R.layout.simple_expandable_list_item_1, getData()); mListView.setAdapter(mMyAdapter); initImageMap(); mListView.setOnItemClickListener(new ListView.OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { try { startActivity(new Intent(getBaseContext(), Class.forName(packageName + "." + mData.get(position)))); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }); } private Object getImageFromMap(Object key) { return mImageMap.get(key); } private List<String> getData() { mListTag.add("Glo"); mData.add("Glo"); for (int i = 0; i < mGloActivity3.length; i++) { mData.add(mGloActivity3[i]); } return mData; } class MyAdapter extends ArrayAdapter<String> { public MyAdapter(Context context, int textViewResourceId, List<String> objects) { super(context, textViewResourceId, objects); } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return !mListTag.contains(getItem(position)); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; if (mListTag.contains(getItem(position))) { view = LayoutInflater.from(getContext()).inflate(R.layout.list_item_tag, null); } else { view = LayoutInflater.from(getContext()).inflate(R.layout.list_item, null); if (getImageFromMap(getItem(position)) != null) { Bitmap bmp = readBitMap(this.getContext(), (Integer) getImageFromMap(getItem(position))); ImageView imageView = (ImageView) view.findViewById(R.id.group_list_item_image); imageView.setImageBitmap(bmp); } } TextView textView = (TextView) view.findViewById(R.id.group_list_item_text); textView.setText(getItem(position)); return view; } } }
gpl-2.0
algo3-2015-fiuba/algocraft
src/vistas/actores/ActorObject.java
230
package vistas.actores; import java.awt.Color; import java.awt.Graphics; public class ActorObject extends Actor { @Override public void dibujar(Graphics g) { g.setColor(Color.white); g.drawRect (20, 20, 10, 10); } }
gpl-2.0
dev-cuttlefish/cuttlefish
src-old/ch/ethz/sg/cuttlefish/misc/VertexFactory.java
1036
/* Copyright (C) 2009 Markus Michael Geipel, David Garcia Becerra This file is part of Cuttlefish. Cuttlefish 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 ch.ethz.sg.cuttlefish.misc; import org.apache.commons.collections15.Factory; /** * Factory class that creates anonymous vertices * @author david */ public class VertexFactory implements Factory<Vertex> { public Vertex create() { return new Vertex(); } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest08210.java
2148
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest08210") public class BenchmarkTest08210 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getHeader("foo"); String bar = new Test().doSomething(param); response.getWriter().write(bar); } // end doPost private class Test { public String doSomething(String param) throws ServletException, IOException { java.util.List<String> valuesList = new java.util.ArrayList<String>( ); valuesList.add("safe"); valuesList.add( param ); valuesList.add( "moresafe" ); valuesList.remove(0); // remove the 1st safe value String bar = valuesList.get(1); // get the last 'safe' value return bar; } } // end innerclass Test } // end DataflowThruInnerClass
gpl-2.0
hurdad/storm-forex
src/jvm/com/github/hurdad/storm/forex/bolt/PercRBolt.java
2483
package com.github.hurdad.storm.forex.bolt; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichBolt; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; public class PercRBolt extends BaseRichBolt { OutputCollector _collector; Integer _period; Map<String, Queue<Double>> _high_queues; Map<String, Queue<Double>> _low_queues; public PercRBolt(Integer period) { _period = period; } @Override public void prepare(Map conf, TopologyContext context, OutputCollector collector) { _collector = collector; _high_queues = new HashMap<String, Queue<Double>>(); _low_queues = new HashMap<String, Queue<Double>>(); } @Override public void execute(Tuple tuple) { // input vars String pair = tuple.getStringByField("pair"); String high = tuple.getStringByField("high"); String low = tuple.getStringByField("low"); String close = tuple.getStringByField("close"); Integer timeslice = tuple.getIntegerByField("timeslice"); // init if (_high_queues.get(pair) == null) _high_queues.put(pair, new LinkedList<Double>()); if (_low_queues.get(pair) == null) _low_queues.put(pair, new LinkedList<Double>()); // pair highs / lows Queue<Double> highs = _high_queues.get(pair); Queue<Double> lows = _low_queues.get(pair); // add to front highs.add(Double.parseDouble(high)); lows.add(Double.parseDouble(low)); // pop back if too long if (highs.size() > _period) highs.poll(); if (lows.size() > _period) lows.poll(); // have enough data to calc perc r if (highs.size() == _period) { // get high Double h = highs.peek(); // loop highs for (Double val : highs) { h = Math.max(val, h); } // get low Double l = lows.peek(); // loop lows for (Double val : lows) { l = Math.min(val, l); } // calc percent R Double perc_r = (h - Double.parseDouble(close)) / (h - l) * -100; // emit _collector.emit(new Values(pair, timeslice, String.format("%.2f", perc_r))); } // save _high_queues.put(pair, highs); _low_queues.put(pair, lows); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("pair", "timeslice", "perc_r")); } }
gpl-2.0
rex-xxx/mt6572_x201
mediatek/packages/apps/Bluetooth/profiles/opp/src/com/mediatek/bluetooth/opp/adp/OppTaskWorkerThread.java
4522
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. and/or its licensors. * Without the prior written permission of MediaTek inc. and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek Software") * have been modified by MediaTek Inc. All revisions are subject to any receiver's * applicable license agreements with MediaTek Inc. */ package com.mediatek.bluetooth.opp.adp; import android.os.Process; import com.mediatek.bluetooth.opp.mmi.OppLog; public class OppTaskWorkerThread extends Thread { private boolean mHasMoreTask = false; private OppTaskHandler mHandler; public OppTaskWorkerThread(String name, OppTaskHandler handler) { super(name + "WorkerThread"); this.mHandler = handler; } @Override public void run() { OppLog.d("OppTask worker thread start: thread name - " + this.getName()); // need to increase the priority (higher than message-listener thread) // or the event will be queued in EventQueue Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND - 3); // loop until be interrupted while (!this.isInterrupted()) { try { // before wait (for new task) OppLog.d("OppTaskWorkerThread[" + this.getName() + "]: 1. beforeWait()"); if (!this.mHandler.beforeWait()) { continue; } // wait for task OppLog.d("OppTaskWorkerThread[" + this.getName() + "]: 2. waitNewTask()"); this.waitNewTask(); // after wait (new task arrival) OppLog.d("OppTaskWorkerThread[" + this.getName() + "]: 3. afterWait()"); this.mHandler.afterWait(); // finish this loop OppLog.d("OppTaskWorkerThread[" + this.getName() + "]: 4. next loop"); } catch (InterruptedException ex) { OppLog.i("OppTaskWorkerThread[" + this.getName() + "] interrupted: " + ex.getMessage()); break; } } OppLog.d("OppTaskWorkerThread[" + this.getName() + "] stopped."); } public synchronized void waitNewTask() throws InterruptedException { // only wait when no more task if (!this.mHasMoreTask) { this.wait(); } // all tasks will be processed below this.mHasMoreTask = false; } public synchronized void notifyNewTask() { OppLog.d("notify new task for OppTaskWorkerThread[" + this.getName() + "]"); this.mHasMoreTask = true; this.notify(); } }
gpl-2.0
vlabatut/totalboumboum
resources/ai/org/totalboumboum/ai/v201112/ais/kayukataskin/v3/criterion/CriterionThird.java
2534
package org.totalboumboum.ai.v201112.ais.kayukataskin.v3.criterion; import java.util.Arrays; import java.util.Set; import java.util.TreeSet; import org.totalboumboum.ai.v201112.adapter.agent.AiUtilityCriterionString; import org.totalboumboum.ai.v201112.adapter.communication.StopRequestException; import org.totalboumboum.ai.v201112.adapter.data.AiTile; import org.totalboumboum.ai.v201112.ais.kayukataskin.v3.KayukaTaskin; /** * Cette classe est un simple exemple de * critère chaîne de caractères. Copiez-la, renommez-la, modifiez-la * pour l'adapter à vos besoin. Notez que le domaine * de définition est spécifiés dans l'appel au constructeur * ({@code super(nom,inf,sup)}). * * @author Pol Kayuka * @author Ayça Taşkın */ @SuppressWarnings("deprecation") public class CriterionThird extends AiUtilityCriterionString { /** Nom de ce critère */ public static final String NAME = "THIRD"; /** Valeurs du domaine de définition */ public static final String VALUE1 = "une valeur"; /** */ public static final String VALUE2 = "une autre valeur"; /** */ public static final String VALUE3 = "encore une autre"; /** */ public static final String VALUE4 = "et puis une autre"; /** */ public static final String VALUE5 = "et enfin une dernière"; /** Domaine de définition */ public static final Set<String> DOMAIN = new TreeSet<String>(Arrays.asList ( VALUE1, VALUE2, VALUE3, VALUE4, VALUE5 )); /** * Crée un nouveau critère entier. * @param ai * ? * @throws StopRequestException * Au cas où le moteur demande la terminaison de l'agent. */ public CriterionThird(KayukaTaskin ai) throws StopRequestException { // init nom + bornes du domaine de définition super(NAME,DOMAIN); ai.checkInterruption(); // init agent this.ai = ai; } ///////////////////////////////////////////////////////////////// // ARTIFICIAL INTELLIGENCE ///////////////////////////////////// ///////////////////////////////////////////////////////////////// /** */ protected KayukaTaskin ai; ///////////////////////////////////////////////////////////////// // PROCESS ///////////////////////////////////// ///////////////////////////////////////////////////////////////// @Override public String processValue(AiTile tile) throws StopRequestException { ai.checkInterruption(); String result = VALUE3; // à compléter par le traitement approprié return result; } }
gpl-2.0
cyberpython/java-gnome
src/bindings/org/gnome/gtk/GtkStyleContextOverride.java
3406
/* * java-gnome, a UI library for writing GTK and GNOME programs from Java! * * Copyright © 2011 Operational Dynamics Consulting, Pty Ltd and Others * * The code in this file, and the program it is a part of, is made available * to you by its authors as open source software: you can redistribute it * and/or modify it under the terms of the GNU General Public License version * 2 ("GPL") 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 GPL for more details. * * You should have received a copy of the GPL along with this program. If not, * see http://www.gnu.org/licenses/. The authors of this program may be * contacted through http://java-gnome.sourceforge.net/. * * Linking this library statically or dynamically with other modules is making * a combined work based on this library. Thus, the terms and conditions of * the GPL cover the whole combination. As a special exception (the * "Claspath Exception"), the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, * and to copy and distribute the resulting executable under terms of your * choice, provided that you also meet, for each linked independent module, * the terms and conditions of the license of that module. An independent * module is a module which is not derived from or based on this library. If * you modify this library, you may extend the Classpath Exception to your * version of the library, but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. */ package org.gnome.gtk; /** * Manual code allowing us to handle some data returned by GtkStyleContext * methods. * * @author Guillaume Mazoyer */ final class GtkStyleContextOverride extends Plumbing { static final RegionFlags hasRegion(StyleContext self, String region) { int result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { result = gtk_style_context_contains_region(pointerOf(self), region); return (RegionFlags) enumFor(RegionFlags.class, result); } } private static native final int gtk_style_context_contains_region(long self, String region); static final String[] getClasses(StyleContext self) { String[] result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { result = gtk_style_context_get_classes(pointerOf(self)); return result; } } private static native final String[] gtk_style_context_get_classes(long self); static final String[] getRegions(StyleContext self) { String[] result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { result = gtk_style_context_get_regions(pointerOf(self)); return result; } } private static native final String[] gtk_style_context_get_regions(long self); }
gpl-2.0
Haixing-Hu/iLibrary
src/main/java/com/github/haixing_hu/ilibrary/AppConfig.java
18577
/* * Copyright (c) 2014 Haixing Hu * * 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.github.haixing_hu.ilibrary; import java.io.IOException; import java.lang.annotation.Annotation; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; import org.springframework.context.MessageSourceResolvable; import org.springframework.context.NoSuchMessageException; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.env.Environment; import org.springframework.core.io.Resource; /** * The global configuration of the application. * * @author Haixing Hu */ public final class AppConfig implements ApplicationContext, Configuration, KeySuffix { private final Logger logger; private final ApplicationContext context; private final Configuration config; private final Locale locale; private final String name; private final String version; private final String stylesheet; /** * Constructs a {@link AppConfig}. */ public AppConfig(final String contexFile) { logger = LoggerFactory.getLogger(AppConfig.class); context = new ClassPathXmlApplicationContext(contexFile); config = context.getBean(Configuration.class); final String localeName = config.getString(Application.ID + LOCALE); if (StringUtils.isEmpty(localeName)) { locale = Locale.getDefault(); } else { locale = new Locale(localeName); } name = context.getMessage(Application.ID + NAME, null, locale); version = config.getString(Application.ID + VERSION); final String css = config.getString(Application.ID + STYLE); stylesheet = this.getClass().getResource(css).toExternalForm(); logger.info("{} {}", name, version); logger.info("Sets the locale to {}.", locale); } /** * Gets the locale. * * @return the locale. */ public Locale getLocale() { return locale; } /** * Gets the name of the application. * * @return the name of the application. */ public String getAppName() { return name; } /** * Gets the version of the application. * * @return the version of the application. */ public String getAppVersion() { return version; } /** * Gets the path of the stylesheet of this application. * * @return the path of the stylesheet of this application. */ public String getStylesheet() { return stylesheet; } @Override public Environment getEnvironment() { return context.getEnvironment(); } @Override public boolean containsBeanDefinition(final String beanName) { return context.containsBeanDefinition(beanName); } @Override public <A extends Annotation> A findAnnotationOnBean(final String beanName, final Class<A> annotationType) { return context.findAnnotationOnBean(beanName, annotationType); } @Override public int getBeanDefinitionCount() { return context.getBeanDefinitionCount(); } @Override public String[] getBeanDefinitionNames() { return context.getBeanDefinitionNames(); } @Override public String[] getBeanNamesForType(final Class<?> type) { return context.getBeanNamesForType(type); } @Override public String[] getBeanNamesForType(final Class<?> type, final boolean includeNonSingletons, final boolean allowEagerInit) { return context.getBeanNamesForType(type, includeNonSingletons, allowEagerInit); } @Override public <T> Map<String, T> getBeansOfType(final Class<T> type) throws BeansException { return context.getBeansOfType(type); } @Override public <T> Map<String, T> getBeansOfType(final Class<T> type, final boolean includeNonSingletons, final boolean allowEagerInit) throws BeansException { return context.getBeansOfType(type, includeNonSingletons, allowEagerInit); } @Override public Map<String, Object> getBeansWithAnnotation( final Class<? extends Annotation> annotationType) throws BeansException { return context.getBeansWithAnnotation(annotationType); } @Override public boolean containsBean(final String name) { return context.containsBean(name); } @Override public String[] getAliases(final String name) { return context.getAliases(name); } @Override public Object getBean(final String name) throws BeansException { return context.getBean(name); } @Override public <T> T getBean(final Class<T> requiredType) throws BeansException { return context.getBean(requiredType); } @Override public <T> T getBean(final String name, final Class<T> requiredType) throws BeansException { return context.getBean(name, requiredType); } @Override public Object getBean(final String name, final Object... args) throws BeansException { return context.getBean(name, args); } @Override public Class<?> getType(final String name) throws NoSuchBeanDefinitionException { return context.getType(name); } @Override public boolean isPrototype(final String name) throws NoSuchBeanDefinitionException { return context.isPrototype(name); } @Override public boolean isSingleton(final String name) throws NoSuchBeanDefinitionException { return context.isSingleton(name); } @Override public boolean isTypeMatch(final String name, final Class<?> targetType) throws NoSuchBeanDefinitionException { return context.isTypeMatch(name, targetType); } @Override public boolean containsLocalBean(final String name) { return context.containsLocalBean(name); } @Override public BeanFactory getParentBeanFactory() { return context.getParentBeanFactory(); } @Override public String getMessage(final String key, final Object[] args, final String defaultMessage, final Locale locale) { return context.getMessage(key, args, defaultMessage, locale); } @Override public String getMessage(final String key, final Object[] args, final Locale locale) throws NoSuchMessageException { logger.trace("Getting message: {}", key); return context.getMessage(key, args, locale); } @Override public String getMessage(final MessageSourceResolvable resolvable, final Locale locale) throws NoSuchMessageException { return context.getMessage(resolvable, locale); } /** * Gets the localized message for a specified key. * * @param key * the key of the message. * @return the localized message for the specified key. */ public String getMessage(final String key) { logger.trace("Getting message: {}", key); return context.getMessage(key, null, locale); } /** * Gets the localized message for a specified key formatted with specified * arguments. * * @param key * the key of the message. * @param args * the arguments used to format the message. * @return the localized message formatted with the specified arguments. */ public String getMessage(final String key, final Object... args) { logger.trace("Getting message: {}", key); return context.getMessage(key, args, locale); } /** * Gets the title associated with a specified action. * * @param key * The key of the specified action. * @return The title associated with the specified action. */ public String getTitle(String key) { logger.trace("Getting title: {}", key); key += KeySuffix.TITLE; final String title = context.getMessage(key, null, "", locale); logger.trace("Find the title for {}: {}", key, title); return title; } /** * Gets the shortcut associated with a specified action. * * @param id * The ID of the specified action. * @return The shortcut associated with the specified action. */ public String getShortcut(final String id) { logger.trace("Getting shortcut: {}", id); String shortcut = config.getString(id + KeySuffix.SHORTCUT); if (! StringUtils.isEmpty(shortcut)) { // substitute the META key according to the operating system final String meta = (SystemUtils.IS_OS_MAC ? "META" : "CTRL"); shortcut = shortcut.replace("META", meta); } else { shortcut = null; } logger.trace("Find the shortcut for {}: {}", id, shortcut); return shortcut; } /** * Gets the description of an action. * * @param id * the ID of a specified action. * @return the description the specified action, or null if it has no description. */ public String getDescription(final String id) { logger.trace("Getting description: {}", id); String description = context.getMessage(id + KeySuffix.DESCRIPTION, null, null, locale); if (StringUtils.isEmpty(description)) { description = null; } logger.trace("Find the description for {}: {}", id, description); return description; } /** * Gets the URL of the icon of an action. * * @param id * the ID of a specified action. * @return the URL of the icon the specified action, or null if it has none. */ public String getIcon(final String id) { logger.trace("Getting icon: {}", id); String icon = config.getString(id + KeySuffix.ICON); if (StringUtils.isEmpty(icon)) { icon = null; } logger.trace("Find the icon for {}: {}", id, icon); return icon; } /** * Gets the URL of the active icon of an action. * * @param id * the ID of a specified action. * @return the URL of the active icon the specified action, or null if it has none. */ public String getActiveIcon(final String id) { logger.trace("Getting active icon: {}", id); String icon = config.getString(id + KeySuffix.ICON + KeySuffix.ACTIVE); if (StringUtils.isEmpty(icon)) { icon = null; } logger.trace("Find the active icon for {}: {}", id, icon); return icon; } @Override public void publishEvent(final ApplicationEvent event) { context.publishEvent(event); } @Override public Resource[] getResources(final String locationPattern) throws IOException { return context.getResources(locationPattern); } @Override public Resource getResource(final String location) { return context.getResource(location); } @Override public ClassLoader getClassLoader() { return context.getClassLoader(); } @Override public String getId() { return context.getId(); } @Override public String getDisplayName() { return context.getDisplayName(); } @Override public long getStartupDate() { return context.getStartupDate(); } @Override public ApplicationContext getParent() { return context.getParent(); } @Override public AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException { return context.getAutowireCapableBeanFactory(); } @Override public Configuration subset(final String prefix) { return config.subset(prefix); } @Override public boolean isEmpty() { return config.isEmpty(); } @Override public boolean containsKey(final String key) { return config.containsKey(key); } @Override public void addProperty(final String key, final Object value) { config.addProperty(key, value); } @Override public void setProperty(final String key, final Object value) { config.setProperty(key, value); } @Override public void clearProperty(final String key) { config.clearProperty(key); } @Override public void clear() { config.clear(); } @Override public Object getProperty(final String key) { return config.getProperties(key); } @Override public Iterator<String> getKeys(final String prefix) { return config.getKeys(prefix); } @Override public Iterator<String> getKeys() { return config.getKeys(); } @Override public Properties getProperties(final String key) { logger.trace("Getting descriptors: {}", key); return config.getProperties(key); } @Override public boolean getBoolean(final String key) { logger.trace("Getting boolean: {}", key); return config.getBoolean(key); } @Override public boolean getBoolean(final String key, final boolean defaultValue) { logger.trace("Getting boolean: {}", key); return config.getBoolean(key, defaultValue); } @Override public Boolean getBoolean(final String key, final Boolean defaultValue) { logger.trace("Getting boolean: {}", key); return config.getBoolean(key, defaultValue); } @Override public byte getByte(final String key) { logger.trace("Getting byte: {}", key); return config.getByte(key); } @Override public byte getByte(final String key, final byte defaultValue) { logger.trace("Getting byte: {}", key); return config.getByte(key, defaultValue); } @Override public Byte getByte(final String key, final Byte defaultValue) { logger.trace("Getting byte: {}", key); return config.getByte(key, defaultValue); } @Override public double getDouble(final String key) { logger.trace("Getting double: {}", key); return config.getDouble(key); } @Override public double getDouble(final String key, final double defaultValue) { logger.trace("Getting double: {}", key); return config.getDouble(key, defaultValue); } @Override public Double getDouble(final String key, final Double defaultValue) { logger.trace("Getting double: {}", key); return config.getDouble(key, defaultValue); } @Override public float getFloat(final String key) { logger.trace("Getting float: {}", key); return config.getFloat(key); } @Override public float getFloat(final String key, final float defaultValue) { logger.trace("Getting float: {}", key); return config.getFloat(key, defaultValue); } @Override public Float getFloat(final String key, final Float defaultValue) { logger.trace("Getting float: {}", key); return config.getFloat(key, defaultValue); } @Override public int getInt(final String key) { logger.trace("Getting int: {}", key); return config.getInt(key); } @Override public int getInt(final String key, final int defaultValue) { logger.trace("Getting int: {}", key); return config.getInt(key, defaultValue); } @Override public Integer getInteger(final String key, final Integer defaultValue) { logger.trace("Getting integer: {}", key); return config.getInteger(key, defaultValue); } @Override public long getLong(final String key) { logger.trace("Getting long: {}", key); return config.getLong(key); } @Override public long getLong(final String key, final long defaultValue) { logger.trace("Getting long: {}", key); return config.getLong(key, defaultValue); } @Override public Long getLong(final String key, final Long defaultValue) { logger.trace("Getting long: {}", key); return config.getLong(key, defaultValue); } @Override public short getShort(final String key) { logger.trace("Getting short: {}", key); return config.getShort(key); } @Override public short getShort(final String key, final short defaultValue) { logger.trace("Getting short: {}", key); return config.getShort(key, defaultValue); } @Override public Short getShort(final String key, final Short defaultValue) { logger.trace("Getting short: {}", key); return config.getShort(key, defaultValue); } @Override public BigDecimal getBigDecimal(final String key) { logger.trace("Getting big decimal: {}", key); return config.getBigDecimal(key); } @Override public BigDecimal getBigDecimal(final String key, final BigDecimal defaultValue) { logger.trace("Getting big decimal: {}", key); return config.getBigDecimal(key, defaultValue); } @Override public BigInteger getBigInteger(final String key) { logger.trace("Getting big integer: {}", key); return config.getBigInteger(key); } @Override public BigInteger getBigInteger(final String key, final BigInteger defaultValue) { logger.trace("Getting big integer: {}", key); return config.getBigInteger(key, defaultValue); } @Override public String getString(final String key) { logger.trace("Getting string: {}", key); return config.getString(key); } @Override public String getString(final String key, final String defaultValue) { logger.trace("Getting string: {}", key); return config.getString(key, defaultValue); } @Override public String[] getStringArray(final String key) { logger.trace("Getting string array: {}", key); return config.getStringArray(key); } @Override public List<Object> getList(final String key) { logger.trace("Getting list: {}", key); return config.getList(key); } @Override public List<Object> getList(final String key, final List<?> defaultValue) { logger.trace("Getting list: {}", key); return config.getList(key, defaultValue); } @Override public String[] getBeanNamesForAnnotation(final Class<? extends Annotation> arg0) { return context.getBeanNamesForAnnotation(arg0); } @Override public <T> T getBean(final Class<T> arg0, final Object... arg1) throws BeansException { return context.getBean(arg0, arg1); } @Override public String getApplicationName() { return context.getApplicationName(); } }
gpl-2.0
Marghytis/SarahsWorld
SarahsWorld/src/world/render/WorldPainter.java
5672
package world.render; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import org.lwjgl.opengl.GL11; import core.Renderer; import core.Updater; import effects.Effect; import effects.particles.ParticleEffect; import effects.particles.ParticleEmitter; import item.Nametag; import main.Main; import main.Res; import menu.Settings; import render.Animator; import render.Framebuffer; import render.Render; import render.VAO; import things.Thing; import util.Color; import util.math.Vec; import world.World; import world.data.WorldData; import world.window.BackgroundWindow; import world.window.TerrainWindow; import world.window.ThingWindow; public class WorldPainter implements Updater, Renderer{ private WorldData world; //tracking private EffectManager effects; private List<Thing> selected = new ArrayList<>(); //rendering private VAO completeWindow; private Framebuffer landscapeBuffer; private TerrainWindow terrain; private BackgroundWindow background; private ThingWindow things; //others Animator death = new Animator(Res.death, () -> {}, false); public WorldPainter(WorldData l, ThingWindow things, TerrainWindow landscape, BackgroundWindow background) { this.world = l; World.world.window = this; this.things = things; this.terrain = landscape; this.background = background; landscapeBuffer = new Framebuffer("Landscape", Main.SIZE.w, Main.SIZE.h); this.completeWindow = Render.quadInScreen(-Main.HALFSIZE.w, Main.HALFSIZE.h, Main.HALFSIZE.w, -Main.HALFSIZE.h); GL11.glClearColor(0, 0, 0, 0); GL11.glClearStencil(0); effects = new EffectManager(); addEffect(new Nametag()); l.getWeather().addEffects(); } public Vec toWorldPos(Vec windowPos) { windowPos.shift(-Main.HALFSIZE.w, -Main.HALFSIZE.h); windowPos.scale(1/Settings.getDouble("ZOOM")); windowPos.shift(-Render.offsetX, -Render.offsetY); return windowPos; } public void select(Thing t) { selected.add(t); t.selected = true; t.switchedSelected = true; } public void deselect(Thing t) { selected.remove(t); t.selected = false; t.switchedSelected = true; } public int selectionSize() { return selected.size(); } public Thing getSelection(int i) { return selected.get(i); } public boolean update(final double delta){ // delta *= Settings.timeScale; effects.update(delta); if(world.isGameOver()) { death.update(delta); } return false; } Vec lastAvatarPos = new Vec(), avatarPos = new Vec(), offset = new Vec(); public void updateTransform(double interpolationShift) { Render.scaleX = (float)(Settings.getDouble("ZOOM")/Main.HALFSIZE.w); Render.scaleY = (float)(Settings.getDouble("ZOOM")/Main.HALFSIZE.h); lastAvatarPos.set(Main.world.engine.lastAvatarPosition).set(Main.world.avatar.pos); avatarPos.set(Main.world.avatar.pos); offset.set(avatarPos).shift(avatarPos.shift(lastAvatarPos, -1), interpolationShift); Render.offsetX = (float)-offset.x; Render.offsetY = (float)-offset.y; } public void draw(double interpolationShift){ // if(Core.updatedToLong) { // for(int i = 0; i < Main.world.engine.timeIndex; i++) { // System.out.println(Main.world.engine.lastTimes[0][i] + " " + Main.world.engine.lastTimes[1][i] + " " + Main.world.engine.lastTimes[2][i] + " " + Main.world.engine.lastTimes[3][i]); // } // } // Main.world.engine.timeIndex = 0; updateTransform(interpolationShift); background.renderBackground(); landscapeBuffer.bind(); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); terrain.renderLandscape(); Framebuffer.bindNone(); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glAlphaFunc(GL11.GL_GREATER, 0.4f); GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ZERO); Render.drawSingleQuad(completeWindow, Color.WHITE, landscapeBuffer.getTex(), 0, 0, 1f/Main.HALFSIZE.w, 1f/Main.HALFSIZE.h, true, 0); things.renderThings(); GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glDisable(GL11.GL_DEPTH_TEST); terrain.renderWater(); //Outlines of living things things.renderOutlines(); //auras // renderAuras(); //draw the darkness which is crouching out of the earth if(Settings.getBoolean("DARKNESS")){ background.renderDarkness(); } // //draw bounding boxes of all things and their anchor points if(Settings.getBoolean("SHOW_BOUNDING_BOX")){ things.renderBoundingBoxes(); } //effects ParticleEmitter.offset.set(Render.offsetX, Render.offsetY); ParticleEffect.wind.set((Main.input.getMousePos(Main.WINDOW).x - Main.HALFSIZE.w)*60f/Main.HALFSIZE.w, 0); effects.forEach(Effect::render); //quests world.forEachQuest((aq) -> aq.render()); if(world.isGameOver()) { Render.drawSingleQuad(completeWindow, Color.BLACK, null, 0, 0, 1f/Main.HALFSIZE.w, 1f/Main.HALFSIZE.h, false, 0); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); death.bindTex(); death.quad.render(new Vec(), Render.scaleX); GL11.glDisable(GL11.GL_ALPHA_TEST); } } public void forEachEffect(Consumer<Effect> cons) { effects.forEach(cons); } public void addEffect(Effect effect){ effects.addEffect(effect); } public void removeEffect(Effect effect) { effects.removeEffect(effect); } public static String getDayTime() { return "evening"; } public String debugName() { return "World Window"; } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest09197.java
3130
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest09197") public class BenchmarkTest09197 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = ""; java.util.Enumeration<String> headers = request.getHeaders("foo"); if (headers.hasMoreElements()) { param = headers.nextElement(); // just grab first element } String bar = new Test().doSomething(param); java.io.FileOutputStream fos = new java.io.FileOutputStream(org.owasp.benchmark.helpers.Utils.testfileDir + bar, false); } // end doPost private class Test { public String doSomething(String param) throws ServletException, IOException { // Chain a bunch of propagators in sequence String a92930 = param; //assign StringBuilder b92930 = new StringBuilder(a92930); // stick in stringbuilder b92930.append(" SafeStuff"); // append some safe content b92930.replace(b92930.length()-"Chars".length(),b92930.length(),"Chars"); //replace some of the end content java.util.HashMap<String,Object> map92930 = new java.util.HashMap<String,Object>(); map92930.put("key92930", b92930.toString()); // put in a collection String c92930 = (String)map92930.get("key92930"); // get it back out String d92930 = c92930.substring(0,c92930.length()-1); // extract most of it String e92930 = new String( new sun.misc.BASE64Decoder().decodeBuffer( new sun.misc.BASE64Encoder().encode( d92930.getBytes() ) )); // B64 encode and decode it String f92930 = e92930.split(" ")[0]; // split it on a space org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing(); String bar = thing.doSomething(f92930); // reflection return bar; } } // end innerclass Test } // end DataflowThruInnerClass
gpl-2.0
mcberg2016/graal-core2
graal/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/graphbuilderconf/InvocationPlugin.java
11476
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.nodes.graphbuilderconf; import java.lang.invoke.MethodHandle; import java.lang.reflect.Method; import org.graalvm.compiler.debug.GraalError; import org.graalvm.compiler.nodes.Invoke; import org.graalvm.compiler.nodes.ValueNode; import org.graalvm.compiler.nodes.type.StampTool; import jdk.vm.ci.meta.MetaAccessProvider; import jdk.vm.ci.meta.ResolvedJavaMethod; /** * Plugin for handling a specific method invocation. */ public interface InvocationPlugin extends GraphBuilderPlugin { /** * The receiver in a non-static method. The class literal for this interface must be used with * {@link InvocationPlugins#put(InvocationPlugin, boolean, boolean, boolean, Class, String, Class...)} * to denote the receiver argument for such a non-static method. */ public interface Receiver { /** * Gets the receiver value, null checking it first if necessary. * * @return the receiver value with a {@linkplain StampTool#isPointerNonNull(ValueNode) * non-null} stamp */ default ValueNode get() { return get(true); } /** * Gets the receiver value, optionally null checking it first if necessary. */ ValueNode get(boolean performNullCheck); /** * Determines if the receiver is constant. */ default boolean isConstant() { return false; } } /** * Determines if this plugin is for a method with a polymorphic signature (e.g. * {@link MethodHandle#invokeExact(Object...)}). */ default boolean isSignaturePolymorphic() { return false; } /** * Determines if this plugin can only be used when inlining the method is it associated with. * That is, this plugin cannot be used when the associated method is the compilation root. */ default boolean inlineOnly() { return isSignaturePolymorphic(); } /** * Handles invocation of a signature polymorphic method. * * @param receiver access to the receiver, {@code null} if {@code targetMethod} is static * @param argsIncludingReceiver all arguments to the invocation include the raw receiver in * position 0 if {@code targetMethod} is not static * @see #execute */ default boolean applyPolymorphic(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode... argsIncludingReceiver) { return defaultHandler(b, targetMethod, receiver, argsIncludingReceiver); } /** * @see #execute */ default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver) { return defaultHandler(b, targetMethod, receiver); } /** * @see #execute */ default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg) { return defaultHandler(b, targetMethod, receiver, arg); } /** * @see #execute */ default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg1, ValueNode arg2) { return defaultHandler(b, targetMethod, receiver, arg1, arg2); } /** * @see #execute */ default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg1, ValueNode arg2, ValueNode arg3) { return defaultHandler(b, targetMethod, receiver, arg1, arg2, arg3); } /** * @see #execute */ default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg1, ValueNode arg2, ValueNode arg3, ValueNode arg4) { return defaultHandler(b, targetMethod, receiver, arg1, arg2, arg3, arg4); } /** * @see #execute */ default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg1, ValueNode arg2, ValueNode arg3, ValueNode arg4, ValueNode arg5) { return defaultHandler(b, targetMethod, receiver, arg1, arg2, arg3, arg4, arg5); } /** * @see #execute */ default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg1, ValueNode arg2, ValueNode arg3, ValueNode arg4, ValueNode arg5, ValueNode arg6) { return defaultHandler(b, targetMethod, receiver, arg1, arg2, arg3, arg4, arg5, arg6); } /** * @see #execute */ default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg1, ValueNode arg2, ValueNode arg3, ValueNode arg4, ValueNode arg5, ValueNode arg6, ValueNode arg7) { return defaultHandler(b, targetMethod, receiver, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } /** * Executes this plugin against a set of invocation arguments. * * The default implementation in {@link InvocationPlugin} dispatches to the {@code apply(...)} * method that matches the number of arguments or to {@link #applyPolymorphic} if {@code plugin} * is {@linkplain #isSignaturePolymorphic() signature polymorphic}. * * @param targetMethod the method for which this plugin is being applied * @param receiver access to the receiver, {@code null} if {@code targetMethod} is static * @param argsIncludingReceiver all arguments to the invocation include the receiver in position * 0 if {@code targetMethod} is not static * @return {@code true} if this plugin handled the invocation of {@code targetMethod} * {@code false} if the graph builder should process the invoke further (e.g., by * inlining it or creating an {@link Invoke} node). A plugin that does not handle an * invocation must not modify the graph being constructed. */ default boolean execute(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode[] argsIncludingReceiver) { if (isSignaturePolymorphic()) { return applyPolymorphic(b, targetMethod, receiver, argsIncludingReceiver); } else if (receiver != null) { assert !targetMethod.isStatic(); assert argsIncludingReceiver.length > 0; if (argsIncludingReceiver.length == 1) { return apply(b, targetMethod, receiver); } else if (argsIncludingReceiver.length == 2) { return apply(b, targetMethod, receiver, argsIncludingReceiver[1]); } else if (argsIncludingReceiver.length == 3) { return apply(b, targetMethod, receiver, argsIncludingReceiver[1], argsIncludingReceiver[2]); } else if (argsIncludingReceiver.length == 4) { return apply(b, targetMethod, receiver, argsIncludingReceiver[1], argsIncludingReceiver[2], argsIncludingReceiver[3]); } else if (argsIncludingReceiver.length == 5) { return apply(b, targetMethod, receiver, argsIncludingReceiver[1], argsIncludingReceiver[2], argsIncludingReceiver[3], argsIncludingReceiver[4]); } else { return defaultHandler(b, targetMethod, receiver, argsIncludingReceiver); } } else { assert targetMethod.isStatic(); if (argsIncludingReceiver.length == 0) { return apply(b, targetMethod, null); } else if (argsIncludingReceiver.length == 1) { return apply(b, targetMethod, null, argsIncludingReceiver[0]); } else if (argsIncludingReceiver.length == 2) { return apply(b, targetMethod, null, argsIncludingReceiver[0], argsIncludingReceiver[1]); } else if (argsIncludingReceiver.length == 3) { return apply(b, targetMethod, null, argsIncludingReceiver[0], argsIncludingReceiver[1], argsIncludingReceiver[2]); } else if (argsIncludingReceiver.length == 4) { return apply(b, targetMethod, null, argsIncludingReceiver[0], argsIncludingReceiver[1], argsIncludingReceiver[2], argsIncludingReceiver[3]); } else if (argsIncludingReceiver.length == 5) { return apply(b, targetMethod, null, argsIncludingReceiver[0], argsIncludingReceiver[1], argsIncludingReceiver[2], argsIncludingReceiver[3], argsIncludingReceiver[4]); } else if (argsIncludingReceiver.length == 6) { return apply(b, targetMethod, null, argsIncludingReceiver[0], argsIncludingReceiver[1], argsIncludingReceiver[2], argsIncludingReceiver[3], argsIncludingReceiver[4], argsIncludingReceiver[5]); } else if (argsIncludingReceiver.length == 7) { return apply(b, targetMethod, null, argsIncludingReceiver[0], argsIncludingReceiver[1], argsIncludingReceiver[2], argsIncludingReceiver[3], argsIncludingReceiver[4], argsIncludingReceiver[5], argsIncludingReceiver[6]); } else { return defaultHandler(b, targetMethod, receiver, argsIncludingReceiver); } } } /** * Handles an invocation when a specific {@code apply} method is not available. */ default boolean defaultHandler(@SuppressWarnings("unused") GraphBuilderContext b, ResolvedJavaMethod targetMethod, @SuppressWarnings("unused") InvocationPlugin.Receiver receiver, ValueNode... args) { throw new GraalError("Invocation plugin for %s does not handle invocations with %d arguments", targetMethod.format("%H.%n(%p)"), args.length); } default StackTraceElement getApplySourceLocation(MetaAccessProvider metaAccess) { Class<?> c = getClass(); for (Method m : c.getDeclaredMethods()) { if (m.getName().equals("apply")) { return metaAccess.lookupJavaMethod(m).asStackTraceElement(0); } else if (m.getName().equals("defaultHandler")) { return metaAccess.lookupJavaMethod(m).asStackTraceElement(0); } } throw new GraalError("could not find method named \"apply\" or \"defaultHandler\" in " + c.getName()); } }
gpl-2.0
mzmine/mzmine3
src/main/java/io/github/mzmine/modules/dataprocessing/filter_scanfilters/mean/MeanFilterParameters.java
1741
/* * Copyright 2006-2021 The MZmine Development Team * * This file is part of MZmine. * * MZmine is free software; you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * MZmine 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 MZmine; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package io.github.mzmine.modules.dataprocessing.filter_scanfilters.mean; import java.awt.Window; import io.github.mzmine.modules.dataprocessing.filter_scanfilters.ScanFilterSetupDialog; import io.github.mzmine.parameters.UserParameter; import io.github.mzmine.parameters.impl.SimpleParameterSet; import io.github.mzmine.parameters.parametertypes.DoubleParameter; import io.github.mzmine.util.ExitCode; public class MeanFilterParameters extends SimpleParameterSet { public static final DoubleParameter oneSidedWindowLength = new DoubleParameter("Window length", "One-sided length of the smoothing window"); public MeanFilterParameters() { super(new UserParameter[] {oneSidedWindowLength}); } public ExitCode showSetupDialog(boolean valueCheckRequired) { ScanFilterSetupDialog dialog = new ScanFilterSetupDialog(valueCheckRequired, this, MeanFilter.class); dialog.showAndWait(); return dialog.getExitCode(); } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jdk/src/share/classes/javax/management/MBeanFeatureInfo.java
9932
/* * Copyright 1999-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package javax.management; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.io.StreamCorruptedException; /** * <p>Provides general information for an MBean descriptor object. * The feature described can be an attribute, an operation, a * parameter, or a notification. Instances of this class are * immutable. Subclasses may be mutable but this is not * recommended.</p> * * @since 1.5 */ public class MBeanFeatureInfo implements Serializable, DescriptorRead { /* Serial version */ static final long serialVersionUID = 3952882688968447265L; /** * The name of the feature. It is recommended that subclasses call * {@link #getName} rather than reading this field, and that they * not change it. * * @serial The name of the feature. */ protected String name; /** * The human-readable description of the feature. It is * recommended that subclasses call {@link #getDescription} rather * than reading this field, and that they not change it. * * @serial The human-readable description of the feature. */ protected String description; /** * @serial The Descriptor for this MBeanFeatureInfo. This field * can be null, which is equivalent to an empty Descriptor. */ private transient Descriptor descriptor; /** * Constructs an <CODE>MBeanFeatureInfo</CODE> object. This * constructor is equivalent to {@code MBeanFeatureInfo(name, * description, (Descriptor) null}. * * @param name The name of the feature. * @param description A human readable description of the feature. */ public MBeanFeatureInfo(String name, String description) { this(name, description, null); } /** * Constructs an <CODE>MBeanFeatureInfo</CODE> object. * * @param name The name of the feature. * @param description A human readable description of the feature. * @param descriptor The descriptor for the feature. This may be null * which is equivalent to an empty descriptor. * * @since 1.6 */ public MBeanFeatureInfo(String name, String description, Descriptor descriptor) { this.name = name; this.description = description; this.descriptor = descriptor; } /** * Returns the name of the feature. * * @return the name of the feature. */ public String getName() { return name; } /** * Returns the human-readable description of the feature. * * @return the human-readable description of the feature. */ public String getDescription() { return description; } /** * Returns the descriptor for the feature. Changing the returned value * will have no affect on the original descriptor. * * @return a descriptor that is either immutable or a copy of the original. * * @since 1.6 */ public Descriptor getDescriptor() { return (Descriptor) ImmutableDescriptor.nonNullDescriptor(descriptor).clone(); } /** * Compare this MBeanFeatureInfo to another. * * @param o the object to compare to. * * @return true if and only if <code>o</code> is an MBeanFeatureInfo such * that its {@link #getName()}, {@link #getDescription()}, and * {@link #getDescriptor()} * values are equal (not necessarily identical) to those of this * MBeanFeatureInfo. */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof MBeanFeatureInfo)) return false; MBeanFeatureInfo p = (MBeanFeatureInfo) o; return (p.getName().equals(getName()) && p.getDescription().equals(getDescription()) && p.getDescriptor().equals(getDescriptor())); } public int hashCode() { return getName().hashCode() ^ getDescription().hashCode() ^ getDescriptor().hashCode(); } /** * Serializes an {@link MBeanFeatureInfo} to an {@link ObjectOutputStream}. * @serialData * For compatibility reasons, an object of this class is serialized as follows. * <ul> * The method {@link ObjectOutputStream#defaultWriteObject defaultWriteObject()} * is called first to serialize the object except the field {@code descriptor} * which is declared as transient. The field {@code descriptor} is serialized * as follows: * <ul> * <li>If {@code descriptor} is an instance of the class * {@link ImmutableDescriptor}, the method {@link ObjectOutputStream#write * write(int val)} is called to write a byte with the value {@code 1}, * then the method {@link ObjectOutputStream#writeObject writeObject(Object obj)} * is called twice to serialize the field names and the field values of the * {@code descriptor}, respectively as a {@code String[]} and an * {@code Object[]};</li> * <li>Otherwise, the method {@link ObjectOutputStream#write write(int val)} * is called to write a byte with the value {@code 0}, then the method * {@link ObjectOutputStream#writeObject writeObject(Object obj)} is called * to serialize directly the field {@code descriptor}. * </ul> * </ul> * @since 1.6 */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); if (descriptor != null && descriptor.getClass() == ImmutableDescriptor.class) { out.write(1); final String[] names = descriptor.getFieldNames(); out.writeObject(names); out.writeObject(descriptor.getFieldValues(names)); } else { out.write(0); out.writeObject(descriptor); } } /** * Deserializes an {@link MBeanFeatureInfo} from an {@link ObjectInputStream}. * @serialData * For compatibility reasons, an object of this class is deserialized as follows. * <ul> * The method {@link ObjectInputStream#defaultReadObject defaultReadObject()} * is called first to deserialize the object except the field * {@code descriptor}, which is not serialized in the default way. Then the method * {@link ObjectInputStream#read read()} is called to read a byte, the field * {@code descriptor} is deserialized according to the value of the byte value: * <ul> * <li>1. The method {@link ObjectInputStream#readObject readObject()} * is called twice to obtain the field names (a {@code String[]}) and * the field values (a {@code Object[]}) of the {@code descriptor}. * The two obtained values then are used to construct * an {@link ImmutableDescriptor} instance for the field * {@code descriptor};</li> * <li>0. The value for the field {@code descriptor} is obtained directly * by calling the method {@link ObjectInputStream#readObject readObject()}. * If the obtained value is null, the field {@code descriptor} is set to * {@link ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR};</li> * <li>-1. This means that there is no byte to read and that the object is from * an earlier version of the JMX API. The field {@code descriptor} is set * to {@link ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR}</li> * <li>Any other value. A {@link StreamCorruptedException} is thrown.</li> * </ul> * </ul> * @since 1.6 */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); switch (in.read()) { case 1: final String[] names = (String[])in.readObject(); if (names.length == 0) { descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR; } else { final Object[] values = (Object[])in.readObject(); descriptor = new ImmutableDescriptor(names, values); } break; case 0: descriptor = (Descriptor)in.readObject(); if (descriptor == null) { descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR; } break; case -1: // from an earlier version of the JMX API descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR; break; default: throw new StreamCorruptedException("Got unexpected byte."); } } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest14967.java
2214
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest14967") public class BenchmarkTest14967 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getHeader("foo"); String bar = doSomething(param); Object[] obj = { "a", "b" }; response.getWriter().format(java.util.Locale.US,bar,obj); } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar = "safe!"; java.util.HashMap<String,Object> map83646 = new java.util.HashMap<String,Object>(); map83646.put("keyA-83646", "a Value"); // put some stuff in the collection map83646.put("keyB-83646", param.toString()); // put it in a collection map83646.put("keyC", "another Value"); // put some stuff in the collection bar = (String)map83646.get("keyB-83646"); // get it back out return bar; } }
gpl-2.0
meijmOrg/Repo-test
freelance-hr-component/src/java/com/yh/hr/component/im/check/service/impl/DataLengthCheckServiceImpl.java
2107
package com.yh.hr.component.im.check.service.impl; import java.util.List; import org.apache.commons.collections.CollectionUtils; import com.yh.hr.component.im.check.service.CollItemCheckService; import com.yh.hr.component.im.dto.CheckColumnDTO; import com.yh.hr.component.im.dto.CheckResultDTO; import com.yh.hr.res.dictionary.DicConstants; import com.yh.hr.res.im.dto.ImCollectTemplateDTO; import com.yh.platform.core.exception.ServiceException; /** * 数据项长度检查实现类 * @author wangx * @date 2017-07-11 * @version 1.0 */ public class DataLengthCheckServiceImpl implements CollItemCheckService { /** * 数据项长度检查 * @param column * @param collList 已映射的采集项模板 * @throws ServiceException */ public CheckResultDTO check(CheckColumnDTO column,List<ImCollectTemplateDTO> collList) throws ServiceException { String importCollName = column.getImportCollName(); if(importCollName==null) { throw new ServiceException(null, "导入采集项名称不能为空!"); } ImCollectTemplateDTO imCollectTemplateDTO=null; if(CollectionUtils.isNotEmpty(collList)) { for(ImCollectTemplateDTO collDTO:collList) { if(DicConstants.YHRS0003_1.equals(collDTO.getEffectiveFlag())&&importCollName.equals(collDTO.getImportCollName())) { imCollectTemplateDTO = collDTO; } } } String importCollValue = column.getImportCollValue(); if(importCollValue!=null&&!"".equals(importCollValue)) { if(imCollectTemplateDTO!=null) { Integer importCollMaxlength = imCollectTemplateDTO.getImportCollMaxlength(); Integer valueLength = importCollValue.length(); if(valueLength>importCollMaxlength) { CheckResultDTO result = new CheckResultDTO(); result.setDatabaseColumnCode(imCollectTemplateDTO.getDatabaseColumnCode()); result.setImportCollValue(importCollValue); result.setCheckType(column.getCheckType()); result.setCheckStatus(DicConstants.YHRS0003_0); result.setCheckMessage("“"+imCollectTemplateDTO.getTemplateCollName()+"”长度超长"); return result; } } } return null; } }
gpl-2.0
supalogix/java-liskov-example
src/CountIntegers.java
293
class CountUniqueIntegers { private Set<Integer> set; public CountIntegers( Set<Integer> set ) { this.set = set; } public int getCount( int[] array ) { int length = array.length; for( int i = 0; i < length; i ++ ) this.set.push( array[i] ); return this.set.size(); } }
gpl-2.0
A203/LuWeidan
CalculatorApplication/app/src/main/java/com/geminno/calculatorapplication/MainActivity.java
9472
package com.geminno.calculatorapplication; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.app.Activity; public class MainActivity extends Activity implements OnClickListener { //ÉùÃ÷һЩ¿Ø¼þ Button btn0=null; Button btn1=null; Button btn2=null; Button btn3=null; Button btn4=null; Button btn5=null; Button btn6=null; Button btn7=null; Button btn8=null; Button btn9=null; Button btnBackspace=null; Button btnCE=null; Button btnC=null; Button btnAdd=null; Button btnSub=null; Button btnMul=null; Button btnDiv=null; Button btnEqu=null; TextView tvResult=null; //ÉùÃ÷Á½¸ö²ÎÊý¡£½ÓÊÕtvResultǰºóµÄÖµ double num1=0,num2=0; double Result=0;//¼ÆËã½á¹û int op=0;//ÅжϲÙ×÷Êý£¬ boolean isClickEqu=false;//ÅжÏÊÇ·ñ°´ÁË¡°=¡±°´Å¥ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //´Ó²¼¾ÖÎļþÖлñÈ¡¿Ø¼þ£¬ btn0=(Button)findViewById(R.id.btn0); btn1=(Button)findViewById(R.id.btn1); btn2=(Button)findViewById(R.id.btn2); btn3=(Button)findViewById(R.id.btn3); btn4=(Button)findViewById(R.id.btn4); btn5=(Button)findViewById(R.id.btn5); btn6=(Button)findViewById(R.id.btn6); btn7=(Button)findViewById(R.id.btn7); btn8=(Button)findViewById(R.id.btn8); btn9=(Button)findViewById(R.id.btn9); btnBackspace=(Button)findViewById(R.id.btnBackspace); btnCE=(Button)findViewById(R.id.btnCE); btnC=(Button)findViewById(R.id.btnC); btnEqu=(Button)findViewById(R.id.btnEqu); btnAdd=(Button)findViewById(R.id.btnAdd); btnSub=(Button)findViewById(R.id.btnSub); btnMul=(Button)findViewById(R.id.btnMul); btnDiv=(Button)findViewById(R.id.btnDiv); tvResult=(TextView)findViewById(R.id.tvResult); //Ìí¼Ó¼àÌý\ btnBackspace.setOnClickListener(this); btnCE.setOnClickListener(this); btn0.setOnClickListener(this); btn1.setOnClickListener(this); btn2.setOnClickListener(this); btn3.setOnClickListener(this); btn4.setOnClickListener(this); btn5.setOnClickListener(this); btn6.setOnClickListener(this); btn7.setOnClickListener(this); btn8.setOnClickListener(this); btn9.setOnClickListener(this); btnAdd.setOnClickListener(this); btnSub.setOnClickListener(this); btnMul.setOnClickListener(this); btnDiv.setOnClickListener(this); btnEqu.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { //btnBackspaceºÍCE-------------------- case R.id.btnBackspace: String myStr=tvResult.getText().toString(); try { tvResult.setText(myStr.substring(0, myStr.length()-1)); } catch (Exception e) { tvResult.setText(""); } break; case R.id.btnCE: tvResult.setText(null); break; //btn0--9--------------------------- case R.id.btn0: if(isClickEqu) { tvResult.setText(null); isClickEqu=false; } String myString=tvResult.getText().toString(); myString+="0"; tvResult.setText(myString); break; case R.id.btn1: if(isClickEqu) { tvResult.setText(null); isClickEqu=false; } String myString1=tvResult.getText().toString(); myString1+="1"; tvResult.setText(myString1); break; case R.id.btn2: if(isClickEqu) { tvResult.setText(null); isClickEqu=false; } String myString2=tvResult.getText().toString(); myString2+="2"; tvResult.setText(myString2); break; case R.id.btn3: if(isClickEqu) { tvResult.setText(null); isClickEqu=false; } String myString3=tvResult.getText().toString(); myString3+="3"; tvResult.setText(myString3); break; case R.id.btn4: if(isClickEqu) { tvResult.setText(null); isClickEqu=false; } String myString4=tvResult.getText().toString(); myString4+="4"; tvResult.setText(myString4); break; case R.id.btn5: if(isClickEqu) { tvResult.setText(null); isClickEqu=false; } String myString5=tvResult.getText().toString(); myString5+="5"; tvResult.setText(myString5); break; case R.id.btn6: if(isClickEqu) { tvResult.setText(null); isClickEqu=false; } String myString6=tvResult.getText().toString(); myString6+="6"; tvResult.setText(myString6); break; case R.id.btn7: if(isClickEqu) { tvResult.setText(null); isClickEqu=false; } String myString7=tvResult.getText().toString(); myString7+="7"; tvResult.setText(myString7); break; case R.id.btn8: if(isClickEqu) { tvResult.setText(null); isClickEqu=false; } String myString8=tvResult.getText().toString(); myString8+="8"; tvResult.setText(myString8); break; case R.id.btn9: if(isClickEqu) { tvResult.setText(null); isClickEqu=false; } String myString9=tvResult.getText().toString(); myString9+="9"; tvResult.setText(myString9); break; //btn+-*/=-------------------------------- case R.id.btnAdd: String myStringAdd=tvResult.getText().toString(); if(myStringAdd.equals(null)) { return; } num1=Double.valueOf(myStringAdd); tvResult.setText(null); op=1; isClickEqu=false; break; // case R.id.btnSub: case R.id.btnSub: String myStringSub=tvResult.getText().toString(); if(myStringSub.equals(null)) { return; } num1=Double.valueOf(myStringSub); tvResult.setText(null); op=2; isClickEqu=false; break; case R.id.btnMul: String myStringMul=tvResult.getText().toString(); if(myStringMul.equals(null)) { return; } num1=Double.valueOf(myStringMul); tvResult.setText(null); op=3; isClickEqu=false; break; case R.id.btnDiv: String myStringDiv=tvResult.getText().toString(); if(myStringDiv.equals(null)) { return; } num1=Double.valueOf(myStringDiv); tvResult.setText(null); op=4; isClickEqu=false; break; case R.id.btnEqu: String myStringEqu=tvResult.getText().toString(); if(myStringEqu.equals(null)) { return; } num2=Double.valueOf(myStringEqu); tvResult.setText(null); switch (op) { case 0: Result=num2; break; case 1: Result=num1+num2; break; case 2: Result=num1-num2; break; case 3: Result=num1*num2; break; case 4: Result=num1/num2; break; default: Result=0; break; } tvResult.setText(String.valueOf(Result)); isClickEqu=true; break; default: break; } } }
gpl-2.0
IntellectualSites/IntellectualServer
ServerAPI/src/main/java/xyz/kvantum/server/api/views/ViewDetector.java
5465
/* * _ __ _ * | |/ /__ __ __ _ _ __ | |_ _ _ _ __ ___ * | ' / \ \ / // _` || '_ \ | __|| | | || '_ ` _ \ * | . \ \ V /| (_| || | | || |_ | |_| || | | | | | * |_|\_\ \_/ \__,_||_| |_| \__| \__,_||_| |_| |_| * * Copyright (C) 2019 Alexander Söderberg * * 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 xyz.kvantum.server.api.views; import xyz.kvantum.files.Path; import xyz.kvantum.server.api.util.MapBuilder; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; /** * Can be used to detect file structures that could be served by the standard library of {@link View views} */ @SuppressWarnings("unused") public final class ViewDetector { private final String basePath; private final Collection<String> ignore; private final Path basePathObject; private final Set<Path> paths = new HashSet<>(); private final Map<String, Map<String, Object>> viewEntries = new HashMap<>(); public ViewDetector(final String basePath, final Path basePathObject, final Collection<String> ignore) { this.basePath = basePath; this.ignore = ignore; this.basePathObject = basePathObject; } public int loadPaths() { this.paths.add(this.basePathObject); this.addSubPaths(this.basePathObject); return this.paths.size(); } public Collection<Path> getPaths() { return new ArrayList<>(this.paths); } public Map<String, Map<String, Object>> getViewEntries() { return new HashMap<>(this.viewEntries); } public void generateViewEntries() { this.paths.forEach(p -> loadSubPath(viewEntries, basePath, basePathObject.toString(), p)); } private void loadSubPath(final Map<String, Map<String, Object>> viewEntries, final String basePath, final String toRemove, final Path path) { String extension = null; boolean moreThanOneType = false; boolean hasIndex = false; String indexExtension = ""; for (final Path subPath : path.getSubPaths(false)) { if (extension == null) { extension = subPath.getExtension(); } else if (!extension.equalsIgnoreCase(subPath.getExtension())) { moreThanOneType = true; } if (!hasIndex) { hasIndex = subPath.getEntityName().equals("index"); indexExtension = subPath.getExtension(); } } if (extension == null) { return; } final String type; if (moreThanOneType) { type = "std"; } else { switch (extension) { case "html": type = "html"; break; case "js": type = "javascript"; break; case "css": type = "css"; break; case "png": case "jpg": case "jpeg": case "ico": type = "img"; break; case "zip": case "txt": case "pdf": type = "download"; break; default: type = "std"; break; } } final String folder = "./" + path.toString(); final String viewPattern; if (moreThanOneType) { if (hasIndex) { viewPattern = (path.toString().replace(toRemove, basePath)) + "[file=index].[extension=" + indexExtension + "]"; } else { viewPattern = (path.toString().replace(toRemove, basePath)) + "<file>.<extension>"; } } else { if (hasIndex) { viewPattern = (path.toString().replace(toRemove, basePath)) + "[file=index].[extension=" + indexExtension + "]"; } else { viewPattern = (path.toString().replace(toRemove, basePath)) + "<file>." + extension; } } final Map<String, Object> info = MapBuilder.<String, Object>newHashMap().put("filter", viewPattern) .put("options", MapBuilder.newHashMap().put("folder", folder).get()) .put("type", type).get(); viewEntries.put(UUID.randomUUID().toString(), info); } private void addSubPaths(final Path path) { for (final Path subPath : path.getSubPaths()) { if (!subPath.isFolder() || ignore.contains(subPath.getEntityName())) { continue; } paths.add(subPath); addSubPaths(subPath); } } }
gpl-2.0
xvhfeng/albianj
Albianj.Persistence.Impl/src/main/java/org/albianj/persistence/impl/db/IUpdateCommand.java
524
package org.albianj.persistence.impl.db; import java.util.Map; import org.albianj.persistence.object.IAlbianObject; import org.albianj.persistence.object.IAlbianObjectAttribute; import org.albianj.persistence.object.IRoutingAttribute; import org.albianj.persistence.object.IRoutingsAttribute; public interface IUpdateCommand { public ICommand builder(IAlbianObject object, IRoutingsAttribute routings, IAlbianObjectAttribute albianObject, Map<String, Object> mapValue, IRoutingAttribute routing); }
gpl-2.0
aktion-hip/vif
org.hip.vif.member.ldap/src/org/hip/vif/member/ldap/LDAPMemberInformation.java
3356
/** This package is part of the application VIF. Copyright (C) 2008-2015, Benno Luthiger This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.hip.vif.member.ldap; import java.sql.SQLException; import java.util.Map; import org.hip.kernel.bom.GettingException; import org.hip.kernel.exc.VException; import org.hip.vif.core.bom.Member; import org.hip.vif.core.bom.MemberHome; import org.hip.vif.core.member.AbstractMemberInformation; import org.hip.vif.core.member.IMemberInformation; /** @author Luthiger Created: 07.01.2008 */ public class LDAPMemberInformation extends AbstractMemberInformation implements IMemberInformation { private final static Object[][] MEMBER_PROPERTIES = { { MemberHome.KEY_USER_ID, "" }, { MemberHome.KEY_NAME, "" }, { MemberHome.KEY_FIRSTNAME, "" }, { MemberHome.KEY_MAIL, "" }, { MemberHome.KEY_SEX, Integer.valueOf(-1) }, { MemberHome.KEY_CITY, "" }, { MemberHome.KEY_STREET, "" }, { MemberHome.KEY_ZIP, "" }, { MemberHome.KEY_PHONE, "" }, { MemberHome.KEY_FAX, "" } }; private transient String userID = ""; // NOPMD by lbenno /** LDAPMemberInformation constructor. * * @param inSource {@link Member} the member instance backing this information * @throws VException */ public LDAPMemberInformation(final Member inSource) throws VException { super(); userID = loadValues(inSource); } @Override public void update(final Member inMember) throws SQLException, VException { // NOPMD by lbenno setAllTo(inMember); inMember.update(true); } @Override public Long insert(final Member inMember) throws SQLException, VException { // NOPMD by lbenno setAllTo(inMember); return inMember.insert(true); } private String loadValues(final Member inSource) throws VException { for (int i = 0; i < MEMBER_PROPERTIES.length; i++) { final String lKey = MEMBER_PROPERTIES[i][0].toString(); Object lValue = null; try { lValue = inSource.get(lKey); } catch (final GettingException exc) { lValue = MEMBER_PROPERTIES[i][1]; } put(lKey, lValue); } return inSource.get(MemberHome.KEY_USER_ID).toString(); } private void setAllTo(final Member inMember) throws VException { for (final Map.Entry<String, Object> lEntry : entries()) { inMember.set(lEntry.getKey(), lEntry.getValue()); } } @Override public String getUserID() { // NOPMD by lbenno return userID; } }
gpl-2.0
digantDj/Gifff-Talk
TMessagesProj/src/main/java/org/giffftalk/messenger/audioinfo/m4a/MP4Box.java
2379
/* * Copyright 2013-2014 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.giffftalk.messenger.audioinfo.m4a; import org.giffftalk.messenger.audioinfo.util.PositionInputStream; import org.giffftalk.messenger.audioinfo.util.RangeInputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; public class MP4Box<I extends PositionInputStream> { protected static final String ASCII = "ISO8859_1"; private final I input; private final MP4Box<?> parent; private final String type; protected final DataInput data; private MP4Atom child; public MP4Box(I input, MP4Box<?> parent, String type) { this.input = input; this.parent = parent; this.type = type; this.data = new DataInputStream(input); } public String getType() { return type; } public MP4Box<?> getParent() { return parent; } public long getPosition() { return input.getPosition(); } public I getInput() { return input; } protected MP4Atom getChild() { return child; } public MP4Atom nextChild() throws IOException { if (child != null) { child.skip(); } int atomLength = data.readInt(); byte[] typeBytes = new byte[4]; data.readFully(typeBytes); String atomType = new String(typeBytes, ASCII); RangeInputStream atomInput; if (atomLength == 1) { // extended length atomInput = new RangeInputStream(input, 16, data.readLong() - 16); } else { atomInput = new RangeInputStream(input, 8, atomLength - 8); } return child = new MP4Atom(atomInput, this, atomType); } public MP4Atom nextChild(String expectedTypeExpression) throws IOException { MP4Atom atom = nextChild(); if (atom.getType().matches(expectedTypeExpression)) { return atom; } throw new IOException("atom type mismatch, expected " + expectedTypeExpression + ", got " + atom.getType()); } }
gpl-2.0
tectronics/xenogeddon
src/com/jmex/model/collada/schema/rigid_constraintType.java
19115
/** * rigid_constraintType.java * * This file was generated by XMLSpy 2007sp2 Enterprise Edition. * * YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE * OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. * * Refer to the XMLSpy Documentation for further details. * http://www.altova.com/xmlspy */ package com.jmex.model.collada.schema; import com.jmex.xml.types.SchemaNCName; public class rigid_constraintType extends com.jmex.xml.xml.Node { public rigid_constraintType(rigid_constraintType node) { super(node); } public rigid_constraintType(org.w3c.dom.Node node) { super(node); } public rigid_constraintType(org.w3c.dom.Document doc) { super(doc); } public rigid_constraintType(com.jmex.xml.xml.Document doc, String namespaceURI, String prefix, String name) { super(doc, namespaceURI, prefix, name); } public void adjustPrefix() { for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Attribute, null, "sid" ); tmpNode != null; tmpNode = getDomNextChild( Attribute, null, "sid", tmpNode ) ) { internalAdjustPrefix(tmpNode, false); } for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Attribute, null, "name" ); tmpNode != null; tmpNode = getDomNextChild( Attribute, null, "name", tmpNode ) ) { internalAdjustPrefix(tmpNode, false); } for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment" ); tmpNode != null; tmpNode = getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", tmpNode ) ) { internalAdjustPrefix(tmpNode, true); new ref_attachmentType(tmpNode).adjustPrefix(); } for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment" ); tmpNode != null; tmpNode = getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment", tmpNode ) ) { internalAdjustPrefix(tmpNode, true); new attachmentType(tmpNode).adjustPrefix(); } for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common" ); tmpNode != null; tmpNode = getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common", tmpNode ) ) { internalAdjustPrefix(tmpNode, true); new technique_commonType8(tmpNode).adjustPrefix(); } for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "technique" ); tmpNode != null; tmpNode = getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "technique", tmpNode ) ) { internalAdjustPrefix(tmpNode, true); new techniqueType5(tmpNode).adjustPrefix(); } for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "extra" ); tmpNode != null; tmpNode = getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "extra", tmpNode ) ) { internalAdjustPrefix(tmpNode, true); new extraType(tmpNode).adjustPrefix(); } } public void setXsiType() { org.w3c.dom.Element el = (org.w3c.dom.Element) domNode; el.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:type", "rigid_constraint"); } public static int getsidMinCount() { return 1; } public static int getsidMaxCount() { return 1; } public int getsidCount() { return getDomChildCount(Attribute, null, "sid"); } public boolean hassid() { return hasDomChild(Attribute, null, "sid"); } public SchemaNCName newsid() { return new SchemaNCName(); } public SchemaNCName getsidAt(int index) throws Exception { return new SchemaNCName(getDomNodeValue(getDomChildAt(Attribute, null, "sid", index))); } public org.w3c.dom.Node getStartingsidCursor() throws Exception { return getDomFirstChild(Attribute, null, "sid" ); } public org.w3c.dom.Node getAdvancedsidCursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Attribute, null, "sid", curNode ); } public SchemaNCName getsidValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new SchemaNCName(getDomNodeValue(curNode)); } public SchemaNCName getsid() throws Exception { return getsidAt(0); } public void removesidAt(int index) { removeDomChildAt(Attribute, null, "sid", index); } public void removesid() { removesidAt(0); } public org.w3c.dom.Node addsid(SchemaNCName value) { if( value.isNull() ) return null; return appendDomChild(Attribute, null, "sid", value.toString()); } public org.w3c.dom.Node addsid(String value) throws Exception { return addsid(new SchemaNCName(value)); } public void insertsidAt(SchemaNCName value, int index) { insertDomChildAt(Attribute, null, "sid", index, value.toString()); } public void insertsidAt(String value, int index) throws Exception { insertsidAt(new SchemaNCName(value), index); } public void replacesidAt(SchemaNCName value, int index) { replaceDomChildAt(Attribute, null, "sid", index, value.toString()); } public void replacesidAt(String value, int index) throws Exception { replacesidAt(new SchemaNCName(value), index); } public static int getnameMinCount() { return 0; } public static int getnameMaxCount() { return 1; } public int getnameCount() { return getDomChildCount(Attribute, null, "name"); } public boolean hasname() { return hasDomChild(Attribute, null, "name"); } public SchemaNCName newname() { return new SchemaNCName(); } public SchemaNCName getnameAt(int index) throws Exception { return new SchemaNCName(getDomNodeValue(getDomChildAt(Attribute, null, "name", index))); } public org.w3c.dom.Node getStartingnameCursor() throws Exception { return getDomFirstChild(Attribute, null, "name" ); } public org.w3c.dom.Node getAdvancednameCursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Attribute, null, "name", curNode ); } public SchemaNCName getnameValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new SchemaNCName(getDomNodeValue(curNode)); } public SchemaNCName getname() throws Exception { return getnameAt(0); } public void removenameAt(int index) { removeDomChildAt(Attribute, null, "name", index); } public void removename() { removenameAt(0); } public org.w3c.dom.Node addname(SchemaNCName value) { if( value.isNull() ) return null; return appendDomChild(Attribute, null, "name", value.toString()); } public org.w3c.dom.Node addname(String value) throws Exception { return addname(new SchemaNCName(value)); } public void insertnameAt(SchemaNCName value, int index) { insertDomChildAt(Attribute, null, "name", index, value.toString()); } public void insertnameAt(String value, int index) throws Exception { insertnameAt(new SchemaNCName(value), index); } public void replacenameAt(SchemaNCName value, int index) { replaceDomChildAt(Attribute, null, "name", index, value.toString()); } public void replacenameAt(String value, int index) throws Exception { replacenameAt(new SchemaNCName(value), index); } public static int getref_attachmentMinCount() { return 1; } public static int getref_attachmentMaxCount() { return 1; } public int getref_attachmentCount() { return getDomChildCount(Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment"); } public boolean hasref_attachment() { return hasDomChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment"); } public ref_attachmentType newref_attachment() { return new ref_attachmentType(domNode.getOwnerDocument().createElementNS("http://www.collada.org/2005/11/COLLADASchema", "ref_attachment")); } public ref_attachmentType getref_attachmentAt(int index) throws Exception { return new ref_attachmentType(getDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", index)); } public org.w3c.dom.Node getStartingref_attachmentCursor() throws Exception { return getDomFirstChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment" ); } public org.w3c.dom.Node getAdvancedref_attachmentCursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", curNode ); } public ref_attachmentType getref_attachmentValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new ref_attachmentType(curNode); } public ref_attachmentType getref_attachment() throws Exception { return getref_attachmentAt(0); } public void removeref_attachmentAt(int index) { removeDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", index); } public void removeref_attachment() { removeref_attachmentAt(0); } public org.w3c.dom.Node addref_attachment(ref_attachmentType value) { return appendDomElement("http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", value); } public void insertref_attachmentAt(ref_attachmentType value, int index) { insertDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", index, value); } public void replaceref_attachmentAt(ref_attachmentType value, int index) { replaceDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", index, value); } public static int getattachmentMinCount() { return 1; } public static int getattachmentMaxCount() { return 1; } public int getattachmentCount() { return getDomChildCount(Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment"); } public boolean hasattachment() { return hasDomChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment"); } public attachmentType newattachment() { return new attachmentType(domNode.getOwnerDocument().createElementNS("http://www.collada.org/2005/11/COLLADASchema", "attachment")); } public attachmentType getattachmentAt(int index) throws Exception { return new attachmentType(getDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment", index)); } public org.w3c.dom.Node getStartingattachmentCursor() throws Exception { return getDomFirstChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment" ); } public org.w3c.dom.Node getAdvancedattachmentCursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment", curNode ); } public attachmentType getattachmentValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new attachmentType(curNode); } public attachmentType getattachment() throws Exception { return getattachmentAt(0); } public void removeattachmentAt(int index) { removeDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment", index); } public void removeattachment() { removeattachmentAt(0); } public org.w3c.dom.Node addattachment(attachmentType value) { return appendDomElement("http://www.collada.org/2005/11/COLLADASchema", "attachment", value); } public void insertattachmentAt(attachmentType value, int index) { insertDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "attachment", index, value); } public void replaceattachmentAt(attachmentType value, int index) { replaceDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "attachment", index, value); } public static int gettechnique_commonMinCount() { return 1; } public static int gettechnique_commonMaxCount() { return 1; } public int gettechnique_commonCount() { return getDomChildCount(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common"); } public boolean hastechnique_common() { return hasDomChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common"); } public technique_commonType8 newtechnique_common() { return new technique_commonType8(domNode.getOwnerDocument().createElementNS("http://www.collada.org/2005/11/COLLADASchema", "technique_common")); } public technique_commonType8 gettechnique_commonAt(int index) throws Exception { return new technique_commonType8(getDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common", index)); } public org.w3c.dom.Node getStartingtechnique_commonCursor() throws Exception { return getDomFirstChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common" ); } public org.w3c.dom.Node getAdvancedtechnique_commonCursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common", curNode ); } public technique_commonType8 gettechnique_commonValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new technique_commonType8(curNode); } public technique_commonType8 gettechnique_common() throws Exception { return gettechnique_commonAt(0); } public void removetechnique_commonAt(int index) { removeDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common", index); } public void removetechnique_common() { removetechnique_commonAt(0); } public org.w3c.dom.Node addtechnique_common(technique_commonType8 value) { return appendDomElement("http://www.collada.org/2005/11/COLLADASchema", "technique_common", value); } public void inserttechnique_commonAt(technique_commonType8 value, int index) { insertDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "technique_common", index, value); } public void replacetechnique_commonAt(technique_commonType8 value, int index) { replaceDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "technique_common", index, value); } public static int gettechniqueMinCount() { return 0; } public static int gettechniqueMaxCount() { return Integer.MAX_VALUE; } public int gettechniqueCount() { return getDomChildCount(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique"); } public boolean hastechnique() { return hasDomChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique"); } public techniqueType5 newtechnique() { return new techniqueType5(domNode.getOwnerDocument().createElementNS("http://www.collada.org/2005/11/COLLADASchema", "technique")); } public techniqueType5 gettechniqueAt(int index) throws Exception { return new techniqueType5(getDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique", index)); } public org.w3c.dom.Node getStartingtechniqueCursor() throws Exception { return getDomFirstChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique" ); } public org.w3c.dom.Node getAdvancedtechniqueCursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "technique", curNode ); } public techniqueType5 gettechniqueValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new techniqueType5(curNode); } public techniqueType5 gettechnique() throws Exception { return gettechniqueAt(0); } public void removetechniqueAt(int index) { removeDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique", index); } public void removetechnique() { while (hastechnique()) removetechniqueAt(0); } public org.w3c.dom.Node addtechnique(techniqueType5 value) { return appendDomElement("http://www.collada.org/2005/11/COLLADASchema", "technique", value); } public void inserttechniqueAt(techniqueType5 value, int index) { insertDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "technique", index, value); } public void replacetechniqueAt(techniqueType5 value, int index) { replaceDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "technique", index, value); } public static int getextraMinCount() { return 0; } public static int getextraMaxCount() { return Integer.MAX_VALUE; } public int getextraCount() { return getDomChildCount(Element, "http://www.collada.org/2005/11/COLLADASchema", "extra"); } public boolean hasextra() { return hasDomChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "extra"); } public extraType newextra() { return new extraType(domNode.getOwnerDocument().createElementNS("http://www.collada.org/2005/11/COLLADASchema", "extra")); } public extraType getextraAt(int index) throws Exception { return new extraType(getDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "extra", index)); } public org.w3c.dom.Node getStartingextraCursor() throws Exception { return getDomFirstChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "extra" ); } public org.w3c.dom.Node getAdvancedextraCursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "extra", curNode ); } public extraType getextraValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new extraType(curNode); } public extraType getextra() throws Exception { return getextraAt(0); } public void removeextraAt(int index) { removeDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "extra", index); } public void removeextra() { while (hasextra()) removeextraAt(0); } public org.w3c.dom.Node addextra(extraType value) { return appendDomElement("http://www.collada.org/2005/11/COLLADASchema", "extra", value); } public void insertextraAt(extraType value, int index) { insertDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "extra", index, value); } public void replaceextraAt(extraType value, int index) { replaceDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "extra", index, value); } }
gpl-2.0
jackkiexu/tuomatuo
tuomatuo-core/src/main/java/com/lami/tuomatuo/core/dao/impl/QQAccountDaoImpl.java
496
package com.lami.tuomatuo.core.dao.impl; import com.lami.tuomatuo.core.base.MySqlBaseDao; import com.lami.tuomatuo.core.dao.QQAccountDaoInterface; import com.lami.tuomatuo.core.model.QQAccount; import org.springframework.stereotype.Repository; /** * Created by xjk on 2016/1/18. */ @Repository("qqAccountDaoInterface") public class QQAccountDaoImpl extends MySqlBaseDao<QQAccount, Long> implements QQAccountDaoInterface { public QQAccountDaoImpl(){ super(QQAccount.class); } }
gpl-2.0
klnusbaum/rxandroidexamples
app/src/main/java/kurtis/rx/androidexamples/ExampleListActivity.java
2227
package kurtis.rx.androidexamples; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class ExampleListActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example_list); setupActionBar(); setupExampleList(); } private void setupActionBar() { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(R.string.example_list_title); } } private void setupExampleList() { RecyclerView exampleList = (RecyclerView) findViewById(R.id.example_list); exampleList.setHasFixedSize(true); exampleList.setLayoutManager(new LinearLayoutManager(this)); exampleList.setAdapter(new ExampleAdapter(this, getExamples())); } private static List<ExampleActivityAndName> getExamples() { List<ExampleActivityAndName> exampleActivityAndNames = new ArrayList<>(); exampleActivityAndNames.add(new ExampleActivityAndName( Example1Activity.class, "Example 1: Simple Color List")); exampleActivityAndNames.add(new ExampleActivityAndName( Example2Activity.class, "Example 2: Favorite Tv Shows")); exampleActivityAndNames.add(new ExampleActivityAndName( Example3Activity.class, "Example 3: Improved Favorite Tv Shows")); exampleActivityAndNames.add(new ExampleActivityAndName( Example4Activity.class, "Example 4: Button Counter")); exampleActivityAndNames.add(new ExampleActivityAndName( Example5Activity.class, "Example 5: Value Display")); exampleActivityAndNames.add(new ExampleActivityAndName( Example6Activity.class, "Example 6: City Search")); return exampleActivityAndNames; } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jdk/test/sun/nio/cs/OLD/DBCS_IBM_EBCDIC_Encoder.java
8255
/* * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ /* */ import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import sun.nio.cs.Surrogate; /** * An abstract base class for subclasses which encodes * IBM double byte host encodings such as ibm code * pages 942,943,948, etc. * */ public abstract class DBCS_IBM_EBCDIC_Encoder extends CharsetEncoder { protected static final char REPLACE_CHAR='\uFFFD'; private byte b1; private byte b2; protected short index1[]; protected String index2; protected String index2a; protected int mask1; protected int mask2; protected int shift; private static final int SBCS = 0; private static final int DBCS = 1; private static final byte SO = 0x0e; private static final byte SI = 0x0f; private int currentState; private final Surrogate.Parser sgp = new Surrogate.Parser(); protected DBCS_IBM_EBCDIC_Encoder(Charset cs) { super(cs, 4.0f, 5.0f, new byte[] {(byte)0x6f}); } protected void implReset() { currentState = SBCS; } protected CoderResult implFlush(ByteBuffer out) { if (currentState == DBCS) { if (out.remaining() < 1) return CoderResult.OVERFLOW; out.put(SI); } implReset(); return CoderResult.UNDERFLOW; } /** * Returns true if the given character can be converted to the * target character encoding. */ public boolean canEncode(char ch) { int index; int theBytes; index = index1[((ch & mask1) >> shift)] + (ch & mask2); if (index < 15000) theBytes = (int)(index2.charAt(index)); else theBytes = (int)(index2a.charAt(index-15000)); if (theBytes != 0) return (true); // only return true if input char was unicode null - all others are // undefined return( ch == '\u0000'); } private CoderResult encodeArrayLoop(CharBuffer src, ByteBuffer dst) { char[] sa = src.array(); int sp = src.arrayOffset() + src.position(); int sl = src.arrayOffset() + src.limit(); byte[] da = dst.array(); int dp = dst.arrayOffset() + dst.position(); int dl = dst.arrayOffset() + dst.limit(); int outputSize = 0; // size of output int spaceNeeded; try { while (sp < sl) { int index; int theBytes; char c = sa[sp]; if (Surrogate.is(c)) { if (sgp.parse(c, sa, sp, sl) < 0) return sgp.error(); return sgp.unmappableResult(); } if (c >= '\uFFFE') return CoderResult.unmappableForLength(1); index = index1[((c & mask1) >> shift)] + (c & mask2); if (index < 15000) theBytes = (int)(index2.charAt(index)); else theBytes = (int)(index2a.charAt(index-15000)); b1= (byte)((theBytes & 0x0000ff00)>>8); b2 = (byte)(theBytes & 0x000000ff); if (b1 == 0x00 && b2 == 0x00 && c != '\u0000') { return CoderResult.unmappableForLength(1); } if (currentState == DBCS && b1 == 0x00) { if (dl - dp < 1) return CoderResult.OVERFLOW; currentState = SBCS; da[dp++] = SI; } else if (currentState == SBCS && b1 != 0x00) { if (dl - dp < 1) return CoderResult.OVERFLOW; currentState = DBCS; da[dp++] = SO; } if (currentState == DBCS) spaceNeeded = 2; else spaceNeeded = 1; if (dl - dp < spaceNeeded) return CoderResult.OVERFLOW; if (currentState == SBCS) da[dp++] = b2; else { da[dp++] = b1; da[dp++] = b2; } sp++; } return CoderResult.UNDERFLOW; } finally { src.position(sp - src.arrayOffset()); dst.position(dp - dst.arrayOffset()); } } private CoderResult encodeBufferLoop(CharBuffer src, ByteBuffer dst) { int mark = src.position(); int outputSize = 0; // size of output int spaceNeeded; try { while (src.hasRemaining()) { int index; int theBytes; char c = src.get(); if (Surrogate.is(c)) { if (sgp.parse(c, src) < 0) return sgp.error(); return sgp.unmappableResult(); } if (c >= '\uFFFE') return CoderResult.unmappableForLength(1); index = index1[((c & mask1) >> shift)] + (c & mask2); if (index < 15000) theBytes = (int)(index2.charAt(index)); else theBytes = (int)(index2a.charAt(index-15000)); b1 = (byte)((theBytes & 0x0000ff00)>>8); b2 = (byte)(theBytes & 0x000000ff); if (b1== 0x00 && b2 == 0x00 && c != '\u0000') { return CoderResult.unmappableForLength(1); } if (currentState == DBCS && b1 == 0x00) { if (dst.remaining() < 1) return CoderResult.OVERFLOW; currentState = SBCS; dst.put(SI); } else if (currentState == SBCS && b1 != 0x00) { if (dst.remaining() < 1) return CoderResult.OVERFLOW; currentState = DBCS; dst.put(SO); } if (currentState == DBCS) spaceNeeded = 2; else spaceNeeded = 1; if (dst.remaining() < spaceNeeded) return CoderResult.OVERFLOW; if (currentState == SBCS) dst.put(b2); else { dst.put(b1); dst.put(b2); } mark++; } return CoderResult.UNDERFLOW; } finally { src.position(mark); } } protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) { if (true && src.hasArray() && dst.hasArray()) return encodeArrayLoop(src, dst); else return encodeBufferLoop(src, dst); } }
gpl-2.0
callakrsos/Gargoyle
gargoyle-jython/src/test/java/com/kyj/fx/nashorn/DefaultScriptEngineTest.java
8095
/******************************** * 프로젝트 : gargoyle-jython * 패키지 : com.kyj.fx.nashorn * 작성일 : 2019. 10. 4. * 작성자 : KYJ (callakrsos@naver.com) *******************************/ package com.kyj.fx.nashorn; import java.io.File; import java.io.IOException; import javax.script.ScriptEngine; import javax.script.ScriptException; import org.junit.Test; import com.kyj.fx.jython.DefaultScriptEngine; /** * @author KYJ (callakrsos@naver.com) * */ public class DefaultScriptEngineTest { // static { // System.setProperty("python.console.encoding", "UTF-8"); // } @Test public void test() throws ScriptException { DefaultScriptEngine z = new DefaultScriptEngine(); ScriptEngine engine = z.createEngine(); // Using the eval() method on the engine causes a direct // interpretataion and execution of the code string passed into it engine.eval("import sys"); engine.eval("print sys"); // Using the put() method allows one to place values into // specified variables within the engine engine.put("a", "42"); // As you can see, once the variable has been set with // a value by using the put() method, we an issue eval statements // to use it. engine.eval("print a"); engine.eval("x = 2 + 2"); // Using the get() method allows one to obtain the value // of a specified variable from the engine instance Object x = engine.get("x"); System.out.println("x: " + x); // engine.eval(" print(\"한글\") "); } /** * Hangul Print Test <br/> * @throws ScriptException * @throws IOException * * @작성자 : KYJ (callakrsos@naver.com) * @작성일 : 2019. 10. 7. */ @Test public void test4() throws IOException, ScriptException { // System.setProperty("python.console.encoding", "EUC-KR"); DefaultScriptEngine engine = new DefaultScriptEngine(); StringBuffer sb = new StringBuffer(); sb.append("import java.lang.String\n"); sb.append("def Hangul(str, encoding='utf-8'):\n"); sb.append(" return java.lang.String(str,encoding)\n"); sb.append("x = '한글 깨짐' \n" ); sb.append("print(x)\n"); sb.append("x = u'한글 안깨짐' \n" ); sb.append("print(x)\n"); sb.append("print(java.lang.String('한글 안깨짐', 'utf-8'))\n"); sb.append("print(Hangul('한글 안깨짐', 'utf-8'))\n"); sb.append("\n"); //// sb.append("import sys"); // sb.append("sys.stdout.write(u\"한글\")"); // sb.toString(); engine.execute(sb.toString()); } /** * read from file. <br/> * @throws ScriptException * @throws IOException * @작성자 : KYJ (callakrsos@naver.com) * @작성일 : 2019. 10. 7. */ @Test public void test3() throws IOException, ScriptException { DefaultScriptEngine engine = new DefaultScriptEngine(); engine.execute(new File("script", "Test.py")); } @Test public void test2() throws IOException, ScriptException { StringBuffer sb = new StringBuffer(); sb.append("x = 100\n"); sb.append("if x > 0:\n"); sb.append(" print('wow this is elegant')\n"); sb.append("else:\n"); sb.append(" print('Oranization is the key.')\n"); sb.append("\n"); sb.append("\n"); sb.append("print('hello ' + ' ' + 'world')\n"); sb.append("\n"); sb.append("\n"); sb.append("def my_function(a='zz'):\n"); sb.append(" print(a)\n"); sb.append("\n"); sb.append("my_function()\n"); sb.append("\n"); sb.append("\n"); sb.append("class my_class:\n"); sb.append(" def __init__(self, x, y ):\n"); sb.append(" self.x = x\n"); sb.append(" self.y = y\n"); sb.append(" print('초기화 함수 ')\n"); sb.append("\n"); sb.append(" def mul(self):\n"); sb.append(" print(self.x * self.y)\n"); sb.append("\n"); sb.append(" def add(self):\n"); sb.append(" print(self.x + self.y)\n"); sb.append("\n"); sb.append("\n"); sb.append("ob1 = my_class(7,8)\n"); sb.append("ob1.mul()\n"); sb.append("\n"); sb.append("ob1.add()\n"); sb.append("\n"); sb.append("decimalValue = 10\n"); sb.append("stringValue = \"10\"\n"); sb.append("floatValue = 10.0\n"); sb.append("\n"); sb.append("print ('String of text goes here %d %s %f' % (decimalValue, stringValue, floatValue))\n"); sb.append("\n"); sb.append("\n"); sb.append("x = 3\n"); sb.append("y = 0\n"); sb.append("try:\n"); sb.append(" print('로켓의 궤도 : %f' % (x/y))\n"); sb.append("except Exception as ex:\n"); sb.append(" print(ex.__str__() )\n"); sb.append("\n"); sb.append("\n"); sb.append("\n"); sb.append("print(range(1,5))\n"); sb.append("\n"); sb.append("\n"); sb.append("items = [1,2,3,4,5, 10]\n"); sb.append("for item in items:\n"); sb.append(" print(item)\n"); sb.append("items.append(11)\n"); sb.append("\n"); sb.append("print(items)\n"); sb.append("\n"); sb.append("items = [ y**2 for y in range(1,10)]\n"); sb.append("print(items)\n"); sb.append("\n"); sb.append("pairs = []\n"); sb.append("A = ['blue', 'yellow', 'red']\n"); sb.append("B = ['red', 'green', 'blue']\n"); sb.append("\n"); sb.append("for a in A:\n"); sb.append(" for b in B:\n"); sb.append(" if a != b:\n"); sb.append(" pairs.append((a,b))\n"); sb.append("print (pairs)\n"); sb.append("\n"); sb.append("\n"); sb.append("pairs = []\n"); sb.append("pairs = [(a,b) for a in A for b in B if a!=b]\n"); sb.append("print(pairs)\n"); sb.append("\n"); sb.append("\n"); sb.append("a = {x for x in 'abracatabra' if x not in 'abc'}\n"); sb.append("print(a)\n"); sb.append("\n"); sb.append("print(\"###############################################\")\n"); sb.append("alpa = 2\n"); sb.append("\n"); sb.append("for a in range(1,10):\n"); sb.append(" print(\"%d x %d = %d\" % (alpa , a , (alpa*a)) )\n"); sb.append("\n"); sb.append("\n"); sb.append("print('###############################################')\n"); sb.append("print('abcdefg'.upper())\n"); sb.append("print(\"%s %s %s\" % (ord('a'), ord('b'), ord('c')))\n"); sb.append("\n"); sb.append("\n"); sb.append("print(\"########################################\")\n"); sb.append("str = \"abcde\"\n"); sb.append("newStr = \"\"\n"); sb.append("for a in range(len(str) - 1, -1 , -1):\n"); sb.append(" newStr += str[a]\n"); sb.append("print(\"print newStr : %s \" % (newStr))\n"); sb.append("\n"); sb.append("\n"); sb.append("books = [ {\n"); sb.append(" \"제목\":\"개발자의 코드\",\n"); sb.append(" \"출판연도\": \"2013.02.28\",\n"); sb.append(" \"출판사\":\"A\",\n"); sb.append(" \"쪽수\":200,\n"); sb.append(" \"추천유무\":False\n"); sb.append("}, {\n"); sb.append(" \"제목\":\"클린코드\",\n"); sb.append(" \"출판연도\": \"2010.03.04\",\n"); sb.append(" \"출판사\":\"B\",\n"); sb.append(" \"쪽수\":584,\n"); sb.append(" \"추천유무\":True\n"); sb.append("}, {\n"); sb.append(" \"제목\":\"빅데이터 마케팅\",\n"); sb.append(" \"출판연도\": \"2014.07.10\",\n"); sb.append(" \"출판사\":\"A\",\n"); sb.append(" \"쪽수\":296,\n"); sb.append(" \"추천유무\":True\n"); sb.append("},\n"); sb.append("]\n"); sb.append("\n"); sb.append("print(\"############################################\")\n"); sb.append("many_page = []\n"); sb.append("my_recommand = []\n"); sb.append("for book in books:\n"); sb.append(" if book[\"쪽수\"] > 250:\n"); sb.append(" many_page.append(book)\n"); sb.append("\n"); sb.append(" if book[\"추천유무\"]:\n"); sb.append(" my_recommand.append(book)\n"); sb.append("\n"); sb.append("print(many_page)\n"); sb.append("print(my_recommand)\n"); DefaultScriptEngine engine = new DefaultScriptEngine(); engine.execute(sb.toString()); } }
gpl-2.0
limelime/Tutorial
src/net/xngo/tutorial/java/xxhash/XxhashString.java
1394
package net.xngo.tutorial.java.xxhash; import net.jpountz.xxhash.XXHashFactory; import net.jpountz.xxhash.StreamingXXHash32; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.io.IOException; /** * Basic example showing how to get the hash value of string using XXHash. * @author Xuan Ngo * */ public class XxhashString { public static void main(String[] args) { XXHashFactory factory = XXHashFactory.fastestInstance(); try { byte[] data = "12345345234572".getBytes("UTF-8"); ByteArrayInputStream in = new ByteArrayInputStream(data); int seed = 0x9747b28c; // Used to initialize the hash value, use whatever // value you want, but always the same. StreamingXXHash32 hash32 = factory.newStreamingHash32(seed); byte[] buf = new byte[8]; // For real-world usage, use a larger buffer, like 8192 bytes for (;;) { int read = in.read(buf); if (read == -1) { break; } hash32.update(buf, 0, read); } int hash = hash32.getValue(); System.out.println(hash); } catch(UnsupportedEncodingException ex) { System.out.println(ex); } catch(IOException ex) { System.out.println(ex); } } }
gpl-2.0
JMaNGOS/JMaNGOS
Commons/src/main/java/org/jmangos/commons/entities/skills/pet/PetExoticCoreHound.java
1292
/******************************************************************************* * Copyright (C) 2013 JMaNGOS <http://jmangos.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ /** * */ package org.jmangos.commons.entities.skills.pet; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import org.jmangos.commons.entities.CharacterSkill; /** * @author MinimaJack * */ @Entity @DiscriminatorValue(value = "787") public class PetExoticCoreHound extends CharacterSkill { /** * */ private static final long serialVersionUID = -2165567397248362584L; }
gpl-2.0
tmachows/slavic-miners-game
ios/src/pl/metaminers/game/IOSLauncher.java
764
package pl.metaminers.game; import org.robovm.apple.foundation.NSAutoreleasePool; import org.robovm.apple.uikit.UIApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration; import pl.metaminers.game.MineFooGame; public class IOSLauncher extends IOSApplication.Delegate { @Override protected IOSApplication createApplication() { IOSApplicationConfiguration config = new IOSApplicationConfiguration(); return new IOSApplication(new MineFooGame(), config); } public static void main(String[] argv) { NSAutoreleasePool pool = new NSAutoreleasePool(); UIApplication.main(argv, null, IOSLauncher.class); pool.close(); } }
gpl-2.0
MarineMC/MarineStandalone
src/main/java/org/marinemc/world/BiomeID.java
3562
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MarineStandalone is a minecraft server software and API. // Copyright (C) MarineMC (marinemc.org) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// package org.marinemc.world; /** * @author Fozie */ public enum BiomeID { UNKNOWN(-1, "unknowned"), OCEAN(0, "Ocean"), PLAINS(1, "Plains"), DESERT(2, "Desert"), EXTREAM_HILLS(3, "Extreme Hills"), FOREST(4, "Forest"), TAIGA( 5, "Taiga"), SWAMPLAND(6, "Swampland"), RIVER(7, "River"), NETHER( 8, "Nether"), THE_END(9, "End"), FROZEN_OCEAN(10, "Frozen Ocean"), FROZEN_RIVER( 11, "Frozen River"), ICE_PLAINS(12, "Ice Plains"), ICE_MOUNTIANS( 13, "Ice Mountains"), MUSHROOM_ISLAND(14, "Mushroom Island"), MUSHROOM_ISLAND_SHORE( 15, "Mushroom Island Shore"), BEACH(16, "Beach"), DESERT_HILLS(17, "Desert Hills"), FOREST_HILLS(18, "Forest Hills"), TAIGA_HILLS(19, "Taiga Hills"), EXTREAM_HILLS_EDGE(20, "Extreme Hills Edge"), JUNGLE( 21, "Jungle"), JUNGLE_HILLS(22, "Jungle Hills"), JUNGLE_EDGE(23, "Jungle Edge"), DEEP_OCEAN(24, "Deep Ocean"), STONE_BEACH(25, "Stone Beach"), COLD_BEACH(26, "Cold Beach"), BIRCH_FOREST(27, "Birch Forest"), BIRCH_FOREST_HILLS(28, "Birch Forest Hills"), ROOFED_FOREST( 29, "Roofed Forest"), COLD_TAIGA(30, "Cold Taiga"), COLD_TAIGA_HILLS( 31, "Cold Taiga Hills"), MEGA_TAIGA(32, "Mega Taiga"), MEGA_TAIGA_HILLS( 33, "Mega Taiga Hills"), EXTREAM_HILLS_EXTRA(34, "Extreme Hills+"), SAVANNA( 35, "Savanna"), SAVANNA_PLATEAU(36, "Savanna Plateau"), MESA(37, "Mesa"), MESA_PLATEUA_F(38, "Mesa Plateau F"), MESA_PLATEAU(39, "Mesa Plateau"), SUNFLOWER_PLAINS(129, "Sunflower Plains"), DESERT_M( 130, "Desert M"), EXTREAM_HILLS_M(131, "Extreme Hills M"), FLOWER_FOREST( 132, "Flower Forest"), TAIGA_M(133, "Taiga M"), SWAMPLAND_M(134, "Swampland M"), ICE_PLAINS_SPIKES(140, "Ice Plains Spikes"), JUNGLE_M( 149, "Jungle M"), JUNGLE_EDGE_M(151, "JungleEdge M"), BIRCH_FOREST_M( 155, "Birch Forest M"), BIRCH_FOREST_HILLS_M(156, "Birch Forest Hills M"), ROOFED_FOREST_M(157, "Roofed Forest M"), COLD_TAIGA_M( 158, "Cold Taiga M"), MEGA_SPRUCE_TAIGA(160, "Mega Spruce Taiga"), REDWOOD_TAIGA_HILLS_M( 161, "Redwood Taiga Hills M"), EXTREME_HILLS_EXTRA_M(162, "Extreme Hills+ M"), SAVANNA_M(163, "Savanna M"), SAVANNA_PLATEAU_M( 164, "Savanna Plateau M"), MESA_BRYCE(165, "Mesa (Bryce)"), MESA_PLATEAU_F_M( 166, "Mesa Plateau F M"), MESA_PLATEAU_M(167, "Mesa Plateau M"); private final byte ID; private final String name; private BiomeID(final int id, final String name) { ID = (byte) id; this.name = name; } public byte getID() { return ID; } public String getName() { return name; } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jdk/src/share/classes/java/awt/DisplayMode.java
5123
/* * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package java.awt; /** * The <code>DisplayMode</code> class encapsulates the bit depth, height, * width, and refresh rate of a <code>GraphicsDevice</code>. The ability to * change graphics device's display mode is platform- and * configuration-dependent and may not always be available * (see {@link GraphicsDevice#isDisplayChangeSupported}). * <p> * For more information on full-screen exclusive mode API, see the * <a href="http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html"> * Full-Screen Exclusive Mode API Tutorial</a>. * * @see GraphicsDevice * @see GraphicsDevice#isDisplayChangeSupported * @see GraphicsDevice#getDisplayModes * @see GraphicsDevice#setDisplayMode * @author Michael Martak * @since 1.4 */ public final class DisplayMode { private Dimension size; private int bitDepth; private int refreshRate; /** * Create a new display mode object with the supplied parameters. * @param width the width of the display, in pixels * @param height the height of the display, in pixels * @param bitDepth the bit depth of the display, in bits per * pixel. This can be <code>BIT_DEPTH_MULTI</code> if multiple * bit depths are available. * @param refreshRate the refresh rate of the display, in hertz. * This can be <code>REFRESH_RATE_UNKNOWN</code> if the * information is not available. * @see #BIT_DEPTH_MULTI * @see #REFRESH_RATE_UNKNOWN */ public DisplayMode(int width, int height, int bitDepth, int refreshRate) { this.size = new Dimension(width, height); this.bitDepth = bitDepth; this.refreshRate = refreshRate; } /** * Returns the height of the display, in pixels. * @return the height of the display, in pixels */ public int getHeight() { return size.height; } /** * Returns the width of the display, in pixels. * @return the width of the display, in pixels */ public int getWidth() { return size.width; } /** * Value of the bit depth if multiple bit depths are supported in this * display mode. * @see #getBitDepth */ public final static int BIT_DEPTH_MULTI = -1; /** * Returns the bit depth of the display, in bits per pixel. This may be * <code>BIT_DEPTH_MULTI</code> if multiple bit depths are supported in * this display mode. * * @return the bit depth of the display, in bits per pixel. * @see #BIT_DEPTH_MULTI */ public int getBitDepth() { return bitDepth; } /** * Value of the refresh rate if not known. * @see #getRefreshRate */ public final static int REFRESH_RATE_UNKNOWN = 0; /** * Returns the refresh rate of the display, in hertz. This may be * <code>REFRESH_RATE_UNKNOWN</code> if the information is not available. * * @return the refresh rate of the display, in hertz. * @see #REFRESH_RATE_UNKNOWN */ public int getRefreshRate() { return refreshRate; } /** * Returns whether the two display modes are equal. * @return whether the two display modes are equal */ public boolean equals(DisplayMode dm) { if (dm == null) { return false; } return (getHeight() == dm.getHeight() && getWidth() == dm.getWidth() && getBitDepth() == dm.getBitDepth() && getRefreshRate() == dm.getRefreshRate()); } /** * {@inheritDoc} */ public boolean equals(Object dm) { if (dm instanceof DisplayMode) { return equals((DisplayMode)dm); } else { return false; } } /** * {@inheritDoc} */ public int hashCode() { return getWidth() + getHeight() + getBitDepth() * 7 + getRefreshRate() * 13; } }
gpl-2.0
neuroradiology/TinyVoxel
core/src/com/toet/TinyVoxel/Renderer/BlockBuilder.java
8245
package com.toet.TinyVoxel.Renderer; import com.toet.TinyVoxel.Config; import com.toet.TinyVoxel.Renderer.Bundles.Grid; import com.toet.TinyVoxel.Renderer.Bundles.TinyGrid; import java.nio.FloatBuffer; /** * Created by Kajos on 20-1-14. */ public class BlockBuilder { public static float low = .0001f; public static final boolean[] CUBE = { // x- false,false,false, false,false, true, false, true, true, false,false,false, false, true, true, false, true,false, // x+ true, true, true, true,false,false, true, true,false, true,false,false, true, true, true, true,false, true, // y- true,false, true, false,false, true, false,false,false, true,false, true, false,false,false, true,false,false, // y+ true, true, true, true, true,false, false, true,false, true, true, true, false, true,false, false, true, true, // z- true, true,false, false,false,false, false, true,false, true, true,false, true,false,false, false,false,false, // z+ true, true, true, false, true, true, true, false, true, false, true, true, false, false, true, true,false, true, }; public static TinyGrid getNeighbor(Grid grid, int x, int y, int z, int dx, int dy, int dz) { if (dx < 0) { TinyGrid cont = null; if (x == 0) { Grid nGrid = grid.owner.getGridSafe(grid.x - 1, grid.y, grid.z); if (nGrid != null) { cont = nGrid.getTinyGrid(Config.GRID_SIZE - 1, y, z); } } else { cont = grid.getTinyGrid(x - 1, y, z); } return cont; } else if (dy < 0) { TinyGrid cont = null; if (y == 0) { Grid nGrid = grid.owner.getGridSafe(grid.x, grid.y - 1, grid.z); if (nGrid != null) { cont = nGrid.getTinyGrid(x, Config.GRID_SIZE - 1, z); } } else { cont = grid.getTinyGrid(x, y - 1, z); } return cont; } else if (dz < 0) { TinyGrid cont = null; if (z == 0) { Grid nGrid = grid.owner.getGridSafe(grid.x, grid.y, grid.z - 1); if (nGrid != null) { cont = nGrid.getTinyGrid(x, y, Config.GRID_SIZE - 1); } } else { cont = grid.getTinyGrid(x, y, z - 1); } return cont; } else if (dx > 0) { TinyGrid cont = null; if (x >= Config.GRID_SIZE - 1) { Grid nGrid = grid.owner.getGridSafe(grid.x + 1, grid.y, grid.z); if (nGrid != null) { cont = nGrid.getTinyGrid(0, y, z); } } else { cont = grid.getTinyGrid(x + 1, y, z); } return cont; } else if (dy > 0) { TinyGrid cont = null; if (y >= Config.GRID_SIZE - 1) { Grid nGrid = grid.owner.getGridSafe(grid.x, grid.y + 1, grid.z); if (nGrid != null) { cont = nGrid.getTinyGrid(x, 0, z); } } else { cont = grid.getTinyGrid(x, y + 1, z); } return cont; } else if (dz > 0) { TinyGrid cont = null; if (z >= Config.GRID_SIZE - 1) { Grid nGrid = grid.owner.getGridSafe(grid.x, grid.y, grid.z + 1); if (nGrid != null) { cont = nGrid.getTinyGrid(x, y, 0); } } else { cont = grid.getTinyGrid(x, y, z + 1); } return cont; } return null; } public static void fillInPalette(FloatBuffer vertices, int start, int end, int palette) { for (int i = start + 4; i < end; i+=5) { vertices.put(i, palette); } } static boolean[] skipArray = new boolean[6]; static int skipCount; public static boolean generateBox(FloatBuffer vertices, int x, int y, int z, Grid grid) { TinyGrid cont = grid.getTinyGrid(x, y, z); if (cont == null) return false; TinyGrid gCont; for(int i = 0; i < skipArray.length; i++) { skipArray[i] = false; } skipCount = 0; if (cont.minX == 0) { gCont = getNeighbor(grid, x, y, z, -1, 0, 0); if (gCont != null) { if (gCont.fullSides[1]) { skipArray[0] = true; skipCount++; } } } if (cont.maxX == Config.TINY_GRID_SIZE) { gCont = getNeighbor(grid, x, y, z, +1, 0, 0); if (gCont != null) { if (gCont.fullSides[0]) { skipArray[1] = true; skipCount++; } } } if (cont.minY == 0) { gCont = getNeighbor(grid, x, y, z, 0, -1, 0); if (gCont != null) { if (gCont.fullSides[3]) { skipArray[2] = true; skipCount++; } } } if (cont.maxY == Config.TINY_GRID_SIZE) { gCont = getNeighbor(grid, x, y, z, 0, +1, 0); if (gCont != null) { if (gCont.fullSides[2]) { skipArray[3] = true; skipCount++; } } } if (cont.minZ == 0) { gCont = getNeighbor(grid, x, y, z, 0, 0, -1); if (gCont != null) { if (gCont.fullSides[5]) { skipArray[4] = true; skipCount++; } } } if (cont.maxZ == Config.TINY_GRID_SIZE) { gCont = getNeighbor(grid, x, y, z, 0, 0, +1); if (gCont != null) { if (gCont.fullSides[4]) { skipArray[5] = true; skipCount++; } } } FloatBuffer write = vertices; float divide = (float)(Config.TINY_GRID_SIZE); float minXf = (float)cont.minX / divide; float minYf = (float)cont.minY / divide; float minZf = (float)cont.minZ / divide; minXf += low; minYf += low; minZf += low; float maxXf = (float)cont.maxX / divide; float maxYf = (float)cont.maxY / divide; float maxZf = (float)cont.maxZ / divide; maxXf -= low; maxYf -= low; maxZf -= low; minXf += x; minYf += y; minZf += z; maxXf += x; maxYf += y; maxZf += z; boolean hasWritten = false; if (skipCount != 6) { int side; for (int i = 0; i < CUBE.length; i += 3) { side = i / (3 * 6); if (skipArray[side]) continue; if (CUBE[i]) write.put(maxXf); else write.put(minXf); if (CUBE[i + 1]) write.put(maxYf); else write.put(minYf); if (CUBE[i + 2]) write.put(maxZf); else write.put(minZf); if (side < 2) { // x write.put(.5f); } else if (side < 4) { // y write.put(1f); } else { // z write.put(1.5f); } // palette is filled in later write.put(0f); hasWritten = true; } } return hasWritten; } }
gpl-2.0
mariuszfoltak/my-budget
server/src/main/java/pl/foltak/mybudget/server/security/CORSFilter.java
1050
package pl.foltak.mybudget.server.security; import java.io.IOException; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.ext.Provider; /** * This filter adds CORS headers and make api accessible for javascript. */ @Provider public class CORSFilter implements ContainerResponseFilter { @Override public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext cres) throws IOException { cres.getHeaders().add("Access-Control-Allow-Origin", "*"); cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization, Authorization-User, Authorization-Password"); cres.getHeaders().add("Access-Control-Allow-Credentials", "true"); cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); cres.getHeaders().add("Access-Control-Max-Age", "1209600"); } }
gpl-2.0
JannesP/java_tower_defense
src/game/object/enemy/EnemyHeavy.java
309
package game.object.enemy; import game.framework.math.Vector2d; import game.framework.resources.Textures; /** * Created by Addy on 23.02.2015. */ public class EnemyHeavy extends Enemy { public EnemyHeavy(Vector2d[] wayPoints) { super(Textures.runnerTexture, 25, 1.0d, 8, wayPoints); } }
gpl-2.0
hsun/cobertura-fork
javancss/src/main/java/javancss/JavancssFrame.java
13787
//COBERTURA EXCLUDE THIS FILE /* Copyright (C) 2000 Chr. Clemens Lee <clemens@kclee.com>. This file is part of JavaNCSS (http://www.kclee.com/clemens/java/javancss/). JavaNCSS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. JavaNCSS 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 JavaNCSS; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package javancss; import java.awt.*; import java.awt.event.*; import java.util.*; import java.text.*; import java.io.*; import javax.swing.*; import javax.swing.border.*; import ccl.swing.AboutDialog; import ccl.swing.AnimationPanel; import ccl.swing.AutoGridBagLayout; import ccl.swing.MainJFrame; import ccl.swing.SwingUtil; import ccl.util.FileUtil; import ccl.util.Init; import ccl.util.Util; /** * Main class used to start JavaNCSS in GUI mode from other * java applications. To start JavaNCSS from the command line, * gui mode or not, class 'Main' is used. * * @author <a href="http://www.kclee.com/clemens/">Chr. Clemens Lee</a> (<a href="mailto:clemens@kclee.com"><i>clemens@kclee.com</i></a>) * @version $Id: JavancssFrame.java 121 2009-01-17 22:19:45Z hboutemy $ */ public class JavancssFrame extends MainJFrame { public static final String S_PACKAGES = "Packages"; public static final String S_CLASSES = "Classes"; public static final String S_METHODS = "Methods"; private static final String S_MN_F_SAVE = "Save"; private int _oldThreadPriority = -1; private AnimationPanel _pAnimationPanel = null; private JTextArea _txtPackage; private JTextArea _txtObject; private JTextArea _txtFunction; private JTextArea _txtError; private JTabbedPane _pTabbedPane = null; private Font pFont = new Font("Monospaced", Font.PLAIN, 12); private boolean _bNoError = true; private String _sProjectName = null; private String _sProjectPath = null; private Init _pInit = null; public void save() { String sFullProjectName = FileUtil.concatPath (_sProjectPath, _sProjectName.toLowerCase()); String sPackagesFullFileName = sFullProjectName + ".packages.txt"; String sClassesFullFileName = sFullProjectName + ".classes.txt"; String sMethodsFullFileName = sFullProjectName + ".methods.txt"; String sSuccessMessage = "Data appended successfully to the following files:"; try { FileUtil.appendFile(sPackagesFullFileName, _txtPackage.getText()); sSuccessMessage += "\n" + sPackagesFullFileName; } catch(Exception ePackages) { SwingUtil.showMessage(this, "Error: could not append to file '" + sPackagesFullFileName + "'.\n" + ePackages); } try { FileUtil.appendFile(sClassesFullFileName, _txtObject.getText()); sSuccessMessage += "\n" + sClassesFullFileName; } catch(Exception eClasses) { SwingUtil.showMessage(this, "Error: could not append to file '" + sClassesFullFileName + "'.\n" + eClasses); } try { FileUtil.appendFile(sMethodsFullFileName, _txtFunction.getText()); sSuccessMessage += "\n" + sMethodsFullFileName; } catch(Exception eMethods) { SwingUtil.showMessage(this, "Error: could not append to file '" + sMethodsFullFileName + "'.\n" + eMethods); } SwingUtil.showMessage(this, sSuccessMessage); } private void _setMenuBar() { Vector vMenus = new Vector(); Vector vFileMenu = new Vector(); Vector vHelpMenu = new Vector(); vFileMenu.addElement("File"); vFileMenu.addElement(S_MN_F_SAVE); vFileMenu.addElement("Exit"); vHelpMenu.addElement("Help"); vHelpMenu.addElement("&Contents..."); vHelpMenu.addElement("---"); vHelpMenu.addElement("About..."); vMenus.addElement(vFileMenu); vMenus.addElement(vHelpMenu); setMenuBar(vMenus); } /** * Returns init object provided with constructor. */ public Init getInit() { return _pInit; } public JavancssFrame(Init pInit_) { super( "JavaNCSS: " + pInit_.getFileName() ); _pInit = pInit_; getInit().setAuthor( "Chr. Clemens Lee" ); super.setBackground( _pInit.getBackground() ); _sProjectName = pInit_.getFileName(); _sProjectPath = pInit_.getFilePath(); if (Util.isEmpty(_sProjectName)) { _sProjectName = pInit_.getApplicationName(); _sProjectPath = pInit_.getApplicationPath(); } _setMenuBar(); _bAboutSelected = false; AutoGridBagLayout pAutoGridBagLayout = new AutoGridBagLayout(); getContentPane().setLayout(pAutoGridBagLayout); Image pImage = Toolkit.getDefaultToolkit(). getImage( SwingUtil.createCCLBorder().getClass().getResource ( "anim_recycle_brown.gif" ) ); _pAnimationPanel = new AnimationPanel( pImage, 350 ); JPanel pPanel = new JPanel(); pPanel.setBorder(new SoftBevelBorder(BevelBorder.LOWERED)); pPanel.add(_pAnimationPanel, BorderLayout.CENTER); getContentPane().add(pPanel); pack(); setSize(640, 480); SwingUtil.centerComponent(this); } public void showJavancss(Javancss pJavancss_) { _bStop = false; _bSave = false; if (_oldThreadPriority != -1) { Thread.currentThread().setPriority(_oldThreadPriority); _pAnimationPanel.stop(); } getContentPane().removeAll(); getContentPane().setLayout(new BorderLayout()); _bNoError = true; if (pJavancss_.getLastErrorMessage() != null && pJavancss_.getNcss() <= 0) { _bNoError = false; JTextArea txtError = new JTextArea(); String sError = "Error in Javancss: " + pJavancss_.getLastErrorMessage(); txtError.setText(sError); JScrollPane jspError = new JScrollPane(txtError); getContentPane().add(jspError, BorderLayout.CENTER); } else { Util.debug("JavancssFrame.showJavancss(..).NOERROR"); JPanel pPanel = new JPanel(true); pPanel.setLayout(new BorderLayout()); _pTabbedPane = new JTabbedPane(); _pTabbedPane.setDoubleBuffered(true); _txtPackage = new JTextArea(); _txtPackage.setFont(pFont); JScrollPane jspPackage = new JScrollPane(_txtPackage); int inset = 5; jspPackage.setBorder( BorderFactory. createEmptyBorder ( inset, inset, inset, inset ) ); _pTabbedPane.addTab("Packages", null, jspPackage); _txtObject = new JTextArea(); _txtObject.setFont(pFont); JScrollPane jspObject = new JScrollPane(_txtObject); jspObject.setBorder( BorderFactory. createEmptyBorder ( inset, inset, inset, inset ) ); _pTabbedPane.addTab("Classes", null, jspObject); _txtFunction = new JTextArea(); _txtFunction.setFont(pFont); JScrollPane jspFunction = new JScrollPane(_txtFunction); jspFunction.setBorder( BorderFactory. createEmptyBorder ( inset, inset, inset, inset ) ); _pTabbedPane.addTab("Methods", null, jspFunction); // date and time String sTimeZoneID = System.getProperty("user.timezone"); if (sTimeZoneID.equals("CET")) { sTimeZoneID = "ECT"; } TimeZone pTimeZone = TimeZone.getTimeZone(sTimeZoneID); Util.debug("JavancssFrame.showJavancss(..).pTimeZone.getID(): " + pTimeZone.getID()); SimpleDateFormat pSimpleDateFormat = new SimpleDateFormat("EEE, MMM dd, yyyy HH:mm:ss");//"yyyy.mm.dd e 'at' hh:mm:ss a z"); pSimpleDateFormat.setTimeZone(pTimeZone); String sDate = pSimpleDateFormat.format(new Date()) + " " + pTimeZone.getID(); _txtPackage.setText(sDate + "\n\n" + pJavancss_.printPackageNcss()); _txtObject.setText(sDate + "\n\n" + pJavancss_.printObjectNcss()); _txtFunction.setText(sDate + "\n\n" + pJavancss_.printFunctionNcss()); if (pJavancss_.getLastErrorMessage() != null) { _txtError = new JTextArea(); String sError = "Errors in Javancss:\n\n" + pJavancss_.getLastErrorMessage(); _txtError.setText(sError); JScrollPane jspError = new JScrollPane(_txtError); jspError.setBorder( BorderFactory. createEmptyBorder ( inset, inset, inset, inset ) ); getContentPane().add(jspError, BorderLayout.CENTER); _pTabbedPane.addTab("Errors", null, jspError); } pPanel.add(_pTabbedPane, BorderLayout.CENTER); getContentPane().add(pPanel, BorderLayout.CENTER); } validate(); repaint(); } private boolean _bStop = false; private boolean _bSave = false; public void run() { _bSave = false; while(!_bStop) { if (_bSave) { save(); _bSave = false; } if (isExitSet()) { exit(); _bStop = true; break; } if (_bAboutSelected) { _bAboutSelected = false; AboutDialog dlgAbout = new AboutDialog ( this, getInit().getAuthor(), javancss.Main.S_RCS_HEADER ); dlgAbout.dispose(); requestFocus(); } try { Thread.sleep(500); } catch (InterruptedException e) { } } } public void setVisible(boolean bVisible_) { if (bVisible_) { _oldThreadPriority = Thread.currentThread().getPriority(); _pAnimationPanel.start(); Thread.currentThread().setPriority(Thread.MIN_PRIORITY); } else { _pAnimationPanel.stop(); } super.setVisible(bVisible_); } public void setSelectedTab(String sTab_) { Util.panicIf(Util.isEmpty(sTab_)); if (!_bNoError) { return; } if (sTab_.equals(S_METHODS)) { /*_pTabbedPane.setSelectedComponent(_txtFunction);*/ _pTabbedPane.setSelectedIndex(2); } else if (sTab_.equals(S_CLASSES)) { /*_pTabbedPane.setSelectedComponent(_txtObject);*/ _pTabbedPane.setSelectedIndex(1); } else { /*_pTabbedPane.setSelectedComponent(_txtPackage);*/ _pTabbedPane.setSelectedIndex(0); } } private boolean _bAboutSelected = false; public void actionPerformed(ActionEvent pActionEvent_) { Util.debug("JavancssFrame.actionPerformed(..).1"); Object oSource = pActionEvent_.getSource(); if (oSource instanceof JMenuItem) { String sMenuItem = ((JMenuItem)oSource).getText(); if (sMenuItem.equals("Beenden") || sMenuItem.equals("Exit")) { processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } else if (sMenuItem.equals(S_MN_F_SAVE)) { _bSave = true; } else if (sMenuItem.equals("Info...") || sMenuItem.equals("About...") || sMenuItem.equals("Info") || sMenuItem.equals("About")) { _bAboutSelected = true; } else if (sMenuItem.equals("Inhalt...") || sMenuItem.equals("Contents...") || sMenuItem.equals("Inhalt") || sMenuItem.equals("Contents")) { String sStartURL = FileUtil.concatPath(FileUtil.getPackagePath("javancss"), S_DOC_DIR) + File.separator + "index.html"; if (Util.isEmpty(sStartURL)) { return; } sStartURL = sStartURL.replace('\\', '/'); if (sStartURL.charAt(0) != '/') { sStartURL = "/" + sStartURL; } sStartURL = "file:" + sStartURL; Util.debug("JavancssFrame.actionPerformed(): sStartURL: " + sStartURL); /*try { URL urlHelpDocument = new URL(sStartURL); //HtmlViewer pHtmlViewer = new HtmlViewer(urlHelpDocument); } catch(Exception pException) { Util.debug("JavancssFrame.actionPerformed(..).pException: " + pException); }*/ } } } }
gpl-2.0
Norkart/NK-VirtualGlobe
Xj3D/src/java/org/web3d/vrml/export/compressors/RangeCompressor.java
2664
/***************************************************************************** * Web3d.org Copyright (c) 2001 * Java Source * * This source is licensed under the GNU LGPL v2.1 * Please read http://www.gnu.org/copyleft/lgpl.html for more information * * This software comes with the standard NO WARRANTY disclaimer for any * purpose. Use it at your own risk. If there's a problem you get to fix it. * ****************************************************************************/ package org.web3d.vrml.export.compressors; // Standard library imports import java.io.DataOutputStream; import java.io.IOException; // Application specific imports import org.web3d.vrml.lang.*; import org.web3d.vrml.nodes.VRMLNodeType; /** * A FieldCompressor that works by compressing the range of data. Floats are * converted to ints before range compression. * * @author Alan Hudson * @version $Revision: 1.4 $ */ public class RangeCompressor extends BinaryFieldEncoder { /** * Compress this field and deposit the output to the bitstream * * @param dos The stream to output the result * @param fieldType The type of field to compress from FieldConstants. * @param data The field data */ public void compress(DataOutputStream dos, int fieldType, int[] data) throws IOException { CompressionTools.rangeCompressIntArray(dos,false,1,data); } /** * Compress this field and deposit the output to the bitstream * * @param dos The stream to output the result * @param fieldType The type of field to compress from FieldConstants. * @param data The field data */ public void compress(DataOutputStream dos, int fieldType, float[] data) throws IOException { switch(fieldType) { case FieldConstants.SFCOLOR: case FieldConstants.SFVEC3F: case FieldConstants.SFROTATION: case FieldConstants.SFCOLORRGBA: case FieldConstants.SFVEC2F: for(int i=0; i < data.length; i++) { dos.writeFloat(data[i]); } break; case FieldConstants.MFCOLOR: case FieldConstants.MFVEC3F: case FieldConstants.MFFLOAT: case FieldConstants.MFROTATION: case FieldConstants.MFCOLORRGBA: case FieldConstants.MFVEC2F: CompressionTools.compressFloatArray(dos, false,1,data); break; default: System.out.println("Unhandled datatype in compress float[]: " + fieldType); } } }
gpl-2.0
FreeCol/freecol
src/net/sf/freecol/common/networking/AnimateAttackMessage.java
7919
/** * Copyright (C) 2002-2022 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.common.networking; import java.util.ArrayList; import java.util.List; import javax.xml.stream.XMLStreamException; import net.sf.freecol.client.FreeColClient; import net.sf.freecol.common.io.FreeColXMLReader; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.Unit; import net.sf.freecol.server.FreeColServer; import net.sf.freecol.server.ai.AIPlayer; /** * The message sent to tell a client to show an attack animation. */ public class AnimateAttackMessage extends ObjectMessage { public static final String TAG = "animateAttack"; private static final String ATTACKER_TAG = "attacker"; private static final String ATTACKER_TILE_TAG = "attackerTile"; private static final String DEFENDER_TAG = "defender"; private static final String DEFENDER_TILE_TAG = "defenderTile"; private static final String SUCCESS_TAG = "success"; /** * Create a new {@code AnimateAttackMessage} for the supplied attacker, * defender, result and visibility information. * * @param attacker The attacking {@code Unit}. * @param defender The defending {@code Unit}. * @param result Whether the attack succeeds. * @param addAttacker Whether to attach the attacker unit. * @param addDefender Whether to attach the defender unit. */ public AnimateAttackMessage(Unit attacker, Unit defender, boolean result, boolean addAttacker, boolean addDefender) { super(TAG, ATTACKER_TAG, attacker.getId(), ATTACKER_TILE_TAG, attacker.getTile().getId(), DEFENDER_TAG, defender.getId(), DEFENDER_TILE_TAG, defender.getTile().getId(), SUCCESS_TAG, Boolean.toString(result)); if (addAttacker) { appendChild((attacker.isOnCarrier()) ? attacker.getCarrier() : attacker); } if (addDefender) { appendChild((defender.isOnCarrier()) ? defender.getCarrier() : defender); } } /** * Create a new {@code AnimateAttackMessage} from a stream. * * @param game The {@code Game} this message belongs to. * @param xr The {@code FreeColXMLReader} to read from. * @exception XMLStreamException if there is a problem reading the stream. */ public AnimateAttackMessage(Game game, FreeColXMLReader xr) throws XMLStreamException { super(TAG, xr, ATTACKER_TAG, ATTACKER_TILE_TAG, DEFENDER_TAG, DEFENDER_TILE_TAG, SUCCESS_TAG); FreeColXMLReader.ReadScope rs = xr.replaceScope(FreeColXMLReader.ReadScope.NOINTERN); List<Unit> units = new ArrayList<>(); try { while (xr.moreTags()) { String tag = xr.getLocalName(); if (Unit.TAG.equals(tag)) { Unit u = xr.readFreeColObject(game, Unit.class); if (u != null) units.add(u); } else { expected(Unit.TAG, tag); } xr.expectTag(tag); } xr.expectTag(TAG); } finally { xr.replaceScope(rs); } appendChildren(units); } /** * Get a unit by key. * * @param game The {@code Game} to look up the unit in. * @param key An attribute key to extract the unit identifier with. * @return The attacker {@code Unit}. */ private Unit getUnit(Game game, String key) { final String id = getStringAttribute(key); if (id == null) return null; Unit unit = game.getFreeColGameObject(id, Unit.class); if (unit != null) return unit; for (Unit u : getChildren(Unit.class)) { if (id.equals(u.getId())) { u.intern(); return u; } if ((u = u.getCarriedUnitById(id)) != null) { u.intern(); return u; } } return null; } /** * Get the attacker unit. * * @param game The {@code Game} to look up the unit in. * @return The attacker {@code Unit}. */ private Unit getAttacker(Game game) { return getUnit(game, ATTACKER_TAG); } /** * Get the defender unit. * * @param game The {@code Game} to look up the unit in. * @return The defender {@code Unit}. */ private Unit getDefender(Game game) { return getUnit(game, DEFENDER_TAG); } /** * Get the attacker tile. * * @param game The {@code Game} to look up the tile in. * @return The attacker {@code Tile}. */ private Tile getAttackerTile(Game game) { return game.getFreeColGameObject(getStringAttribute(ATTACKER_TILE_TAG), Tile.class); } /** * Get the defender tile. * * @param game The {@code Game} to look up the tile in. * @return The defender {@code Tile}. */ private Tile getDefenderTile(Game game) { return game.getFreeColGameObject(getStringAttribute(DEFENDER_TILE_TAG), Tile.class); } /** * Get the result of the attack. * * @return The result. */ private boolean getResult() { return getBooleanAttribute(SUCCESS_TAG, Boolean.FALSE); } /** * {@inheritDoc} */ @Override public MessagePriority getPriority() { return Message.MessagePriority.ANIMATION; } /** * {@inheritDoc} */ @Override public void aiHandler(FreeColServer freeColServer, AIPlayer aiPlayer) { // Ignored } /** * {@inheritDoc} */ @Override public void clientHandler(FreeColClient freeColClient) { final Game game = freeColClient.getGame(); final Player player = freeColClient.getMyPlayer(); final Tile attackerTile = getAttackerTile(game); final Tile defenderTile = getDefenderTile(game); final boolean result = getResult(); final Unit attacker = getAttacker(game); final Unit defender = getDefender(game); if (attacker == null) { logger.warning("Attack animation missing attacker unit."); return; } if (defender == null) { logger.warning("Attack animation missing defender unit."); return; } if (attackerTile == null) { logger.warning("Attack animation for: " + player.getId() + " omitted attacker tile."); } if (defenderTile == null) { logger.warning("Attack animation for: " + player.getId() + " omitted defender tile."); } // This only performs animation, if required. It does not // actually perform an attack. igc(freeColClient) .animateAttackHandler(attacker, defender, attackerTile, defenderTile, result); clientGeneric(freeColClient); } }
gpl-2.0
rafaelkalan/metastone
src/main/java/net/demilich/metastone/game/spells/desc/condition/ManaMaxedCondition.java
569
package net.demilich.metastone.game.spells.desc.condition; import net.demilich.metastone.game.GameContext; import net.demilich.metastone.game.Player; import net.demilich.metastone.game.entities.Entity; import net.demilich.metastone.game.logic.GameLogic; public class ManaMaxedCondition extends Condition { public ManaMaxedCondition(ConditionDesc desc) { super(desc); } @Override protected boolean isFulfilled(GameContext context, Player player, ConditionDesc desc, Entity target) { return player.getMaxMana() >= GameLogic.MAX_MANA; } }
gpl-2.0
DiegoArranzGarcia/JavaTracer
JavaTracer/src/com/inspector/objectinspector/view/ObjectInspectorViewInterface.java
450
package com.inspector.objectinspector.view; import com.general.view.jtreetable.TableTreeNode; import com.inspector.objectinspector.presenter.ObjectInspectorPresenterInterface; public interface ObjectInspectorViewInterface { public void setController(ObjectInspectorPresenterInterface objectInspectorPresenter); public void clearTable(); public TableTreeNode getRoot(); public void refreshTable(); public ObjectInspectorView getView() ; }
gpl-2.0
ismail-l/test-repo
src/tms2/server/usercategory/UserCategoryManager.java
5586
/* * Autshumato Terminology Management System (TMS) * Free web application for the management of multilingual terminology databases (termbanks). * * Copyright (C) 2013 Centre for Text Technology (CTexT®), North-West University * and Department of Arts and Culture, Government of South Africa * Home page: http://www.nwu.co.za/ctext * Project page: http://autshumatotms.sourceforge.net * * 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 tms2.server.usercategory; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import javax.servlet.http.HttpSession; import tms2.server.sql.StoredProcedureManager; import tms2.server.user.UserManager; import tms2.shared.User; import tms2.shared.UserCategory; /** * * @author I. Lavangee * */ public class UserCategoryManager { /** * Retrieves all the user categories including the users the belong to each. * Used by the User & Categories panel in the Administration Interface. * @param connection * @return * @throws SQLException */ public static ArrayList<UserCategory> getAllUserCategoriesWithUsers(Connection connection, HttpSession session, String authToken) throws SQLException { ArrayList<UserCategory> userCategories = new ArrayList<UserCategory>(); String sql = "select * from tms.usercategories"; CallableStatement stored_procedure = StoredProcedureManager.genericReturnedRef(connection, sql); ResultSet results = (ResultSet) stored_procedure.getObject(1); while (results.next()) { int userCategoryId = results.getInt("usercategoryid"); ArrayList<User> users = UserManager.getAllUsersByCategory(connection, userCategoryId); UserCategory category = newUserCategoryWithUsers(results, users); userCategories.add(category); } results.close(); stored_procedure.close(); return userCategories; } public static UserCategory getUserCategoryByUserCategoryId(Connection connection, long userCategoryId) throws SQLException { UserCategory userCategory = null; String sql = "select * from tms.usercategories where usercategoryid = " + userCategoryId; CallableStatement stored_procedure = StoredProcedureManager.genericReturnedRef(connection, sql); ResultSet results = (ResultSet) stored_procedure.getObject(1); if (results.next()) userCategory = newUserCategory(results); results.close(); stored_procedure.close(); return userCategory; } public static boolean getUserCategoryIsAdmin(Connection connection, long userCategoryId) throws SQLException { boolean isAdmin = false; String sql = "select isadmin from tms.usercategories where usercategoryid = " + userCategoryId; CallableStatement stored_procedure = StoredProcedureManager.genericReturnedRef(connection, sql); ResultSet results = (ResultSet) stored_procedure.getObject(1); if (results.next()) isAdmin = results.getBoolean("isadmin"); results.close(); stored_procedure.close(); return isAdmin; } public static UserCategory updateUserCategory(Connection connection, UserCategory userCategory, boolean is_updating) throws SQLException { UserCategory updated = null; CallableStatement stored_procedure = null; if (is_updating) stored_procedure = StoredProcedureManager.updateUserCategory(connection, userCategory); else stored_procedure = StoredProcedureManager.createUserCategory(connection, userCategory); long result = -1; result = (Long)stored_procedure.getObject(1); if (result > -1) updated = getUserCategoryByUserCategoryId(connection, result); stored_procedure.close(); return updated; } public static void deleteUserCategory(Connection connection, UserCategory userCategory, String authToken, HttpSession session) throws SQLException { String sql = "delete from tms.usercategories where usercategoryid = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1, userCategory.getUserCategoryId()); statement.executeUpdate(); } private static UserCategory newUserCategory(ResultSet results) throws SQLException { UserCategory userCategory = new UserCategory(); userCategory.setUserCategoryId(results.getInt("usercategoryid")); userCategory.setUserCategoryName(results.getString("usercategory")); userCategory.setAdmin(results.getBoolean("isadmin")); return userCategory; } // Create a UserCategory instance, with all the users belonging to this category, using the result set provided. private static UserCategory newUserCategoryWithUsers(ResultSet results, ArrayList<User> users) throws SQLException { UserCategory userCategory = new UserCategory(); userCategory.setUserCategoryId(results.getInt("usercategoryid")); userCategory.setUserCategoryName(results.getString("usercategory")); userCategory.setAdmin(results.getBoolean("isadmin")); userCategory.setUsers(users); return userCategory; } }
gpl-2.0
ruslanrf/wpps
wpps_plugins/tuwien.dbai.wpps.core/src/tuwien/dbai/wpps/core/wpmodel/physmodel/im/instadp/EFontStyle.java
680
/** * */ package tuwien.dbai.wpps.core.wpmodel.physmodel.im.instadp; import tuwien.dbai.wpps.core.wpmodel.IContainsRDFResource; import tuwien.dbai.wpps.ontschema.InterfaceModelOnt; import com.hp.hpl.jena.rdf.model.Resource; /** * @author Ruslan (ruslanrf@gmail.com) * @created Jul 3, 2012 5:58:16 PM */ public enum EFontStyle implements IContainsRDFResource { NORMAL_FONT_STYLE(InterfaceModelOnt.NormalFontStyle), ITALIC(InterfaceModelOnt.Italic), OBLIQUE(InterfaceModelOnt.Oblique) ; EFontStyle(Resource fontStyle) { this.fontStyle = fontStyle; } private final Resource fontStyle; @Override public Resource getRdfResource() { return fontStyle; } }
gpl-2.0
rex-xxx/mt6572_x201
mediatek/packages/apps/Bluetooth/profiles/map/src/com/mediatek/bluetooth/map/cache/FolderListObject.java
2588
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ package com.mediatek.bluetooth.map.cache; import com.mediatek.bluetooth.map.util.UtcUtil; public class FolderListObject{ private String mTime = UtcUtil.getCurrentTime(); // "yyyymmddTHHMMSSZ", or "" if none private int mSize; private String mName; public void setName(String name){ mName = name; } public void setSize(int size){ mSize = size; } }
gpl-2.0
Desmaster/Pixxel
map/tiled/Tile.java
285
package nl.tdegroot.games.pixxel.map.tiled; public class Tile { public int tileID; public int firstGID,lastGID; public Tile(int tileID, int firstGID, int lastGID) { this.tileID = tileID; this.firstGID = firstGID; this.lastGID = lastGID; } }
gpl-2.0
ryan-gyger/senior-web
src/main/java/org/nized/web/domain/Checkin.java
1597
package org.nized.web.domain; import java.util.Date; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonSerialize @JsonDeserialize public class Checkin { private Person person; // Based on email stored in DB private Date date_scanned; public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public Date getDateScanned() { return date_scanned; } public void setDateScanned(Date dateScanned) { this.date_scanned = dateScanned; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((date_scanned == null) ? 0 : date_scanned.hashCode()); result = prime * result + ((person == null) ? 0 : person.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; } Checkin other = (Checkin) obj; if (date_scanned == null) { if (other.date_scanned != null) { return false; } } else if (!date_scanned.equals(other.date_scanned)) { return false; } if (person == null) { if (other.person != null) { return false; } } else if (!person.equals(other.person)) { return false; } return true; } @Override public String toString() { return "Checkin [person=" + person + ", date_scanned=" + date_scanned + "]"; } }
gpl-2.0
rodnaph/sockso
test/com/pugh/sockso/JsonUtilsTest.java
257
package com.pugh.sockso; import com.pugh.sockso.tests.SocksoTestCase; public class JsonUtilsTest extends SocksoTestCase { public void testStringEscapesDoubleQuotes() { assertEquals( "\"a\\\"b\"", JsonUtils.string("a\"b") ); } }
gpl-2.0
NexusTools/JVM.JS-JavaRuntime
src/net/nexustools/jvm/runtime/java/lang/reflect/ParameterizedType.java
3996
/* * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package net.nexustools.jvm.runtime.java.lang.reflect; /** * ParameterizedType represents a parameterized type such as * Collection&lt;String&gt;. * * <p>A parameterized type is created the first time it is needed by a * reflective method, as specified in this package. When a * parameterized type p is created, the generic type declaration that * p instantiates is resolved, and all type arguments of p are created * recursively. See {@link net.nexustools.jvm.runtime.java.lang.reflect.TypeVariable * TypeVariable} for details on the creation process for type * variables. Repeated creation of a parameterized type has no effect. * * <p>Instances of classes that implement this interface must implement * an equals() method that equates any two instances that share the * same generic type declaration and have equal type parameters. * * @since 1.5 */ public interface ParameterizedType extends Type { /** * Returns an array of {@code Type} objects representing the actual type * arguments to this type. * * <p>Note that in some cases, the returned array be empty. This can occur * if this type represents a non-parameterized type nested within * a parameterized type. * * @return an array of {@code Type} objects representing the actual type * arguments to this type * @throws TypeNotPresentException if any of the * actual type arguments refers to a non-existent type declaration * @throws MalformedParameterizedTypeException if any of the * actual type parameters refer to a parameterized type that cannot * be instantiated for any reason * @since 1.5 */ Type[] getActualTypeArguments(); /** * Returns the {@code Type} object representing the class or interface * that declared this type. * * @return the {@code Type} object representing the class or interface * that declared this type * @since 1.5 */ Type getRawType(); /** * Returns a {@code Type} object representing the type that this type * is a member of. For example, if this type is {@code O<T>.I<S>}, * return a representation of {@code O<T>}. * * <p>If this type is a top-level type, {@code null} is returned. * * @return a {@code Type} object representing the type that * this type is a member of. If this type is a top-level type, * {@code null} is returned * @throws TypeNotPresentException if the owner type * refers to a non-existent type declaration * @throws MalformedParameterizedTypeException if the owner type * refers to a parameterized type that cannot be instantiated * for any reason * @since 1.5 */ Type getOwnerType(); }
gpl-2.0
pivotal/tcs-hq-product-plugin
src/main/java/com/springsource/hq/plugin/tcserver/plugin/appmgmt/ScriptingApplicationManager.java
1761
/* Copyright (C) 2010-2014 Pivotal Software, Inc. All rights reserved. This program and the accompanying materials are made available under the terms of the 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.springsource.hq.plugin.tcserver.plugin.appmgmt; import java.util.List; import java.util.Map; import org.hyperic.hq.product.PluginException; import org.hyperic.util.config.ConfigResponse; import com.springsource.hq.plugin.tcserver.plugin.appmgmt.domain.ApplicationStatus; import com.springsource.hq.plugin.tcserver.plugin.appmgmt.domain.Service; public interface ScriptingApplicationManager { List<ApplicationStatus> deploy(ConfigResponse config) throws PluginException; Map<String, List<String>> getServiceHostMappings(ConfigResponse config) throws PluginException; List<Service> list(ConfigResponse config) throws PluginException; List<ApplicationStatus> reload(ConfigResponse config) throws PluginException; List<ApplicationStatus> start(ConfigResponse config) throws PluginException; List<ApplicationStatus> stop(ConfigResponse config) throws PluginException; List<ApplicationStatus> undeploy(ConfigResponse config) throws PluginException; }
gpl-2.0
o-alex/GVoD
bootstrap/server/caracal-client/src/main/java/se/sics/gvod/bootstrap/cclient/CaracalKeyFactory.java
3205
/* * Copyright (C) 2009 Swedish Institute of Computer Science (SICS) Copyright (C) * 2009 Royal Institute of Technology (KTH) * * GVoD is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package se.sics.gvod.bootstrap.cclient; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import se.sics.caracaldb.Key; import se.sics.caracaldb.KeyRange; /** * @author Alex Ormenisan <aaor@sics.se> */ public class CaracalKeyFactory { private static byte[] prefix; static { String schema = "gvod-v1"; try { prefix = MessageDigest.getInstance("MD5").digest(schema.getBytes()); } catch (NoSuchAlgorithmException ex) { System.exit(1); throw new RuntimeException(ex); } } private final static byte peerKey = 0x01; private final static byte fileMetaKey = 0x02; public static KeyRange getOverlayRange(int overlayId) { ByteBuffer startKey = ByteBuffer.allocate(sizeofOverlayKeyPrefix()); startKey.put(prefix); startKey.putInt(overlayId); startKey.put(peerKey); ByteBuffer endKey = ByteBuffer.allocate(sizeofOverlayKeyPrefix()); endKey.put(prefix); endKey.putInt(overlayId); endKey.put(fileMetaKey); return new KeyRange(KeyRange.Bound.CLOSED, new Key(startKey), new Key(endKey), KeyRange.Bound.OPEN); } public static Key getOverlayPeerKey(int overlayId, int nodeId) { ByteBuffer oKey = ByteBuffer.allocate(sizeofOverlayPeerKey()); oKey.put(prefix); oKey.putInt(overlayId); oKey.put(peerKey); oKey.putInt(nodeId); return new Key(oKey); } public static Key getFileMetadataKey(int overlayId) { ByteBuffer byteKey = ByteBuffer.allocate(sizeofOverlayKeyPrefix()); byteKey.put(prefix); byteKey.putInt(overlayId); byteKey.put(fileMetaKey); return new Key(byteKey); } private static int sizeofOverlayKeyPrefix() { int size = 0; size += prefix.length; size += Integer.SIZE/8; //overlayId; size += Byte.SIZE/8; //key type = overlay peer key return size; } private static int sizeofOverlayPeerKey() { int size = 0; size += sizeofOverlayKeyPrefix(); size += Integer.SIZE/8; //nodeId; return size; } public static class KeyException extends Exception { public KeyException(String message) { super(message); } } }
gpl-2.0
GeoTechSystems/GeoTechMobile
app/src/main/java/de/geotech/systems/kriging/DataPoint.java
219
package de.geotech.systems.kriging; public class DataPoint { String name, region, date, typ; double xCoordinate, yCoordinate; int id; int isValuePoint; Integer data, intData; boolean hasConvergence = true; }
gpl-2.0
dkfellows/stendhal
src/games/stendhal/client/gui/login/LoginDialog.java
19502
/* $Id$ */ /*************************************************************************** * (C) Copyright 2003 - Marauroa * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.client.gui.login; import games.stendhal.client.StendhalClient; import games.stendhal.client.stendhal; import games.stendhal.client.gui.ProgressBar; import games.stendhal.client.gui.WindowUtils; import games.stendhal.client.gui.layout.SBoxLayout; import games.stendhal.client.sprite.DataLoader; import games.stendhal.client.update.ClientGameConfiguration; import java.awt.Component; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Document; import marauroa.client.BannedAddressException; import marauroa.client.LoginFailedException; import marauroa.client.TimeoutException; import marauroa.common.io.Persistence; import marauroa.common.net.InvalidVersionException; import marauroa.common.net.message.MessageS2CLoginNACK; import org.apache.log4j.Logger; /** * Server login dialog. * */ public class LoginDialog extends JDialog { private static final long serialVersionUID = -1182930046629241075L; private ProfileList profiles; private JComboBox profilesComboBox; private JCheckBox saveLoginBox; private JCheckBox savePasswordBox; private JTextField usernameField; private JPasswordField passwordField; private JTextField serverField; private JTextField serverPortField; private JButton loginButton; private JButton removeButton; // End of variables declaration private final StendhalClient client; private ProgressBar progressBar; // Object checking that all required fields are filled private DataValidator fieldValidator; /** * Create a new LoginDialog. * * @param owner parent window * @param client client */ public LoginDialog(final Frame owner, final StendhalClient client) { super(owner, true); this.client = client; initializeComponent(); WindowUtils.closeOnEscape(this); } /** * Create the dialog contents. */ private void initializeComponent() { this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (getOwner() == null) { System.exit(0); } getOwner().setEnabled(true); dispose(); } }); JLabel l; this.setTitle("Login to Server"); this.setResizable(false); // // contentPane // JComponent contentPane = (JComponent) getContentPane(); contentPane.setLayout(new GridBagLayout()); final int pad = SBoxLayout.COMMON_PADDING; contentPane.setBorder(BorderFactory.createEmptyBorder(pad, pad, pad, pad)); final GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.LINE_START; /* * Profiles */ l = new JLabel("Account profiles"); c.insets = new Insets(4, 4, 15, 4); // column c.gridx = 0; // row c.gridy = 0; contentPane.add(l, c); profilesComboBox = new JComboBox(); profilesComboBox.addActionListener(new ProfilesCB()); /* * Remove profile button */ removeButton = createRemoveButton(); // Container for the profiles list and the remove button JComponent box = SBoxLayout.createContainer(SBoxLayout.HORIZONTAL, pad); profilesComboBox.setAlignmentY(Component.CENTER_ALIGNMENT); box.add(profilesComboBox); box.add(removeButton); c.gridx = 1; c.gridy = 0; c.fill = GridBagConstraints.BOTH; contentPane.add(box, c); /* * Server Host */ l = new JLabel("Server name"); c.insets = new Insets(4, 4, 4, 4); // column c.gridx = 0; // row c.gridy = 1; contentPane.add(l, c); serverField = new JTextField( ClientGameConfiguration.get("DEFAULT_SERVER")); c.gridx = 1; c.gridy = 1; c.fill = GridBagConstraints.BOTH; contentPane.add(serverField, c); /* * Server Port */ l = new JLabel("Server port"); c.insets = new Insets(4, 4, 4, 4); c.gridx = 0; c.gridy = 2; contentPane.add(l, c); serverPortField = new JTextField( ClientGameConfiguration.get("DEFAULT_PORT")); c.gridx = 1; c.gridy = 2; c.insets = new Insets(4, 4, 4, 4); c.fill = GridBagConstraints.BOTH; contentPane.add(serverPortField, c); /* * Username */ l = new JLabel("Type your username"); c.insets = new Insets(4, 4, 4, 4); c.gridx = 0; c.gridy = 3; contentPane.add(l, c); usernameField = new JTextField(); c.gridx = 1; c.gridy = 3; c.fill = GridBagConstraints.BOTH; contentPane.add(usernameField, c); /* * Password */ l = new JLabel("Type your password"); c.gridx = 0; c.gridy = 4; c.fill = GridBagConstraints.NONE; contentPane.add(l, c); passwordField = new JPasswordField(); c.gridx = 1; c.gridy = 4; c.fill = GridBagConstraints.BOTH; contentPane.add(passwordField, c); /* * Save Profile/Login */ saveLoginBox = new JCheckBox("Save login profile locally"); saveLoginBox.setSelected(false); c.gridx = 0; c.gridy = 5; c.fill = GridBagConstraints.NONE; contentPane.add(saveLoginBox, c); /* * Save Profile Password */ savePasswordBox = new JCheckBox("Save password"); savePasswordBox.setSelected(true); savePasswordBox.setEnabled(false); c.gridx = 0; c.gridy = 6; c.fill = GridBagConstraints.NONE; c.insets = new Insets(0, 20, 0, 0); contentPane.add(savePasswordBox, c); loginButton = new JButton(); loginButton.setText("Login to Server"); loginButton.setMnemonic(KeyEvent.VK_L); this.rootPane.setDefaultButton(loginButton); loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { loginButtonActionPerformed(); } }); c.gridx = 1; c.gridy = 5; c.gridheight = 2; c.anchor = GridBagConstraints.CENTER; c.insets = new Insets(15, 4, 4, 4); contentPane.add(loginButton, c); // Before loading profiles so that we can catch the data filled from // there bindEditListener(); /* * Load saved profiles */ profiles = loadProfiles(); populateProfiles(profiles); /* * Add this callback after everything is initialized */ saveLoginBox.addChangeListener(new SaveProfileStateCB()); // // Dialog // this.pack(); usernameField.requestFocusInWindow(); if (getOwner() != null) { getOwner().setEnabled(false); this.setLocationRelativeTo(getOwner()); } } /** * Prepare the field validator and bind it to the relevant text fields. */ private void bindEditListener() { fieldValidator = new DataValidator(loginButton, serverField.getDocument(), serverPortField.getDocument(), usernameField.getDocument(), passwordField.getDocument()); } /** * Create the remove character button. * * @return JButton */ private JButton createRemoveButton() { final URL url = DataLoader.getResource("data/gui/trash.png"); ImageIcon icon = new ImageIcon(url); JButton button = new JButton(icon); // Clear the margins that buttons normally add button.setMargin(new Insets(0, 0, 0, 0)); button.setToolTipText("Remove the selected account from the list"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { removeButtonActionPerformed(); } }); return button; } /** * Called when the login button is activated. */ private void loginButtonActionPerformed() { // If this window isn't enabled, we shouldn't act. if (!isEnabled()) { return; } setEnabled(false); Profile profile; profile = new Profile(); profile.setHost((serverField.getText()).trim()); try { profile.setPort(Integer.parseInt(serverPortField.getText().trim())); // Support for saving port number. Only save when input is a number // intensifly@gmx.com } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(this, "That is not a valid port number. Please try again.", "Invalid port", JOptionPane.WARNING_MESSAGE); return; } profile.setUser(usernameField.getText().trim()); profile.setPassword(new String(passwordField.getPassword())); /* * Save profile? */ if (saveLoginBox.isSelected()) { profiles.add(profile); populateProfiles(profiles); if (savePasswordBox.isSelected()) { saveProfiles(profiles); } else { final String pw = profile.getPassword(); profile.setPassword(""); saveProfiles(profiles); profile.setPassword(pw); } } /* * Run the connection procces in separate thread. added by TheGeneral */ final Thread t = new Thread(new ConnectRunnable(profile), "Login"); t.start(); } /** * Called when the remove profile button is activated. */ private void removeButtonActionPerformed() { // If this window isn't enabled, we shouldn't act. if (!isEnabled() || (profiles.profiles.size() == 0)) { return; } setEnabled(false); Profile profile; profile = (Profile) profilesComboBox.getSelectedItem(); Object[] options = { "Remove", "Cancel" }; Integer confirmRemoveProfile = JOptionPane.showOptionDialog(this, "This will permanently remove a user profile from your local list of accounts.\n" + "It will not delete an account on any servers.\n" + "Are you sure you want to remove \'" + profile.getUser() + "@" + profile.getHost() + "\' profile?", "Remove user profile from local list of accounts", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (confirmRemoveProfile == 0) { profiles.remove(profile); saveProfiles(profiles); profiles = loadProfiles(); populateProfiles(profiles); } setEnabled(true); } @Override public void setEnabled(final boolean b) { super.setEnabled(b); // Enabling login button is conditional fieldValidator.revalidate(); removeButton.setEnabled(b); } /** * Connect to a server using a given profile. * * @param profile profile used for login */ public void connect(final Profile profile) { // We are not in EDT SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar = new ProgressBar(LoginDialog.this); progressBar.start(); } }); try { client.connect(profile.getHost(), profile.getPort()); // for each major connection milestone call step(). progressBar is // created in EDT, so it is not guaranteed non null in the main // thread. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.step(); } }); } catch (final Exception ex) { // if something goes horribly just cancel the progressbar SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.cancel(); setEnabled(true); } }); String message = "unable to connect to server"; if (profile != null) { message = message + " " + profile.getHost() + ":" + profile.getPort(); } else { message = message + ", because profile was null"; } Logger.getLogger(LoginDialog.class).error(message, ex); handleError("Unable to connect to server. Did you misspell the server name?", "Connection failed"); return; } try { client.setAccountUsername(profile.getUser()); client.setCharacter(profile.getCharacter()); client.login(profile.getUser(), profile.getPassword(), profile.getSeed()); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.finish(); // workaround near failures in AWT at openjdk (tested on openjdk-1.6.0.0) try { setVisible(false); } catch (NullPointerException npe) { Logger.getLogger(LoginDialog.class).error("Error probably related to bug in JRE occured", npe); LoginDialog.this.dispose(); } } }); } catch (final InvalidVersionException e) { handleError("You are running an incompatible version of Stendhal. Please update", "Invalid version"); } catch (final TimeoutException e) { handleError("Server is not available right now.\nThe server may be down or, if you are using a custom server,\nyou may have entered its name and port number incorrectly.", "Error Logging In"); } catch (final LoginFailedException e) { handleError(e.getMessage(), "Login failed"); if (e.getReason() == MessageS2CLoginNACK.Reasons.SEED_WRONG) { System.exit(1); } } catch (final BannedAddressException e) { handleError("Your IP is banned. If you think this is not right, please send a Support Request to http://sourceforge.net/tracker/?func=add&group_id=1111&atid=201111", "IP Banned"); } } /** * Displays the error message, removes the progress bar and * either enabled the login dialog in interactive mode or exits * the client in non interactive mode. * * @param errorMessage error message * @param errorTitle title of error dialog box */ private void handleError(final String errorMessage, final String errorTitle) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.cancel(); JOptionPane.showMessageDialog( LoginDialog.this, errorMessage, errorTitle, JOptionPane.ERROR_MESSAGE); if (isVisible()) { setEnabled(true); } else { // Hack for non interactive login System.exit(1); } } }); } /** * Load saves profiles. * @return ProfileList */ private ProfileList loadProfiles() { final ProfileList tmpProfiles = new ProfileList(); try { final InputStream is = Persistence.get().getInputStream(false, stendhal.getGameFolder(), "user.dat"); try { tmpProfiles.load(is); } finally { is.close(); } } catch (final FileNotFoundException fnfe) { // Ignore } catch (final IOException ioex) { JOptionPane.showMessageDialog(this, "An error occurred while loading your login information", "Error Loading Login Information", JOptionPane.WARNING_MESSAGE); } return tmpProfiles; } /** * Populate the profiles combobox and select the default. * * @param profiles profile data */ private void populateProfiles(final ProfileList profiles) { profilesComboBox.removeAllItems(); for (Profile p : profiles) { profilesComboBox.addItem(p); } /* * The last profile (if any) is the default. */ final int count = profilesComboBox.getItemCount(); if (count != 0) { profilesComboBox.setSelectedIndex(count - 1); } } /** * Called when a profile selection is changed. */ private void profilesCB() { Profile profile; String host; profile = (Profile) profilesComboBox.getSelectedItem(); if (profile != null) { host = profile.getHost(); serverField.setText(host); serverPortField.setText(String.valueOf(profile.getPort())); usernameField.setText(profile.getUser()); passwordField.setText(profile.getPassword()); } else { serverPortField.setText(String.valueOf(Profile.DEFAULT_SERVER_PORT)); usernameField.setText(""); passwordField.setText(""); } } /** * Checks that a group of Documents (text fields) is not empty, and enables * or disables a JComponent on that condition. */ private static class DataValidator implements DocumentListener { private final Document[] documents; private final JComponent component; /** * Create a new DataValidator. * * @param component component to be enabled depending on the state of * documents * @param docs documents */ DataValidator(JComponent component, Document... docs) { this.component = component; documents = docs; for (Document doc : docs) { doc.addDocumentListener(this); } revalidate(); } @Override public void insertUpdate(DocumentEvent e) { revalidate(); } @Override public void removeUpdate(DocumentEvent e) { if (e.getDocument().getLength() == 0) { component.setEnabled(false); } } @Override public void changedUpdate(DocumentEvent e) { // Attribute change - ignore } /** * Do a full document state check and set the component status according * to the result. */ final void revalidate() { for (Document doc : documents) { if (doc.getLength() == 0) { component.setEnabled(false); return; } } component.setEnabled(true); } } /* * Author: Da_MusH Description: Methods for saving and loading login * information to disk. These should probably make a separate class in the * future, but it will work for now. comment: Thegeneral has added encoding * for password and username. Changed for multiple profiles. */ private void saveProfiles(final ProfileList profiles) { try { final OutputStream os = Persistence.get().getOutputStream(false, stendhal.getGameFolder(), "user.dat"); try { profiles.save(os); } finally { os.close(); } } catch (final IOException ioex) { JOptionPane.showMessageDialog(this, "An error occurred while saving your login information", "Error Saving Login Information", JOptionPane.WARNING_MESSAGE); } } /** * Called when save profile selection change. */ private void saveProfileStateCB() { savePasswordBox.setEnabled(saveLoginBox.isSelected()); } /** * Server connect thread runnable. */ private final class ConnectRunnable implements Runnable { private final Profile profile; /** * Create a new ConnectRunnable. * * @param profile profile used for connection */ private ConnectRunnable(final Profile profile) { this.profile = profile; } @Override public void run() { connect(profile); } } /** * Profiles combobox selection change listener. */ private class ProfilesCB implements ActionListener { @Override public void actionPerformed(final ActionEvent e) { profilesCB(); } } /** * Save profile selection change. */ private class SaveProfileStateCB implements ChangeListener { @Override public void stateChanged(final ChangeEvent ev) { saveProfileStateCB(); } } }
gpl-2.0
mdavid/IKVM.NET-cvs-clone
openjdk/java/security/AccessController.java
23993
/* * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package java.security; import ikvm.internal.CallerID; import sun.misc.Unsafe; import sun.security.util.Debug; /** * <p> The AccessController class is used for access control operations * and decisions. * * <p> More specifically, the AccessController class is used for * three purposes: * * <ul> * <li> to decide whether an access to a critical system * resource is to be allowed or denied, based on the security policy * currently in effect,<p> * <li>to mark code as being "privileged", thus affecting subsequent * access determinations, and<p> * <li>to obtain a "snapshot" of the current calling context so * access-control decisions from a different context can be made with * respect to the saved context. </ul> * * <p> The {@link #checkPermission(Permission) checkPermission} method * determines whether the access request indicated by a specified * permission should be granted or denied. A sample call appears * below. In this example, <code>checkPermission</code> will determine * whether or not to grant "read" access to the file named "testFile" in * the "/temp" directory. * * <pre> * * FilePermission perm = new FilePermission("/temp/testFile", "read"); * AccessController.checkPermission(perm); * * </pre> * * <p> If a requested access is allowed, * <code>checkPermission</code> returns quietly. If denied, an * AccessControlException is * thrown. AccessControlException can also be thrown if the requested * permission is of an incorrect type or contains an invalid value. * Such information is given whenever possible. * * Suppose the current thread traversed m callers, in the order of caller 1 * to caller 2 to caller m. Then caller m invoked the * <code>checkPermission</code> method. * The <code>checkPermission </code>method determines whether access * is granted or denied based on the following algorithm: * * <pre> {@code * for (int i = m; i > 0; i--) { * * if (caller i's domain does not have the permission) * throw AccessControlException * * else if (caller i is marked as privileged) { * if (a context was specified in the call to doPrivileged) * context.checkPermission(permission) * return; * } * }; * * // Next, check the context inherited when the thread was created. * // Whenever a new thread is created, the AccessControlContext at * // that time is stored and associated with the new thread, as the * // "inherited" context. * * inheritedContext.checkPermission(permission); * }</pre> * * <p> A caller can be marked as being "privileged" * (see {@link #doPrivileged(PrivilegedAction) doPrivileged} and below). * When making access control decisions, the <code>checkPermission</code> * method stops checking if it reaches a caller that * was marked as "privileged" via a <code>doPrivileged</code> * call without a context argument (see below for information about a * context argument). If that caller's domain has the * specified permission, no further checking is done and * <code>checkPermission</code> * returns quietly, indicating that the requested access is allowed. * If that domain does not have the specified permission, an exception * is thrown, as usual. * * <p> The normal use of the "privileged" feature is as follows. If you * don't need to return a value from within the "privileged" block, do * the following: * * <pre> {@code * somemethod() { * ...normal code here... * AccessController.doPrivileged(new PrivilegedAction<Void>() { * public Void run() { * // privileged code goes here, for example: * System.loadLibrary("awt"); * return null; // nothing to return * } * }); * ...normal code here... * }}</pre> * * <p> * PrivilegedAction is an interface with a single method, named * <code>run</code>. * The above example shows creation of an implementation * of that interface; a concrete implementation of the * <code>run</code> method is supplied. * When the call to <code>doPrivileged</code> is made, an * instance of the PrivilegedAction implementation is passed * to it. The <code>doPrivileged</code> method calls the * <code>run</code> method from the PrivilegedAction * implementation after enabling privileges, and returns the * <code>run</code> method's return value as the * <code>doPrivileged</code> return value (which is * ignored in this example). * * <p> If you need to return a value, you can do something like the following: * * <pre> {@code * somemethod() { * ...normal code here... * String user = AccessController.doPrivileged( * new PrivilegedAction<String>() { * public String run() { * return System.getProperty("user.name"); * } * }); * ...normal code here... * }}</pre> * * <p>If the action performed in your <code>run</code> method could * throw a "checked" exception (those listed in the <code>throws</code> clause * of a method), then you need to use the * <code>PrivilegedExceptionAction</code> interface instead of the * <code>PrivilegedAction</code> interface: * * <pre> {@code * somemethod() throws FileNotFoundException { * ...normal code here... * try { * FileInputStream fis = AccessController.doPrivileged( * new PrivilegedExceptionAction<FileInputStream>() { * public FileInputStream run() throws FileNotFoundException { * return new FileInputStream("someFile"); * } * }); * } catch (PrivilegedActionException e) { * // e.getException() should be an instance of FileNotFoundException, * // as only "checked" exceptions will be "wrapped" in a * // PrivilegedActionException. * throw (FileNotFoundException) e.getException(); * } * ...normal code here... * }}</pre> * * <p> Be *very* careful in your use of the "privileged" construct, and * always remember to make the privileged code section as small as possible. * * <p> Note that <code>checkPermission</code> always performs security checks * within the context of the currently executing thread. * Sometimes a security check that should be made within a given context * will actually need to be done from within a * <i>different</i> context (for example, from within a worker thread). * The {@link #getContext() getContext} method and * AccessControlContext class are provided * for this situation. The <code>getContext</code> method takes a "snapshot" * of the current calling context, and places * it in an AccessControlContext object, which it returns. A sample call is * the following: * * <pre> * * AccessControlContext acc = AccessController.getContext() * * </pre> * * <p> * AccessControlContext itself has a <code>checkPermission</code> method * that makes access decisions based on the context <i>it</i> encapsulates, * rather than that of the current execution thread. * Code within a different context can thus call that method on the * previously-saved AccessControlContext object. A sample call is the * following: * * <pre> * * acc.checkPermission(permission) * * </pre> * * <p> There are also times where you don't know a priori which permissions * to check the context against. In these cases you can use the * doPrivileged method that takes a context: * * <pre> {@code * somemethod() { * AccessController.doPrivileged(new PrivilegedAction<Object>() { * public Object run() { * // Code goes here. Any permission checks within this * // run method will require that the intersection of the * // callers protection domain and the snapshot's * // context have the desired permission. * } * }, acc); * ...normal code here... * }}</pre> * * @see AccessControlContext * * @author Li Gong * @author Roland Schemers */ public final class AccessController { @cli.System.ThreadStaticAttribute.Annotation private static PrivilegedElement privileged_stack_top; private static final class PrivilegedElement { CallerID callerID; AccessControlContext context; } private static Object doPrivileged(Object action, AccessControlContext context, CallerID callerID) { PrivilegedElement savedPrivilegedElement = privileged_stack_top; try { PrivilegedElement pi = new PrivilegedElement(); pi.callerID = callerID; pi.context = context; privileged_stack_top = pi; try { if (action instanceof PrivilegedAction) { return ((PrivilegedAction)action).run(); } else { return ((PrivilegedExceptionAction)action).run(); } } catch (Exception x) { if (!(x instanceof RuntimeException)) { Unsafe.getUnsafe().throwException(new PrivilegedActionException(x)); } throw (RuntimeException)x; } } finally { privileged_stack_top = savedPrivilegedElement; } } /** * Don't allow anyone to instantiate an AccessController */ private AccessController() { } /** * Performs the specified <code>PrivilegedAction</code> with privileges * enabled. The action is performed with <i>all</i> of the permissions * possessed by the caller's protection domain. * * <p> If the action's <code>run</code> method throws an (unchecked) * exception, it will propagate through this method. * * <p> Note that any DomainCombiner associated with the current * AccessControlContext will be ignored while the action is performed. * * @param action the action to be performed. * * @return the value returned by the action's <code>run</code> method. * * @exception NullPointerException if the action is <code>null</code> * * @see #doPrivileged(PrivilegedAction,AccessControlContext) * @see #doPrivileged(PrivilegedExceptionAction) * @see #doPrivilegedWithCombiner(PrivilegedAction) * @see java.security.DomainCombiner */ @ikvm.internal.HasCallerID public static <T> T doPrivileged(PrivilegedAction<T> action) { return (T)doPrivileged(action, null, CallerID.getCallerID()); } /** * Performs the specified <code>PrivilegedAction</code> with privileges * enabled. The action is performed with <i>all</i> of the permissions * possessed by the caller's protection domain. * * <p> If the action's <code>run</code> method throws an (unchecked) * exception, it will propagate through this method. * * <p> This method preserves the current AccessControlContext's * DomainCombiner (which may be null) while the action is performed. * * @param action the action to be performed. * * @return the value returned by the action's <code>run</code> method. * * @exception NullPointerException if the action is <code>null</code> * * @see #doPrivileged(PrivilegedAction) * @see java.security.DomainCombiner * * @since 1.6 */ public static <T> T doPrivilegedWithCombiner(PrivilegedAction<T> action) { DomainCombiner dc = null; AccessControlContext acc = getStackAccessControlContext(); if (acc == null || (dc = acc.getAssignedCombiner()) == null) { return AccessController.doPrivileged(action); } return AccessController.doPrivileged(action, preserveCombiner(dc)); } /** * Performs the specified <code>PrivilegedAction</code> with privileges * enabled and restricted by the specified * <code>AccessControlContext</code>. * The action is performed with the intersection of the permissions * possessed by the caller's protection domain, and those possessed * by the domains represented by the specified * <code>AccessControlContext</code>. * <p> * If the action's <code>run</code> method throws an (unchecked) exception, * it will propagate through this method. * * @param action the action to be performed. * @param context an <i>access control context</i> * representing the restriction to be applied to the * caller's domain's privileges before performing * the specified action. If the context is * <code>null</code>, * then no additional restriction is applied. * * @return the value returned by the action's <code>run</code> method. * * @exception NullPointerException if the action is <code>null</code> * * @see #doPrivileged(PrivilegedAction) * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext) */ @ikvm.internal.HasCallerID public static <T> T doPrivileged(PrivilegedAction<T> action, AccessControlContext context) { return (T)doPrivileged(action, context, CallerID.getCallerID()); } /** * Performs the specified <code>PrivilegedExceptionAction</code> with * privileges enabled. The action is performed with <i>all</i> of the * permissions possessed by the caller's protection domain. * * <p> If the action's <code>run</code> method throws an <i>unchecked</i> * exception, it will propagate through this method. * * <p> Note that any DomainCombiner associated with the current * AccessControlContext will be ignored while the action is performed. * * @param action the action to be performed * * @return the value returned by the action's <code>run</code> method * * @exception PrivilegedActionException if the specified action's * <code>run</code> method threw a <i>checked</i> exception * @exception NullPointerException if the action is <code>null</code> * * @see #doPrivileged(PrivilegedAction) * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext) * @see #doPrivilegedWithCombiner(PrivilegedExceptionAction) * @see java.security.DomainCombiner */ @ikvm.internal.HasCallerID public static <T> T doPrivileged(PrivilegedExceptionAction<T> action) throws PrivilegedActionException { return (T)doPrivileged(action, null, CallerID.getCallerID()); } /** * Performs the specified <code>PrivilegedExceptionAction</code> with * privileges enabled. The action is performed with <i>all</i> of the * permissions possessed by the caller's protection domain. * * <p> If the action's <code>run</code> method throws an <i>unchecked</i> * exception, it will propagate through this method. * * <p> This method preserves the current AccessControlContext's * DomainCombiner (which may be null) while the action is performed. * * @param action the action to be performed. * * @return the value returned by the action's <code>run</code> method * * @exception PrivilegedActionException if the specified action's * <code>run</code> method threw a <i>checked</i> exception * @exception NullPointerException if the action is <code>null</code> * * @see #doPrivileged(PrivilegedAction) * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext) * @see java.security.DomainCombiner * * @since 1.6 */ public static <T> T doPrivilegedWithCombiner (PrivilegedExceptionAction<T> action) throws PrivilegedActionException { DomainCombiner dc = null; AccessControlContext acc = getStackAccessControlContext(); if (acc == null || (dc = acc.getAssignedCombiner()) == null) { return AccessController.doPrivileged(action); } return AccessController.doPrivileged(action, preserveCombiner(dc)); } /** * preserve the combiner across the doPrivileged call */ private static AccessControlContext preserveCombiner (DomainCombiner combiner) { /** * callerClass[0] = Reflection.getCallerClass * callerClass[1] = AccessController.preserveCombiner * callerClass[2] = AccessController.doPrivileged * callerClass[3] = caller */ final Class callerClass = sun.reflect.Reflection.getCallerClass(3); ProtectionDomain callerPd = doPrivileged (new PrivilegedAction<ProtectionDomain>() { public ProtectionDomain run() { return callerClass.getProtectionDomain(); } }); // perform 'combine' on the caller of doPrivileged, // even if the caller is from the bootclasspath ProtectionDomain[] pds = new ProtectionDomain[] {callerPd}; return new AccessControlContext(combiner.combine(pds, null), combiner); } /** * Performs the specified <code>PrivilegedExceptionAction</code> with * privileges enabled and restricted by the specified * <code>AccessControlContext</code>. The action is performed with the * intersection of the the permissions possessed by the caller's * protection domain, and those possessed by the domains represented by the * specified <code>AccessControlContext</code>. * <p> * If the action's <code>run</code> method throws an <i>unchecked</i> * exception, it will propagate through this method. * * @param action the action to be performed * @param context an <i>access control context</i> * representing the restriction to be applied to the * caller's domain's privileges before performing * the specified action. If the context is * <code>null</code>, * then no additional restriction is applied. * * @return the value returned by the action's <code>run</code> method * * @exception PrivilegedActionException if the specified action's * <code>run</code> method * threw a <i>checked</i> exception * @exception NullPointerException if the action is <code>null</code> * * @see #doPrivileged(PrivilegedAction) * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext) */ @ikvm.internal.HasCallerID public static <T> T doPrivileged(PrivilegedExceptionAction<T> action, AccessControlContext context) throws PrivilegedActionException { return (T)doPrivileged(action, context, CallerID.getCallerID()); } /** * Returns the AccessControl context. i.e., it gets * the protection domains of all the callers on the stack, * starting at the first class with a non-null * ProtectionDomain. * * @return the access control context based on the current stack or * null if there was only privileged system code. */ private static AccessControlContext getStackAccessControlContext() { AccessControlContext context = null; CallerID callerID = null; PrivilegedElement pi = privileged_stack_top; if (pi != null) { context = pi.context; callerID = pi.callerID; } return getStackAccessControlContext(context, callerID); } private static native AccessControlContext getStackAccessControlContext(AccessControlContext context, CallerID callerID); /** * Returns the "inherited" AccessControl context. This is the context * that existed when the thread was created. Package private so * AccessControlContext can use it. */ static native AccessControlContext getInheritedAccessControlContext(); /** * This method takes a "snapshot" of the current calling context, which * includes the current Thread's inherited AccessControlContext, * and places it in an AccessControlContext object. This context may then * be checked at a later point, possibly in another thread. * * @see AccessControlContext * * @return the AccessControlContext based on the current context. */ public static AccessControlContext getContext() { AccessControlContext acc = getStackAccessControlContext(); if (acc == null) { // all we had was privileged system code. We don't want // to return null though, so we construct a real ACC. return new AccessControlContext(null, true); } else { return acc.optimize(); } } /** * Determines whether the access request indicated by the * specified permission should be allowed or denied, based on * the current AccessControlContext and security policy. * This method quietly returns if the access request * is permitted, or throws a suitable AccessControlException otherwise. * * @param perm the requested permission. * * @exception AccessControlException if the specified permission * is not permitted, based on the current security policy. * @exception NullPointerException if the specified permission * is <code>null</code> and is checked based on the * security policy currently in effect. */ public static void checkPermission(Permission perm) throws AccessControlException { //System.err.println("checkPermission "+perm); //Thread.currentThread().dumpStack(); if (perm == null) { throw new NullPointerException("permission can't be null"); } AccessControlContext stack = getStackAccessControlContext(); // if context is null, we had privileged system code on the stack. if (stack == null) { Debug debug = AccessControlContext.getDebug(); boolean dumpDebug = false; if (debug != null) { dumpDebug = !Debug.isOn("codebase="); dumpDebug &= !Debug.isOn("permission=") || Debug.isOn("permission=" + perm.getClass().getCanonicalName()); } if (dumpDebug && Debug.isOn("stack")) { Thread.currentThread().dumpStack(); } if (dumpDebug && Debug.isOn("domain")) { debug.println("domain (context is null)"); } if (dumpDebug) { debug.println("access allowed "+perm); } return; } AccessControlContext acc = stack.optimize(); acc.checkPermission(perm); } }
gpl-2.0
cprasmu/RasCam-Server
src/cprasmu/rascam/camera/model/MeteringMode.java
1840
/* * copyright (C) 2013 Christian P Rasmussen * * 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 cprasmu.rascam.camera.model; public enum MeteringMode { AVERAGE (0,"average","Average"), SPOT (1,"spot","Spot"), BACKLIT (2,"backlit","Backlit"), MATRIX (3,"matrix","Matrix"); public int mode; public String name; public String displayName; private MeteringMode(int mode, String name,String displayName) { this.mode = mode; this.name = name; this.displayName=displayName; } public static MeteringMode fromInt(int code) { switch(code) { case 0: return AVERAGE; case 1: return SPOT; case 2: return BACKLIT; case 3: return MATRIX; } return null; } public MeteringMode next(){ if(this.equals(AVERAGE)){ return SPOT; } else if(this.equals(SPOT)){ return BACKLIT; } else if(this.equals(BACKLIT)){ return MATRIX; } else if(this.equals(MATRIX)){ return AVERAGE; } else { return null; } } public MeteringMode previous(){ if(this.equals(MATRIX)){ return BACKLIT; } else if(this.equals(BACKLIT)){ return SPOT; } else if(this.equals(SPOT)){ return AVERAGE; } else if(this.equals(AVERAGE)){ return MATRIX; } else { return null; } } }
gpl-2.0
ganncamp/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest02153.java
3459
/** * OWASP Benchmark Project v1.2beta * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest02153") public class BenchmarkTest02153 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String param = request.getParameter("vector"); if (param == null) param = ""; String bar = doSomething(param); String cmd = org.owasp.benchmark.helpers.Utils.getInsecureOSCommandString(this.getClass().getClassLoader()); String[] args = {cmd}; String[] argsEnv = { bar }; Runtime r = Runtime.getRuntime(); try { Process p = r.exec(args, argsEnv, new java.io.File(System.getProperty("user.dir"))); org.owasp.benchmark.helpers.Utils.printOSCommandResults(p, response); } catch (IOException e) { System.out.println("Problem executing cmdi - TestCase"); throw new ServletException(e); } } // end doPost private static String doSomething(String param) throws ServletException, IOException { // Chain a bunch of propagators in sequence String a56534 = param; //assign StringBuilder b56534 = new StringBuilder(a56534); // stick in stringbuilder b56534.append(" SafeStuff"); // append some safe content b56534.replace(b56534.length()-"Chars".length(),b56534.length(),"Chars"); //replace some of the end content java.util.HashMap<String,Object> map56534 = new java.util.HashMap<String,Object>(); map56534.put("key56534", b56534.toString()); // put in a collection String c56534 = (String)map56534.get("key56534"); // get it back out String d56534 = c56534.substring(0,c56534.length()-1); // extract most of it String e56534 = new String( new sun.misc.BASE64Decoder().decodeBuffer( new sun.misc.BASE64Encoder().encode( d56534.getBytes() ) )); // B64 encode and decode it String f56534 = e56534.split(" ")[0]; // split it on a space org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing(); String g56534 = "barbarians_at_the_gate"; // This is static so this whole flow is 'safe' String bar = thing.doSomething(g56534); // reflection return bar; } }
gpl-2.0
iucn-whp/world-heritage-outlook
portlets/iucn-dbservice-portlet/docroot/WEB-INF/service/com/iucn/whp/dbservice/service/assessment_statusLocalServiceClp.java
20922
/** * Copyright (c) 2000-2012 Liferay, Inc. 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. */ package com.iucn.whp.dbservice.service; import com.liferay.portal.service.InvokableLocalService; /** * @author alok.sen */ public class assessment_statusLocalServiceClp implements assessment_statusLocalService { public assessment_statusLocalServiceClp( InvokableLocalService invokableLocalService) { _invokableLocalService = invokableLocalService; _methodName0 = "addassessment_status"; _methodParameterTypes0 = new String[] { "com.iucn.whp.dbservice.model.assessment_status" }; _methodName1 = "createassessment_status"; _methodParameterTypes1 = new String[] { "long" }; _methodName2 = "deleteassessment_status"; _methodParameterTypes2 = new String[] { "long" }; _methodName3 = "deleteassessment_status"; _methodParameterTypes3 = new String[] { "com.iucn.whp.dbservice.model.assessment_status" }; _methodName4 = "dynamicQuery"; _methodParameterTypes4 = new String[] { }; _methodName5 = "dynamicQuery"; _methodParameterTypes5 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery" }; _methodName6 = "dynamicQuery"; _methodParameterTypes6 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int" }; _methodName7 = "dynamicQuery"; _methodParameterTypes7 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int", "com.liferay.portal.kernel.util.OrderByComparator" }; _methodName8 = "dynamicQueryCount"; _methodParameterTypes8 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery" }; _methodName9 = "fetchassessment_status"; _methodParameterTypes9 = new String[] { "long" }; _methodName10 = "getassessment_status"; _methodParameterTypes10 = new String[] { "long" }; _methodName11 = "getPersistedModel"; _methodParameterTypes11 = new String[] { "java.io.Serializable" }; _methodName12 = "getassessment_statuses"; _methodParameterTypes12 = new String[] { "int", "int" }; _methodName13 = "getassessment_statusesCount"; _methodParameterTypes13 = new String[] { }; _methodName14 = "updateassessment_status"; _methodParameterTypes14 = new String[] { "com.iucn.whp.dbservice.model.assessment_status" }; _methodName15 = "updateassessment_status"; _methodParameterTypes15 = new String[] { "com.iucn.whp.dbservice.model.assessment_status", "boolean" }; _methodName16 = "getBeanIdentifier"; _methodParameterTypes16 = new String[] { }; _methodName17 = "setBeanIdentifier"; _methodParameterTypes17 = new String[] { "java.lang.String" }; _methodName19 = "findAll"; _methodParameterTypes19 = new String[] { }; } public com.iucn.whp.dbservice.model.assessment_status addassessment_status( com.iucn.whp.dbservice.model.assessment_status assessment_status) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName0, _methodParameterTypes0, new Object[] { ClpSerializer.translateInput( assessment_status) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.iucn.whp.dbservice.model.assessment_status createassessment_status( long statusid) { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName1, _methodParameterTypes1, new Object[] { statusid }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.iucn.whp.dbservice.model.assessment_status deleteassessment_status( long statusid) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName2, _methodParameterTypes2, new Object[] { statusid }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.PortalException) { throw (com.liferay.portal.kernel.exception.PortalException)t; } if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.iucn.whp.dbservice.model.assessment_status deleteassessment_status( com.iucn.whp.dbservice.model.assessment_status assessment_status) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName3, _methodParameterTypes3, new Object[] { ClpSerializer.translateInput( assessment_status) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery() { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName4, _methodParameterTypes4, new Object[] { }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.liferay.portal.kernel.dao.orm.DynamicQuery)ClpSerializer.translateOutput(returnObj); } @SuppressWarnings("rawtypes") public java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName5, _methodParameterTypes5, new Object[] { ClpSerializer.translateInput(dynamicQuery) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List)ClpSerializer.translateOutput(returnObj); } @SuppressWarnings("rawtypes") public java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start, int end) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName6, _methodParameterTypes6, new Object[] { ClpSerializer.translateInput(dynamicQuery), start, end }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List)ClpSerializer.translateOutput(returnObj); } @SuppressWarnings("rawtypes") public java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start, int end, com.liferay.portal.kernel.util.OrderByComparator orderByComparator) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName7, _methodParameterTypes7, new Object[] { ClpSerializer.translateInput(dynamicQuery), start, end, ClpSerializer.translateInput(orderByComparator) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List)ClpSerializer.translateOutput(returnObj); } public long dynamicQueryCount( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName8, _methodParameterTypes8, new Object[] { ClpSerializer.translateInput(dynamicQuery) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return ((Long)returnObj).longValue(); } public com.iucn.whp.dbservice.model.assessment_status fetchassessment_status( long statusid) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName9, _methodParameterTypes9, new Object[] { statusid }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.iucn.whp.dbservice.model.assessment_status getassessment_status( long statusid) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName10, _methodParameterTypes10, new Object[] { statusid }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.PortalException) { throw (com.liferay.portal.kernel.exception.PortalException)t; } if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.liferay.portal.model.PersistedModel getPersistedModel( java.io.Serializable primaryKeyObj) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName11, _methodParameterTypes11, new Object[] { ClpSerializer.translateInput(primaryKeyObj) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.PortalException) { throw (com.liferay.portal.kernel.exception.PortalException)t; } if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.liferay.portal.model.PersistedModel)ClpSerializer.translateOutput(returnObj); } public java.util.List<com.iucn.whp.dbservice.model.assessment_status> getassessment_statuses( int start, int end) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName12, _methodParameterTypes12, new Object[] { start, end }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List<com.iucn.whp.dbservice.model.assessment_status>)ClpSerializer.translateOutput(returnObj); } public int getassessment_statusesCount() throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName13, _methodParameterTypes13, new Object[] { }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return ((Integer)returnObj).intValue(); } public com.iucn.whp.dbservice.model.assessment_status updateassessment_status( com.iucn.whp.dbservice.model.assessment_status assessment_status) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName14, _methodParameterTypes14, new Object[] { ClpSerializer.translateInput( assessment_status) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public com.iucn.whp.dbservice.model.assessment_status updateassessment_status( com.iucn.whp.dbservice.model.assessment_status assessment_status, boolean merge) throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName15, _methodParameterTypes15, new Object[] { ClpSerializer.translateInput(assessment_status), merge }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (com.iucn.whp.dbservice.model.assessment_status)ClpSerializer.translateOutput(returnObj); } public java.lang.String getBeanIdentifier() { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName16, _methodParameterTypes16, new Object[] { }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.lang.String)ClpSerializer.translateOutput(returnObj); } public void setBeanIdentifier(java.lang.String beanIdentifier) { try { _invokableLocalService.invokeMethod(_methodName17, _methodParameterTypes17, new Object[] { ClpSerializer.translateInput(beanIdentifier) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } } public java.lang.Object invokeMethod(java.lang.String name, java.lang.String[] parameterTypes, java.lang.Object[] arguments) throws java.lang.Throwable { throw new UnsupportedOperationException(); } public java.util.List<com.iucn.whp.dbservice.model.assessment_status> findAll() throws com.liferay.portal.kernel.exception.SystemException { Object returnObj = null; try { returnObj = _invokableLocalService.invokeMethod(_methodName19, _methodParameterTypes19, new Object[] { }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof com.liferay.portal.kernel.exception.SystemException) { throw (com.liferay.portal.kernel.exception.SystemException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.util.List<com.iucn.whp.dbservice.model.assessment_status>)ClpSerializer.translateOutput(returnObj); } private InvokableLocalService _invokableLocalService; private String _methodName0; private String[] _methodParameterTypes0; private String _methodName1; private String[] _methodParameterTypes1; private String _methodName2; private String[] _methodParameterTypes2; private String _methodName3; private String[] _methodParameterTypes3; private String _methodName4; private String[] _methodParameterTypes4; private String _methodName5; private String[] _methodParameterTypes5; private String _methodName6; private String[] _methodParameterTypes6; private String _methodName7; private String[] _methodParameterTypes7; private String _methodName8; private String[] _methodParameterTypes8; private String _methodName9; private String[] _methodParameterTypes9; private String _methodName10; private String[] _methodParameterTypes10; private String _methodName11; private String[] _methodParameterTypes11; private String _methodName12; private String[] _methodParameterTypes12; private String _methodName13; private String[] _methodParameterTypes13; private String _methodName14; private String[] _methodParameterTypes14; private String _methodName15; private String[] _methodParameterTypes15; private String _methodName16; private String[] _methodParameterTypes16; private String _methodName17; private String[] _methodParameterTypes17; private String _methodName19; private String[] _methodParameterTypes19; }
gpl-2.0
gforghetti/jenkins-tomcat-wildbook
src/main/java/org/ecocean/servlet/export/IndividualSearchExportCapture.java
5158
package org.ecocean.servlet.export; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import org.ecocean.*; import org.ecocean.servlet.ServletUtilities; import java.lang.StringBuffer; //adds spots to a new encounter public class IndividualSearchExportCapture extends HttpServlet{ public void init(ServletConfig config) throws ServletException { super.init(config); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ //set the response response.setContentType("text/html"); PrintWriter out = response.getWriter(); String context="context0"; context=ServletUtilities.getContext(request); Shepherd myShepherd = new Shepherd(context); Vector<MarkedIndividual> rIndividuals = new Vector<MarkedIndividual>(); myShepherd.beginDBTransaction(); String order = ""; String locCode=request.getParameter("locationCodeField"); MarkedIndividualQueryResult result = IndividualQueryProcessor.processQuery(myShepherd, request, order); rIndividuals = result.getResult(); int numIndividuals=rIndividuals.size(); int numSharks=0; out.println("<pre>"); out.println("title='Example CAPTURE Export of Marked Individuals from the "+CommonConfiguration.getHTMLTitle(context)+"'"); try { int startYear=(new Integer(request.getParameter("year1"))).intValue(); int startMonth=(new Integer(request.getParameter("month1"))).intValue(); int endMonth=(new Integer(request.getParameter("month2"))).intValue(); int endYear=(new Integer(request.getParameter("year2"))).intValue(); //check for seasons wrapping over years int wrapsYear=0; if(startMonth>endMonth) {wrapsYear=1;} int numYearsCovered=endYear-startYear-wrapsYear+1; out.println("task read captures x matrix occasions="+numYearsCovered); //now, let's print out our capture histories //out.println("<br><br>Capture histories for live recaptures modeling: "+startYear+"-"+endYear+", months "+startMonth+"-"+endMonth+"<br><br><pre>"); int maxLengthID=0; for(int p=0;p<numIndividuals;p++) { MarkedIndividual s=rIndividuals.get(p); if(s.getIndividualID().length()>maxLengthID){maxLengthID=s.getIndividualID().length();} } out.println("format='(a"+maxLengthID+","+numYearsCovered+"f1.0)'"); out.println("read input data"); for(int i=0;i<numIndividuals;i++) { MarkedIndividual s=rIndividuals.get(i); boolean wasSightedInRequestedLocation=false; if((request.getParameter("locationCodeField")!=null)&&(!request.getParameter("locationCodeField").trim().equals(""))){ wasSightedInRequestedLocation=s.wasSightedInLocationCode(locCode); } else{ wasSightedInRequestedLocation=true; } if((wasSightedInRequestedLocation)&&(s.wasSightedInPeriod(startYear,startMonth,endYear,endMonth))) { boolean wasReleased=false; StringBuffer sb=new StringBuffer(); //lets print out each shark's capture history for(int f=startYear;f<=(endYear-wrapsYear);f++) { boolean sharkWasSeen=false; if((request.getParameter("locationCodeField")!=null)&&(!request.getParameter("locationCodeField").trim().equals(""))){ sharkWasSeen=s.wasSightedInPeriod(f,startMonth,1,(f+wrapsYear),endMonth, 31, locCode); } else{ sharkWasSeen=s.wasSightedInPeriod(f,startMonth,1,(f+wrapsYear),endMonth, 31); } if(sharkWasSeen){ sb.append("1"); wasReleased=true; } else{ sb.append("0"); } } if(wasReleased) { String adjustedID=s.getIndividualID(); while(adjustedID.length()<maxLengthID){adjustedID+="X";} out.println(adjustedID+sb.toString()); numSharks++; } } //end if } //end while myShepherd.rollbackDBTransaction(); myShepherd.closeDBTransaction(); } catch(Exception e) { out.println("<p><strong>Error encountered</strong></p>"); out.println("<p>Please let the webmaster know you encountered an error at: IndividualSearchExportCapture servlet</p>"); e.printStackTrace(); myShepherd.rollbackDBTransaction(); myShepherd.closeDBTransaction(); } out.println("task closure test<br/>task model selection"); //out.println("task population estimate ALL"); //out.println("task population estimate NULL JACKKNIFE REMOVAL ZIPPEN MT-CH MH-CH MTH-CH"); out.println("task population estimate ALL"); out.close(); } }
gpl-2.0
sidney9111/Weixin_android
src/com/peiban/app/ui/DetailActivity.java
24070
package com.peiban.app.ui; import java.util.List; import java.util.Map; import net.tsz.afinal.http.AjaxCallBack; import android.content.Intent; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.peiban.R; import com.peiban.app.Constants; import com.peiban.app.api.AlbumApi; import com.peiban.app.api.ErrorCode; import com.peiban.app.api.FriendApi; import com.peiban.app.api.UserInfoApi; import com.peiban.app.control.AlbumControl; import com.peiban.app.control.DialogMark; import com.peiban.app.ui.common.ChatPrompt; import com.peiban.app.ui.common.ChatPrompt.ChatPromptLisenter; import com.peiban.app.ui.common.FinalOnloadBitmap; import com.peiban.command.TextdescTool; import com.peiban.vo.AlbumVo; import com.peiban.vo.CustomerVo; /** * * 功能: 详细资料 <br /> * 日期:2013-5-28<br /> * 地点:淘高手网<br /> * 版本:ver 1.0<br /> * * @author fighter * @since */ public abstract class DetailActivity extends BaseActivity { private static final String TAG = DetailActivity.class.getCanonicalName(); private static final String FRIEND = "好友可见"; private static final String VIP_TAG = "VIP/认证可见"; /** 头像 */ private ImageView imgHead; /** 角标 */ private ImageView imgSubscript; /** 认证提示 */ private TextView txtAuth; /** 认证与 成为 VIP 按钮 */ private Button btnAuth; private Button btnVip; /** 用户名 */ private TextView txtUserName; /** 性别 */ private ImageView imgSex; /** 年龄 */ private TextView txtAge; /** 在线状态 */ private TextView txtLineState; /** 签名 */ private TextView txtSign; /** 相册 */ private LinearLayout layoutAlbum; private TextView textAlbum; /** * 项目列表 */ private LinearLayout layoutProject; /** QQ */ private TextView txtQq; /** 身高 */ private TextView txtHeight; /** 体重 */ private TextView txtBody; /** 职业 */ private TextView txtProfession; /** 手机号码 */ private TextView txtPhone; /** 薪资意愿 */ private TextView txtWages; /** 兴趣爱好 */ private TextView txtHobby; private Button btnSayHello; private Button btnAddFriend; private Button btnApply1; private Button btnApply2; private LinearLayout mDetailsInfo; private LinearLayout mDetailsInfoHide; private LinearLayout mApply; private CustomerVo customer; private UserInfoApi userInfoApi; private FriendApi friendApi; private DialogMark dialogMark; @Override protected void initTitle() { setBtnBack(); setTitleContent(R.string.details_title); } @Override protected void baseInit() { super.baseInit(); customer = (CustomerVo) getIntent().getSerializableExtra("data"); if (customer == null) { Toast.makeText(getBaseContext(), "操作错误.", Toast.LENGTH_SHORT) .show(); finish(); return; } dialogMark = new DialogMark(DetailActivity.this, customer) { @Override protected void markName(String markName) { DetailActivity.this.markName(markName); } }; userInfoApi = new UserInfoApi(); friendApi = new FriendApi(); mDetailsInfo = (LinearLayout) this.findViewById(R.id.details_info); mApply = (LinearLayout) this.findViewById(R.id.details_apply); this.imgHead = (ImageView) this .findViewById(R.id.details_head_img_head); this.imgSex = (ImageView) this.findViewById(R.id.details_head_img_sex); this.imgSubscript = (ImageView) this .findViewById(R.id.details_head_img_subscript); this.txtUserName = (TextView) this .findViewById(R.id.details_head_txt_username); this.txtAge = (TextView) this.findViewById(R.id.details_head_txt_age); this.txtLineState = (TextView) this .findViewById(R.id.details_head_txt_line_state); this.txtAuth = (TextView) this .findViewById(R.id.details_head_txt_auth_state); this.textAlbum = (TextView) this.findViewById(R.id.details_layout_albums_tag); this.btnAuth = (Button) this.findViewById(R.id.details_head_btn_auth); this.btnVip = (Button) this.findViewById(R.id.details_head_btn_vip); this.txtSign = (TextView) this.findViewById(R.id.detail_info_signature); this.txtHeight = (TextView) this.findViewById(R.id.detail_info_tall); this.txtBody = (TextView) this.findViewById(R.id.detail_info_weight); this.txtProfession = (TextView) this.findViewById(R.id.detail_info_job); this.txtPhone = (TextView) this .findViewById(R.id.detail_info_mobilephone); this.txtQq = (TextView) this.findViewById(R.id.detail_info_qq); this.txtWages = (TextView) this.findViewById(R.id.detail_info_salary); this.txtHobby = (TextView) this.findViewById(R.id.detail_info_savor); this.layoutAlbum = (LinearLayout) this .findViewById(R.id.details_layout_albums); //this.layoutProject = (LinearLayout)this.findViewById(R.id.details_layout_projects); this.btnApply1 = (Button) this.findViewById(R.id.details_apply_btn1); this.btnApply2 = (Button) this.findViewById(R.id.details_apply_btn2); this.btnAddFriend = (Button) this .findViewById(R.id.details_btn_add_friend); this.btnSayHello = (Button) this .findViewById(R.id.details_btn_say_hello); this.mDetailsInfoHide = (LinearLayout) this .findViewById(R.id.details_info_hide); addLitener(); showHeadInfo(); getScore(); getApplyAuth(); } private void addLitener() { View.OnClickListener l = new DetailOnClick(); getBtnAddFriend().setOnClickListener(l); getBtnSayHello().setOnClickListener(l); getBtnApply1().setOnClickListener(l); getBtnApply2().setOnClickListener(l); getImgHead().setOnClickListener(l); } /** * 更新我的信息 * * @author fighter <br /> * 创建时间:2013-6-19<br /> * 修改时间:<br /> */ protected void updateHeadInfo() { CustomerVo tempVo = getMyCustomerVo(); if(tempVo != null){ customer = tempVo; } showHeadInfo(); showInfo(); } protected void showHeadInfo() { if ("1".equals(customer.getSex())) { this.imgSex.setImageResource(R.drawable.sex_man); } else { this.imgSex.setImageResource(R.drawable.sex_woman); } if(Constants.CustomerType.CHATTING.equals(customer.getCustomertype())){ if("1".equals(customer.getAgent())){ imgSubscript.setImageResource(R.drawable.subscript_economic); imgSubscript.setVisibility(View.VISIBLE); }else if("1".equals(customer.getHeadattest())){ imgSubscript.setVisibility(View.VISIBLE); imgSubscript.setBackgroundResource(R.drawable.subscript_auth); }else{ imgSubscript.setVisibility(View.GONE); } }else{ if("1".equals(customer.getVip())){ imgSubscript.setVisibility(View.VISIBLE); imgSubscript.setBackgroundResource(R.drawable.subscript_vip); }else{ imgSubscript.setVisibility(View.GONE); } } FinalOnloadBitmap.finalDisplay(getBaseContext(), customer, imgHead, getHeadBitmap()); this.txtWages.setText(customer.getSalary()); String name = TextdescTool.getCustomerName(customer); this.txtUserName.setText(name); this.txtAge.setText(TextdescTool.dateToAge(customer.getBirthday()) + "岁"); showInfo(); } /** * 展现信息 * * 作者:fighter <br /> * 创建时间:2013-5-28<br /> * 修改时间:<br /> */ public void showInfo() { mDetailsInfo.setVisibility(View.VISIBLE); mDetailsInfoHide.setVisibility(View.GONE); this.txtSign.setText(customer.getSign()); this.txtQq.setText(customer.getQq()); this.txtBody.setText(customer.getWeight()); this.txtHeight.setText(customer.getHeight()); this.txtPhone.setText(customer.getPhone()); this.txtProfession.setText(customer.getProfession()); this.txtHobby.setText(customer.getInterest()); } public void hideInfo() { // mDetailsInfo.setVisibility(View.GONE); // mDetailsInfoHide.setVisibility(View.VISIBLE); } public void hideApply() { mApply.setVisibility(View.GONE); } public void showApply() { mApply.setVisibility(View.VISIBLE); } protected void markName(final String markName) { if (!checkNetWork()) { return; } friendApi.markFriend(getUserInfoVo().getUid(), customer.getUid(), markName, new AjaxCallBack<String>() { @Override public void onStart() { super.onStart(); getWaitDialog().setMessage("修改中..."); getWaitDialog().show(); } @Override public void onSuccess(String t) { super.onSuccess(t); getWaitDialog().cancel(); String data = ErrorCode.getData(getBaseContext(), t); if (data != null) { if ("1".equals(data)) { markNameSuccess(markName); } } } @Override public void onFailure(Throwable t, String strMsg) { super.onFailure(t, strMsg); getWaitDialog().cancel(); showToast(strMsg); } }); } protected void markNameSuccess(String markName) { getPromptDialog().addCannel(); getPromptDialog().removeConfirm(); getPromptDialog().setCannelText("确定"); getPromptDialog().setMessage("修改成功!"); getPromptDialog().show(); customer.setMarkName(markName); showHeadInfo(); } protected void getNetworkAlum(){ } /** * 从服务器获取相册信息 * */ protected void getNetworkAlbum() { // TODO 从服务器获取相册信息 if (!checkNetWork()) { showToast(getResources().getString(R.string.toast_network)); }else { AlbumApi albumApi = new AlbumApi(); String uid = getUserInfoVo().getUid(); albumApi.getAlbum(uid, getCustomer().getUid(), new AjaxCallBack<String>() { @Override public void onStart() { // TODO 准备从服务器获取 super.onStart(); } @Override public void onSuccess(String t) { // TODO 服务器获取成功 super.onSuccess(t); String data = ErrorCode.getData(t); if (!"".equals(data)) { showAlbum(data); } else { getLayoutAlbum().setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(getUserInfoVo().getUid().equals(getCustomer().getUid())){ Intent intent=new Intent(DetailActivity.this,AlbumActivity.class); startActivity(intent); }else{ Intent intent=new Intent(DetailActivity.this,FriendAlbumActivity.class); intent.putExtra("touid", getCustomer().getUid()); startActivity(intent); } } }); getWaitDialog().dismiss(); } } @Override public void onFailure(Throwable t, String strMsg) { // TODO 服务器获取失败 super.onFailure(t, strMsg); } }); } } /** * 显示相册信息 * * */ private void showAlbum(String data) { if(DEBUG){ Log.e("相册:", data); } if(FRIEND.equals(data)){ textAlbum.setVisibility(View.VISIBLE); textAlbum.setText(FRIEND); layoutAlbum.setVisibility(View.GONE); }else if(VIP_TAG.equals(data)){ textAlbum.setVisibility(View.VISIBLE); textAlbum.setText(VIP_TAG); layoutAlbum.setVisibility(View.GONE); }else{ textAlbum.setVisibility(View.GONE); layoutAlbum.setVisibility(View.VISIBLE); try { List<AlbumVo> albumList=null; albumList=JSONArray.parseArray(data, AlbumVo.class); AlbumControl albumControl=new AlbumControl(DetailActivity.this,getLayoutAlbum(),albumList); albumControl.showAlbum(getUserInfoVo().getUid(),getCustomer().getUid()); } catch (Exception e) { // TODO: handle exception } } } /** * 获取积分 * * 作者:fighter <br /> * 创建时间:2013-5-28<br /> * 修改时间:<br /> */ protected void getScore() { getUserInfoApi().getScore(getUserInfoVo().getUid(), getCustomer().getUid(), new AjaxCallBack<String>() { @Override public void onSuccess(String t) { super.onSuccess(t); int errorCode = ErrorCode.getError(t); if (errorCode == 0) { Map<String, String> data = (Map<String, String>) JSON .parse(ErrorCode.getData(t)); scoreUploadSuccess(data); } else { scoreUploadError(); } } @Override public void onFailure(Throwable t, String strMsg) { super.onFailure(t, strMsg); scoreUploadError(); } }); } /** * 获取评分成功. * * @param data * ascore 外表评分 sscore 服务评分 usercp 等级 作者:fighter <br /> * 创建时间:2013-5-28<br /> * 修改时间:<br /> */ protected abstract void scoreUploadSuccess(Map<String, String> data); /** * 评分获取失败 * * 作者:fighter <br /> * 创建时间:2013-5-28<br /> * 修改时间:<br /> */ protected abstract void scoreUploadError(); /** * @return the 头像 */ public ImageView getImgHead() { return imgHead; } /** * @return the 用户名 */ public TextView getTxtUserName() { return txtUserName; } /** * @return the 性别 */ public ImageView getImgSex() { return imgSex; } /** * @return the 年龄 */ public TextView getTxtAge() { return txtAge; } /** * @return the 在线状态 */ public TextView getTxtLineState() { return txtLineState; } /** * @return the 个性签名 */ public TextView getTxtSign() { return txtSign; } /** * @return the 相册 */ public LinearLayout getLayoutAlbum() { return layoutAlbum; } /** * @return the qq */ public TextView getTxtQq() { return txtQq; } /** * @return the 身高 */ public TextView getTxtHeight() { return txtHeight; } /** * @return the 体重 */ public TextView getTxtBody() { return txtBody; } /** * @return the 职业 */ public TextView getTxtProfession() { return txtProfession; } /** * @return the 手机号 */ public TextView getTxtPhone() { return txtPhone; } /** * @return the 资金意愿 */ public TextView getTxtWages() { return txtWages; } /** * @return the 兴趣 */ public TextView getTxtHobby() { return txtHobby; } /** * @return the 角标 */ public ImageView getImgSubscript() { return imgSubscript; } public DialogMark getDialogMark() { return dialogMark; } /** * @return the 认证按钮 */ public Button getBtnAuth() { return btnAuth; } public Button getBtnVip() { return btnVip; } /** * @return the 认证提示 */ public TextView getTxtAuth() { return txtAuth; } /** * @return 打招呼按钮 */ public Button getBtnSayHello() { return btnSayHello; } /** * @return 添加好友按钮 */ public Button getBtnAddFriend() { return btnAddFriend; } /** * @return the customer */ public CustomerVo getCustomer() { return customer; } /** * @return the btnApply1 */ public Button getBtnApply1() { return btnApply1; } /** * @return the btnApply2 */ public Button getBtnApply2() { return btnApply2; } /** * @return the 用户信息接口 */ public UserInfoApi getUserInfoApi() { return userInfoApi; } /** * 获取是否能查看好友信息权限. * * 作者:fighter <br /> * 创建时间:2013-5-29<br /> * 修改时间:<br /> */ protected void applyAuth() { if (!checkNetWork()) return; } /*** * 获取是否有查看权限. * * 作者:fighter <br /> * 创建时间:2013-6-14<br /> * 修改时间:<br /> */ protected void getApplyAuth() { } /** * 申请查看 * * 作者:fighter <br /> * 创建时间:2013-5-29<br /> * 修改时间:<br /> */ protected void apply1Action() { if(!checkCustomerType()){ return; } getUserInfoApi().applyAuth(getUserInfoVo().getUid(), customer.getUid(), new ApplyAuthCallback()); } protected void apply2Action() { if (!checkNetWork()) { showToast(getResources().getString(R.string.toast_network)); return; } System.out.println("评价::;;"); if (Constants.CustomerType.CHATTING.equals(getCustomer() .getCustomertype())) { Intent intent = new Intent(DetailActivity.this, EvaluateActivity.class); intent.putExtra("data", getCustomer()); startActivity(intent); } else { evaluateSorce(); } } /** * 判断用户类型评分 * */ public void evaluateSorce() { if (Constants.CustomerType.CHATTING.equals(getCustomer() .getCustomertype())) { editSorce(getCustomer().getAscore(), getCustomer().getSscore()); } else { editSorce("0", "0"); } } /** * 评分 Param asorce:外貌评分,ssorce:服务评分 ps:外貌评分和服务评分都是0即上传魅力值 * */ public void editSorce(String asorce, String ssorce) { userInfoApi.editScore(getUserInfoVo().getUid(), getCustomer().getUid(), asorce, ssorce, new AjaxCallBack<String>() { @Override public void onStart() { // TODO Auto-generated method stub super.onStart(); getWaitDialog().setMessage("提交请求"); getWaitDialog().show(); } @Override public void onSuccess(String t) { // TODO Auto-generated method stub super.onSuccess(t); String data = ErrorCode.getData(getBaseContext(), t); if (data != null && "1".equals(data)) { getWaitDialog().setMessage("提交成功"); } else { getWaitDialog().setMessage("提交失败"); } getWaitDialog().cancel(); } @Override public void onFailure(Throwable t, String strMsg) { // TODO Auto-generated method stub super.onFailure(t, strMsg); getWaitDialog().setMessage("提交失败:" + strMsg); getWaitDialog().cancel(); } }); } protected void addFriendAction() { //20151119 暂时不验证用户 // if(!checkCustomerType()){ // return; // } if (!checkNetWork()) return; getFriendApi().toFriend(getUserInfoVo().getUid(), getCustomer().getUid(), new AddFriendCallback()); } protected void sayHelloAction() { //20151119 // if(!checkCustomerType()){ // return; // } // 1. 判断本地是否有该用户. CustomerVo tempCustomerVo = null; try { tempCustomerVo = getFinalDb().findById(getCustomer().getUid(), CustomerVo.class); } catch (Exception e) { } // 2. 没有就保存. if (tempCustomerVo == null) { try { getCustomer().setFriend("0"); getFinalDb().save(getCustomer()); } catch (Exception e) { } } // if(!ChatPrompt.isShow(getBaseContext())){ // ChatPrompt.showPrompt(this, new ChatPromptLisenter(this){ // // @Override // public void onClick(View v) { // super.onClick(v); // Intent intent = new Intent(DetailActivity.this, ChatMainActivity.class); // intent.putExtra("data", getCustomer()); // startActivity(intent); // } // // }); // }else{ Intent intent = new Intent(DetailActivity.this, ChatMainActivity.class); intent.putExtra("data", getCustomer()); startActivity(intent); // } } class DetailOnClick implements View.OnClickListener { @Override public void onClick(View v) { if (v == getBtnAddFriend()) { addFriendAction(); } else if (v == getBtnSayHello()) { sayHelloAction(); } else if (v == getBtnApply1()) { apply1Action(); } else if (v == getBtnApply2()) { apply2Action(); } else if (v.getId() == R.id.detail_layout_albums) { if (getUserInfoVo().getUid() != getCustomer().getUid()) { Intent intent = new Intent(DetailActivity.this, FriendAlbumActivity.class); intent.putExtra("fid", getCustomer().getUid()); startActivity(intent); } }else if(v == getImgHead()){ Intent intent = new Intent(DetailActivity.this, ShowHeadActivity.class); intent.putExtra("data", customer.getHead()); startActivity(intent); } } } /** * @return the friendApi */ public FriendApi getFriendApi() { return friendApi; } /*** * 效验用户是否给我授权权限查看用户信息 * * @author fighter <br /> * 创建时间:2013-6-20<br /> * 修改时间:<br /> */ protected void checkUserAuth(){ if("1".equals(customer.getFriend())){ return; } getUserInfoApi().checkAuth(getUserInfoVo().getUid(), customer.getUid(), new AjaxCallBack<String>() { @Override public void onSuccess(String t) { super.onSuccess(t); try { String data = ErrorCode.getData(t); if(data != null){ // 如果没有权限 显示申请查看信息. if(!"1".equals(data)){ getBtnApply1().setVisibility(View.VISIBLE); } } } catch (Exception e) { // TODO: handle exception } } }); } /** * 获取用户在服务器上的信息 * * @author fighter <br /> * 创建时间:2013-6-27<br /> * 修改时间:<br /> */ protected void getRefresh() { Log.d(TAG, "getRefresh()"); getUserInfoApi().getInfo(getMyCustomerVo().getUid(), customer.getUid(), new AjaxCallBack<String>() { @Override public void onSuccess(String t) { super.onSuccess(t); Log.v(TAG, t); try { String data = ErrorCode.getData(t); if(!TextUtils.isEmpty(data)){ CustomerVo customerVo = JSONObject.toJavaObject(JSONObject.parseObject(data), CustomerVo.class); customer = customerVo; showHeadInfo(); showInfo(); System.out.println("显示成功!"); } } catch (Exception e) { Log.e(TAG, "getRefresh()", e); } } }); } private boolean checkUserType(){ boolean flag = false; if("1".equals(customer.getFriend())){ flag = true; }else{ // 如果是陪聊用户 检查是否是认证 if(Constants.CustomerType.CHATTING.equals(getMyCustomerVo().getCustomertype())){ if("1".equals(getMyCustomerVo().getHeadattest())){ flag = true; }else{ flag = false; } } // 如果是寻伴用户 检查是否是VIP if(Constants.CustomerType.WITHCHAT.equals(getMyCustomerVo().getCustomertype())){ if("1".equals(getMyCustomerVo().getVip())){ flag = true; }else{ flag = false; } } } return flag; } private boolean checkCustomerType(){ boolean flag = false; if("1".equals(customer.getFriend())){ flag = true; }else{ // 如果是陪聊用户 检查是否是认证 if(Constants.CustomerType.CHATTING.equals(getMyCustomerVo().getCustomertype())){ if("1".equals(getMyCustomerVo().getHeadattest())){ flag = true; }else{ flag = false; gotoAuth(); } } // 如果是寻伴用户 检查是否是VIP if(Constants.CustomerType.WITHCHAT.equals(getMyCustomerVo().getCustomertype())){ if("1".equals(getMyCustomerVo().getVip())){ flag = true; }else{ flag = false; gotoVip(); } } } return flag; } /** * 我要认证 * * @author fighter <br /> * 创建时间:2013-6-20<br /> * 修改时间:<br /> */ private void gotoAuth(){ getPromptDialog().addCannel(); getPromptDialog().addConfirm(new View.OnClickListener() { @Override public void onClick(View v) { // 去认证头像. getPromptDialog().cancel(); Intent intent = new Intent(DetailActivity.this, HeadAuthActivity.class); startActivity(intent); } }); getPromptDialog().setMessage("成为VIP/认证用户!"); getPromptDialog().setCannelText("以后在说"); getPromptDialog().setConfirmText("我要认证"); getPromptDialog().show(); } /*** * 提示是否成为VIP * * @author fighter <br /> * 创建时间:2013-6-20<br /> * 修改时间:<br /> */ private void gotoVip(){ getPromptDialog().addCannel(); getPromptDialog().addConfirm(new View.OnClickListener() { @Override public void onClick(View v) { // 去认证头像. getPromptDialog().cancel(); Intent intent = new Intent(DetailActivity.this, MyPointActivity.class); startActivity(intent); } }); getPromptDialog().setMessage("成为VIP用户!"); getPromptDialog().setCannelText("以后在说"); getPromptDialog().setConfirmText("成为VIP"); getPromptDialog().show(); } }
gpl-2.0
mgrigioni/oseb
base/src/org/adempierelbr/process/ProcAvgCostCreate.java
13740
/****************************************************************************** * Product: Compiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.adempierelbr.process; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import org.adempierelbr.model.X_LBR_AverageCost; import org.adempierelbr.model.X_LBR_AverageCostLine; import org.adempierelbr.util.AdempiereLBR; import org.compiere.model.MPeriod; import org.compiere.process.ProcessInfoParameter; import org.compiere.process.SvrProcess; import org.compiere.util.DB; import org.compiere.util.Env; import org.compiere.util.Msg; /** * Average Cost BR * * @author Ricardo Santana * @contributor Mario Grigioni * @version $Id: ProcAvgCostCreate.java, 30/07/2006 00:51:01 ralexsander Exp $ */ public class ProcAvgCostCreate extends SvrProcess { private int p_LBR_AverageCost_ID = 0; private String costType = ""; private final String MANUFACTURED = X_LBR_AverageCostLine.LBR_AVGCOSTTYPE_Manufactured; private final String PUCHASED = X_LBR_AverageCostLine.LBR_AVGCOSTTYPE_Purchased; public String trxName = null; /** * Prepare */ protected void prepare () { ProcessInfoParameter[] para = getParameter(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else if (name.equals("lbr_AvgCostType")) costType = (String) para[i].getParameter(); else log.log(Level.SEVERE, "Unknown Parameter: " + name); } p_LBR_AverageCost_ID = getRecord_ID(); } // prepare /** * Process * @return Info * @throws Exception */ protected String doIt() throws Exception { if (p_LBR_AverageCost_ID == 0) { log.warning("LBR_AverageCost_ID=" + p_LBR_AverageCost_ID); return "ERR: No LBR_AverageCost_ID"; } X_LBR_AverageCost avgCost = new X_LBR_AverageCost(getCtx(), p_LBR_AverageCost_ID, trxName); MPeriod period = new MPeriod(getCtx(), avgCost.getC_Period_ID(), trxName); cleanupLines(avgCost.get_ID(),costType); Map<Integer,BigDecimal> nfsComp = getNfComplementar(period); String sql = ""; if(costType.equals(PUCHASED)){ sql = "SELECT DISTINCT aux.M_Product_ID, QtyOnDate(aux.M_Product_ID, ?), " + "aux.CurrentCostPrice, SUM(aux.TotalCost), SUM(aux.QtyEntered) " + "FROM( " + "SELECT p.M_Product_ID, COALESCE(c.CurrentCostPrice,0) as CurrentCostPrice, " + "CASE WHEN ( il.LBR_CFOP_ID IN (SELECT LBR_CFOP_ID FROM LBR_CFOP WHERE Value LIKE '%.116' OR Value LIKE '%.117') ) " + "THEN " + "(SUM((il.PriceEntered-(il.lbr_PriceEnteredBR*0.0925))*il.QtyEntered)) " + "ELSE " + "SUM(il.PriceEntered*il.QtyEntered) " + "END AS TotalCost, " + "SUM(il.QtyEntered) as QtyEntered " + "FROM C_Invoice i " + "INNER JOIN C_InvoiceLine il ON i.C_Invoice_ID = il.C_Invoice_ID " + "INNER JOIN C_DocType dt ON dt.C_DocType_ID=i.C_DocTypeTarget_ID " + "INNER JOIN M_Product p ON p.M_Product_ID = il.M_Product_ID " + "LEFT JOIN M_Cost c ON (c.M_Product_ID = il.M_Product_ID AND " + "c.M_CostElement_ID = ?) " + "WHERE i.DocStatus IN ('CL', 'CO') " + "AND p.ProductType = 'I' " + "AND i.AD_Client_ID = ? " + "AND p.IsPurchased = 'Y' " + "AND PriceEntered > 0 " + "AND QtyEntered > 0 " + "AND dt.DocBaseType = 'API' " + "AND ((dt.lbr_HasOpenItems = 'Y' AND il.LBR_CFOP_ID NOT IN (SELECT LBR_CFOP_ID FROM LBR_CFOP WHERE Value LIKE '%.922')) " + "OR (dt.lbr_HasOpenItems = 'N' AND il.LBR_CFOP_ID IN (SELECT LBR_CFOP_ID FROM LBR_CFOP WHERE Value LIKE '%.116' OR Value LIKE '%.117'))) " + "AND TRUNC(i.DateAcct) BETWEEN ? AND ? " + "GROUP BY p.M_Product_ID, c.CurrentCostPrice, il.LBR_CFOP_ID " + "ORDER BY CurrentCostPrice DESC) aux " + "GROUP BY aux.M_Product_ID, aux.CurrentCostPrice"; } else if(costType.equals(MANUFACTURED)){ sql = "SELECT PlanCost.M_Product_ID, QtyOnDate(PlanCost.M_Product_ID, ?), c.CurrentCostPrice, " + "SUM(Custo*ProductionQty) AS Custo, SUM(ProductionQty) AS Qtd " + "FROM " + "(SELECT pp.M_ProductionPlan_ID, pp.M_Product_ID, pp.ProductionQty AS ProductionQty, " + "SUM((ABS(pl.MovementQty)/ABS(pp.ProductionQty)) * c.CurrentCostPrice) AS Custo FROM M_Production pr " + "INNER JOIN M_ProductionPlan pp ON pr.M_Production_ID=pp.M_Production_ID " + "INNER JOIN M_ProductionLine pl ON (pl.M_ProductionPlan_ID=pp.M_ProductionPlan_ID AND pl.M_Product_ID <> pp.M_Product_ID) " + "INNER JOIN M_Cost c ON (c.M_Product_ID=pl.M_Product_ID AND c.M_CostElement_ID=?) " + "WHERE pr.Processed='Y' " + "AND pr.AD_Client_ID=? " + "AND TRUNC(pr.MovementDate) BETWEEN ? AND ? " + " GROUP BY pp.M_ProductionPlan_ID, pp.M_Product_ID, pp.ProductionQty " + ") PlanCost INNER JOIN M_Cost c ON (c.M_Product_ID=PlanCost.M_Product_ID AND c.M_CostElement_ID=?) " + "GROUP BY PlanCost.M_Product_ID, CurrentCostPrice"; } PreparedStatement pstmt = null; ResultSet rs = null; try { int i=1; pstmt = DB.prepareStatement (sql, trxName); pstmt.setTimestamp(i++, AdempiereLBR.addDays(period.getStartDate(), -1)); pstmt.setInt(i++, avgCost.getM_CostElement_ID()); pstmt.setInt(i++, avgCost.getAD_Client_ID()); pstmt.setTimestamp(i++, period.getStartDate()); pstmt.setTimestamp(i++, period.getEndDate()); if(costType.equals(MANUFACTURED)) pstmt.setInt(i++, avgCost.getM_CostElement_ID()); rs = pstmt.executeQuery (); while (rs.next ()) { X_LBR_AverageCostLine line = new X_LBR_AverageCostLine(getCtx(), 0, trxName); line.setLBR_AverageCost_ID(p_LBR_AverageCost_ID); line.setM_Product_ID(rs.getInt(1)); line.setCurrentQty(rs.getBigDecimal(2)); line.setCurrentCostPrice(rs.getBigDecimal(3)); line.setCumulatedAmt(rs.getBigDecimal(4)); line.setCumulatedQty(rs.getBigDecimal(5)); line.setlbr_AvgCostType(costType); BigDecimal totCurrent = line.getCurrentCostPrice().multiply(line.getCurrentQty()); BigDecimal totCumulated = line.getCumulatedAmt(); if (costType.equals(PUCHASED) && !nfsComp.isEmpty()){ BigDecimal compAmt = nfsComp.get(rs.getInt(1)); if (compAmt != null && compAmt.signum() == 1){ totCumulated = totCumulated.add(compAmt); line.setExpenseAmt(compAmt); } } BigDecimal total = totCurrent.add(totCumulated); BigDecimal sumQty = line.getCurrentQty().add(line.getCumulatedQty()); if(sumQty.signum() == 0) { sumQty = Env.ONE; line.setDescription("ERRO NO CALCULO, DIVIDIDO POR ZERO"); } line.setFutureCostPrice(total.divide(sumQty, 12, BigDecimal.ROUND_HALF_UP)); line.save(); } /** Executar varias vezes devido aos niveis da LDM */ if(costType.equals(MANUFACTURED)) { int j=0; BigDecimal oldCost = Env.ZERO; Boolean allLevelsOK = false; while(!allLevelsOK) { i=1; sql = "SELECT PlanCost.M_Product_ID, PlanCost.LBR_AverageCostLine_ID, " + "SUM(Custo*ProductionQty) AS Custo, SUM(ProductionQty) AS Qtd " + "FROM " + "(SELECT pp.M_ProductionPlan_ID, pp.M_Product_ID, avgl.LBR_AverageCostLine_ID, pp.ProductionQty AS ProductionQty, " + "SUM((ABS(pl.MovementQty)/ABS(pp.ProductionQty)) * (CASE WHEN new_avg_cost.FutureCostPrice IS NOT NULL OR new_avg_cost.FutureCostPrice > 0 THEN new_avg_cost.FutureCostPrice ELSE c.CurrentCostPrice END)) AS Custo FROM M_Production pr " + "INNER JOIN M_ProductionPlan pp ON pr.M_Production_ID=pp.M_Production_ID " + "INNER JOIN M_ProductionLine pl ON (pl.M_ProductionPlan_ID=pp.M_ProductionPlan_ID AND pl.M_Product_ID <> pp.M_Product_ID) " + "INNER JOIN M_Cost c ON (c.M_Product_ID=pl.M_Product_ID AND c.M_CostElement_ID=?) " + "INNER JOIN LBR_AverageCostLine avgl ON (avgl.M_Product_ID=pp.M_Product_ID AND avgl.LBR_AverageCost_ID=? AND avgl.lbr_AvgCostType='M') " + " LEFT JOIN LBR_AverageCostLine new_avg_cost ON (new_avg_cost.M_Product_ID=pl.M_Product_ID AND new_avg_cost.LBR_AverageCost_ID=? AND new_avg_cost.lbr_AvgCostType='M') " + "WHERE pr.Processed='Y' " + "AND pr.AD_Client_ID=? " + "AND TRUNC(pr.MovementDate) BETWEEN ? AND ? " + "GROUP BY pp.M_ProductionPlan_ID, pp.M_Product_ID, pp.ProductionQty, avgl.LBR_AverageCostLine_ID " + ") PlanCost " + "GROUP BY PlanCost.M_Product_ID, PlanCost.LBR_AverageCostLine_ID"; pstmt = DB.prepareStatement (sql, trxName); pstmt.setInt(i++, avgCost.getM_CostElement_ID()); pstmt.setInt(i++, avgCost.getLBR_AverageCost_ID()); pstmt.setInt(i++, avgCost.getLBR_AverageCost_ID()); pstmt.setInt(i++, avgCost.getAD_Client_ID()); pstmt.setTimestamp(i++, period.getStartDate()); pstmt.setTimestamp(i++, period.getEndDate()); rs = pstmt.executeQuery (); while (rs.next ()) { X_LBR_AverageCostLine line = new X_LBR_AverageCostLine(getCtx(), rs.getInt(2), trxName); line.setCumulatedAmt(rs.getBigDecimal(3)); line.setCumulatedQty(rs.getBigDecimal(4)); BigDecimal totCurrent = line.getCurrentCostPrice().multiply(line.getCurrentQty()); BigDecimal totCumulated = line.getCumulatedAmt(); BigDecimal total = totCurrent.add(totCumulated); BigDecimal sumQty = line.getCurrentQty().add(line.getCumulatedQty()); if(sumQty.signum() == 0) { sumQty = Env.ONE; line.setDescription("ERRO NO CALCULO, DIVIDIDO POR ZERO"); } line.setFutureCostPrice(total.divide(sumQty, 12, BigDecimal.ROUND_HALF_UP)); line.save(); } BigDecimal result = DB.getSQLValueBD(avgCost.get_TrxName(), "SELECT SUM(CumulatedAmt+ExpenseAmt) " + "FROM LBR_AverageCostLine WHERE LBR_AverageCost_ID=?", avgCost.getLBR_AverageCost_ID()); log.info("Passo: " + j + " / Cost total: " + result); if(result.compareTo(oldCost) == 0 || j > 29) allLevelsOK = true; else{ oldCost = result; j++; } } } // Produtos Comprados if(costType.equals(PUCHASED)) avgCost.setlbr_AvgStep1(true); // Produtos Fabricados else avgCost.setlbr_AvgStep3(true); avgCost.save(trxName); } catch (Exception e) { log.log (Level.SEVERE, sql, e); } finally{ DB.close(rs, pstmt); } return Msg.getMsg(Env.getAD_Language(getCtx()), "ProcessOK", true); } // doIt private void cleanupLines(int ID, String costType){ String sql = "DELETE FROM LBR_AverageCostLine " + "WHERE lbr_AvgCostType=? AND LBR_AverageCost_ID=?"; DB.executeUpdate(sql, new Object[]{costType,ID}, false, trxName); } //cleanupLine private Map<Integer,BigDecimal> getNfComplementar(MPeriod period){ String sql = "SELECT M_Product_ID, SUM(ComplAmt) FROM ( " + "SELECT nfComplementar.*, (TotalLines * perct) as ComplAmt FROM ( " + "SELECT M_Product_ID, LineTotalAmt, " + "(SELECT TotalLines FROM LBR_NotaFiscal WHERE nfl.LBR_NotaFiscal_ID = LBR_NotaFiscal.LBR_NotaFiscal_ID) as GrandTotal, " + "ROUND(LineTotalAmt / (SELECT TotalLines FROM LBR_NotaFiscal WHERE nfl.LBR_NotaFiscal_ID = LBR_NotaFiscal.LBR_NotaFiscal_ID),4) as perct, " + "compl.LBR_RefNotaFiscal_ID, compl.TotalLines " + "FROM LBR_NotaFiscalLine nfl " + "INNER JOIN " + "(SELECT ref.LBR_NotaFiscal_ID as LBR_RefNotaFiscal_ID, complementar.LineNetAmt as TotalLines " + "FROM C_InvoiceLine complementar " + "INNER JOIN C_Invoice i ON (complementar.C_Invoice_ID = i.C_Invoice_ID) " + "INNER JOIN LBR_NotaFiscal ref ON (complementar.LBR_NotaFiscal_ID = ref.LBR_NotaFiscal_ID) " + "WHERE i.DocStatus='CO' AND complementar.C_Charge_ID = 3000114 " + "AND i.dateacct BETWEEN ? and ?) compl " + "ON (nfl.LBR_NotaFiscal_ID = compl.LBR_RefNotaFiscal_ID)) nfComplementar) " + "GROUP BY M_Product_ID"; Map<Integer, BigDecimal> nfs = new HashMap<Integer,BigDecimal>(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement (sql, get_TrxName()); pstmt.setTimestamp(1, period.getStartDate()); pstmt.setTimestamp(2, period.getEndDate()); rs = pstmt.executeQuery (); while (rs.next ()) { nfs.put(rs.getInt(1), rs.getBigDecimal(2)); } } catch (Exception e) { log.log(Level.SEVERE, "", e); } finally{ DB.close(rs, pstmt); } return nfs; } } //ProcAvgCostCreate
gpl-2.0
manuelgentile/MAP
java8/java8_mixins/src/main/java/java8_mixins/Main.java
568
package java8_mixins; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class Main { private static class Device {} private static class DeviceA extends Device implements SwitchableMixin {} private static class DeviceB extends Device implements SwitchableMixin {} @Test public void prova() { DeviceA a = new DeviceA(); DeviceB b = new DeviceB(); a.setActivated(true); assertTrue(a.isActivated()); assertFalse(b.isActivated()); } }
gpl-2.0
ActiveVolcano/cmd-text
src/main/java/cn/chenqingcan/cmdtext/Head.java
1175
package cn.chenqingcan.cmdtext; import java.io.*; import cn.chenqingcan.util.*; /** * 看文件开头几行 * @author 陈庆灿 */ public class Head { //------------------------------------------------------------------------ /** 程序入口 */ public static void main(String[] args) { TextFileInfo file; int lineno; try { file = TextFileInfo.prompt(); } catch (Throwable e) { return; } for (;;) { try { lineno = VolcanoConsoleUtil.inputInteger("行数"); } catch (Throwable e) { return; } try { echoHeadLine(file, lineno); } catch (Throwable e) { System.err.println(VolcanoExceptionUtil.throwableToSimpleString(e)); } } } //------------------------------------------------------------------------ /** 指定行数回显文件开头 */ private static void echoHeadLine(final TextFileInfo file, final int lineno) throws Throwable { try (BufferedReader reader = VolcanoFileUtil.openFileReader(file.getFileName(), file.getCharset())) { for (int n = 0 ; n < lineno ; n++) { String s = reader.readLine(); if (s == null) { return; } System.out.println(s); } } } }
gpl-2.0
IFT8/Spring
src/cn/ift8/spring/normal/annotation/normal/Student.java
344
package cn.ift8.spring.normal.annotation.normal; /** * Created by IFT8 * on 2015/8/16. */ public class Student { private Long sid; private String sname; @Override public String toString() { return "Student{" + "sid=" + sid + ", sname='" + sname + '\'' + '}'; } }
gpl-2.0
didmar/jrl
src/main/java/com/github/didmar/jrl/utils/plot/Gnuplot.java
4145
package com.github.didmar.jrl.utils.plot; import java.io.File; import java.io.IOException; import java.io.PrintStream; import org.eclipse.jdt.annotation.NonNullByDefault; /** * This class is used to communicate with a gnuplot instance. See * http://www.gnuplot.info/ for details about gnuplot. Note that gnuplot exits, * when the java program does. However, by sending the <tt>&quot;exit&quot;</tt> * command to gnuplot via {@link Gnuplot#execute(String)}, the gnuplot process * exits, too. In order to quit a gnuplot session, the method * {@link Gnuplot#close()} first sends the <tt>&quot;exit&quot;</tt> command to * gnuplot and then closes the communication channel. * <p> * If the default constructor does not work on your system, try to set the * gnuplot executable in the public static field * {@link com.github.didmar.jrl.utils.plot.Gnuplot#executable}. * * This class is borrowed from the Java XCSF library. * * @author Didier Marin */ @NonNullByDefault public final class Gnuplot { /** * Gnuplot executable on the filesystem */ public final static String executable = getGnuplotExecutableName(); // communication channel: console.output -> process.input private final PrintStream console; /** * Default constructor executes a OS-specific command to start gnuplot and * establishes the communication. If this constructor does not work on your * machine, you can specify the executable in * {@link com.github.didmar.jrl.utils.plot.Gnuplot#executable}. * <p> * <b>Windows</b><br/> * Gnuplot is expected to be installed at the default location, that is * * <pre> * C:\&lt;localized program files directory&gt;\gnuplot\bin\pgnuplot.exe * </pre> * * where the <tt>Program Files</tt> directory name depends on the language * set for the OS. This constructor retrieves the localized name of this * directory. * <p> * <b>Linux</b><br/> * On linux systems the <tt>gnuplot</tt> executable has to be linked in one * of the default pathes in order to be available system-wide. * <p> * <b>Other Operating Systems</b><br/> * Other operating systems are not available to the developers and comments * on how defaults on these systems would look like are very welcome. * * @throws IOException * if the system fails to execute gnuplot */ public Gnuplot() throws IOException { // start the gnuplot process and connect channels Process p = Runtime.getRuntime().exec(executable); console = new PrintStream(p.getOutputStream()); } public static String getGnuplotExecutableName() { final String os = System.getProperty("os.name").toLowerCase(); if (os.contains("linux")) { // assume that path is set return "gnuplot"; } if (os.contains("windows")) { // assume default installation path, i.e. // <localized:program files>/gnuplot/ String programFiles = System.getenv("ProgramFiles"); if (programFiles == null) { // nothing found? ups. programFiles = "C:" + File.separatorChar + "Program Files"; } // assert separator if (!programFiles.endsWith(File.separator)) { programFiles += File.separatorChar; } return programFiles + "gnuplot" + File.separatorChar + "bin" + File.separatorChar + "pgnuplot.exe"; } throw new RuntimeException("Operating system '" + os + "' is not supported. " + "If you have Gnuplot installed, " + "specify the executable command via" + System.getProperty("line.separator") + "Gnuplot.executable " + "= \"your executable\""); } /** * Sends the given <code>command</code> to gnuplot. Multiple commands can be * seperated with a semicolon. * * @param command * the command to execute on the gnuplot process */ public final void execute(String command) { console.println(command); console.flush(); } /** * Exit gnuplot and close the in/out streams. */ public final void close() { this.execute("exit"); console.close(); } /* * (non-Javadoc) * * @see java.lang.Object#finalize() */ @Override protected final void finalize() throws Throwable { this.close(); super.finalize(); } }
gpl-2.0
scoophealth/oscar
src/main/java/org/oscarehr/ws/rest/to/model/FavoriteTo1.java
6203
/** * Copyright (c) 2013-2015. Department of Computer Science, University of Victoria. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Computer Science * LeadLab * University of Victoria * Victoria, Canada */ package org.oscarehr.ws.rest.to.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name="favorite") public class FavoriteTo1 implements Serializable { private static final long serialVersionUID = 1L; private Integer favoriteId; private String brandName; private String genericName; private String atc; private String favoriteName; // DIN number in Canada. private String regionalIdentifier; private Integer providerNo; private float takeMin; private float takeMax; private String frequency; private Integer duration; private String durationUnit; private Integer quantity; private String route; private String form; private String method; private Boolean prn; private Integer repeats; private String instructions; private Float strength; private String strengthUnit; private String externalProvider; private Boolean longTerm; private Boolean noSubstitutions; public Integer getId() { return favoriteId; } public void setId(Integer id) { this.favoriteId = id; } public Integer getFavoriteId() { return favoriteId; } public void setFavoriteId(Integer id) { this.favoriteId = id; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public String getGenericName() { return genericName; } public void setGenericName(String genericName) { this.genericName = genericName; } public String getAtc() { return atc; } public void setAtc(String atc) { this.atc = atc; } public String getFavoriteName() { return favoriteName; } public void setFavoriteName(String favoriteName) { this.favoriteName = favoriteName; } public String getRegionalIdentifier() { return regionalIdentifier; } public void setRegionalIdentifier(String regionalIdentifier) { this.regionalIdentifier = regionalIdentifier; } public Integer getProviderNo() { return providerNo; } public void setProviderNo(Integer providerNo) { this.providerNo = providerNo; } public float getTakeMin() { return takeMin; } public void setTakeMin(float takeMin) { this.takeMin = takeMin; } public float getTakeMax() { return takeMax; } public void setTakeMax(float takeMax) { this.takeMax = takeMax; } public String getFrequency() { return frequency; } public void setFrequency(String frequency) { this.frequency = frequency; } public Integer getDuration() { return duration; } public void setDuration(Integer duration) { this.duration = duration; } public String getDurationUnit() { return durationUnit; } public void setDurationUnit(String durationUnit) { this.durationUnit = durationUnit; } public String getRoute() { return route; } public void setRoute(String route) { this.route = route; } public String getForm() { return form; } public void setForm(String form) { this.form = form; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public Boolean getPrn() { return prn; } public void setPrn(Boolean prn) { this.prn = prn; } public Integer getRepeats() { return repeats; } public void setRepeats(Integer repeats) { this.repeats = repeats; } public String getInstructions() { return instructions; } public void setInstructions(String instructions) { this.instructions = instructions; } public Float getStrength() { return strength; } public void setStrength(Float strength) { this.strength = strength; } public String getStrengthUnit() { return strengthUnit; } public void setStrengthUnit(String strengthUnit) { this.strengthUnit = strengthUnit; } public String getExternalProvider() { return externalProvider; } public void setExternalProvider(String externalProvider) { this.externalProvider = externalProvider; } public Boolean getLongTerm() { return longTerm; } public void setLongTerm(Boolean longTerm) { this.longTerm = longTerm; } public Boolean getNoSubstitutions() { return noSubstitutions; } public void setNoSubstitutions(Boolean noSubstitutions) { this.noSubstitutions = noSubstitutions; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } }
gpl-2.0
o-alex/GVoD
system/src/main/java/se/sics/gvod/system/HostManagerComp.java
4732
/* * Copyright (C) 2009 Swedish Institute of Computer Science (SICS) Copyright (C) * 2009 Royal Institute of Technology (KTH) * * GVoD is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package se.sics.gvod.system; import com.google.common.util.concurrent.SettableFuture; import se.sics.gvod.manager.VoDManagerImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.sics.gvod.bootstrap.client.BootstrapClientComp; import se.sics.gvod.bootstrap.client.BootstrapClientInit; import se.sics.gvod.bootstrap.client.BootstrapClientPort; import se.sics.gvod.bootstrap.server.BootstrapServerComp; import se.sics.gvod.bootstrap.server.peermanager.PeerManagerPort; import se.sics.gvod.common.utility.UtilityUpdatePort; import se.sics.gvod.core.VoDComp; import se.sics.gvod.core.VoDInit; import se.sics.gvod.core.VoDPort; import se.sics.kompics.Component; import se.sics.kompics.ComponentDefinition; import se.sics.kompics.Init; import se.sics.kompics.Positive; import se.sics.kompics.network.Network; import se.sics.kompics.timer.Timer; import se.sics.p2ptoolbox.util.traits.Nated; /** * @author Alex Ormenisan <aaor@sics.se> */ public class HostManagerComp extends ComponentDefinition { private static final Logger log = LoggerFactory.getLogger(HostManagerComp.class); private Positive<Network> network = requires(Network.class); private Positive<Timer> timer = requires(Timer.class); private Component vodMngr; private Component vod; private Component bootstrapClient; private Component bootstrapServer; private Component peerManager; private Component globalCroupier; private final HostManagerConfig config; public HostManagerComp(HostManagerInit init) { log.debug("starting... - self {}, bootstrap server {}", new Object[]{init.config.getSelf(), init.config.getCaracalClient()}); this.config = init.config; this.vodMngr = create(VoDManagerImpl.class, new VoDManagerImpl.VoDManagerInit(config.getVoDManagerConfig())); init.gvodSyncIFuture.set(vodMngr.getComponent()); this.vod = create(VoDComp.class, new VoDInit(config.getVoDConfig())); this.bootstrapClient = create(BootstrapClientComp.class, new BootstrapClientInit(config.getBootstrapClientConfig())); log.info("{} node is Natted:{}", config.getSelf(), config.getSelf().hasTrait(Nated.class)); if (!config.getSelf().hasTrait(Nated.class)) { bootstrapServer = create(BootstrapServerComp.class, new BootstrapServerComp.BootstrapServerInit(config.getBootstrapServerConfig())); peerManager = init.peerManager; connect(bootstrapServer.getNegative(Network.class), network); connect(bootstrapServer.getNegative(PeerManagerPort.class), peerManager.getPositive(PeerManagerPort.class)); } else { bootstrapServer = null; peerManager = null; } connect(vodMngr.getNegative(VoDPort.class), vod.getPositive(VoDPort.class)); connect(vod.getNegative(Network.class), network); connect(vod.getNegative(BootstrapClientPort.class), bootstrapClient.getPositive(BootstrapClientPort.class)); connect(vod.getNegative(Timer.class), timer); connect(bootstrapClient.getNegative(Network.class), network); connect(bootstrapClient.getNegative(Timer.class), timer); connect(bootstrapClient.getNegative(UtilityUpdatePort.class), vod.getPositive(UtilityUpdatePort.class)); connect(vodMngr.getNegative(UtilityUpdatePort.class), vod.getPositive(UtilityUpdatePort.class)); } public static class HostManagerInit extends Init<HostManagerComp> { public final HostManagerConfig config; public final Component peerManager; public final SettableFuture gvodSyncIFuture; public HostManagerInit(HostManagerConfig config, Component peerManager, SettableFuture gvodSyncIFuture) { this.config = config; this.peerManager = peerManager; this.gvodSyncIFuture = gvodSyncIFuture; } } }
gpl-2.0
tea-dragon/triplea
src/main/java/games/strategy/triplea/attatchments/AbstractRulesAttachment.java
15736
package games.strategy.triplea.attatchments; import games.strategy.engine.data.Attachable; import games.strategy.engine.data.GameData; import games.strategy.engine.data.GameMap; import games.strategy.engine.data.GameParseException; import games.strategy.engine.data.PlayerID; import games.strategy.engine.data.PlayerList; import games.strategy.engine.data.Territory; import games.strategy.engine.data.annotations.GameProperty; import games.strategy.engine.data.annotations.InternalDoNotExport; import games.strategy.triplea.delegate.Matches; import games.strategy.triplea.delegate.OriginalOwnerTracker; import games.strategy.util.Match; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Set; /** * The Purpose of this class is to hold shared and simple methods used by RulesAttachment * * @author veqryn [Mark Christopher Duncan] * */ public abstract class AbstractRulesAttachment extends AbstractConditionsAttachment implements ICondition { private static final long serialVersionUID = -6977650137928964759L; @InternalDoNotExport protected boolean m_countEach = false; // Do Not Export (do not include in IAttachment). Determines if we will be counting each for the purposes of m_objectiveValue @InternalDoNotExport protected int m_eachMultiple = 1; // Do Not Export (do not include in IAttachment). The multiple that will be applied to m_objectiveValue if m_countEach is true @InternalDoNotExport protected int m_territoryCount = -1; // Do Not Export (do not include in IAttachment). Used with the next Territory conditions to determine the number of territories needed to be valid (ex: m_alliedOwnershipTerritories) protected ArrayList<PlayerID> m_players = new ArrayList<PlayerID>(); // A list of players that can be used with directOwnershipTerritories, directExclusionTerritories, directPresenceTerritories, or any of the other territory lists protected int m_objectiveValue = 0; // only used if the attachment begins with "objectiveAttachment" protected int m_uses = -1; // only matters for objectiveValue, does not affect the condition protected HashMap<Integer, Integer> m_turns = null; // condition for what turn it is protected boolean m_switch = true; // for on/off conditions protected String m_gameProperty = null; // allows custom GameProperties public AbstractRulesAttachment(final String name, final Attachable attachable, final GameData gameData) { super(name, attachable, gameData); } /** * Adds to, not sets. Anything that adds to instead of setting needs a clear function as well. * * @param names * @throws GameParseException */ @GameProperty(xmlProperty = true, gameProperty = true, adds = true) public void setPlayers(final String names) throws GameParseException { final PlayerList pl = getData().getPlayerList(); for (final String p : names.split(":")) { final PlayerID player = pl.getPlayerID(p); if (player == null) throw new GameParseException("Could not find player. name:" + p + thisErrorMsg()); m_players.add(player); } } @GameProperty(xmlProperty = true, gameProperty = true, adds = false) public void setPlayers(final ArrayList<PlayerID> value) { m_players = value; } public ArrayList<PlayerID> getPlayers() { if (m_players.isEmpty()) return new ArrayList<PlayerID>(Collections.singletonList((PlayerID) getAttachedTo())); else return m_players; } public void clearPlayers() { m_players.clear(); } public void resetPlayers() { m_players = new ArrayList<PlayerID>(); } @Override @GameProperty(xmlProperty = true, gameProperty = true, adds = false) public void setChance(final String chance) throws GameParseException { throw new GameParseException("chance not allowed for use with RulesAttachments, instead use it with Triggers or PoliticalActions" + thisErrorMsg()); } @GameProperty(xmlProperty = true, gameProperty = true, adds = false) public void setObjectiveValue(final String value) { m_objectiveValue = getInt(value); } @GameProperty(xmlProperty = true, gameProperty = true, adds = false) public void setObjectiveValue(final Integer value) { m_objectiveValue = value; } public int getObjectiveValue() { return m_objectiveValue; } public void resetObjectiveValue() { m_objectiveValue = 0; } /** * Internal use only, is not set by xml or property utils. * Is used to determine the number of territories we need to satisfy a specific territory based condition check. * It is set multiple times during each check [isSatisfied], as there might be multiple types of territory checks being done. So it is just a temporary value. * * @param value */ @InternalDoNotExport protected void setTerritoryCount(final String value) { if (value.equals("each")) { m_territoryCount = 1; m_countEach = true; } else m_territoryCount = getInt(value); } public int getTerritoryCount() { return m_territoryCount; } /** * Used to determine if there is a multiple on this national objective (if the user specified 'each' in the count. * For example, you may want to have the player receive 3 PUs for controlling each territory, in a list of territories. * * @return */ public int getEachMultiple() { if (!getCountEach()) return 1; return m_eachMultiple; } protected boolean getCountEach() { return m_countEach; } @GameProperty(xmlProperty = true, gameProperty = true, adds = false) public void setUses(final String s) { m_uses = getInt(s); } @GameProperty(xmlProperty = true, gameProperty = true, adds = false) public void setUses(final Integer u) { m_uses = u; } /** * "uses" on RulesAttachments apply ONLY to giving money (PUs) to the player, they do NOT apply to the condition, and therefore should not be tested for in isSatisfied. * * @return */ public int getUses() { return m_uses; } public void resetUses() { m_uses = -1; } @GameProperty(xmlProperty = true, gameProperty = true, adds = false) public void setSwitch(final String value) { m_switch = getBool(value); } @GameProperty(xmlProperty = true, gameProperty = true, adds = false) public void setSwitch(final Boolean value) { m_switch = value; } public boolean getSwitch() { return m_switch; } public void resetSwitch() { m_switch = true; } @GameProperty(xmlProperty = true, gameProperty = true, adds = false) public void setGameProperty(final String value) { m_gameProperty = value; } public String getGameProperty() { return m_gameProperty; } public boolean getGamePropertyState(final GameData data) { if (m_gameProperty == null) return false; return data.getProperties().get(m_gameProperty, false); } public void resetGameProperty() { m_gameProperty = null; } @GameProperty(xmlProperty = true, gameProperty = true, adds = false) public void setTurns(final String turns) throws GameParseException { if (turns == null) { m_turns = null; return; } m_turns = new HashMap<Integer, Integer>(); final String[] s = turns.split(":"); if (s.length < 1) throw new GameParseException("Empty turn list" + thisErrorMsg()); for (final String subString : s) { int start, end; try { start = getInt(subString); end = start; } catch (final Exception e) { final String[] s2 = subString.split("-"); if (s2.length != 2) throw new GameParseException("Invalid syntax for turn range, must be 'int-int'" + thisErrorMsg()); start = getInt(s2[0]); if (s2[1].equals("+")) { end = Integer.MAX_VALUE; } else end = getInt(s2[1]); } final Integer t = Integer.valueOf(start); final Integer u = Integer.valueOf(end); m_turns.put(t, u); } } @GameProperty(xmlProperty = true, gameProperty = true, adds = false) public void setTurns(final HashMap<Integer, Integer> value) { m_turns = value; } public HashMap<Integer, Integer> getTurns() { return m_turns; } public void resetTurns() { m_turns = null; } protected boolean checkTurns(final GameData data) { final int turn = data.getSequence().getRound(); for (final Integer t : m_turns.keySet()) { if (turn >= t && turn <= m_turns.get(t)) return true; } return false; } /** * Takes a string like "original", "originalNoWater", "enemy", "controlled", "controlledNoWater", "all", "map", and turns it into an actual list of territories. * Also sets territoryCount. * * @author veqryn */ protected Set<Territory> getTerritoriesBasedOnStringName(final String name, final Collection<PlayerID> players, final GameData data) { final GameMap gameMap = data.getMap(); if (name.equals("original") || name.equals("enemy")) // get all originally owned territories { final Set<Territory> originalTerrs = new HashSet<Territory>(); for (final PlayerID player : players) { originalTerrs.addAll(OriginalOwnerTracker.getOriginallyOwned(data, player)); } setTerritoryCount(String.valueOf(originalTerrs.size())); return originalTerrs; } else if (name.equals("originalNoWater")) // get all originally owned territories, but no water or impassibles { final Set<Territory> originalTerrs = new HashSet<Territory>(); for (final PlayerID player : players) { originalTerrs.addAll(Match.getMatches(OriginalOwnerTracker.getOriginallyOwned(data, player), Matches.TerritoryIsNotImpassableToLandUnits(player, data))); // TODO: does this account for occupiedTerrOf??? } setTerritoryCount(String.valueOf(originalTerrs.size())); return originalTerrs; } else if (name.equals("controlled")) { final Set<Territory> ownedTerrs = new HashSet<Territory>(); for (final PlayerID player : players) { ownedTerrs.addAll(gameMap.getTerritoriesOwnedBy(player)); } setTerritoryCount(String.valueOf(ownedTerrs.size())); return ownedTerrs; } else if (name.equals("controlledNoWater")) { final Set<Territory> ownedTerrsNoWater = new HashSet<Territory>(); for (final PlayerID player : players) { ownedTerrsNoWater.addAll(Match.getMatches(gameMap.getTerritoriesOwnedBy(player), Matches.TerritoryIsNotImpassableToLandUnits(player, data))); } setTerritoryCount(String.valueOf(ownedTerrsNoWater.size())); return ownedTerrsNoWater; } else if (name.equals("all")) { final Set<Territory> allTerrs = new HashSet<Territory>(); for (final PlayerID player : players) { allTerrs.addAll(gameMap.getTerritoriesOwnedBy(player)); allTerrs.addAll(OriginalOwnerTracker.getOriginallyOwned(data, player)); } setTerritoryCount(String.valueOf(allTerrs.size())); return allTerrs; } else if (name.equals("map")) { final Set<Territory> allTerrs = new HashSet<Territory>(gameMap.getTerritories()); setTerritoryCount(String.valueOf(allTerrs.size())); return allTerrs; } else { // The list just contained 1 territory final Set<Territory> terr = new HashSet<Territory>(); final Territory t = data.getMap().getTerritory(name); if (t == null) throw new IllegalStateException("No territory called:" + name + thisErrorMsg()); terr.add(t); setTerritoryCount(String.valueOf(1)); return terr; } } /** * Takes the raw data from the xml, and turns it into an actual territory list. * Will also set territoryCount. * * @author veqryn * @throws GameParseException */ protected Set<Territory> getTerritoryListBasedOnInputFromXML(final String[] terrs, final Collection<PlayerID> players, final GameData data) { // If there's only 1, it might be a 'group' (original, controlled, controlledNoWater, all) if (terrs.length == 1) { return getTerritoriesBasedOnStringName(terrs[0], players, data); } else if (terrs.length == 2) { if (!terrs[1].equals("controlled") && !terrs[1].equals("controlledNoWater") && !terrs[1].equals("original") && !terrs[1].equals("originalNoWater") && !terrs[1].equals("all") && !terrs[1].equals("map") && !terrs[1].equals("enemy")) { return getListedTerritories(terrs, true, true); // Get the list of territories } else { final Set<Territory> rVal = getTerritoriesBasedOnStringName(terrs[1], players, data); setTerritoryCount(String.valueOf(terrs[0])); // set it a second time, since getTerritoriesBasedOnStringName also sets it (so do it after the method call). return rVal; } } else { return getListedTerritories(terrs, true, true); // Get the list of territories } } protected void validateNames(final String[] terrList) throws GameParseException { /*if (terrList != null && (!terrList.equals("controlled") && !terrList.equals("controlledNoWater") && !terrList.equals("original") && !terrList.equals("originalNoWater") && !terrList.equals("all") && !terrList.equals("map") && !terrList.equals("enemy"))) { if (terrList.length != 2) getListedTerritories(terrList); else if (terrList.length == 2 && (!terrList[1].equals("controlled") && !terrList[1].equals("controlledNoWater") && !terrList[1].equals("original") && !terrList.equals("originalNoWater") && !terrList[1].equals("all") && !terrList[1].equals("map") && !terrList[1].equals("enemy"))) getListedTerritories(terrList); }*/ if (terrList != null && terrList.length > 0) getListedTerritories(terrList, true, true); // removed checks for length & group commands because it breaks the setTerritoryCount feature. } /** * Validate that all listed territories actually exist. Will return an empty list of territories if sent a list that is empty or contains only a "" string. * * @param list * @return * @throws GameParseException */ public Set<Territory> getListedTerritories(final String[] list, final boolean testFirstItemForCount, final boolean mustSetTerritoryCount) { final Set<Territory> rVal = new HashSet<Territory>(); // this list is null, empty, or contains "", so return a blank list of territories if (list == null || list.length == 0 || (list.length == 1 && (list[0] == null || list[0].length() == 0))) return rVal; boolean haveSetCount = false; for (int i = 0; i < list.length; i++) { final String name = list[i]; if (testFirstItemForCount && i == 0) { // See if the first entry contains the number of territories needed to meet the criteria try { // check if this is an integer, and if so set territory count getInt(name); if (mustSetTerritoryCount) { haveSetCount = true; setTerritoryCount(name); } continue; } catch (final Exception e) { } } if (name.equals("each")) { m_countEach = true; if (mustSetTerritoryCount) { haveSetCount = true; setTerritoryCount(String.valueOf(1)); } continue; } // Skip looking for the territory if the original list contains one of the 'group' commands if (name.equals("controlled") || name.equals("controlledNoWater") || name.equals("original") || name.equals("originalNoWater") || name.equals("all") || name.equals("map") || name.equals("enemy")) break; // Validate all territories exist final Territory territory = getData().getMap().getTerritory(name); if (territory == null) throw new IllegalStateException("No territory called:" + name + thisErrorMsg()); rVal.add(territory); } if (mustSetTerritoryCount && !haveSetCount) { setTerritoryCount(String.valueOf(rVal.size())); // if we have not set it, then set it to be the size of this list } return rVal; } @Override public void validate(final GameData data) throws GameParseException { super.validate(data); // TODO Auto-generated method stub } }
gpl-2.0
daffycricket/tarotdroid
tarotDroidUiLib/src/main/java/org/nla/tarotdroid/lib/ui/controls/FacebookThumbnailItem.java
2372
/* This file is part of the Android application TarotDroid. TarotDroid 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. TarotDroid 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 TarotDroid. If not, see <http://www.gnu.org/licenses/>. */ package org.nla.tarotdroid.lib.ui.controls; import org.nla.tarotdroid.lib.R; import android.content.Context; import android.view.LayoutInflater; import android.widget.LinearLayout; import android.widget.TextView; import com.facebook.widget.ProfilePictureView; /** * A view aimed to display an facebook picture, a title and a content. * @author Nicolas LAURENT daffycricket<a>yahoo.fr */ public class FacebookThumbnailItem extends LinearLayout { /** * The title string. */ private CharSequence title; /** * The content string. */ private CharSequence content; /** * The facebook id. */ private String facebookId; /** * Constructs a FacebookThumbnailItem. * @param context * @param facebookId * @param title * @param content */ public FacebookThumbnailItem(final Context context, String facebookId, CharSequence title, CharSequence content) { super(context); LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.thumbnail_item_facebook, this); this.facebookId = facebookId; this.title = title; this.content = content; this.initializeViews(); } /** * Initializes the views. */ private void initializeViews() { TextView txtTitle = (TextView) this.findViewById(R.id.txtTitle); TextView txtContent = (TextView) this.findViewById(R.id.txtContent); txtTitle.setText(this.title); txtContent.setText(this.content); if (this.facebookId != null) { ProfilePictureView pictureView = (ProfilePictureView) this.findViewById(R.id.imgThumbnail); pictureView.setProfileId(this.facebookId); } } }
gpl-2.0
RoProducts/rastertheque
MapboxLibrary/src/com/mapbox/mapboxsdk/tileprovider/MapTileLayerBase.java
10470
// Created by plusminus on 21:46:22 - 25.09.2008 package com.mapbox.mapboxsdk.tileprovider; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import com.mapbox.mapboxsdk.geometry.BoundingBox; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.tileprovider.constants.TileLayerConstants; import com.mapbox.mapboxsdk.tileprovider.tilesource.ITileLayer; import com.mapbox.mapboxsdk.util.BitmapUtils; import uk.co.senab.bitmapcache.CacheableBitmapDrawable; /** * This is an abstract class. The tile provider is responsible for: * <ul> * <li>determining if a map tile is available,</li> * <li>notifying the client, via a callback handler</li> * </ul> * see {@link MapTile} for an overview of how tiles are served by this provider. * * @author Marc Kurtz * @author Nicolas Gramlich */ public abstract class MapTileLayerBase implements IMapTileProviderCallback, TileLayerConstants { protected Context context; protected final MapTileCache mTileCache; private Handler mTileRequestCompleteHandler; private boolean mUseDataConnection = true; private ITileLayer mTileSource; protected String mCacheKey = ""; /** * Attempts to get a Drawable that represents a {@link MapTile}. If the tile is not immediately * available this will return null and attempt to get the tile from known tile sources for * subsequent future requests. Note that this may return a {@link CacheableBitmapDrawable} in * which case you should follow proper handling procedures for using that Drawable or it may * reused while you are working with it. * * @see CacheableBitmapDrawable */ public abstract Drawable getMapTile(MapTile pTile, boolean allowRemote); public abstract void detach(); /** * Gets the minimum zoom level this tile provider can provide * * @return the minimum zoom level */ public float getMinimumZoomLevel() { return mTileSource.getMinimumZoomLevel(); } /** * Get the maximum zoom level this tile provider can provide. * * @return the maximum zoom level */ public float getMaximumZoomLevel() { return mTileSource.getMaximumZoomLevel(); } /** * Get the tile size in pixels this tile provider provides. * * @return the tile size in pixels */ public int getTileSizePixels() { return mTileSource.getTileSizePixels(); } /** * Get the tile provider bounding box. * * @return the tile source bounding box */ public BoundingBox getBoundingBox() { return mTileSource.getBoundingBox(); } /** * Get the tile provider center. * * @return the tile source center */ public LatLng getCenterCoordinate() { return mTileSource.getCenterCoordinate(); } /** * Get the tile provider suggested starting zoom. * * @return the tile suggested starting zoom */ public float getCenterZoom() { return mTileSource.getCenterZoom(); } /** * Sets the tile source for this tile provider. * * @param pTileSource the tile source */ public void setTileSource(final ITileLayer pTileSource) { if (mTileSource != null) { mTileSource.detach(); } mTileSource = pTileSource; if (mTileSource != null) { mCacheKey = mTileSource.getCacheKey(); } } /** * Gets the tile source for this tile provider. * * @return the tile source */ public ITileLayer getTileSource() { return mTileSource; } /** * Gets the cache key for that layer * * @return the cache key */ public String getCacheKey() { return mCacheKey; } /** * Creates a {@link MapTileCache} to be used to cache tiles in memory. */ public MapTileCache createTileCache(final Context aContext) { return new MapTileCache(aContext); } public MapTileLayerBase(final Context aContext, final ITileLayer pTileSource) { this(aContext, pTileSource, null); } public MapTileLayerBase(final Context aContext, final ITileLayer pTileSource, final Handler pDownloadFinishedListener) { this.context = aContext; mTileRequestCompleteHandler = pDownloadFinishedListener; mTileSource = pTileSource; mTileCache = this.createTileCache(aContext); } /** * Called by implementation class methods indicating that they have completed the request as * best it can. The tile is added to the cache, and a MAPTILE_SUCCESS_ID message is sent. * * @param pState the map tile request state object * @param pDrawable the Drawable of the map tile */ @Override public void mapTileRequestCompleted(final MapTileRequestState pState, final Drawable pDrawable) { // tell our caller we've finished and it should update its view if (mTileRequestCompleteHandler != null) { Message msg = new Message(); msg.obj = pState.getMapTile().getTileRect(); msg.what = MapTile.MAPTILE_SUCCESS_ID; mTileRequestCompleteHandler.sendMessage(msg); } if (DEBUG_TILE_PROVIDERS) { Log.d(TAG, "MapTileLayerBase.mapTileRequestCompleted(): " + pState.getMapTile()); } } /** * Called by implementation class methods indicating that they have failed to retrieve the * requested map tile. a MAPTILE_FAIL_ID message is sent. * * @param pState the map tile request state object */ @Override public void mapTileRequestFailed(final MapTileRequestState pState) { if (mTileRequestCompleteHandler != null) { mTileRequestCompleteHandler.sendEmptyMessage(MapTile.MAPTILE_FAIL_ID); } if (DEBUG_TILE_PROVIDERS) { Log.d(TAG, "MapTileLayerBase.mapTileRequestFailed(): " + pState.getMapTile()); } } /** * Called by implementation class methods indicating that they have produced an expired result * that can be used but better results may be delivered later. The tile is added to the cache, * and a MAPTILE_SUCCESS_ID message is sent. * * @param pState the map tile request state object * @param pDrawable the Drawable of the map tile */ @Override public void mapTileRequestExpiredTile(MapTileRequestState pState, CacheableBitmapDrawable pDrawable) { // Put the expired tile into the cache putExpiredTileIntoCache(pState.getMapTile(), pDrawable.getBitmap()); // tell our caller we've finished and it should update its view if (mTileRequestCompleteHandler != null) { mTileRequestCompleteHandler.sendEmptyMessage(MapTile.MAPTILE_SUCCESS_ID); } if (DEBUG_TILE_PROVIDERS) { Log.i(TAG, "MapTileLayerBase.mapTileRequestExpiredTile(): " + pState.getMapTile()); } } private void putTileIntoCacheInternal(final MapTile pTile, final Drawable pDrawable) { mTileCache.putTile(pTile, pDrawable); } private class CacheTask extends AsyncTask<Object, Void, Void> { @Override protected Void doInBackground(Object... params) { putTileIntoCacheInternal((MapTile) params[0], (Drawable) params[1]); return null; } } private void putTileIntoCache(final MapTile pTile, final Drawable pDrawable) { if (pDrawable != null) { if (Looper.myLooper() == Looper.getMainLooper()) { (new CacheTask()).execute(pTile, pDrawable); } else { putTileIntoCacheInternal(pTile, pDrawable); } } } protected void putTileIntoCache(final MapTileRequestState pState, final Drawable pDrawable) { putTileIntoCache(pState.getMapTile(), pDrawable); } protected void removeTileFromCache(final MapTileRequestState pState) { mTileCache.removeTileFromMemory(pState.getMapTile()); } public void putExpiredTileIntoCache(final MapTile pTile, final Bitmap bitmap) { if (bitmap == null) { return; } CacheableBitmapDrawable drawable = mTileCache.putTileInMemoryCache(pTile, bitmap); BitmapUtils.setCacheDrawableExpired(drawable); } public void setTileRequestCompleteHandler(final Handler handler) { mTileRequestCompleteHandler = handler; } public void clearTileMemoryCache() { mTileCache.purgeMemoryCache(); } public void clearTileDiskCache() { mTileCache.purgeDiskCache(); } public void setDiskCacheEnabled(final boolean enabled) { mTileCache.setDiskCacheEnabled(enabled); } /** * Whether to use the network connection if it's available. */ @Override public boolean useDataConnection() { return mUseDataConnection; } /** * Set whether to use the network connection if it's available. * * @param pMode if true use the network connection if it's available. if false don't use the * network connection even if it's available. */ public void setUseDataConnection(final boolean pMode) { mUseDataConnection = pMode; } public boolean hasNoSource() { return mTileSource == null; } public CacheableBitmapDrawable getMapTileFromMemory(MapTile pTile) { return (mTileCache != null) ? mTileCache.getMapTileFromMemory(pTile) : null; } public CacheableBitmapDrawable createCacheableBitmapDrawable(Bitmap bitmap, MapTile aTile) { return (mTileCache != null) ? mTileCache.createCacheableBitmapDrawable(bitmap, aTile) : null; } public Bitmap getBitmapFromRemoved(final int width, final int height) { return (mTileCache != null) ? mTileCache.getBitmapFromRemoved(width, height) : null; } /** * If a given MapTile is present in this cache, remove it from memory. * @param aTile */ public void removeTileFromMemory(final MapTile aTile) { if (mTileCache != null) { mTileCache.removeTileFromMemory(aTile); } } private static final String TAG = "MapTileLayerBase"; }
gpl-2.0
Baaleos/nwnx2-linux
plugins/jvm/java/src/org/nwnx/nwnx2/jvm/constants/Creature.java
5415
package org.nwnx.nwnx2.jvm.constants; /** * This class contains all unique constants beginning with "CREATURE". * Non-distinct keys are filtered; only the LAST appearing was * kept. */ public final class Creature { private Creature() {} public final static int MODEL_TYPE_NONE = 0; public final static int MODEL_TYPE_SKIN = 1; public final static int MODEL_TYPE_TATTOO = 2; public final static int MODEL_TYPE_UNDEAD = 255; public final static int PART_BELT = 8; public final static int PART_HEAD = 20; public final static int PART_LEFT_BICEP = 13; public final static int PART_LEFT_FOOT = 1; public final static int PART_LEFT_FOREARM = 11; public final static int PART_LEFT_HAND = 17; public final static int PART_LEFT_SHIN = 3; public final static int PART_LEFT_SHOULDER = 15; public final static int PART_LEFT_THIGH = 4; public final static int PART_NECK = 9; public final static int PART_PELVIS = 6; public final static int PART_RIGHT_BICEP = 12; public final static int PART_RIGHT_FOOT = 0; public final static int PART_RIGHT_FOREARM = 10; public final static int PART_RIGHT_HAND = 16; public final static int PART_RIGHT_SHIN = 2; public final static int PART_RIGHT_SHOULDER = 14; public final static int PART_RIGHT_THIGH = 5; public final static int PART_TORSO = 7; public final static int SIZE_HUGE = 5; public final static int SIZE_INVALID = 0; public final static int SIZE_LARGE = 4; public final static int SIZE_MEDIUM = 3; public final static int SIZE_SMALL = 2; public final static int SIZE_TINY = 1; public final static int TAIL_TYPE_BONE = 2; public final static int TAIL_TYPE_DEVIL = 3; public final static int TAIL_TYPE_LIZARD = 1; public final static int TAIL_TYPE_NONE = 0; public final static int TYPE_CLASS = 2; public final static int TYPE_DOES_NOT_HAVE_SPELL_EFFECT = 6; public final static int TYPE_HAS_SPELL_EFFECT = 5; public final static int TYPE_IS_ALIVE = 4; public final static int TYPE_PERCEPTION = 7; public final static int TYPE_PLAYER_CHAR = 1; public final static int TYPE_RACIAL_TYPE = 0; public final static int TYPE_REPUTATION = 3; public final static int WING_TYPE_ANGEL = 2; public final static int WING_TYPE_BAT = 3; public final static int WING_TYPE_BIRD = 6; public final static int WING_TYPE_BUTTERFLY = 5; public final static int WING_TYPE_DEMON = 1; public final static int WING_TYPE_DRAGON = 4; public final static int WING_TYPE_NONE = 0; public static String nameOf(int value) { if (value == 0) return "Creature.MODEL_TYPE_NONE"; if (value == 1) return "Creature.MODEL_TYPE_SKIN"; if (value == 2) return "Creature.MODEL_TYPE_TATTOO"; if (value == 255) return "Creature.MODEL_TYPE_UNDEAD"; if (value == 8) return "Creature.PART_BELT"; if (value == 20) return "Creature.PART_HEAD"; if (value == 13) return "Creature.PART_LEFT_BICEP"; if (value == 1) return "Creature.PART_LEFT_FOOT"; if (value == 11) return "Creature.PART_LEFT_FOREARM"; if (value == 17) return "Creature.PART_LEFT_HAND"; if (value == 3) return "Creature.PART_LEFT_SHIN"; if (value == 15) return "Creature.PART_LEFT_SHOULDER"; if (value == 4) return "Creature.PART_LEFT_THIGH"; if (value == 9) return "Creature.PART_NECK"; if (value == 6) return "Creature.PART_PELVIS"; if (value == 12) return "Creature.PART_RIGHT_BICEP"; if (value == 0) return "Creature.PART_RIGHT_FOOT"; if (value == 10) return "Creature.PART_RIGHT_FOREARM"; if (value == 16) return "Creature.PART_RIGHT_HAND"; if (value == 2) return "Creature.PART_RIGHT_SHIN"; if (value == 14) return "Creature.PART_RIGHT_SHOULDER"; if (value == 5) return "Creature.PART_RIGHT_THIGH"; if (value == 7) return "Creature.PART_TORSO"; if (value == 5) return "Creature.SIZE_HUGE"; if (value == 0) return "Creature.SIZE_INVALID"; if (value == 4) return "Creature.SIZE_LARGE"; if (value == 3) return "Creature.SIZE_MEDIUM"; if (value == 2) return "Creature.SIZE_SMALL"; if (value == 1) return "Creature.SIZE_TINY"; if (value == 2) return "Creature.TAIL_TYPE_BONE"; if (value == 3) return "Creature.TAIL_TYPE_DEVIL"; if (value == 1) return "Creature.TAIL_TYPE_LIZARD"; if (value == 0) return "Creature.TAIL_TYPE_NONE"; if (value == 2) return "Creature.TYPE_CLASS"; if (value == 6) return "Creature.TYPE_DOES_NOT_HAVE_SPELL_EFFECT"; if (value == 5) return "Creature.TYPE_HAS_SPELL_EFFECT"; if (value == 4) return "Creature.TYPE_IS_ALIVE"; if (value == 7) return "Creature.TYPE_PERCEPTION"; if (value == 1) return "Creature.TYPE_PLAYER_CHAR"; if (value == 0) return "Creature.TYPE_RACIAL_TYPE"; if (value == 3) return "Creature.TYPE_REPUTATION"; if (value == 2) return "Creature.WING_TYPE_ANGEL"; if (value == 3) return "Creature.WING_TYPE_BAT"; if (value == 6) return "Creature.WING_TYPE_BIRD"; if (value == 5) return "Creature.WING_TYPE_BUTTERFLY"; if (value == 1) return "Creature.WING_TYPE_DEMON"; if (value == 4) return "Creature.WING_TYPE_DRAGON"; if (value == 0) return "Creature.WING_TYPE_NONE"; return "Creature.(not found: " + value + ")"; } public static String nameOf(float value) { return "Creature.(not found: " + value + ")"; } public static String nameOf(String value) { return "Creature.(not found: " + value + ")"; } }
gpl-2.0
BiglySoftware/BiglyBT
core/src/com/biglybt/pif/ipfilter/IPBanned.java
1197
/* * File : IPBanned.java * Created : 08-Jan-2007 * By : jstockall * Copyright (C) Azureus Software, Inc, All Rights Reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details ( see the LICENSE file ). * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.biglybt.pif.ipfilter; /** * @author jstockall * @since 2.5.0.2 */ public interface IPBanned { public String getBannedIP(); /** * returns the torrent name the IP was banned by the user * @return */ public String getBannedTorrentName(); public long getBannedTime(); }
gpl-2.0
dkfellows/stendhal
src/games/stendhal/client/Triple.java
2762
/* $Id$ */ /*************************************************************************** * (C) Copyright 2003-2010 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.client; /** * A container for three objects. * * @param <P> type of first object * @param <S> type of second object * @param <T> type of third object */ public final class Triple<P, S, T> { // they are used in equals and hashcode private final P prim; private final S sec; private final T third; @Override public int hashCode() { final int prime = 31; int result = 1; int add; if (prim == null) { add = 0; } else { add = prim.hashCode(); } result = prime * result + add; if (sec == null) { add = 0; } else { add = sec.hashCode(); } result = prime * result + add; if (third == null) { add = 0; } else { add = third.hashCode(); } result = prime * result + add; return result; } @SuppressWarnings("unchecked") @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof Triple)) { return false; } final Triple<P, S , T> other = (Triple <P, S, T>) obj; return nullSafeEquals(prim, other.prim) && nullSafeEquals(sec, other.sec) && nullSafeEquals(third, other.third); } /** * Null safe equality check for objects. <b>Note: this should be replaced * with Objects.equals() once we start requiring java 7.</b> * * @param a first object * @param b second object * @return <code>true</code> if both <code>a</code> and <code>b</code> are * <code>null</code> or if they are equal otherwise. In any other case the * result is <code>false</code> */ private boolean nullSafeEquals(Object a, Object b) { if (a == null) { return b == null; } return a.equals(b); } /** * Create a triple. * * @param prim first object * @param sec second object * @param third third object */ public Triple(final P prim, final S sec, final T third) { this.prim = prim; this.sec = sec; this.third = third; } }
gpl-2.0
stormymauldin/stuff
src/main/org/tzi/use/gui/views/PrintableView.java
1182
/* * USE - UML based specification environment * Copyright (C) 1999-2004 Mark Richters, University of Bremen * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* $ProjectHeader: use 2-1-0-release.1 Sun, 09 May 2004 13:57:11 +0200 mr $ */ package org.tzi.use.gui.views; import java.awt.print.PageFormat; /** * Views with print facility implement this interface. * * @version $ProjectVersion: 2-1-0-release.1 $ * @author Mark Richters */ public interface PrintableView { void printView(PageFormat pf); }
gpl-2.0
lamsfoundation/lams
3rdParty_sources/mysql-connector/com/mysql/cj/CharsetMapping.java
50215
/* * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 2.0, as published by the * Free Software Foundation. * * This program is also distributed with certain software (including but not * limited to OpenSSL) that is licensed under separate terms, as designated in a * particular file or component or in included license documentation. The * authors of MySQL hereby grant you an additional permission to link the * program and your derivative works with the separately licensed software that * they have included with MySQL. * * Without limiting anything contained in the foregoing, this file, which is * part of MySQL Connector/J, is also subject to the Universal FOSS Exception, * version 1.0, a copy of which can be found at * http://oss.oracle.com/licenses/universal-foss-exception. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, * for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.mysql.cj; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeMap; /** * Mapping between MySQL charset names and Java charset names. I've investigated placing these in a .properties file, but unfortunately under most appservers * this complicates configuration because the security policy needs to be changed by the user to allow the driver to read them :( */ public class CharsetMapping { public static final int MAP_SIZE = 2048; // Size of static maps public static final String[] COLLATION_INDEX_TO_COLLATION_NAME; public static final MysqlCharset[] COLLATION_INDEX_TO_CHARSET; public static final Map<String, MysqlCharset> CHARSET_NAME_TO_CHARSET; public static final Map<String, Integer> CHARSET_NAME_TO_COLLATION_INDEX; private static final Map<String, List<MysqlCharset>> JAVA_ENCODING_UC_TO_MYSQL_CHARSET; private static final Set<String> MULTIBYTE_ENCODINGS; public static final Set<Integer> UTF8MB4_INDEXES; private static final String MYSQL_CHARSET_NAME_armscii8 = "armscii8"; private static final String MYSQL_CHARSET_NAME_ascii = "ascii"; private static final String MYSQL_CHARSET_NAME_big5 = "big5"; private static final String MYSQL_CHARSET_NAME_binary = "binary"; private static final String MYSQL_CHARSET_NAME_cp1250 = "cp1250"; private static final String MYSQL_CHARSET_NAME_cp1251 = "cp1251"; private static final String MYSQL_CHARSET_NAME_cp1256 = "cp1256"; private static final String MYSQL_CHARSET_NAME_cp1257 = "cp1257"; private static final String MYSQL_CHARSET_NAME_cp850 = "cp850"; private static final String MYSQL_CHARSET_NAME_cp852 = "cp852"; private static final String MYSQL_CHARSET_NAME_cp866 = "cp866"; private static final String MYSQL_CHARSET_NAME_cp932 = "cp932"; private static final String MYSQL_CHARSET_NAME_dec8 = "dec8"; private static final String MYSQL_CHARSET_NAME_eucjpms = "eucjpms"; private static final String MYSQL_CHARSET_NAME_euckr = "euckr"; private static final String MYSQL_CHARSET_NAME_gb18030 = "gb18030"; private static final String MYSQL_CHARSET_NAME_gb2312 = "gb2312"; private static final String MYSQL_CHARSET_NAME_gbk = "gbk"; private static final String MYSQL_CHARSET_NAME_geostd8 = "geostd8"; private static final String MYSQL_CHARSET_NAME_greek = "greek"; private static final String MYSQL_CHARSET_NAME_hebrew = "hebrew"; private static final String MYSQL_CHARSET_NAME_hp8 = "hp8"; private static final String MYSQL_CHARSET_NAME_keybcs2 = "keybcs2"; private static final String MYSQL_CHARSET_NAME_koi8r = "koi8r"; private static final String MYSQL_CHARSET_NAME_koi8u = "koi8u"; private static final String MYSQL_CHARSET_NAME_latin1 = "latin1"; private static final String MYSQL_CHARSET_NAME_latin2 = "latin2"; private static final String MYSQL_CHARSET_NAME_latin5 = "latin5"; private static final String MYSQL_CHARSET_NAME_latin7 = "latin7"; private static final String MYSQL_CHARSET_NAME_macce = "macce"; private static final String MYSQL_CHARSET_NAME_macroman = "macroman"; private static final String MYSQL_CHARSET_NAME_sjis = "sjis"; private static final String MYSQL_CHARSET_NAME_swe7 = "swe7"; private static final String MYSQL_CHARSET_NAME_tis620 = "tis620"; private static final String MYSQL_CHARSET_NAME_ucs2 = "ucs2"; private static final String MYSQL_CHARSET_NAME_ujis = "ujis"; private static final String MYSQL_CHARSET_NAME_utf16 = "utf16"; private static final String MYSQL_CHARSET_NAME_utf16le = "utf16le"; private static final String MYSQL_CHARSET_NAME_utf32 = "utf32"; private static final String MYSQL_CHARSET_NAME_utf8 = "utf8"; private static final String MYSQL_CHARSET_NAME_utf8mb4 = "utf8mb4"; public static final String NOT_USED = MYSQL_CHARSET_NAME_latin1; // punting for not-used character sets public static final String COLLATION_NOT_DEFINED = "none"; public static final int MYSQL_COLLATION_INDEX_utf8 = 33; public static final int MYSQL_COLLATION_INDEX_binary = 63; private static int numberOfEncodingsConfigured = 0; static { // complete list of mysql character sets and their corresponding java encoding names MysqlCharset[] charset = new MysqlCharset[] { new MysqlCharset(MYSQL_CHARSET_NAME_ascii, 1, 0, new String[] { "US-ASCII", "ASCII" }), new MysqlCharset(MYSQL_CHARSET_NAME_big5, 2, 0, new String[] { "Big5" }), new MysqlCharset(MYSQL_CHARSET_NAME_gbk, 2, 0, new String[] { "GBK" }), new MysqlCharset(MYSQL_CHARSET_NAME_sjis, 2, 0, new String[] { "SHIFT_JIS", "Cp943", "WINDOWS-31J" }), // SJIS is alias for SHIFT_JIS, Cp943 is rather a cp932 but we map it to sjis for years new MysqlCharset(MYSQL_CHARSET_NAME_cp932, 2, 1, new String[] { "WINDOWS-31J" }), // MS932 is alias for WINDOWS-31J new MysqlCharset(MYSQL_CHARSET_NAME_gb2312, 2, 0, new String[] { "GB2312" }), new MysqlCharset(MYSQL_CHARSET_NAME_ujis, 3, 0, new String[] { "EUC_JP" }), new MysqlCharset(MYSQL_CHARSET_NAME_eucjpms, 3, 0, new String[] { "EUC_JP_Solaris" }, new ServerVersion(5, 0, 3)), // "EUC_JP_Solaris = >5.0.3 eucjpms," new MysqlCharset(MYSQL_CHARSET_NAME_gb18030, 4, 0, new String[] { "GB18030" }, new ServerVersion(5, 7, 4)), new MysqlCharset(MYSQL_CHARSET_NAME_euckr, 2, 0, new String[] { "EUC-KR" }), new MysqlCharset(MYSQL_CHARSET_NAME_latin1, 1, 1, new String[] { "Cp1252", "ISO8859_1" }), new MysqlCharset(MYSQL_CHARSET_NAME_swe7, 1, 0, new String[] { "Cp1252" }), // new mapping, Cp1252 ? new MysqlCharset(MYSQL_CHARSET_NAME_hp8, 1, 0, new String[] { "Cp1252" }), // new mapping, Cp1252 ? new MysqlCharset(MYSQL_CHARSET_NAME_dec8, 1, 0, new String[] { "Cp1252" }), // new mapping, Cp1252 ? new MysqlCharset(MYSQL_CHARSET_NAME_armscii8, 1, 0, new String[] { "Cp1252" }), // new mapping, Cp1252 ? new MysqlCharset(MYSQL_CHARSET_NAME_geostd8, 1, 0, new String[] { "Cp1252" }), // new mapping, Cp1252 ? new MysqlCharset(MYSQL_CHARSET_NAME_latin2, 1, 0, new String[] { "ISO8859_2" }), // latin2 is an alias new MysqlCharset(MYSQL_CHARSET_NAME_greek, 1, 0, new String[] { "ISO8859_7", "greek" }), new MysqlCharset(MYSQL_CHARSET_NAME_latin7, 1, 0, new String[] { "ISO-8859-13" }), // was ISO8859_7, that's incorrect; also + "LATIN7 = latin7," is wrong java encoding name new MysqlCharset(MYSQL_CHARSET_NAME_hebrew, 1, 0, new String[] { "ISO8859_8" }), // hebrew is an alias new MysqlCharset(MYSQL_CHARSET_NAME_latin5, 1, 0, new String[] { "ISO8859_9" }), // LATIN5 is an alias new MysqlCharset(MYSQL_CHARSET_NAME_cp850, 1, 0, new String[] { "Cp850", "Cp437" }), new MysqlCharset(MYSQL_CHARSET_NAME_cp852, 1, 0, new String[] { "Cp852" }), new MysqlCharset(MYSQL_CHARSET_NAME_keybcs2, 1, 0, new String[] { "Cp852" }), // new, Kamenicky encoding usually known as Cp895 but there is no official cp895 specification; close to Cp852, see http://ftp.muni.cz/pub/localization/charsets/cs-encodings-faq new MysqlCharset(MYSQL_CHARSET_NAME_cp866, 1, 0, new String[] { "Cp866" }), new MysqlCharset(MYSQL_CHARSET_NAME_koi8r, 1, 1, new String[] { "KOI8_R" }), new MysqlCharset(MYSQL_CHARSET_NAME_koi8u, 1, 0, new String[] { "KOI8_R" }), new MysqlCharset(MYSQL_CHARSET_NAME_tis620, 1, 0, new String[] { "TIS620" }), new MysqlCharset(MYSQL_CHARSET_NAME_cp1250, 1, 0, new String[] { "Cp1250" }), new MysqlCharset(MYSQL_CHARSET_NAME_cp1251, 1, 1, new String[] { "Cp1251" }), new MysqlCharset(MYSQL_CHARSET_NAME_cp1256, 1, 0, new String[] { "Cp1256" }), new MysqlCharset(MYSQL_CHARSET_NAME_cp1257, 1, 0, new String[] { "Cp1257" }), new MysqlCharset(MYSQL_CHARSET_NAME_macroman, 1, 0, new String[] { "MacRoman" }), new MysqlCharset(MYSQL_CHARSET_NAME_macce, 1, 0, new String[] { "MacCentralEurope" }), new MysqlCharset(MYSQL_CHARSET_NAME_utf8, 3, 1, new String[] { "UTF-8" }), new MysqlCharset(MYSQL_CHARSET_NAME_utf8mb4, 4, 0, new String[] { "UTF-8" }), // "UTF-8 = *> 5.5.2 utf8mb4," new MysqlCharset(MYSQL_CHARSET_NAME_ucs2, 2, 0, new String[] { "UnicodeBig" }), new MysqlCharset(MYSQL_CHARSET_NAME_binary, 1, 1, new String[] { "ISO8859_1" }), // US-ASCII ? new MysqlCharset(MYSQL_CHARSET_NAME_utf16, 4, 0, new String[] { "UTF-16" }), new MysqlCharset(MYSQL_CHARSET_NAME_utf16le, 4, 0, new String[] { "UTF-16LE" }), new MysqlCharset(MYSQL_CHARSET_NAME_utf32, 4, 0, new String[] { "UTF-32" }) }; HashMap<String, MysqlCharset> charsetNameToMysqlCharsetMap = new HashMap<>(); HashMap<String, List<MysqlCharset>> javaUcToMysqlCharsetMap = new HashMap<>(); Set<String> tempMultibyteEncodings = new HashSet<>(); // Character sets that we can't convert ourselves. for (int i = 0; i < charset.length; i++) { String charsetName = charset[i].charsetName; charsetNameToMysqlCharsetMap.put(charsetName, charset[i]); numberOfEncodingsConfigured += charset[i].javaEncodingsUc.size(); for (String encUC : charset[i].javaEncodingsUc) { // fill javaUcToMysqlCharsetMap List<MysqlCharset> charsets = javaUcToMysqlCharsetMap.get(encUC); if (charsets == null) { charsets = new ArrayList<>(); javaUcToMysqlCharsetMap.put(encUC, charsets); } charsets.add(charset[i]); // fill multi-byte charsets if (charset[i].mblen > 1) { tempMultibyteEncodings.add(encUC); } } } CHARSET_NAME_TO_CHARSET = Collections.unmodifiableMap(charsetNameToMysqlCharsetMap); JAVA_ENCODING_UC_TO_MYSQL_CHARSET = Collections.unmodifiableMap(javaUcToMysqlCharsetMap); MULTIBYTE_ENCODINGS = Collections.unmodifiableSet(tempMultibyteEncodings); // complete list of mysql collations and their corresponding character sets each element of collation[1]..collation[MAP_SIZE-1] must not be null Collation[] collation = new Collation[MAP_SIZE]; collation[1] = new Collation(1, "big5_chinese_ci", 1, MYSQL_CHARSET_NAME_big5); collation[2] = new Collation(2, "latin2_czech_cs", 0, MYSQL_CHARSET_NAME_latin2); collation[3] = new Collation(3, "dec8_swedish_ci", 0, MYSQL_CHARSET_NAME_dec8); collation[4] = new Collation(4, "cp850_general_ci", 1, MYSQL_CHARSET_NAME_cp850); collation[5] = new Collation(5, "latin1_german1_ci", 1, MYSQL_CHARSET_NAME_latin1); collation[6] = new Collation(6, "hp8_english_ci", 0, MYSQL_CHARSET_NAME_hp8); collation[7] = new Collation(7, "koi8r_general_ci", 0, MYSQL_CHARSET_NAME_koi8r); collation[8] = new Collation(8, "latin1_swedish_ci", 0, MYSQL_CHARSET_NAME_latin1); collation[9] = new Collation(9, "latin2_general_ci", 1, MYSQL_CHARSET_NAME_latin2); collation[10] = new Collation(10, "swe7_swedish_ci", 0, MYSQL_CHARSET_NAME_swe7); collation[11] = new Collation(11, "ascii_general_ci", 0, MYSQL_CHARSET_NAME_ascii); collation[12] = new Collation(12, "ujis_japanese_ci", 0, MYSQL_CHARSET_NAME_ujis); collation[13] = new Collation(13, "sjis_japanese_ci", 0, MYSQL_CHARSET_NAME_sjis); collation[14] = new Collation(14, "cp1251_bulgarian_ci", 0, MYSQL_CHARSET_NAME_cp1251); collation[15] = new Collation(15, "latin1_danish_ci", 0, MYSQL_CHARSET_NAME_latin1); collation[16] = new Collation(16, "hebrew_general_ci", 0, MYSQL_CHARSET_NAME_hebrew); collation[18] = new Collation(18, "tis620_thai_ci", 0, MYSQL_CHARSET_NAME_tis620); collation[19] = new Collation(19, "euckr_korean_ci", 0, MYSQL_CHARSET_NAME_euckr); collation[20] = new Collation(20, "latin7_estonian_cs", 0, MYSQL_CHARSET_NAME_latin7); collation[21] = new Collation(21, "latin2_hungarian_ci", 0, MYSQL_CHARSET_NAME_latin2); collation[22] = new Collation(22, "koi8u_general_ci", 0, MYSQL_CHARSET_NAME_koi8u); collation[23] = new Collation(23, "cp1251_ukrainian_ci", 0, MYSQL_CHARSET_NAME_cp1251); collation[24] = new Collation(24, "gb2312_chinese_ci", 0, MYSQL_CHARSET_NAME_gb2312); collation[25] = new Collation(25, "greek_general_ci", 0, MYSQL_CHARSET_NAME_greek); collation[26] = new Collation(26, "cp1250_general_ci", 1, MYSQL_CHARSET_NAME_cp1250); collation[27] = new Collation(27, "latin2_croatian_ci", 0, MYSQL_CHARSET_NAME_latin2); collation[28] = new Collation(28, "gbk_chinese_ci", 1, MYSQL_CHARSET_NAME_gbk); collation[29] = new Collation(29, "cp1257_lithuanian_ci", 0, MYSQL_CHARSET_NAME_cp1257); collation[30] = new Collation(30, "latin5_turkish_ci", 1, MYSQL_CHARSET_NAME_latin5); collation[31] = new Collation(31, "latin1_german2_ci", 0, MYSQL_CHARSET_NAME_latin1); collation[32] = new Collation(32, "armscii8_general_ci", 0, MYSQL_CHARSET_NAME_armscii8); collation[33] = new Collation(33, "utf8_general_ci", 1, MYSQL_CHARSET_NAME_utf8); collation[34] = new Collation(34, "cp1250_czech_cs", 0, MYSQL_CHARSET_NAME_cp1250); collation[35] = new Collation(35, "ucs2_general_ci", 1, MYSQL_CHARSET_NAME_ucs2); collation[36] = new Collation(36, "cp866_general_ci", 1, MYSQL_CHARSET_NAME_cp866); collation[37] = new Collation(37, "keybcs2_general_ci", 1, MYSQL_CHARSET_NAME_keybcs2); collation[38] = new Collation(38, "macce_general_ci", 1, MYSQL_CHARSET_NAME_macce); collation[39] = new Collation(39, "macroman_general_ci", 1, MYSQL_CHARSET_NAME_macroman); collation[40] = new Collation(40, "cp852_general_ci", 1, MYSQL_CHARSET_NAME_cp852); collation[41] = new Collation(41, "latin7_general_ci", 1, MYSQL_CHARSET_NAME_latin7); collation[42] = new Collation(42, "latin7_general_cs", 0, MYSQL_CHARSET_NAME_latin7); collation[43] = new Collation(43, "macce_bin", 0, MYSQL_CHARSET_NAME_macce); collation[44] = new Collation(44, "cp1250_croatian_ci", 0, MYSQL_CHARSET_NAME_cp1250); collation[45] = new Collation(45, "utf8mb4_general_ci", 1, MYSQL_CHARSET_NAME_utf8mb4); collation[46] = new Collation(46, "utf8mb4_bin", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[47] = new Collation(47, "latin1_bin", 0, MYSQL_CHARSET_NAME_latin1); collation[48] = new Collation(48, "latin1_general_ci", 0, MYSQL_CHARSET_NAME_latin1); collation[49] = new Collation(49, "latin1_general_cs", 0, MYSQL_CHARSET_NAME_latin1); collation[50] = new Collation(50, "cp1251_bin", 0, MYSQL_CHARSET_NAME_cp1251); collation[51] = new Collation(51, "cp1251_general_ci", 1, MYSQL_CHARSET_NAME_cp1251); collation[52] = new Collation(52, "cp1251_general_cs", 0, MYSQL_CHARSET_NAME_cp1251); collation[53] = new Collation(53, "macroman_bin", 0, MYSQL_CHARSET_NAME_macroman); collation[54] = new Collation(54, "utf16_general_ci", 1, MYSQL_CHARSET_NAME_utf16); collation[55] = new Collation(55, "utf16_bin", 0, MYSQL_CHARSET_NAME_utf16); collation[56] = new Collation(56, "utf16le_general_ci", 1, MYSQL_CHARSET_NAME_utf16le); collation[57] = new Collation(57, "cp1256_general_ci", 1, MYSQL_CHARSET_NAME_cp1256); collation[58] = new Collation(58, "cp1257_bin", 0, MYSQL_CHARSET_NAME_cp1257); collation[59] = new Collation(59, "cp1257_general_ci", 1, MYSQL_CHARSET_NAME_cp1257); collation[60] = new Collation(60, "utf32_general_ci", 1, MYSQL_CHARSET_NAME_utf32); collation[61] = new Collation(61, "utf32_bin", 0, MYSQL_CHARSET_NAME_utf32); collation[62] = new Collation(62, "utf16le_bin", 0, MYSQL_CHARSET_NAME_utf16le); collation[63] = new Collation(63, "binary", 1, MYSQL_CHARSET_NAME_binary); collation[64] = new Collation(64, "armscii8_bin", 0, MYSQL_CHARSET_NAME_armscii8); collation[65] = new Collation(65, "ascii_bin", 0, MYSQL_CHARSET_NAME_ascii); collation[66] = new Collation(66, "cp1250_bin", 0, MYSQL_CHARSET_NAME_cp1250); collation[67] = new Collation(67, "cp1256_bin", 0, MYSQL_CHARSET_NAME_cp1256); collation[68] = new Collation(68, "cp866_bin", 0, MYSQL_CHARSET_NAME_cp866); collation[69] = new Collation(69, "dec8_bin", 0, MYSQL_CHARSET_NAME_dec8); collation[70] = new Collation(70, "greek_bin", 0, MYSQL_CHARSET_NAME_greek); collation[71] = new Collation(71, "hebrew_bin", 0, MYSQL_CHARSET_NAME_hebrew); collation[72] = new Collation(72, "hp8_bin", 0, MYSQL_CHARSET_NAME_hp8); collation[73] = new Collation(73, "keybcs2_bin", 0, MYSQL_CHARSET_NAME_keybcs2); collation[74] = new Collation(74, "koi8r_bin", 0, MYSQL_CHARSET_NAME_koi8r); collation[75] = new Collation(75, "koi8u_bin", 0, MYSQL_CHARSET_NAME_koi8u); collation[76] = new Collation(76, "utf8_tolower_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[77] = new Collation(77, "latin2_bin", 0, MYSQL_CHARSET_NAME_latin2); collation[78] = new Collation(78, "latin5_bin", 0, MYSQL_CHARSET_NAME_latin5); collation[79] = new Collation(79, "latin7_bin", 0, MYSQL_CHARSET_NAME_latin7); collation[80] = new Collation(80, "cp850_bin", 0, MYSQL_CHARSET_NAME_cp850); collation[81] = new Collation(81, "cp852_bin", 0, MYSQL_CHARSET_NAME_cp852); collation[82] = new Collation(82, "swe7_bin", 0, MYSQL_CHARSET_NAME_swe7); collation[83] = new Collation(83, "utf8_bin", 0, MYSQL_CHARSET_NAME_utf8); collation[84] = new Collation(84, "big5_bin", 0, MYSQL_CHARSET_NAME_big5); collation[85] = new Collation(85, "euckr_bin", 0, MYSQL_CHARSET_NAME_euckr); collation[86] = new Collation(86, "gb2312_bin", 0, MYSQL_CHARSET_NAME_gb2312); collation[87] = new Collation(87, "gbk_bin", 0, MYSQL_CHARSET_NAME_gbk); collation[88] = new Collation(88, "sjis_bin", 0, MYSQL_CHARSET_NAME_sjis); collation[89] = new Collation(89, "tis620_bin", 0, MYSQL_CHARSET_NAME_tis620); collation[90] = new Collation(90, "ucs2_bin", 0, MYSQL_CHARSET_NAME_ucs2); collation[91] = new Collation(91, "ujis_bin", 0, MYSQL_CHARSET_NAME_ujis); collation[92] = new Collation(92, "geostd8_general_ci", 0, MYSQL_CHARSET_NAME_geostd8); collation[93] = new Collation(93, "geostd8_bin", 0, MYSQL_CHARSET_NAME_geostd8); collation[94] = new Collation(94, "latin1_spanish_ci", 0, MYSQL_CHARSET_NAME_latin1); collation[95] = new Collation(95, "cp932_japanese_ci", 1, MYSQL_CHARSET_NAME_cp932); collation[96] = new Collation(96, "cp932_bin", 0, MYSQL_CHARSET_NAME_cp932); collation[97] = new Collation(97, "eucjpms_japanese_ci", 1, MYSQL_CHARSET_NAME_eucjpms); collation[98] = new Collation(98, "eucjpms_bin", 0, MYSQL_CHARSET_NAME_eucjpms); collation[99] = new Collation(99, "cp1250_polish_ci", 0, MYSQL_CHARSET_NAME_cp1250); collation[101] = new Collation(101, "utf16_unicode_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[102] = new Collation(102, "utf16_icelandic_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[103] = new Collation(103, "utf16_latvian_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[104] = new Collation(104, "utf16_romanian_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[105] = new Collation(105, "utf16_slovenian_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[106] = new Collation(106, "utf16_polish_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[107] = new Collation(107, "utf16_estonian_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[108] = new Collation(108, "utf16_spanish_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[109] = new Collation(109, "utf16_swedish_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[110] = new Collation(110, "utf16_turkish_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[111] = new Collation(111, "utf16_czech_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[112] = new Collation(112, "utf16_danish_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[113] = new Collation(113, "utf16_lithuanian_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[114] = new Collation(114, "utf16_slovak_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[115] = new Collation(115, "utf16_spanish2_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[116] = new Collation(116, "utf16_roman_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[117] = new Collation(117, "utf16_persian_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[118] = new Collation(118, "utf16_esperanto_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[119] = new Collation(119, "utf16_hungarian_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[120] = new Collation(120, "utf16_sinhala_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[121] = new Collation(121, "utf16_german2_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[122] = new Collation(122, "utf16_croatian_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[123] = new Collation(123, "utf16_unicode_520_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[124] = new Collation(124, "utf16_vietnamese_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[128] = new Collation(128, "ucs2_unicode_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[129] = new Collation(129, "ucs2_icelandic_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[130] = new Collation(130, "ucs2_latvian_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[131] = new Collation(131, "ucs2_romanian_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[132] = new Collation(132, "ucs2_slovenian_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[133] = new Collation(133, "ucs2_polish_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[134] = new Collation(134, "ucs2_estonian_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[135] = new Collation(135, "ucs2_spanish_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[136] = new Collation(136, "ucs2_swedish_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[137] = new Collation(137, "ucs2_turkish_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[138] = new Collation(138, "ucs2_czech_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[139] = new Collation(139, "ucs2_danish_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[140] = new Collation(140, "ucs2_lithuanian_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[141] = new Collation(141, "ucs2_slovak_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[142] = new Collation(142, "ucs2_spanish2_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[143] = new Collation(143, "ucs2_roman_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[144] = new Collation(144, "ucs2_persian_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[145] = new Collation(145, "ucs2_esperanto_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[146] = new Collation(146, "ucs2_hungarian_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[147] = new Collation(147, "ucs2_sinhala_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[148] = new Collation(148, "ucs2_german2_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[149] = new Collation(149, "ucs2_croatian_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[150] = new Collation(150, "ucs2_unicode_520_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[151] = new Collation(151, "ucs2_vietnamese_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[159] = new Collation(159, "ucs2_general_mysql500_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[160] = new Collation(160, "utf32_unicode_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[161] = new Collation(161, "utf32_icelandic_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[162] = new Collation(162, "utf32_latvian_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[163] = new Collation(163, "utf32_romanian_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[164] = new Collation(164, "utf32_slovenian_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[165] = new Collation(165, "utf32_polish_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[166] = new Collation(166, "utf32_estonian_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[167] = new Collation(167, "utf32_spanish_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[168] = new Collation(168, "utf32_swedish_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[169] = new Collation(169, "utf32_turkish_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[170] = new Collation(170, "utf32_czech_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[171] = new Collation(171, "utf32_danish_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[172] = new Collation(172, "utf32_lithuanian_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[173] = new Collation(173, "utf32_slovak_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[174] = new Collation(174, "utf32_spanish2_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[175] = new Collation(175, "utf32_roman_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[176] = new Collation(176, "utf32_persian_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[177] = new Collation(177, "utf32_esperanto_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[178] = new Collation(178, "utf32_hungarian_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[179] = new Collation(179, "utf32_sinhala_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[180] = new Collation(180, "utf32_german2_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[181] = new Collation(181, "utf32_croatian_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[182] = new Collation(182, "utf32_unicode_520_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[183] = new Collation(183, "utf32_vietnamese_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[192] = new Collation(192, "utf8_unicode_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[193] = new Collation(193, "utf8_icelandic_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[194] = new Collation(194, "utf8_latvian_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[195] = new Collation(195, "utf8_romanian_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[196] = new Collation(196, "utf8_slovenian_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[197] = new Collation(197, "utf8_polish_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[198] = new Collation(198, "utf8_estonian_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[199] = new Collation(199, "utf8_spanish_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[200] = new Collation(200, "utf8_swedish_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[201] = new Collation(201, "utf8_turkish_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[202] = new Collation(202, "utf8_czech_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[203] = new Collation(203, "utf8_danish_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[204] = new Collation(204, "utf8_lithuanian_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[205] = new Collation(205, "utf8_slovak_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[206] = new Collation(206, "utf8_spanish2_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[207] = new Collation(207, "utf8_roman_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[208] = new Collation(208, "utf8_persian_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[209] = new Collation(209, "utf8_esperanto_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[210] = new Collation(210, "utf8_hungarian_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[211] = new Collation(211, "utf8_sinhala_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[212] = new Collation(212, "utf8_german2_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[213] = new Collation(213, "utf8_croatian_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[214] = new Collation(214, "utf8_unicode_520_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[215] = new Collation(215, "utf8_vietnamese_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[223] = new Collation(223, "utf8_general_mysql500_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[224] = new Collation(224, "utf8mb4_unicode_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[225] = new Collation(225, "utf8mb4_icelandic_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[226] = new Collation(226, "utf8mb4_latvian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[227] = new Collation(227, "utf8mb4_romanian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[228] = new Collation(228, "utf8mb4_slovenian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[229] = new Collation(229, "utf8mb4_polish_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[230] = new Collation(230, "utf8mb4_estonian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[231] = new Collation(231, "utf8mb4_spanish_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[232] = new Collation(232, "utf8mb4_swedish_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[233] = new Collation(233, "utf8mb4_turkish_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[234] = new Collation(234, "utf8mb4_czech_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[235] = new Collation(235, "utf8mb4_danish_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[236] = new Collation(236, "utf8mb4_lithuanian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[237] = new Collation(237, "utf8mb4_slovak_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[238] = new Collation(238, "utf8mb4_spanish2_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[239] = new Collation(239, "utf8mb4_roman_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[240] = new Collation(240, "utf8mb4_persian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[241] = new Collation(241, "utf8mb4_esperanto_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[242] = new Collation(242, "utf8mb4_hungarian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[243] = new Collation(243, "utf8mb4_sinhala_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[244] = new Collation(244, "utf8mb4_german2_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[245] = new Collation(245, "utf8mb4_croatian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[246] = new Collation(246, "utf8mb4_unicode_520_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[247] = new Collation(247, "utf8mb4_vietnamese_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[248] = new Collation(248, "gb18030_chinese_ci", 1, MYSQL_CHARSET_NAME_gb18030); collation[249] = new Collation(249, "gb18030_bin", 0, MYSQL_CHARSET_NAME_gb18030); collation[250] = new Collation(250, "gb18030_unicode_520_ci", 0, MYSQL_CHARSET_NAME_gb18030); collation[255] = new Collation(255, "utf8mb4_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[256] = new Collation(256, "utf8mb4_de_pb_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[257] = new Collation(257, "utf8mb4_is_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[258] = new Collation(258, "utf8mb4_lv_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[259] = new Collation(259, "utf8mb4_ro_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[260] = new Collation(260, "utf8mb4_sl_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[261] = new Collation(261, "utf8mb4_pl_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[262] = new Collation(262, "utf8mb4_et_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[263] = new Collation(263, "utf8mb4_es_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[264] = new Collation(264, "utf8mb4_sv_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[265] = new Collation(265, "utf8mb4_tr_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[266] = new Collation(266, "utf8mb4_cs_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[267] = new Collation(267, "utf8mb4_da_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[268] = new Collation(268, "utf8mb4_lt_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[269] = new Collation(269, "utf8mb4_sk_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[270] = new Collation(270, "utf8mb4_es_trad_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[271] = new Collation(271, "utf8mb4_la_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[273] = new Collation(273, "utf8mb4_eo_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[274] = new Collation(274, "utf8mb4_hu_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[275] = new Collation(275, "utf8mb4_hr_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[277] = new Collation(277, "utf8mb4_vi_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[278] = new Collation(278, "utf8mb4_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[279] = new Collation(279, "utf8mb4_de_pb_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[280] = new Collation(280, "utf8mb4_is_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[281] = new Collation(281, "utf8mb4_lv_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[282] = new Collation(282, "utf8mb4_ro_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[283] = new Collation(283, "utf8mb4_sl_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[284] = new Collation(284, "utf8mb4_pl_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[285] = new Collation(285, "utf8mb4_et_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[286] = new Collation(286, "utf8mb4_es_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[287] = new Collation(287, "utf8mb4_sv_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[288] = new Collation(288, "utf8mb4_tr_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[289] = new Collation(289, "utf8mb4_cs_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[290] = new Collation(290, "utf8mb4_da_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[291] = new Collation(291, "utf8mb4_lt_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[292] = new Collation(292, "utf8mb4_sk_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[293] = new Collation(293, "utf8mb4_es_trad_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[294] = new Collation(294, "utf8mb4_la_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[296] = new Collation(296, "utf8mb4_eo_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[297] = new Collation(297, "utf8mb4_hu_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[298] = new Collation(298, "utf8mb4_hr_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[300] = new Collation(300, "utf8mb4_vi_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[303] = new Collation(303, "utf8mb4_ja_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[304] = new Collation(304, "utf8mb4_ja_0900_as_cs_ks", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[305] = new Collation(305, "utf8mb4_0900_as_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[306] = new Collation(306, "utf8mb4_ru_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[307] = new Collation(307, "utf8mb4_ru_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[326] = new Collation(326, "utf8mb4_test_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[327] = new Collation(327, "utf16_test_ci", 0, MYSQL_CHARSET_NAME_utf16); collation[328] = new Collation(328, "utf8mb4_test_400_ci", 0, MYSQL_CHARSET_NAME_utf8mb4); collation[336] = new Collation(336, "utf8_bengali_standard_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[337] = new Collation(337, "utf8_bengali_traditional_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[352] = new Collation(352, "utf8_phone_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[353] = new Collation(353, "utf8_test_ci", 0, MYSQL_CHARSET_NAME_utf8); collation[354] = new Collation(354, "utf8_5624_1", 0, MYSQL_CHARSET_NAME_utf8); collation[355] = new Collation(355, "utf8_5624_2", 0, MYSQL_CHARSET_NAME_utf8); collation[356] = new Collation(356, "utf8_5624_3", 0, MYSQL_CHARSET_NAME_utf8); collation[357] = new Collation(357, "utf8_5624_4", 0, MYSQL_CHARSET_NAME_utf8); collation[358] = new Collation(358, "ucs2_test_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[359] = new Collation(359, "ucs2_vn_ci", 0, MYSQL_CHARSET_NAME_ucs2); collation[360] = new Collation(360, "ucs2_5624_1", 0, MYSQL_CHARSET_NAME_ucs2); collation[368] = new Collation(368, "utf8_5624_5", 0, MYSQL_CHARSET_NAME_utf8); collation[391] = new Collation(391, "utf32_test_ci", 0, MYSQL_CHARSET_NAME_utf32); collation[2047] = new Collation(2047, "utf8_maxuserid_ci", 0, MYSQL_CHARSET_NAME_utf8); COLLATION_INDEX_TO_COLLATION_NAME = new String[MAP_SIZE]; COLLATION_INDEX_TO_CHARSET = new MysqlCharset[MAP_SIZE]; Map<String, Integer> charsetNameToCollationIndexMap = new TreeMap<>(); Map<String, Integer> charsetNameToCollationPriorityMap = new TreeMap<>(); Set<Integer> tempUTF8MB4Indexes = new HashSet<>(); Collation notUsedCollation = new Collation(0, COLLATION_NOT_DEFINED, 0, NOT_USED); for (int i = 1; i < MAP_SIZE; i++) { Collation coll = collation[i] != null ? collation[i] : notUsedCollation; COLLATION_INDEX_TO_COLLATION_NAME[i] = coll.collationName; COLLATION_INDEX_TO_CHARSET[i] = coll.mysqlCharset; String charsetName = coll.mysqlCharset.charsetName; if (!charsetNameToCollationIndexMap.containsKey(charsetName) || charsetNameToCollationPriorityMap.get(charsetName) < coll.priority) { charsetNameToCollationIndexMap.put(charsetName, i); charsetNameToCollationPriorityMap.put(charsetName, coll.priority); } // Filling indexes of utf8mb4 collations if (charsetName.equals(MYSQL_CHARSET_NAME_utf8mb4)) { tempUTF8MB4Indexes.add(i); } } CHARSET_NAME_TO_COLLATION_INDEX = Collections.unmodifiableMap(charsetNameToCollationIndexMap); UTF8MB4_INDEXES = Collections.unmodifiableSet(tempUTF8MB4Indexes); collation = null; } public final static String getMysqlCharsetForJavaEncoding(String javaEncoding, ServerVersion version) { List<MysqlCharset> mysqlCharsets = CharsetMapping.JAVA_ENCODING_UC_TO_MYSQL_CHARSET.get(javaEncoding.toUpperCase(Locale.ENGLISH)); if (mysqlCharsets != null) { Iterator<MysqlCharset> iter = mysqlCharsets.iterator(); MysqlCharset currentChoice = null; while (iter.hasNext()) { MysqlCharset charset = iter.next(); if (version == null) { // Take the first one we get return charset.charsetName; } if (currentChoice == null || currentChoice.minimumVersion.compareTo(charset.minimumVersion) < 0 || currentChoice.priority < charset.priority && currentChoice.minimumVersion.compareTo(charset.minimumVersion) == 0) { if (charset.isOkayForVersion(version)) { currentChoice = charset; } } } if (currentChoice != null) { return currentChoice.charsetName; } } return null; } public static int getCollationIndexForJavaEncoding(String javaEncoding, ServerVersion version) { String charsetName = getMysqlCharsetForJavaEncoding(javaEncoding, version); if (charsetName != null) { Integer ci = CHARSET_NAME_TO_COLLATION_INDEX.get(charsetName); if (ci != null) { return ci.intValue(); } } return 0; } public static String getMysqlCharsetNameForCollationIndex(Integer collationIndex) { if (collationIndex != null && collationIndex > 0 && collationIndex < MAP_SIZE) { return COLLATION_INDEX_TO_CHARSET[collationIndex].charsetName; } return null; } /** * MySQL charset could map to several Java encodings. * So here we choose the one according to next rules: * <ul> * <li>if there is no static mapping for this charset then return javaEncoding value as is because this * could be a custom charset for example * <li>if static mapping exists and javaEncoding equals to one of Java encoding canonical names or aliases available * for this mapping then javaEncoding value as is; this is required when result should match to connection encoding, for example if connection encoding is * Cp943 we must avoid getting SHIFT_JIS for sjis mysql charset * <li>if static mapping exists and javaEncoding doesn't match any Java encoding canonical * names or aliases available for this mapping then return default Java encoding (the first in mapping list) * </ul> * * @param mysqlCharsetName * MySQL charset name * @param javaEncoding * fall-back java encoding name * @return java encoding name */ public static String getJavaEncodingForMysqlCharset(String mysqlCharsetName, String javaEncoding) { String res = javaEncoding; MysqlCharset cs = CHARSET_NAME_TO_CHARSET.get(mysqlCharsetName); if (cs != null) { res = cs.getMatchingJavaEncoding(javaEncoding); } return res; } public static String getJavaEncodingForMysqlCharset(String mysqlCharsetName) { return getJavaEncodingForMysqlCharset(mysqlCharsetName, null); } public static String getJavaEncodingForCollationIndex(Integer collationIndex, String javaEncoding) { if (collationIndex != null && collationIndex > 0 && collationIndex < MAP_SIZE) { MysqlCharset cs = COLLATION_INDEX_TO_CHARSET[collationIndex]; return cs.getMatchingJavaEncoding(javaEncoding); } return null; } public static String getJavaEncodingForCollationIndex(Integer collationIndex) { return getJavaEncodingForCollationIndex(collationIndex, null); } public final static int getNumberOfCharsetsConfigured() { return numberOfEncodingsConfigured; } /** * Does the character set contain multi-byte encoded characters. * * @param javaEncodingName * java encoding name * @return true if the character set contains multi-byte encoded characters. */ final public static boolean isMultibyteCharset(String javaEncodingName) { return MULTIBYTE_ENCODINGS.contains(javaEncodingName.toUpperCase(Locale.ENGLISH)); } public static int getMblen(String charsetName) { if (charsetName != null) { MysqlCharset cs = CHARSET_NAME_TO_CHARSET.get(charsetName); if (cs != null) { return cs.mblen; } } return 0; } } class MysqlCharset { public final String charsetName; public final int mblen; public final int priority; public final List<String> javaEncodingsUc = new ArrayList<>(); public final ServerVersion minimumVersion; /** * Constructs MysqlCharset object * * @param charsetName * MySQL charset name * @param mblen * Max number of bytes per character * @param priority * MysqlCharset with highest value of this param will be used for Java encoding --&gt; Mysql charsets conversion. * @param javaEncodings * List of Java encodings corresponding to this MySQL charset; the first name in list is the default for mysql --&gt; java data conversion */ public MysqlCharset(String charsetName, int mblen, int priority, String[] javaEncodings) { this(charsetName, mblen, priority, javaEncodings, new ServerVersion(0, 0, 0)); } private void addEncodingMapping(String encoding) { String encodingUc = encoding.toUpperCase(Locale.ENGLISH); if (!this.javaEncodingsUc.contains(encodingUc)) { this.javaEncodingsUc.add(encodingUc); } } public MysqlCharset(String charsetName, int mblen, int priority, String[] javaEncodings, ServerVersion minimumVersion) { this.charsetName = charsetName; this.mblen = mblen; this.priority = priority; for (int i = 0; i < javaEncodings.length; i++) { String encoding = javaEncodings[i]; try { Charset cs = Charset.forName(encoding); addEncodingMapping(cs.name()); Set<String> als = cs.aliases(); Iterator<String> ali = als.iterator(); while (ali.hasNext()) { addEncodingMapping(ali.next()); } } catch (Exception e) { // if there is no support of this charset in JVM it's still possible to use our converter for 1-byte charsets if (mblen == 1) { addEncodingMapping(encoding); } } } if (this.javaEncodingsUc.size() == 0) { if (mblen > 1) { addEncodingMapping("UTF-8"); } else { addEncodingMapping("Cp1252"); } } this.minimumVersion = minimumVersion; } @Override public String toString() { StringBuilder asString = new StringBuilder(); asString.append("["); asString.append("charsetName="); asString.append(this.charsetName); asString.append(",mblen="); asString.append(this.mblen); // asString.append(",javaEncoding="); // asString.append(this.javaEncodings.toString()); asString.append("]"); return asString.toString(); } boolean isOkayForVersion(ServerVersion version) { return version.meetsMinimum(this.minimumVersion); } /** * If javaEncoding parameter value is one of available java encodings for this charset * then returns javaEncoding value as is. Otherwise returns first available java encoding name. * * @param javaEncoding * java encoding name * @return java encoding name */ String getMatchingJavaEncoding(String javaEncoding) { if (javaEncoding != null && this.javaEncodingsUc.contains(javaEncoding.toUpperCase(Locale.ENGLISH))) { return javaEncoding; } return this.javaEncodingsUc.get(0); } } class Collation { public final int index; public final String collationName; public final int priority; public final MysqlCharset mysqlCharset; public Collation(int index, String collationName, int priority, String charsetName) { this.index = index; this.collationName = collationName; this.priority = priority; this.mysqlCharset = CharsetMapping.CHARSET_NAME_TO_CHARSET.get(charsetName); } @Override public String toString() { StringBuilder asString = new StringBuilder(); asString.append("["); asString.append("index="); asString.append(this.index); asString.append(",collationName="); asString.append(this.collationName); asString.append(",charsetName="); asString.append(this.mysqlCharset.charsetName); asString.append(",javaCharsetName="); asString.append(this.mysqlCharset.getMatchingJavaEncoding(null)); asString.append("]"); return asString.toString(); } }
gpl-2.0
zeminlu/comitaco
unittest/ar/edu/taco/regresion/taco/singlylinkedlist/ExamplesBaseSinglyLinkedListTest.java
3303
/* * TACO: Translation of Annotated COde * Copyright (c) 2010 Universidad de Buenos Aires * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA, * 02110-1301, USA */ package ar.edu.taco.regresion.taco.singlylinkedlist; import ar.edu.taco.regresion.CollectionTestBase; import ar.edu.taco.regresion.GenericTestBase; import ar.uba.dc.rfm.dynalloy.visualization.VizException; public class ExamplesBaseSinglyLinkedListTest extends CollectionTestBase { @Override protected String getClassToCheck() { return "examples.singlylinkedlist.base.SinglyLinkedList"; } public void test_contains() throws VizException { setConfigKeyRelevantClasses("examples.singlylinkedlist.base.SinglyLinkedList,examples.singlylinkedlist.base.SinglyLinkedListNode"); setConfigKeyRelevancyAnalysis(true); setConfigKeyCheckNullDereference(true); setConfigKeyUseJavaArithmetic(false); setConfigKeyObjectScope(3); setConfigKeyInferScope(false); setConfigKeyTypeScopes("examples.singlylinkedlist.base.SinglyLinkedList:1,examples.singlylinkedlist.base.SinglyLinkedListNode:2"); setConfigKeySkolemizeInstanceInvariant(true); setConfigKeySkolemizeInstanceAbstraction(true); setConfigKeyGenerateUnitTestCase(false); simulate(GENERIC_PROPERTIES,"contains_0"); } public void test_insertBack() throws VizException { setConfigKeyRelevantClasses("examples.singlylinkedlist.base.SinglyLinkedList,examples.singlylinkedlist.base.SinglyLinkedListNode"); setConfigKeyRelevancyAnalysis(true); setConfigKeyCheckNullDereference(true); setConfigKeyUseJavaArithmetic(false); setConfigKeyObjectScope(3); setConfigKeyInferScope(false); setConfigKeyTypeScopes("examples.singlylinkedlist.base.SinglyLinkedList:1,examples.singlylinkedlist.base.SinglyLinkedListNode:2"); setConfigKeySkolemizeInstanceInvariant(true); setConfigKeySkolemizeInstanceAbstraction(true); setConfigKeyGenerateUnitTestCase(false); simulate(GENERIC_PROPERTIES,"insertBack_0"); } public void test_remove() throws VizException { setConfigKeyRelevantClasses("examples.singlylinkedlist.base.SinglyLinkedList,examples.singlylinkedlist.base.SinglyLinkedListNode"); setConfigKeyRelevancyAnalysis(true); setConfigKeyCheckNullDereference(true); setConfigKeyUseJavaArithmetic(false); setConfigKeyObjectScope(3); setConfigKeyInferScope(false); setConfigKeyTypeScopes("examples.singlylinkedlist.base.SinglyLinkedList:1,examples.singlylinkedlist.base.SinglyLinkedListNode:2"); setConfigKeySkolemizeInstanceInvariant(true); setConfigKeySkolemizeInstanceAbstraction(true); setConfigKeyGenerateUnitTestCase(false); simulate(GENERIC_PROPERTIES,"remove_0"); } }
gpl-3.0
federicomartinlara1976/chronos-libs
chronos-utils/src/main/java/net/bounceme/chronos/utils/assemblers/GenericAssembler.java
2716
package net.bounceme.chronos.utils.assemblers; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.bounceme.chronos.utils.common.Constantes; import net.bounceme.chronos.utils.exceptions.AssembleException; /** * Clase genérica que implementa el comportamiento de Assembler. Sigue el patrón * de diseño template-method. * * @author frederik * * @param <SOURCE> * @param <TARGET> */ public abstract class GenericAssembler<SOURCE, TARGET> implements Assembler<SOURCE, TARGET> { protected Logger logger = LoggerFactory.getLogger(GenericAssembler.class); private Class<SOURCE> classSource; private Class<TARGET> classTarget; public GenericAssembler(Class<SOURCE> classSource, Class<TARGET> classTarget) { this.classSource = classSource; this.classTarget = classTarget; } /** * @return * @throws AssembleException */ protected SOURCE newSourceInstance() { try { return (classSource!=null) ? (SOURCE) classSource.newInstance() : null; } catch (InstantiationException | IllegalAccessException e) { return null; } } /** * @return * @throws AssembleException */ protected TARGET newTargetInstance() { try { return (classTarget!=null) ? (TARGET) classTarget.newInstance() : null; } catch (InstantiationException | IllegalAccessException e) { logger.error(e.getMessage()); return null; } } /** * @return */ protected Class<SOURCE> getClassSource() { return classSource; } /** * @return */ protected Class<TARGET> getClassTarget() { return classTarget; } /* (non-Javadoc) * @see net.bounceme.chronos.utils.assemblers.Assembler#assemble(java.util.Collection) */ public final Collection<TARGET> assemble(Collection<SOURCE> source) { if (source == null || source.isEmpty()) { return new ArrayList<TARGET>(0); } List<TARGET> items = new ArrayList<TARGET>(source.size()); for (SOURCE s : source) { items.add(assemble(s)); } return items; } /* (non-Javadoc) * @see net.bounceme.chronos.utils.assemblers.Assembler#assemble(java.util.Collection) */ @SuppressWarnings(Constantes.UNCHECKED) public final TARGET[] assemble(SOURCE[] source) { if (source == null || source.length == 0) { return null; } TARGET[] items = (TARGET[]) Array.newInstance(classTarget, source.length); int index = 0; for (SOURCE s : source) { items[index] = assemble(s); index++; } return items; } }
gpl-3.0
14mRh4X0r/ForgeEssentialsMain
src/main/java/com/forgeessentials/util/AreaSelector/WorldArea.java
1671
package com.forgeessentials.util.AreaSelector; import net.minecraft.world.World; import com.forgeessentials.data.api.SaveableObject.SaveableField; import com.forgeessentials.data.api.SaveableObject.UniqueLoadingKey; public class WorldArea extends AreaBase { @SaveableField public int dim; public WorldArea(World world, Point start, Point end) { super(start, end); dim = world.provider.dimensionId; } public WorldArea(int dim, Point start, Point end) { super(start, end); this.dim = dim; } public WorldArea(int dim, AreaBase area) { super(area.getHighPoint(), area.getLowPoint()); this.dim = dim; } public WorldArea(World world, AreaBase area) { super(area.getHighPoint(), area.getLowPoint()); dim = world.provider.dimensionId; } public boolean contains(WorldPoint p) { if (p.dim == dim) return super.contains(p); else return false; } public boolean contains(WorldArea area) { if (area.dim == dim) return super.contains(area); else return false; } public boolean intersectsWith(WorldArea area) { if (area.dim == dim) return super.intersectsWith(area); else return false; } public AreaBase getIntersection(WorldArea area) { if (area.dim == dim) return super.getIntersection(area); else return null; } public boolean makesCuboidWith(WorldArea area) { if (area.dim == dim) return super.makesCuboidWith(area); else return false; } @UniqueLoadingKey() private String getLoadingField() { return "WorldArea" + this; } @Override public String toString() { return " { " + dim + " , " + getHighPoint().toString() + " , " + getLowPoint().toString() + " }"; } }
gpl-3.0
Quntn/projetPOX
src/main/java/io/robusta/upload/api/DeleteFileDropboxServlet.java
1142
package io.robusta.upload.api; import java.io.IOException; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/deletefiledropbox") @MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB maxFileSize = 1024 * 1024 * 10, // 10MB maxRequestSize = 1024 * 1024 * 50) // 50MB public class DeleteFileDropboxServlet extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; @EJB private DropboxService dbs; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { String path = req.getParameter("filename"); dbs.delete("/"+path); resp.sendRedirect(req.getContextPath() + "/accueil"); } catch (Exception e) { e.printStackTrace(); req.setAttribute("message", "Erreur de fichier, réessayez"); resp.sendRedirect(req.getContextPath() + "/accueil"); } } }
gpl-3.0
Malandrix/Explosion-Man
Explosion Man/src/com/gmail/bunnehrealm/explosionman/MainClass.java
8770
/*Explosion Man for general explosions on Bukkit Copyright (C) 2013 Rory Finnegan 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.gmail.bunnehrealm.explosionman; import java.io.File; import java.io.IOException; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import com.gmail.bunnehrealm.explosionman.Listeners.Deathclass; import com.gmail.bunnehrealm.explosionman.Listeners.PreventDamage; import com.gmail.bunnehrealm.explosionman.Listeners.PreventFlyKick; import com.gmail.bunnehrealm.explosionman.Listeners.StopDrops; import com.gmail.bunnehrealm.explosionman.sticks.Boomstick; import com.gmail.bunnehrealm.explosionman.sticks.LeapStick; import com.gmail.bunnehrealm.explosionman.sticks.SetBoomstick; import com.gmail.bunnehrealm.explosionman.sticks.SetLeapStick; public class MainClass extends JavaPlugin { public File playersFile; public FileConfiguration players; public String fileName; public JavaPlugin plugin; public Boomstick boomListen = new Boomstick(this); public Deathclass deathListen = new Deathclass(this); public Explodecmd explodeCmd = new Explodecmd(this); public FexplodeClass fexplodeCmd = new FexplodeClass(this); public PreventDamage damageListen = new PreventDamage(this); public LaunchClass launchCmd = new LaunchClass(this); public LeapClass leapCmd = new LeapClass(this); public LeapStick leapStick = new LeapStick(this); public ExplodeKit explodeKit = new ExplodeKit(this); public PreventDamage MoreListen = new PreventDamage(this); public PreventFlyKick flyListen = new PreventFlyKick(this); public SetBoomstick setBoomstick = new SetBoomstick(this); public SetLeapStick setLeapStick = new SetLeapStick(this); public StopDrops dropListen = new StopDrops(this); public MyLeap myLeap = new MyLeap(this); public MyBoom myBoom = new MyBoom(this); @Override public void onDisable() { getLogger().info("Explosion Man has been DISABLED!"); if(playersFile.exists()) savePlayers(); else{ return; } } @Override public void onEnable() { this.getConfig().options().copyDefaults(true); this.saveDefaultConfig(); getLogger().info("Explosion Man has been ENABLED!"); PluginManager pm = getServer().getPluginManager(); pm.registerEvents(this.boomListen, this); pm.registerEvents(this.deathListen, this); pm.registerEvents(this.leapStick, this); pm.registerEvents(this.flyListen, this); pm.registerEvents(this.damageListen, this); pm.registerEvents(this.dropListen, this); getCommand("myboom").setExecutor(myBoom); getCommand("explodekit").setExecutor(explodeKit); getCommand("leap").setExecutor(leapCmd); getCommand("explode").setExecutor(explodeCmd); getCommand("setboomstick").setExecutor(setBoomstick); getCommand("setleapstick").setExecutor(setLeapStick); getCommand("fexplode").setExecutor(fexplodeCmd); getCommand("myleap").setExecutor(myLeap); getCommand("launch").setExecutor(launchCmd); playersFile = new File(getDataFolder(), "players.yml"); players = new YamlConfiguration(); try{ firstRun(); } catch(Exception e){ return; } loadPlayers(); if (!this.getConfig().isSet("dropblocks")) { this.getConfig().set("dropblocks", true); } if (!this.getConfig().isSet("explodefire")) { this.getConfig().set("explodefire", false); } if (!this.getConfig().isSet("explodeblocks")) { this.getConfig().set("exlodeblocks", true); } if (!this.getConfig().isSet("explodepower")) { this.getConfig().set("explodepower", 4); } if (!this.getConfig().isSet("explodebigpower")) { this.getConfig().set("explodebigpower", 50); } if (!this.getConfig().isSet("fexplodefire")) { this.getConfig().set("fexplodefire", false); } if (!this.getConfig().isSet("fexplodeblocks")) { this.getConfig().set("fexplodeblocks", true); } if (!this.getConfig().isSet("fexplodepower")) { this.getConfig().set("fexplodepower", 4); } if (!this.getConfig().isSet("fexplodebigpower")) { this.getConfig().set("fexplodebigpower", 50); } if (!this.getConfig().isSet("boomblocks")) { this.getConfig().set("boomblocks", true); } if (!this.getConfig().isSet("boomitem")) { this.getConfig().set("boomitem", 280); } if (!this.getConfig().isSet("boomfire")) { this.getConfig().set("boomfire", false); } if (!this.getConfig().isSet("boompower")) { this.getConfig().set("boompower", 4); } if (!this.getConfig().isSet("deathpower")) { this.getConfig().set("deathpower", 4); } if (!this.getConfig().isSet("deathfire")) { this.getConfig().set("deathfire", false); } if (!this.getConfig().isSet("deathblocks")) { this.getConfig().set("deathblocks", true); } if (!this.getConfig().isSet("explodemsg")) { this.getConfig().set("explodemsg", false); } if (!this.getConfig().isSet("explodetext")) { this.getConfig().set("explodetext", "Insert message here"); } if (!this.getConfig().isSet("fexplodemsg")) { this.getConfig().set("fexplodemsg", false); } if (!this.getConfig().isSet("fexplodetext")) { this.getConfig().set("fexplodetext", "Insert message here"); } if (!this.getConfig().isSet("boomstickmsg")) { this.getConfig().set("boomstickmsg", false); } if (!this.getConfig().isSet("boomsticktext")) { this.getConfig().set("boomsticktext", "Insert message here"); } if (!this.getConfig().isSet("launchfire")) { this.getConfig().set("launchfire", false); } if (!this.getConfig().isSet("launchblocks")) { this.getConfig().set("launchblocks", true); } if (!this.getConfig().isSet("launchpower")) { this.getConfig().set("launchpower", 4); } if (!this.getConfig().isSet("launchheight")) { this.getConfig().set("launchheight", 5); } if (!this.getConfig().isSet("launchmsg")) { this.getConfig().set("launchmsg", false); } if (!this.getConfig().isSet("launchtxt")) { this.getConfig().set("launchtxt", "Insert message here"); } if (!this.getConfig().isSet("leapfire")) { this.getConfig().set("leapfire", false); } if (!this.getConfig().isSet("leapblocks")) { this.getConfig().set("leapblocks", true); } if (!this.getConfig().isSet("leapdefault")) { this.getConfig().set("leapdefault", 5); } if (!this.getConfig().isSet("leapexplode")) { this.getConfig().set("leapexplode", true); } if (!this.getConfig().isSet("leapstartpower")) { this.getConfig().set("leapstartpower", 4); } if (!this.getConfig().isSet("leapmsg")) { this.getConfig().set("leapmsg", false); } if (!this.getConfig().isSet("leaptxt")) { this.getConfig().set("leaptxt", "Insert message here"); } if (!this.getConfig().isSet("leapstickfire")) { this.getConfig().set("leapstickfire", false); } if (!this.getConfig().isSet("leapstickblocks")) { this.getConfig().set("leapstickblocks", true); } if (!this.getConfig().isSet("leapstickid")) { this.getConfig().set("leapstickid", 289); } if (!this.getConfig().isSet("leapstickexplode")) { this.getConfig().set("leapstickexplode", true); } if (!this.getConfig().isSet("leapmsg")) { this.getConfig().set("leapmsg", false); } if (!this.getConfig().isSet("leapstickstartpower")) { this.getConfig().set("leapstickstartpower", 4); } if (!this.getConfig().isSet("leapstickmsg")) { this.getConfig().set("leapstickmsg", false); } if (!this.getConfig().isSet("leapsticktxt")) { this.getConfig().set("testms", "Insert message here"); } if (!this.getConfig().isSet("Version")) { this.getConfig().set("Version", "1.7 #(PLEASE DO NOT CHANGE)"); } this.saveConfig(); this.savePlayers(); } private void firstRun() throws Exception{ if(!playersFile.exists()){ getLogger().info("Creating a players.yml file"); playersFile.getParentFile().mkdirs(); playersFile.createNewFile(); } } public void loadPlayers() { try { players.load(playersFile); } catch (Exception e) { return; } } public void savePlayers(){ try{ players.save(playersFile); } catch(IOException e){ return; } } }
gpl-3.0
epsilony/tb
src/test/java/net/epsilony/tb/implicit/TrackContourBuilderTest.java
5181
/* * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * 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 net.epsilony.tb.implicit; import java.awt.geom.Rectangle2D; import java.util.List; import net.epsilony.tb.solid.Line; import net.epsilony.tb.analysis.Math2D; import net.epsilony.tb.analysis.DifferentiableFunction; import net.epsilony.tb.analysis.LogicalMaximum; import net.epsilony.tb.solid.SegmentStartCoordIterable; import net.epsilony.tb.solid.winged.WingedCell; import org.junit.Test; import static org.junit.Assert.*; /** * * @author <a href="mailto:epsilonyuan@gmail.com">Man YUAN</a> */ public class TrackContourBuilderTest { public TrackContourBuilderTest() { } double diskCenterX = 10; double diskCenterY = -20; double diskRadius = 50; double holeCenterX = 15; double holeCenterY = -15; double holeRadius = 20; public class SampleOneDiskWithAHole implements DifferentiableFunction { LogicalMaximum max = new LogicalMaximum(); private CircleLevelSet disk; private CircleLevelSet hole; public SampleOneDiskWithAHole() { max.setK(diskRadius - holeRadius, 1e-10, true); disk = new CircleLevelSet(diskCenterX, diskCenterY, diskRadius); disk.setConcrete(true); hole = new CircleLevelSet(holeCenterX, holeCenterY, holeRadius); hole.setConcrete(false); max.setFunctions(disk, hole); } @Override public double[] value(double[] input, double[] output) { return max.value(input, output); } @Override public int getDiffOrder() { return max.getDiffOrder(); } @Override public int getInputDimension() { return max.getInputDimension(); } @Override public int getOutputDimension() { return max.getOutputDimension(); } @Override public void setDiffOrder(int diffOrder) { max.setDiffOrder(diffOrder); } } @Test public void testDiskWithAHole() { TriangleContourCellFactory factory = new TriangleContourCellFactory(); double edgeLength = 5; int expChainsSize = 2; double errRatio = 0.05; Rectangle2D range = new Rectangle2D.Double(diskCenterX - diskRadius - edgeLength * 2, diskCenterY - diskRadius - edgeLength * 2, diskRadius * 2 + edgeLength * 4, diskRadius * 2 + edgeLength * 4); SampleOneDiskWithAHole levelsetFunction = new SampleOneDiskWithAHole(); factory.setRectangle(range); factory.setEdgeLength(edgeLength); List<WingedCell> cells = factory.produce(); TrackContourBuilder builder = new TrackContourBuilder(); builder.setCells((List) cells); builder.setLevelSetFunction(levelsetFunction); SimpleGradientSolver solver = new SimpleGradientSolver(); solver.setMaxEval(200); builder.setImplicitFunctionSolver(solver); builder.genContour(); List<Line> contourHeads = builder.getContourHeads(); assertEquals(expChainsSize, contourHeads.size()); for (int i = 0; i < contourHeads.size(); i++) { double x0, y0, rad; Line head = contourHeads.get(i); boolean b = Math2D.isAnticlockwise(new SegmentStartCoordIterable(head)); if (b) { x0 = diskCenterX; y0 = diskCenterY; rad = diskRadius; } else { x0 = holeCenterX; y0 = holeCenterY; rad = holeRadius; } double expArea = Math.PI * rad * rad; expArea *= b ? 1 : -1; Line seg = head; double actArea = 0; double[] center = new double[] { x0, y0 }; do { double[] startCoord = seg.getStart().getCoord(); double[] endCoord = seg.getEnd().getCoord(); actArea += 0.5 * Math2D.cross(endCoord[0] - startCoord[0], endCoord[1] - startCoord[1], x0 - startCoord[0], y0 - startCoord[1]); seg = (Line) seg.getSucc(); double actRadius = Math2D.distance(startCoord, center); assertEquals(rad, actRadius, 1e-5); actRadius = Math2D.distance(endCoord, center); assertEquals(rad, actRadius, 1e-5); } while (seg != head); assertEquals(expArea, actArea, Math.abs(expArea) * errRatio); } } }
gpl-3.0
iterate-ch/cyberduck
dracoon/src/main/java/ch/cyberduck/core/sds/triplecrypt/TripleCryptEncryptingInputStream.java
6159
package ch.cyberduck.core.sds.triplecrypt; /* * Copyright (c) 2002-2022 iterate GmbH. All rights reserved. * https://cyberduck.io/ * * 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. */ import ch.cyberduck.core.sds.SDSSession; import ch.cyberduck.core.sds.io.swagger.client.model.FileKey; import ch.cyberduck.core.transfer.TransferStatus; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.ProxyInputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Arrays; import com.dracoon.sdk.crypto.CryptoUtils; import com.dracoon.sdk.crypto.FileEncryptionCipher; import com.dracoon.sdk.crypto.error.CryptoException; import com.dracoon.sdk.crypto.model.EncryptedDataContainer; import com.dracoon.sdk.crypto.model.PlainDataContainer; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; public class TripleCryptEncryptingInputStream extends ProxyInputStream { private static final Logger log = LogManager.getLogger(TripleCryptEncryptingInputStream.class); private final SDSSession session; private final InputStream proxy; private final FileEncryptionCipher cipher; private final TransferStatus status; // Buffer for encrypted content waiting to be read private ByteBuffer buffer = ByteBuffer.allocate(0); private boolean eof = false; /** * @param proxy the cleartext InputStream to use as source */ public TripleCryptEncryptingInputStream(final SDSSession session, final InputStream proxy, final FileEncryptionCipher cipher, final TransferStatus status) { super(proxy); this.session = session; this.proxy = proxy; this.cipher = cipher; this.status = status; } @Override public int read(final byte[] b) throws IOException { return this.read(b, 0, b.length); } @Override public int read(final byte[] b, final int off, final int len) throws IOException { try { int read = 0; if(buffer.hasRemaining()) { // Buffer still has encrypted content available read = Math.min(len, buffer.remaining()); System.arraycopy(buffer.array(), buffer.position(), b, off, read); buffer.position(buffer.position() + read); } else if(eof) { // Buffer is consumed and EOF flag set return IOUtils.EOF; } if(buffer.hasRemaining()) { return read; } if(!eof) { this.fillBuffer(len); } return read; } catch(CryptoException e) { throw new IOException(e); } } private void fillBuffer(final int len) throws IOException, CryptoException { // Read ahead to the next chunk end final int allocate = (len / IOUtils.DEFAULT_BUFFER_SIZE) * IOUtils.DEFAULT_BUFFER_SIZE + IOUtils.DEFAULT_BUFFER_SIZE; buffer = ByteBuffer.allocate(allocate); final byte[] plain = new byte[allocate]; final int read = IOUtils.read(proxy, plain, 0, allocate); if(read > 0) { int position = 0; for(int chunkOffset = 0; chunkOffset < read; chunkOffset += SDSSession.DEFAULT_CHUNKSIZE) { int chunkLen = Math.min(SDSSession.DEFAULT_CHUNKSIZE, read - chunkOffset); final byte[] bytes = Arrays.copyOfRange(plain, chunkOffset, chunkOffset + chunkLen); final PlainDataContainer data = TripleCryptKeyPair.createPlainDataContainer(bytes, bytes.length); final EncryptedDataContainer encrypted = cipher.processBytes(data); final byte[] encBuf = encrypted.getContent(); System.arraycopy(encBuf, 0, buffer.array(), position, encBuf.length); position += encBuf.length; } buffer.limit(position); } if(read < allocate) { // EOF in proxy stream, finalize cipher and put remaining bytes into buffer eof = true; final EncryptedDataContainer encContainer = cipher.doFinal(); final byte[] content = encContainer.getContent(); buffer = this.combine(buffer, ByteBuffer.wrap(content)); final String tag = CryptoUtils.byteArrayToString(encContainer.getTag()); final ObjectReader reader = session.getClient().getJSON().getContext(null).readerFor(FileKey.class); final FileKey fileKey = reader.readValue(status.getFilekey().array()); if(null == fileKey.getTag()) { // Only override if not already set pre-computed in bulk feature fileKey.setTag(tag); final ObjectWriter writer = session.getClient().getJSON().getContext(null).writerFor(FileKey.class); final ByteArrayOutputStream out = new ByteArrayOutputStream(); writer.writeValue(out, fileKey); status.setFilekey(ByteBuffer.wrap(out.toByteArray())); } else { log.warn(String.format("Skip setting tag in file key already found in %s", status)); } } } private ByteBuffer combine(final ByteBuffer b1, final ByteBuffer b2) { final int pos = b1.position(); final ByteBuffer allocate = ByteBuffer.allocate(b1.limit() + b2.limit()).put(b1).put(b2); allocate.position(pos); return allocate; } }
gpl-3.0
MNLBC/Group2Projects
5. William Kalingasan/W5D3_Homework/Codes/Item1/W5D2_Homework/src/com/oocl/mnlbc/dao/UserMapper.java
474
package com.oocl.mnlbc.dao; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.oocl.mnlbc.model.User; public class UserMapper implements RowMapper<User> { public User mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setUserName(rs.getString("USERNAME")); user.setPassword(rs.getString("PASSWORD")); user.setRemark(rs.getString("REMARK")); return user; } }
gpl-3.0
rosario-raulin/SkunkmanAI
src/world/Stone.java
290
package world; final class Stone extends AbstractWO { Stone(int x, int y) { super(x, y); } @Override public boolean isWalkable() { return false; } @Override public WORating rating() { return WORating.AVOID; } @Override public boolean isBlocked() { return true; } }
gpl-3.0
veithen/visualwas
clientlib/src/main/java/com/github/veithen/visualwas/client/pmi/StatDescriptor.java
1295
/* * #%L * VisualWAS * %% * Copyright (C) 2013 - 2020 Andreas Veithen * %% * 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/gpl-3.0.html>. * #L% */ package com.github.veithen.visualwas.client.pmi; import java.io.Serializable; import com.github.veithen.visualwas.connector.mapped.MappedClass; @MappedClass("com.ibm.websphere.pmi.stat.StatDescriptor") public class StatDescriptor implements Serializable { private static final long serialVersionUID = -2844135786824830882L; private final String[] subPath; private final int dataId = -3; public StatDescriptor(String... path) { subPath = path; } public String[] getPath() { return subPath; } }
gpl-3.0
dbs-leipzig/foodbroker
src/main/java/org/biiig/foodbroker/stores/StoreCombiner.java
160
package org.biiig.foodbroker.stores; /** * Created by peet on 28.11.14. */ public interface StoreCombiner { void add(Store store); void combine(); }
gpl-3.0
socoolby/CoolClock
app/src/main/java/clock/socoolby/com/clock/protocol/WeatherResponse.java
4725
package clock.socoolby.com.clock.protocol; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class WeatherResponse extends ResponseBase { /* { "error": 0, "status": "success", "date": "2016-05-26", "results": [{ "currentCity": "深圳", "pm25": "31", "index": [{ "title": "穿衣", "zs": "热", "tipt": "穿衣指数", "des": "天气热,建议着短裙、短裤、短薄外套、T恤等夏季服装。" }, { "title": "洗车", "zs": "不宜", "tipt": "洗车指数", "des": "不宜洗车,未来24小时内有雨,如果在此期间洗车,雨水和路上的泥水可能会再次弄脏您的爱车。" }, { "title": "旅游", "zs": "较不宜", "tipt": "旅游指数", "des": "温度适宜,风力不大,但预计将有有强降水出现,会给您的出游增添很多麻烦,建议您最好选择室内活动。" }, { "title": "感冒", "zs": "较易发", "tipt": "感冒指数", "des": "天气转凉,空气湿度较大,较易发生感冒,体质较弱的朋友请注意适当防护。" }, { "title": "运动", "zs": "较不宜", "tipt": "运动指数", "des": "有较强降水,建议您选择在室内进行健身休闲运动。" }, { "title": "紫外线强度", "zs": "弱", "tipt": "紫外线强度指数", "des": "紫外线强度较弱,建议出门前涂擦SPF在12-15之间、PA+的防晒护肤品。" }], "weather_data": [{ "date": "周四 05月26日 (实时:28℃)", "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/dayu.png", "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/dayu.png", "weather": "大雨", "wind": "微风", "temperature": "31 ~ 25℃" }, { "date": "周五", "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/baoyu.png", "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/leizhenyu.png", "weather": "暴雨转雷阵雨", "wind": "微风", "temperature": "29 ~ 25℃" }, { "date": "周六", "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/leizhenyu.png", "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/zhenyu.png", "weather": "雷阵雨转阵雨", "wind": "微风", "temperature": "30 ~ 25℃" }, { "date": "周日", "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/zhenyu.png", "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/zhenyu.png", "weather": "阵雨", "wind": "微风", "temperature": "31 ~ 26℃" }] }] } */ private int mErrorCode; private String mCurrentCity; private int mPM25; private Weather todayWeather; public class Weather { public String date; public String weather; public String wind; public String temperature; public void parse(JSONObject jsonObject) { try { date = jsonObject.getString("date"); weather = jsonObject.getString("weather"); wind = jsonObject.getString("wind"); temperature = jsonObject.getString("temperature"); } catch (JSONException e) { e.printStackTrace(); } } } public int getmErrorCode() { return mErrorCode; } public void setmErrorCode(int mErrorCode) { this.mErrorCode = mErrorCode; } public String getmCurrentCity() { return mCurrentCity; } public void setmCurrentCity(String mCurrentCity) { this.mCurrentCity = mCurrentCity; } public int getmPM25() { return mPM25; } public void setmPM25(int mPM25) { this.mPM25 = mPM25; } public Weather getTodayWeather() { return todayWeather; } public void setTodayWeather(Weather todayWeather) { this.todayWeather = todayWeather; } public WeatherResponse(JSONObject response) { super.parseResponse(response); } @Override protected boolean parse(JSONObject object) throws JSONException { mErrorCode = object.getInt("error"); if (mErrorCode == 0) { JSONArray results = object.getJSONArray("results"); JSONObject summary = (JSONObject) results.get(0); mCurrentCity = summary.getString("currentCity"); mPM25 = summary.getInt("pm25"); JSONArray weathers = summary.getJSONArray("weather_data"); todayWeather = new Weather(); JSONObject todayJsonObject = (JSONObject) weathers.get(0); todayWeather.parse(todayJsonObject); } return true; } }
gpl-3.0
noodlewiz/xjavab
xjavab-ext/src/main/java/com/noodlewiz/xjavab/ext/randr/internal/EventDispatcher.java
1464
// // DO NOT MODIFY!!! This file was machine generated. DO NOT MODIFY!!! // // Copyright (c) 2014 Vincent W. Chen. // // This file is part of XJavaB. // // XJavaB 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. // // XJavaB 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 XJavaB. If not, see <http://www.gnu.org/licenses/>. // package com.noodlewiz.xjavab.ext.randr.internal; import java.nio.ByteBuffer; import com.noodlewiz.xjavab.core.XEvent; public class EventDispatcher implements com.noodlewiz.xjavab.core.internal.EventDispatcher { @Override public XEvent dispatch(final ByteBuffer __xjb_buf, final int __xjb_code) { switch (__xjb_code) { case 0 : return EventUnpacker.unpackScreenChangeNotify(__xjb_buf); case 1 : return EventUnpacker.unpackNotify(__xjb_buf); default: throw new IllegalArgumentException(("Invalid event code: "+ __xjb_code)); } } }
gpl-3.0
UM-LPM/EARS
src/org/um/feri/ears/problems/unconstrained/cec2014/F2.java
426
package org.um.feri.ears.problems.unconstrained.cec2014; import org.um.feri.ears.problems.unconstrained.cec.Functions; public class F2 extends CEC2014 { public F2(int d) { super(d, 2); name = "F02 Bent Cigar Function"; } @Override public double eval(double[] x) { return Functions.bent_cigar_func(x, numberOfDimensions, OShift, M, 1, 1) + funcNum * 100.0; } }
gpl-3.0
CCWI/SocialMediaCrawler
src/edu/hm/cs/smc/channels/linkedin/models/LinkedInEmployeeCountRange.java
482
package edu.hm.cs.smc.channels.linkedin.models; import javax.persistence.Entity; import edu.hm.cs.smc.database.models.BaseEntity; @Entity public class LinkedInEmployeeCountRange extends BaseEntity { private String code; private String name; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
gpl-3.0